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
//! EDID 1.x block decoder.
//!
//! EDID (Extended Display Identification Data) is the 128-byte block monitors
//! return over DDC. The header at byte 0 is the fixed magic
//! `00 FF FF FF FF FF FF 00`. Subsequent fields encode manufacturer (PNP
//! code), product code, manufacture date, EDID version, established and
//! standard timings, four detailed timing descriptors, and an extension
//! count.
//!
//! Sources:
//! - Linux: `/sys/class/drm/card*-*/edid` (binary blob, 128 or 256+ bytes
//!   depending on extension blocks).
//! - Windows: SetupDi / `MonitorManufacturer`/`EDID` registry value under
//!   `HKLM\SYSTEM\CurrentControlSet\Enum\DISPLAY\*\*\Device Parameters\EDID`.

use super::{ProfileGroup, ScanOutcome, Setting, SettingRisk, SettingValue, Subsystem};

const EDID_MAGIC: [u8; 8] = [0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00];

/// Scan platform-specific sources and return one [`ProfileGroup`] per EDID
/// block found.
///
/// `Err` when the display source itself could not be opened, so nothing was
/// read. A monitor whose block could not be read is named in `unread`. A
/// connector or instance that stores no EDID is simply absent.
pub fn scan_edid_groups() -> Result<ScanOutcome, String> {
    #[cfg(target_os = "linux")]
    {
        let mut out = ScanOutcome::default();
        linux_scan(&mut out)?;
        Ok(out)
    }
    #[cfg(windows)]
    {
        let mut out = ScanOutcome::default();
        windows_scan(&mut out)?;
        Ok(out)
    }
    #[cfg(not(any(target_os = "linux", windows)))]
    {
        Err("EDID is not read on this platform".into())
    }
}

/// Decide what one raw EDID blob means. An empty blob is a connector that
/// stores no EDID (typically one with nothing attached), so `Ok(None)`. Bytes
/// that are present but are not an EDID block are `Err`, not a missing monitor.
#[cfg_attr(not(any(target_os = "linux", windows, test)), allow(dead_code))]
fn classify_block(
    bytes: &[u8],
    source: &str,
    locator: &str,
) -> Result<Option<ProfileGroup>, String> {
    if bytes.is_empty() {
        return Ok(None);
    }
    decode_block(bytes, source.to_string(), locator.to_string())
        .map(Some)
        .ok_or_else(|| {
            format!(
                "{} bytes are not an EDID block (bad header, or shorter than 128 bytes)",
                bytes.len()
            )
        })
}

#[cfg(target_os = "linux")]
fn linux_scan(out: &mut ScanOutcome) -> Result<(), String> {
    use std::fs;
    let drm = "/sys/class/drm";
    let rd = fs::read_dir(drm).map_err(|e| format!("cannot list {drm}: {e}"))?;
    for entry in rd {
        let entry = match entry {
            Ok(entry) => entry,
            Err(e) => {
                out.unread.push(format!("{drm}: {e}"));
                continue;
            }
        };
        let edid = entry.path().join("edid");
        // A connector without an edid file has no block to read.
        if !edid.exists() {
            continue;
        }
        let locator = entry.file_name().to_string_lossy().to_string();
        let source = edid.display().to_string();
        match fs::read(&edid) {
            Ok(bytes) => match classify_block(&bytes, &source, &locator) {
                Ok(Some(group)) => out.groups.push(group),
                Ok(None) => {}
                Err(reason) => out.unread.push(format!("{source}: {reason}")),
            },
            Err(e) => out.unread.push(format!("{source}: {e}")),
        }
    }
    Ok(())
}

