cpvc 0.6.0

A simple crate + wrapper for controlling system audio cross platform
Documentation
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
// #[cfg(target_os="macos")]
// use objc2_core_audio::{
//         AudioObjectGetPropertyData, AudioObjectSetPropertyData, AudioObjectGetPropertyDataSize,
//         AudioObjectID, AudioObjectPropertyAddress,
//         kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectSystemObject,
//         kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain,
//         kAudioDevicePropertyScopeOutput, kAudioDevicePropertyMute,
//         kAudioDevicePropertyVolumeScalar, kAudioDevicePropertyDeviceNameCFString,
//         kAudioDevicePropertyStreamFormat, kAudioObjectPropertyScopeOutput,
//         kAudioHardwarePropertyDevices, kAudioDevicePropertyStreams,
//         kAudioObjectPropertyScopeInput,
// };
// #[cfg(target_os="windows")]
// use windows::Win32::Media::Audio::IMMDevice;
// use crate::debug_eprintln;

// #[derive(Debug, Clone)]
// enum DeviceId {
//     MacOS(u32),
//     Windows(String),
//     PulseAudio
// }

// #[derive(Debug)]
// pub struct AudioDevice {
//     pub device_name: String,
//     pub hw_name: String,
//     pub device_id: DeviceId,
//     channels: u32,
//     vol_ctl: VolControl,
// }

// impl AudioDevice {
//     pub fn get_default_device() -> Result<AudioDevice, Error> {

//         #[cfg(target_os="macos")] {
//             use crate::coreaudio::{CoreAudio};

//             let captured_device_id = CoreAudio::capture_output_device_id();
//             if let Ok(device_id) = captured_device_id {
//                 let mut device_name = String::new();
//                 let channels;
//                 let name = CoreAudio::get_device_name(captured_device_id.unwrap());
//                 if name.is_ok() {
//                     device_name.push_str(&name.unwrap());
//                 }
                
//                 let device_stats = get_output_device_details(device_id);
//                 if let Ok(stats) = device_stats {
//                     channels = stats.mChannelsPerFrame;
//                 } else {
//                     channels = 0;
//                 }
//                 return Ok(AudioDevice {
//                     device_name: device_name.clone(),
//                     device_id: DeviceId::MacOS(device_id),
//                     hw_name: device_name,
//                     channels,
//                     vol_ctl: VolControl::new(DeviceId::MacOS(device_id), channels)
//                 });
//             } else {
//                 return Err(Error::DeviceCaptureFailed);
//             }
//         }

//         Err(Error::UnsupportedOS)
//     }

//     pub fn get_device_from_id(device_id: DeviceId) -> Result<AudioDevice, Error> {
//         #[cfg(target_os="macos")] {
//             use crate::coreaudio::{get_device_name, get_output_device_details};
//             let device_id = match device_id {
//                 DeviceId::MacOS(id_num) => {
//                     id_num
//                 }
//                 _ => {
//                     return Err(Error::DeviceCaptureFailed);
//                 }
//             };
//             let mut device_name = String::new();
//             let channels;
//             let name = get_device_name(device_id);
//             if name.is_ok() {
//                 device_name.push_str(&name.unwrap());
//             } else {
//                 return Err(Error::DeviceNotFound);
//             }
            
//             let device_stats = get_output_device_details(device_id);
//             if let Ok(stats) = device_stats {
//                 channels = stats.mChannelsPerFrame;
//             } else {
//                 return Err(Error::DeviceDetailsCaptureFailed);
//             }
//             return Ok(AudioDevice {
//                 device_name: device_name.clone(),
//                 device_id: DeviceId::MacOS(device_id),
//                 hw_name: device_name,
//                 channels,
//                 vol_ctl: VolControl::new(DeviceId::MacOS(device_id), channels)
//             });

//         }
//         #[cfg(target_os="windows")] {
//             let device_id = match device_id {
//                 DeviceId::Windows(pwstr) => {
//                     pwstr
//                 },
//                 _ => {
//                     return Err(Error::DeviceCaptureFailed);
//                 }
//             };
//             let name;
//             let hw_name;
//             let channels;


//             unsafe {
//                 use windows::{core::PWSTR, Win32::{Media::Audio::Endpoints::IAudioEndpointVolume, System::Com::{CLSCTX_ALL, STGM_READ}}};

