volumecontrol-windows 0.1.2

Windows (WASAPI) volume control bindings for volumecontrol
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
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
//! Windows WASAPI volume control backend.
//!
//! This crate exposes an [`AudioDevice`] type that implements
//! [`volumecontrol_core::AudioDevice`].  It exists primarily as an
//! implementation detail of the
//! [`volumecontrol`](https://crates.io/crates/volumecontrol) crate, which
//! selects the correct backend automatically.  If cross-platform support is not
//! a concern you may depend on this crate directly.
//!
//! When the `wasapi` feature is **not** enabled every method returns
//! [`AudioError::Unsupported`], which allows the crate to compile on any
//! platform without the Windows SDK.
//!
//! # Feature flags
//!
//! | Feature  | Description                                    | Requires              |
//! |----------|------------------------------------------------|-----------------------|
//! | `wasapi` | Enable the real WASAPI backend via `windows`    | Windows target only  |
//!
//! # Example
//!
//! ```no_run
//! use volumecontrol_windows::AudioDevice;
//! use volumecontrol_core::AudioDevice as _;
//!
//! fn main() -> Result<(), volumecontrol_core::AudioError> {
//!     let device = AudioDevice::from_default()?;
//!     println!("{device}");  // e.g. "Speakers ({0.0.0.00000000}.{…})"
//!     println!("Current volume: {}%", device.get_vol()?);
//!     Ok(())
//! }
//! ```

#![deny(missing_docs)]

mod internal;

use std::fmt;

use volumecontrol_core::{AudioDevice as AudioDeviceTrait, AudioError, DeviceInfo};

#[cfg(feature = "wasapi")]
use std::sync::Mutex;

#[cfg(feature = "wasapi")]
use windows::Win32::Media::Audio::Endpoints::IAudioEndpointVolume;

/// Represents a WASAPI audio output device (Windows).
///
/// # Feature flags
///
/// Real WASAPI integration requires the `wasapi` feature and must be built
/// for a Windows target.  Without the feature every method returns
/// [`AudioError::Unsupported`].
///
/// # Thread safety
///
/// `AudioDevice` is [`Send`] because all COM interface pointers in the
/// `windows` crate are `Send + Sync`: `AddRef` / `Release` are guaranteed to
/// be thread-safe by the COM specification, and `windows-rs` marks every COM
/// interface accordingly.  COM is initialised with `COINIT_MULTITHREADED` (the
/// multi-threaded apartment), so the cached endpoint can be used from any
/// thread in the process without cross-apartment marshalling.
pub struct AudioDevice {
    /// WASAPI endpoint identifier (GUID string).
    id: String,
    /// Friendly device name.
    name: String,
    /// Cached [`IAudioEndpointVolume`] interface.
    ///
    /// Wrapped in a [`Mutex`] to allow transparent re-initialisation on
    /// `AUDCLNT_E_DEVICE_INVALIDATED` errors using only a shared reference
    /// (`&self`).  Only present when the `wasapi` feature is enabled.
    #[cfg(feature = "wasapi")]
    endpoint: Mutex<IAudioEndpointVolume>,
}

impl fmt::Debug for AudioDevice {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The `endpoint` field (a COM interface pointer) is intentionally
        // omitted: it contains no useful human-readable information and
        // exposing raw COM interface addresses in debug output would be
        // confusing.  `finish_non_exhaustive` signals that the struct has
        // additional fields.
        f.debug_struct("AudioDevice")
            .field("id", &self.id)
            .field("name", &self.name)
            .finish_non_exhaustive()
    }
}

impl fmt::Display for AudioDevice {
    /// Formats the device as `"name (id)"`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({})", self.name, self.id)
    }
}

