| 1 |
"""Retrieve and parse EDID (Extended Display Identification Data) from various OSes. |
| 2 |
|
| 3 |
It includes methods for fetching EDID data from Windows, macOS, and other |
| 4 |
platforms, as well as parsing the EDID data into a structured format. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import binascii |
| 10 |
import contextlib |
| 11 |
import json |
| 12 |
import math |
| 13 |
import os |
| 14 |
import re |
| 15 |
import string |
| 16 |
import struct |
| 17 |
import subprocess |
| 18 |
import sys |
| 19 |
from hashlib import md5 |
| 20 |
|
| 21 |
if sys.platform == "win32": |
| 22 |
import threading |
| 23 |
|
| 24 |
# Use registry as fallback for Win2k/XP/2003 |
| 25 |
import winreg |
| 26 |
|
| 27 |
from DisplayCAL import util_win |
| 28 |
|
| 29 |
wmi = None |
| 30 |
if sys.getwindowsversion() >= (6,): |
| 31 |
# Use WMI for Vista/Win7 |
| 32 |
import pythoncom |
| 33 |
|
| 34 |
with contextlib.suppress(ImportError): |
| 35 |
import wmi |
| 36 |
else: |
| 37 |
# Use registry as fallback for Win2k/XP/2003 |
| 38 |
import winreg |
| 39 |
|
| 40 |
from DisplayCAL import config, real_display_size_mm |
| 41 |
from DisplayCAL.util_os import which |
| 42 |
from DisplayCAL.util_str import safe_str |
| 43 |
|
| 44 |
HEADER = (0, 8) |
| 45 |
MANUFACTURER_ID = (8, 10) |
| 46 |
PRODUCT_ID = (10, 12) |
| 47 |
SERIAL_32 = (12, 16) |
| 48 |
WEEK_OF_MANUFACTURE = 16 |
| 49 |
YEAR_OF_MANUFACTURE = 17 |
| 50 |
EDID_VERSION = 18 |
| 51 |
EDID_REVISION = 19 |
| 52 |
MAX_H_SIZE_CM = 21 |
| 53 |
MAX_V_SIZE_CM = 22 |
| 54 |
GAMMA = 23 |
| 55 |
FEATURES = 24 |
| 56 |
LO_RG_XY = 25 |
| 57 |
LO_BW_XY = 26 |
| 58 |
HI_R_X = 27 |
| 59 |
HI_R_Y = 28 |
| 60 |
HI_G_X = 29 |
| 61 |
HI_G_Y = 30 |
| 62 |
HI_B_X = 31 |
| 63 |
HI_B_Y = 32 |
| 64 |
HI_W_X = 33 |
| 65 |
HI_W_Y = 34 |
| 66 |
BLOCKS = ((54, 72), (72, 90), (90, 108), (108, 126)) |
| 67 |
BLOCK_TYPE = 3 |
| 68 |
BLOCK_CONTENTS = (5, 18) |
| 69 |
BLOCK_TYPE_SERIAL_ASCII = b"\xff" |
| 70 |
BLOCK_TYPE_ASCII = b"\xfe" |
| 71 |
BLOCK_TYPE_MONITOR_NAME = b"\xfc" |
| 72 |
BLOCK_TYPE_COLOR_POINT = b"\xfb" |
| 73 |
BLOCK_TYPE_COLOR_MANAGEMENT_DATA = b"\xf9" |
| 74 |
EXTENSION_FLAG = 126 |
| 75 |
CHECKSUM = 127 |
| 76 |
BLOCK_DI_EXT = b"\x40" |
| 77 |
TRC = (81, 127) |
| 78 |
|
| 79 |
PNP_ID_CACHE = {} |
| 80 |
|
| 81 |
|
| 82 |
def combine_hi_8lo(hi: int, lo: int) -> int: |
| 83 |
"""Combine two 8-bit values into a single 16-bit value. |
| 84 |
|
| 85 |
Args: |
| 86 |
hi (int): The high byte. |
| 87 |
lo (int): The low byte. |
| 88 |
|
| 89 |
Returns: |
| 90 |
int: The combined 16-bit value. |
| 91 |
""" |
| 92 |
return hi << 8 | lo |
| 93 |
|
| 94 |
|
| 95 |
def get_edid( |
| 96 |
display_no: int = 0, |
| 97 |
display_name: None | str = None, |
| 98 |
device: None | str = None, |
| 99 |
) -> dict: |
| 100 |
"""Get and parse EDID. Return dict. |
| 101 |
|
| 102 |
On all platforms, display_no (zero-based) is used for index-based lookup. |
| 103 |
On Mac OS X, display_name is tried first for name-based matching; if no |
| 104 |
name match is found, falls back to the display at position display_no. |
| 105 |
|
| 106 |
Args: |
| 107 |
display_no (int): The display number (zero-based). |
| 108 |
display_name (None | str): The display name (preferred match on macOS). |
| 109 |
device (None | str): The device identifier. |
| 110 |
|
| 111 |
Returns: |
| 112 |
dict: Parsed EDID data. |
| 113 |
""" |
| 114 |
edid = None |
| 115 |
if sys.platform == "win32": |
| 116 |
edid = get_edid_windows(display_no, device) |
| 117 |
elif sys.platform == "darwin": |
| 118 |
edid = get_edid_darwin(display_name, display_no) |
| 119 |
else: |
| 120 |
edid = get_edid_from_xrandr(display_no) |
| 121 |
|
| 122 |
if edid and len(edid) >= 128: |
| 123 |
return parse_edid(edid) |
| 124 |
|
| 125 |
return {} |
| 126 |
|
| 127 |
|
| 128 |
def get_edid_windows(display_no: int, device: str) -> bytes: |
| 129 |
"""Get EDID for a Windows display. |
| 130 |
|
| 131 |
Tries WMI first (Vista+), falls back to the registry on all versions. |
| 132 |
|
| 133 |
Args: |
| 134 |
display_no (int): The display number (zero-based). |
| 135 |
device (str): The device identifier. |
| 136 |
|
| 137 |
Raises: |
| 138 |
WMIError: If WMI is available but the query fails. |
| 139 |
|
| 140 |
Returns: |
| 141 |
bytes: The EDID data. |
| 142 |
""" |
| 143 |
edid = None |
| 144 |
|
| 145 |
if not device: |
| 146 |
# The ordering will work as long as Argyll continues using EnumDisplayMonitors |
| 147 |
monitors = util_win.get_real_display_devices_info() |
| 148 |
moninfo = monitors[display_no] |
| 149 |
device = util_win.get_active_display_device(moninfo["Device"]) |
| 150 |
|
| 151 |
if not device: |
| 152 |
return None |
| 153 |
|
| 154 |
device_id = device.DeviceID.split("\\")[1] |
| 155 |
wmi_connection = None |
| 156 |
not_main_thread = threading.current_thread() is not threading.main_thread() |
| 157 |
|
| 158 |
if wmi: |
| 159 |
if not_main_thread: |
| 160 |
pythoncom.CoInitialize() |
| 161 |
wmi_connection = wmi.WMI(namespace="WMI") |
| 162 |
|
| 163 |
if wmi_connection: |
| 164 |
return get_edid_windows_wmi(device_id, wmi_connection, not_main_thread) |
| 165 |
return get_edid_windows_registry(device_id, device) |
| 166 |
|
| 167 |
|
| 168 |
def get_edid_windows_wmi( |
| 169 |
device_id: str, wmi_connection: wmi.WMI, not_main_thread: bool |
| 170 |
) -> bytes: |
| 171 |
"""Get EDID using WMI for Windows Vista/Win7. |
| 172 |
|
| 173 |
Args: |
| 174 |
device_id (str): The device ID. |
| 175 |
wmi_connection (wmi.WMI): The WMI connection. |
| 176 |
not_main_thread (bool): Whether the current thread is not the main thread. |
| 177 |
|
| 178 |
Raises: |
| 179 |
WMIError: If there is an error with WMI. |
| 180 |
|
| 181 |
Returns: |
| 182 |
bytes: The EDID data. |
| 183 |
""" |
| 184 |
edid = None |
| 185 |
|
| 186 |
# http://msdn.microsoft.com/en-us/library/Aa392707 |
| 187 |
try: |
| 188 |
msmonitors = wmi_connection.WmiMonitorDescriptorMethods() |
| 189 |
except Exception as exception: |
| 190 |
if not_main_thread: |
| 191 |
pythoncom.CoUninitialize() |
| 192 |
raise WMIError(safe_str(exception)) from exception |
| 193 |
|
| 194 |
for msmonitor in msmonitors: |
| 195 |
if msmonitor.InstanceName.split("\\")[1] == device_id: |
| 196 |
try: |
| 197 |
edid = msmonitor.WmiGetMonitorRawEEdidV1Block(0) |
| 198 |
except Exception: |
| 199 |
# No EDID entry |
| 200 |
pass |
| 201 |
else: |
| 202 |
edid = bytes(edid[0]) |
| 203 |
break |
| 204 |
|
| 205 |
if not_main_thread: |
| 206 |
pythoncom.CoUninitialize() |
| 207 |
|
| 208 |
return edid |
| 209 |
|
| 210 |
|
| 211 |
def get_edid_windows_registry(id_: str, device: str) -> bytes: |
| 212 |
"""Get EDID using the Windows registry for Win2k/XP/2003. |
| 213 |
|
| 214 |
Args: |
| 215 |
id_ (str): The device ID. |
| 216 |
device (str): The device identifier. |
| 217 |
|
| 218 |
Returns: |
| 219 |
bytes: The EDID data. |
| 220 |
""" |
| 221 |
edid = None |
| 222 |
|
| 223 |
# http://msdn.microsoft.com/en-us/library/ff546173%28VS.85%29.aspx |
| 224 |
# "The Enum tree is reserved for use by operating system components, |
| 225 |
# and its layout is subject to change. (...) |
| 226 |
# Drivers and Windows applications must not access the Enum tree directly." |
| 227 |
# But do we care? |
| 228 |
# Probably not, as older Windows' API isn't likely gonna change. |
| 229 |
driver = "\\".join(device.DeviceID.split("\\")[-2:]) |
| 230 |
subkey = f"SYSTEM\\CurrentControlSet\\Enum\\DISPLAY\\{id_}" |
| 231 |
|
| 232 |
try: |
| 233 |
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, subkey) |
| 234 |
except OSError: |
| 235 |
# Registry error |
| 236 |
print( |
| 237 |
"Windows registry error: Key", |
| 238 |
f"HKEY_LOCAL_MACHINE\\{subkey}", |
| 239 |
"does not exist.", |
| 240 |
) |
| 241 |
return None |
| 242 |
|
| 243 |
numsubkeys, numvalues, mtime = winreg.QueryInfoKey(key) |
| 244 |
|
| 245 |
for i in range(numsubkeys): |
| 246 |
hkname = winreg.EnumKey(key, i) |
| 247 |
hk = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, f"{subkey}\\{hkname}") |
| 248 |
|
| 249 |
try: |
| 250 |
test = winreg.QueryValueEx(hk, "Driver")[0] |
| 251 |
except OSError: |
| 252 |
# No Driver entry |
| 253 |
continue |
| 254 |
|
| 255 |
if test != driver: |
| 256 |
continue |
| 257 |
|
| 258 |
# Found our display device |
| 259 |
try: |
| 260 |
devparms = winreg.OpenKey( |
| 261 |
winreg.HKEY_LOCAL_MACHINE, |
| 262 |
f"{subkey}\\{hkname}\\Device Parameters", |
| 263 |
) |
| 264 |
except OSError: |
| 265 |
# No Device Parameters (registry error?) |
| 266 |
print( |
| 267 |
"Windows registry error: Key", |
| 268 |
f"HKEY_LOCAL_MACHINE\\{subkey}\\{hkname}Device Parameters", |
| 269 |
"does not exist.", |
| 270 |
) |
| 271 |
continue |
| 272 |
|
| 273 |
try: |
| 274 |
edid = winreg.QueryValueEx(devparms, "EDID")[0] |
| 275 |
except OSError: |
| 276 |
# No EDID entry |
| 277 |
pass |
| 278 |
else: |
| 279 |
return edid |
| 280 |
|
| 281 |
return edid |
| 282 |
|
| 283 |
|
| 284 |
def get_edid_darwin(display_name: str, display_no: int = 0) -> None | bytes: |
| 285 |
"""Get EDID via ioreg on macOS. |
| 286 |
|
| 287 |
Tries to match by EDID monitor_name == display_name first. When that |
| 288 |
fails (e.g. because ArgyllCMS returns a generic name such as "Display #1" |
| 289 |
on macOS Tahoe / Apple Silicon), falls back to returning the EDID at |
| 290 |
position display_no from the list of valid EDIDs found in ioreg. |
| 291 |
|
| 292 |
Args: |
| 293 |
display_name (str): The display name reported by ArgyllCMS. |
| 294 |
display_no (int): Zero-based display index used as a fallback. |
| 295 |
|
| 296 |
Returns: |
| 297 |
None | bytes: Raw EDID bytes or None. |
| 298 |
""" |
| 299 |
# Get EDID via ioreg |
| 300 |
p = subprocess.Popen( |
| 301 |
["ioreg", "-c", "IODisplay", "-S", "-w0"], # noqa: S607 |
| 302 |
stdout=subprocess.PIPE, # noqa: S607 |
| 303 |
) |
| 304 |
stdout, stderr = p.communicate() |
| 305 |
if not stdout: |
| 306 |
return None |
| 307 |
all_edids = [] |
| 308 |
for edid in [ |
| 309 |
binascii.unhexlify(edid_hex) |
| 310 |
for edid_hex in re.findall( |
| 311 |
r'"IODisplayEDID"\s*=\s*<([0-9A-Fa-f]*)>', stdout.decode() |
| 312 |
) |
| 313 |
]: |
| 314 |
if not edid or len(edid) < 128: |
| 315 |
continue |
| 316 |
all_edids.append(edid) |
| 317 |
parsed_edid = parse_edid(edid) |
| 318 |
if parsed_edid.get("monitor_name", parsed_edid.get("ascii")) == display_name: |
| 319 |
return edid |
| 320 |
# Name-based match failed (ArgyllCMS gave a generic name like "Display #1"). |
| 321 |
# Fall back to the display at the given index so that the EDID monitor name |
| 322 |
# can still be used for profile naming and display identification. |
| 323 |
if 0 <= display_no < len(all_edids): |
| 324 |
return all_edids[display_no] |
| 325 |
return None |
| 326 |
|
| 327 |
|
| 328 |
def get_display_name_from_system_profiler(width: int, height: int) -> str | None: |
| 329 |
"""Return the display model name from system_profiler on macOS. |
| 330 |
|
| 331 |
Used as a last-resort fallback when ioreg does not expose IODisplayEDID |
| 332 |
(e.g. Apple Silicon Macs running macOS Tahoe with external displays). |
| 333 |
|
| 334 |
Matches by display resolution because system_profiler and ArgyllCMS may |
| 335 |
enumerate displays in different orders. When multiple displays share the |
| 336 |
same resolution the first match is returned. |
| 337 |
|
| 338 |
Resolution strings like "1920 x 1080 (3840 x 2160 HiDPI)" contain multiple |
| 339 |
pairs; all pairs are tried so that both logical and physical resolutions match. |
| 340 |
Multiple resolution keys are checked in case macOS changes the key name. |
| 341 |
|
| 342 |
Args: |
| 343 |
width (int): Display width in pixels as reported by ArgyllCMS. |
| 344 |
height (int): Display height in pixels as reported by ArgyllCMS. |
| 345 |
|
| 346 |
Returns: |
| 347 |
str | None: Display model name, or None if not determinable. |
| 348 |
""" |
| 349 |
try: |
| 350 |
p = subprocess.Popen( # noqa: S607 |
| 351 |
["system_profiler", "SPDisplaysDataType", "-json"], |
| 352 |
stdout=subprocess.PIPE, |
| 353 |
stderr=subprocess.PIPE, |
| 354 |
) |
| 355 |
stdout, _ = p.communicate() |
| 356 |
if not stdout: |
| 357 |
return None |
| 358 |
data = json.loads(stdout) |
| 359 |
except Exception: |
| 360 |
return None |
| 361 |
|
| 362 |
for gpu in data.get("SPDisplaysDataType", []): |
| 363 |
for display in gpu.get("spdisplays_ndrvs", []): |
| 364 |
name = display.get("_name", "").strip() |
| 365 |
if not name: |
| 366 |
continue |
| 367 |
for res_key in ( |
| 368 |
"spdisplays_resolution", |
| 369 |
"_spdisplays_resolution", # macOS Tahoe uses underscore prefix |
| 370 |
"spdisplays_native-resolution", |
| 371 |
"spdisplays_ui-resolution", |
| 372 |
"spdisplays_pixelresolution", |
| 373 |
"_spdisplays_pixels", # macOS Tahoe physical pixel count |
| 374 |
): |
| 375 |
resolution = display.get(res_key, "") |
| 376 |
if not resolution: |
| 377 |
continue |
| 378 |
# findall captures every (w, h) pair in strings like |
| 379 |
# "1920 x 1080 (3840 x 2160 HiDPI)" or "spdisplays_3840x2160" |
| 380 |
for w, h in re.findall(r"(\d+)\s*[xX×]\s*(\d+)", resolution): |
| 381 |
if int(w) == width and int(h) == height: |
| 382 |
return name |
| 383 |
return None |
| 384 |
|
| 385 |
|
| 386 |
def get_edid_from_xrandr(display_no: int) -> bytes: |
| 387 |
"""Get EDID using `xrandr` utility. |
| 388 |
|
| 389 |
Tries to find the EDID by matching the xrandr output name stored in the |
| 390 |
display dict. When that name-based match fails (e.g. because ArgyllCMS |
| 391 |
reports a generic name such as "Monitor 1" or "Display #1" that does not |
| 392 |
appear in xrandr output, or because geometry-based display lookup returned |
| 393 |
nothing), falls back to collecting all EDID blocks from xrandr in output |
| 394 |
order and returning the block at position display_no. |
| 395 |
|
| 396 |
Args: |
| 397 |
display_no (int): The display number (zero-based). |
| 398 |
|
| 399 |
Returns: |
| 400 |
bytes: The EDID data. |
| 401 |
""" |
| 402 |
display = real_display_size_mm.get_display(display_no) |
| 403 |
if display: |
| 404 |
# EDID already fetched (e.g. via Wayland DBus in get_wayland_display) |
| 405 |
edid = display.get("edid") |
| 406 |
if edid: |
| 407 |
return edid |
| 408 |
|
| 409 |
p = subprocess.Popen([which("xrandr"), "--verbose"], stdout=subprocess.PIPE) # noqa: S607 |
| 410 |
stdout, stderr = p.communicate() |
| 411 |
|
| 412 |
if not stdout: |
| 413 |
return None |
| 414 |
|
| 415 |
name = display["name"] if display else None |
| 416 |
|
| 417 |
# Pass 1: name-based match (fast path - exits early on success). |
| 418 |
# ArgyllCMS >= 3.3.0 reports just the xrandr output name (e.g. "DP-2"), |
| 419 |
# but xrandr may render it as "Monitor 1, Output DP-2 connected". |
| 420 |
if name is not None: |
| 421 |
found_display = False |
| 422 |
found_edid = False |
| 423 |
edid_data = [] |
| 424 |
for line in stdout.splitlines(): |
| 425 |
if found_edid: |
| 426 |
if line.startswith(b"\t\t"): |
| 427 |
edid_data.append(line.strip()) |
| 428 |
else: |
| 429 |
break |
| 430 |
if found_display and b"EDID" in line: |
| 431 |
found_edid = True |
| 432 |
if not found_display: |
| 433 |
if (name + b" connected") in line: |
| 434 |
found_display = True |
| 435 |
elif (b", Output " + name + b" connected") in line: |
| 436 |
found_display = True |
| 437 |
|
| 438 |
hex_data = b"".join(edid_data) |
| 439 |
if hex_data: |
| 440 |
try: |
| 441 |
return binascii.unhexlify(hex_data) |
| 442 |
except Exception: |
| 443 |
pass |
| 444 |
|
| 445 |
# Pass 2: index-based fallback. Collect every EDID block that appears in |
| 446 |
# xrandr output (in the order xrandr lists them) and return the one at |
| 447 |
# display_no. This handles cases where the name match above failed, e.g. |
| 448 |
# because ArgyllCMS used a generic label ("Monitor 1") that does not appear |
| 449 |
# as an xrandr output name. Ordering may not match for multi-display |
| 450 |
# setups when xrandr and ArgyllCMS enumerate differently, but for single- |
| 451 |
# display configurations this is always correct. |
| 452 |
all_edids = [] |
| 453 |
in_edid = False |
| 454 |
edid_data = [] |
| 455 |
for line in stdout.splitlines(): |
| 456 |
if in_edid: |
| 457 |
if line.startswith(b"\t\t"): |
| 458 |
edid_data.append(line.strip()) |
| 459 |
else: |
| 460 |
hex_data = b"".join(edid_data) |
| 461 |
if hex_data: |
| 462 |
try: |
| 463 |
all_edids.append(binascii.unhexlify(hex_data)) |
| 464 |
except Exception: |
| 465 |
all_edids.append(None) |
| 466 |
edid_data = [] |
| 467 |
in_edid = False |
| 468 |
if b"EDID" in line and not in_edid: |
| 469 |
in_edid = True |
| 470 |
edid_data = [] |
| 471 |
if edid_data: |
| 472 |
hex_data = b"".join(edid_data) |
| 473 |
if hex_data: |
| 474 |
try: |
| 475 |
all_edids.append(binascii.unhexlify(hex_data)) |
| 476 |
except Exception: |
| 477 |
all_edids.append(None) |
| 478 |
|
| 479 |
if 0 <= display_no < len(all_edids) and all_edids[display_no]: |
| 480 |
return all_edids[display_no] |
| 481 |
return None |
| 482 |
|
| 483 |
|
| 484 |
def parse_manufacturer_id(block: bytes) -> str: |
| 485 |
"""Parse the manufacturer id and return decoded string. |
| 486 |
|
| 487 |
The range is always ASCII charcode 64 to 95. |
| 488 |
|
| 489 |
Args: |
| 490 |
block (bytes): The block containing the manufacturer ID. |
| 491 |
|
| 492 |
Returns: |
| 493 |
str: The decoded manufacturer ID. |
| 494 |
""" |
| 495 |
h = combine_hi_8lo(block[0], block[1]) |
| 496 |
manufacturer_id = [ |
| 497 |
chr(((h >> shift) & 0x1F) + ord("A") - 1) for shift in (10, 5, 0) |
| 498 |
] |
| 499 |
return "".join(manufacturer_id).strip() |
| 500 |
|
| 501 |
|
| 502 |
def get_manufacturer_name(manufacturer_id: str) -> str: |
| 503 |
"""Try and get a nice descriptive string for our manufacturer id. |
| 504 |
|
| 505 |
This uses either hwdb or pnp.ids which will be looked for in several places. |
| 506 |
If it can't find the file, it returns None. |
| 507 |
|
| 508 |
Examples: |
| 509 |
SAM -> Samsung Electric Company |
| 510 |
NEC -> NEC Corporation |
| 511 |
|
| 512 |
hwdb/pnp.ids can be created from Excel data available from uefi.org: |
| 513 |
http://www.uefi.org/PNP_ACPI_Registry |
| 514 |
http://www.uefi.org/uefi-pnp-export |
| 515 |
http://www.uefi.org/uefi-acpi-export |
| 516 |
|
| 517 |
But it is probably a better idea to use HWDB as it contains various |
| 518 |
additions from other sources: |
| 519 |
https://github.com/systemd/systemd/blob/master/hwdb/20-acpi-vendor.hwdb |
| 520 |
|
| 521 |
Args: |
| 522 |
manufacturer_id (str): The manufacturer ID. |
| 523 |
|
| 524 |
Returns: |
| 525 |
str: The descriptive manufacturer name. |
| 526 |
""" |
| 527 |
if not PNP_ID_CACHE: |
| 528 |
load_pnp_id_cache() |
| 529 |
|
| 530 |
return PNP_ID_CACHE.get(manufacturer_id) |
| 531 |
|
| 532 |
|
| 533 |
def load_pnp_id_cache() -> None: |
| 534 |
"""Load the `PNP_ID_CACHE` content from various possible locations.""" |
| 535 |
for path in get_pnp_id_paths(): |
| 536 |
if not os.path.isfile(path): |
| 537 |
continue |
| 538 |
|
| 539 |
try: |
| 540 |
with open(path, encoding="utf-8", errors="replace") as pnp_ids: |
| 541 |
lines = pnp_ids.readlines() |
| 542 |
except OSError: |
| 543 |
continue |
| 544 |
|
| 545 |
if path.endswith("hwdb"): |
| 546 |
parse_hwdb_data(lines) |
| 547 |
else: |
| 548 |
parse_pnpid_data(lines) |
| 549 |
|
| 550 |
|
| 551 |
def get_pnp_id_paths() -> list: |
| 552 |
"""Get the list of possible paths for the pnp.ids file. |
| 553 |
|
| 554 |
Returns: |
| 555 |
list: List of possible paths. |
| 556 |
""" |
| 557 |
paths = [ |
| 558 |
"/usr/lib/udev/hwdb.d/20-acpi-vendor.hwdb", # systemd |
| 559 |
"/usr/share/hwdata/pnp.ids", # hwdata, e.g. Red Hat |
| 560 |
"/usr/share/misc/pnp.ids", # pnputils, e.g. Debian |
| 561 |
"/usr/share/libgnome-desktop/pnp.ids", |
| 562 |
] # fallback gnome-desktop |
| 563 |
# if sys.platform in ("darwin", "win32"): |
| 564 |
# fallback |
| 565 |
paths.append(os.path.join(config.PYDIR, "pnp.ids")) |
| 566 |
# fallback for tests |
| 567 |
paths.append(os.path.join(config.PYDIR, "DisplayCAL", "pnp.ids")) |
| 568 |
return paths |
| 569 |
|
| 570 |
|
| 571 |
def parse_hwdb_data(lines: list[str]) -> None: |
| 572 |
"""Parse a from the hwdb file data. |
| 573 |
|
| 574 |
Updates the `PNP_ID_CACHE` dictionary with the parsed data. |
| 575 |
|
| 576 |
Args: |
| 577 |
lines (list[str]): The line to parse. |
| 578 |
""" |
| 579 |
id_, name = None, None |
| 580 |
for line in lines: |
| 581 |
if line.strip().startswith("acpi:"): |
| 582 |
id_ = line.split(":")[1][:3] |
| 583 |
continue |
| 584 |
if line.strip().startswith("ID_VENDOR_FROM_DATABASE"): |
| 585 |
name = line.split("=", 1)[1].strip() |
| 586 |
else: |
| 587 |
continue |
| 588 |
if id_ and name and id_ not in PNP_ID_CACHE: |
| 589 |
PNP_ID_CACHE[id_] = name |
| 590 |
|
| 591 |
|
| 592 |
def parse_pnpid_data(lines: list[str]) -> None: |
| 593 |
"""Parse data from the pnp.ids file content. |
| 594 |
|
| 595 |
Args: |
| 596 |
lines (list[str]): The data to parse. |
| 597 |
""" |
| 598 |
id_, name = None, None |
| 599 |
for line in lines: |
| 600 |
try: |
| 601 |
# Strip leading/trailing whitespace |
| 602 |
# (non-breaking spaces too) |
| 603 |
id_, name = line.strip(string.whitespace + "\u00a0").split(None, 1) |
| 604 |
except ValueError: |
| 605 |
id_, name = None, None |
| 606 |
if id_ and name and id_ not in PNP_ID_CACHE: |
| 607 |
PNP_ID_CACHE[id_] = name |
| 608 |
|
| 609 |
|
| 610 |
def edid_get_bit(value: int, bit: int) -> int: |
| 611 |
"""Get the bit value at the specified position. |
| 612 |
|
| 613 |
Args: |
| 614 |
value (int): The value to extract the bit from. |
| 615 |
bit (int): The bit position. |
| 616 |
|
| 617 |
Returns: |
| 618 |
int: The bit value. |
| 619 |
""" |
| 620 |
return (value & (1 << bit)) >> bit |
| 621 |
|
| 622 |
|
| 623 |
def edid_get_bits(value: int, begin: int, end: int) -> int: |
| 624 |
"""Get the bits from the specified range. |
| 625 |
|
| 626 |
Args: |
| 627 |
value (int): The value to extract the bits from. |
| 628 |
begin (int): The starting bit position. |
| 629 |
end (int): The ending bit position. |
| 630 |
|
| 631 |
Returns: |
| 632 |
int: The extracted bits. |
| 633 |
""" |
| 634 |
mask = (1 << (end - begin + 1)) - 1 |
| 635 |
return (value >> begin) & mask |
| 636 |
|
| 637 |
|
| 638 |
def edid_decode_fraction(high: int, low: int) -> float: |
| 639 |
"""Decode a fraction from high and low bits. |
| 640 |
|
| 641 |
Args: |
| 642 |
high (int): The high bits. |
| 643 |
low (int): The low bits. |
| 644 |
|
| 645 |
Returns: |
| 646 |
float: The decoded fraction. |
| 647 |
""" |
| 648 |
result = 0.0 |
| 649 |
high = (high << 2) | low |
| 650 |
for i in range(10): |
| 651 |
result += edid_get_bit(high, i) * math.pow(2, i - 10) |
| 652 |
return result |
| 653 |
|
| 654 |
|
| 655 |
def edid_parse_string(desc: bytes) -> bytes: |
| 656 |
"""Parse a string from EDID data. |
| 657 |
|
| 658 |
Args: |
| 659 |
desc (bytes): The description to parse. |
| 660 |
|
| 661 |
Returns: |
| 662 |
bytes: The parsed string. |
| 663 |
""" |
| 664 |
# Return value should match colord's cd_edid_parse_string in cd-edid.c |
| 665 |
# Remember: In C, NULL terminates a string, so do the same here |
| 666 |
# Replace newline with NULL |
| 667 |
desc = desc[:13].replace(b"\n", b"\x00").replace(b"\r", b"\x00") |
| 668 |
|
| 669 |
# Strip anything after the first NULL byte (if any) |
| 670 |
null_index: int = desc.find(b"\x00") |
| 671 |
if null_index != -1: |
| 672 |
desc = desc[:null_index] |
| 673 |
|
| 674 |
# Strip trailing whitespace |
| 675 |
desc = desc.rstrip() |
| 676 |
|
| 677 |
# Replace all non-printable chars with NULL |
| 678 |
desc = bytearray(desc) |
| 679 |
non_printable_count = 0 |
| 680 |
for i in range(len(desc)): |
| 681 |
if desc[i] < 32 or desc[i] > 126: |
| 682 |
desc[i] = 0 |
| 683 |
non_printable_count += 1 |
| 684 |
|
| 685 |
# Only use string if max 4 replaced chars |
| 686 |
if non_printable_count <= 4: |
| 687 |
# Replace any NULL chars with dashes to make a printable string |
| 688 |
desc = desc.replace(b"\x00", b"-") |
| 689 |
return bytes(desc) |
| 690 |
|
| 691 |
return None |
| 692 |
|
| 693 |
|
| 694 |
def parse_edid(edid: bytes) -> dict: |
| 695 |
"""Parse raw EDID data (binary string) and return dict. |
| 696 |
|
| 697 |
Args: |
| 698 |
edid (bytes): The raw EDID data. |
| 699 |
|
| 700 |
Returns: |
| 701 |
dict: The parsed EDID data. |
| 702 |
""" |
| 703 |
if len(edid) not in [128, 256, 384]: |
| 704 |
edid = fix_edid_encoding(edid) |
| 705 |
|
| 706 |
result = parse_edid_header(edid) |
| 707 |
result.update(parse_edid_basic_display_parameters(edid)) |
| 708 |
result.update(parse_edid_chromaticity_coordinates(edid)) |
| 709 |
result.update(parse_edid_descriptor_blocks(edid)) |
| 710 |
result.update(parse_edid_extension_blocks(edid)) |
| 711 |
|
| 712 |
return result |
| 713 |
|
| 714 |
|
| 715 |
def fix_edid_encoding(edid: bytes) -> bytes: |
| 716 |
"""Fix the encoding of EDID data. |
| 717 |
|
| 718 |
Args: |
| 719 |
edid (bytes): The EDID data to fix. |
| 720 |
|
| 721 |
Returns: |
| 722 |
bytes: The fixed EDID data. |
| 723 |
""" |
| 724 |
# this is probably encoded/decoded in a wrong way and contains 2-bytes characters |
| 725 |
# |
| 726 |
# b"\xc2" and b"\xc3" are codepoints |
| 727 |
# they can only appear if the byte data is decoded with latin-1 and encoded |
| 728 |
# back with utf-8. |
| 729 |
# This apparently is a wrong conversion. |
| 730 |
if b"\xc2" in edid or b"\xc3" in edid: |
| 731 |
edid = edid.decode("utf-8").encode("latin-1") |
| 732 |
return edid |
| 733 |
|
| 734 |
|
| 735 |
def parse_edid_header(edid: bytes) -> dict: |
| 736 |
"""Parse the EDID header. |
| 737 |
|
| 738 |
Args: |
| 739 |
edid (bytes): The raw EDID data. |
| 740 |
|
| 741 |
Returns: |
| 742 |
dict: The parsed EDID header. |
| 743 |
""" |
| 744 |
result = { |
| 745 |
"edid": edid, |
| 746 |
"hash": md5(edid).hexdigest(), # noqa: S324 |
| 747 |
"header": edid[HEADER[0] : HEADER[1]], |
| 748 |
"manufacturer_id": parse_manufacturer_id( |
| 749 |
edid[MANUFACTURER_ID[0] : MANUFACTURER_ID[1]] |
| 750 |
), |
| 751 |
} |
| 752 |
manufacturer = get_manufacturer_name(result["manufacturer_id"]) |
| 753 |
if manufacturer: |
| 754 |
result["manufacturer"] = manufacturer |
| 755 |
return result |
| 756 |
|
| 757 |
|
| 758 |
def parse_edid_basic_display_parameters(edid: bytes) -> dict: |
| 759 |
"""Parse the basic display parameters from the EDID data. |
| 760 |
|
| 761 |
Args: |
| 762 |
edid (bytes): The raw EDID data. |
| 763 |
|
| 764 |
Returns: |
| 765 |
dict: The parsed basic display parameters. |
| 766 |
""" |
| 767 |
result = { |
| 768 |
"product_id": struct.unpack("<H", edid[PRODUCT_ID[0] : PRODUCT_ID[1]])[0], |
| 769 |
"serial_32": struct.unpack("<I", edid[SERIAL_32[0] : SERIAL_32[1]])[0], |
| 770 |
"week_of_manufacture": edid[WEEK_OF_MANUFACTURE], |
| 771 |
"year_of_manufacture": edid[YEAR_OF_MANUFACTURE] + 1990, |
| 772 |
"edid_version": edid[EDID_VERSION], |
| 773 |
"edid_revision": edid[EDID_REVISION], |
| 774 |
"max_h_size_cm": edid[MAX_H_SIZE_CM], |
| 775 |
"max_v_size_cm": edid[MAX_V_SIZE_CM], |
| 776 |
} |
| 777 |
if edid[GAMMA] != b"\xff": |
| 778 |
result["gamma"] = edid[GAMMA] / 100.0 + 1 |
| 779 |
result["features"] = edid[FEATURES] |
| 780 |
return result |
| 781 |
|
| 782 |
|
| 783 |
def parse_edid_chromaticity_coordinates(edid: bytes) -> dict: |
| 784 |
"""Parse the chromaticity coordinates from the EDID data. |
| 785 |
|
| 786 |
Args: |
| 787 |
edid (bytes): The raw EDID data. |
| 788 |
|
| 789 |
Returns: |
| 790 |
dict: The parsed chromaticity coordinates. |
| 791 |
""" |
| 792 |
return { |
| 793 |
"red_x": edid_decode_fraction( |
| 794 |
edid[HI_R_X], edid_get_bits(edid[LO_RG_XY], 6, 7) |
| 795 |
), |
| 796 |
"red_y": edid_decode_fraction( |
| 797 |
edid[HI_R_Y], edid_get_bits(edid[LO_RG_XY], 4, 5) |
| 798 |
), |
| 799 |
"green_x": edid_decode_fraction( |
| 800 |
edid[HI_G_X], edid_get_bits(edid[LO_RG_XY], 2, 3) |
| 801 |
), |
| 802 |
"green_y": edid_decode_fraction( |
| 803 |
edid[HI_G_Y], edid_get_bits(edid[LO_RG_XY], 0, 1) |
| 804 |
), |
| 805 |
"blue_x": edid_decode_fraction( |
| 806 |
edid[HI_B_X], edid_get_bits(edid[LO_BW_XY], 6, 7) |
| 807 |
), |
| 808 |
"blue_y": edid_decode_fraction( |
| 809 |
edid[HI_B_Y], edid_get_bits(edid[LO_BW_XY], 4, 5) |
| 810 |
), |
| 811 |
"white_x": edid_decode_fraction( |
| 812 |
edid[HI_W_X], edid_get_bits(edid[LO_BW_XY], 2, 3) |
| 813 |
), |
| 814 |
"white_y": edid_decode_fraction( |
| 815 |
edid[HI_W_Y], edid_get_bits(edid[LO_BW_XY], 0, 1) |
| 816 |
), |
| 817 |
} |
| 818 |
|
| 819 |
|
| 820 |
def parse_edid_descriptor_blocks(edid: bytes) -> dict: |
| 821 |
"""Parse the descriptor blocks from the EDID data. |
| 822 |
|
| 823 |
Args: |
| 824 |
edid (bytes): The raw EDID data. |
| 825 |
|
| 826 |
Returns: |
| 827 |
dict: The parsed descriptor blocks. |
| 828 |
""" |
| 829 |
text_types = { |
| 830 |
BLOCK_TYPE_SERIAL_ASCII: "serial_ascii", |
| 831 |
BLOCK_TYPE_ASCII: "ascii", |
| 832 |
BLOCK_TYPE_MONITOR_NAME: "monitor_name", |
| 833 |
} |
| 834 |
result = {} |
| 835 |
# Parse descriptor blocks |
| 836 |
for start, stop in BLOCKS: |
| 837 |
block = edid[start:stop] |
| 838 |
if block[:BLOCK_TYPE] != b"\x00\x00\x00": |
| 839 |
# Ignore pixel clock data |
| 840 |
continue |
| 841 |
text_type = text_types.get(block[BLOCK_TYPE : BLOCK_TYPE + 1]) |
| 842 |
if text_type: |
| 843 |
desc = edid_parse_string(block[BLOCK_CONTENTS[0] : BLOCK_CONTENTS[1]]) |
| 844 |
if desc is not None: |
| 845 |
result[text_type] = desc.decode("utf-8") |
| 846 |
elif block[BLOCK_TYPE] == BLOCK_TYPE_COLOR_POINT: |
| 847 |
result.update(parse_color_point_data(block)) |
| 848 |
elif block[BLOCK_TYPE] == BLOCK_TYPE_COLOR_MANAGEMENT_DATA: |
| 849 |
# TODO: Implement? How could it be used? |
| 850 |
result["color_management_data"] = block[ |
| 851 |
BLOCK_CONTENTS[0] : BLOCK_CONTENTS[1] |
| 852 |
] |
| 853 |
return result |
| 854 |
|
| 855 |
|
| 856 |
def parse_color_point_data(block: bytes) -> dict: |
| 857 |
"""Parse the color point data from the EDID data. |
| 858 |
|
| 859 |
Args: |
| 860 |
block (bytes): The block containing the color point data. |
| 861 |
|
| 862 |
Returns: |
| 863 |
dict: The parsed color point data. |
| 864 |
""" |
| 865 |
result = {} |
| 866 |
for i in (5, 10): |
| 867 |
# 2nd white point index in range 1...255 |
| 868 |
# 3rd white point index in range 2...255 |
| 869 |
# 0 = do not use |
| 870 |
if block[i] <= i / 5: |
| 871 |
continue |
| 872 |
|
| 873 |
white_x = edid_decode_fraction(block[i + 2], edid_get_bits(block[i + 1], 2, 3)) |
| 874 |
result[f"white_x_{block[i]}"] = white_x |
| 875 |
if "white_x" not in result: |
| 876 |
result["white_x"] = white_x |
| 877 |
white_y = edid_decode_fraction(block[i + 3], edid_get_bits(block[i + 1], 0, 1)) |
| 878 |
result[f"white_y_{block[i]}"] = white_y |
| 879 |
if "white_y" not in result: |
| 880 |
result["white_y"] = white_y |
| 881 |
if block[i + 4] != "\xff": |
| 882 |
gamma = block[i + 4] / 100.0 + 1 |
| 883 |
result[f"gamma_{block[i]}"] = gamma |
| 884 |
if "gamma" not in result: |
| 885 |
result["gamma"] = gamma |
| 886 |
return result |
| 887 |
|
| 888 |
|
| 889 |
def parse_edid_extension_blocks(edid: bytes) -> dict: |
| 890 |
"""Parse the extension blocks from the EDID data. |
| 891 |
|
| 892 |
Args: |
| 893 |
edid (bytes): The raw EDID data. |
| 894 |
|
| 895 |
Returns: |
| 896 |
dict: The parsed extension blocks. |
| 897 |
""" |
| 898 |
result = { |
| 899 |
"ext_flag": edid[EXTENSION_FLAG], |
| 900 |
"checksum": edid[CHECKSUM], |
| 901 |
"checksum_valid": sum(char for char in edid) % 256 == 0, |
| 902 |
} |
| 903 |
if len(edid) > 128 and result["ext_flag"] > 0: |
| 904 |
# Parse extension blocks |
| 905 |
block = edid[128:] |
| 906 |
while block: |
| 907 |
if block[0] == BLOCK_DI_EXT and block[TRC[0]] != "\0": |
| 908 |
# TODO: Implement |
| 909 |
pass |
| 910 |
block = block[128:] |
| 911 |
return result |
| 912 |
|
| 913 |
|
| 914 |
class WMIError(Exception): |
| 915 |
"""Custom exception for WMI errors.""" |