//                 let mut id = format!("{}\0", device_id).encode_utf16().collect::<Vec<u16>>();
//                 let pwstr = PWSTR(id.as_mut_ptr());

//                 let enumerator = crate::wasapi::get_enumerator();
//                 let device = match enumerator.GetDevice(pwstr) {
//                     Ok(device) => {
//                         device
//                     },
//                     Err(_) => {
//                         return Err(Error::DeviceCaptureFailed);
//                     },
//                 };
//                 let volume_controls = device.Activate::<IAudioEndpointVolume>(CLSCTX_ALL, None).unwrap();
//                 channels = volume_controls.GetChannelCount().unwrap();
//                 let result = device.OpenPropertyStore(STGM_READ);
//                 match result {
//                     Ok(properties) => {
//                         use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;

//                         name = properties.GetValue(&PKEY_Device_FriendlyName).unwrap().to_string();
//                         hw_name = name.clone()
//                         // dbg!(properties.GetValue(&PKEY_Device_FriendlyName));
//                     },
//                     Err(error) => {
//                         panic!("{}", error);
//                     }
//                 }
//             }
            
//             return Ok(AudioDevice{
//                 device_name: name,
//                 hw_name,
//                 device_id: DeviceId::Windows(device_id.clone()),
//                 channels,
//                 vol_ctl: VolControl::new(DeviceId::Windows(device_id.clone()), channels),
//             })

//         }
//         Err(Error::UnsupportedOS)
//     }

//     pub fn get_device_from_name(name: String) -> Result<AudioDevice, Error> {
//         #[cfg(target_os="macos")] {
//             use crate::{coreaudio::get_device_name, coreaudio::get_output_device_details, scan::scan_devices};

//             if let Some(device_id) = scan_devices().remove(&name) {
//                 let mut device_name = String::new();
//                 let channels;
//                 let name = get_device_name(device_id);
//                 if name.is_ok() {
//                     device_name.push_str(&name.unwrap());
//                 } else {
//                     return Err(Error::DeviceDetailsCaptureFailed);
//                 }
                
//                 let device_stats = get_output_device_details(device_id);
//                 if let Ok(stats) = device_stats {
//                     channels = stats.mChannelsPerFrame;
//                 } else {
//                     return Err(Error::DeviceDetailsCaptureFailed);
//                 }
//                 return Ok(AudioDevice {
//                     device_name: device_name.clone(),
//                     device_id: DeviceId::MacOS(device_id),
//                     hw_name: device_name,
//                     channels,
//                     vol_ctl: VolControl::new(DeviceId::MacOS(device_id), channels)
//                 });
//             }
//             return Err(Error::DeviceNotFound);        
//         }
//         Err(Error::UnsupportedOS)
//     }

//     pub fn default_volume_control(&self) -> VolControl {
//         self.vol_ctl.clone()
//     }

// }

// #[derive(Debug, Clone)]
// pub struct VolControl {
//     hw_id: DeviceId,
//     channels: u32,

// }

// impl VolControl {
//     fn new(hw_id: DeviceId, channels: u32) -> VolControl {
//         VolControl { hw_id, channels }
//     }

//     pub fn set_vol(&self, val: f32) -> bool {
//         let mut success = Some(false);
//         #[cfg(target_os="macos")]{
//             use std::ptr::{null, NonNull};
//             let hw_id = match self.hw_id {
//                 DeviceId::MacOS(id) => {
//                     id
//                 }
//                 _ => {
//                     return false;
//                 }
//             };

//             let channel_count = self.channels;

//             let volume_data_size = size_of::<f32>() as u32;

//             for channel in 0..=channel_count {
//                 debug_eprintln(&format!("channel {}", channel));
//                 let volume_property_address_channel = AudioObjectPropertyAddress {
//                     mSelector: kAudioDevicePropertyVolumeScalar,
//                     mScope: kAudioDevicePropertyScopeOutput,
//                     mElement: channel,
//                 };

//                 unsafe {
//                     let change_volume_status = AudioObjectSetPropertyData(hw_id,
//                         NonNull::new_unchecked(&volume_property_address_channel as *const _ as *mut _),
//                         0, null(),
//                         volume_data_size, NonNull::new_unchecked( &val as *const _ as *mut _));
//                     if change_volume_status != 0 {
//                         debug_eprintln(&format!("Failed to change volume on channel {} (This may be normal behavior)", if channel == 0 {"0 (Master Channel)".to_string()} else {channel.to_string()}));
//                     }
//                 }
//             }

