use super::{ProfileGroup, ScanOutcome, Setting, SettingRisk, SettingValue, Subsystem};
const EDID_MAGIC: [u8; 8] = [0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00];
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())
}
}
#[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");
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,
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)) => {
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(())
}
#[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())
}
#[cfg(windows)]
fn live_monitor_keys() -> Option<std::collections::HashSet<String>> {
use windows::core::PCWSTR;
use windows::Win32::Graphics::Gdi::{EnumDisplayDevicesW, DISPLAY_DEVICEW};
const MONITOR_ACTIVE: u32 = 0x0000_0001;
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)
}
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))
}
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];
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
}
fn read_preferred_timing(bytes: &[u8]) -> Option<(u32, u32, f64, bool)> {
if bytes.len() < 72 {
return None;
}
let dtd = &bytes[54..72];
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);
let interlaced = (dtd[17] & 0x80) != 0;
let v_frame = if interlaced { v_active * 2 } else { v_active };
Some((h_active, v_frame, refresh, interlaced))
}
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")
);
assert_eq!(
manufactured_text(0xFF, 2024).as_deref(),
Some("model year 2024")
);
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);
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; b[17] = 34; b[18] = 1; b[19] = 4; b[20] = 0x80; b[21] = 60; b[22] = 34; b[23] = (2.2 * 100.0 - 100.0) as u8; b[24] = 0xE0;
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; 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;
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
}
#[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");
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:?}"
);
}
#[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() {
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() {
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);
}
}