ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
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
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
//! Audio device monitoring module
//!
//! Provides cross-platform audio device enumeration.
//! - Windows: `Win32_SoundDevice` via PowerShell/CIM
//! - Linux: ALSA via /proc/asound
//! - macOS: `system_profiler SPAudioDataType`
//!
//! Note that `system_profiler` reports which device is *default* for playback and
//! capture, not what each device is capable of. The macOS direction is read from
//! the per-device channel counts instead, and is `None` where they are absent.

use crate::error::IronError;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AudioDeviceType {
    Output,
    Input,
    Duplex,
    /// Retained for compatibility. No reader produces it: an endpoint whose
    /// direction was not established is `device_type: None`, not a class of its own.
    Unknown,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AudioState {
    Active,
    /// Disabled by the user or an administrator (`DeviceState` 2 on Windows).
    Disabled,
    Idle,
    Suspended,
    Unavailable,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioDevice {
    pub id: String,
    /// Endpoint name as the platform presents it, `None` where it was not read.
    pub name: Option<String>,
    /// Whether the endpoint plays, captures, or both. `None` where the platform
    /// did not establish it.
    ///
    /// The macOS reader used to write `Output` for every endpoint that was not
    /// the default input, and the note on that path said capability was
    /// "inferred". It now reads the channel counts `system_profiler` reports.
    pub device_type: Option<AudioDeviceType>,
    /// Endpoint state, where the platform reports one.
    ///
    /// `None` where it was not established, which was not previously
    /// expressible. Linux and macOS set the literal `AudioState::Active` at
    /// every construction site. Windows really does read something -- but it
    /// reads `Win32_SoundDevice.Status`, which is Device-Manager health, while
    /// this entity is described as "endpoint state as the platform reports
    /// it: active, disabled, unplugged, not present". Those are different
    /// properties, and the match had a `_ => Active` arm that turned the eight
    /// WMI status values it did not handle -- `Unknown` and `Pred Fail` among
    /// them -- into the healthiest one.
    ///
    /// The real endpoint state is a `DeviceState` DWORD under
    /// `HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\Audio`
    /// (1 active, 2 disabled, 4 not present, 8 unplugged), readable without
    /// elevation; this reader does not go through that enumeration.
    pub state: Option<AudioState>,
    /// Whether this is the endpoint the system routes to by default.
    ///
    /// `None` where it was not established. On Windows this was "whichever row
    /// came first", which named an audio *controller* as the default output.
    pub is_default: Option<bool>,
    pub is_output: bool,
    /// Whether the endpoint is enabled, from the same `DeviceState` as
    /// [`Self::state`]: `Some(state == active)` where that was read.
    ///
    /// `None` on Linux (ALSA card enumeration carries no enable state) and macOS
    /// (`system_profiler` does not report one). Both used to write `true`, so
    /// every device was enabled whether or not it was.
    pub is_enabled: Option<bool>,
    /// Device volume, if it has been read. Nothing reads it: the default
    /// device was given `Some(100)` and every other device `None`, so the one
    /// device a user looks at was the one carrying an invented figure.
    pub volume: Option<u8>,
    /// Device mute state, if it has been read. Nothing reads it either.
    pub muted: Option<bool>,
}

/// One endpoint as the Windows audio service records it.
#[cfg(target_os = "windows")]
struct WindowsEndpoint {
    is_output: bool,
    state: Option<AudioState>,
}

/// Per-endpoint volume, mute and default flag, from the audio service.
///
/// Keyed by endpoint GUID so it joins the registry enumeration this module
/// already does. `IMMDevice::GetId` returns `{0.0.0.00000000}.{guid}`; the
/// trailing brace-wrapped GUID is the same key the `MMDevices\Audio\Render`
/// and `...\Capture` trees use.
///
/// **Why COM and not WMI or the registry.** Neither carries a live master
/// volume: `Win32_SoundDevice` has no volume property at all, and the
/// `MMDevices` tree stores endpoint *configuration*, not the current scalar the
/// mixer shows. The absence reason these readings replace said as much -- "ironmon
/// has no mixer binding on this platform" and "which endpoint the system routes
/// to by default is a COM call this crate does not make" -- and both were
/// accurate descriptions of an unimplemented reader rather than of the platform.
///
/// Volume is reported as the scalar percentage the mixer displays, which is
/// what `board.audio.{n}.volume` asks for, and not the dB level: the two differ
/// by the taper Windows applies, and a consumer comparing ironmon's figure against
/// the slider would find the dB one wrong.
#[cfg(target_os = "windows")]
fn windows_endpoint_mixer() -> std::collections::HashMap<String, EndpointMixer> {
    use windows::Win32::Media::Audio::Endpoints::IAudioEndpointVolume;
    use windows::Win32::Media::Audio::{
        eCapture, eConsole, eRender, IMMDeviceEnumerator, MMDeviceEnumerator, DEVICE_STATE_ACTIVE,
    };
    use windows::Win32::System::Com::{
        CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_APARTMENTTHREADED,
    };

    let mut out = std::collections::HashMap::new();

    // SAFETY: every call below is on interfaces obtained from the call above
    // it; every interface is created and dropped inside the `'com` block, and
    // `CoUninitialize` runs after that block on every path out.
    //
    // **The block is the fix for a crash, not a tidy-up.** `enumerator` is a
    // reference-counted COM interface whose `Drop` calls `Release`, and Rust
    // drops it at the end of the scope it was declared in -- which was the same
    // scope as `CoUninitialize()`, and *after* it. Releasing an interface on a
    // thread whose COM apartment has already been torn down is undefined, and
    // on Windows it presents as an access violation: the process dies with no
    // panic and the test harness reports only "test exited abnormally".
    //
    // Which is what every Windows CI run has done since 2026-09-03, the day
    // this reader landed. It survives on the development machine because
    // something else -- the `wmi` crate, usually -- has already initialised COM
    // on that thread, so `initialised` is false and `CoUninitialize` never runs.
    // A first-in wins, and on a fresh runner thread this reader is first in.
    unsafe {
        // The audio service is apartment-threaded. A failure here usually means
        // COM is already initialised on this thread with a different model,
        // which is not fatal -- the interfaces still work -- so the result is
        // deliberately not propagated, only the uninitialise is skipped.
        let initialised = CoInitializeEx(None, COINIT_APARTMENTTHREADED).is_ok();

        'com: {
            let enumerator: Result<IMMDeviceEnumerator, _> =
                CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL);
            let Ok(enumerator) = enumerator else {
                break 'com;
            };

            // Which endpoint each direction routes to. A machine with no output at
            // all has no default, which is why this is an `Option` rather than a
            // sentinel.
            let mut defaults: std::collections::HashSet<String> = std::collections::HashSet::new();
            for flow in [eRender, eCapture] {
                if let Ok(device) = enumerator.GetDefaultAudioEndpoint(flow, eConsole) {
                    if let Ok(id) = device.GetId() {
                        if let Some(guid) = endpoint_guid(&id.to_string().unwrap_or_default()) {
                            defaults.insert(guid);
                        }
                    }
                }
            }

            for flow in [eRender, eCapture] {
                let Ok(collection) = enumerator.EnumAudioEndpoints(flow, DEVICE_STATE_ACTIVE)
                else {
                    continue;
                };
                let count = collection.GetCount().unwrap_or(0);
                for i in 0..count {
                    let Ok(device) = collection.Item(i) else {
                        continue;
                    };
                    let Ok(id) = device.GetId() else { continue };
                    let Some(guid) = endpoint_guid(&id.to_string().unwrap_or_default()) else {
                        continue;
                    };

                    let volume: Result<IAudioEndpointVolume, _> = device.Activate(CLSCTX_ALL, None);
                    let (level, muted) = match volume {
                        Ok(v) => (
                            // The scalar is 0.0-1.0; the entity is a percentage.
                            v.GetMasterVolumeLevelScalar()
                                .ok()
                                .map(|s| (s * 100.0).round().clamp(0.0, 100.0) as u8),
                            v.GetMute().ok().map(|m| m.as_bool()),
                        ),
                        // An endpoint whose volume interface will not activate
                        // reports no level, rather than a default one.
                        Err(_) => (None, None),
                    };

                    out.insert(
                        guid.clone(),
                        EndpointMixer {
                            volume: level,
                            muted,
                            is_default: defaults.contains(&guid),
                            is_render: flow == eRender,
                        },
                    );
                }
            }
        }
        // Every interface above is out of scope and released by here.

        if initialised {
            CoUninitialize();
        }
    }

    out
}