#[cfg(windows)]
fn windows_scan(out: &mut ScanOutcome) -> Result<(), String> {
    use std::io::ErrorKind;
    use winreg::enums::*;
    use winreg::RegKey;
    let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
    let display = hklm
        .open_subkey(r"SYSTEM\CurrentControlSet\Enum\DISPLAY")
        .map_err(|e| format!(r"cannot open HKLM\SYSTEM\CurrentControlSet\Enum\DISPLAY: {e}"))?;
    let live = live_monitor_keys();
    for mfg in display.enum_keys() {
        let mfg = match mfg {
            Ok(mfg) => mfg,
            Err(e) => {
                out.unread.push(format!(r"Enum\DISPLAY: {e}"));
                continue;
            }
        };
        let mfg_key = match display.open_subkey(&mfg) {
            Ok(key) => key,
            Err(e) => {
                out.unread.push(format!(r"Enum\DISPLAY\{mfg}: {e}"));
                continue;
            }
        };
        for inst in mfg_key.enum_keys() {
            let inst = match inst {
                Ok(inst) => inst,
                Err(e) => {
                    out.unread.push(format!(r"Enum\DISPLAY\{mfg}: {e}"));
                    continue;
                }
            };
            let label = format!("{}/{}", mfg, inst);
            let dev = match mfg_key.open_subkey(format!("{}\\Device Parameters", inst)) {
                Ok(dev) => dev,
                // No Device Parameters key: this instance stores no EDID.
                Err(e) if e.kind() == ErrorKind::NotFound => continue,
                Err(e) => {
                    out.unread
                        .push(format!(r"Enum\DISPLAY\{label}\Device Parameters: {e}"));
                    continue;
                }
            };
            let bytes = match dev.get_raw_value("EDID") {
                Ok(value) => value.bytes,
                Err(e) if e.kind() == ErrorKind::NotFound => continue,
                Err(e) => {
                    out.unread.push(format!(r"Enum\DISPLAY\{label}\EDID: {e}"));
                    continue;
                }
            };
            let source = format!(r"HKLM\SYSTEM\CurrentControlSet\Enum\DISPLAY\{}", label);
            match classify_block(&bytes, &source, &label) {
                Ok(Some(mut group)) => {
                    // Enum\DISPLAY keeps every monitor ever attached. Only the
                    // live list says which are attached now.
                    match &live {
                        Some(keys) if !keys.contains(&label.to_ascii_uppercase()) => group.note(
                            "Not attached now: Enum\\DISPLAY keeps monitors that were connected before, and this one is not in the live display list.",
                        ),
                        Some(_) => {}
                        None => group.note(
                            "The live display list could not be read, so whether this monitor is attached now is unknown.",
                        ),
                    }
                    out.groups.push(group);
                }
                Ok(None) => {}
                Err(reason) => out.unread.push(format!("{source}: {reason}")),
            }
        }
    }
    Ok(())
}

/// The `MFG/INSTANCE` key of a monitor interface path, in the form used under
/// `Enum\DISPLAY`. For example, `\\?\DISPLAY#GSM5B09#5&2a4b8b5&0&UID12345#{guid}`
/// gives `GSM5B09/5&2A4B8B5&0&UID12345`.
#[cfg_attr(not(any(windows, test)), allow(dead_code))]
fn enum_display_key(device_path: &str) -> Option<String> {
    let mut parts = device_path.split('#');
    let _prefix = parts.next()?;
    let mfg = parts.next()?;
    let inst = parts.next()?;
    if mfg.is_empty() || inst.is_empty() {
        return None;
    }
    Some(format!("{}/{}", mfg, inst).to_ascii_uppercase())
}