#[cfg(feature = "wasapi")]
impl AudioDevice {
    /// Calls `op` with the cached [`IAudioEndpointVolume`], retrying once
    /// after an automatic cache refresh if the endpoint signals
    /// [`EndpointError::DeviceInvalidated`] (`AUDCLNT_E_DEVICE_INVALIDATED`).
    ///
    /// A [`ComGuard`] is created for the duration of the call to ensure COM is
    /// initialised on the calling thread.
    ///
    /// # Errors
    ///
    /// - On `DeviceInvalidated` the cache is refreshed via
    ///   [`try_refresh_endpoint`]; if the refresh itself fails, that error is
    ///   returned.  If the retry still returns `DeviceInvalidated` (device
    ///   disappeared between calls) `AudioError::DeviceNotFound` is returned.
    /// - On any other [`EndpointError::Error`] the wrapped [`AudioError`] is
    ///   propagated unchanged.
    /// - Returns [`AudioError::EndpointLockPoisoned`] if the endpoint mutex is
    ///   poisoned (a thread panicked while holding the lock).
    ///
    /// [`ComGuard`]: internal::wasapi::ComGuard
    /// [`try_refresh_endpoint`]: AudioDevice::try_refresh_endpoint
    fn with_endpoint<T>(
        &self,
        op: impl Fn(&IAudioEndpointVolume) -> Result<T, internal::wasapi::EndpointError>,
    ) -> Result<T, AudioError> {
        let _com = internal::wasapi::ComGuard::new()?;
        let guard = self
            .endpoint
            .lock()
            .map_err(|_| AudioError::EndpointLockPoisoned)?;
        match op(&guard) {
            Ok(v) => Ok(v),
            Err(internal::wasapi::EndpointError::Error(e)) => Err(e),
            Err(internal::wasapi::EndpointError::DeviceInvalidated) => {
                // Release the lock before refreshing so `try_refresh_endpoint`
                // can also acquire it.
                drop(guard);
                // AUDCLNT_E_DEVICE_INVALIDATED — refresh cache and retry once.
                self.try_refresh_endpoint()?;
                let guard = self
                    .endpoint
                    .lock()
                    .map_err(|_| AudioError::EndpointLockPoisoned)?;
                match op(&guard) {
                    Ok(v) => Ok(v),
                    Err(internal::wasapi::EndpointError::Error(e)) => Err(e),
                    // Still invalidated after a fresh endpoint: device is gone.
                    Err(internal::wasapi::EndpointError::DeviceInvalidated) => {
                        Err(AudioError::DeviceNotFound)
                    }
                }
            }
        }
    }

    /// Re-resolves the device by its cached ID and replaces the stored
    /// [`IAudioEndpointVolume`] with a freshly activated one.
    ///
    /// Called by [`with_endpoint`] when an endpoint operation returns
    /// [`EndpointError::DeviceInvalidated`]
    /// (`AUDCLNT_E_DEVICE_INVALIDATED`).
    /// The caller is responsible for ensuring COM is already initialised on the
    /// current thread (i.e. a [`ComGuard`] is alive in the calling scope).
    ///
    /// # Errors
    ///
    /// Returns [`AudioError::DeviceNotFound`] if the device no longer exists,
    /// [`AudioError::InitializationFailed`] on other COM failures, or
    /// [`AudioError::EndpointLockPoisoned`] if the endpoint mutex is poisoned.
    ///
    /// [`with_endpoint`]: AudioDevice::with_endpoint
    /// [`ComGuard`]: internal::wasapi::ComGuard
    fn try_refresh_endpoint(&self) -> Result<(), AudioError> {
        let enumerator = internal::wasapi::create_enumerator()?;
        let device = internal::wasapi::get_device_by_id(&enumerator, &self.id)?;
        let new_endpoint = internal::wasapi::endpoint_volume(&device)?;
        *self
            .endpoint
            .lock()
            .map_err(|_| AudioError::EndpointLockPoisoned)? = new_endpoint;
        Ok(())
    }
}

impl AudioDeviceTrait for AudioDevice {
    /// Returns the system default audio render device.
    ///
    /// # Errors
    ///
    /// Returns [`AudioError::InitializationFailed`] if COM cannot be
    /// initialised or if the default device cannot be resolved.
    /// Returns [`AudioError::Unsupported`] when the `wasapi` feature is
    /// not enabled.
    fn from_default() -> Result<Self, AudioError> {
        #[cfg(feature = "wasapi")]
        {
            let _com = internal::wasapi::ComGuard::new()?;
            let enumerator = internal::wasapi::create_enumerator()?;
            let device = internal::wasapi::get_default_device(&enumerator)?;
            let id = internal::wasapi::device_id(&device)?;
            let name = internal::wasapi::device_name(&device)?;
            let endpoint = internal::wasapi::endpoint_volume(&device)?;
            Ok(Self {
                id,
                name,
                endpoint: Mutex::new(endpoint),
            })
        }
        #[cfg(not(feature = "wasapi"))]
        Err(AudioError::Unsupported)
    }