/// Pull the endpoint GUID out of an `IMMDevice` id.
///
/// The id is `{0.0.0.00000000}.{a1b2...}`: a container id, a dot, then the
/// endpoint GUID in braces. The registry trees this module already reads are
/// keyed by that second component alone.
#[cfg(target_os = "windows")]
fn endpoint_guid(device_id: &str) -> Option<String> {
    let guid = device_id.rsplit('.').next()?;
    (guid.starts_with('{') && guid.ends_with('}')).then(|| guid.to_ascii_lowercase())
}

/// What the audio service reports about one endpoint's mixer.
#[cfg(target_os = "windows")]
struct EndpointMixer {
    volume: Option<u8>,
    muted: Option<bool>,
    is_default: bool,
    /// Output rather than input. The two directions each have their own
    /// default, and "master volume" means the output one.
    is_render: bool,
}

pub struct AudioMonitor {
    devices: Vec<AudioDevice>,
    /// System master volume, if it has been read.
    ///
    /// It never has been. This was initialised to `Some(100)` in the
    /// constructor and no `refresh_*` path on any platform assigns it, so
    /// `ironmon cli audio` reported "Master Volume: 100%" on every machine, the
    /// TUI printed the same, and the agent tool surface published
    /// `"master_volume": 100`. None of those was a reading.
    master_volume: Option<u8>,
    /// System mute state, if it has been read — see [`Self::master_volume`].
    /// It was a constant `false`, reported as "Muted: No".
    master_muted: Option<bool>,
}