/// Keys of the monitors attached now: the active monitor devices under every
/// display adapter. `None` when no adapter could be enumerated, so presence is
/// unknown rather than "nothing attached".
#[cfg(windows)]
fn live_monitor_keys() -> Option<std::collections::HashSet<String>> {
    use windows::core::PCWSTR;
    use windows::Win32::Graphics::Gdi::{EnumDisplayDevicesW, DISPLAY_DEVICEW};

    /// `DISPLAY_DEVICE_ACTIVE`
    const MONITOR_ACTIVE: u32 = 0x0000_0001;
    /// `EDD_GET_DEVICE_INTERFACE_NAME`: the monitor DeviceID is its interface path.
    const GET_DEVICE_INTERFACE_NAME: u32 = 0x0000_0001;

    let mut keys = std::collections::HashSet::new();
    let mut adapters = 0u32;
    let mut a = 0u32;
    loop {
        let mut adapter = DISPLAY_DEVICEW {
            cb: std::mem::size_of::<DISPLAY_DEVICEW>() as u32,
            ..Default::default()
        };
        if !unsafe { EnumDisplayDevicesW(None, a, &mut adapter, 0) }.as_bool() {
            break;
        }
        a += 1;
        adapters += 1;
        let mut m = 0u32;
        loop {
            let mut mon = DISPLAY_DEVICEW {
                cb: std::mem::size_of::<DISPLAY_DEVICEW>() as u32,
                ..Default::default()
            };
            let adapter_name = PCWSTR(adapter.DeviceName.as_ptr());
            let found = unsafe {
                EnumDisplayDevicesW(adapter_name, m, &mut mon, GET_DEVICE_INTERFACE_NAME)
            }
            .as_bool();
            if !found {
                break;
            }
            m += 1;
            if mon.StateFlags & MONITOR_ACTIVE == 0 {
                continue;
            }
            let end = mon
                .DeviceID
                .iter()
                .position(|c| *c == 0)
                .unwrap_or(mon.DeviceID.len());
            let path = String::from_utf16_lossy(&mon.DeviceID[..end]);
            if let Some(key) = enum_display_key(&path) {
                keys.insert(key);
            }
        }
    }
    (adapters > 0).then_some(keys)
}

