fix(calls): Windows mic captures in communications mode so Voice Clarity removes room echo
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -27,12 +27,14 @@ uuid.workspace = true
27
27
28
28
[target.'cfg(windows)'.dependencies]
29
29
windows = { version = "0.62", features = [
30
"Win32_Devices_FunctionDiscovery",
30
31
"Win32_Foundation",
31
32
"Win32_Media_Audio",
32
33
"Win32_System_Com",
33
34
"Win32_System_Com_StructuredStorage",
34
35
"Win32_System_Threading",
35
36
"Win32_System_Variant",
37
"Win32_UI_Shell_PropertiesSystem",
36
38
] }
37
39
windows-core = "0.62"
38
40
@@ -27,12 +27,14 @@ uuid.workspace = true27
27
28
[target.'cfg(windows)'.dependencies]28
[target.'cfg(windows)'.dependencies]29
windows = { version = "0.62", features = [29
windows = { version = "0.62", features = [30
"Win32_Devices_FunctionDiscovery",30
"Win32_Foundation",31
"Win32_Foundation",31
"Win32_Media_Audio",32
"Win32_Media_Audio",32
"Win32_System_Com",33
"Win32_System_Com",33
"Win32_System_Com_StructuredStorage",34
"Win32_System_Com_StructuredStorage",34
"Win32_System_Threading",35
"Win32_System_Threading",35
"Win32_System_Variant",36
"Win32_System_Variant",37
"Win32_UI_Shell_PropertiesSystem",36
] }38
] }37
windows-core = "0.62"39
windows-core = "0.62"38
40
@@ -1336,14 +1336,14 @@ async fn drive(
1336
1336
}
1337
1337
Some(CallCommand::DisableAudio) => {
1338
1338
let audio = live.audio.as_ref().expect("audio set above");
1339
muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
1340
audio_disabled = true;
1341
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, control, timeline);
1339
1342
if audio.uses_devices() {
1340
1343
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
1341
1344
factory.set_adm_recording_enabled(false);
1342
1345
factory.set_adm_playout_enabled(false);
1343
1346
}
1344
muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
1345
audio_disabled = true;
1346
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, control, timeline);
1347
1347
control.send(CallUpdate::ListenOnly(true));
1348
1348
}
1349
1349
Some(CallCommand::SelectInput(choice)) => {
@@ -2491,6 +2491,17 @@ fn software_wanted(
2491
2491
SoftwareAudioPlan::wanted(mic_settings, sharing_sound, audio.is_some_and(AudioSetup::uses_devices))
2492
2492
}
2493
2493
2494
fn restore_device_track(factory: &PeerConnectionFactory, input: &DeviceChoice, peer: &PeerConnection, device_track: &RtcAudioTrack, timeline: &Timeline) {
2495
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
2496
if cfg!(windows) && !factory.adm_recording_enabled() {
2497
factory.set_adm_recording_enabled(true);
2498
devices::select_input(factory, input);
2499
}
2500
if let Err(error) = swap_audio_track(peer, device_track) {
2501
timeline.record("microphone track not restored", error.to_string());
2502
}
2503
}
2504
2494
2505
#[allow(clippy::too_many_arguments)]
2495
2506
fn sync_software_audio(
2496
2507
factory: &PeerConnectionFactory,
@@ -2513,9 +2524,7 @@ fn sync_software_audio(
2513
2524
*software_audio = None;
2514
2525
let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
2515
2526
let Some(plan) = wanted else {
2516
if let Err(error) = swap_audio_track(peer, device_track) {
2517
timeline.record("microphone track not restored", error.to_string());
2518
}
2527
restore_device_track(factory, input, peer, device_track, timeline);
2519
2528
control.send(CallUpdate::ShareSound(false));
2520
2529
return;
2521
2530
};
@@ -2524,6 +2533,13 @@ fn sync_software_audio(
2524
2533
match started {
2525
2534
Ok(audio) => {
2526
2535
timeline.record("software audio", format!("{:?}, computer sound {:?}", plan.processing, audio.loopback));
2536
if let Some(source) = &audio.microphone_source {
2537
timeline.record("mic capture", source.clone());
2538
}
2539
if cfg!(windows) && audio.microphone_source.is_some() {
2540
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
2541
factory.set_adm_recording_enabled(false);
2542
}
2527
2543
if let Some(warning) = &audio.warning {
2528
2544
timeline.record("computer sound warning", warning.clone());
2529
2545
}
@@ -2532,9 +2548,7 @@ fn sync_software_audio(
2532
2548
}
2533
2549
Err(error) => {
2534
2550
timeline.record("software audio failed", error.to_string());
2535
if let Err(error) = swap_audio_track(peer, device_track) {
2536
timeline.record("microphone track not restored", error.to_string());
2537
}
2551
restore_device_track(factory, input, peer, device_track, timeline);
2538
2552
if was_sharing_sound || plan.computer_sound {
2539
2553
control.send(CallUpdate::ShareSound(false));
2540
2554
}
@@ -1336,14 +1336,14 @@ async fn drive(1336
}1336
}1337
Some(CallCommand::DisableAudio) => {1337
Some(CallCommand::DisableAudio) => {1338
let audio = live.audio.as_ref().expect("audio set above");1338
let audio = live.audio.as_ref().expect("audio set above");1339
muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);1340
audio_disabled = true;1341
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, control, timeline);1339
if audio.uses_devices() {1342
if audio.uses_devices() {1340
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;1343
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;1341
factory.set_adm_recording_enabled(false);1344
factory.set_adm_recording_enabled(false);1342
factory.set_adm_playout_enabled(false);1345
factory.set_adm_playout_enabled(false);1343
}1346
}1344
muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);1345
audio_disabled = true;1346
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, control, timeline);1347
control.send(CallUpdate::ListenOnly(true));1347
control.send(CallUpdate::ListenOnly(true));1348
}1348
}1349
Some(CallCommand::SelectInput(choice)) => {1349
Some(CallCommand::SelectInput(choice)) => {@@ -2491,6 +2491,17 @@ fn software_wanted(2491
SoftwareAudioPlan::wanted(mic_settings, sharing_sound, audio.is_some_and(AudioSetup::uses_devices))2491
SoftwareAudioPlan::wanted(mic_settings, sharing_sound, audio.is_some_and(AudioSetup::uses_devices))2492
}2492
}2493
2493
2494
fn restore_device_track(factory: &PeerConnectionFactory, input: &DeviceChoice, peer: &PeerConnection, device_track: &RtcAudioTrack, timeline: &Timeline) {2495
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;2496
if cfg!(windows) && !factory.adm_recording_enabled() {2497
factory.set_adm_recording_enabled(true);2498
devices::select_input(factory, input);2499
}2500
if let Err(error) = swap_audio_track(peer, device_track) {2501
timeline.record("microphone track not restored", error.to_string());2502
}2503
}2504
2494
#[allow(clippy::too_many_arguments)]2505
#[allow(clippy::too_many_arguments)]2495
fn sync_software_audio(2506
fn sync_software_audio(2496
factory: &PeerConnectionFactory,2507
factory: &PeerConnectionFactory,@@ -2513,9 +2524,7 @@ fn sync_software_audio(2513
*software_audio = None;2524
*software_audio = None;2514
let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);2525
let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);2515
let Some(plan) = wanted else {2526
let Some(plan) = wanted else {2516
if let Err(error) = swap_audio_track(peer, device_track) {2527
restore_device_track(factory, input, peer, device_track, timeline);2517
timeline.record("microphone track not restored", error.to_string());2518
}2519
control.send(CallUpdate::ShareSound(false));2528
control.send(CallUpdate::ShareSound(false));2520
return;2529
return;2521
};2530
};@@ -2524,6 +2533,13 @@ fn sync_software_audio(2524
match started {2533
match started {2525
Ok(audio) => {2534
Ok(audio) => {2526
timeline.record("software audio", format!("{:?}, computer sound {:?}", plan.processing, audio.loopback));2535
timeline.record("software audio", format!("{:?}, computer sound {:?}", plan.processing, audio.loopback));2536
if let Some(source) = &audio.microphone_source {2537
timeline.record("mic capture", source.clone());2538
}2539
if cfg!(windows) && audio.microphone_source.is_some() {2540
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;2541
factory.set_adm_recording_enabled(false);2542
}2527
if let Some(warning) = &audio.warning {2543
if let Some(warning) = &audio.warning {2528
timeline.record("computer sound warning", warning.clone());2544
timeline.record("computer sound warning", warning.clone());2529
}2545
}@@ -2532,9 +2548,7 @@ fn sync_software_audio(2532
}2548
}2533
Err(error) => {2549
Err(error) => {2534
timeline.record("software audio failed", error.to_string());2550
timeline.record("software audio failed", error.to_string());2535
if let Err(error) = swap_audio_track(peer, device_track) {2551
restore_device_track(factory, input, peer, device_track, timeline);2536
timeline.record("microphone track not restored", error.to_string());2537
}2538
if was_sharing_sound || plan.computer_sound {2552
if was_sharing_sound || plan.computer_sound {2539
control.send(CallUpdate::ShareSound(false));2553
control.send(CallUpdate::ShareSound(false));2540
}2554
}@@ -26,6 +26,8 @@ pub mod luma_effects;
26
26
pub mod matte;
27
27
#[cfg(windows)]
28
28
mod loopback_windows;
29
#[cfg(windows)]
30
mod mic_windows;
29
31
pub mod meeting;
30
32
pub mod meeting_options;
31
33
pub mod mic_processing;
@@ -26,6 +26,8 @@ pub mod luma_effects;26
pub mod matte;26
pub mod matte;27
#[cfg(windows)]27
#[cfg(windows)]28
mod loopback_windows;28
mod loopback_windows;29
#[cfg(windows)]30
mod mic_windows;29
pub mod meeting;31
pub mod meeting;30
pub mod meeting_options;32
pub mod meeting_options;31
pub mod mic_processing;33
pub mod mic_processing;@@ -68,7 +68,11 @@ impl MicSettings {
68
68
}
69
69
70
70
pub fn uses_device_track(self) -> bool {
71
!self.music_mode && self.noise_suppression != NoiseSuppression::Off
71
self.uses_device_track_on(cfg!(windows))
72
}
73
74
pub fn uses_device_track_on(self, windows: bool) -> bool {
75
!windows && !self.music_mode && self.noise_suppression != NoiseSuppression::Off
72
76
}
73
77
74
78
pub fn ml_noise_suppression(self) -> bool {
@@ -105,6 +109,17 @@ mod tests {
105
109
assert!(!MicSettings { noise_suppression: NoiseSuppression::Auto, music_mode: true }.ml_noise_suppression());
106
110
}
107
111
112
#[test]
113
fn windows_never_uses_the_device_track() {
114
for noise_suppression in NoiseSuppression::ALL {
115
for music_mode in [false, true] {
116
let settings = MicSettings { noise_suppression, music_mode };
117
assert!(!settings.uses_device_track_on(true));
118
assert_eq!(settings.uses_device_track_on(false), !music_mode && noise_suppression != NoiseSuppression::Off);
119
}
120
}
121
}
122
108
123
#[test]
109
124
fn off_leaves_the_device_track_and_processes_nothing() {
110
125
let settings = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };
@@ -68,7 +68,11 @@ impl MicSettings {68
}68
}69
69
70
pub fn uses_device_track(self) -> bool {70
pub fn uses_device_track(self) -> bool {71
!self.music_mode && self.noise_suppression != NoiseSuppression::Off71
self.uses_device_track_on(cfg!(windows))72
}73
74
pub fn uses_device_track_on(self, windows: bool) -> bool {75
!windows && !self.music_mode && self.noise_suppression != NoiseSuppression::Off72
}76
}73
77
74
pub fn ml_noise_suppression(self) -> bool {78
pub fn ml_noise_suppression(self) -> bool {@@ -105,6 +109,17 @@ mod tests {105
assert!(!MicSettings { noise_suppression: NoiseSuppression::Auto, music_mode: true }.ml_noise_suppression());109
assert!(!MicSettings { noise_suppression: NoiseSuppression::Auto, music_mode: true }.ml_noise_suppression());106
}110
}107
111
112
#[test]113
fn windows_never_uses_the_device_track() {114
for noise_suppression in NoiseSuppression::ALL {115
for music_mode in [false, true] {116
let settings = MicSettings { noise_suppression, music_mode };117
assert!(!settings.uses_device_track_on(true));118
assert_eq!(settings.uses_device_track_on(false), !music_mode && noise_suppression != NoiseSuppression::Off);119
}120
}121
}122
108
#[test]123
#[test]109
fn off_leaves_the_device_track_and_processes_nothing() {124
fn off_leaves_the_device_track_and_processes_nothing() {110
let settings = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };125
let settings = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };@@ -0,0 +1,145 @@
1
use std::mem::size_of;
2
use std::sync::atomic::Ordering;
3
use std::sync::mpsc;
4
5
use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;
6
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};
7
use windows::Win32::Media::Audio::{
8
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
9
AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDCLNT_STREAMOPTIONS_NONE, AudioCategory_Communications, AudioClientProperties,
10
IAudioCaptureClient, IAudioClient, IAudioClient2, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX, eCapture,
11
eCommunications,
12
};
13
use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};
14
use windows::Win32::System::Com::{CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize, STGM_READ};
15
use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
16
use windows::core::{BOOL, HSTRING, Interface};
17
18
use crate::audio::SAMPLE_RATE;
19
use crate::capture::Capture;
20
use crate::devices::DeviceChoice;
21
use crate::error::{Error, Result};
22
use crate::pcm::SampleQueue;
23
24
const BITS: u16 = 16;
25
const EVENT_WAIT_MS: u32 = 100;
26
const PCM_TAG: u16 = 1;
27
28
fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {
29
Error::Audio(format!("{what}: {error}"))
30
}
31
32
fn open_device(choice: &DeviceChoice) -> Result<IMMDevice> {
33
unsafe {
34
let enumerator: IMMDeviceEnumerator =
35
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|error| audio_error("device enumerator", error))?;
36
match choice {
37
DeviceChoice::SystemDefault => enumerator
38
.GetDefaultAudioEndpoint(eCapture, eCommunications)
39
.map_err(|error| audio_error("default communications microphone", error)),
40
DeviceChoice::Device(key) => enumerator
41
.GetDevice(&HSTRING::from(key.as_str()))
42
.map_err(|error| audio_error("microphone endpoint", error)),
43
}
44
}
45
}
46
47
fn friendly_name(device: &IMMDevice) -> String {
48
unsafe {
49
let Ok(store) = device.OpenPropertyStore(STGM_READ) else { return String::new() };
50
let Ok(mut value) = store.GetValue(&PKEY_Device_FriendlyName) else { return String::new() };
51
let name = value.Anonymous.Anonymous.Anonymous.pwszVal.to_string().unwrap_or_default();
52
let _ = PropVariantClear(&mut value as *mut PROPVARIANT);
53
name
54
}
55
}
56
57
fn initialise(device: &IMMDevice) -> Result<(IAudioClient, IAudioCaptureClient, HANDLE)> {
58
let block_align = BITS / 8;
59
let format = WAVEFORMATEX {
60
wFormatTag: PCM_TAG,
61
nChannels: 1,
62
nSamplesPerSec: SAMPLE_RATE,
63
nAvgBytesPerSec: SAMPLE_RATE * u32::from(block_align),
64
nBlockAlign: block_align,
65
wBitsPerSample: BITS,
66
cbSize: 0,
67
};
68
let flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
69
unsafe {
70
let client: IAudioClient = device.Activate(CLSCTX_ALL, None).map_err(|error| audio_error("activate microphone", error))?;
71
let properties = AudioClientProperties {
72
cbSize: size_of::<AudioClientProperties>() as u32,
73
bIsOffload: BOOL(0),
74
eCategory: AudioCategory_Communications,
75
Options: AUDCLNT_STREAMOPTIONS_NONE,
76
};
77
client
78
.cast::<IAudioClient2>()
79
.and_then(|extended| extended.SetClientProperties(&raw const properties))
80
.map_err(|error| audio_error("communications category", error))?;
81
client
82
.Initialize(AUDCLNT_SHAREMODE_SHARED, flags, 0, 0, &raw const format, None)
83
.map_err(|error| audio_error("initialize microphone", error))?;
84
let event = CreateEventW(None, false, false, None).map_err(|error| audio_error("event", error))?;
85
client.SetEventHandle(event).map_err(|error| audio_error("event handle", error))?;
86
let capture = client.GetService::<IAudioCaptureClient>().map_err(|error| audio_error("capture service", error))?;
87
client.Start().map_err(|error| audio_error("start microphone", error))?;
88
Ok((client, capture, event))
89
}
90
}
91
92
fn drain(capture: &IAudioCaptureClient, queue: &SampleQueue) -> windows::core::Result<()> {
93
unsafe {
94
while capture.GetNextPacketSize()? > 0 {
95
let mut data = std::ptr::null_mut();
96
let mut frames = 0u32;
97
let mut flags = 0u32;
98
capture.GetBuffer(&mut data, &mut frames, &mut flags, None, None)?;
99
let samples: Vec<i16> = if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 || data.is_null() {
100
vec![0; frames as usize]
101
} else {
102
std::slice::from_raw_parts(data.cast::<i16>(), frames as usize).to_vec()
103
};
104
capture.ReleaseBuffer(frames)?;
105
queue.push(&samples);
106
}
107
}
108
Ok(())
109
}
110
111
pub fn start_communications_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<(Capture, String)> {
112
let (ready_sender, ready) = mpsc::channel::<Result<String>>();
113
let choice = choice.clone();
114
let capture = Capture::spawn_thread("mic-communications", move |stop| {
115
unsafe {
116
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
117
}
118
let started = open_device(&choice).and_then(|device| {
119
let name = friendly_name(&device);
120
initialise(&device).map(|(client, capture, event)| (name, client, capture, event))
121
});
122
match started {
123
Ok((name, client, capture, event)) => {
124
let _ = ready_sender.send(Ok(name));
125
while !stop.load(Ordering::SeqCst) {
126
let waited = unsafe { WaitForSingleObject(event, EVENT_WAIT_MS) };
127
if waited == WAIT_OBJECT_0 && drain(&capture, &queue).is_err() {
128
break;
129
}
130
}
131
unsafe {
132
let _ = client.Stop();
133
let _ = CloseHandle(event);
134
}
135
}
136
Err(error) => {
137
let _ = ready_sender.send(Err(error));
138
}
139
}
140
unsafe { CoUninitialize() };
141
})
142
.map_err(|error| audio_error("microphone thread", error))?;
143
let name = ready.recv().map_err(|_| Error::Audio("microphone thread ended".into()))??;
144
Ok((capture, name))
145
}
@@ -0,0 +1,145 @@1
use std::mem::size_of;2
use std::sync::atomic::Ordering;3
use std::sync::mpsc;4
5
use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;6
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};7
use windows::Win32::Media::Audio::{8
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,9
AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDCLNT_STREAMOPTIONS_NONE, AudioCategory_Communications, AudioClientProperties,10
IAudioCaptureClient, IAudioClient, IAudioClient2, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX, eCapture,11
eCommunications,12
};13
use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};14
use windows::Win32::System::Com::{CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize, STGM_READ};15
use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};16
use windows::core::{BOOL, HSTRING, Interface};17
18
use crate::audio::SAMPLE_RATE;19
use crate::capture::Capture;20
use crate::devices::DeviceChoice;21
use crate::error::{Error, Result};22
use crate::pcm::SampleQueue;23
24
const BITS: u16 = 16;25
const EVENT_WAIT_MS: u32 = 100;26
const PCM_TAG: u16 = 1;27
28
fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {29
Error::Audio(format!("{what}: {error}"))30
}31
32
fn open_device(choice: &DeviceChoice) -> Result<IMMDevice> {33
unsafe {34
let enumerator: IMMDeviceEnumerator =35
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|error| audio_error("device enumerator", error))?;36
match choice {37
DeviceChoice::SystemDefault => enumerator38
.GetDefaultAudioEndpoint(eCapture, eCommunications)39
.map_err(|error| audio_error("default communications microphone", error)),40
DeviceChoice::Device(key) => enumerator41
.GetDevice(&HSTRING::from(key.as_str()))42
.map_err(|error| audio_error("microphone endpoint", error)),43
}44
}45
}46
47
fn friendly_name(device: &IMMDevice) -> String {48
unsafe {49
let Ok(store) = device.OpenPropertyStore(STGM_READ) else { return String::new() };50
let Ok(mut value) = store.GetValue(&PKEY_Device_FriendlyName) else { return String::new() };51
let name = value.Anonymous.Anonymous.Anonymous.pwszVal.to_string().unwrap_or_default();52
let _ = PropVariantClear(&mut value as *mut PROPVARIANT);53
name54
}55
}56
57
fn initialise(device: &IMMDevice) -> Result<(IAudioClient, IAudioCaptureClient, HANDLE)> {58
let block_align = BITS / 8;59
let format = WAVEFORMATEX {60
wFormatTag: PCM_TAG,61
nChannels: 1,62
nSamplesPerSec: SAMPLE_RATE,63
nAvgBytesPerSec: SAMPLE_RATE * u32::from(block_align),64
nBlockAlign: block_align,65
wBitsPerSample: BITS,66
cbSize: 0,67
};68
let flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;69
unsafe {70
let client: IAudioClient = device.Activate(CLSCTX_ALL, None).map_err(|error| audio_error("activate microphone", error))?;71
let properties = AudioClientProperties {72
cbSize: size_of::<AudioClientProperties>() as u32,73
bIsOffload: BOOL(0),74
eCategory: AudioCategory_Communications,75
Options: AUDCLNT_STREAMOPTIONS_NONE,76
};77
client78
.cast::<IAudioClient2>()79
.and_then(|extended| extended.SetClientProperties(&raw const properties))80
.map_err(|error| audio_error("communications category", error))?;81
client82
.Initialize(AUDCLNT_SHAREMODE_SHARED, flags, 0, 0, &raw const format, None)83
.map_err(|error| audio_error("initialize microphone", error))?;84
let event = CreateEventW(None, false, false, None).map_err(|error| audio_error("event", error))?;85
client.SetEventHandle(event).map_err(|error| audio_error("event handle", error))?;86
let capture = client.GetService::<IAudioCaptureClient>().map_err(|error| audio_error("capture service", error))?;87
client.Start().map_err(|error| audio_error("start microphone", error))?;88
Ok((client, capture, event))89
}90
}91
92
fn drain(capture: &IAudioCaptureClient, queue: &SampleQueue) -> windows::core::Result<()> {93
unsafe {94
while capture.GetNextPacketSize()? > 0 {95
let mut data = std::ptr::null_mut();96
let mut frames = 0u32;97
let mut flags = 0u32;98
capture.GetBuffer(&mut data, &mut frames, &mut flags, None, None)?;99
let samples: Vec<i16> = if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 || data.is_null() {100
vec![0; frames as usize]101
} else {102
std::slice::from_raw_parts(data.cast::<i16>(), frames as usize).to_vec()103
};104
capture.ReleaseBuffer(frames)?;105
queue.push(&samples);106
}107
}108
Ok(())109
}110
111
pub fn start_communications_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<(Capture, String)> {112
let (ready_sender, ready) = mpsc::channel::<Result<String>>();113
let choice = choice.clone();114
let capture = Capture::spawn_thread("mic-communications", move |stop| {115
unsafe {116
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);117
}118
let started = open_device(&choice).and_then(|device| {119
let name = friendly_name(&device);120
initialise(&device).map(|(client, capture, event)| (name, client, capture, event))121
});122
match started {123
Ok((name, client, capture, event)) => {124
let _ = ready_sender.send(Ok(name));125
while !stop.load(Ordering::SeqCst) {126
let waited = unsafe { WaitForSingleObject(event, EVENT_WAIT_MS) };127
if waited == WAIT_OBJECT_0 && drain(&capture, &queue).is_err() {128
break;129
}130
}131
unsafe {132
let _ = client.Stop();133
let _ = CloseHandle(event);134
}135
}136
Err(error) => {137
let _ = ready_sender.send(Err(error));138
}139
}140
unsafe { CoUninitialize() };141
})142
.map_err(|error| audio_error("microphone thread", error))?;143
let name = ready.recv().map_err(|_| Error::Audio("microphone thread ended".into()))??;144
Ok((capture, name))145
}@@ -27,6 +27,14 @@ impl NoiseStage {
27
27
let input: [f32; FRAME_SIZE] = std::array::from_fn(|index| samples[index]);
28
28
self.channels[channel_index].process_frame(samples, &input);
29
29
}
30
31
pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {
32
let mut floats: Vec<f32> = samples.iter().map(|sample| f32::from(*sample)).collect();
33
self.process(channel_index, &mut floats);
34
for (sample, processed) in samples.iter_mut().zip(floats) {
35
*sample = processed.clamp(f32::from(i16::MIN), f32::from(i16::MAX)) as i16;
36
}
37
}
30
38
}
31
39
32
40
impl Default for NoiseStage {
@@ -27,6 +27,14 @@ impl NoiseStage {27
let input: [f32; FRAME_SIZE] = std::array::from_fn(|index| samples[index]);27
let input: [f32; FRAME_SIZE] = std::array::from_fn(|index| samples[index]);28
self.channels[channel_index].process_frame(samples, &input);28
self.channels[channel_index].process_frame(samples, &input);29
}29
}30
31
pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {32
let mut floats: Vec<f32> = samples.iter().map(|sample| f32::from(*sample)).collect();33
self.process(channel_index, &mut floats);34
for (sample, processed) in samples.iter_mut().zip(floats) {35
*sample = processed.clamp(f32::from(i16::MIN), f32::from(i16::MAX)) as i16;36
}37
}30
}38
}31
39
32
impl Default for NoiseStage {40
impl Default for NoiseStage {@@ -16,6 +16,7 @@ use crate::devices::DeviceChoice;
16
16
use crate::error::{Error, Result};
17
17
use crate::mic_processing::{ApmConfig, MicSettings};
18
18
use crate::mixer::mix_frames;
19
use crate::noise_stage::NoiseStage;
19
20
use crate::pcm::SampleQueue;
20
21
use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};
21
22
@@ -44,11 +45,13 @@ impl FrameSource {
44
45
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45
46
pub struct SoftwareAudioPlan {
46
47
pub processing: ApmConfig,
48
pub ml_noise: bool,
47
49
pub computer_sound: bool,
48
50
}
49
51
50
52
struct Feeder {
51
53
processing: ApmConfig,
54
ml_noise: Option<NoiseStage>,
52
55
source: NativeAudioSource,
53
56
microphone: FrameSource,
54
57
computer: FrameSource,
@@ -79,6 +82,9 @@ impl Feeder {
79
82
if !muted && let Some(processing) = processing.as_mut() {
80
83
let _ = processing.process_stream(&mut microphone, SAMPLE_RATE as i32, 1);
81
84
}
85
if !muted && let Some(noise_stage) = self.ml_noise.as_mut() {
86
noise_stage.process_pcm(0, &mut microphone);
87
}
82
88
let computer = self.computer.next_frame();
83
89
let frame = AudioFrame {
84
90
data: mix_frames(µphone, &computer, muted).into(),
@@ -99,6 +105,7 @@ pub struct SoftwareAudio {
99
105
pub plan: SoftwareAudioPlan,
100
106
pub loopback: Option<LoopbackKind>,
101
107
pub warning: Option<String>,
108
pub microphone_source: Option<String>,
102
109
microphone_muted: Arc<AtomicBool>,
103
110
running: Arc<AtomicBool>,
104
111
feeder: Option<std::thread::JoinHandle<()>>,
@@ -108,8 +115,13 @@ pub struct SoftwareAudio {
108
115
109
116
impl SoftwareAudioPlan {
110
117
pub fn wanted(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {
111
(sharing_sound || (uses_devices && !mic.uses_device_track())).then(|| SoftwareAudioPlan {
118
Self::wanted_on(cfg!(windows), mic, sharing_sound, uses_devices)
119
}
120
121
pub fn wanted_on(windows: bool, mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {
122
(sharing_sound || (uses_devices && !mic.uses_device_track_on(windows))).then(|| SoftwareAudioPlan {
112
123
processing: mic.apm_config(),
124
ml_noise: mic.ml_noise_suppression(),
113
125
computer_sound: sharing_sound,
114
126
})
115
127
}
@@ -127,6 +139,7 @@ impl SoftwareAudio {
127
139
) -> Result<Self> {
128
140
let mut captures = Vec::new();
129
141
let mut warning = None;
142
let mut microphone_source = None;
130
143
let (microphone, computer, loopback) = if mode == AudioMode::Platform {
131
144
let computer_queue = SampleQueue::default();
132
145
let (computer, loopback) = if plan.computer_sound {
@@ -139,11 +152,15 @@ impl SoftwareAudio {
139
152
};
140
153
let microphone_queue = SampleQueue::default();
141
154
let microphone = match start_microphone(input, microphone_queue.clone()) {
142
Ok(capture) => {
143
captures.push(capture);
155
Ok(started) => {
156
microphone_source = Some(started.source);
157
captures.push(started.capture);
144
158
FrameSource::Captured(microphone_queue)
145
159
}
146
160
Err(error) => {
161
if !plan.computer_sound {
162
return Err(error);
163
}
147
164
warning.get_or_insert(format!("microphone not captured while sharing sound: {error}"));
148
165
FrameSource::Silence
149
166
}
@@ -170,6 +187,7 @@ impl SoftwareAudio {
170
187
let running = Arc::new(AtomicBool::new(true));
171
188
let feeder = Feeder {
172
189
processing: plan.processing,
190
ml_noise: plan.ml_noise.then(NoiseStage::new),
173
191
source,
174
192
microphone,
175
193
computer,
@@ -187,6 +205,7 @@ impl SoftwareAudio {
187
205
plan,
188
206
loopback,
189
207
warning,
208
microphone_source,
190
209
microphone_muted,
191
210
running,
192
211
feeder: Some(thread),
@@ -227,7 +246,7 @@ mod tests {
227
246
228
247
#[tokio::test(flavor = "multi_thread")]
229
248
async fn synthetic_sources_start_and_stop_cleanly() {
230
let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), computer_sound: true };
249
let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), ml_noise: true, computer_sound: true };
231
250
let audio = SoftwareAudio::start(&shared_factory(), AudioMode::Tone, 440.0, &DeviceChoice::SystemDefault, plan, true, None).unwrap();
232
251
assert_eq!(audio.loopback, Some(LoopbackKind::Synthetic));
233
252
assert!(audio.warning.is_none());
@@ -240,17 +259,40 @@ mod tests {
240
259
fn the_plan_follows_sharing_and_the_mic_choice() {
241
260
let auto = MicSettings::default();
242
261
let off = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };
243
assert_eq!(SoftwareAudioPlan::wanted(auto, false, true), None);
244
assert_eq!(SoftwareAudioPlan::wanted(off, false, false), None);
245
let mic_only = SoftwareAudioPlan::wanted(off, false, true).unwrap();
262
assert_eq!(SoftwareAudioPlan::wanted_on(false, auto, false, true), None);
263
assert_eq!(SoftwareAudioPlan::wanted_on(false, off, false, false), None);
264
let mic_only = SoftwareAudioPlan::wanted_on(false, off, false, true).unwrap();
246
265
assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());
247
let sharing = SoftwareAudioPlan::wanted(auto, true, false).unwrap();
266
let sharing = SoftwareAudioPlan::wanted_on(false, auto, true, false).unwrap();
248
267
assert!(sharing.computer_sound && sharing.processing.echo_canceller);
249
268
}
250
269
270
#[test]
271
fn windows_runs_the_software_path_for_every_mic_setting() {
272
for noise_suppression in NoiseSuppression::ALL {
273
for music_mode in [false, true] {
274
let mic = MicSettings { noise_suppression, music_mode };
275
assert!(SoftwareAudioPlan::wanted_on(true, mic, false, true).is_some());
276
assert!(SoftwareAudioPlan::wanted_on(true, mic, false, false).is_none());
277
assert_eq!(SoftwareAudioPlan::wanted_on(false, mic, false, true).is_some(), !mic.uses_device_track_on(false));
278
}
279
}
280
}
281
282
#[test]
283
fn rnnoise_runs_in_the_software_path_only_for_auto() {
284
let ml_noise = |noise_suppression, music_mode| {
285
SoftwareAudioPlan::wanted_on(true, MicSettings { noise_suppression, music_mode }, false, true).unwrap().ml_noise
286
};
287
assert!(ml_noise(NoiseSuppression::Auto, false));
288
assert!(!ml_noise(NoiseSuppression::Low, false));
289
assert!(!ml_noise(NoiseSuppression::Off, false));
290
assert!(!ml_noise(NoiseSuppression::Auto, true));
291
}
292
251
293
#[tokio::test(flavor = "multi_thread")]
252
294
async fn a_microphone_only_plan_has_no_computer_sound() {
253
let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), computer_sound: false };
295
let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), ml_noise: true, computer_sound: false };
254
296
let audio = SoftwareAudio::start(&shared_factory(), AudioMode::Silence, 440.0, &DeviceChoice::SystemDefault, plan, false, None).unwrap();
255
297
assert_eq!(audio.loopback, None);
256
298
tokio::time::sleep(Duration::from_millis(60)).await;
@@ -16,6 +16,7 @@ use crate::devices::DeviceChoice;16
use crate::error::{Error, Result};16
use crate::error::{Error, Result};17
use crate::mic_processing::{ApmConfig, MicSettings};17
use crate::mic_processing::{ApmConfig, MicSettings};18
use crate::mixer::mix_frames;18
use crate::mixer::mix_frames;19
use crate::noise_stage::NoiseStage;19
use crate::pcm::SampleQueue;20
use crate::pcm::SampleQueue;20
use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};21
use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};21
22
@@ -44,11 +45,13 @@ impl FrameSource {44
#[derive(Debug, Clone, Copy, PartialEq, Eq)]45
#[derive(Debug, Clone, Copy, PartialEq, Eq)]45
pub struct SoftwareAudioPlan {46
pub struct SoftwareAudioPlan {46
pub processing: ApmConfig,47
pub processing: ApmConfig,48
pub ml_noise: bool,47
pub computer_sound: bool,49
pub computer_sound: bool,48
}50
}49
51
50
struct Feeder {52
struct Feeder {51
processing: ApmConfig,53
processing: ApmConfig,54
ml_noise: Option<NoiseStage>,52
source: NativeAudioSource,55
source: NativeAudioSource,53
microphone: FrameSource,56
microphone: FrameSource,54
computer: FrameSource,57
computer: FrameSource,@@ -79,6 +82,9 @@ impl Feeder {79
if !muted && let Some(processing) = processing.as_mut() {82
if !muted && let Some(processing) = processing.as_mut() {80
let _ = processing.process_stream(&mut microphone, SAMPLE_RATE as i32, 1);83
let _ = processing.process_stream(&mut microphone, SAMPLE_RATE as i32, 1);81
}84
}85
if !muted && let Some(noise_stage) = self.ml_noise.as_mut() {86
noise_stage.process_pcm(0, &mut microphone);87
}82
let computer = self.computer.next_frame();88
let computer = self.computer.next_frame();83
let frame = AudioFrame {89
let frame = AudioFrame {84
data: mix_frames(µphone, &computer, muted).into(),90
data: mix_frames(µphone, &computer, muted).into(),@@ -99,6 +105,7 @@ pub struct SoftwareAudio {99
pub plan: SoftwareAudioPlan,105
pub plan: SoftwareAudioPlan,100
pub loopback: Option<LoopbackKind>,106
pub loopback: Option<LoopbackKind>,101
pub warning: Option<String>,107
pub warning: Option<String>,108
pub microphone_source: Option<String>,102
microphone_muted: Arc<AtomicBool>,109
microphone_muted: Arc<AtomicBool>,103
running: Arc<AtomicBool>,110
running: Arc<AtomicBool>,104
feeder: Option<std::thread::JoinHandle<()>>,111
feeder: Option<std::thread::JoinHandle<()>>,@@ -108,8 +115,13 @@ pub struct SoftwareAudio {108
115
109
impl SoftwareAudioPlan {116
impl SoftwareAudioPlan {110
pub fn wanted(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {117
pub fn wanted(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {111
(sharing_sound || (uses_devices && !mic.uses_device_track())).then(|| SoftwareAudioPlan {118
Self::wanted_on(cfg!(windows), mic, sharing_sound, uses_devices)119
}120
121
pub fn wanted_on(windows: bool, mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {122
(sharing_sound || (uses_devices && !mic.uses_device_track_on(windows))).then(|| SoftwareAudioPlan {112
processing: mic.apm_config(),123
processing: mic.apm_config(),124
ml_noise: mic.ml_noise_suppression(),113
computer_sound: sharing_sound,125
computer_sound: sharing_sound,114
})126
})115
}127
}@@ -127,6 +139,7 @@ impl SoftwareAudio {127
) -> Result<Self> {139
) -> Result<Self> {128
let mut captures = Vec::new();140
let mut captures = Vec::new();129
let mut warning = None;141
let mut warning = None;142
let mut microphone_source = None;130
let (microphone, computer, loopback) = if mode == AudioMode::Platform {143
let (microphone, computer, loopback) = if mode == AudioMode::Platform {131
let computer_queue = SampleQueue::default();144
let computer_queue = SampleQueue::default();132
let (computer, loopback) = if plan.computer_sound {145
let (computer, loopback) = if plan.computer_sound {@@ -139,11 +152,15 @@ impl SoftwareAudio {139
};152
};140
let microphone_queue = SampleQueue::default();153
let microphone_queue = SampleQueue::default();141
let microphone = match start_microphone(input, microphone_queue.clone()) {154
let microphone = match start_microphone(input, microphone_queue.clone()) {142
Ok(capture) => {155
Ok(started) => {143
captures.push(capture);156
microphone_source = Some(started.source);157
captures.push(started.capture);144
FrameSource::Captured(microphone_queue)158
FrameSource::Captured(microphone_queue)145
}159
}146
Err(error) => {160
Err(error) => {161
if !plan.computer_sound {162
return Err(error);163
}147
warning.get_or_insert(format!("microphone not captured while sharing sound: {error}"));164
warning.get_or_insert(format!("microphone not captured while sharing sound: {error}"));148
FrameSource::Silence165
FrameSource::Silence149
}166
}@@ -170,6 +187,7 @@ impl SoftwareAudio {170
let running = Arc::new(AtomicBool::new(true));187
let running = Arc::new(AtomicBool::new(true));171
let feeder = Feeder {188
let feeder = Feeder {172
processing: plan.processing,189
processing: plan.processing,190
ml_noise: plan.ml_noise.then(NoiseStage::new),173
source,191
source,174
microphone,192
microphone,175
computer,193
computer,@@ -187,6 +205,7 @@ impl SoftwareAudio {187
plan,205
plan,188
loopback,206
loopback,189
warning,207
warning,208
microphone_source,190
microphone_muted,209
microphone_muted,191
running,210
running,192
feeder: Some(thread),211
feeder: Some(thread),@@ -227,7 +246,7 @@ mod tests {227
246
228
#[tokio::test(flavor = "multi_thread")]247
#[tokio::test(flavor = "multi_thread")]229
async fn synthetic_sources_start_and_stop_cleanly() {248
async fn synthetic_sources_start_and_stop_cleanly() {230
let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), computer_sound: true };249
let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), ml_noise: true, computer_sound: true };231
let audio = SoftwareAudio::start(&shared_factory(), AudioMode::Tone, 440.0, &DeviceChoice::SystemDefault, plan, true, None).unwrap();250
let audio = SoftwareAudio::start(&shared_factory(), AudioMode::Tone, 440.0, &DeviceChoice::SystemDefault, plan, true, None).unwrap();232
assert_eq!(audio.loopback, Some(LoopbackKind::Synthetic));251
assert_eq!(audio.loopback, Some(LoopbackKind::Synthetic));233
assert!(audio.warning.is_none());252
assert!(audio.warning.is_none());@@ -240,17 +259,40 @@ mod tests {240
fn the_plan_follows_sharing_and_the_mic_choice() {259
fn the_plan_follows_sharing_and_the_mic_choice() {241
let auto = MicSettings::default();260
let auto = MicSettings::default();242
let off = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };261
let off = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };243
assert_eq!(SoftwareAudioPlan::wanted(auto, false, true), None);262
assert_eq!(SoftwareAudioPlan::wanted_on(false, auto, false, true), None);244
assert_eq!(SoftwareAudioPlan::wanted(off, false, false), None);263
assert_eq!(SoftwareAudioPlan::wanted_on(false, off, false, false), None);245
let mic_only = SoftwareAudioPlan::wanted(off, false, true).unwrap();264
let mic_only = SoftwareAudioPlan::wanted_on(false, off, false, true).unwrap();246
assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());265
assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());247
let sharing = SoftwareAudioPlan::wanted(auto, true, false).unwrap();266
let sharing = SoftwareAudioPlan::wanted_on(false, auto, true, false).unwrap();248
assert!(sharing.computer_sound && sharing.processing.echo_canceller);267
assert!(sharing.computer_sound && sharing.processing.echo_canceller);249
}268
}250
269
270
#[test]271
fn windows_runs_the_software_path_for_every_mic_setting() {272
for noise_suppression in NoiseSuppression::ALL {273
for music_mode in [false, true] {274
let mic = MicSettings { noise_suppression, music_mode };275
assert!(SoftwareAudioPlan::wanted_on(true, mic, false, true).is_some());276
assert!(SoftwareAudioPlan::wanted_on(true, mic, false, false).is_none());277
assert_eq!(SoftwareAudioPlan::wanted_on(false, mic, false, true).is_some(), !mic.uses_device_track_on(false));278
}279
}280
}281
282
#[test]283
fn rnnoise_runs_in_the_software_path_only_for_auto() {284
let ml_noise = |noise_suppression, music_mode| {285
SoftwareAudioPlan::wanted_on(true, MicSettings { noise_suppression, music_mode }, false, true).unwrap().ml_noise286
};287
assert!(ml_noise(NoiseSuppression::Auto, false));288
assert!(!ml_noise(NoiseSuppression::Low, false));289
assert!(!ml_noise(NoiseSuppression::Off, false));290
assert!(!ml_noise(NoiseSuppression::Auto, true));291
}292
251
#[tokio::test(flavor = "multi_thread")]293
#[tokio::test(flavor = "multi_thread")]252
async fn a_microphone_only_plan_has_no_computer_sound() {294
async fn a_microphone_only_plan_has_no_computer_sound() {253
let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), computer_sound: false };295
let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), ml_noise: true, computer_sound: false };254
let audio = SoftwareAudio::start(&shared_factory(), AudioMode::Silence, 440.0, &DeviceChoice::SystemDefault, plan, false, None).unwrap();296
let audio = SoftwareAudio::start(&shared_factory(), AudioMode::Silence, 440.0, &DeviceChoice::SystemDefault, plan, false, None).unwrap();255
assert_eq!(audio.loopback, None);297
assert_eq!(audio.loopback, None);256
tokio::time::sleep(Duration::from_millis(60)).await;298
tokio::time::sleep(Duration::from_millis(60)).await;@@ -40,7 +40,29 @@ fn named_input(choice: &DeviceChoice) -> Option<Device> {
40
40
.find(|device| device.description().is_ok_and(|description| description.name() == wanted))
41
41
}
42
42
43
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {
43
pub struct MicrophoneStart {
44
pub capture: Capture,
45
pub source: String,
46
}
47
48
#[cfg(windows)]
49
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
50
match crate::mic_windows::start_communications_microphone(choice, queue.clone()) {
51
Ok((capture, name)) => Ok(MicrophoneStart { capture, source: format!("wasapi communications ({name})") }),
52
Err(error) => {
53
let capture = start_cpal_microphone(choice, queue)?;
54
Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}") })
55
}
56
}
57
}
58
59
#[cfg(not(windows))]
60
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
61
let capture = start_cpal_microphone(choice, queue)?;
62
Ok(MicrophoneStart { capture, source: "cpal".into() })
63
}
64
65
fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {
44
66
let device = named_input(choice)
45
67
.or_else(|| cpal::default_host().default_input_device())
46
68
.ok_or_else(|| Error::Audio("no microphone".into()))?;
@@ -40,7 +40,29 @@ fn named_input(choice: &DeviceChoice) -> Option<Device> {40
.find(|device| device.description().is_ok_and(|description| description.name() == wanted))40
.find(|device| device.description().is_ok_and(|description| description.name() == wanted))41
}41
}42
42
43
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {43
pub struct MicrophoneStart {44
pub capture: Capture,45
pub source: String,46
}47
48
#[cfg(windows)]49
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {50
match crate::mic_windows::start_communications_microphone(choice, queue.clone()) {51
Ok((capture, name)) => Ok(MicrophoneStart { capture, source: format!("wasapi communications ({name})") }),52
Err(error) => {53
let capture = start_cpal_microphone(choice, queue)?;54
Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}") })55
}56
}57
}58
59
#[cfg(not(windows))]60
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {61
let capture = start_cpal_microphone(choice, queue)?;62
Ok(MicrophoneStart { capture, source: "cpal".into() })63
}64
65
fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {44
let device = named_input(choice)66
let device = named_input(choice)45
.or_else(|| cpal::default_host().default_input_device())67
.or_else(|| cpal::default_host().default_input_device())46
.ok_or_else(|| Error::Audio("no microphone".into()))?;68
.ok_or_else(|| Error::Audio("no microphone".into()))?;