impl AudioMonitor {
    pub fn new() -> Result<Self, IronError> {
        let mut monitor = Self {
            devices: Vec::new(),
            // Nothing reads these yet. Reading the system mixer needs
            // IAudioEndpointVolume on Windows, PulseAudio or ALSA on Linux and
            // CoreAudio on macOS; until one of those is wired up the honest
            // value is "not read", not "100%".
            master_volume: None,
            master_muted: None,
        };
        monitor.refresh()?;
        Ok(monitor)
    }

    pub fn refresh(&mut self) -> Result<(), IronError> {
        self.devices.clear();
        #[cfg(target_os = "windows")]
        self.refresh_windows()?;
        #[cfg(target_os = "linux")]
        self.refresh_linux()?;
        #[cfg(target_os = "macos")]
        self.refresh_macos()?;
        Ok(())
    }

    pub fn devices(&self) -> &[AudioDevice] {
        &self.devices
    }
    pub fn master_volume(&self) -> Option<u8> {
        self.master_volume
    }
    /// Whether the system is muted, or `None` because nothing reads it.
    pub fn is_muted(&self) -> Option<bool> {
        self.master_muted
    }
    pub fn default_output(&self) -> Option<&AudioDevice> {
        self.devices
            .iter()
            .find(|d| d.is_default == Some(true) && d.is_output)
    }
    pub fn default_input(&self) -> Option<&AudioDevice> {
        self.devices
            .iter()
            .find(|d| d.is_default == Some(true) && !d.is_output)
    }

    // ==================== Hardware Control APIs ====================

    /// Set the master volume level (0-100).
    ///
    /// # Not implemented
    ///
    /// This assigned the field and returned `Ok(())`, touching no audio API on
    /// any platform. A caller set the volume to 20, was told it had worked, and
    /// the machine did not change — while `master_volume()` then returned the
    /// 20 it had just stored, so even reading it back appeared to confirm it.
    ///
    /// It returns an error until a real mixer call is behind it. A control that
    /// reports success without acting is worse than one that is absent.
    pub fn set_master_volume(&mut self, volume: u8) -> Result<(), crate::error::IronError> {
        if volume > 100 {
            return Err(crate::error::IronError::InvalidInput(format!(
                "Volume must be 0-100, got {volume}"
            )));
        }
        Err(crate::error::IronError::NotImplemented(
            concat!(
                "setting the master volume: IronMonitor has no mixer binding on this ",
                "platform, and this call previously changed only its own copy of ",
                "the value"
            )
            .to_string(),
        ))
    }

    /// Set the master mute state.
    ///
    /// # Not implemented
    ///
    /// See [`Self::set_master_volume`]. This changed only the field.
    pub fn set_mute(&mut self, _muted: bool) -> Result<(), crate::error::IronError> {
        Err(crate::error::IronError::NotImplemented(
            "setting the mute state: IronMonitor has no mixer binding on this platform".to_string(),
        ))
    }

    /// Set volume for a specific device by ID.
    pub fn set_device_volume(
        &mut self,
        device_id: &str,
        volume: u8,
    ) -> Result<(), crate::error::IronError> {
        if volume > 100 {
            return Err(crate::error::IronError::InvalidInput(format!(
                "Volume must be 0-100, got {}",
                volume
            )));
        }
        if !self.devices.iter().any(|d| d.id == device_id) {
            return Err(crate::error::IronError::NotFound(format!(
                "Audio device '{}' not found",
                device_id
            )));
        }
        // Not implemented: this used to store the value in the device record and
        // return Ok, so the next read reported a volume the hardware never had.
        Err(crate::error::IronError::NotImplemented(
            concat!(
                "setting a device's volume: IronMonitor has no mixer binding on this ",
                "platform, and this call previously changed only its own copy of ",
                "the value"
            )
            .to_string(),
        ))
    }

    /// Set mute state for a specific device by ID.
    ///
    /// # Not implemented
    ///
    /// See [`Self::set_master_volume`]. This changed only the field.
    pub fn set_device_mute(
        &mut self,
        device_id: &str,
        _muted: bool,
    ) -> Result<(), crate::error::IronError> {
        if self.devices.iter().any(|d| d.id == device_id) {
            Err(crate::error::IronError::NotImplemented(
                concat!(
                    "setting a device's mute state: IronMonitor has no mixer binding ",
                    "on this platform"
                )
                .to_string(),
            ))
        } else {
            Err(crate::error::IronError::NotFound(format!(
                "Audio device '{}' not found",
                device_id
            )))
        }
    }