pub fn decode_block(bytes: &[u8], source: String, locator: String) -> Option<ProfileGroup> {
    if bytes.len() < 128 {
        return None;
    }
    if bytes[..8] != EDID_MAGIC {
        return None;
    }

    let mfg = decode_pnp(&bytes[8..10]);
    let product_code = u16::from_le_bytes([bytes[10], bytes[11]]);
    let serial_id = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]);
    let week = bytes[16];
    let year = bytes[17] as u16 + 1990;
    let edid_major = bytes[18];
    let edid_minor = bytes[19];
    let video_input = bytes[20];
    let digital = (video_input & 0x80) != 0;
    let max_h_cm = bytes[21];
    let max_v_cm = bytes[22];
    let gamma_raw = bytes[23];
    let gamma = (gamma_raw as f64 + 100.0) / 100.0;
    let features = bytes[24];
    let dpms_standby = (features & 0x80) != 0;
    let dpms_suspend = (features & 0x40) != 0;
    let dpms_active_off = (features & 0x20) != 0;
    let display_type = (features >> 3) & 0x3;
    let display_type_str = if digital {
        match display_type {
            0 => "RGB 4:4:4",
            1 => "RGB 4:4:4 + YCrCb 4:4:4",
            2 => "RGB 4:4:4 + YCrCb 4:2:2",
            _ => "RGB 4:4:4 + YCrCb 4:4:4 + YCrCb 4:2:2",
        }
    } else {
        match display_type {
            0 => "Monochrome",
            1 => "RGB color",
            2 => "Non-RGB color",
            _ => "Undefined",
        }
    };
    let monitor_name = read_monitor_name_descriptor(bytes);
    let preferred = read_preferred_timing(bytes);

    let label = monitor_name
        .clone()
        .unwrap_or_else(|| format!("{} {:04X}", mfg, product_code));
    let mut group = ProfileGroup::new(
        Subsystem::Display,
        format!("EDID: {} — {}", locator, label),
        format!("EDID {}.{}", edid_major, edid_minor),
        source,
    );

    group.push(Setting::info(
        "edid.manufacturer",
        "Manufacturer (PNP)",
        SettingValue::Text(mfg),
    ));
    group.push(Setting::info(
        "edid.product_code",
        "Product Code",
        SettingValue::Uint(product_code as u64),
    ));
    if serial_id != 0 {
        group.push(Setting::info(
            "edid.serial_id",
            "Serial ID",
            SettingValue::Uint(serial_id as u64),
        ));
    }
    if let Some(name) = monitor_name {
        group.push(Setting::info(
            "edid.monitor_name",
            "Monitor Name",
            SettingValue::Text(name),
        ));
    }
    if let Some(text) = manufactured_text(week, year) {
        group.push(Setting::info(
            "edid.manufactured",
            "Manufactured",
            SettingValue::Text(text),
        ));
    }
    group.push(Setting::info(
        "edid.signal",
        "Video Signal",
        SettingValue::Text(if digital {
            "Digital".into()
        } else {
            "Analog".into()
        }),
    ));
    group.push(Setting::info(
        "edid.display_type",
        "Display Type",
        SettingValue::Text(display_type_str.into()),
    ));
    if max_h_cm > 0 && max_v_cm > 0 {
        group.push(Setting::info(
            "edid.max_image_size",
            "Max Image Size",
            SettingValue::Text(format!("{} × {} cm", max_h_cm, max_v_cm)),
        ));
    }
    if gamma_raw != 0xFF {
        group.push(
            Setting::info("edid.gamma", "Gamma", SettingValue::Float(gamma))
                .with_description("Display transfer characteristic. 2.2 is sRGB."),
        );
    }
    group.push(Setting::info(
        "edid.dpms_standby",
        "DPMS Standby Supported",
        SettingValue::Bool(dpms_standby),
    ));
    group.push(Setting::info(
        "edid.dpms_suspend",
        "DPMS Suspend Supported",
        SettingValue::Bool(dpms_suspend),
    ));
    group.push(Setting::info(
        "edid.dpms_active_off",
        "DPMS Active-Off Supported",
        SettingValue::Bool(dpms_active_off),
    ));
    if let Some((h, v, refresh_hz, interlaced)) = preferred {
        group.push(
            Setting::info(
                "edid.preferred_timing",
                "Preferred Native Timing",
                SettingValue::Text(format!(
                    "{}×{}{} @ {:.2} Hz",
                    h,
                    v,
                    if interlaced { "i" } else { "" },
                    refresh_hz
                )),
            )
            .with_description(concat!(
                "First Detailed Timing Descriptor — manufacturer's ",
                "recommended mode. An `i` marks an interlaced mode, whose ",
                "line count the descriptor stores per field and which is ",
                "doubled here to whole frames."
            ))
            .with_risk(SettingRisk::Safe),
        );
    }
    let ext_count = bytes[126];
    group.push(Setting::info(
        "edid.extension_blocks",
        "Extension Blocks",
        SettingValue::Uint(ext_count as u64),
    ));
    Some(group)
}

/// Decode the 3-letter PNP manufacturer code from two big-endian bytes.
/// Each letter is a 5-bit value with 'A' = 1.
fn decode_pnp(b: &[u8]) -> String {
    if b.len() < 2 {
        return "???".into();
    }
    let word = ((b[0] as u16) << 8) | b[1] as u16;
    let a = ((word >> 10) & 0x1F) as u8;
    let b2 = ((word >> 5) & 0x1F) as u8;
    let c = (word & 0x1F) as u8;
    fn ch(v: u8) -> char {
        if v == 0 {
            '?'
        } else {
            (b'A' + v - 1) as char
        }
    }
    format!("{}{}{}", ch(a), ch(b2), ch(c))
}

/// Walk the four 18-byte detailed-timing/monitor-descriptor blocks at
/// offsets 54..72..90..108 and return the monitor name (descriptor type
/// `0xFC`) if present.
fn read_monitor_name_descriptor(bytes: &[u8]) -> Option<String> {
    for off in [54usize, 72, 90, 108] {
        if off + 18 > bytes.len() {
            continue;
        }
        let block = &bytes[off..off + 18];
        // A descriptor (not a detailed timing) has first two bytes = 00 00.
        if block[0] == 0 && block[1] == 0 && block[3] == 0xFC {
            let raw = &block[5..18];
            let mut s = String::new();
            for &b in raw {
                if b == 0x0A {
                    break;
                }
                if (0x20..0x7F).contains(&b) {
                    s.push(b as char);
                }
            }
            let trimmed = s.trim().to_string();
            if !trimmed.is_empty() {
                return Some(trimmed);
            }
        }
    }
    None
}