    /// Returns the audio device identified by `id`.
    ///
    /// # Errors
    ///
    /// Returns [`AudioError::DeviceNotFound`] if no device with the given
    /// identifier exists.
    /// Returns [`AudioError::InitializationFailed`] if COM cannot be
    /// initialised or another lookup failure occurs.
    /// Returns [`AudioError::Unsupported`] when the `wasapi` feature is
    /// not enabled.
    fn from_id(id: &str) -> Result<Self, AudioError> {
        #[cfg(feature = "wasapi")]
        {
            let _com = internal::wasapi::ComGuard::new()?;
            let enumerator = internal::wasapi::create_enumerator()?;
            let device = internal::wasapi::get_device_by_id(&enumerator, id)?;
            let resolved_id = internal::wasapi::device_id(&device)?;
            let name = internal::wasapi::device_name(&device)?;
            let endpoint = internal::wasapi::endpoint_volume(&device)?;
            Ok(Self {
                id: resolved_id,
                name,
                endpoint: Mutex::new(endpoint),
            })
        }
        #[cfg(not(feature = "wasapi"))]
        {
            let _ = id;
            Err(AudioError::Unsupported)
        }
    }

    /// Returns the first audio device whose name contains `name`
    /// (case-insensitive substring match).
    ///
    /// # Errors
    ///
    /// Returns [`AudioError::DeviceNotFound`] if no matching device is found.
    /// Returns [`AudioError::InitializationFailed`] if COM cannot be
    /// initialised or another lookup failure occurs.
    /// Returns [`AudioError::Unsupported`] when the `wasapi` feature is
    /// not enabled.
    fn from_name(name: &str) -> Result<Self, AudioError> {
        #[cfg(feature = "wasapi")]
        {
            let _com = internal::wasapi::ComGuard::new()?;
            let enumerator = internal::wasapi::create_enumerator()?;
            let devices = internal::wasapi::list_devices(&enumerator)?;

            let needle = name.to_lowercase();
            let info = devices
                .into_iter()
                .find(|d| d.name.to_lowercase().contains(&needle))
                .ok_or(AudioError::DeviceNotFound)?;

            // Re-resolve the IMMDevice from its ID to activate the endpoint.
            let device = internal::wasapi::get_device_by_id(&enumerator, &info.id)?;
            let endpoint = internal::wasapi::endpoint_volume(&device)?;

            Ok(Self {
                id: info.id,
                name: info.name,
                endpoint: Mutex::new(endpoint),
            })
        }
        #[cfg(not(feature = "wasapi"))]
        {
            let _ = name;
            Err(AudioError::Unsupported)
        }
    }

    /// Lists all available audio render devices.
    ///
    /// # Errors
    ///
    /// Returns [`AudioError::ListFailed`] if the device list cannot be
    /// retrieved.
    /// Returns [`AudioError::InitializationFailed`] if COM cannot be
    /// initialised.
    /// Returns [`AudioError::Unsupported`] when the `wasapi` feature is
    /// not enabled.
    fn list() -> Result<Vec<DeviceInfo>, AudioError> {
        #[cfg(feature = "wasapi")]
        {
            let _com = internal::wasapi::ComGuard::new()?;
            let enumerator = internal::wasapi::create_enumerator()?;
            internal::wasapi::list_devices(&enumerator)
        }
        #[cfg(not(feature = "wasapi"))]
        Err(AudioError::Unsupported)
    }

    /// Returns the current volume level in the range `0..=100`.
    ///
    /// # Errors
    ///
    /// Returns [`AudioError::GetVolumeFailed`] if the volume cannot be read.
    /// Returns [`AudioError::DeviceNotFound`] if this device no longer exists.
    /// Returns [`AudioError::Unsupported`] when the `wasapi` feature is
    /// not enabled.
    fn get_vol(&self) -> Result<u8, AudioError> {
        #[cfg(feature = "wasapi")]
        {
            self.with_endpoint(internal::wasapi::get_volume)
        }
        #[cfg(not(feature = "wasapi"))]
        Err(AudioError::Unsupported)
    }

    /// Sets the volume level.
    ///
    /// `vol` is clamped to `0..=100` before being applied.
    ///
    /// # Errors
    ///
    /// Returns [`AudioError::SetVolumeFailed`] if the volume cannot be set.
    /// Returns [`AudioError::DeviceNotFound`] if this device no longer exists.
    /// Returns [`AudioError::Unsupported`] when the `wasapi` feature is
    /// not enabled.
    fn set_vol(&self, vol: u8) -> Result<(), AudioError> {
        #[cfg(feature = "wasapi")]
        {
            self.with_endpoint(|ep| internal::wasapi::set_volume(ep, vol))
        }
        #[cfg(not(feature = "wasapi"))]
        {
            let _ = vol;
            Err(AudioError::Unsupported)
        }
    }