    /// Enumerate this machine's audio endpoints.
    ///
    /// Three separate things were wrong here, and all three came from the same
    /// root cause as the display reader: **the list was of the wrong kind of
    /// object**, so everything hung off it had to be guessed.
    ///
    /// The PowerShell it ran concatenated `Win32_SoundDevice` — audio
    /// *adapters* — with the PnP `AudioEndpoint` class. On the development
    /// machine that produced twelve "endpoints", eight of which are codecs and
    /// controllers: `Realtek High Definition Audio`, `AMD Streaming Audio
    /// Device`, `NVIDIA High Definition Audio` twice. The entity reads
    /// "endpoint name **as the platform presents it to a user**", and a user is
    /// never shown any of those.
    ///
    /// Direction came from a regular expression over the name:
    ///
    /// ```ignore
    /// $isInput = $dev.Name -match 'Microphone|Input|Capture|Line In'
    /// ```
    ///
    /// which was **inverted on half the real endpoints here**. A virtual audio
    /// interface names its endpoints from the application's point of view, so
    /// `MOTIV Mix Virtual Input` is what you play *into* — a render endpoint —
    /// and `MOTIV Mix Virtual Output` is what you record *from*. The registry
    /// says Render and Capture respectively; the regex said the opposite of
    /// both.
    ///
    /// And the default endpoint was whichever row came first:
    ///
    /// ```ignore
    /// let is_default = if is_output && !has_default_output { .. true } else { false };
    /// ```
    ///
    /// The endpoint list itself is kept — it is Windows' own presentation, and
    /// it carries no duplicates — and joined to
    /// `MMDevices\Audio\{Render,Capture}` on the GUID that ends the PnP device
    /// id, which is exactly the registry subkey name. That join is an equality
    /// on a unique key rather than a name match: the friendly names do not join
    /// reliably, because Windows disambiguates a second instance of an adapter
    /// by prefixing `2- `.
    #[cfg(target_os = "windows")]
    fn refresh_windows(&mut self) -> Result<(), IronError> {
        const QUERY: &str = concat!(
            "Get-CimInstance Win32_PnPEntity | Where-Object { $_.PNPClass -eq 'AudioEndpoint' } ",
            "| Select-Object Name, PNPDeviceID | ConvertTo-Json -Compress"
        );

        let endpoints = Self::windows_endpoint_registry();
        // One COM session for the whole enumeration rather than one per device.
        let mixer = windows_endpoint_mixer();

        // "Master volume" is the level of the endpoint the system routes output
        // to -- the figure the volume slider shows. It is not a separate system
        // property, and Windows has none: there is only ever a per-endpoint
        // level, so taking the default output's is what the name means.
        //
        // `None` where no default output was found, which is a machine with no
        // active render endpoint at all. It used to be a hardcoded `Some(100)`.
        if let Some(default_out) = mixer.values().find(|m| m.is_default && m.is_render) {
            self.master_volume = default_out.volume;
            self.master_muted = default_out.muted;
        }

        let Some(value) =
            crate::core::command::capture_json("powershell", &["-NoProfile", "-Command", QUERY])?
        else {
            return Ok(());
        };

        for (idx, item) in crate::core::command::json_items(&value).iter().enumerate() {
            // An endpoint with no Name is kept with its name unread, not dropped:
            // it still has a registry entry, a direction and a state.
            let name = item["Name"].as_str().map(str::to_string);
            let pnp_id = item["PNPDeviceID"].as_str().unwrap_or("");

            // `SWD\MMDEVAPI\{0.0.0.00000000}.{116ba9f0-...}` — the endpoint's
            // own GUID is the last brace group.
            let Some(guid) = pnp_id
                .rfind('{')
                .map(|i| pnp_id[i..].to_ascii_lowercase())
                .filter(|g| g.ends_with('}'))
            else {
                continue;
            };

            // An endpoint the audio service does not have a key for is one this
            // reader cannot describe: its direction and state would both have
            // to be invented, which is what the previous version did.
            let Some(endpoint) = endpoints.get(&guid) else {
                continue;
            };

            self.devices.push(AudioDevice {
                id: format!("audio{idx}"),
                name,
                device_type: Some(if endpoint.is_output {
                    AudioDeviceType::Output
                } else {
                    AudioDeviceType::Input
                }),
                state: endpoint.state,
                // From the audio service. This was "whichever row came first",
                // which on this machine named an audio *controller* as the
                // default output; then it was `None` with a note that the COM
                // call was not made. It is made now -- see
                // `windows_endpoint_mixer`.
                //
                // An endpoint the mixer enumeration did not return keeps its
                // absence: `DEVICE_STATE_ACTIVE` is what that enumeration asks
                // for, so a disabled or unplugged endpoint has no live volume
                // to report and is not given one.
                is_default: mixer.get(&guid).map(|m| m.is_default),
                is_output: endpoint.is_output,
                // Unknown when the state is: `None == Some(Active)` was false,
                // which reported an endpoint whose state was never read as disabled.
                is_enabled: endpoint.state.map(|s| s == AudioState::Active),
                volume: mixer.get(&guid).and_then(|m| m.volume),
                muted: mixer.get(&guid).and_then(|m| m.muted),
            });
        }
        Ok(())
    }