/// Decode the first Detailed Timing Descriptor at offset 54 (the
/// manufacturer-preferred / native mode). Returns (h_active, v_active, refresh_hz).
/// The first Detailed Timing Descriptor: active pixels, refresh, and whether the
/// mode is interlaced.
///
/// The interlace flag is not decoration. For an interlaced timing the spec stores
/// **vertical active as lines per field**, so a 1080i mode carries 540 in the
/// DTD. Ignoring the flag reported an AV receiver on this machine as
/// `1920×540 @ 60.05 Hz` — a resolution no equipment has — where the real mode
/// is 1920×1080 interlaced at a 60 Hz field rate. The frame lines are what a
/// reader means by a resolution, so they are what is returned, with the flag
/// alongside so the caller can say which it is.
fn read_preferred_timing(bytes: &[u8]) -> Option<(u32, u32, f64, bool)> {
    if bytes.len() < 72 {
        return None;
    }
    let dtd = &bytes[54..72];
    // Bytes 0-1: pixel clock in 10 kHz units (little-endian). 0 => monitor descriptor.
    let pixel_clock_khz = (u16::from_le_bytes([dtd[0], dtd[1]]) as u32) * 10;
    if pixel_clock_khz == 0 {
        return None;
    }
    let h_active_lo = dtd[2] as u32;
    let h_blank_lo = dtd[3] as u32;
    let h_active_hi = ((dtd[4] >> 4) & 0xF) as u32;
    let h_blank_hi = (dtd[4] & 0xF) as u32;
    let h_active = (h_active_hi << 8) | h_active_lo;
    let h_blank = (h_blank_hi << 8) | h_blank_lo;

    let v_active_lo = dtd[5] as u32;
    let v_blank_lo = dtd[6] as u32;
    let v_active_hi = ((dtd[7] >> 4) & 0xF) as u32;
    let v_blank_hi = (dtd[7] & 0xF) as u32;
    let v_active = (v_active_hi << 8) | v_active_lo;
    let v_blank = (v_blank_hi << 8) | v_blank_lo;

    let h_total = h_active + h_blank;
    let v_total = v_active + v_blank;
    if h_total == 0 || v_total == 0 {
        return None;
    }
    let refresh = (pixel_clock_khz as f64 * 1000.0) / (h_total as f64 * v_total as f64);

    // Byte 17 bit 7. The refresh computed above is the field rate for an
    // interlaced mode, which is the number equipment is labelled with — 1080i60
    // means sixty fields — so it is left as it is and only the line count is
    // doubled back to whole frames.
    let interlaced = (dtd[17] & 0x80) != 0;
    let v_frame = if interlaced { v_active * 2 } else { v_active };

    Some((h_active, v_frame, refresh, interlaced))
}

