1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
use crate::Windows;
use crate::Windows::{
Win32::Foundation::{HANDLE, PSTR},
Win32::Media::Audio::CoreAudio::{
eCapture, eConsole, eRender, AudioSessionStateActive, AudioSessionStateExpired,
AudioSessionStateInactive, IAudioCaptureClient, IAudioClient, IAudioRenderClient,
IAudioSessionControl, IAudioSessionEvents, IMMDevice, IMMDeviceCollection,
IMMDeviceEnumerator, MMDeviceEnumerator, AUDCLNT_SHAREMODE_EXCLUSIVE,
AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
AUDCLNT_STREAMFLAGS_EVENTCALLBACK, AUDCLNT_STREAMFLAGS_LOOPBACK,
AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, DEVICE_STATE_ACTIVE, WAVE_FORMAT_EXTENSIBLE,
},
Win32::Media::Multimedia::{WAVEFORMATEX, WAVEFORMATEXTENSIBLE},
Win32::System::Com::StructuredStorage::STGM_READ,
Win32::System::Com::CLSCTX_ALL,
Win32::System::Com::{
CoCreateInstance, CoInitializeEx, COINIT_APARTMENTTHREADED, COINIT_MULTITHREADED,
},
Win32::System::PropertiesSystem::PropVariantToStringAlloc,
Win32::System::Threading::{CreateEventA, WaitForSingleObject},
};
use std::collections::VecDeque;
use std::error;
use std::fmt;
use std::mem;
use std::ptr;
use std::rc::Weak;
use std::slice;
use widestring::U16CString;
use windows::runtime::Interface;
use Windows::Win32::System::SystemServices::{
DEVPKEY_Device_DeviceDesc, DEVPKEY_Device_FriendlyName,
};
use Windows::Win32::System::Threading::WAIT_OBJECT_0;
use crate::WaveFormat;
use crate::{AudioSessionEvents, EventCallbacks};
pub(crate) type WasapiRes<T> = Result<T, Box<dyn error::Error>>;
#[derive(Debug)]
pub struct WasapiError {
desc: String,
}
impl fmt::Display for WasapiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.desc)
}
}
impl error::Error for WasapiError {
fn description(&self) -> &str {
&self.desc
}
}
impl WasapiError {
pub fn new(desc: &str) -> Self {
WasapiError {
desc: desc.to_owned(),
}
}
}
pub fn initialize_mta() -> Result<(), windows::runtime::Error> {
unsafe { CoInitializeEx(std::ptr::null_mut(), COINIT_MULTITHREADED) }
}
pub fn initialize_sta() -> Result<(), windows::runtime::Error> {
unsafe { CoInitializeEx(std::ptr::null_mut(), COINIT_APARTMENTTHREADED) }
}
#[derive(Clone)]
pub enum Direction {
Render,
Capture,
}
#[derive(Clone)]
pub enum ShareMode {
Shared,
Exclusive,
}
#[derive(Clone)]
pub enum SampleType {
Float,
Int,
}
pub fn get_default_device(direction: &Direction) -> WasapiRes<Device> {
let dir = match direction {
Direction::Capture => eCapture,
Direction::Render => eRender,
};
let enumerator: IMMDeviceEnumerator =
unsafe { CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)? };
let device = unsafe { enumerator.GetDefaultAudioEndpoint(dir, eConsole)? };
let dev = Device {
device,
direction: direction.clone(),
};
debug!("default device {:?}", dev.get_friendlyname());
Ok(dev)
}
pub struct DeviceCollection {
collection: IMMDeviceCollection,
direction: Direction,
}
impl DeviceCollection {
pub fn new(direction: &Direction) -> WasapiRes<DeviceCollection> {
let dir = match direction {
Direction::Capture => eCapture,
Direction::Render => eRender,
};
let enumerator: IMMDeviceEnumerator =
unsafe { CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)? };
let devs = unsafe { enumerator.EnumAudioEndpoints(dir, DEVICE_STATE_ACTIVE)? };
Ok(DeviceCollection {
collection: devs,
direction: direction.clone(),
})
}
pub fn get_nbr_devices(&self) -> WasapiRes<u32> {
let count = unsafe { self.collection.GetCount()? };
Ok(count)
}
pub fn get_device_at_index(&self, idx: u32) -> WasapiRes<Device> {
let device = unsafe { self.collection.Item(idx)? };
Ok(Device {
device,
direction: self.direction.clone(),
})
}
pub fn get_device_with_name(&self, name: &str) -> WasapiRes<Device> {
let count = unsafe { self.collection.GetCount()? };
trace!("nbr devices {}", count);
for n in 0..count {
let device = self.get_device_at_index(n)?;
let devname = device.get_friendlyname()?;
if name == devname {
return Ok(device);
}
}
Err(WasapiError::new(format!("Unable to find device {}", name).as_str()).into())
}
}
pub struct Device {
device: IMMDevice,
direction: Direction,
}
impl Device {
pub fn get_iaudioclient(&self) -> WasapiRes<AudioClient> {
let mut audio_client: mem::MaybeUninit<IAudioClient> = mem::MaybeUninit::zeroed();
unsafe {
self.device.Activate(
&IAudioClient::IID,
CLSCTX_ALL.0,
ptr::null_mut(),
audio_client.as_mut_ptr() as *mut _,
)?;
Ok(AudioClient {
client: audio_client.assume_init(),
direction: self.direction.clone(),
sharemode: None,
})
}
}
pub fn get_state(&self) -> WasapiRes<u32> {
let state: u32 = unsafe { self.device.GetState()? };
trace!("state: {:?}", state);
Ok(state)
}
pub fn get_friendlyname(&self) -> WasapiRes<String> {
let store = unsafe { self.device.OpenPropertyStore(STGM_READ as u32)? };
let prop = unsafe { store.GetValue(&DEVPKEY_Device_FriendlyName)? };
let propstr = unsafe { PropVariantToStringAlloc(&prop)? };
let wide_name = unsafe { U16CString::from_ptr_str(propstr.0) };
let name = wide_name.to_string_lossy();
trace!("name: {}", name);
Ok(name)
}
pub fn get_description(&self) -> WasapiRes<String> {
let store = unsafe { self.device.OpenPropertyStore(STGM_READ as u32)? };
let prop = unsafe { store.GetValue(&DEVPKEY_Device_DeviceDesc)? };
let propstr = unsafe { PropVariantToStringAlloc(&prop)? };
let wide_desc = unsafe { U16CString::from_ptr_str(propstr.0) };
let desc = wide_desc.to_string_lossy();
trace!("description: {}", desc);
Ok(desc)
}
pub fn get_id(&self) -> WasapiRes<String> {
let idstr = unsafe { self.device.GetId()? };
let wide_id = unsafe { U16CString::from_ptr_str(idstr.0) };
let id = wide_id.to_string_lossy();
trace!("id: {}", id);
Ok(id)
}
}
pub struct AudioClient {
client: IAudioClient,
direction: Direction,
sharemode: Option<ShareMode>,
}
impl AudioClient {
pub fn get_mixformat(&self) -> WasapiRes<WaveFormat> {
let temp_fmt_ptr = unsafe { self.client.GetMixFormat()? };
let temp_fmt = unsafe { *temp_fmt_ptr };
let mix_format =
if temp_fmt.cbSize == 22 && temp_fmt.wFormatTag as u32 == WAVE_FORMAT_EXTENSIBLE {
unsafe {
WaveFormat {
wave_fmt: (temp_fmt_ptr as *const _ as *const WAVEFORMATEXTENSIBLE).read(),
}
}
} else {
WaveFormat::from_waveformatex(temp_fmt)?
};
Ok(mix_format)
}
pub fn is_supported(
&self,
wave_fmt: &WaveFormat,
sharemode: &ShareMode,
) -> WasapiRes<Option<WaveFormat>> {
let supported = match sharemode {
ShareMode::Exclusive => {
unsafe {
self.client.IsFormatSupported(
AUDCLNT_SHAREMODE_EXCLUSIVE,
wave_fmt.as_waveformatex_ptr(),
)?
};
None
}
ShareMode::Shared => {
let supported_format = unsafe {
self.client
.IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, wave_fmt.as_waveformatex_ptr())
}?;
if supported_format.is_null() {
debug!("requested format is directly supported");
None
} else {
let temp_fmt: WAVEFORMATEX = unsafe { supported_format.read() };
debug!("requested format is not directly supported");
let new_fmt = if temp_fmt.cbSize == 22
&& temp_fmt.wFormatTag as u32 == WAVE_FORMAT_EXTENSIBLE
{
debug!("got the supported format as a WAVEFORMATEXTENSIBLE");
let temp_fmt_ext: WAVEFORMATEXTENSIBLE = unsafe {
(supported_format as *const _ as *const WAVEFORMATEXTENSIBLE).read()
};
WaveFormat {
wave_fmt: temp_fmt_ext,
}
} else {
debug!("got the supported format as a WAVEFORMATEX, converting..");
WaveFormat::from_waveformatex(temp_fmt)?
};
Some(new_fmt)
}
}
};
Ok(supported)
}
pub fn get_periods(&self) -> WasapiRes<(i64, i64)> {
let mut def_time = 0;
let mut min_time = 0;
unsafe { self.client.GetDevicePeriod(&mut def_time, &mut min_time)? };
trace!("default period {}, min period {}", def_time, min_time);
Ok((def_time, min_time))
}
pub fn initialize_client(
&mut self,
wavefmt: &WaveFormat,
period: i64,
direction: &Direction,
sharemode: &ShareMode,
convert: bool,
) -> WasapiRes<()> {
let mut streamflags = match (&self.direction, direction, sharemode) {
(Direction::Render, Direction::Capture, ShareMode::Shared) => {
AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_LOOPBACK
}
(Direction::Render, Direction::Capture, ShareMode::Exclusive) => {
return Err(WasapiError::new("Cant use Loopback with exclusive mode").into());
}
(Direction::Capture, Direction::Render, _) => {
return Err(WasapiError::new("Cant render to a capture device").into());
}
_ => AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
};
if convert {
streamflags |=
AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
}
let mode = match sharemode {
ShareMode::Exclusive => AUDCLNT_SHAREMODE_EXCLUSIVE,
ShareMode::Shared => AUDCLNT_SHAREMODE_SHARED,
};
self.sharemode = Some(sharemode.clone());
unsafe {
self.client.Initialize(
mode,
streamflags,
period,
period,
wavefmt.as_waveformatex_ptr(),
std::ptr::null(),
)?;
}
Ok(())
}
pub fn set_get_eventhandle(&self) -> WasapiRes<Handle> {
let h_event = unsafe { CreateEventA(std::ptr::null_mut(), false, false, PSTR::default()) };
unsafe { self.client.SetEventHandle(h_event)? };
Ok(Handle { handle: h_event })
}
pub fn get_bufferframecount(&self) -> WasapiRes<u32> {
let buffer_frame_count = unsafe { self.client.GetBufferSize()? };
trace!("buffer_frame_count {}", buffer_frame_count);
Ok(buffer_frame_count)
}
pub fn get_current_padding(&self) -> WasapiRes<u32> {
let padding_count = unsafe { self.client.GetCurrentPadding()? };
trace!("padding_count {}", padding_count);
Ok(padding_count)
}
pub fn get_available_space_in_frames(&self) -> WasapiRes<u32> {
let frames = match self.sharemode {
Some(ShareMode::Exclusive) => {
let buffer_frame_count = unsafe { self.client.GetBufferSize()? };
trace!("buffer_frame_count {}", buffer_frame_count);
buffer_frame_count
}
Some(ShareMode::Shared) => {
let padding_count = unsafe { self.client.GetCurrentPadding()? };
let buffer_frame_count = unsafe { self.client.GetBufferSize()? };
buffer_frame_count - padding_count
}
_ => return Err(WasapiError::new("Client has not been initialized").into()),
};
Ok(frames)
}
pub fn start_stream(&self) -> WasapiRes<()> {
unsafe { self.client.Start()? };
Ok(())
}
pub fn stop_stream(&self) -> WasapiRes<()> {
unsafe { self.client.Stop()? };
Ok(())
}
pub fn reset_stream(&self) -> WasapiRes<()> {
unsafe { self.client.Reset()? };
Ok(())
}
pub fn get_audiorenderclient(&self) -> WasapiRes<AudioRenderClient> {
let mut renderclient_ptr = ptr::null_mut();
unsafe {
self.client
.GetService(&IAudioRenderClient::IID, &mut renderclient_ptr)?
};
if renderclient_ptr.is_null() {
return Err(WasapiError::new("Failed getting IAudioCaptureClient").into());
}
let client = unsafe { mem::transmute(renderclient_ptr) };
Ok(AudioRenderClient { client })
}
pub fn get_audiocaptureclient(&self) -> WasapiRes<AudioCaptureClient> {
let mut renderclient_ptr = ptr::null_mut();
unsafe {
self.client
.GetService(&IAudioCaptureClient::IID, &mut renderclient_ptr)?
};
if renderclient_ptr.is_null() {
return Err(WasapiError::new("Failed getting IAudioCaptureClient").into());
}
let client = unsafe { mem::transmute(renderclient_ptr) };
Ok(AudioCaptureClient {
client,
sharemode: self.sharemode.clone(),
})
}
pub fn get_audiosessioncontrol(&self) -> WasapiRes<AudioSessionControl> {
let mut sessioncontrol_ptr = ptr::null_mut();
unsafe {
self.client
.GetService(&IAudioSessionControl::IID, &mut sessioncontrol_ptr)?
};
if sessioncontrol_ptr.is_null() {
return Err(WasapiError::new("Failed getting IAudioSessionControl").into());
}
let control = unsafe { mem::transmute(sessioncontrol_ptr) };
Ok(AudioSessionControl { control })
}
}
pub struct AudioSessionControl {
control: IAudioSessionControl,
}
#[derive(Debug)]
pub enum SessionState {
Active,
Inactive,
Expired,
}
impl AudioSessionControl {
pub fn get_state(&self) -> WasapiRes<SessionState> {
let state = unsafe { self.control.GetState()? };
#[allow(non_upper_case_globals)]
let sessionstate = match state {
AudioSessionStateActive => SessionState::Active,
AudioSessionStateInactive => SessionState::Inactive,
AudioSessionStateExpired => SessionState::Expired,
_ => {
return Err(WasapiError::new("Got an illegal state").into());
}
};
Ok(sessionstate)
}
pub fn register_session_notification(&self, callbacks: Weak<EventCallbacks>) -> WasapiRes<()> {
let events: IAudioSessionEvents = AudioSessionEvents::new(callbacks).into();
match unsafe { self.control.RegisterAudioSessionNotification(events) } {
Ok(()) => Ok(()),
Err(err) => {
Err(WasapiError::new(&format!("Failed to register notifications, {}", err)).into())
}
}
}
}
pub struct AudioRenderClient {
client: IAudioRenderClient,
}
impl AudioRenderClient {
pub fn write_to_device(
&self,
nbr_frames: usize,
byte_per_frame: usize,
data: &[u8],
) -> WasapiRes<()> {
let nbr_bytes = nbr_frames * byte_per_frame;
if nbr_bytes != data.len() {
return Err(WasapiError::new(
format!(
"Wrong length of data, got {}, expected {}",
data.len(),
nbr_bytes
)
.as_str(),
)
.into());
}
let bufferptr = unsafe { self.client.GetBuffer(nbr_frames as u32)? };
let bufferslice = unsafe { slice::from_raw_parts_mut(bufferptr, nbr_bytes) };
bufferslice.copy_from_slice(data);
unsafe { self.client.ReleaseBuffer(nbr_frames as u32, 0)? };
trace!("wrote {} frames", nbr_frames);
Ok(())
}
pub fn write_to_device_from_deque(
&self,
nbr_frames: usize,
byte_per_frame: usize,
data: &mut VecDeque<u8>,
) -> WasapiRes<()> {
let nbr_bytes = nbr_frames * byte_per_frame;
if nbr_bytes > data.len() {
return Err(WasapiError::new(
format!("To little data, got {}, need {}", data.len(), nbr_bytes).as_str(),
)
.into());
}
let bufferptr = unsafe { self.client.GetBuffer(nbr_frames as u32)? };
let bufferslice = unsafe { slice::from_raw_parts_mut(bufferptr, nbr_bytes) };
for element in bufferslice.iter_mut() {
*element = data.pop_front().unwrap();
}
unsafe { self.client.ReleaseBuffer(nbr_frames as u32, 0)? };
trace!("wrote {} frames", nbr_frames);
Ok(())
}
}
pub struct AudioCaptureClient {
client: IAudioCaptureClient,
sharemode: Option<ShareMode>,
}
impl AudioCaptureClient {
pub fn get_next_nbr_frames(&self) -> WasapiRes<Option<u32>> {
if let Some(ShareMode::Exclusive) = self.sharemode {
return Ok(None);
}
let nbr_frames = unsafe { self.client.GetNextPacketSize()? };
Ok(Some(nbr_frames))
}
pub fn read_from_device(&self, bytes_per_frame: usize, data: &mut [u8]) -> WasapiRes<u32> {
let data_len_in_frames = data.len() / bytes_per_frame;
let mut buffer = mem::MaybeUninit::uninit();
let mut nbr_frames_returned = 0;
unsafe {
self.client.GetBuffer(
buffer.as_mut_ptr(),
&mut nbr_frames_returned,
&mut 0,
ptr::null_mut(),
ptr::null_mut(),
)?
};
if nbr_frames_returned == 0 {
unsafe { self.client.ReleaseBuffer(nbr_frames_returned)? };
return Ok(0);
}
if data_len_in_frames < nbr_frames_returned as usize {
unsafe { self.client.ReleaseBuffer(nbr_frames_returned)? };
return Err(WasapiError::new(
format!(
"Wrong length of data, got {} frames, expected at least {} frames",
data_len_in_frames, nbr_frames_returned
)
.as_str(),
)
.into());
}
let len_in_bytes = nbr_frames_returned as usize * bytes_per_frame;
let bufferptr = unsafe { buffer.assume_init() };
let bufferslice = unsafe { slice::from_raw_parts(bufferptr, len_in_bytes) };
data[..len_in_bytes].copy_from_slice(bufferslice);
unsafe { self.client.ReleaseBuffer(nbr_frames_returned)? };
trace!("read {} frames", nbr_frames_returned);
Ok(nbr_frames_returned)
}
pub fn read_from_device_to_deque(
&self,
bytes_per_frame: usize,
data: &mut VecDeque<u8>,
) -> WasapiRes<()> {
let mut buffer = mem::MaybeUninit::uninit();
let mut nbr_frames_returned = 0;
unsafe {
self.client.GetBuffer(
buffer.as_mut_ptr(),
&mut nbr_frames_returned,
&mut 0,
ptr::null_mut(),
ptr::null_mut(),
)?
};
let len_in_bytes = nbr_frames_returned as usize * bytes_per_frame;
let bufferptr = unsafe { buffer.assume_init() };
let bufferslice = unsafe { slice::from_raw_parts(bufferptr, len_in_bytes) };
for element in bufferslice.iter() {
data.push_back(*element);
}
unsafe { self.client.ReleaseBuffer(nbr_frames_returned)? };
trace!("read {} frames", nbr_frames_returned);
Ok(())
}
}
pub struct Handle {
handle: HANDLE,
}
impl Handle {
pub fn wait_for_event(&self, timeout_ms: u32) -> WasapiRes<()> {
let retval = unsafe { WaitForSingleObject(self.handle, timeout_ms) };
if retval != WAIT_OBJECT_0 {
return Err(WasapiError::new("Wait timed out").into());
}
Ok(())
}
}