    /// Every audio endpoint the Windows audio service knows about, by GUID.
    ///
    /// `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio` has a
    /// `Render` and a `Capture` subtree, which is where the direction comes
    /// from, and each endpoint key carries a `DeviceState` DWORD. Both are
    /// readable without elevation.
    #[cfg(target_os = "windows")]
    fn windows_endpoint_registry() -> std::collections::HashMap<String, WindowsEndpoint> {
        use winreg::enums::HKEY_LOCAL_MACHINE;
        use winreg::RegKey;

        const BASE: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio";

        let mut out = std::collections::HashMap::new();
        for (flow, is_output) in [("Render", true), ("Capture", false)] {
            let Ok(tree) =
                RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(format!("{BASE}\\{flow}"))
            else {
                continue;
            };
            for guid in tree.enum_keys().flatten() {
                let Ok(key) = tree.open_subkey(&guid) else {
                    continue;
                };
                // The documented states are a four-bit mask -- 1 active,
                // 2 disabled, 4 not present, 8 unplugged -- and Windows sets
                // further undocumented bits above them, so the value is masked
                // rather than compared.
                let state =
                    key.get_value::<u32, _>("DeviceState")
                        .ok()
                        .and_then(|raw| match raw & 0xF {
                            1 => Some(AudioState::Active),
                            // Disabled is not suspended. The old mapping labelled a
                            // disabled endpoint "Suspended".
                            2 => Some(AudioState::Disabled),
                            4 | 8 => Some(AudioState::Unavailable),
                            _ => None,
                        });
                out.insert(
                    guid.to_ascii_lowercase(),
                    WindowsEndpoint { is_output, state },
                );
            }
        }
        out
    }
    #[cfg(target_os = "linux")]
    fn refresh_linux(&mut self) -> Result<(), IronError> {
        use std::fs;

        // Read from /proc/asound for ALSA card enumeration. A kernel with no
        // ALSA has no /proc/asound, which is a reading; a file that will not
        // open is not, and both used to leave the list silently empty.
        let cards_path = std::path::Path::new("/proc/asound/cards");
        let cards = match fs::read_to_string(cards_path) {
            Ok(c) => Some(c),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => {
                return Err(IronError::System(format!(
                    "cannot read /proc/asound/cards: {e}"
                )))
            }
        };
        if let Some(cards_content) = cards {
            for line in cards_content.lines() {
                let trimmed = line.trim();
                // Lines like " 0 [PCH            ]: HDA-Intel - HDA Intel PCH"
                if let Some(bracket_start) = trimmed.find('[') {
                    if let Some(bracket_end) = trimmed.find(']') {
                        let card_id_str: String = trimmed
                            .chars()
                            .take_while(|c| c.is_ascii_digit() || c.is_whitespace())
                            .collect();
                        // A line whose card number does not parse is skipped. It used
                        // to be card 0, which every later check then treated as real.
                        let Ok(card_num) = card_id_str.trim().parse::<u32>() else {
                            continue;
                        };
                        let short_name = trimmed[bracket_start + 1..bracket_end].trim().to_string();

                        // Get full name from the colon part
                        let full_name = if let Some(colon_idx) = trimmed.find("- ") {
                            trimmed[colon_idx + 2..].trim().to_string()
                        } else {
                            short_name.clone()
                        };

                        // Check for playback/capture devices
                        let pcm_path = format!("/proc/asound/card{}", card_num);
                        let pcm_names: Vec<String> = fs::read_dir(&pcm_path)
                            .into_iter()
                            .flatten()
                            .flatten()
                            .map(|e| e.file_name().to_string_lossy().into_owned())
                            .collect();
                        let (has_playback, has_capture) =
                            alsa_pcm_directions(pcm_names.iter().map(String::as_str));

                        // A card with neither playback nor capture PCMs has no direction
                        // to report, so it is `None` rather than a class of its own.
                        let device_type = match (has_playback, has_capture) {
                            (true, true) => Some(AudioDeviceType::Duplex),
                            (true, false) => Some(AudioDeviceType::Output),
                            (false, true) => Some(AudioDeviceType::Input),
                            (false, false) => None,
                        };

                        self.devices.push(AudioDevice {
                            id: format!("hw:{}", card_num),
                            name: Some(full_name),
                            device_type,
                            state: None,
                            // Set below from the PulseAudio/PipeWire default sink, where
                            // one is reported. This used to be `card_num == 0`, which
                            // named card 0 the default whether or not it was.
                            is_default: None,
                            is_output: has_playback,
                            // ALSA's card list has no enable state. This used to be `true`.
                            is_enabled: None,
                            volume: None,
                            muted: None,
                        });
                    }
                }
            }
        }

        // The default sink is named by PulseAudio/PipeWire. Its card is the one
        // its own `alsa.card` property names. A sink that is not ALSA, or a
        // machine with no pactl, leaves every card's default unknown.
        if let Some(default_card) = pactl_stdout(&["info"])
            .zip(pactl_stdout(&["list", "sinks"]))
            .and_then(|(info, sinks)| default_sink_alsa_card(&info, &sinks))
        {
            for dev in &mut self.devices {
                if let Some(card) = dev
                    .id
                    .strip_prefix("hw:")
                    .and_then(|n| n.parse::<u32>().ok())
                {
                    dev.is_default = Some(card == default_card);
                }
            }
        }

        // No fallback device. An empty list means the ALSA cards file told us
        // nothing, which is not the same as one working duplex device.
        Ok(())
    }