//             let mute_property_address = AudioObjectPropertyAddress {
//                 mSelector: kAudioDevicePropertyMute,
//                 mScope: kAudioDevicePropertyScopeOutput,
//                 mElement: kAudioObjectPropertyElementMain
//             };

//             let mut sync_status = true;
//             // Mute then unmute hardware device so software sound level will sync with hardware sound level
//             for mute in (0..=1 as u32).rev() {
//                 let mute_data_size = size_of::<u32>() as u32;
//                 unsafe {
//                     let mute_status = AudioObjectSetPropertyData(hw_id,
//                         NonNull::new_unchecked(&mute_property_address as *const _ as *mut _),
//                         0, null(),
//                         mute_data_size, NonNull::new_unchecked(&mute as *const _ as *mut _));
//                     if mute_status != 0 {
//                         sync_status = false;
//                     }
//                 }
//             }
//             if success.is_none() {
//                 success.replace(sync_status);
//             }
//         }
//         success.unwrap_or(false)
//     }
//     pub fn get_vol(&self) -> f32 {
//         let mut vol = 0.0;
//         #[cfg(target_os="macos")] {
//             use std::ptr::{NonNull, null};

//             let hw_id = match self.hw_id {
//                 DeviceId::MacOS(id) => {
//                     id
//                 }
//                 _ => {
//                     return 0.0;
//                 }
//             };


//             let mute_property_address = AudioObjectPropertyAddress {
//                     mSelector: kAudioDevicePropertyMute,
//                     mScope: kAudioDevicePropertyScopeOutput,
//                     mElement: kAudioObjectPropertyElementMain
//                 };

//             // Check if Muted
//             let channel_count = self.channels;
//             let mut total_volume: f32 = 0.0;
//             let mut total_channels = 0;
//             let mut channel_volume: f32 = 0.0;
//             let mut volume_data_size = size_of::<f32>() as u32;

//             for channel in 0..=channel_count {
//                 let volume_property_address_channel = AudioObjectPropertyAddress {
//                     mSelector: kAudioDevicePropertyVolumeScalar,
//                     mScope: kAudioDevicePropertyScopeOutput,
//                     mElement: channel,
//                 };

//                 unsafe {


//                     let get_volume_data_size_status = AudioObjectGetPropertyDataSize(
//                             hw_id,
//                             NonNull::new_unchecked(&volume_property_address_channel as *const _ as *mut _),
//                             0,
//                             null(),
//                             NonNull::new_unchecked(&mut volume_data_size as *const _ as *mut _),
//                         );
//                     if get_volume_data_size_status == 0 {
//                         let get_volume_status = AudioObjectGetPropertyData(
//                             hw_id,
//                             NonNull::new_unchecked(&volume_property_address_channel as *const _ as *mut _),
//                             0,
//                             null(),
//                             NonNull::new_unchecked(&volume_data_size as *const _ as *mut _),
//                             NonNull::new_unchecked(&mut channel_volume as *mut _ as *mut _));

//                         if get_volume_status != 0 {
//                             debug_eprintln(&format!("Failed to get volume on channel {} (This may be normal behavior)", if channel == 0 {"0 (Master Channel)".to_string()} else {channel.to_string()}));
//                         } else {
//                             total_channels += 1;
//                             total_volume += channel_volume;
//                         }
//                     } else {
//                         debug_eprintln(&format!("Failed to get volume data size on channel {} (This may be normal behavior)", if channel == 0 {"0 (Master Channel)".to_string()} else {channel.to_string()}));
//                     }
//                 }
//             }
//             if total_channels > 0 {
//                 total_volume *= 100.0;
//                 total_volume = total_volume.round();
//                 vol = (total_volume as u32 / total_channels) as f32;
//             }
//         }
//         vol.into()
//     }
//     pub fn set_mute(&self, mute: bool) -> bool {
//         let mut status = false;
//         #[cfg(target_os="macos")] {
//             let hw_id = match self.hw_id {
//                 DeviceId::MacOS(id) => {
//                     id
//                 }
//                 _ => {
//                     return false;
//                 }
//             };


