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
//! Camera and webcam device monitoring.
//!
//! # Platform Support
//!
//! - **Linux**: Reads `/sys/class/video4linux/`, `/dev/video*`
//! - **Windows**: Uses WMI (`Win32_PnPEntity` with the `Camera` PnP class)
//! - **macOS**: Uses `system_profiler SPCameraDataType`
//!
//! # Examples
//!
//! ```no_run
//! use ironmonitor::camera::CameraMonitor;
//!
//! let monitor = CameraMonitor::new().unwrap();
//! for cam in monitor.cameras() {
//!     println!("{} ({:?}) - {}",
//!         cam.name.as_deref().unwrap_or("name not read"), cam.connection, match cam.is_active {
//!             Some(true) => "streaming", Some(false) => "idle", None => "unknown" });
//! }
//! ```

use serde::{Deserialize, Serialize};

use crate::error::IronError;

/// Camera connection type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CameraConnection {
    /// Built-in / integrated webcam
    Internal,
    /// USB-connected camera
    USB,
    /// IP / network camera
    Network,
    /// CSI / MIPI (embedded, e.g., Raspberry Pi, Jetson)
    CSI,
    /// Virtual / software camera (OBS, ManyCam, etc.)
    Virtual,
    /// Unknown connection
    Unknown,
}

/// Camera capability
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CameraCapability {
    /// Video capture
    VideoCapture,
    /// Still image capture
    StillCapture,
    /// Streaming output
    Streaming,
    /// Hardware encoding
    HardwareEncoding,
    /// Infrared / night vision
    Infrared,
    /// Depth sensing (ToF, structured light)
    DepthSensing,
    /// Autofocus
    Autofocus,
    /// Pan/tilt/zoom
    PTZ,
    /// Microphone integrated
    Microphone,
}

/// Information about a single camera device
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CameraInfo {
    /// Device name, `None` where the platform did not give one. The device is
    /// still reported, so a nameless camera is not folded into "no cameras".
    pub name: Option<String>,
    /// Connection type, `None` where the platform did not say.
    ///
    /// The macOS reader used to write `Internal` on every camera whose model
    /// string did not name USB or virtual. A built-in camera and a phone used
    /// as a webcam (Continuity Camera) look the same in the output this reader
    /// has, so that was a guess, and it is `None` now.
    pub connection: Option<CameraConnection>,
    /// Device path (/dev/video0, device instance, etc.)
    pub device_path: String,
    /// Driver in use
    pub driver: String,
    /// Vendor / manufacturer, `None` where the platform names none.
    ///
    /// The macOS reader used to write "Apple" on every camera, USB ones
    /// included, and the Windows reader wrote an empty string for a missing
    /// `Manufacturer`.
    pub vendor: Option<String>,
    /// Maximum resolution (width)
    pub max_width: u32,
    /// Maximum resolution (height)
    pub max_height: u32,
    /// Supported pixel formats (e.g., YUYV, MJPG, H264).
    ///
    /// `None` where they were not read. Only the Linux reader enumerates them
    /// (`VIDIOC_ENUM_FMT`). It used to return `["YUYV", "MJPG"]` for every
    /// camera, and the Windows and macOS readers used to write an empty list,
    /// which the ontology then published as a list the camera had listed as
    /// empty.
    pub formats: Option<Vec<String>>,
    /// Device capabilities
    pub capabilities: Vec<CameraCapability>,
    /// Whether the camera is an infrared sensor, `None` where that was not
    /// established.
    ///
    /// Only the Linux reader sets it, from the device's own V4L2 format list: a
    /// device offering only luminance formats (`GREY`, `Y8`, `Y16`) and no
    /// colour format is `Some(true)`. The reader used to match the device name
    /// for "IR " or "infrared", which is a guess about a label, so a camera
    /// called anything else was never flagged. Windows and macOS do not set it.
    pub infrared: Option<bool>,
    /// Whether the camera is streaming right now.
    ///
    /// `None` where that could not be established, which is most of the time
    /// and was not previously expressible. The ontology entity calls this "the
    /// one genuinely live field in this cluster", and it was live on exactly
    /// one of three platforms: Linux really does probe the device node, macOS
    /// set the literal `true`, and Windows used
    /// `Win32_PnPEntity.Status == "OK"` -- which is true of every working
    /// camera that is switched off. An idle laptop reported its webcam as
    /// streaming, which is the wrong way round for a privacy signal.
    pub is_active: Option<bool>,
    /// Device index (e.g., 0 for /dev/video0)
    pub index: u32,
}

