Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Improve audio latency handling and add Windows support
Richie McIlroy6931d19f6b63
diff --git a/Cargo.lock b/Cargo.lockindex c300f3b8c..7042e2a63 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1058,6 +1058,7 @@ dependencies = ["tempfile","tokio","tracing",+ "windows 0.60.0","workspace-hack",]diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rsindex e771e9934..6847601a9 100644--- a/apps/cli/src/main.rs+++ b/apps/cli/src/main.rs@@ -166,7 +166,8 @@ impl Export {let exporter_output_path = cap_export::mp4::Mp4ExportSettings {fps: 60,resolution_base: XY::new(1920, 1080),- compression: cap_export::mp4::ExportCompression::Minimal,+ compression: cap_export::mp4::ExportCompression::Maximum,+ custom_bpp: None,}.export(exporter_base, move |_f| {// print!("\rrendered frame {f}");diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.tomlindex 3f27ef5cd..6d682a249 100644--- a/crates/audio/Cargo.toml+++ b/crates/audio/Cargo.toml@@ -16,6 +16,13 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }[target.'cfg(target_os = "macos")'.dependencies]cidre = { workspace = true }+[target.'cfg(windows)'.dependencies]+windows = { workspace = true, features = [+ "Win32_Media_Audio",+ "Win32_System_Com",+ "Win32_Devices_FunctionDiscovery",+] }+[dev-dependencies]tempfile = "3"diff --git a/crates/audio/src/latency.rs b/crates/audio/src/latency.rsindex e6c4d52cf..97ee04ad3 100644--- a/crates/audio/src/latency.rs+++ b/crates/audio/src/latency.rs@@ -495,7 +495,12 @@ pub fn estimate_input_latency(.unwrap_or_else(|| InputLatencyInfo::from_buffer_only(sample_rate, buffer_size_frames))}- #[cfg(not(target_os = "macos"))]+ #[cfg(windows)]+ {+ windows::estimate_input_latency(sample_rate, buffer_size_frames, device_name)+ }++ #[cfg(not(any(target_os = "macos", windows)))]{let _ = device_name;InputLatencyInfo::from_buffer_only(sample_rate, buffer_size_frames)@@ -736,6 +741,205 @@ mod macos {}}+#[cfg(windows)]+mod windows {+ use super::{InputLatencyInfo, OutputTransportKind, WIRELESS_MIN_LATENCY_SECS};+ use tracing::{debug, trace, warn};+ use windows::{+ Win32::Devices::FunctionDiscovery::PKEY_Device_BusEnumeratorName,+ Win32::Media::Audio::{IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, eCapture},+ Win32::System::Com::{+ CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, STGM_READ,+ },+ core::PCWSTR,+ };++ const BLUETOOTH_DEVICE_PATTERNS: &[&str] = &[+ "airpod",+ "bluetooth",+ "bt ",+ "wireless",+ "bose",+ "sony wh",+ "sony wf",+ "jabra",+ "beats",+ "galaxy buds",+ "pixel buds",+ "anker",+ "jbl ",+ "soundcore",+ "tozo",+ "raycon",+ "skullcandy",+ "sennheiser momentum",+ "audio-technica ath-m50xbt",+ "marshall",+ "b&o",+ "bang & olufsen",+ "shokz",+ "aftershokz",+ ];++ fn is_likely_bluetooth_device(device_name: &str) -> bool {+ let lower = device_name.to_lowercase();+ BLUETOOTH_DEVICE_PATTERNS+ .iter()+ .any(|pattern| lower.contains(pattern))+ }++ fn detect_transport_via_mmdevice(device_name: &str) -> Option<OutputTransportKind> {+ unsafe {+ let _ = CoInitializeEx(None, COINIT_MULTITHREADED);++ let enumerator: IMMDeviceEnumerator =+ CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;++ let collection = enumerator.EnumAudioEndpoints(eCapture, 1).ok()?;+ let count = collection.GetCount().ok()?;++ for i in 0..count {+ let device: IMMDevice = match collection.Item(i) {+ Ok(d) => d,+ Err(_) => continue,+ };++ let props = match device.OpenPropertyStore(STGM_READ) {+ Ok(p) => p,+ Err(_) => continue,+ };++ let friendly_name = get_device_friendly_name(&device);+ let matches_name = friendly_name+ .as_ref()+ .map(|n| n.to_lowercase().contains(&device_name.to_lowercase()))+ .unwrap_or(false);++ if !matches_name {+ continue;+ }++ if let Ok(bus_enum) = props.GetValue(&PKEY_Device_BusEnumeratorName) {+ let bus_name = bus_enum.Anonymous.Anonymous.Anonymous.pwszVal;+ if !bus_name.is_null() {+ let bus_str = PCWSTR(bus_name).to_string().ok()?;+ trace!(+ device = ?friendly_name,+ bus = %bus_str,+ "Windows audio device bus enumerator"+ );++ let bus_lower = bus_str.to_lowercase();+ if bus_lower.contains("bthenum") || bus_lower.contains("bluetooth") {+ debug!(+ device = ?friendly_name,+ "Detected Bluetooth audio device via Windows API"+ );+ return Some(OutputTransportKind::Wireless);+ }+ }+ }++ return Some(OutputTransportKind::Wired);+ }++ None+ }+ }++ fn get_device_friendly_name(device: &IMMDevice) -> Option<String> {+ use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;++ unsafe {+ let props = device.OpenPropertyStore(STGM_READ).ok()?;+ let name_val = props.GetValue(&PKEY_Device_FriendlyName).ok()?;+ let name_ptr = name_val.Anonymous.Anonymous.Anonymous.pwszVal;+ if name_ptr.is_null() {+ return None;+ }+ PCWSTR(name_ptr).to_string().ok()+ }+ }++ pub fn estimate_input_latency(+ sample_rate: u32,+ buffer_size_frames: u32,+ device_name: Option<&str>,+ ) -> InputLatencyInfo {+ if sample_rate == 0 {+ return InputLatencyInfo::new(0.0, 0.0, OutputTransportKind::Unknown);+ }++ let buffer_latency_secs = buffer_size_frames as f64 / sample_rate as f64;++ let transport_kind = device_name+ .and_then(|name| {+ if let Some(transport) = detect_transport_via_mmdevice(name) {+ return Some(transport);+ }++ if is_likely_bluetooth_device(name) {+ debug!(+ device = %name,+ "Detected likely Bluetooth device via name pattern matching"+ );+ return Some(OutputTransportKind::Wireless);+ }++ None+ })+ .unwrap_or(OutputTransportKind::Unknown);++ let device_latency_secs = match transport_kind {+ OutputTransportKind::Wireless => {+ debug!(+ device = ?device_name,+ latency_ms = WIRELESS_MIN_LATENCY_SECS * 1000.0,+ "Using wireless latency for audio device"+ );+ WIRELESS_MIN_LATENCY_SECS+ }+ _ => 0.01,+ };++ InputLatencyInfo::new(device_latency_secs, buffer_latency_secs, transport_kind)+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ #[test]+ fn detects_airpods() {+ assert!(is_likely_bluetooth_device("AirPods Pro"));+ assert!(is_likely_bluetooth_device("airpods"));+ }++ #[test]+ fn detects_generic_bluetooth() {+ assert!(is_likely_bluetooth_device("Bluetooth Headset"));+ assert!(is_likely_bluetooth_device("BT Audio"));+ }++ #[test]+ fn does_not_detect_wired() {+ assert!(!is_likely_bluetooth_device("Realtek HD Audio"));+ assert!(!is_likely_bluetooth_device("USB Microphone"));+ assert!(!is_likely_bluetooth_device("Blue Yeti"));+ }++ #[test]+ fn wireless_mic_gets_higher_latency() {+ let wireless = estimate_input_latency(48000, 1024, Some("AirPods Pro"));+ let wired = estimate_input_latency(48000, 1024, Some("USB Microphone"));++ assert!(wireless.device_latency_secs >= WIRELESS_MIN_LATENCY_SECS);+ assert!(wired.device_latency_secs < WIRELESS_MIN_LATENCY_SECS);+ assert!(wireless.total_latency_secs > wired.total_latency_secs);+ }+ }+}+#[cfg(test)]#[allow(clippy::unchecked_duration_subtraction)]mod tests {diff --git a/crates/enc-avfoundation/src/mp4.rs b/crates/enc-avfoundation/src/mp4.rsindex 2498624be..10542d5d4 100644--- a/crates/enc-avfoundation/src/mp4.rs+++ b/crates/enc-avfoundation/src/mp4.rs@@ -1,9 +1,11 @@use cap_media_info::{AudioInfo, VideoInfo};use cidre::{cm::SampleTimingInfo, objc::Obj, *};-use ffmpeg::frame;+use ffmpeg::{frame, software::resampling};use std::{path::PathBuf, time::Duration};use tracing::*;+const AAC_MAX_SAMPLE_RATE: u32 = 48000;+// before pausing at all, subtract 0.// on pause, record last frame time.// on resume, store last frame time and clear offset timestamp@@ -16,6 +18,8 @@ pub struct MP4Encoder {asset_writer: arc::R<av::AssetWriter>,video_input: arc::R<av::AssetWriterInput>,audio_input: Option<arc::R<av::AssetWriterInput>>,+ audio_resampler: Option<resampling::Context>,+ audio_output_rate: u32,last_frame_timestamp: Option<Duration>,pause_timestamp: Option<Duration>,timestamp_offset: Duration,@@ -44,6 +48,8 @@ pub enum InitError {AudioAssetWriterInputCreate(&'static cidre::ns::Exception),#[error("AddAudioInput/{0}")]AddAudioInput(&'static cidre::ns::Exception),+ #[error("AudioResampler/{0}")]+ AudioResampler(ffmpeg::Error),}#[derive(thiserror::Error, Debug)]@@ -183,11 +189,43 @@ impl MP4Encoder {video_input};- let audio_input = audio_config- .as_ref()- .map(|config| {+ let (audio_input, audio_resampler, audio_output_rate) = match audio_config.as_ref() {+ Some(config) => {debug!("{config:?}");+ let output_rate = config.sample_rate.min(AAC_MAX_SAMPLE_RATE);++ let resampler = if config.sample_rate > AAC_MAX_SAMPLE_RATE {+ info!(+ input_rate = config.sample_rate,+ output_rate,+ "Audio sample rate {} exceeds AAC max {}, resampling",+ config.sample_rate,+ AAC_MAX_SAMPLE_RATE+ );++ let mut output_config = *config;+ output_config.sample_rate = output_rate;++ Some(+ ffmpeg::software::resampler(+ (+ config.sample_format,+ config.channel_layout(),+ config.sample_rate,+ ),+ (+ output_config.sample_format,+ output_config.channel_layout(),+ output_config.sample_rate,+ ),+ )+ .map_err(InitError::AudioResampler)?,+ )+ } else {+ None+ };+let output_settings = cidre::ns::Dictionary::with_keys_values(&[av::audio::all_formats_keys::id(),@@ -197,7 +235,7 @@ impl MP4Encoder {&[cat::AudioFormat::MPEG4_AAC.as_ref(),(config.channels as u32).as_ref(),- (config.sample_rate).as_ref(),+ output_rate.as_ref(),],);@@ -213,15 +251,18 @@ impl MP4Encoder {.add_input(&audio_input).map_err(InitError::AddAudioInput)?;- Ok::<_, InitError>(audio_input)- })- .transpose()?;+ (Some(audio_input), resampler, output_rate)+ }+ None => (None, None, 0),+ };asset_writer.start_writing();Ok(Self {config: video_config,audio_input,+ audio_resampler,+ audio_output_rate,asset_writer,video_input,last_frame_timestamp: None,@@ -333,6 +374,22 @@ impl MP4Encoder {return Err(QueueFrameError::NotReadyForMore);}+ let processed_frame: std::borrow::Cow<'_, frame::Audio> =+ if let Some(resampler) = &mut self.audio_resampler {+ let mut resampled = frame::Audio::empty();+ resampler.run(frame, &mut resampled).ok();+ resampled.set_rate(self.audio_output_rate);+ std::borrow::Cow::Owned(resampled)+ } else {+ std::borrow::Cow::Borrowed(frame)+ };++ let frame = processed_frame.as_ref();++ if frame.samples() == 0 {+ return Ok(());+ }+let audio_desc = cat::audio::StreamBasicDesc::common_f32(frame.rate() as f64,frame.channels() as u32,diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rsindex 30d34c7bf..a50514d29 100644--- a/crates/recording/src/feeds/microphone.rs+++ b/crates/recording/src/feeds/microphone.rs@@ -1,3 +1,4 @@+use cap_audio::estimate_input_latency;use cap_media_info::{AudioInfo, ffmpeg_sample_format_for};use cap_timestamp::Timestamp;use cpal::{@@ -318,9 +319,16 @@ const MIN_LATENCY_MS: u32 = 10;const MAX_LATENCY_MS: u32 = 120;const ABS_MIN_BUFFER_FRAMES: u32 = 128;-fn stream_config_with_latency(config: &SupportedStreamConfig) -> (cpal::StreamConfig, Option<u32>) {+const WIRELESS_TARGET_LATENCY_MS: u32 = 80;+const WIRELESS_MIN_LATENCY_MS: u32 = 50;+const WIRELESS_MAX_LATENCY_MS: u32 = 200;++fn stream_config_with_latency(+ config: &SupportedStreamConfig,+ device_name: Option<&str>,+) -> (cpal::StreamConfig, Option<u32>) {let mut stream_config: cpal::StreamConfig = config.clone().into();- let buffer_size_frames = desired_buffer_size_frames(config);+ let buffer_size_frames = desired_buffer_size_frames(config, device_name);if let Some(frames) = buffer_size_frames {stream_config.buffer_size = BufferSize::Fixed(frames);@@ -329,7 +337,10 @@ fn stream_config_with_latency(config: &SupportedStreamConfig) -> (cpal::StreamCo(stream_config, buffer_size_frames)}-fn desired_buffer_size_frames(config: &SupportedStreamConfig) -> Option<u32> {+fn desired_buffer_size_frames(+ config: &SupportedStreamConfig,+ device_name: Option<&str>,+) -> Option<u32> {match config.buffer_size() {cpal::SupportedBufferSize::Range { min, max } => {let sample_rate = config.sample_rate().0;@@ -338,9 +349,26 @@ fn desired_buffer_size_frames(config: &SupportedStreamConfig) -> Option<u32> {return None;}- let desired = latency_ms_to_frames(sample_rate, TARGET_LATENCY_MS);- let min_latency_frames = latency_ms_to_frames(sample_rate, MIN_LATENCY_MS);- let max_latency_frames = latency_ms_to_frames(sample_rate, MAX_LATENCY_MS);+ let latency_info = estimate_input_latency(sample_rate, 1024, device_name);+ let is_wireless = latency_info.transport.is_wireless();++ let (target_ms, min_ms, max_ms) = if is_wireless {+ info!(+ "Detected wireless microphone '{}', using extended buffer settings",+ device_name.unwrap_or("unknown")+ );+ (+ WIRELESS_TARGET_LATENCY_MS,+ WIRELESS_MIN_LATENCY_MS,+ WIRELESS_MAX_LATENCY_MS,+ )+ } else {+ (TARGET_LATENCY_MS, MIN_LATENCY_MS, MAX_LATENCY_MS)+ };++ let desired = latency_ms_to_frames(sample_rate, target_ms);+ let min_latency_frames = latency_ms_to_frames(sample_rate, min_ms);+ let max_latency_frames = latency_ms_to_frames(sample_rate, max_ms);let desired = desired.clamp(min_latency_frames, max_latency_frames);let device_max = *max;@@ -504,7 +532,8 @@ impl Message<SetInput> for MicrophoneFeed {};let sample_format = config.sample_format();- let (stream_config, buffer_size_frames) = stream_config_with_latency(&config);+ let (stream_config, buffer_size_frames) =+ stream_config_with_latency(&config, Some(&label));let actor_ref = ctx.actor_ref();let (ready_future, done_tx) = Self::spawn_input_stream(StreamSpawnParams {@@ -587,7 +616,8 @@ impl Message<SetInput> for MicrophoneFeed {};let sample_format = config.sample_format();- let (stream_config, buffer_size_frames) = stream_config_with_latency(&config);+ let (stream_config, buffer_size_frames) =+ stream_config_with_latency(&config, Some(&label));let new_id = self.input_id_counter;self.input_id_counter += 1;diff --git a/crates/recording/src/sources/audio_mixer.rs b/crates/recording/src/sources/audio_mixer.rsindex dbf2335f2..04982e8ac 100644--- a/crates/recording/src/sources/audio_mixer.rs+++ b/crates/recording/src/sources/audio_mixer.rs@@ -15,10 +15,10 @@ use tracing::{debug, info, warn};use crate::output_pipeline::AudioFrame;-const DEFAULT_BUFFER_TIMEOUT: Duration = Duration::from_millis(80);+const DEFAULT_BUFFER_TIMEOUT: Duration = Duration::from_millis(100);const MIN_BUFFER_TIMEOUT: Duration = Duration::from_millis(20);-const MAX_BUFFER_TIMEOUT: Duration = Duration::from_millis(180);-const BUFFER_TIMEOUT_HEADROOM: f64 = 2.0;+const MAX_BUFFER_TIMEOUT: Duration = Duration::from_millis(250);+const BUFFER_TIMEOUT_HEADROOM: f64 = 2.5;// Wait TICK_MS for frames to arrive// Assume all sources' frames for that tick have arrived after TICK_MSdiff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rsindex bb88608f2..a8ba9e591 100644--- a/crates/recording/src/sources/microphone.rs+++ b/crates/recording/src/sources/microphone.rs@@ -41,7 +41,7 @@ impl AudioSource for Microphone {let audio_info = source_info.with_max_channels(MICROPHONE_TARGET_CHANNELS);let source_channels = source_info.channels;let target_channels = audio_info.channels;- let (tx, rx) = flume::bounded(8);+ let (tx, rx) = flume::bounded(32);feed_lock.ask(microphone::AddSender(tx))diff --git a/crates/recording/src/sources/screen_capture/windows.rs b/crates/recording/src/sources/screen_capture/windows.rsindex 680f02a5c..d79ea442a 100644--- a/crates/recording/src/sources/screen_capture/windows.rs+++ b/crates/recording/src/sources/screen_capture/windows.rs@@ -368,14 +368,43 @@ impl output_pipeline::AudioSource for SystemAudioSource {async {let mut error_tx = Some(error_tx);+ let audio_frame_counter: Arc<AtomicU32> = Arc::new(AtomicU32::new(0));+ let audio_drop_counter: Arc<AtomicU32> = Arc::new(AtomicU32::new(0));let capturer = scap_cpal::create_capturer(- move |data, info, config| {- use scap_ffmpeg::*;-- let timestamp = Timestamp::from_cpal(info.timestamp().capture);-- let _ = tx.try_send(AudioFrame::new(data.as_ffmpeg(config), timestamp));+ {+ let audio_frame_counter = audio_frame_counter.clone();+ let audio_drop_counter = audio_drop_counter.clone();+ move |data, info, config| {+ use scap_ffmpeg::*;++ let timestamp = Timestamp::from_cpal(info.timestamp().capture);+ let frame = AudioFrame::new(data.as_ffmpeg(config), timestamp);++ const MAX_RETRIES: u32 = 3;+ const RETRY_DELAY_US: u64 = 500;++ let mut retries = 0;+ let mut current_frame = Some(frame);++ while let Some(f) = current_frame.take() {+ match tx.try_send(f) {+ Ok(()) => {+ audio_frame_counter.fetch_add(1, atomic::Ordering::Relaxed);+ break;+ }+ Err(err) if err.is_full() && retries < MAX_RETRIES => {+ retries += 1;+ std::thread::sleep(Duration::from_micros(RETRY_DELAY_US));+ current_frame = Some(err.into_inner());+ }+ Err(_) => {+ audio_drop_counter.fetch_add(1, atomic::Ordering::Relaxed);+ break;+ }+ }+ }+ }},move |e| {if let Some(error_tx) = error_tx.take() {@@ -384,6 +413,32 @@ impl output_pipeline::AudioSource for SystemAudioSource {},)?;+ tokio::spawn({+ async move {+ loop {+ tokio::time::sleep(Duration::from_secs(5)).await;+ let captured = audio_frame_counter.load(atomic::Ordering::Relaxed);+ let dropped = audio_drop_counter.load(atomic::Ordering::Relaxed);+ let total = captured + dropped;+ if dropped > 0 {+ let drop_pct = if total > 0 {+ 100.0 * dropped as f64 / total as f64+ } else {+ 0.0+ };+ warn!(+ captured = captured,+ dropped = dropped,+ drop_pct = format!("{:.1}%", drop_pct),+ "System audio capture dropping frames due to full channel"+ );+ } else if captured > 0 {+ debug!(captured = captured, "System audio frames captured");+ }+ }+ }+ });+Ok(Self { capturer })}}diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex bd98ec812..fa4e68582 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -1208,6 +1208,7 @@ impl ProjectUniforms {))}+ #[allow(clippy::too_many_arguments)]pub fn new(constants: &RenderVideoConstants,project: &ProjectConfiguration,