    /// Returns `true` if the device is currently muted.
    ///
    /// # Errors
    ///
    /// Returns [`AudioError::GetMuteFailed`] if the mute state cannot be read.
    /// Returns [`AudioError::DeviceNotFound`] if this device no longer exists.
    /// Returns [`AudioError::Unsupported`] when the `wasapi` feature is
    /// not enabled.
    fn is_mute(&self) -> Result<bool, AudioError> {
        #[cfg(feature = "wasapi")]
        {
            self.with_endpoint(internal::wasapi::get_mute)
        }
        #[cfg(not(feature = "wasapi"))]
        Err(AudioError::Unsupported)
    }

    /// Mutes or unmutes the device.
    ///
    /// # Errors
    ///
    /// Returns [`AudioError::SetMuteFailed`] if the mute state cannot be
    /// changed.
    /// Returns [`AudioError::DeviceNotFound`] if this device no longer exists.
    /// Returns [`AudioError::Unsupported`] when the `wasapi` feature is
    /// not enabled.
    fn set_mute(&self, muted: bool) -> Result<(), AudioError> {
        #[cfg(feature = "wasapi")]
        {
            self.with_endpoint(|ep| internal::wasapi::set_mute(ep, muted))
        }
        #[cfg(not(feature = "wasapi"))]
        {
            let _ = muted;
            Err(AudioError::Unsupported)
        }
    }

    fn id(&self) -> &str {
        &self.id
    }