    #[cfg(target_os = "macos")]
    fn refresh_macos(&mut self) -> Result<(), IronError> {
        // Use system_profiler for audio device info. It ships with macOS, so a
        // failure to run it is a failure rather than an absent optional tool.
        let stdout =
            crate::core::command::capture("system_profiler", &["SPAudioDataType", "-json"])?;
        {
            {
                let stdout = stdout.as_str();
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(stdout) {
                    if let Some(audio_data) = json.get("SPAudioDataType").and_then(|v| v.as_array())
                    {
                        let mut idx = 0u32;
                        for device in audio_data {
                            // No name is kept as unread. The old fallback was the
                            // literal "Audio Device".
                            let name = device.get("_name").and_then(|v| v.as_str());
                            let has_output = device
                                .get("coreaudio_default_audio_output_device")
                                .and_then(|v| v.as_str())
                                == Some("spaudio_yes");
                            let has_input = device
                                .get("coreaudio_default_audio_input_device")
                                .and_then(|v| v.as_str())
                                == Some("spaudio_yes");

                            // The `coreaudio_default_*` keys above say which device is
                            // default, not what it supports, so they do not give the
                            // direction. The channel counts do; see `macos_device_type`.
                            let device_type = macos_device_type(device);

                            self.devices.push(AudioDevice {
                                id: format!("audio{}", idx),
                                name: name.map(str::to_string),
                                device_type,
                                state: None,
                                is_default: Some(has_output || has_input),
                                is_output: has_output || (!has_input),
                                // `system_profiler` reports no enable state. This used to be `true`.
                                is_enabled: None,
                                volume: None,
                                muted: None,
                            });
                            idx += 1;
                        }
                    }
                }
            }
        }

        // No fallback device, and no invented 100% volume with it. See the
        // Windows path above.
        Ok(())
    }
}

/// The direction of one `system_profiler SPAudioDataType` device.
///
/// `coreaudio_device_input` and `coreaudio_device_output` carry the channel
/// count of each direction the device has streams in, and are absent for a
/// direction it lacks. `None` when neither is reported, which the reader used to
/// turn into `Output` for every device.
#[cfg(any(target_os = "macos", test))]
fn macos_device_type(device: &serde_json::Value) -> Option<AudioDeviceType> {
    let has_channels = |key: &str| {
        device
            .get(key)
            .and_then(|v| v.as_u64().or_else(|| v.as_str()?.parse().ok()))
            .is_some_and(|n| n > 0)
    };
    match (
        has_channels("coreaudio_device_input"),
        has_channels("coreaudio_device_output"),
    ) {
        (true, true) => Some(AudioDeviceType::Duplex),
        (true, false) => Some(AudioDeviceType::Input),
        (false, true) => Some(AudioDeviceType::Output),
        (false, false) => None,
    }
}

/// Standard output of a `pactl` call, or `None` where pactl is absent or fails.
#[cfg(target_os = "linux")]
fn pactl_stdout(args: &[&str]) -> Option<String> {
    let output = std::process::Command::new("pactl")
        .args(args)
        .output()
        .ok()?;
    output
        .status
        .success()
        .then(|| String::from_utf8_lossy(&output.stdout).into_owned())
}

/// Whether an ALSA card has a playback and a capture PCM, from the `pcmNp` and
/// `pcmNc` entries under its `/proc/asound/cardN` directory.
///
/// Any PCM number counts. The reader used to look only at `pcm0`, and a card
/// whose playback lives on another device number (an NVIDIA HDMI card uses
/// pcm3, pcm7 and so on) was then reported as having no playback at all.
#[cfg(any(target_os = "linux", test))]
fn alsa_pcm_directions<'a>(entries: impl IntoIterator<Item = &'a str>) -> (bool, bool) {
    let mut playback = false;
    let mut capture = false;
    for entry in entries {
        let Some(rest) = entry.strip_prefix("pcm") else {
            continue;
        };
        let Some(direction) = rest.chars().last() else {
            continue;
        };
        let digits = &rest[..rest.len() - direction.len_utf8()];
        if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
            continue;
        }
        match direction {
            'p' => playback = true,
            'c' => capture = true,
            _ => {}
        }
    }
    (playback, capture)
}

/// The ALSA card number of the default sink, from `pactl info` and
/// `pactl list sinks`.
///
/// `None` where the default sink is not named, is missing from the sink list,
/// or carries no `alsa.card` property (a Bluetooth or network sink).
#[cfg(any(target_os = "linux", test))]
fn default_sink_alsa_card(info: &str, sinks: &str) -> Option<u32> {
    let default_sink = info
        .lines()
        .find_map(|line| line.strip_prefix("Default Sink:"))
        .map(str::trim)
        .filter(|name| !name.is_empty())?;
    // `pactl list sinks` separates its sinks with "Sink #N" headers.
    sinks
        .split("\nSink #")
        .find(|block| {
            block
                .lines()
                .any(|line| line.trim().strip_prefix("Name:").map(str::trim) == Some(default_sink))
        })
        .and_then(|block| {
            block.lines().find_map(|line| {
                let value = line.trim().strip_prefix("alsa.card = \"")?;
                value.strip_suffix('"')?.parse::<u32>().ok()
            })
        })
}

