Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(capture): detect HDR/WCG monitors and read the framebuffer at full depth
rubenluetke10-beep5d7b6a6826da
diff --git a/jarvis/appshot/hdr_image.py b/jarvis/appshot/hdr_image.pynew file mode 100644index 0000000000..a05f3bdace--- /dev/null+++ b/jarvis/appshot/hdr_image.py@@ -0,0 +1,205 @@+"""Colour-exact still images: HDR PNG masters and their SDR stand-ins.++A full-depth capture arrives as scRGB — linear light, BT.709 primaries,+1.0 = 80 nits, values above 1 for highlights and below 0 for colours outside+sRGB. Two things are made from it:++* the **master**, lossless: a 16-bit PNG in BT.2020 primaries with the PQ+ transfer (HDR10's signal), tagged with a ``cICP`` chunk (PNG, third+ edition) and a ``cLLi`` chunk with the content's light levels. Viewers that+ read ``cICP`` show it exactly as the monitor did.+* the **SDR stand-in**, 8-bit sRGB, for everything that cannot take HDR — the+ model's image, the clipboard, chat. SDR white maps to sRGB white, so normal+ UI looks the same as on screen; only highlights above SDR white clip.++SDR captures keep 8 bits and gain the monitor's ICC profile instead+(:func:`encode_png8`), which is the exact description of their pixels.++Pure numpy + zlib (+ Pillow for 8-bit); no platform code.+"""++from __future__ import annotations++import struct+import zlib+from typing import Any++#: BT.709 linear -> BT.2020 linear (both D65), ITU-R BT.2087.+_BT709_TO_BT2020 = (+ (0.627404, 0.329283, 0.043313),+ (0.069097, 0.919540, 0.011362),+ (0.016391, 0.088013, 0.895595),+)+_PQ_M1, _PQ_M2 = 0.1593017578125, 78.84375+_PQ_C1, _PQ_C2, _PQ_C3 = 0.8359375, 18.8515625, 18.6875+#: scRGB 1.0 in nits.+SCRGB_NITS = 80.0+#: cICP: BT.2020 primaries, PQ transfer, RGB (identity matrix), full range.+CICP_BT2100_PQ = (9, 16, 0, 1)+++def pq_encode(nits: Any) -> Any:+ """SMPTE ST 2084: absolute luminance (cd/m²) -> PQ signal 0..1."""+ import numpy as np # noqa: PLC0415++ y = np.clip(np.asarray(nits, dtype=np.float32) / 10000.0, 0.0, 1.0)+ p = np.power(y, _PQ_M1)+ return np.power((_PQ_C1 + _PQ_C2 * p) / (1.0 + _PQ_C3 * p), _PQ_M2)+++def pq_decode(signal: Any) -> Any:+ """PQ signal 0..1 -> absolute luminance in cd/m²."""+ import numpy as np # noqa: PLC0415++ e = np.power(np.clip(np.asarray(signal, dtype=np.float32), 0.0, 1.0), 1.0 / _PQ_M2)+ return 10000.0 * np.power(np.maximum(e - _PQ_C1, 0.0) / (_PQ_C2 - _PQ_C3 * e), 1.0 / _PQ_M1)+++def scrgb_to_bt2020_nits(scrgb: Any) -> Any:+ """scRGB ``(h, w, 3|4)`` -> linear BT.2020 in nits, ``float32 (h, w, 3)``."""+ import numpy as np # noqa: PLC0415++ rgb = np.asarray(scrgb)[..., :3].astype(np.float32)+ matrix = np.asarray(_BT709_TO_BT2020, dtype=np.float32) * SCRGB_NITS+ out = rgb @ matrix.T+ np.maximum(out, 0.0, out=out) # BT.2020 holds every visible scRGB colour+ return out+++def scrgb_to_pq16(scrgb: Any) -> Any:+ """scRGB -> BT.2020 PQ, ``uint16 (h, w, 3)`` full range — the PNG master's pixels."""+ import numpy as np # noqa: PLC0415++ signal = pq_encode(scrgb_to_bt2020_nits(scrgb))+ return np.rint(signal * 65535.0).astype(np.uint16)+++def light_levels(scrgb: Any) -> tuple[float, float]:+ """``(MaxCLL, MaxFALL)`` in nits: the brightest pixel and the average frame light."""+ nits = scrgb_to_bt2020_nits(scrgb)+ peak = nits.max(axis=-1)+ return float(peak.max(initial=0.0)), float(peak.mean()) if peak.size else 0.0+++def scrgb_to_srgb8(scrgb: Any, sdr_white_nits: float = SCRGB_NITS) -> Any:+ """scRGB -> 8-bit sRGB ``(h, w, 3)``, SDR white at full white, highlights clipped."""+ import numpy as np # noqa: PLC0415++ rgb = np.asarray(scrgb)[..., :3].astype(np.float32)+ rgb *= SCRGB_NITS / max(1.0, float(sdr_white_nits))+ np.clip(rgb, 0.0, 1.0, out=rgb)+ low = rgb * 12.92+ high = 1.055 * np.power(rgb, 1.0 / 2.4) - 0.055+ out = np.where(rgb <= 0.0031308, low, high)+ return np.rint(out * 255.0).astype(np.uint8)+++def srgb8_to_scrgb(rgb8: Any, sdr_white_nits: float = SCRGB_NITS) -> Any:+ """8-bit sRGB -> scRGB at the given SDR white (for drawing on an HDR master)."""+ import numpy as np # noqa: PLC0415++ c = np.asarray(rgb8)[..., :3].astype(np.float32) / 255.0+ lin = np.where(c <= 0.04045, c / 12.92, np.power((c + 0.055) / 1.055, 2.4))+ return lin * (float(sdr_white_nits) / SCRGB_NITS)+++def composite_over_scrgb(base: Any, overlay_rgba8: Any, sdr_white_nits: float) -> Any:+ """Lay an 8-bit sRGB RGBA drawing (markings) over an scRGB image, in linear light.++ The drawing shows at SDR white, as UI on the HDR desktop does.+ """+ import numpy as np # noqa: PLC0415++ out = np.asarray(base)[..., :3].astype(np.float32)+ overlay = np.asarray(overlay_rgba8)+ alpha = overlay[..., 3:4].astype(np.float32) / 255.0+ mask = alpha[..., 0] > 0+ if mask.any():+ colour = srgb8_to_scrgb(overlay[mask], sdr_white_nits)+ a = alpha[mask]+ out[mask] = out[mask] * (1.0 - a) + colour * a+ return out+++# ---------------------------------------------------------------------------+# PNG writing+# ---------------------------------------------------------------------------+++def _chunk(kind: bytes, data: bytes) -> bytes:+ return (+ struct.pack(">I", len(data))+ + kind+ + data+ + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)+ )+++def _scanlines_up(raw: Any) -> bytes:+ """PNG rows with the "Up" filter: each byte minus the byte above (screens are flat)."""+ import numpy as np # noqa: PLC0415++ rows = np.ascontiguousarray(raw).reshape(raw.shape[0], -1)+ filtered = np.empty_like(rows)+ filtered[0] = rows[0]+ np.subtract(rows[1:], rows[:-1], out=filtered[1:])+ lines = np.empty((rows.shape[0], rows.shape[1] + 1), dtype=np.uint8)+ lines[:, 0] = 2+ lines[0, 0] = 0+ lines[:, 1:] = filtered+ return lines.tobytes()+++def encode_png16(+ rgb16: Any,+ *,+ cicp: tuple[int, int, int, int] = CICP_BT2100_PQ,+ light: tuple[float, float] | None = None,+ level: int = 6,+) -> bytes:+ """A 16-bit RGB PNG with ``cICP`` (and ``cLLi`` when ``light`` is given)."""+ import numpy as np # noqa: PLC0415++ pixels = np.asarray(rgb16, dtype=np.uint16)+ height, width = pixels.shape[:2]+ big_endian = pixels.astype(">u2").view(np.uint8).reshape(height, width * 6)+ header = struct.pack(">IIBBBBB", width, height, 16, 2, 0, 0, 0)+ chunks = [_chunk(b"IHDR", header), _chunk(b"cICP", bytes(cicp))]+ if light is not None:+ max_cll, max_fall = (max(0, min(0xFFFFFFFF, round(v * 10000))) for v in light)+ chunks.append(_chunk(b"cLLi", struct.pack(">II", max_cll, max_fall)))+ data = zlib.compress(_scanlines_up(big_endian), level)+ chunks.append(_chunk(b"IDAT", data))+ chunks.append(_chunk(b"IEND", b""))+ return b"\x89PNG\r\n\x1a\n" + b"".join(chunks)+++def encode_png8(rgb8: Any, icc_profile: bytes | None = None) -> bytes:+ """An 8-bit RGB PNG carrying the monitor's ICC profile when there is one."""+ import io # noqa: PLC0415++ from PIL import Image # noqa: PLC0415++ image = Image.fromarray(rgb8, "RGB") if not isinstance(rgb8, Image.Image) else rgb8+ buffer = io.BytesIO()+ options: dict[str, Any] = {"format": "PNG", "compress_level": 6}+ if icc_profile:+ options["icc_profile"] = icc_profile+ image.save(buffer, **options)+ return buffer.getvalue()+++def read_png_cicp(data: bytes) -> tuple[int, int, int, int] | None:+ """The ``cICP`` tag of a PNG, or ``None`` (tests and the library use this)."""+ if not data.startswith(b"\x89PNG\r\n\x1a\n"):+ return None+ pos = 8+ while pos + 8 <= len(data):+ (length,) = struct.unpack_from(">I", data, pos)+ kind = data[pos + 4 : pos + 8]+ if kind == b"cICP" and length == 4:+ return tuple(data[pos + 8 : pos + 12]) # type: ignore[return-value]+ if kind == b"IDAT":+ return None+ pos += 12 + length+ return Nonediff --git a/jarvis/platform/display_color.py b/jarvis/platform/display_color.pynew file mode 100644index 0000000000..3de444a259--- /dev/null+++ b/jarvis/platform/display_color.py@@ -0,0 +1,366 @@+"""What a monitor really shows: plain SDR, a wide colour gamut, or HDR.++:func:`display_color` answers per monitor, at capture time, because the mode can+change any second (Windows: Win+Alt+B, macOS: an HDR video starting). Captures+use the answer to decide whether they may stay 8-bit SDR or must read the+framebuffer at full depth, and which colour tags the saved file carries.++Per platform:++* **Windows** — the display configuration API reports the active colour mode+ (SDR / WCG / HDR, Windows 11 24H2+; older builds report "advanced colour"+ on or off), the bit depth and the SDR white level. The monitor's ICC+ profile comes from GDI.+* **macOS** — NSScreen reports extended dynamic range headroom and the+ screen's colour space (as ICC data).+* **Linux** — no portable API reports either; the answer is plain SDR with no+ profile, said honestly via ``source``.++Never raises: anything unknown is SDR, which is what every capture path+already handles.+"""++from __future__ import annotations++import logging+import struct+import sys+from dataclasses import dataclass+from typing import Literal++log = logging.getLogger(__name__)++Mode = Literal["sdr", "wcg", "hdr"]+Gamut = Literal["srgb", "p3", "bt2020"]++#: scRGB 1.0 is 80 nits; Windows' default SDR white in HDR mode is 200-240.+SCRGB_NITS = 80.0+#: Windows GDI monitor names look like ``\\.\DISPLAY1``.+_GDI_PREFIX = "\\\\.\\"+++@dataclass(frozen=True, slots=True)+class DisplayColor:+ mode: Mode = "sdr"+ bits_per_channel: int = 8+ #: Brightness of SDR white while the display runs HDR (Windows "SDR content+ #: brightness"). Plain SDR white is scRGB 1.0 = 80 nits by definition.+ sdr_white_nits: float = SCRGB_NITS+ #: The monitor's ICC profile, when the OS has one (SDR colour management).+ icc_profile: bytes | None = None+ #: Primaries of that profile, rounded to the nearest standard gamut.+ gamut: Gamut = "srgb"+ #: Where the answer came from — "default" means nothing could be asked.+ source: str = "default"++ @property+ def extended(self) -> bool:+ """True when the desktop holds more than 8-bit sRGB can carry."""+ return self.mode != "sdr"+++SDR = DisplayColor()+++def display_color(+ device_name: str | None = None, *, point: tuple[int, int] | None = None+) -> DisplayColor:+ """The colour state of one monitor, asked at capture time.++ ``device_name`` is the OS name of the monitor: the GDI name on Windows+ (``DISPLAY1`` behind the ``\\\\.\\`` prefix, what DXGI reports), the+ screen's localized name on macOS (Qt's ``QScreen.name()``). On Windows+ ``point`` — any physical desktop pixel on that monitor — finds it instead;+ Qt reports a friendly name there that no colour API knows. Neither means+ the primary monitor.+ """+ try:+ if sys.platform == "win32":+ if not (device_name or "").startswith(_GDI_PREFIX):+ device_name = device_at(point) if point is not None else None+ return _windows(device_name)+ if sys.platform == "darwin":+ return _macos(device_name)+ except Exception: # noqa: BLE001 - detection is advisory; SDR is always safe+ log.debug("display colour detection failed", exc_info=True)+ return SDR+++# ---------------------------------------------------------------------------+# ICC profile primaries+# ---------------------------------------------------------------------------+++def icc_gamut(profile: bytes | None) -> Gamut:+ """The standard gamut nearest to an ICC profile's red/green/blue colorants.++ Compares the colorant triangle's area in xy with sRGB's: Display P3 is+ about 1.36x sRGB, BT.2020 about 1.9x. A profile without colorant tags+ (LUT-based) counts as sRGB.+ """+ if not profile or len(profile) < 132:+ return "srgb"+ try:+ (count,) = struct.unpack_from(">I", profile, 128)+ tags: dict[bytes, tuple[float, float]] = {}+ for i in range(min(count, 200)):+ sig, offset, size = struct.unpack_from(">4sII", profile, 132 + 12 * i)+ if sig in (b"rXYZ", b"gXYZ", b"bXYZ") and size >= 20:+ x, y, z = (v / 65536.0 for v in struct.unpack_from(">iii", profile, offset + 8))+ total = x + y + z+ if total > 0:+ tags[sig] = (x / total, y / total)+ if len(tags) != 3:+ return "srgb"+ area = _triangle_area(tags[b"rXYZ"], tags[b"gXYZ"], tags[b"bXYZ"])+ except (struct.error, ValueError):+ return "srgb"+ # sRGB's colorants adapted to the profile white D50.+ srgb = _triangle_area((0.6484, 0.3309), (0.3212, 0.5978), (0.1559, 0.0660))+ ratio = area / srgb if srgb else 1.0+ if ratio >= 1.6:+ return "bt2020"+ if ratio >= 1.18:+ return "p3"+ return "srgb"+++def _triangle_area(a: tuple[float, float], b: tuple[float, float], c: tuple[float, float]) -> float:+ return abs((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])) / 2.0+++# ---------------------------------------------------------------------------+# Windows+# ---------------------------------------------------------------------------++_QDC_ONLY_ACTIVE_PATHS = 2+_GET_SOURCE_NAME = 1+_GET_ADVANCED_COLOR_INFO = 9+_GET_SDR_WHITE_LEVEL = 11+_GET_ADVANCED_COLOR_INFO_2 = 15+++def _windows(device_name: str | None) -> DisplayColor:+ import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415++ user32 = ctypes.WinDLL("user32")++ class LUID(ctypes.Structure):+ _fields_ = [("low", wintypes.DWORD), ("high", wintypes.LONG)]++ class Rational(ctypes.Structure):+ _fields_ = [("num", ctypes.c_uint32), ("den", ctypes.c_uint32)]++ class PathSource(ctypes.Structure):+ _fields_ = [+ ("adapter", LUID), ("id", ctypes.c_uint32),+ ("mode_index", ctypes.c_uint32), ("flags", ctypes.c_uint32),+ ]++ class PathTarget(ctypes.Structure):+ _fields_ = [+ ("adapter", LUID), ("id", ctypes.c_uint32), ("mode_index", ctypes.c_uint32),+ ("technology", ctypes.c_uint32), ("rotation", ctypes.c_uint32),+ ("scaling", ctypes.c_uint32), ("refresh", Rational),+ ("scanline", ctypes.c_uint32), ("available", wintypes.BOOL),+ ("flags", ctypes.c_uint32),+ ]++ class DisplayPath(ctypes.Structure):+ _fields_ = [("source", PathSource), ("target", PathTarget), ("flags", ctypes.c_uint32)]++ class ModeInfo(ctypes.Structure):+ _fields_ = [+ ("kind", ctypes.c_uint32), ("id", ctypes.c_uint32),+ ("adapter", LUID), ("info", ctypes.c_byte * 48),+ ]++ class Header(ctypes.Structure):+ _fields_ = [+ ("kind", ctypes.c_uint32), ("size", ctypes.c_uint32),+ ("adapter", LUID), ("id", ctypes.c_uint32),+ ]++ class SourceName(ctypes.Structure):+ _fields_ = [("header", Header), ("name", wintypes.WCHAR * 32)]++ class AdvancedColor(ctypes.Structure):+ _fields_ = [+ ("header", Header), ("flags", ctypes.c_uint32),+ ("encoding", ctypes.c_uint32), ("bits", ctypes.c_uint32),+ ]++ class AdvancedColor2(ctypes.Structure):+ _fields_ = [+ ("header", Header), ("flags", ctypes.c_uint32), ("encoding", ctypes.c_uint32),+ ("bits", ctypes.c_uint32), ("mode", ctypes.c_uint32),+ ]++ class WhiteLevel(ctypes.Structure):+ _fields_ = [("header", Header), ("level", ctypes.c_ulong)]++ def ask(info, kind: int, adapter, target_id: int) -> bool:+ info.header.kind = kind+ info.header.size = ctypes.sizeof(info)+ info.header.adapter = adapter+ info.header.id = target_id+ return user32.DisplayConfigGetDeviceInfo(ctypes.byref(info)) == 0++ path_count, mode_count = ctypes.c_uint32(), ctypes.c_uint32()+ if user32.GetDisplayConfigBufferSizes(+ _QDC_ONLY_ACTIVE_PATHS, ctypes.byref(path_count), ctypes.byref(mode_count)+ ):+ return SDR+ paths = (DisplayPath * max(1, path_count.value))()+ modes = (ModeInfo * max(1, mode_count.value))()+ if user32.QueryDisplayConfig(+ _QDC_ONLY_ACTIVE_PATHS, ctypes.byref(path_count), paths,+ ctypes.byref(mode_count), modes, None,+ ):+ return SDR+ wanted = (device_name or _primary_device_name()).casefold()+ for path in paths[: path_count.value]:+ source = SourceName()+ if not ask(source, _GET_SOURCE_NAME, path.source.adapter, path.source.id):+ continue+ if source.name.casefold() != wanted:+ continue+ adapter, target = path.target.adapter, path.target.id+ mode: Mode = "sdr"+ bits = 8+ info2 = AdvancedColor2()+ if ask(info2, _GET_ADVANCED_COLOR_INFO_2, adapter, target):+ mode = {1: "wcg", 2: "hdr"}.get(info2.mode, "sdr")+ bits = int(info2.bits) or 8+ else: # before Windows 11 24H2: advanced colour on means HDR+ info = AdvancedColor()+ if ask(info, _GET_ADVANCED_COLOR_INFO, adapter, target):+ enabled = bool(info.flags & 0b10)+ wide = bool(info.flags & 0b100)+ mode = "hdr" if enabled else ("wcg" if wide else "sdr")+ bits = int(info.bits) or 8+ white = SCRGB_NITS+ level = WhiteLevel()+ if mode != "sdr" and ask(level, _GET_SDR_WHITE_LEVEL, adapter, target) and level.level:+ white = level.level * SCRGB_NITS / 1000.0+ profile = _windows_icc(source.name)+ return DisplayColor(+ mode=mode,+ bits_per_channel=bits,+ sdr_white_nits=white,+ icc_profile=profile,+ gamut=icc_gamut(profile),+ source="windows-displayconfig",+ )+ return SDR+++def device_at(point: tuple[int, int] | None) -> str | None:+ """Windows: the GDI name of the monitor holding physical ``point``."""+ if sys.platform != "win32":+ return None+ try:+ return _monitor_device(point or (0, 0))+ except Exception: # noqa: BLE001 - advisory, like the rest of this module+ log.debug("monitor lookup failed", exc_info=True)+ return None+++def _primary_device_name() -> str:+ return _monitor_device((0, 0))+++def _monitor_device(point: tuple[int, int]) -> str:+ import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415++ class MonitorInfo(ctypes.Structure):+ _fields_ = [+ ("size", wintypes.DWORD), ("monitor", wintypes.RECT), ("work", wintypes.RECT),+ ("flags", wintypes.DWORD), ("device", wintypes.WCHAR * 32),+ ]++ user32 = ctypes.WinDLL("user32")+ user32.MonitorFromPoint.restype = wintypes.HMONITOR+ user32.MonitorFromPoint.argtypes = [wintypes.POINT, wintypes.DWORD]+ handle = user32.MonitorFromPoint(+ wintypes.POINT(int(point[0]), int(point[1])), 2+ ) # MONITOR_DEFAULTTONEAREST+ info = MonitorInfo()+ info.size = ctypes.sizeof(info)+ user32.GetMonitorInfoW.argtypes = [wintypes.HMONITOR, ctypes.POINTER(MonitorInfo)]+ if not user32.GetMonitorInfoW(handle, ctypes.byref(info)):+ return r"\\.\DISPLAY1"+ return info.device+++def _windows_icc(device_name: str) -> bytes | None:+ """The ICC profile Windows colour-manages this monitor with, if any."""+ import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415+ from pathlib import Path # noqa: PLC0415++ gdi32 = ctypes.WinDLL("gdi32")+ gdi32.CreateDCW.restype = wintypes.HDC+ gdi32.CreateDCW.argtypes = [+ wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPCWSTR, ctypes.c_void_p+ ]+ gdi32.GetICMProfileW.argtypes = [wintypes.HDC, ctypes.POINTER(wintypes.DWORD), wintypes.LPWSTR]+ gdi32.DeleteDC.argtypes = [wintypes.HDC]+ hdc = gdi32.CreateDCW("DISPLAY", device_name, None, None)+ if not hdc:+ return None+ try:+ size = wintypes.DWORD(260)+ buffer = ctypes.create_unicode_buffer(size.value)+ if not gdi32.GetICMProfileW(hdc, ctypes.byref(size), buffer):+ return None+ path = Path(buffer.value)+ finally:+ gdi32.DeleteDC(hdc)+ try:+ data = path.read_bytes()+ except OSError:+ return None+ # The generic sRGB profile adds nothing a plain sRGB file does not say.+ return data if len(data) >= 132 and data[36:40] == b"acsp" else None+++# ---------------------------------------------------------------------------+# macOS+# ---------------------------------------------------------------------------+++def _macos(device_name: str | None) -> DisplayColor:+ from AppKit import NSScreen # noqa: PLC0415++ screens = list(NSScreen.screens() or [])+ if not screens:+ return SDR+ screen = screens[0]+ if device_name:+ for candidate in screens:+ name = getattr(candidate, "localizedName", None)+ if callable(name) and str(name()) == device_name:+ screen = candidate+ break+ headroom = float(screen.maximumExtendedDynamicRangeColorComponentValue())+ potential = float(screen.maximumPotentialExtendedDynamicRangeColorComponentValue())+ space = screen.colorSpace()+ data = space.ICCProfileData() if space is not None else None+ profile = bytes(data) if data is not None else None+ gamut = icc_gamut(profile)+ if headroom > 1.0 or potential > 1.0:+ mode: Mode = "hdr"+ elif gamut != "srgb":+ mode = "wcg"+ else:+ mode = "sdr"+ return DisplayColor(+ mode=mode,+ bits_per_channel=10 if mode != "sdr" else 8,+ icc_profile=profile,+ gamut=gamut,+ source="macos-nsscreen",+ )diff --git a/jarvis/platform/win_duplication.py b/jarvis/platform/win_duplication.pynew file mode 100644index 0000000000..bae9b65d47--- /dev/null+++ b/jarvis/platform/win_duplication.py@@ -0,0 +1,848 @@+"""Windows: read a monitor's framebuffer at full depth (Desktop Duplication, FP16).++GDI, mss and 8-bit Windows Graphics Capture hand back an SDR copy of an HDR+desktop: highlights clip and the wide gamut is squeezed into sRGB. Desktop+Duplication with ``DuplicateOutput1`` and an FP16 format returns what the+compositor scans out — scRGB, linear light, BT.709 primaries with values+beyond 0..1, where 1.0 is 80 nits.++Two consumers:++* :meth:`DesktopDuplication.read_linear` — one full frame as an FP16 array,+ for screenshots.+* :meth:`DesktopDuplication.read_p010` — a crop, scaled to the video size and+ converted ON THE GPU to BT.2020 PQ 10-bit 4:2:0 (P010 planes), with the+ mouse pointer drawn in. A 4K frame never crosses the bus as FP16, which is+ what keeps 60 FPS recording possible.++Windows-only by construction (D3D11/DXGI through ctypes, no extra package);+importing elsewhere is harmless and :func:`available` says no. Windows that+:class:`exclude_from_capture <jarvis.platform.capture_exclusion>` excludes+stay out of these frames, exactly as with Windows Graphics Capture.+"""++from __future__ import annotations++import ctypes+import logging+import sys+from ctypes import wintypes+from dataclasses import dataclass+from typing import Any++log = logging.getLogger(__name__)++_DXGI_FORMAT_R16G16B16A16_FLOAT = 10+_DXGI_FORMAT_R16G16_UNORM = 35+_DXGI_FORMAT_R16_UNORM = 56+_DXGI_FORMAT_R8G8B8A8_UNORM = 28+_D3D11_USAGE_DEFAULT = 0+_D3D11_USAGE_STAGING = 3+_D3D11_BIND_CONSTANT_BUFFER = 0x4+_D3D11_BIND_SHADER_RESOURCE = 0x8+_D3D11_BIND_UNORDERED_ACCESS = 0x80+_D3D11_CPU_ACCESS_READ = 0x20000+_D3D11_MAP_READ = 1+_D3D_FEATURE_LEVEL_11_0 = 0xB000+_D3D11_SDK_VERSION = 7+_D3D_DRIVER_TYPE_UNKNOWN = 0+_D3D11_FILTER_MIN_MAG_MIP_LINEAR = 0x15+_D3D11_TEXTURE_ADDRESS_CLAMP = 3+_DXGI_ERROR_NOT_FOUND = -2005270526 # 0x887A0002+_DXGI_ERROR_WAIT_TIMEOUT = -2005270489 # 0x887A0027+_DXGI_ERROR_ACCESS_LOST = -2005270490 # 0x887A0026+_ROTATION_IDENTITY = (0, 1) # UNSPECIFIED, IDENTITY+_POINTER_MONOCHROME, _POINTER_COLOR, _POINTER_MASKED = 1, 2, 4++# vtable slots (IUnknown = 0..2)+_QUERY_INTERFACE, _RELEASE = 0, 2+_FACTORY1_ENUM_ADAPTERS1 = 12+_ADAPTER_ENUM_OUTPUTS = 7+_OUTPUT_GET_DESC = 7+_OUTPUT5_DUPLICATE_OUTPUT1 = 26+_OUTPUT6_GET_DESC1 = 27+_DUP_GET_DESC, _DUP_ACQUIRE, _DUP_POINTER_SHAPE, _DUP_RELEASE_FRAME = 7, 8, 11, 14+_DEV_CREATE_BUFFER, _DEV_CREATE_TEXTURE2D = 3, 5+_DEV_CREATE_SRV, _DEV_CREATE_UAV = 7, 8+_DEV_CREATE_COMPUTE_SHADER, _DEV_CREATE_SAMPLER = 18, 23+_DEV_GET_IMMEDIATE_CONTEXT = 40+_CTX_MAP, _CTX_UNMAP, _CTX_DISPATCH = 14, 15, 41+_CTX_COPY_RESOURCE, _CTX_UPDATE_SUBRESOURCE = 47, 48+_CTX_CS_SRV, _CTX_CS_UAV, _CTX_CS_SHADER, _CTX_CS_SAMPLERS, _CTX_CS_CBUFFERS = 67, 68, 69, 70, 71+_BLOB_POINTER, _BLOB_SIZE = 3, 4++#: Linear scRGB in, BT.2020 PQ limited-range P010 out (Y plane + interleaved+#: CbCr at half resolution). One thread per 2x2 block. The pointer is drawn+#: before conversion, at SDR white, so it looks like the one on screen.+_SHADER = r"""+Texture2D<float4> Desk : register(t0);+Texture2D<float4> Cur : register(t1);+SamplerState Lin : register(s0);+RWTexture2D<float> OutY : register(u0);+RWTexture2D<float2> OutUV : register(u1);+cbuffer Params : register(b0) {+ float4 Crop; // x, y, w, h in desktop pixels+ float4 Sizes; // desktop w, h, output w, h+ float4 CursorRect; // x, y, w, h in desktop pixels; w == 0: no pointer+ float4 Scales; // x: scRGB value of SDR white+};+static const float3x3 To2020 = {+ 0.627404, 0.329283, 0.043313,+ 0.069097, 0.919540, 0.011362,+ 0.016391, 0.088013, 0.895595 };+static const float3 Luma = float3(0.2627, 0.6780, 0.0593);++float3 Pq(float3 l) {+ float3 y = saturate(max(l, 0.0) * (80.0 / 10000.0));+ float3 p = pow(y, 0.1593017578125);+ return pow((0.8359375 + 18.8515625 * p) / (1.0 + 18.6875 * p), 78.84375);+}++float3 SrgbToLinear(float3 c) {+ float3 lo = c / 12.92;+ float3 hi = pow((c + 0.055) / 1.055, 2.4);+ return float3(c.r <= 0.04045 ? lo.r : hi.r,+ c.g <= 0.04045 ? lo.g : hi.g,+ c.b <= 0.04045 ? lo.b : hi.b);+}++float3 Fetch(float2 px) {+ float2 pos = Crop.xy + (px + 0.5) * Crop.zw / Sizes.zw;+ float3 c = Desk.SampleLevel(Lin, pos / Sizes.xy, 0).rgb;+ if (CursorRect.z > 0) {+ float2 q = pos - CursorRect.xy;+ if (q.x >= 0 && q.y >= 0 && q.x < CursorRect.z && q.y < CursorRect.w) {+ float4 k = Cur.Load(int3(int2(q), 0));+ if (abs(k.a * 255.0 - 1.0) < 0.5) {+ // An inverting pointer pixel: the opposite of what is below.+ float l = dot(c, float3(0.2126, 0.7152, 0.0722)) / Scales.x;+ c = (l < 0.5 ? 1.0 : 0.0) * Scales.x;+ } else {+ c = lerp(c, SrgbToLinear(k.rgb) * Scales.x, k.a);+ }+ }+ }+ return mul(To2020, c);+}++[numthreads(8, 8, 1)]+void main(uint3 id : SV_DispatchThreadID) {+ uint2 half = uint2(Sizes.zw) / 2;+ if (id.x >= half.x || id.y >= half.y) return;+ float3 acc = 0.0;+ [unroll] for (uint i = 0; i < 4; i++) {+ uint2 p = id.xy * 2 + uint2(i & 1, i >> 1);+ float3 e = Pq(Fetch(float2(p)));+ OutY[p] = round(64.0 + 876.0 * dot(e, Luma)) * 64.0 / 65535.0;+ acc += e;+ }+ acc *= 0.25;+ float yc = dot(acc, Luma);+ float cb = round(512.0 + 896.0 * (acc.b - yc) / 1.8814);+ float cr = round(512.0 + 896.0 * (acc.r - yc) / 1.4746);+ OutUV[id.xy] = float2(cb, cr) * 64.0 / 65535.0;+}+"""+++class DuplicationUnavailable(RuntimeError):+ """This monitor cannot be read at full depth here; use the SDR path."""+++class AccessLost(DuplicationUnavailable):+ """The desktop switched (mode change, secure desktop, full-screen app)."""+++@dataclass(frozen=True, slots=True)+class OutputInfo:+ device_name: str+ #: Desktop rectangle in physical pixels: left, top, right, bottom.+ rect: tuple[int, int, int, int]+ bits_per_color: int+ #: DXGI_COLOR_SPACE_TYPE; 12 = RGB full G2084 P2020 (HDR), 0 = sRGB.+ color_space: int+ max_nits: float+ max_full_frame_nits: float+ min_nits: float++ @property+ def hdr(self) -> bool:+ return self.color_space == 12++ @property+ def size(self) -> tuple[int, int]:+ return self.rect[2] - self.rect[0], self.rect[3] - self.rect[1]+++def available() -> bool:+ return sys.platform == "win32"+++class _GUID(ctypes.Structure):+ _fields_ = [+ ("d1", ctypes.c_uint32), ("d2", ctypes.c_uint16),+ ("d3", ctypes.c_uint16), ("d4", ctypes.c_ubyte * 8),+ ]++ @classmethod+ def parse(cls, text: str) -> _GUID:+ import uuid # noqa: PLC0415++ raw = uuid.UUID(text).bytes_le+ guid = cls()+ ctypes.memmove(ctypes.byref(guid), raw, 16)+ return guid+++_IID_FACTORY1 = _GUID.parse("770aae78-f26f-4dba-a829-253c83d1b387")+_IID_OUTPUT5 = _GUID.parse("80a07424-ab52-42eb-833c-0c42fd282d98")+_IID_OUTPUT6 = _GUID.parse("068346e8-aaec-4b84-add7-137f513f77a1")+_IID_TEXTURE2D = _GUID.parse("6f15aaf2-d208-4e89-9ab4-489535d34f9c")+++class _OutputDesc(ctypes.Structure):+ _fields_ = [+ ("name", wintypes.WCHAR * 32), ("rect", wintypes.RECT),+ ("attached", wintypes.BOOL), ("rotation", ctypes.c_uint32),+ ("monitor", wintypes.HMONITOR),+ ]+++class _OutputDesc1(ctypes.Structure):+ _fields_ = [+ ("name", wintypes.WCHAR * 32), ("rect", wintypes.RECT),+ ("attached", wintypes.BOOL), ("rotation", ctypes.c_uint32),+ ("monitor", wintypes.HMONITOR), ("bits", ctypes.c_uint32),+ ("color_space", ctypes.c_uint32), ("primaries", ctypes.c_float * 8),+ ("min_nits", ctypes.c_float), ("max_nits", ctypes.c_float),+ ("max_full_frame_nits", ctypes.c_float),+ ]+++class _ModeDesc(ctypes.Structure):+ _fields_ = [+ ("width", ctypes.c_uint32), ("height", ctypes.c_uint32),+ ("refresh_num", ctypes.c_uint32), ("refresh_den", ctypes.c_uint32),+ ("format", ctypes.c_uint32), ("scanline", ctypes.c_uint32),+ ("scaling", ctypes.c_uint32),+ ]+++class _DuplDesc(ctypes.Structure):+ _fields_ = [("mode", _ModeDesc), ("rotation", ctypes.c_uint32), ("in_memory", wintypes.BOOL)]+++class _PointerPosition(ctypes.Structure):+ _fields_ = [("position", wintypes.POINT), ("visible", wintypes.BOOL)]+++class _FrameInfo(ctypes.Structure):+ _fields_ = [+ ("last_present", ctypes.c_int64), ("last_mouse", ctypes.c_int64),+ ("accumulated", ctypes.c_uint32), ("coalesced", wintypes.BOOL),+ ("protected_masked", wintypes.BOOL), ("pointer", _PointerPosition),+ ("metadata_size", ctypes.c_uint32), ("pointer_shape_size", ctypes.c_uint32),+ ]+++class _PointerShapeInfo(ctypes.Structure):+ _fields_ = [+ ("type", ctypes.c_uint32), ("width", ctypes.c_uint32),+ ("height", ctypes.c_uint32), ("pitch", ctypes.c_uint32),+ ("hotspot", wintypes.POINT),+ ]+++class _Texture2DDesc(ctypes.Structure):+ _fields_ = [+ ("width", ctypes.c_uint32), ("height", ctypes.c_uint32),+ ("mips", ctypes.c_uint32), ("array", ctypes.c_uint32),+ ("format", ctypes.c_uint32), ("samples", ctypes.c_uint32),+ ("quality", ctypes.c_uint32), ("usage", ctypes.c_uint32),+ ("bind", ctypes.c_uint32), ("cpu", ctypes.c_uint32), ("misc", ctypes.c_uint32),+ ]+++class _BufferDesc(ctypes.Structure):+ _fields_ = [+ ("size", ctypes.c_uint32), ("usage", ctypes.c_uint32), ("bind", ctypes.c_uint32),+ ("cpu", ctypes.c_uint32), ("misc", ctypes.c_uint32), ("stride", ctypes.c_uint32),+ ]+++class _SubresourceData(ctypes.Structure):+ _fields_ = [("data", ctypes.c_void_p), ("pitch", ctypes.c_uint32), ("slice", ctypes.c_uint32)]+++class _Mapped(ctypes.Structure):+ _fields_ = [("data", ctypes.c_void_p), ("pitch", ctypes.c_uint32), ("depth", ctypes.c_uint32)]+++class _SamplerDesc(ctypes.Structure):+ _fields_ = [+ ("filter", ctypes.c_uint32), ("u", ctypes.c_uint32), ("v", ctypes.c_uint32),+ ("w", ctypes.c_uint32), ("lod_bias", ctypes.c_float),+ ("anisotropy", ctypes.c_uint32), ("compare", ctypes.c_uint32),+ ("border", ctypes.c_float * 4), ("min_lod", ctypes.c_float), ("max_lod", ctypes.c_float),+ ]+++class _Params(ctypes.Structure):+ _fields_ = [+ ("crop", ctypes.c_float * 4), ("sizes", ctypes.c_float * 4),+ ("cursor", ctypes.c_float * 4), ("scales", ctypes.c_float * 4),+ ]+++class _Com:+ """A raw COM pointer with vtable calls by slot; :meth:`release` exactly once."""++ __slots__ = ("ptr",)++ def __init__(self, ptr: int | None) -> None:+ if not ptr:+ raise DuplicationUnavailable("A graphics object could not be created.")+ self.ptr = ptr++ def call(self, slot: int, *args: Any, restype: Any = ctypes.c_long) -> Any:+ vtable = ctypes.cast(+ ctypes.cast(self.ptr, ctypes.POINTER(ctypes.c_void_p))[0],+ ctypes.POINTER(ctypes.c_void_p),+ )+ prototype = ctypes.WINFUNCTYPE(restype, ctypes.c_void_p, *map(_argtype, args))+ return prototype(vtable[slot])(self.ptr, *args)++ def check(self, slot: int, *args: Any, what: str) -> None:+ hr = self.call(slot, *args)+ if hr < 0:+ _raise(hr, what)++ def query(self, iid: _GUID) -> _Com:+ out = ctypes.c_void_p()+ hr = self.call(_QUERY_INTERFACE, ctypes.pointer(iid), ctypes.pointer(out))+ if hr < 0:+ _raise(hr, "query interface")+ return _Com(out.value)++ def release(self) -> None:+ if self.ptr:+ self.call(_RELEASE, restype=ctypes.c_ulong)+ self.ptr = 0+++def _argtype(arg: Any) -> Any:+ """Plain numbers keep their C type; everything pointer-like goes as ``void*``.++ ``c_void_p`` accepts ``None``, ``byref()``, arrays and pointer instances.+ """+ if isinstance(arg, ctypes._SimpleCData) and not isinstance( # noqa: SLF001+ arg, (ctypes.c_void_p, ctypes.c_char_p)+ ):+ return type(arg)+ return ctypes.c_void_p+++def _raise(hr: int, what: str) -> None:+ if hr == _DXGI_ERROR_ACCESS_LOST:+ raise AccessLost(f"Desktop duplication lost access during {what}.")+ raise DuplicationUnavailable(f"{what} failed (HRESULT 0x{hr & 0xFFFFFFFF:08X}).")+++def _out() -> ctypes.c_void_p:+ return ctypes.c_void_p()+++def _compile_shader() -> bytes:+ compiler = ctypes.WinDLL("d3dcompiler_47")+ source = _SHADER.encode("ascii")+ code, errors = ctypes.c_void_p(), ctypes.c_void_p()+ compiler.D3DCompile.restype = ctypes.c_long+ hr = compiler.D3DCompile(+ source, ctypes.c_size_t(len(source)), b"appshot_p010", None, None,+ b"main", b"cs_5_0", ctypes.c_uint(1 << 15), ctypes.c_uint(0), # OPTIMIZATION_LEVEL3+ ctypes.byref(code), ctypes.byref(errors),+ )+ if errors.value:+ blob = _Com(errors.value)+ size = blob.call(_BLOB_SIZE, restype=ctypes.c_size_t)+ text = ctypes.string_at(blob.call(_BLOB_POINTER, restype=ctypes.c_void_p), size)+ blob.release()+ if hr < 0:+ raise DuplicationUnavailable(f"Shader compile failed: {text.decode(errors='replace')}")+ if hr < 0 or not code.value:+ _raise(hr, "shader compile")+ blob = _Com(code.value)+ try:+ size = blob.call(_BLOB_SIZE, restype=ctypes.c_size_t)+ return ctypes.string_at(blob.call(_BLOB_POINTER, restype=ctypes.c_void_p), size)+ finally:+ blob.release()+++class DesktopDuplication:+ """One monitor, duplicated at FP16. Not thread-safe: use from one thread.++ ``device_name`` is the monitor's GDI name (``\\\\.\\DISPLAY1``); ``None``+ takes the first monitor on the first adapter. Raises+ :class:`DuplicationUnavailable` when the monitor cannot be duplicated+ (rotated, remote session, no D3D11) — callers fall back to SDR capture.+ """++ def __init__(self, device_name: str | None = None) -> None:+ if not available():+ raise DuplicationUnavailable("Desktop duplication exists only on Windows.")+ self._objects: list[_Com] = []+ self._dup: _Com | None = None+ self._desktop: _Com | None = None+ self._desktop_srv: _Com | None = None+ self._has_frame = False+ self._pointer_pos = (0, 0)+ self._pointer_visible = False+ self._pointer_size = (0, 0)+ self._pointer_srv: _Com | None = None+ self._pointer_tex: _Com | None = None+ self._p010: dict[str, Any] = {}+ self._shader: _Com | None = None+ try:+ self._open(device_name)+ except BaseException:+ self.close()+ raise++ # -- setup ---------------------------------------------------------------+ def _keep(self, obj: _Com) -> _Com:+ self._objects.append(obj)+ return obj++ def _open(self, device_name: str | None) -> None:+ from jarvis.core.win32_dpi import per_monitor_dpi_context # noqa: PLC0415++ dxgi = ctypes.WinDLL("dxgi")+ d3d11 = ctypes.WinDLL("d3d11")+ factory_ptr = _out()+ hr = dxgi.CreateDXGIFactory1(ctypes.byref(_IID_FACTORY1), ctypes.byref(factory_ptr))+ if hr < 0:+ _raise(hr, "CreateDXGIFactory1")+ factory = self._keep(_Com(factory_ptr.value))+ adapter, output, desc = self._find_output(factory, device_name)+ level = ctypes.c_uint32(_D3D_FEATURE_LEVEL_11_0)+ device_ptr, context_ptr = _out(), _out()+ hr = d3d11.D3D11CreateDevice(+ ctypes.c_void_p(adapter.ptr), _D3D_DRIVER_TYPE_UNKNOWN, None, 0,+ ctypes.byref(level), 1, _D3D11_SDK_VERSION,+ ctypes.byref(device_ptr), None, ctypes.byref(context_ptr),+ )+ if hr < 0:+ _raise(hr, "D3D11CreateDevice")+ self._device = self._keep(_Com(device_ptr.value))+ self._context = self._keep(_Com(context_ptr.value))+ self._output5 = self._keep(output.query(_IID_OUTPUT5))+ info = self._describe(output, desc)+ self.info = info+ formats = (ctypes.c_uint32 * 1)(_DXGI_FORMAT_R16G16B16A16_FLOAT)+ dup = _out()+ # DuplicateOutput1 refuses a DPI-unaware thread.+ with per_monitor_dpi_context():+ hr = self._output5.call(+ _OUTPUT5_DUPLICATE_OUTPUT1, ctypes.c_void_p(self._device.ptr),+ ctypes.c_uint(0), ctypes.c_uint(1), formats, ctypes.byref(dup),+ )+ if hr < 0:+ _raise(hr, "DuplicateOutput1")+ self._dup = _Com(dup.value)+ dupl = _DuplDesc()+ self._dup.call(_DUP_GET_DESC, ctypes.byref(dupl), restype=None)+ if dupl.rotation not in _ROTATION_IDENTITY:+ raise DuplicationUnavailable("Rotated monitors are recorded with the SDR path.")+ self.size = (int(dupl.mode.width), int(dupl.mode.height))+ self.refresh_hz = (+ dupl.mode.refresh_num / dupl.mode.refresh_den if dupl.mode.refresh_den else 0.0+ )+ self._desktop = self._texture(+ self.size, _DXGI_FORMAT_R16G16B16A16_FLOAT, bind=_D3D11_BIND_SHADER_RESOURCE+ )+ self._desktop_srv = self._view(_DEV_CREATE_SRV, self._desktop)++ def _find_output(self, factory: _Com, device_name: str | None):+ wanted = (device_name or "").casefold()+ index = 0+ while True:+ adapter_ptr = _out()+ hr = factory.call(+ _FACTORY1_ENUM_ADAPTERS1, ctypes.c_uint(index), ctypes.byref(adapter_ptr)+ )+ if hr == _DXGI_ERROR_NOT_FOUND:+ break+ if hr < 0:+ _raise(hr, "EnumAdapters1")+ adapter = _Com(adapter_ptr.value)+ slot = 0+ found = None+ while True:+ output_ptr = _out()+ hr = adapter.call(+ _ADAPTER_ENUM_OUTPUTS, ctypes.c_uint(slot), ctypes.byref(output_ptr)+ )+ if hr < 0:+ break+ output = _Com(output_ptr.value)+ desc = _OutputDesc()+ output.check(_OUTPUT_GET_DESC, ctypes.byref(desc), what="output description")+ if found is None and (not wanted or desc.name.casefold() == wanted):+ found = (output, desc)+ else:+ output.release()+ slot += 1+ if found is not None:+ self._keep(adapter)+ self._keep(found[0])+ return adapter, found[0], found[1]+ adapter.release()+ index += 1+ raise DuplicationUnavailable(f"No graphics output drives {device_name or 'a monitor'}.")++ def _describe(self, output: _Com, desc: _OutputDesc) -> OutputInfo:+ rect = (desc.rect.left, desc.rect.top, desc.rect.right, desc.rect.bottom)+ try:+ output6 = output.query(_IID_OUTPUT6)+ except DuplicationUnavailable:+ return OutputInfo(desc.name, rect, 8, 0, 0.0, 0.0, 0.0)+ try:+ d1 = _OutputDesc1()+ output6.check(_OUTPUT6_GET_DESC1, ctypes.byref(d1), what="output description")+ finally:+ output6.release()+ return OutputInfo(+ desc.name, rect, int(d1.bits), int(d1.color_space),+ float(d1.max_nits), float(d1.max_full_frame_nits), float(d1.min_nits),+ )++ def _texture(+ self, size: tuple[int, int], fmt: int, *, bind: int = 0, staging: bool = False,+ initial: tuple[Any, int] | None = None,+ ) -> _Com:+ desc = _Texture2DDesc(+ width=size[0], height=size[1], mips=1, array=1, format=fmt, samples=1,+ usage=_D3D11_USAGE_STAGING if staging else _D3D11_USAGE_DEFAULT,+ bind=0 if staging else bind, cpu=_D3D11_CPU_ACCESS_READ if staging else 0,+ )+ data = None+ if initial is not None:+ data = ctypes.byref(_SubresourceData(initial[0], initial[1], 0))+ out = _out()+ self._device.check(+ _DEV_CREATE_TEXTURE2D, ctypes.byref(desc), data, ctypes.byref(out), what="texture"+ )+ return self._keep(_Com(out.value))++ def _view(self, slot: int, resource: _Com) -> _Com:+ out = _out()+ self._device.check(+ slot, ctypes.c_void_p(resource.ptr), None, ctypes.byref(out), what="resource view"+ )+ return self._keep(_Com(out.value))++ # -- frames --------------------------------------------------------------+ def acquire(self, timeout_ms: int = 0) -> bool:+ """Take the newest desktop image if one arrived. True when it changed.++ The previous image stays readable when nothing new arrived, so a+ static screen keeps recording the same picture.+ """+ if self._dup is None:+ raise AccessLost("The duplication is closed.")+ info = _FrameInfo()+ resource = _out()+ hr = self._dup.call(+ _DUP_ACQUIRE, ctypes.c_uint(max(0, int(timeout_ms))),+ ctypes.byref(info), ctypes.byref(resource),+ )+ if hr == _DXGI_ERROR_WAIT_TIMEOUT:+ return False+ if hr < 0:+ _raise(hr, "AcquireNextFrame")+ changed = False+ try:+ if info.last_mouse:+ self._pointer_visible = bool(info.pointer.visible)+ self._pointer_pos = (int(info.pointer.position.x), int(info.pointer.position.y))+ if info.pointer_shape_size:+ self._read_pointer_shape(int(info.pointer_shape_size))+ # Only a presented frame holds the desktop: the very first acquire+ # of an FP16 duplication returns an all-black surface.+ if info.last_present:+ texture = _Com(resource.value).query(_IID_TEXTURE2D)+ try:+ self._context.call(+ _CTX_COPY_RESOURCE, ctypes.c_void_p(self._desktop.ptr),+ ctypes.c_void_p(texture.ptr), restype=None,+ )+ finally:+ texture.release()+ self._has_frame = True+ changed = True+ finally:+ if resource.value:+ _Com(resource.value).release()+ self._dup.call(_DUP_RELEASE_FRAME)+ return changed or bool(info.last_mouse)++ def wait_first_frame(self, timeout_ms: int = 1000) -> None:+ """Block until the desktop image is readable (the first presented frame).++ A desktop where nothing moves presents nothing; then this raises and the+ caller takes the SDR path instead of waiting longer.+ """+ import time # noqa: PLC0415++ deadline = time.monotonic() + timeout_ms / 1000.0+ while not self._has_frame:+ remaining = int((deadline - time.monotonic()) * 1000)+ if remaining <= 0:+ raise DuplicationUnavailable("The desktop image did not arrive in time.")+ self.acquire(min(remaining, 100))++ def read_linear(self) -> Any:+ """The whole monitor as ``float16`` ``(height, width, 4)`` scRGB (1.0 = 80 nits)."""+ import numpy as np # noqa: PLC0415++ self.wait_first_frame()+ staging = self._texture(self.size, _DXGI_FORMAT_R16G16B16A16_FLOAT, staging=True)+ try:+ self._context.call(+ _CTX_COPY_RESOURCE, ctypes.c_void_p(staging.ptr),+ ctypes.c_void_p(self._desktop.ptr), restype=None,+ )+ return self._read_back(staging, self.size, np.float16, 4)+ finally:+ self._objects.remove(staging)+ staging.release()++ def read_p010(+ self,+ crop: tuple[int, int, int, int],+ out_size: tuple[int, int],+ *,+ sdr_white: float = 1.0,+ draw_pointer: bool = True,+ ) -> tuple[Any, Any]:+ """``crop`` (x, y, w, h, monitor pixels) as BT.2020 PQ P010 planes of ``out_size``.++ Returns ``(y, uv)``: ``uint16`` arrays of shape ``(h, w)`` and+ ``(h/2, w/2, 2)``, 10-bit codes in the high bits as P010 stores them.+ ``sdr_white`` is the scRGB value of SDR white, used for the pointer.+ """+ import numpy as np # noqa: PLC0415++ width, height = out_size+ if width % 2 or height % 2 or width < 2 or height < 2:+ raise ValueError("P010 needs an even output size.")+ self.wait_first_frame()+ planes = self._p010_targets(out_size)+ params = _Params()+ params.crop[:] = [float(v) for v in crop]+ params.sizes[:] = [float(self.size[0]), float(self.size[1]), float(width), float(height)]+ if draw_pointer and self._pointer_visible and self._pointer_srv is not None:+ params.cursor[:] = [+ float(self._pointer_pos[0]), float(self._pointer_pos[1]),+ float(self._pointer_size[0]), float(self._pointer_size[1]),+ ]+ params.scales[0] = float(sdr_white)+ ctx = self._context+ ctx.call(+ _CTX_UPDATE_SUBRESOURCE, ctypes.c_void_p(planes["cbuffer"].ptr), ctypes.c_uint(0),+ None, ctypes.byref(params), ctypes.c_uint(0), ctypes.c_uint(0), restype=None,+ )+ pointer_srv = self._pointer_srv.ptr if self._pointer_srv is not None else None+ srvs = (ctypes.c_void_p * 2)(self._desktop_srv.ptr, pointer_srv)+ uavs = (ctypes.c_void_p * 2)(planes["y_uav"].ptr, planes["uv_uav"].ptr)+ samplers = (ctypes.c_void_p * 1)(planes["sampler"].ptr)+ buffers = (ctypes.c_void_p * 1)(planes["cbuffer"].ptr)+ ctx.call(_CTX_CS_SHADER, ctypes.c_void_p(self._shader.ptr), None, ctypes.c_uint(0),+ restype=None)+ ctx.call(_CTX_CS_SRV, ctypes.c_uint(0), ctypes.c_uint(2), srvs, restype=None)+ ctx.call(_CTX_CS_UAV, ctypes.c_uint(0), ctypes.c_uint(2), uavs, None, restype=None)+ ctx.call(_CTX_CS_SAMPLERS, ctypes.c_uint(0), ctypes.c_uint(1), samplers, restype=None)+ ctx.call(_CTX_CS_CBUFFERS, ctypes.c_uint(0), ctypes.c_uint(1), buffers, restype=None)+ ctx.call(+ _CTX_DISPATCH, ctypes.c_uint((width // 2 + 7) // 8),+ ctypes.c_uint((height // 2 + 7) // 8), ctypes.c_uint(1), restype=None,+ )+ # Unbind the outputs so the copies below see finished writes.+ none2 = (ctypes.c_void_p * 2)(None, None)+ ctx.call(_CTX_CS_UAV, ctypes.c_uint(0), ctypes.c_uint(2), none2, None, restype=None)+ ctx.call(_CTX_CS_SRV, ctypes.c_uint(0), ctypes.c_uint(2), none2, restype=None)+ for name in ("y", "uv"):+ ctx.call(+ _CTX_COPY_RESOURCE, ctypes.c_void_p(planes[f"{name}_stage"].ptr),+ ctypes.c_void_p(planes[name].ptr), restype=None,+ )+ y = self._read_back(planes["y_stage"], (width, height), np.uint16, 1)[..., 0]+ uv = self._read_back(planes["uv_stage"], (width // 2, height // 2), np.uint16, 2)+ return y, uv++ def _p010_targets(self, size: tuple[int, int]) -> dict[str, Any]:+ if self._p010.get("size") == size:+ return self._p010+ if self._shader is None:+ code = _compile_shader()+ out = _out()+ self._device.check(+ _DEV_CREATE_COMPUTE_SHADER, ctypes.c_char_p(code), ctypes.c_size_t(len(code)),+ None, ctypes.byref(out), what="compute shader",+ )+ self._shader = self._keep(_Com(out.value))+ for key in ("y", "uv", "y_uav", "uv_uav", "y_stage", "uv_stage"):+ obj = self._p010.pop(key, None)+ if obj is not None:+ self._objects.remove(obj)+ obj.release()+ width, height = size+ half = (width // 2, height // 2)+ targets = self._p010+ targets["y"] = self._texture(+ size, _DXGI_FORMAT_R16_UNORM, bind=_D3D11_BIND_UNORDERED_ACCESS+ )+ targets["uv"] = self._texture(+ half, _DXGI_FORMAT_R16G16_UNORM, bind=_D3D11_BIND_UNORDERED_ACCESS+ )+ targets["y_uav"] = self._view(_DEV_CREATE_UAV, targets["y"])+ targets["uv_uav"] = self._view(_DEV_CREATE_UAV, targets["uv"])+ targets["y_stage"] = self._texture(size, _DXGI_FORMAT_R16_UNORM, staging=True)+ targets["uv_stage"] = self._texture(half, _DXGI_FORMAT_R16G16_UNORM, staging=True)+ if "sampler" not in targets:+ desc = _SamplerDesc(+ filter=_D3D11_FILTER_MIN_MAG_MIP_LINEAR, u=_D3D11_TEXTURE_ADDRESS_CLAMP,+ v=_D3D11_TEXTURE_ADDRESS_CLAMP, w=_D3D11_TEXTURE_ADDRESS_CLAMP,+ anisotropy=1, compare=1, max_lod=3.402823e38,+ )+ out = _out()+ self._device.check(+ _DEV_CREATE_SAMPLER, ctypes.byref(desc), ctypes.byref(out), what="sampler"+ )+ targets["sampler"] = self._keep(_Com(out.value))+ buffer_desc = _BufferDesc(+ size=ctypes.sizeof(_Params), usage=_D3D11_USAGE_DEFAULT,+ bind=_D3D11_BIND_CONSTANT_BUFFER,+ )+ out = _out()+ self._device.check(+ _DEV_CREATE_BUFFER, ctypes.byref(buffer_desc), None, ctypes.byref(out),+ what="constant buffer",+ )+ targets["cbuffer"] = self._keep(_Com(out.value))+ targets["size"] = size+ return targets++ def _read_back(self, staging: _Com, size: tuple[int, int], dtype: Any, channels: int) -> Any:+ import numpy as np # noqa: PLC0415++ mapped = _Mapped()+ self._context.check(+ _CTX_MAP, ctypes.c_void_p(staging.ptr), ctypes.c_uint(0),+ ctypes.c_uint(_D3D11_MAP_READ), ctypes.c_uint(0), ctypes.byref(mapped),+ what="Map",+ )+ try:+ width, height = size+ item = np.dtype(dtype).itemsize * channels+ raw = (ctypes.c_ubyte * (mapped.pitch * height)).from_address(mapped.data)+ rows = np.frombuffer(raw, dtype=np.uint8).reshape(height, mapped.pitch)+ return (+ rows[:, : width * item].copy().view(dtype).reshape(height, width, channels)+ )+ finally:+ self._context.call(+ _CTX_UNMAP, ctypes.c_void_p(staging.ptr), ctypes.c_uint(0), restype=None+ )++ def _read_pointer_shape(self, size: int) -> None:+ import numpy as np # noqa: PLC0415++ buffer = (ctypes.c_ubyte * size)()+ required = ctypes.c_uint()+ shape = _PointerShapeInfo()+ hr = self._dup.call(+ _DUP_POINTER_SHAPE, ctypes.c_uint(size), buffer,+ ctypes.byref(required), ctypes.byref(shape),+ )+ if hr < 0:+ return # Keep the previous pointer; a missing shape is cosmetic.+ rgba = pointer_rgba(bytes(buffer), shape.type, shape.width, shape.height, shape.pitch)+ if rgba is None:+ return+ for attr in ("_pointer_srv", "_pointer_tex"):+ old = getattr(self, attr)+ if old is not None:+ self._objects.remove(old)+ old.release()+ setattr(self, attr, None)+ height, width = rgba.shape[:2]+ data = np.ascontiguousarray(rgba)+ self._pointer_tex = self._texture(+ (width, height), _DXGI_FORMAT_R8G8B8A8_UNORM, bind=_D3D11_BIND_SHADER_RESOURCE,+ initial=(data.ctypes.data, width * 4),+ )+ self._pointer_srv = self._view(_DEV_CREATE_SRV, self._pointer_tex)+ self._pointer_size = (width, height)++ def close(self) -> None:+ """Release the duplication first, then every object in reverse order."""+ if self._dup is not None:+ try:+ self._dup.release()+ except OSError:+ log.debug("duplication release failed", exc_info=True)+ self._dup = None+ for obj in reversed(self._objects):+ try:+ obj.release()+ except OSError:+ log.debug("graphics object release failed", exc_info=True)+ self._objects.clear()++ def __enter__(self) -> DesktopDuplication:+ return self++ def __exit__(self, *_exc: object) -> None:+ self.close()+++def pointer_rgba(data: bytes, kind: int, width: int, height: int, pitch: int) -> Any:+ """A DXGI pointer shape as straight-alpha RGBA ``uint8`` ``(h, w, 4)``.++ Inverting pixels (monochrome AND=1/XOR=1, masked-colour XOR pixels) get+ alpha exactly 1, which the shader draws as "the opposite of below".+ """+ import numpy as np # noqa: PLC0415++ if width <= 0 or height <= 0:+ return None+ if kind == _POINTER_MONOCHROME:+ rows = height // 2+ bits = np.unpackbits(+ np.frombuffer(data, dtype=np.uint8)[: pitch * height].reshape(height, pitch), axis=1+ )[:, :width]+ and_mask, xor_mask = bits[:rows].astype(bool), bits[rows:].astype(bool)+ out = np.zeros((rows, width, 4), dtype=np.uint8)+ white = ~and_mask & xor_mask+ black = ~and_mask & ~xor_mask+ invert = and_mask & xor_mask+ out[white] = (255, 255, 255, 255)+ out[black] = (0, 0, 0, 255)+ out[invert] = (0, 0, 0, 1)+ return out+ pixels = np.frombuffer(data, dtype=np.uint8)[: pitch * height].reshape(height, pitch)+ bgra = pixels[:, : width * 4].reshape(height, width, 4)+ out = np.empty_like(bgra)+ out[..., 0], out[..., 1], out[..., 2] = bgra[..., 2], bgra[..., 1], bgra[..., 0]+ if kind == _POINTER_MASKED:+ mask = bgra[..., 3] == 0xFF+ rgb_set = bgra[..., :3].any(axis=2)+ out[..., 3] = 255+ out[mask & ~rgb_set, 3] = 0+ out[mask & rgb_set, 3] = 1+ return out+ out[..., 3] = bgra[..., 3]+ out[out[..., 3] == 1, 3] = 0 # 1 is reserved for inverting pixels+ return outdiff --git a/tests/unit/appshot/test_hdr_image.py b/tests/unit/appshot/test_hdr_image.pynew file mode 100644index 0000000000..46cda74b58--- /dev/null+++ b/tests/unit/appshot/test_hdr_image.py@@ -0,0 +1,104 @@+"""HDR masters and SDR stand-ins: the colour maths and the PNG bytes."""++from __future__ import annotations++import struct+import zlib++import numpy as np+import pytest++from jarvis.appshot import hdr_image+++def _decode_png16(data: bytes) -> tuple[np.ndarray, dict[bytes, bytes]]:+ """Minimal reader for what encode_png16 writes (filters None and Up)."""+ pos, chunks, idat = 8, {}, b""+ while pos < len(data):+ (length,) = struct.unpack_from(">I", data, pos)+ kind = data[pos + 4 : pos + 8]+ body = data[pos + 8 : pos + 8 + length]+ (crc,) = struct.unpack_from(">I", data, pos + 8 + length)+ assert crc == zlib.crc32(kind + body) & 0xFFFFFFFF+ if kind == b"IDAT":+ idat += body+ else:+ chunks[kind] = body+ pos += 12 + length+ width, height, depth, colour = struct.unpack_from(">IIBB", chunks[b"IHDR"])+ assert (depth, colour) == (16, 2)+ raw = np.frombuffer(zlib.decompress(idat), dtype=np.uint8).reshape(height, width * 6 + 1)+ rows = raw[:, 1:].copy()+ for y in range(height):+ assert raw[y, 0] in (0, 2)+ if raw[y, 0] == 2:+ rows[y] = rows[y] + rows[y - 1]+ pixels = rows.view(">u2").reshape(height, width, 3).astype(np.uint16)+ return pixels, chunks+++def test_pq_hits_the_standard_reference_points() -> None:+ signal = hdr_image.pq_encode(np.array([0.0, 100.0, 1000.0, 10000.0]))+ # ST 2084 reference values: 100 nits ~ 0.508, 1000 nits ~ 0.752.+ assert signal[0] == pytest.approx(0.0, abs=1e-6)+ assert signal[1] == pytest.approx(0.5081, abs=1e-3)+ assert signal[2] == pytest.approx(0.7518, abs=1e-3)+ assert signal[3] == pytest.approx(1.0, abs=1e-6)+++def test_pq_round_trips() -> None:+ nits = np.array([0.05, 1.0, 80.0, 284.0, 455.0, 4000.0], dtype=np.float32)+ back = hdr_image.pq_decode(hdr_image.pq_encode(nits))+ assert np.allclose(back, nits, rtol=2e-3)+++def test_sdr_white_becomes_srgb_white_and_highlights_clip() -> None:+ white = 284.0 / hdr_image.SCRGB_NITS+ scrgb = np.array([[[white, white, white, 1.0], [2 * white, 0.0, 0.0, 1.0]]], np.float16)+ srgb = hdr_image.scrgb_to_srgb8(scrgb, 284.0)+ assert srgb[0, 0].tolist() == [255, 255, 255]+ assert srgb[0, 1].tolist() == [255, 0, 0]+++def test_srgb_mid_grey_survives_the_trip_through_scrgb() -> None:+ grey = np.full((1, 1, 3), 128, np.uint8)+ scrgb = hdr_image.srgb8_to_scrgb(grey, 200.0)+ assert hdr_image.scrgb_to_srgb8(scrgb, 200.0)[0, 0].tolist() == [128, 128, 128]+++def test_wide_gamut_red_stays_inside_bt2020() -> None:+ # A red beyond sRGB arrives with negative green/blue in scRGB.+ scrgb = np.array([[[1.3, -0.05, -0.02, 1.0]]], np.float32)+ nits = hdr_image.scrgb_to_bt2020_nits(scrgb)+ assert (nits >= 0).all()+ assert nits[0, 0, 0] > nits[0, 0, 1] > 0+++def test_png16_carries_cicp_light_levels_and_exact_pixels() -> None:+ rng = np.random.default_rng(7)+ pixels = rng.integers(0, 65536, size=(5, 7, 3), dtype=np.uint16)+ data = hdr_image.encode_png16(pixels, light=(455.5, 12.25))+ decoded, chunks = _decode_png16(data)+ assert np.array_equal(decoded, pixels)+ assert chunks[b"cICP"] == bytes((9, 16, 0, 1))+ assert struct.unpack(">II", chunks[b"cLLi"]) == (4555000, 122500)+ assert hdr_image.read_png_cicp(data) == (9, 16, 0, 1)+++def test_markings_lay_over_hdr_at_sdr_white() -> None:+ base = np.zeros((1, 2, 4), np.float32)+ overlay = np.array([[[255, 255, 255, 255], [0, 0, 0, 0]]], np.uint8)+ out = hdr_image.composite_over_scrgb(base, overlay, 240.0)+ assert out[0, 0].tolist() == pytest.approx([3.0, 3.0, 3.0])+ assert out[0, 1].tolist() == [0.0, 0.0, 0.0]+++def test_png8_embeds_the_icc_profile() -> None:+ from io import BytesIO++ from PIL import Image++ profile = b"\0" * 36 + b"acsp" + b"\0" * 200+ data = hdr_image.encode_png8(np.zeros((2, 2, 3), np.uint8), profile)+ assert Image.open(BytesIO(data)).info.get("icc_profile") == profile+ assert hdr_image.read_png_cicp(data) is Nonediff --git a/tests/unit/platform/test_display_color.py b/tests/unit/platform/test_display_color.pynew file mode 100644index 0000000000..86fd474372--- /dev/null+++ b/tests/unit/platform/test_display_color.py@@ -0,0 +1,84 @@+"""Display colour detection: ICC gamut classification and the safe default."""++from __future__ import annotations++import struct+import sys++import numpy as np++from jarvis.platform import display_color as dc+from jarvis.platform import win_duplication+++def _icc(primaries: dict[bytes, tuple[float, float]]) -> bytes:+ """A minimal ICC body with r/g/b colorant tags at the given xy (Y = 1)."""+ tags = []+ data = b""+ offset = 132 + 12 * len(primaries)+ for sig, (x, y) in primaries.items():+ big_x, big_z = x / y, (1 - x - y) / y+ body = b"XYZ \0\0\0\0" + struct.pack(+ ">iii", round(big_x * 65536), 65536, round(big_z * 65536)+ )+ tags.append(struct.pack(">4sII", sig, offset + len(data), len(body)))+ data += body+ header = bytearray(128)+ header[36:40] = b"acsp"+ return bytes(header) + struct.pack(">I", len(tags)) + b"".join(tags) + data+++def test_srgb_profile_is_srgb() -> None:+ profile = _icc(+ {b"rXYZ": (0.6484, 0.3309), b"gXYZ": (0.3212, 0.5978), b"bXYZ": (0.1559, 0.066)}+ )+ assert dc.icc_gamut(profile) == "srgb"+++def test_p3_profile_is_p3() -> None:+ profile = _icc(+ {b"rXYZ": (0.6820, 0.3190), b"gXYZ": (0.2851, 0.6740), b"bXYZ": (0.1556, 0.0661)}+ )+ assert dc.icc_gamut(profile) == "p3"+++def test_bt2020_profile_is_bt2020() -> None:+ profile = _icc(+ {b"rXYZ": (0.7140, 0.2970), b"gXYZ": (0.1720, 0.7710), b"bXYZ": (0.1300, 0.0510)}+ )+ assert dc.icc_gamut(profile) == "bt2020"+++def test_broken_or_lut_profiles_count_as_srgb() -> None:+ assert dc.icc_gamut(None) == "srgb"+ assert dc.icc_gamut(b"short") == "srgb"+ assert dc.icc_gamut(_icc({b"rXYZ": (0.68, 0.32)})) == "srgb"+++def test_unknown_platforms_report_plain_sdr(monkeypatch) -> None:+ monkeypatch.setattr(sys, "platform", "linux")+ assert dc.display_color("DP-1") == dc.SDR+ assert not dc.display_color().extended+ assert dc.device_at((0, 0)) is None+++def test_duplication_is_windows_only(monkeypatch) -> None:+ monkeypatch.setattr(sys, "platform", "linux")+ assert not win_duplication.available()+++def test_monochrome_pointer_masks() -> None:+ # 2x1 pointer: AND row then XOR row, one byte per row (pitch 1).+ # Pixel 0: AND=0 XOR=1 -> white; pixel 1: AND=1 XOR=1 -> invert.+ data = bytes([0b01000000, 0b11000000])+ rgba = win_duplication.pointer_rgba(data, 1, 2, 2, 1)+ assert rgba.shape == (1, 2, 4)+ assert rgba[0, 0].tolist() == [255, 255, 255, 255]+ assert rgba[0, 1].tolist() == [0, 0, 0, 1]+++def test_colour_pointer_reserves_alpha_one_for_inversion() -> None:+ bgra = np.array([[[10, 20, 30, 255], [1, 2, 3, 1]]], np.uint8)+ rgba = win_duplication.pointer_rgba(bgra.tobytes(), 2, 2, 1, 8)+ assert rgba[0, 0].tolist() == [30, 20, 10, 255]+ assert rgba[0, 1, 3] == 0