    fn name(&self) -> &str {
        &self.name
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use volumecontrol_core::AudioDevice as AudioDeviceTrait;

    /// `Display` output must follow the `"name (id)"` format.
    ///
    /// The test is gated on `not(wasapi)` because constructing an
    /// [`AudioDevice`] directly without a valid COM endpoint is only safe when
    /// the `wasapi` feature is disabled (no `endpoint` field exists).
    #[test]
    #[cfg(not(feature = "wasapi"))]
    fn display_format_is_name_paren_id() {
        let device = AudioDevice {
            id: "{0.0.0.00000000}.{E9B0A576-1234-5678-ABCD-000000000000}".to_string(),
            name: "Speakers".to_string(),
        };
        assert_eq!(
            device.to_string(),
            "Speakers ({0.0.0.00000000}.{E9B0A576-1234-5678-ABCD-000000000000})"
        );
    }

    // ------------------------------------------------------------------
    // Stub-path tests — only compiled and run when `wasapi` is disabled.
    // ------------------------------------------------------------------

    #[test]
    #[cfg(not(feature = "wasapi"))]
    fn default_returns_unsupported_without_feature() {
        assert!(matches!(
            AudioDevice::from_default(),
            Err(AudioError::Unsupported)
        ));
    }

    #[test]
    #[cfg(not(feature = "wasapi"))]
    fn from_id_returns_unsupported_without_feature() {
        assert!(matches!(
            AudioDevice::from_id("test-id"),
            Err(AudioError::Unsupported)
        ));
    }

    #[test]
    #[cfg(not(feature = "wasapi"))]
    fn from_name_returns_unsupported_without_feature() {
        assert!(matches!(
            AudioDevice::from_name("test-name"),
            Err(AudioError::Unsupported)
        ));
    }

    #[test]
    #[cfg(not(feature = "wasapi"))]
    fn list_returns_unsupported_without_feature() {
        assert!(matches!(AudioDevice::list(), Err(AudioError::Unsupported)));
    }

    #[test]
    #[cfg(not(feature = "wasapi"))]
    fn get_vol_returns_unsupported_without_feature() {
        let device = AudioDevice {
            id: String::from("stub-id"),
            name: String::from("stub-name"),
        };
        assert!(matches!(device.get_vol(), Err(AudioError::Unsupported)));
    }

    #[test]
    #[cfg(not(feature = "wasapi"))]
    fn set_vol_returns_unsupported_without_feature() {
        let device = AudioDevice {
            id: String::from("stub-id"),
            name: String::from("stub-name"),
        };
        assert!(matches!(device.set_vol(50), Err(AudioError::Unsupported)));
    }

    #[test]
    #[cfg(not(feature = "wasapi"))]
    fn is_mute_returns_unsupported_without_feature() {
        let device = AudioDevice {
            id: String::from("stub-id"),
            name: String::from("stub-name"),
        };
        assert!(matches!(device.is_mute(), Err(AudioError::Unsupported)));
    }

    #[test]
    #[cfg(not(feature = "wasapi"))]
    fn set_mute_returns_unsupported_without_feature() {
        let device = AudioDevice {
            id: String::from("stub-id"),
            name: String::from("stub-name"),
        };
        assert!(matches!(
            device.set_mute(true),
            Err(AudioError::Unsupported)
        ));
    }

    // ------------------------------------------------------------------
    // Real-world WASAPI tests — only compiled and run with `wasapi` feature.
    // These run on Windows CI runners that always have at least one audio
    // endpoint available.
    // ------------------------------------------------------------------

    /// A device ID that is guaranteed to not match any real WASAPI endpoint.
    #[cfg(feature = "wasapi")]
    const BOGUS_ID: &str = "volumecontrol-test-nonexistent-{00000000-0000-0000-0000-000000000000}";

    /// A device name that is guaranteed to not match any real audio device.
    #[cfg(feature = "wasapi")]
    const BOGUS_NAME: &str = "zzz-volumecontrol-test-nonexistent-device-name";

    /// `from_id` with a clearly invalid ID must return `DeviceNotFound` or a
    /// graceful `InitializationFailed` — never a panic or `Unsupported`.
    #[test]
    #[cfg(feature = "wasapi")]
    fn from_id_bogus_returns_not_found() {
        let result = AudioDevice::from_id(BOGUS_ID);
        assert!(
            matches!(
                result,
                Err(AudioError::DeviceNotFound | AudioError::InitializationFailed(_))
            ),
            "expected DeviceNotFound or InitializationFailed, got {result:?}"
        );
    }

    /// `from_name` with a clearly invalid name must return `DeviceNotFound` or
    /// `InitializationFailed` — never a panic or `Unsupported`.
    #[test]
    #[cfg(feature = "wasapi")]
    fn from_name_bogus_returns_not_found() {
        let result = AudioDevice::from_name(BOGUS_NAME);
        assert!(
            matches!(
                result,
                Err(AudioError::DeviceNotFound | AudioError::InitializationFailed(_))
            ),
            "expected DeviceNotFound or InitializationFailed, got {result:?}"
        );
    }

    /// `from_name` must match regardless of the case of the query string.
    #[test]
    #[cfg(feature = "wasapi")]
    fn from_name_case_insensitive_match_returns_ok() {
        let default_device = AudioDevice::from_default().expect("from_default() failed");
        let upper = default_device.name().to_uppercase();
        let found = AudioDevice::from_name(&upper);
        assert!(
            found.is_ok(),
            "from_name with uppercase query '{upper}' should succeed (case-insensitive)"
        );
    }

    /// On Windows there is always at least one audio render endpoint; `list()`
    /// must succeed and return a non-empty `Vec`.
    #[test]
    #[cfg(feature = "wasapi")]
    fn list_returns_non_empty_vec() {
        let devices = AudioDevice::list().expect("list() failed on Windows");
        assert!(
            !devices.is_empty(),
            "list() returned an empty Vec on Windows"
        );
    }

    /// On Windows there is always a default audio render endpoint; `default()`
    /// must succeed.
    #[test]
    #[cfg(feature = "wasapi")]
    fn default_device_always_found() {
        AudioDevice::from_default()
            .expect("from_default() failed — no default audio device on Windows");
    }

    /// `get_vol` must return a value in `0..=100`; `set_vol` to a different
    /// level must be reflected by the next `get_vol` call.  The original volume
    /// is restored when the test finishes.
    #[test]
    #[cfg(feature = "wasapi")]
    fn default_device_volume_round_trip() {
        let device = AudioDevice::from_default().expect("from_default() failed");

        let original_vol = device.get_vol().expect("get_vol() failed");
        assert!(
            original_vol <= 100,
            "get_vol returned {original_vol}, out of range"
        );

        // Pick a target volume that differs from the current one.
        let target_vol: u8 = if original_vol >= 50 { 25 } else { 75 };

        device.set_vol(target_vol).expect("set_vol() failed");

        let new_vol = device.get_vol().expect("get_vol() after set_vol() failed");
        assert_eq!(new_vol, target_vol, "volume did not change to {target_vol}");

        // Restore original volume — best-effort; ignore errors on cleanup.
        let _ = device.set_vol(original_vol);
    }

    /// `set_mute(!original)` must flip the mute state; the change must be
    /// visible via `is_mute`.  The original state is restored afterwards.
    #[test]
    #[cfg(feature = "wasapi")]
    fn default_device_mute_round_trip() {
        let device = AudioDevice::from_default().expect("from_default() failed");

        let original = device.is_mute().expect("is_mute() failed");

        // Toggle to the opposite state.
        device.set_mute(!original).expect("set_mute() failed");

        let toggled = device.is_mute().expect("is_mute() after set_mute() failed");
        assert_eq!(
            toggled, !original,
            "mute state did not toggle to {}",
            !original
        );

        // Restore — best-effort; ignore errors on cleanup.
        let _ = device.set_mute(original);
    }
}