impl CameraInfo {
    /// Get resolution as a formatted string (e.g., "1920x1080")
    pub fn resolution(&self) -> String {
        if self.max_width > 0 && self.max_height > 0 {
            format!("{}x{}", self.max_width, self.max_height)
        } else {
            "unknown".into()
        }
    }

    /// Infer megapixels from max resolution
    pub fn megapixels(&self) -> f64 {
        (self.max_width as f64 * self.max_height as f64) / 1_000_000.0
    }
}

/// `VIDIOC_ENUM_FMT`, which is `_IOWR('V', 2, struct v4l2_fmtdesc)`.
#[cfg(target_os = "linux")]
const VIDIOC_ENUM_FMT: u32 = 0xC040_5602;
/// `V4L2_BUF_TYPE_VIDEO_CAPTURE`.
#[cfg(target_os = "linux")]
const V4L2_BUF_TYPE_VIDEO_CAPTURE: u32 = 1;
/// A cap on the format walk. No driver offers anywhere near this many.
#[cfg(target_os = "linux")]
const V4L2_ENUM_FMT_LIMIT: u32 = 256;

/// `struct v4l2_fmtdesc` from `linux/videodev2.h`, 64 bytes on every
/// architecture because it holds no pointers or `long`s.
#[cfg(target_os = "linux")]
#[repr(C)]
#[derive(Default)]
struct V4l2Fmtdesc {
    index: u32,
    buf_type: u32,
    flags: u32,
    description: [u8; 32],
    pixelformat: u32,
    mbus_code: u32,
    reserved: [u32; 3],
}

#[cfg(target_os = "linux")]
const _: () = assert!(std::mem::size_of::<V4l2Fmtdesc>() == 64);

/// Spells a V4L2 pixel format. The format is a FourCC packed little-endian
/// into a `u32`, so `YUYV` is `0x5659_5559`; space padding (`"Z16 "`) is
/// dropped.
#[cfg(any(target_os = "linux", test))]
fn fourcc_to_string(code: u32) -> String {
    String::from_utf8_lossy(&code.to_le_bytes())
        .trim_end()
        .to_string()
}

/// Pixel formats that carry one luminance channel and no colour.
#[cfg(any(target_os = "linux", test))]
const LUMINANCE_FORMATS: &[&str] = &["GREY", "Y8", "Y8I", "Y10", "Y12", "Y16"];

/// Depth formats. A depth sensor is neither an infrared camera nor a colour one.
#[cfg(any(target_os = "linux", test))]
const DEPTH_FORMATS: &[&str] = &["Z16", "INZI"];

/// Whether a device is an infrared sensor, from the pixel formats it offers.
///
/// `Some(true)` when every format is luminance-only: a sensor with no colour
/// output is what an IR camera is. `Some(false)` when the device offers any
/// colour format. `None` otherwise, including a depth-only device and a device
/// whose formats were not read, because neither says whether it is infrared.
#[cfg(any(target_os = "linux", test))]
fn infrared_from_formats(formats: Option<&[String]>) -> Option<bool> {
    let formats = formats.filter(|f| !f.is_empty())?;
    let is = |list: &[&str], f: &String| list.contains(&f.as_str());
    if formats
        .iter()
        .any(|f| !is(LUMINANCE_FORMATS, f) && !is(DEPTH_FORMATS, f))
    {
        Some(false)
    } else if formats.iter().all(|f| is(LUMINANCE_FORMATS, f)) {
        Some(true)
    } else {
        None
    }
}

/// Monitor for camera and webcam devices
pub struct CameraMonitor {
    cameras: Vec<CameraInfo>,
}