impl Default for AudioMonitor {
    fn default() -> Self {
        Self::new().unwrap_or(Self {
            devices: Vec::new(),
            master_volume: None,
            master_muted: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Nothing in IronMonitor reads the system mixer, so nothing may report one.
    ///
    /// `master_volume` was initialised to `Some(100)` in the constructor and
    /// assigned by no `refresh_*` path on any platform, so `ironmon cli audio`
    /// printed "Master Volume: 100%" on every machine, the TUI printed the
    /// same, and the agent tool surface published `"master_volume": 100`. This
    /// fails the moment a real reader lands, which is when the wording on
    /// those three surfaces needs revisiting.
    #[test]
    fn the_master_volume_is_the_default_output_or_nothing() {
        let monitor = AudioMonitor::new().expect("monitor");

        // This test was written when no platform read a mixer at all, and it
        // asserted `None` everywhere. Windows reads one now, so asserting
        // absence would pin the defect rather than the principle.
        //
        // The principle is what the original constructor got wrong: it set
        // `Some(100)` from nowhere, and every surface published "Master Volume:
        // 100%" on every machine. A master volume is not a system property --
        // Windows has only per-endpoint levels -- so the only honest value is
        // the default *output* endpoint's, and any other number is invented.
        let default_output = monitor
            .devices()
            .iter()
            .find(|d| d.is_output && d.is_default == Some(true));

        match default_output {
            Some(device) => {
                assert_eq!(
                    monitor.master_volume(),
                    device.volume,
                    "master volume must be the default output's level, not a figure of its own"
                );
                assert_eq!(monitor.is_muted(), device.muted);
            }
            // No default output found: on a platform with no mixer binding at
            // all, and on a machine with no active render endpoint.
            None => {
                assert_eq!(
                    monitor.master_volume(),
                    None,
                    "with no default output there is nothing for a master volume to be"
                );
                assert_eq!(monitor.is_muted(), None);
            }
        }

        // Whatever is reported is a percentage. The old value was 100, which is
        // in range -- so this alone would not have caught it, and it is here to
        // catch a scalar published without its 0-1 to 0-100 conversion.
        for device in monitor.devices() {
            if let Some(volume) = device.volume {
                assert!(
                    volume <= 100,
                    "{:?}: volume {volume} is not a percentage",
                    device.name
                );
            }
        }
    }

    /// A control that reports success without acting is worse than one that is
    /// absent, because the caller has no way to find out.
    #[test]
    fn the_mixer_setters_decline_rather_than_pretend() {
        let mut monitor = AudioMonitor::new().expect("monitor");
        let before_volume = monitor.master_volume();
        let before_muted = monitor.is_muted();

        assert!(
            monitor.set_master_volume(75).is_err(),
            "setting the volume touches no audio API and must not return Ok"
        );
        assert!(monitor.set_mute(true).is_err());

        // The failed call must not have left its argument behind as though it
        // were a reading. Compared against what was read before the call rather
        // than against `None`, since a mixer that *is* read has a real value
        // here and pinning `None` would only pin the platform this runs on.
        assert_eq!(monitor.master_volume(), before_volume);
        assert_eq!(monitor.is_muted(), before_muted);

        // Argument validation still comes first.
        assert!(monitor.set_master_volume(101).is_err());
    }

    /// Constructing the monitor either enumerates or says why it could not.
    ///
    /// See the identically-shaped tests in `camera`, `usb` and the rest: this
    /// asserted `is_ok()`, which was true by construction while `refresh` could
    /// not fail. A failure must carry a reason, because a reason is the whole
    /// difference between "this machine has none" and "nobody looked".
    #[test]
    fn the_default_sink_names_its_alsa_card_and_nothing_else_is_guessed() {
        let info = "Server Version: 15.0.0\nDefault Sink: alsa_output.pci-0000_00_1f.3.analog-stereo\nDefault Source: x\n";
        let sinks = concat!(
            "Sink #0\n",
            "\tState: SUSPENDED\n",
            "\tName: alsa_output.pci-0000_01_00.1.hdmi-stereo\n",
            "\tProperties:\n",
            "\t\talsa.card = \"1\"\n",
            "Sink #1\n",
            "\tState: RUNNING\n",
            "\tName: alsa_output.pci-0000_00_1f.3.analog-stereo\n",
            "\tProperties:\n",
            "\t\talsa.card = \"0\"\n",
            "\t\talsa.card_name = \"HDA Intel PCH\"\n",
        );
        assert_eq!(default_sink_alsa_card(info, sinks), Some(0));

        // A Bluetooth default sink has no ALSA card, so no card is the default.
        let bluez = "Default Sink: bluez_output.AA_BB.1\n";
        let bluez_sinks =
            "Sink #2\n\tName: bluez_output.AA_BB.1\n\tProperties:\n\t\tdevice.api = \"bluez\"\n";
        assert_eq!(default_sink_alsa_card(bluez, bluez_sinks), None);

        // A default that is not in the sink list is not guessed at.
        assert_eq!(default_sink_alsa_card("Default Sink: gone\n", sinks), None);
        // No default reported at all.
        assert_eq!(default_sink_alsa_card("Server Version: 15\n", sinks), None);
    }

    /// Shaped like the `SPAudioDataType` entries of `system_profiler -json`: the
    /// speakers have output streams only, the microphone input only, and the
    /// default flags do not decide the direction.
    #[test]
    fn the_macos_direction_comes_from_the_stream_counts_not_the_defaults() {
        let speakers: serde_json::Value = serde_json::from_str(
            r#"{"_name": "MacBook Pro Speakers", "coreaudio_device_output": 2, "coreaudio_default_audio_output_device": "spaudio_yes"}"#,
        )
        .unwrap();
        assert_eq!(macos_device_type(&speakers), Some(AudioDeviceType::Output));

        let microphone: serde_json::Value = serde_json::from_str(
            r#"{"_name": "MacBook Pro Microphone", "coreaudio_device_input": 1}"#,
        )
        .unwrap();
        assert_eq!(macos_device_type(&microphone), Some(AudioDeviceType::Input));

        let interface: serde_json::Value = serde_json::from_str(
            r#"{"_name": "USB Interface", "coreaudio_device_input": "2", "coreaudio_device_output": 2}"#,
        )
        .unwrap();
        assert_eq!(macos_device_type(&interface), Some(AudioDeviceType::Duplex));
    }

    /// A device whose output names no stream count is not called an output, and
    /// a zero count is not a direction.
    #[test]
    fn a_macos_device_with_no_stream_counts_has_no_direction() {
        let bare: serde_json::Value =
            serde_json::from_str(r#"{"_name": "Mystery Device"}"#).unwrap();
        assert_eq!(macos_device_type(&bare), None);

        let zero: serde_json::Value = serde_json::from_str(
            r#"{"_name": "Silent", "coreaudio_device_input": 0, "coreaudio_device_output": 0}"#,
        )
        .unwrap();
        assert_eq!(macos_device_type(&zero), None);
    }

    /// An NVIDIA HDMI card has playback PCMs only on device numbers other than 0,
    /// and the reader used to report it as having no playback at all.
    #[test]
    fn alsa_card_directions_look_at_every_pcm_not_only_pcm0() {
        assert_eq!(
            alsa_pcm_directions(["info", "id", "pcm3p", "pcm7p", "pcm8p"]),
            (true, false)
        );
        assert_eq!(alsa_pcm_directions(["pcm0c"]), (false, true));
        assert_eq!(alsa_pcm_directions(["pcm0p", "pcm0c"]), (true, true));
        // Names that only look like PCM entries are not devices.
        assert_eq!(
            alsa_pcm_directions(["pcm", "pcmxp", "pcm0", "pcm1x"]),
            (false, false)
        );
    }

    #[test]
    fn test_audio_monitor_creation() {
        match AudioMonitor::new() {
            Ok(_monitor) => {}
            Err(e) => {
                let why = e.to_string();
                assert!(
                    why.len() > 10,
                    "enumeration failed without saying why: {why:?}"
                );
            }
        }
    }

    /// Whatever is enumerated must be identifiable. How many there are is the
    /// machine's business.
    ///
    /// This asserted `!devices().is_empty()`, under a comment reading
    /// "Should have at least one device (placeholder on all platforms)" — it
    /// existed to assert that the invented fallback device was present, and it
    /// failed on the Linux and Windows CI runners the moment that device was
    /// removed, because a headless runner genuinely has no audio endpoint.
    ///
    /// A test that pins a placeholder makes the placeholder the contract. The
    /// honest assertion is about the shape of what is reported, not about a
    /// count the hardware decides.
    #[test]
    fn test_audio_monitor_devices() {
        let monitor = AudioMonitor::new().unwrap();
        for device in monitor.devices() {
            assert!(
                !device.id.is_empty(),
                "an audio device was reported with no id"
            );
            // A name is either read or absent; an empty string is neither.
            if let Some(name) = &device.name {
                assert!(
                    !name.trim().is_empty(),
                    "audio device {} was reported with an empty name",
                    device.id
                );
            }
        }
    }

    #[test]
    fn test_audio_monitor_master_volume() {
        let monitor = AudioMonitor::new().unwrap();
        if let Some(vol) = monitor.master_volume() {
            assert!(vol <= 100);
        }
    }

    #[test]
    fn test_audio_device_serialization() {
        let device = AudioDevice {
            id: "test".to_string(),
            name: Some("Test Device".to_string()),
            device_type: Some(AudioDeviceType::Output),
            state: Some(AudioState::Active),
            is_default: Some(true),
            is_output: true,
            is_enabled: Some(true),
            volume: Some(50),
            muted: Some(false),
        };
        let json = serde_json::to_string(&device).unwrap();
        let deserialized: AudioDevice = serde_json::from_str(&json).unwrap();
        assert_eq!(device.id, deserialized.id);
        assert_eq!(device.name, deserialized.name);
    }

    #[test]
    fn test_audio_monitor_default() {
        let monitor = AudioMonitor::default();
        // Default should work without panic
        let _ = monitor.devices();
    }
}