//             let mute_property_address = AudioObjectPropertyAddress {
//                         mSelector: kAudioDevicePropertyMute,
//                         mScope: kAudioDevicePropertyScopeOutput,
//                         mElement: kAudioObjectPropertyElementMain
//                     };
//             let mute_data_size = size_of::<u32>() as u32;
//             let mute = match mute {
//                 true => {
//                     1
//                 },
//                 false => {
//                     0
//                 }
//             };
//             unsafe {
//                 use std::ptr::{NonNull, null};
//                 let mute_status = AudioObjectSetPropertyData(hw_id,
//                     NonNull::new_unchecked(&mute_property_address as *const _ as *mut _),
//                     0, null(),
//                     mute_data_size, NonNull::new_unchecked(&mute as *const _ as *mut _));
//                 if mute_status != 0 {
//                     status = false;
//                 }
//             }
//         }
//         status
//     }

//     pub fn is_mute(&self) -> Result<bool, VolumeError> {
//         let mut mute:u32 = 0;
//         let hw_id = match self.hw_id {
//             DeviceId::MacOS(id) => {
//                 id
//             }
//             _ => {
//                 return Err(VolumeError::MuteStatusCaptureFailed);
//             }
//         };

//         #[cfg(target_os="macos")] {
//             let mute_property_address = AudioObjectPropertyAddress {
//                         mSelector: kAudioDevicePropertyMute,
//                         mScope: kAudioDevicePropertyScopeOutput,
//                         mElement: kAudioObjectPropertyElementMain
//                     };
//             let mut mute_data_size = size_of::<u32>() as u32;

//             unsafe {
//                 use std::ptr::{NonNull, null};
//                 let mute_status = AudioObjectGetPropertyData(hw_id,
//                     NonNull::new_unchecked(&mute_property_address as *const _ as *mut _),
//                     0, null(),
//                     NonNull::new_unchecked(&mut mute_data_size as *mut _), 
//                     NonNull::new_unchecked(&mut mute as *mut _ as *mut _));
//                 if mute_status != 0 {
//                     return Err(VolumeError::MuteStatusCaptureFailed);
//                 }
//             }
//         }
//         Ok(match mute {
//             1 => {
//                 true
//             }
//             _ => {
//                 false
//             }
//         })
//     }

//     #[cfg(target_os="windows")] 
//     fn get_hw_device(&self) -> Result<IMMDevice, Error> {
//         let device_id = match self.hw_id.clone() {
//             DeviceId::Windows(pwstr) => {
//                 pwstr
//             },
//             _ => {
//                 return Err(Error::DeviceCaptureFailed);
//             }
//         };

//         unsafe {
//             use windows::core::PWSTR;

//             use crate::wasapi::get_enumerator;

//             let mut id = format!("{}\0", device_id).encode_utf16().collect::<Vec<u16>>();
//             let pwstr = PWSTR(id.as_mut_ptr());

//             let enumerator = get_enumerator();
//             match enumerator.GetDevice(pwstr) {
//                 Ok(device) => {
//                     Ok(device)
//                 },
//                 Err(_) => {
//                     Err(Error::DeviceCaptureFailed)
//                 },
//             }
//         }
//     }
// }

// #[derive(Debug)]
// pub enum Error {
//     UnsupportedOS,
//     DeviceCaptureFailed,
//     DeviceDetailsCaptureFailed,
//     DeviceNotFound,
// }

// #[derive(Debug)]
// pub enum VolumeError {
//     MuteStatusCaptureFailed,
// }

// #[cfg(test)]
// mod tests {
//     use crate::device::AudioDevice;

//     #[test]
//     fn get_audio_device() {
//         dbg!(AudioDevice::get_default_device());
//         dbg!(AudioDevice::get_device_from_name("External Headphones".to_string()));
//         #[cfg(target_os="windows")] {
//             use crate::device::DeviceId;
            
//         }
//         assert!(false);
//     }

//     #[test]
//     fn get_audio_device_volume() {
//         let device = AudioDevice::get_default_device().unwrap();
//         let mut vol_ctl = device.default_volume_control();
//         dbg!(vol_ctl.get_vol());
//         dbg!(device);
//         assert!(false);
//     }

//     #[test]
//     fn check_muted() {
//         let device = AudioDevice::get_default_device().unwrap();
//         let mut vol_ctl = device.default_volume_control();
//         dbg!(vol_ctl.is_mute());
//         dbg!(vol_ctl.set_mute(true));
//         dbg!(device);
//         assert!(false);
//     }
// }