impl CameraMonitor {
    /// Create a new CameraMonitor and enumerate all cameras.
    pub fn new() -> Result<Self, IronError> {
        let mut monitor = Self {
            cameras: Vec::new(),
        };
        monitor.refresh()?;
        Ok(monitor)
    }

    /// Refresh the list of camera devices.
    ///
    /// Returns `Err` when the enumeration failed, and `Ok` with an empty list
    /// only when it succeeded and found nothing. Those were the same value
    /// until 6.0.0, and the resolver publishes the second as a fact about the
    /// machine -- `"no cameras detected"`, an answer to "can this machine see".
    /// See [`crate::core::command`].
    pub fn refresh(&mut self) -> Result<(), IronError> {
        self.cameras.clear();

        #[cfg(target_os = "linux")]
        self.refresh_linux()?;

        #[cfg(target_os = "windows")]
        self.refresh_windows()?;

        #[cfg(target_os = "macos")]
        self.refresh_macos()?;

        Ok(())
    }

    /// Get all detected cameras.
    pub fn cameras(&self) -> &[CameraInfo] {
        &self.cameras
    }

    /// Get count of detected cameras.
    pub fn count(&self) -> usize {
        self.cameras.len()
    }

    #[cfg(target_os = "linux")]
    fn refresh_linux(&mut self) -> Result<(), IronError> {
        // Enumerate /sys/class/video4linux/
        let v4l_path = std::path::Path::new("/sys/class/video4linux");
        if !v4l_path.exists() {
            // A real answer: no V4L2 subsystem, so no camera can be seen.
            return Ok(());
        }

        let entries = std::fs::read_dir(v4l_path)
            .map_err(|e| IronError::System(format!("cannot read /sys/class/video4linux: {e}")))?;
        for entry in entries.flatten() {
            let dev_name = entry.file_name().to_string_lossy().to_string();
            if !dev_name.starts_with("video") {
                continue;
            }
            let index: u32 = dev_name
                .strip_prefix("video")
                .and_then(|s| s.parse().ok())
                .unwrap_or(0);

            let base = entry.path();
            let name = std::fs::read_to_string(base.join("name"))
                .unwrap_or_default()
                .trim()
                .to_string();

            // Skip metadata / output-only devices
            // Check device capabilities via uevent
            let uevent = std::fs::read_to_string(base.join("uevent")).unwrap_or_default();
            if uevent.contains("DEVTYPE=video4linux-subdev") {
                continue;
            }

            let driver = Self::read_sysfs_link_name(&base.join("device/driver"));

            // Infer connection type from device path
            let dev_path_str = base.to_string_lossy().to_string();
            // `None` when no bus in the sysfs path matches. The old fallback was
            // `Unknown`, which is a value the ontology published as a measurement.
            let connection = if dev_path_str.contains("usb") {
                Some(CameraConnection::USB)
            } else if dev_path_str.contains("platform") || dev_path_str.contains("csi") {
                Some(CameraConnection::CSI)
            } else if name.to_lowercase().contains("virtual") || name.to_lowercase().contains("obs")
            {
                Some(CameraConnection::Virtual)
            } else if dev_path_str.contains("pci") {
                Some(CameraConnection::Internal)
            } else {
                None
            };

            let mut capabilities = vec![CameraCapability::VideoCapture];

            // Try to read supported formats from /dev/videoN. Capabilities are
            // derived from them only when they were read: with no list there is
            // no H264 or Z16 to find, and that is not the same as finding none.
            let dev_file = format!("/dev/{}", dev_name);
            let formats = Self::read_v4l2_formats(&dev_file);
            if let Some(list) = &formats {
                if list.iter().any(|f| f == "H264" || f == "HEVC") {
                    capabilities.push(CameraCapability::HardwareEncoding);
                }
                if list.iter().any(|f| f.contains("Z16") || f.contains("INZI")) {
                    capabilities.push(CameraCapability::DepthSensing);
                }
            }
            let infrared = infrared_from_formats(formats.as_deref());
            if infrared == Some(true) {
                capabilities.push(CameraCapability::Infrared);
            }

            // Try to infer vendor from USB path
            let vendor = Self::read_usb_vendor(&base);

            self.cameras.push(CameraInfo {
                // An unreadable name is `None`. The device node's name (`video0`)
                // used to stand in for it, which is an identifier, not a name.
                name: (!name.is_empty()).then_some(name),
                connection,
                device_path: dev_file,
                driver,
                vendor,
                max_width: 0, // Would need v4l2 ioctl to get actual max
                max_height: 0,
                formats,
                capabilities,
                infrared,
                is_active: Self::is_device_busy(&format!("/dev/{}", dev_name)),
                index,
            });
        }
        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn read_sysfs_link_name(path: &std::path::Path) -> String {
        std::fs::read_link(path)
            .ok()
            .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
            .unwrap_or_default()
    }

    /// The capture formats a V4L2 device offers, from `VIDIOC_ENUM_FMT`, which
    /// is asked for each index in turn until the driver answers `EINVAL`.
    ///
    /// `None` when the node cannot be opened, or the driver lists no capture
    /// format at index zero (a metadata node looks like that). No external tool
    /// is involved, so a missing `v4l2-ctl` is not a reason for a constant.
    #[cfg(target_os = "linux")]
    fn read_v4l2_formats(dev: &str) -> Option<Vec<String>> {
        use std::os::unix::io::AsRawFd;

        let file = std::fs::OpenOptions::new().read(true).open(dev).ok()?;
        let fd = file.as_raw_fd();
        let mut formats = Vec::new();
        for index in 0..V4L2_ENUM_FMT_LIMIT {
            let mut desc = V4l2Fmtdesc {
                index,
                buf_type: V4L2_BUF_TYPE_VIDEO_CAPTURE,
                ..Default::default()
            };
            // SAFETY: `desc` is a live `v4l2_fmtdesc`-sized struct for the whole
            // call, and `fd` stays open until `file` is dropped at the end of
            // this function.
            let rc = unsafe {
                libc::ioctl(
                    fd,
                    VIDIOC_ENUM_FMT as libc::c_ulong,
                    &mut desc as *mut V4l2Fmtdesc,
                )
            };
            if rc < 0 {
                // EINVAL after at least one format is how the driver ends the
                // list. Anything else, or EINVAL at index zero, is not a list.
                let end_of_list =
                    std::io::Error::last_os_error().raw_os_error() == Some(libc::EINVAL);
                return if end_of_list && index > 0 {
                    Some(formats)
                } else {
                    None
                };
            }
            formats.push(fourcc_to_string(desc.pixelformat));
        }
        // The driver never ran out of formats within the limit, so the list is
        // not one this reader can vouch for.
        None
    }

    #[cfg(target_os = "linux")]
    fn read_usb_vendor(base: &std::path::Path) -> Option<String> {
        // Walk up to find vendor info in USB hierarchy
        let mut path = base.to_path_buf();
        for _ in 0..5 {
            let vendor_path = path.join("manufacturer");
            if let Ok(v) = std::fs::read_to_string(&vendor_path) {
                let v = v.trim();
                if !v.is_empty() {
                    return Some(v.to_string());
                }
            }
            if !path.pop() {
                break;
            }
        }
        None
    }

    /// `Some(true)` when the open fails with EBUSY, `Some(false)` when it
    /// succeeds, and `None` for any other failure. A permission error on a
    /// device node says nothing about whether it is streaming; the old code
    /// read every such error as idle, which is the wrong answer for a privacy
    /// signal.
    #[cfg(target_os = "linux")]
    fn is_device_busy(dev: &str) -> Option<bool> {
        use std::fs::OpenOptions;
        match OpenOptions::new().read(true).open(dev) {
            Ok(_) => Some(false),
            Err(e) if e.raw_os_error() == Some(16) => Some(true), // EBUSY
            Err(_) => None,
        }
    }

    /// Whether any application is holding a camera open, from the capability
    /// access manager's consent store.
    ///
    /// Windows records a `LastUsedTimeStart` and `LastUsedTimeStop` per
    /// application under `CapabilityAccessManager\ConsentStore\webcam`, and a
    /// `LastUsedTimeStop` of zero means that application still has the device
    /// open. It is readable without elevation.
    ///
    /// The signal is per-application, not per-device, so it is used in one
    /// direction only: **if nothing at all is using a camera then no particular
    /// camera is streaming**, which is sound for every device. The converse is
    /// not -- one application streaming says nothing about which of several
    /// cameras it opened -- so a positive resolves to `None` rather than being
    /// spread across every camera on the machine.
    #[cfg(target_os = "windows")]
    fn camera_in_use_windows() -> Option<bool> {
        use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
        use winreg::RegKey;

        const STORE: &str = concat!(
            r"SOFTWARE\Microsoft\Windows\CurrentVersion",
            r"\CapabilityAccessManager\ConsentStore\webcam"
        );

        let mut saw_a_key = false;
        let mut any_open = false;

        for root in [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE] {
            let Ok(store) = RegKey::predef(root).open_subkey(STORE) else {
                continue;
            };
            // Packaged apps sit directly under the store; desktop programs sit
            // one level down under `NonPackaged`.
            let mut groups = vec![store];
            if let Ok(np) = groups[0].open_subkey("NonPackaged") {
                groups.push(np);
            }
            for group in &groups {
                for name in group.enum_keys().flatten() {
                    let Ok(app) = group.open_subkey(&name) else {
                        continue;
                    };
                    let Ok(stop) = app.get_value::<u64, _>("LastUsedTimeStop") else {
                        continue;
                    };
                    saw_a_key = true;
                    if stop == 0 {
                        any_open = true;
                    }
                }
            }
        }

        match (saw_a_key, any_open) {
            // Nothing has the device open, so nothing is streaming.
            (true, false) => Some(false),
            // Something is, but the store does not say which camera.
            (true, true) => None,
            // No consent store, or nothing has ever used a camera: no reading.
            (false, _) => None,
        }
    }

    #[cfg(target_os = "windows")]
    fn refresh_windows(&mut self) -> Result<(), IronError> {
        let in_use = Self::camera_in_use_windows();

        let json = crate::core::command::capture_json(
            "powershell",
            &["-NoProfile", "-Command",
                // `Image` is the PnP class for still-image devices --
                // scanners, and the scanner half of a multifunction printer.
                // Including it here made `ironmon` report a Brother MFC-L2900DW
                // as two cameras, which is not a camera enumeration that is
                // slightly too generous; it is a wrong answer to the question
                // "can this machine see". Windows 10 1703 and later put every
                // webcam under `Camera`, so nothing real is lost by asking only
                // for that.
                // `Service` is the driver bound to the device -- `usbvideo`
                // for both cameras on the development host, the direct
                // analogue of the `device/driver` symlink the Linux reader
                // follows to `uvcvideo`. It was not selected, so `driver` was
                // hardcoded empty and the ontology reported "reader returned
                // an empty string" for a column nobody had asked for.
                "Get-CimInstance Win32_PnPEntity | Where-Object { $_.PNPClass -eq 'Camera' } | Select-Object Name, Manufacturer, DeviceID, Status, PNPClass, Service | ConvertTo-Json -Compress"],
        )?;
        let Some(val) = json else {
            return Ok(());
        };
        let items = crate::core::command::json_items(&val);
        for (i, item) in items.iter().enumerate() {
            // A device with no Name keeps its place with the name unread. The old
            // fallback was the literal "Unknown Camera", which the ontology published.
            let name = item["Name"].as_str().map(str::to_string);
            let name_lower = name.as_deref().unwrap_or("").to_lowercase();
            let vendor = item["Manufacturer"]
                .as_str()
                .filter(|s| !s.trim().is_empty())
                .map(str::to_string);
            let device_id = item["DeviceID"].as_str().unwrap_or("").to_string();
            let lower = device_id.to_lowercase();
            let connection = if lower.contains("usb") {
                Some(CameraConnection::USB)
            } else if lower.contains("pci") {
                Some(CameraConnection::Internal)
            } else if name_lower.contains("virtual") || name_lower.contains("obs") {
                Some(CameraConnection::Virtual)
            } else {
                // Not established from the device ID. The old fallback called every
                // other camera Internal, including ones on buses this reader does not
                // recognise, and then `Unknown`, which is a value rather than an absence.
                None
            };

            self.cameras.push(CameraInfo {
                name,
                connection,
                device_path: device_id,
                driver: item["Service"].as_str().unwrap_or("").to_string(),
                vendor,
                // No reader on any platform fills these; see the absence
                // reason in `ontology::resolve`, which now says so instead of
                // reporting that the camera listed no modes.
                max_width: 0,
                max_height: 0,
                // Not read on Windows. The Media Foundation format list is not
                // queried here, and an empty list would claim the camera has none.
                formats: None,
                capabilities: vec![CameraCapability::VideoCapture],
                // Not read on Windows: the PnP record does not say whether a sensor is infrared.
                infrared: None,
                // See `camera_in_use_windows`: the negative is attributable
                // to every camera, the positive is not attributable to any.
                is_active: in_use,
                index: i as u32,
            });
        }
        Ok(())
    }

    #[cfg(target_os = "macos")]
    fn refresh_macos(&mut self) -> Result<(), IronError> {
        let text = crate::core::command::capture(
            "system_profiler",
            &["SPCameraDataType", "-detailLevel", "full"],
        )?;
        self.cameras = parse_macos_cameras(&text);
        Ok(())
    }
}

/// One device block from `system_profiler SPCameraDataType`, before it becomes
/// a [`CameraInfo`].
#[cfg(any(target_os = "macos", test))]
#[derive(Default)]
struct MacCameraBlock {
    name: String,
    model_id: String,
    unique_id: String,
    vendor: Option<String>,
}

/// Reads the cameras out of `system_profiler SPCameraDataType -detailLevel full`.
///
/// Every device goes through the same conversion, the last one included. The
/// last device used to be built by a separate branch that hard-coded
/// `Internal`, and it alone differed from the rest. Vendor is set only when the
/// output names one, and autofocus is not listed because nothing here reads it.
#[cfg(any(target_os = "macos", test))]
fn parse_macos_cameras(text: &str) -> Vec<CameraInfo> {
    let mut blocks: Vec<MacCameraBlock> = Vec::new();
    for line in text.lines() {
        let trimmed = line.trim();
        let is_attribute = ["Model ID:", "Unique ID:", "Manufacturer:"]
            .iter()
            .any(|key| trimmed.starts_with(key));
        if trimmed.ends_with(':')
            && !is_attribute
            && !trimmed.starts_with("Camera")
            && !trimmed.is_empty()
        {
            blocks.push(MacCameraBlock {
                name: trimmed.trim_end_matches(':').to_string(),
                ..Default::default()
            });
        } else if let Some(block) = blocks.last_mut() {
            if let Some(v) = trimmed.strip_prefix("Model ID:") {
                block.model_id = v.trim().to_string();
            } else if let Some(v) = trimmed.strip_prefix("Unique ID:") {
                block.unique_id = v.trim().to_string();
            } else if let Some(v) = trimmed.strip_prefix("Manufacturer:") {
                let v = v.trim();
                if !v.is_empty() {
                    block.vendor = Some(v.to_string());
                }
            }
        }
    }

    blocks
        .into_iter()
        .filter(|b| !b.name.is_empty())
        .enumerate()
        .map(|(i, b)| {
            // The bus is named only where the model string names it. A built-in
            // camera is not named as one, so it gets no connection rather than
            // `Internal`: the output does not separate it from other cameras.
            let model = b.model_id.to_lowercase();
            let connection = if model.contains("usb") {
                Some(CameraConnection::USB)
            } else if model.contains("virtual") {
                Some(CameraConnection::Virtual)
            } else {
                None
            };
            CameraInfo {
                name: Some(b.name),
                connection,
                device_path: b.unique_id,
                driver: String::new(),
                vendor: b.vendor,
                max_width: 0,
                max_height: 0,
                formats: None,
                capabilities: vec![CameraCapability::VideoCapture],
                infrared: None,
                is_active: None,
                index: i as u32,
            }
        })
        .collect()
}

impl Default for CameraMonitor {
    fn default() -> Self {
        Self::new().unwrap_or(Self {
            cameras: Vec::new(),
        })
    }
}

impl std::fmt::Display for CameraConnection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Internal => write!(f, "Internal"),
            Self::USB => write!(f, "USB"),
            Self::Network => write!(f, "Network"),
            Self::CSI => write!(f, "CSI/MIPI"),
            Self::Virtual => write!(f, "Virtual"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

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

    /// Constructing the monitor either enumerates or says why it could not.
    ///
    /// This asserted `is_ok()`, which was true by construction until 6.0.0
    /// because `refresh` could not fail. Now that it can, the contract is
    /// weaker and more useful: **whatever happens, the caller can tell which
    /// happened.** A failure has to carry a reason, because a reason is the
    /// whole difference between "this machine has none" and "nobody looked".
    #[test]
    fn test_camera_monitor_creation() {
        match CameraMonitor::new() {
            Ok(_monitor) => {}
            Err(e) => {
                let why = e.to_string();
                assert!(
                    why.len() > 10,
                    "enumeration failed without saying why: {why:?}"
                );
            }
        }
    }

    #[test]
    fn test_camera_monitor_default() {
        let monitor = CameraMonitor::default();
        let _ = monitor.cameras();
    }

    #[test]
    fn test_camera_info_resolution() {
        let cam = CameraInfo {
            name: Some("Test".into()),
            connection: Some(CameraConnection::USB),
            device_path: String::new(),
            driver: String::new(),
            vendor: None,
            max_width: 1920,
            max_height: 1080,
            formats: None,
            capabilities: Vec::new(),
            infrared: None,
            is_active: Some(false),
            index: 0,
        };
        assert_eq!(cam.resolution(), "1920x1080");
        assert!((cam.megapixels() - 2.0736).abs() < 0.01);
    }

    #[test]
    fn test_camera_serialization() {
        let cam = CameraInfo {
            name: Some("Test Camera".into()),
            connection: Some(CameraConnection::Internal),
            device_path: "/dev/video0".into(),
            driver: "uvcvideo".into(),
            vendor: Some("Logitech".into()),
            max_width: 1920,
            max_height: 1080,
            formats: Some(vec!["YUYV".into(), "MJPG".into()]),
            capabilities: vec![CameraCapability::VideoCapture],
            infrared: Some(false),
            is_active: Some(false),
            index: 0,
        };
        let json = serde_json::to_string(&cam).unwrap();
        assert!(json.contains("Test Camera"));
        let _: CameraInfo = serde_json::from_str(&json).unwrap();
    }

    /// The FourCC codes below are the little-endian `u32` values a driver
    /// returns in `v4l2_fmtdesc.pixelformat`, computed from the ASCII bytes.
    #[test]
    fn test_fourcc_spelling() {
        assert_eq!(fourcc_to_string(0x5659_5559), "YUYV");
        assert_eq!(fourcc_to_string(0x4750_4A4D), "MJPG");
        assert_eq!(fourcc_to_string(0x3436_3248), "H264");
        // Depth formats are space-padded to four bytes.
        assert_eq!(fourcc_to_string(0x2036_315A), "Z16");
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_v4l2_fmtdesc_matches_kernel_layout() {
        assert_eq!(std::mem::size_of::<V4l2Fmtdesc>(), 64);
        assert_eq!(std::mem::offset_of!(V4l2Fmtdesc, pixelformat), 44);
        assert_eq!(VIDIOC_ENUM_FMT, 0xC040_5602);
    }

    /// Shaped like `system_profiler SPCameraDataType -detailLevel full` output
    /// with a built-in camera first and a USB camera last. The USB camera is the
    /// one the old reader hard-coded as `Internal`.
    const MACOS_CAMERAS: &str = concat!(
        "Camera:\n",
        "\n",
        "    FaceTime HD Camera:\n",
        "\n",
        "      Model ID: FaceTime HD Camera\n",
        "      Unique ID: 3F2A0000000000000000000000000001\n",
        "\n",
        "    Logi C920 HD Pro Webcam:\n",
        "\n",
        "      Model ID: UVC Camera (046d:08e5) USB\n",
        "      Unique ID: 0x14100000046d08e5\n",
        "      Manufacturer: Logitech\n",
    );

    #[test]
    fn test_macos_camera_parse_keeps_every_device_on_one_path() {
        let cams = parse_macos_cameras(MACOS_CAMERAS);
        assert_eq!(cams.len(), 2);

        assert_eq!(cams[0].name.as_deref(), Some("FaceTime HD Camera"));
        assert_eq!(cams[0].index, 0);
        // Nothing in the output names a bus for the built-in camera, so it is not
        // called Internal.
        assert_eq!(cams[0].connection, None);
        assert_eq!(cams[0].device_path, "3F2A0000000000000000000000000001");

        // The last device gets the same connection rule as the rest.
        assert_eq!(cams[1].name.as_deref(), Some("Logi C920 HD Pro Webcam"));
        assert_eq!(cams[1].index, 1);
        assert_eq!(cams[1].connection, Some(CameraConnection::USB));
        assert_eq!(cams[1].device_path, "0x14100000046d08e5");
    }

    #[test]
    fn test_macos_camera_vendor_is_only_what_the_output_names() {
        let cams = parse_macos_cameras(MACOS_CAMERAS);
        // No manufacturer line: unknown, not "Apple".
        assert_eq!(cams[0].vendor, None);
        assert_eq!(cams[1].vendor.as_deref(), Some("Logitech"));
    }

    #[test]
    fn test_macos_camera_does_not_claim_autofocus() {
        for cam in parse_macos_cameras(MACOS_CAMERAS) {
            assert_eq!(cam.capabilities, vec![CameraCapability::VideoCapture]);
            assert_eq!(cam.is_active, None);
            assert_eq!(cam.infrared, None);
        }
    }

    fn formats(list: &[&str]) -> Vec<String> {
        list.iter().map(|f| f.to_string()).collect()
    }

    /// A colour webcam offers YUYV and MJPG; it is not infrared.
    #[test]
    fn test_infrared_colour_formats_mean_not_infrared() {
        let f = formats(&["YUYV", "MJPG"]);
        assert_eq!(infrared_from_formats(Some(&f)), Some(false));
        let mixed = formats(&["GREY", "YUYV"]);
        assert_eq!(infrared_from_formats(Some(&mixed)), Some(false));
    }

    /// An IR sensor offers only luminance formats, whatever its name says.
    #[test]
    fn test_infrared_luminance_only_formats_mean_infrared() {
        let grey = formats(&["GREY"]);
        assert_eq!(infrared_from_formats(Some(&grey)), Some(true));
        let y8_y16 = formats(&["Y8", "Y16"]);
        assert_eq!(infrared_from_formats(Some(&y8_y16)), Some(true));
    }

    /// A depth sensor offers Z16 and no colour. It is not called infrared, and
    /// nothing here establishes that it is not.
    #[test]
    fn test_infrared_depth_only_is_unknown() {
        let depth = formats(&["Z16"]);
        assert_eq!(infrared_from_formats(Some(&depth)), None);
        let depth_and_grey = formats(&["Z16", "GREY"]);
        assert_eq!(infrared_from_formats(Some(&depth_and_grey)), None);
    }

    /// No list read, or an empty one, establishes nothing.
    #[test]
    fn test_infrared_without_a_format_list_is_unknown() {
        assert_eq!(infrared_from_formats(None), None);
        assert_eq!(infrared_from_formats(Some(&[])), None);
    }

    #[test]
    fn test_macos_camera_parse_of_empty_output_is_empty() {
        assert!(parse_macos_cameras("Camera:\n\n").is_empty());
    }
}