/// Text for the EDID manufacture date. Byte 16 is the week of manufacture
/// (1-54), 0 when the week is unspecified, or 0xFF when byte 17 is a model
/// year rather than a manufacture year. This used to print 0xFF as
/// "week 255 of <year>".
fn manufactured_text(week: u8, year: u16) -> Option<String> {
    match week {
        0xFF => Some(format!("model year {}", year)),
        0 if year > 1990 => Some(format!("year {} (week unspecified)", year)),
        0 => None,
        w => Some(format!("week {} of {}", w, year)),
    }
}

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

    #[test]
    fn manufactured_week_model_year_and_unspecified() {
        assert_eq!(
            manufactured_text(10, 2024).as_deref(),
            Some("week 10 of 2024")
        );
        // 0xFF is the model-year flag, not a week.
        assert_eq!(
            manufactured_text(0xFF, 2024).as_deref(),
            Some("model year 2024")
        );
        // Week 0 means unspecified: the year is still reported, the week is not.
        assert_eq!(
            manufactured_text(0, 2024).as_deref(),
            Some("year 2024 (week unspecified)")
        );
        assert_eq!(manufactured_text(0, 1990), None);
    }

    fn synth_edid(name: &str, h: u32, v: u32, pclk_khz: u32) -> Vec<u8> {
        let mut b = vec![0u8; 128];
        b[..8].copy_from_slice(&EDID_MAGIC);
        // Manufacturer = "ABC": A=1,B=2,C=3 → bits 1<<10 | 2<<5 | 3
        let mfg_word: u16 = (1 << 10) | (2 << 5) | 3;
        b[8] = (mfg_word >> 8) as u8;
        b[9] = (mfg_word & 0xFF) as u8;
        b[10] = 0x42;
        b[11] = 0x00;
        b[16] = 10; // week
        b[17] = 34; // year offset → 2024
        b[18] = 1; // major
        b[19] = 4; // minor
        b[20] = 0x80; // digital input
        b[21] = 60; // 60 cm wide
        b[22] = 34; // 34 cm tall
        b[23] = (2.2 * 100.0 - 100.0) as u8; // gamma 2.2
        b[24] = 0xE0; // all DPMS bits

        // DTD at offset 54
        let pclk_units = (pclk_khz / 10) as u16;
        b[54] = (pclk_units & 0xFF) as u8;
        b[55] = (pclk_units >> 8) as u8;
        b[56] = (h & 0xFF) as u8;
        b[57] = 0x00; // h blank lo (= 0 for simplicity)
        b[58] = (((h >> 8) & 0xF) << 4) as u8;
        b[59] = (v & 0xFF) as u8;
        b[60] = 0x00;
        b[61] = (((v >> 8) & 0xF) << 4) as u8;

        // Monitor name descriptor at offset 72
        b[72] = 0x00;
        b[73] = 0x00;
        b[74] = 0x00;
        b[75] = 0xFC;
        b[76] = 0x00;
        let n = name.as_bytes();
        for (i, &c) in n.iter().take(13).enumerate() {
            b[77 + i] = c;
        }
        if n.len() < 13 {
            b[77 + n.len()] = 0x0A;
        }
        b
    }

    /// An interlaced mode reports whole frames, not fields.
    ///
    /// The bytes below are the real first DTD from a Yamaha RX-A740 read out of
    /// this machine's registry, not a synthesised one — a fixture built by the
    /// same hand as the parser is what let four NVMe SMART fields ship sixteen
    /// bytes out of place. Decoded against the EDID specification it is
    /// 1920 active pixels, 540 lines *per field*, pixel clock 74.25 MHz, flags
    /// byte 0x9E with bit 7 set for interlace: 1080i60.
    ///
    /// Before the flag was read this reported `1920×540`, a resolution no
    /// equipment has.
    #[test]
    fn an_interlaced_mode_reports_frame_lines_not_field_lines() {
        const RX_A740_DTD: [u8; 18] = [
            0x01, 0x1D, 0x80, 0x18, 0x71, 0x1C, 0x16, 0x20, 0x58, 0x2C, 0x25, 0x00, 0xC4, 0x8E,
            0x21, 0x00, 0x00, 0x9E,
        ];

        let mut b = synth_edid("RX-A740", 1920, 1080, 74_250);
        b[54..72].copy_from_slice(&RX_A740_DTD);

        let (h, v, refresh, interlaced) = read_preferred_timing(&b).expect("a timing");
        assert_eq!(h, 1920);
        assert_eq!(
            v, 1080,
            "540 field lines must be reported as 1080 frame lines"
        );
        assert!(interlaced, "flags byte 0x9E has bit 7 set");
        // 74.25 MHz over 2200 × 562 is the field rate, which is what 1080i60 names.
        assert!(
            (refresh - 60.05).abs() < 0.05,
            "field rate was {refresh}, expected ~60.05"
        );

        let g = decode_block(&b, "test".into(), "hdmi".into()).expect("decodes");
        let shown = g
            .settings
            .iter()
            .find(|s| s.id == "edid.preferred_timing")
            .map(|s| s.value.to_string())
            .expect("preferred timing is published");
        assert!(
            shown.contains("1920×1080i"),
            "an interlaced mode must be marked as one, got {shown:?}"
        );
    }

    /// A progressive mode is left alone by the same code path.
    #[test]
    fn a_progressive_mode_is_not_doubled() {
        let b = synth_edid("Test Display", 2560, 1440, 241_500);
        let (h, v, _, interlaced) = read_preferred_timing(&b).expect("a timing");
        assert_eq!((h, v), (2560, 1440));
        assert!(!interlaced);
    }

    #[test]
    fn detects_magic_and_pnp() {
        let b = synth_edid("Test Display", 2560, 1440, 241_500);
        let g = decode_block(&b, "test".into(), "card0".into()).unwrap();
        let mfg = g
            .settings
            .iter()
            .find(|s| s.id == "edid.manufacturer")
            .unwrap();
        assert!(matches!(&mfg.value, SettingValue::Text(t) if t == "ABC"));
    }

    #[test]
    fn extracts_monitor_name() {
        let b = synth_edid("DELL U2723QE", 3840, 2160, 533_250);
        let g = decode_block(&b, "test".into(), "card0".into()).unwrap();
        let name = g
            .settings
            .iter()
            .find(|s| s.id == "edid.monitor_name")
            .unwrap();
        assert!(matches!(&name.value, SettingValue::Text(t) if t.contains("DELL")));
    }

    #[test]
    fn decodes_preferred_timing() {
        // 2560x1440 with pclk such that refresh ≈ 60 Hz when h_total≈h_active, v_total≈v_active
        let b = synth_edid("Mon", 2560, 1440, 220_000);
        let g = decode_block(&b, "test".into(), "card0".into()).unwrap();
        let t = g
            .settings
            .iter()
            .find(|s| s.id == "edid.preferred_timing")
            .unwrap();
        if let SettingValue::Text(s) = &t.value {
            assert!(s.contains("2560×1440"));
        } else {
            panic!("expected text");
        }
    }

    #[test]
    fn rejects_bad_magic() {
        let b = vec![0u8; 128];
        assert!(decode_block(&b, "test".into(), "card0".into()).is_none());
    }

    #[test]
    fn enum_display_key_matches_registry_instance() {
        let path =
            r"\\?\DISPLAY#GSM5B09#5&2a4b8b5&0&UID12345#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}";
        assert_eq!(
            enum_display_key(path).as_deref(),
            Some("GSM5B09/5&2A4B8B5&0&UID12345")
        );
    }

    #[test]
    fn an_empty_blob_is_no_monitor_not_a_failed_read() {
        // A connector with nothing attached stores an empty EDID.
        assert!(classify_block(&[], "src", "card0-HDMI-A-1")
            .unwrap()
            .is_none());
    }

    #[test]
    fn bytes_that_are_not_an_edid_block_are_unread() {
        let err = classify_block(&[0u8; 128], "src", "card0-DP-1").unwrap_err();
        assert!(
            err.contains("128 bytes are not an EDID block"),
            "got {err:?}"
        );
        let short = classify_block(&[0x00, 0xFF, 0xFF], "src", "card0-DP-2").unwrap_err();
        assert!(short.contains("3 bytes"), "got {short:?}");
    }

    #[test]
    fn a_valid_block_classifies_to_its_group() {
        let b = synth_edid("DELL U2723QE", 3840, 2160, 533_250);
        let g = classify_block(&b, "src", "card0-DP-1")
            .unwrap()
            .expect("a monitor group");
        assert!(g.device.contains("card0-DP-1"));
        assert!(g.device.contains("DELL U2723QE"));
    }

    #[test]
    fn enum_display_key_rejects_short_paths() {
        assert_eq!(enum_display_key(r"\\?\DISPLAY"), None);
        assert_eq!(enum_display_key(r"\\?\DISPLAY##{guid}"), None);
    }
}