| 1 |
"""Integration with madVR's Test Pattern Generator (madTPG) for display calibration. |
| 2 |
|
| 3 |
It supports both local and network-based communication with madVR instances, |
| 4 |
enabling features such as 3D LUT creation, device gamma ramp manipulation, and |
| 5 |
test pattern display. |
| 6 |
|
| 7 |
See developers/interfaces/madTPG.h in the madVR package |
| 8 |
""" |
| 9 |
|
| 10 |
from __future__ import annotations |
| 11 |
|
| 12 |
import contextlib |
| 13 |
import ctypes |
| 14 |
import errno |
| 15 |
import getpass |
| 16 |
import os |
| 17 |
import platform |
| 18 |
import socket |
| 19 |
import struct |
| 20 |
import sys |
| 21 |
import threading |
| 22 |
from binascii import unhexlify |
| 23 |
from io import BytesIO, StringIO |
| 24 |
from time import sleep, time |
| 25 |
from typing import Any, BinaryIO, Callable, TextIO |
| 26 |
from zlib import crc32 |
| 27 |
|
| 28 |
if sys.platform == "win32": |
| 29 |
import winreg |
| 30 |
|
| 31 |
if sys.platform == "win32": |
| 32 |
import win32api |
| 33 |
|
| 34 |
from DisplayCAL import colormath, worker_base |
| 35 |
from DisplayCAL import cubeiterator as ci |
| 36 |
from DisplayCAL import localization as lang |
| 37 |
from DisplayCAL.config import CaseSensitiveConfigParser |
| 38 |
from DisplayCAL.icc_profile import ( |
| 39 |
ICCProfile, |
| 40 |
ICCProfileTag, |
| 41 |
LUT16Type, |
| 42 |
TextDescriptionType, |
| 43 |
TextType, |
| 44 |
) |
| 45 |
from DisplayCAL.imfile import tiff_get_header |
| 46 |
from DisplayCAL.meta import VERSION_STRING |
| 47 |
from DisplayCAL.network import get_network_addr |
| 48 |
|
| 49 |
CALLBACK = ctypes.CFUNCTYPE( |
| 50 |
None, |
| 51 |
ctypes.c_void_p, |
| 52 |
ctypes.POINTER(None), |
| 53 |
ctypes.c_char_p, |
| 54 |
ctypes.c_ulong, |
| 55 |
ctypes.c_ulonglong, |
| 56 |
ctypes.c_char_p, |
| 57 |
ctypes.c_ulonglong, |
| 58 |
ctypes.c_bool, |
| 59 |
) |
| 60 |
|
| 61 |
H3D_HEADER = ( |
| 62 |
b"3DLT\x01\x00\x00\x00DisplayCAL\x00\x00\x00\x00\x00\x00\x00\x00" |
| 63 |
b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00" |
| 64 |
b"\x00\x00\x00\x00\x00\x08\x00\x00\x00\x08\x00\x00\x00\x08\x00\x00" |
| 65 |
b"\x00\x00\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00" |
| 66 |
b"\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00\x00\x00" |
| 67 |
b"\x06\x00\x00\x00\x06" |
| 68 |
) |
| 69 |
|
| 70 |
MIN_VERSION = (0, 88, 20, 0) |
| 71 |
|
| 72 |
# Search for madTPG on the local PC, connect to the first found instance |
| 73 |
CM_ConnectToLocalInstance = 0 |
| 74 |
# Search for madTPG on the LAN, connect to the first found instance |
| 75 |
CM_ConnectToLanInstance = 1 |
| 76 |
# Start madTPG on the local PC and connect to it |
| 77 |
CM_StartLocalInstance = 2 |
| 78 |
# Search local PC and LAN, and let the user choose which instance to connect to |
| 79 |
CM_ShowListDialog = 3 |
| 80 |
# Let the user enter the IP address of a PC which runs madTPG, then connect |
| 81 |
CM_ShowIpAddrDialog = 4 |
| 82 |
# fail immediately |
| 83 |
CM_Fail = 5 |
| 84 |
|
| 85 |
_METHOD_NAMES = ( |
| 86 |
"ConnectEx", |
| 87 |
"Disable3dlut", |
| 88 |
"Enable3dlut", |
| 89 |
"EnterFullscreen", |
| 90 |
"GetBlackAndWhiteLevel", |
| 91 |
"GetDeviceGammaRamp", |
| 92 |
"GetSelected3dlut", |
| 93 |
"GetVersion", |
| 94 |
"IsDisableOsdButtonPressed", |
| 95 |
"IsFseModeEnabled", |
| 96 |
"IsFullscreen", |
| 97 |
"IsStayOnTopButtonPressed", |
| 98 |
"IsUseFullscreenButtonPressed", |
| 99 |
"LeaveFullscreen", |
| 100 |
"SetDisableOsdButton", |
| 101 |
"SetDeviceGammaRamp", |
| 102 |
"SetOsdText", |
| 103 |
"GetPatternConfig", |
| 104 |
"SetPatternConfig", |
| 105 |
"ShowProgressBar", |
| 106 |
"SetProgressBarPos", |
| 107 |
"SetSelected3dlut", |
| 108 |
"SetStayOnTopButton", |
| 109 |
"SetUseFullscreenButton", |
| 110 |
"ShowRGB", |
| 111 |
"ShowRGBEx", |
| 112 |
"Load3dlutFile", |
| 113 |
"LoadHdr3dlutFile", |
| 114 |
"Disconnect", |
| 115 |
"Quit", |
| 116 |
"Load3dlutFromArray256", |
| 117 |
"LoadHdr3dlutFromArray256", |
| 118 |
) |
| 119 |
|
| 120 |
_AUTONET_METHOD_NAMES = ("AddConnectionCallback", "Listen", "Announce") |
| 121 |
|
| 122 |
_LOCK = threading.RLock() |
| 123 |
|
| 124 |
|
| 125 |
def safe_print(*args) -> None: |
| 126 |
"""Thread-safe print function.""" |
| 127 |
with _LOCK: |
| 128 |
print(*args) |
| 129 |
|
| 130 |
|
| 131 |
def icc_device_link_to_madvr( |
| 132 |
icc_device_link_filename: str, |
| 133 |
unity: bool = False, |
| 134 |
colorspace: None | str | list[float] = None, |
| 135 |
hdr: None | int = None, |
| 136 |
logfile: TextIO = sys.stdout, |
| 137 |
convert_video_rgb_to_clut65: bool = False, |
| 138 |
append_linear_cal: bool = True, |
| 139 |
) -> bool: |
| 140 |
"""Convert ICC device link profile to madVR 256^3 3D LUT using interpolation. |
| 141 |
|
| 142 |
madvr 3D LUT will be written to: |
| 143 |
<device link filename without extension> + '.3dlut' |
| 144 |
|
| 145 |
Args: |
| 146 |
icc_device_link_filename (str): Path to the ICC device link profile. |
| 147 |
unity (bool): If True, write a unity madVR 3D LUT. |
| 148 |
colorspace (None | str | list[float]): The target color space for the |
| 149 |
3D LUT. If None, the color space will be inferred from the |
| 150 |
filename. |
| 151 |
hdr (None | int): If 2, write a madVR HDR 3D LUT. If 1, write a madVR |
| 152 |
HDR2SDR 3D LUT. If None, write a madVR SDR 3D LUT. |
| 153 |
logfile (TextIO): The log file to write progress messages to. |
| 154 |
convert_video_rgb_to_clut65 (bool): If True, convert video RGB to |
| 155 |
CLUT65 format when writing the 3D LUT. This is useful for madVR's |
| 156 |
video RGB to CLUT65 conversion. |
| 157 |
append_linear_cal (bool): If True, append a madVR cal1 table to the 3D |
| 158 |
LUT. |
| 159 |
|
| 160 |
Returns: |
| 161 |
bool: True if the conversion was successful, False otherwise. |
| 162 |
""" |
| 163 |
start_time = time() |
| 164 |
filename = os.path.splitext(icc_device_link_filename)[0] |
| 165 |
h3d_params = {} |
| 166 |
name = get_transfer_function_and_name(hdr, filename, h3d_params) |
| 167 |
colorspace = process_colorspace(colorspace, name) |
| 168 |
if not colorspace: |
| 169 |
return False |
| 170 |
|
| 171 |
h3d_params["Input_Primaries"] = colorspace |
| 172 |
h3d_params["Input_Range"] = (16, 235) |
| 173 |
h3d_params["Output_Range"] = (16, 235) |
| 174 |
|
| 175 |
# Create madVR 3D LUT |
| 176 |
h3d_stream = BytesIO(H3D_HEADER) |
| 177 |
h3dlut = H3DLUT(h3d_stream, check_lut_size=False) |
| 178 |
h3dlut.parametersData = h3d_params |
| 179 |
h3dlut.write(f"{filename}.3dlut") |
| 180 |
raw = open(f"{filename}.3dlut", "r+b") # noqa: SIM115 |
| 181 |
raw.seek(h3dlut.lutFileOffset) |
| 182 |
# Make sure no longer needed h3DLUT instance can be garbage collected |
| 183 |
del h3dlut |
| 184 |
|
| 185 |
fill_madvr_3dlut_with_icc_device_link( |
| 186 |
unity, |
| 187 |
logfile, |
| 188 |
raw, |
| 189 |
icc_device_link_filename, |
| 190 |
convert_video_rgb_to_clut65, |
| 191 |
) |
| 192 |
|
| 193 |
if append_linear_cal: |
| 194 |
append_calibration_table(raw) |
| 195 |
raw.close() |
| 196 |
|
| 197 |
print_lut_generation_summary(unity, colorspace, start_time, filename) |
| 198 |
return True |
| 199 |
|
| 200 |
|
| 201 |
def get_transfer_function_and_name( |
| 202 |
hdr: None | int, filename: str, h3d_params: dict |
| 203 |
) -> str: |
| 204 |
"""Determine transfer function and base name for madVR 3D LUT. |
| 205 |
|
| 206 |
Args: |
| 207 |
hdr (None | int): If 2, write a madVR HDR 3D LUT. If 1, write a madVR |
| 208 |
HDR2SDR 3D LUT. If None, write a madVR SDR 3D LUT. |
| 209 |
filename (str): The base filename to use for the 3D LUT. |
| 210 |
h3d_params (dict): The dictionary to populate with transfer function |
| 211 |
parameters. |
| 212 |
|
| 213 |
Returns: |
| 214 |
str: The base name for the 3D LUT. |
| 215 |
""" |
| 216 |
if filename.endswith(".HDR") or hdr == 2: |
| 217 |
name = os.path.splitext(filename)[0] |
| 218 |
h3d_params["Input_Transfer_Function"] = "PQ" |
| 219 |
h3d_params["Output_Transfer_Function"] = "PQ" |
| 220 |
elif filename.endswith(".HDR2SDR") or hdr == 1: |
| 221 |
name = os.path.splitext(filename)[0] |
| 222 |
h3d_params["Input_Transfer_Function"] = "PQ" |
| 223 |
else: |
| 224 |
name = filename |
| 225 |
return name |
| 226 |
|
| 227 |
|
| 228 |
def process_colorspace(colorspace: None | str | list[float], name: str) -> list[float]: |
| 229 |
"""Process and validate the target color space for madVR 3D LUT. |
| 230 |
|
| 231 |
Args: |
| 232 |
colorspace (None | str | list[float]): The target color space for the |
| 233 |
3D LUT. If None, the color space will be inferred from the |
| 234 |
filename. |
| 235 |
name (str): The base filename to use for the 3D LUT. |
| 236 |
|
| 237 |
Returns: |
| 238 |
list[float]: The processed color space primaries and whitepoint. If the |
| 239 |
color space is invalid, returns the original colorspace value. |
| 240 |
""" |
| 241 |
if not colorspace: |
| 242 |
colorspace = os.path.splitext(name)[1] |
| 243 |
colorspace = colorspace[1:] |
| 244 |
|
| 245 |
if not isinstance(colorspace, (list, tuple)): |
| 246 |
key = { |
| 247 |
"BT709": "Rec. 709", |
| 248 |
"SMPTE_C": "SMPTE-C", |
| 249 |
"EBU_PAL": "PAL/SECAM", |
| 250 |
"BT2020": "Rec. 2020", |
| 251 |
"DCI_P3": "DCI P3 D65", |
| 252 |
}.get(colorspace) |
| 253 |
if not key: |
| 254 |
if not colorspace: |
| 255 |
safe_print("ERROR - no target color space suffix in filename") |
| 256 |
else: |
| 257 |
safe_print("ERROR - invalid target color space:", colorspace) |
| 258 |
safe_print( |
| 259 |
"Possible target color spaces:", |
| 260 |
"BT709, SMPTE_C, EBU_PAL, BT2020, DCI_P3", |
| 261 |
) |
| 262 |
return colorspace |
| 263 |
|
| 264 |
rgb_space = colormath.get_rgb_space(key) |
| 265 |
colorspace = colormath.get_rgb_space_primaries_wp_xy(rgb_space) |
| 266 |
colorspace = list(colorspace) |
| 267 |
|
| 268 |
# Use a D65 white for the 3D LUT Input_Primaries as |
| 269 |
# madVR can only deal correctly with D65 |
| 270 |
# Use the same D65 xy values as written by madVR |
| 271 |
# 3D LUT install API (ASTM E308-01) |
| 272 |
colorspace[6:] = [0.31273, 0.32902] |
| 273 |
return colorspace |
| 274 |
|
| 275 |
|
| 276 |
def fill_madvr_3dlut_with_icc_device_link( |
| 277 |
unity: bool, |
| 278 |
logfile: TextIO, |
| 279 |
raw: BinaryIO, |
| 280 |
icc_device_link_filename: str, |
| 281 |
convert_video_rgb_to_clut65: bool, |
| 282 |
) -> None: |
| 283 |
"""Fill madVR 3D LUT with values from ICC device link profile. |
| 284 |
|
| 285 |
Args: |
| 286 |
unity (bool): If True, write a unity madVR 3D LUT. |
| 287 |
logfile (TextIO): The log file to write progress messages to. |
| 288 |
raw (BinaryIO): The binary stream to write the 3D LUT data to. |
| 289 |
icc_device_link_filename (str): Path to the ICC device link profile. |
| 290 |
convert_video_rgb_to_clut65 (bool): If True, convert video RGB to |
| 291 |
CLUT65 format when writing the 3D LUT. This is useful for madVR's |
| 292 |
video RGB to CLUT65 conversion. |
| 293 |
""" |
| 294 |
# Lookup 256^3 values through device link and fill madVR cLUT |
| 295 |
clutres = 256 |
| 296 |
clutmax = clutres - 1.0 |
| 297 |
if unity: |
| 298 |
logfile.write("Writing unity madVR 3D LUT...\n") |
| 299 |
prevperc = -1 |
| 300 |
for i in range(clutres): |
| 301 |
for j in range(clutres): |
| 302 |
for k in range(clutres): |
| 303 |
# Optimize for speed |
| 304 |
b, g, r = chr(k), chr(j), chr(i) |
| 305 |
raw.write(b + b + g + g + r + r).encode() |
| 306 |
perc = round(i / clutmax * 100) |
| 307 |
if perc > prevperc: |
| 308 |
logfile.write(f"\r{perc}%") |
| 309 |
prevperc = perc |
| 310 |
else: |
| 311 |
link = ICCProfile(icc_device_link_filename) |
| 312 |
# Need a worker for abort event handling |
| 313 |
worker = worker_base.WorkerBase() |
| 314 |
# icclu verbose=0 gives a speed increase |
| 315 |
xicclu = worker_base.XiccluMP( |
| 316 |
link, |
| 317 |
scale=clutmax, |
| 318 |
use_icclu=True, |
| 319 |
logfile=logfile, |
| 320 |
output_format=("<H", 65535), |
| 321 |
reverse=True, |
| 322 |
output_stream=raw, |
| 323 |
convert_video_rgb_to_clut65=convert_video_rgb_to_clut65, |
| 324 |
verbose=0, |
| 325 |
worker=worker, |
| 326 |
) |
| 327 |
xicclu._in = ci.Cube3D(clutres) |
| 328 |
logfile.write( |
| 329 |
"Looking up 256^3 input values through device link and " |
| 330 |
"writing madVR 3D LUT...\n" |
| 331 |
) |
| 332 |
xicclu.exit() |
| 333 |
xicclu.get() |
| 334 |
|
| 335 |
|
| 336 |
def append_calibration_table(raw: BinaryIO) -> None: |
| 337 |
"""Append a madVR cal1 table to the 3D LUT. |
| 338 |
|
| 339 |
Args: |
| 340 |
raw (BinaryIO): The binary stream to write the calibration table to. |
| 341 |
""" |
| 342 |
# Append a MadVR cal1 table to the 3dlut. |
| 343 |
# This can be used to ensure that the Graphics Card VideoLuts |
| 344 |
# are correctly setup to match what the 3dLut is expecting. |
| 345 |
# |
| 346 |
# Note that the calibration curves are full range, |
| 347 |
# never TV encoded output values. |
| 348 |
# |
| 349 |
# Format is (little endian): |
| 350 |
# 4 byte magic number 'cal1' |
| 351 |
# 4 byte version = 1 |
| 352 |
# 4 byte number per channel entries = 256 |
| 353 |
# 4 byte bytes per entry = 2 |
| 354 |
# [3][256] 2 byte entry values. Tables are in RGB order |
| 355 |
raw.write(b"cal1") |
| 356 |
raw.write(struct.pack("<I", 1)) |
| 357 |
raw.write(struct.pack("<I", 256)) |
| 358 |
raw.write(struct.pack("<I", 2)) |
| 359 |
# Linear (unity) calibration |
| 360 |
for _ in range(3): |
| 361 |
for j in range(256): |
| 362 |
raw.write(struct.pack("<H", j * 257)) |
| 363 |
|
| 364 |
|
| 365 |
def print_lut_generation_summary( |
| 366 |
unity: bool, colorspace: list[float], start_time: float, filename: str |
| 367 |
) -> None: |
| 368 |
"""Print summary after LUT generation. |
| 369 |
|
| 370 |
Args: |
| 371 |
unity (bool): Whether a unity LUT was generated. |
| 372 |
colorspace (list[float]): The colorspace primaries and whitepoint. |
| 373 |
start_time (float): The start time of the LUT generation. |
| 374 |
filename (str): The filename of the generated LUT. |
| 375 |
""" |
| 376 |
safe_print("") |
| 377 |
if unity: |
| 378 |
msg = "Finished writing unity madVR 3D LUT in" |
| 379 |
else: |
| 380 |
msg = "Finished up-interpolating device link and writing madVR 3D LUT in" |
| 381 |
safe_print(msg, time() - start_time, "seconds") |
| 382 |
if filename.endswith(".HDR"): |
| 383 |
safe_print( |
| 384 |
"Gamut (rx ry gx gy bx by wx wy):", |
| 385 |
"{:.5f} {:.5f} {:.5f} {:.5f} {:.5f} {:.5f} {:.5f} {:.5f}".format( |
| 386 |
*tuple(colorspace) |
| 387 |
), |
| 388 |
) |
| 389 |
|
| 390 |
|
| 391 |
def inet_pton(ip_string: str) -> str: |
| 392 |
"""Convert ip_string to packed IP representation. |
| 393 |
|
| 394 |
Convert an IP address in string format to the packed binary format used in |
| 395 |
low-level network functions. |
| 396 |
|
| 397 |
Args: |
| 398 |
ip_string (str): The IP address in string format, either IPv4 or IPv6. |
| 399 |
|
| 400 |
Returns: |
| 401 |
str: The packed binary representation of the IP address. |
| 402 |
""" |
| 403 |
if ":" in ip_string: |
| 404 |
# IPv6 |
| 405 |
return "".join( |
| 406 |
[unhexlify(block.rjust(4, "0")) for block in ip_string.split(":")] |
| 407 |
) |
| 408 |
# IPv4 |
| 409 |
return "".join([chr(int(block)) for block in ip_string.split(".")]) |
| 410 |
|
| 411 |
|
| 412 |
def trunc(value: str, length: int) -> str: |
| 413 |
"""For string types, return value truncated to length. |
| 414 |
|
| 415 |
Args: |
| 416 |
value (str): The value to be truncated. |
| 417 |
length (int): The maximum length of the string. |
| 418 |
|
| 419 |
Returns: |
| 420 |
str: The truncated string, or the original value if it is shorter than |
| 421 |
or equal to the specified length. |
| 422 |
""" |
| 423 |
if isinstance(value, str) and len(repr(value)) > length: |
| 424 |
value = value[: length - 3 - len(str(length)) - len(repr(value)) + len(value)] |
| 425 |
return f"{value!r}[{length:d}]" |
| 426 |
return repr(value) |
| 427 |
|
| 428 |
|
| 429 |
class H3DLUT: |
| 430 |
"""3D LUT file format used by madVR. |
| 431 |
|
| 432 |
Args: |
| 433 |
stream_or_filename (None | str | BinaryIO, optional): The file path or |
| 434 |
a binary stream containing the 3D LUT data. |
| 435 |
check_lut_size (bool): Whether to check the size of the LUT data |
| 436 |
against the expected size. |
| 437 |
""" |
| 438 |
|
| 439 |
# https://sourceforge.net/projects/thr3dlut |
| 440 |
|
| 441 |
def __init__( |
| 442 |
self, |
| 443 |
stream_or_filename: None | str | BinaryIO = None, |
| 444 |
check_lut_size: bool = True, |
| 445 |
) -> None: |
| 446 |
if not stream_or_filename: |
| 447 |
return |
| 448 |
if isinstance(stream_or_filename, str): |
| 449 |
self.filename = stream_or_filename |
| 450 |
with open(stream_or_filename, "rb") as lut: |
| 451 |
data = lut.read() |
| 452 |
else: |
| 453 |
self.filename = None |
| 454 |
data = stream_or_filename.read() |
| 455 |
self.signature = data[:4] |
| 456 |
self.fileVersion = struct.unpack("<l", data[4:8])[0] |
| 457 |
self.programName = data[8:40].rstrip(b"\0") |
| 458 |
self.programVersion = struct.unpack("<q", data[40:48])[0] |
| 459 |
self.inputBitDepth = struct.unpack("<3l", data[48:60]) |
| 460 |
self.inputColorEncoding = struct.unpack("<l", data[60:64])[0] |
| 461 |
self.outputBitDepth = struct.unpack("<l", data[64:68])[0] |
| 462 |
self.outputColorEncoding = struct.unpack("<l", data[68:72])[0] |
| 463 |
self.parametersFileOffset = struct.unpack("<l", data[72:76])[0] |
| 464 |
parameters_size = struct.unpack("<l", data[76:80])[0] |
| 465 |
self.lutFileOffset = struct.unpack("<l", data[80:84])[0] |
| 466 |
self.lutCompressionMethod = struct.unpack("<l", data[84:88])[0] |
| 467 |
if self.lutCompressionMethod != 0: |
| 468 |
raise ValueError( |
| 469 |
f"Compression method not supported: {self.lutCompressionMethod}" |
| 470 |
) |
| 471 |
self.lutCompressedSize = struct.unpack("<l", data[88:92])[0] |
| 472 |
self.lutUncompressedSize = struct.unpack("<l", data[92:96])[0] |
| 473 |
self.parametersData = {} |
| 474 |
for line in ( |
| 475 |
data[ |
| 476 |
self.parametersFileOffset : self.parametersFileOffset + parameters_size |
| 477 |
] |
| 478 |
.rstrip(b"\0") |
| 479 |
.splitlines() |
| 480 |
): |
| 481 |
item = line.decode().split(maxsplit=1) |
| 482 |
if len(item) == 2: |
| 483 |
key, values = item |
| 484 |
values = values.split() |
| 485 |
if len(values) == 1: |
| 486 |
value = values[0] |
| 487 |
else: |
| 488 |
for i, value in enumerate(values): |
| 489 |
if value.isdigit(): |
| 490 |
values[i] = int(value) |
| 491 |
elif not value.isalpha(): |
| 492 |
values[i] = float(value) |
| 493 |
value = tuple(values) |
| 494 |
self.parametersData[key] = value |
| 495 |
self.LUTDATA = data[ |
| 496 |
self.lutFileOffset : self.lutFileOffset + self.lutCompressedSize |
| 497 |
] |
| 498 |
if check_lut_size and len(self.LUTDATA) != self.lutCompressedSize: |
| 499 |
raise ValueError( |
| 500 |
f"3DLUT size {len(self.LUTDATA)} " |
| 501 |
f"does not match expected size {self.lutCompressedSize}" |
| 502 |
) |
| 503 |
if len(data) == self.lutFileOffset + self.lutCompressedSize + 1552: |
| 504 |
# Calibration appendended |
| 505 |
self.LUTDATA += data[ |
| 506 |
self.lutFileOffset + self.lutCompressedSize : self.lutFileOffset |
| 507 |
+ self.lutCompressedSize |
| 508 |
+ 1552 |
| 509 |
] |
| 510 |
|
| 511 |
@property |
| 512 |
def data(self) -> bytes: |
| 513 |
"""Return the raw 3D LUT data as bytes. |
| 514 |
|
| 515 |
Returns: |
| 516 |
bytes: The raw 3D LUT data, including header and parameters. |
| 517 |
""" |
| 518 |
parameters_data = [] |
| 519 |
for key in self.parametersData: |
| 520 |
values = self.parametersData[key] |
| 521 |
if isinstance(values, str): |
| 522 |
value = values |
| 523 |
else: |
| 524 |
values = list(values) |
| 525 |
for i, value in enumerate(values): |
| 526 |
if isinstance(value, float): |
| 527 |
values[i] = f"{value:.5f}" |
| 528 |
else: |
| 529 |
values[i] = f"{value}" |
| 530 |
value = " ".join(values) |
| 531 |
parameters_data.append((f"{key} {value}").encode()) |
| 532 |
parameters_data = b"\r\n".join(parameters_data) + b"\0" |
| 533 |
parameters_size = len(parameters_data) |
| 534 |
return b"".join( |
| 535 |
( |
| 536 |
self.signature, |
| 537 |
struct.pack("<l", self.fileVersion), |
| 538 |
self.programName.ljust(32, b"\0"), |
| 539 |
struct.pack("<q", self.programVersion), |
| 540 |
struct.pack("<3l", *self.inputBitDepth), |
| 541 |
struct.pack("<l", self.inputColorEncoding), |
| 542 |
struct.pack("<l", self.outputBitDepth), |
| 543 |
struct.pack("<l", self.outputColorEncoding), |
| 544 |
struct.pack("<l", self.parametersFileOffset), |
| 545 |
struct.pack("<l", parameters_size), |
| 546 |
struct.pack("<l", self.lutFileOffset), |
| 547 |
struct.pack("<l", self.lutCompressionMethod), |
| 548 |
struct.pack("<l", self.lutCompressedSize), |
| 549 |
struct.pack("<l", self.lutUncompressedSize), |
| 550 |
b"\0" * (self.parametersFileOffset - 96), |
| 551 |
parameters_data, |
| 552 |
b"\0" |
| 553 |
* (self.lutFileOffset - self.parametersFileOffset - parameters_size), |
| 554 |
self.LUTDATA, |
| 555 |
) |
| 556 |
) |
| 557 |
|
| 558 |
@property |
| 559 |
def source_colorspace(self) -> tuple[int, str]: |
| 560 |
"""Return the 3D LUT source colorspace slot and name as 2-tuple. |
| 561 |
|
| 562 |
Returns: |
| 563 |
tuple[int, str]: A tuple containing the source colorspace slot |
| 564 |
(0 for Rec. 709, 1 for SMPTE-C, etc.) and the name of the |
| 565 |
colorspace (e.g., "Rec. 709", "SMPTE-C", etc.). |
| 566 |
""" |
| 567 |
# Determine gamut slot only based on primaries (omit whitepoint) |
| 568 |
xy = list(self.parametersData.get("Input_Primaries", [])[:6]) |
| 569 |
rgb_space_name = colormath.find_primaries_wp_xy_rgb_space_name(xy) |
| 570 |
return { |
| 571 |
"Rec. 709": 0, |
| 572 |
"SMPTE-C": 1, # SMPTE RP 145 (NTSC) |
| 573 |
"PAL/SECAM": 2, |
| 574 |
"Rec. 2020": 3, |
| 575 |
"DCI P3": 4, |
| 576 |
"DCI P3 D65": 4, |
| 577 |
}.get(rgb_space_name), rgb_space_name |
| 578 |
|
| 579 |
def _get_stream( |
| 580 |
self, stream_or_filename: None | str | BinaryIO = None, ext: None | str = None |
| 581 |
) -> BinaryIO: |
| 582 |
"""Get a writable stream for the 3D LUT data. |
| 583 |
|
| 584 |
Args: |
| 585 |
stream_or_filename (None | str | BinaryIO, optional): The file path |
| 586 |
or a binary stream to write the 3D LUT data to. |
| 587 |
ext (str, optional): The file extension to use if a filename is |
| 588 |
provided. Defaults to None. |
| 589 |
|
| 590 |
Returns: |
| 591 |
BinaryIO: A writable stream for the 3D LUT data. |
| 592 |
""" |
| 593 |
if not stream_or_filename: |
| 594 |
stream_or_filename = self.filename |
| 595 |
if ext: |
| 596 |
stream_or_filename = os.path.splitext(stream_or_filename)[0] + ext |
| 597 |
if isinstance(stream_or_filename, str): |
| 598 |
stream = open(stream_or_filename, "wb") # noqa: SIM115 |
| 599 |
else: |
| 600 |
stream = stream_or_filename |
| 601 |
return stream |
| 602 |
|
| 603 |
def write(self, stream_or_filename: None | str | BinaryIO = None) -> None: |
| 604 |
"""Write 3D LUT to stream or filename. |
| 605 |
|
| 606 |
Args: |
| 607 |
stream_or_filename (None | str | BinaryIO, optional): The file path |
| 608 |
or a binary stream to write the 3D LUT data to. If None, uses |
| 609 |
the filename from the instance. If a string is provided, it |
| 610 |
will be used as the filename with a ".3dlut" extension. |
| 611 |
""" |
| 612 |
stream = self._get_stream(stream_or_filename) |
| 613 |
stream.write(self.data) |
| 614 |
if isinstance(stream_or_filename, str): |
| 615 |
if not self.filename: |
| 616 |
self.filename = stream_or_filename |
| 617 |
stream.close() |
| 618 |
|
| 619 |
def write_devicelink( |
| 620 |
self, stream_or_filename: None | str | BinaryIO = None |
| 621 |
) -> None: |
| 622 |
"""Write 3D LUT to ICC device link. |
| 623 |
|
| 624 |
Args: |
| 625 |
stream_or_filename (None | str | BinaryIO, optional): The file path |
| 626 |
or a binary stream to write the ICC device link data to. If None, |
| 627 |
uses the filename from the instance. If a string is provided, it |
| 628 |
will be used as the filename with a ".icc" extension. |
| 629 |
""" |
| 630 |
stream = self._get_stream(stream_or_filename, ".icc") |
| 631 |
|
| 632 |
link = ICCProfile() |
| 633 |
link.connectionColorSpace = b"RGB" |
| 634 |
link.profileClass = b"link" |
| 635 |
link.tags.desc = TextDescriptionType() |
| 636 |
link.tags.desc.ASCII = os.path.splitext(os.path.basename(stream.name))[0] |
| 637 |
link.tags.cprt = TextType(b"text\0\0\0\0No copyright", b"cprt") |
| 638 |
|
| 639 |
input_grid_steps = ( |
| 640 |
2 ** self.inputBitDepth[0] |
| 641 |
) # Assume equal bitdepth for R, G, B |
| 642 |
# madVR 3D LUTs are 256^3, but ICC LUT16Type only supports up to |
| 643 |
# 255^3. As madVR 3D LUTs use video levels encoding, we simply skip |
| 644 |
# the first cLUT entry in each dimension and fix the offset by |
| 645 |
# scaling the input/output shaper curves. That way, only level 1 of |
| 646 |
# 255 will be affected (with black at 16 and white at 235), |
| 647 |
# which isn't used in actual video content. |
| 648 |
clut_grid_steps = 255 if input_grid_steps > 255 else input_grid_steps |
| 649 |
# Filling a 255^3 list is VERY memory intensive in Python, so we 'fake' |
| 650 |
# the LUT16Type cLUT and only use tag data of offsets/sizes and shaper |
| 651 |
# curves while writing the raw cLUT data directly without going through |
| 652 |
# decoding/re-encoding roundtrip |
| 653 |
a2b0 = LUT16Type() |
| 654 |
a2b0.matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] |
| 655 |
a2b0.input = [] |
| 656 |
for _ in range(3): |
| 657 |
a2b0.input.append([]) |
| 658 |
for j in range(4096): |
| 659 |
a2b0.input[-1].append( |
| 660 |
min(max(j / 4095.0 * (256 / 255.0) - (256 / 255.0 - 1), 0), 1) |
| 661 |
* 65535 |
| 662 |
) |
| 663 |
input_bytes = len(a2b0.input) * len(a2b0.input[0]) * 2 |
| 664 |
a2b0.clut = [[[0] * 3 for i in range(clut_grid_steps)]] # Fake cLUT |
| 665 |
a2b0.output = [] |
| 666 |
for _ in range(3): |
| 667 |
a2b0.output.append([]) |
| 668 |
for j in range(4096): |
| 669 |
a2b0.output[-1].append( |
| 670 |
min(max(j / 4095.0 * (256 / 255.0), 0), 1) * 65535 |
| 671 |
) |
| 672 |
output_bytes = len(a2b0.output) * len(a2b0.output[0]) * 2 |
| 673 |
tag_data = a2b0.tagData[: 52 + input_bytes] # Exclude cLUT and output curves |
| 674 |
|
| 675 |
# Write actual cLUT |
| 676 |
# XXX Currently only 16 bit RGB data is supported |
| 677 |
samples_per_pixel = 3 # RGB |
| 678 |
bytes_per_sample = self.outputBitDepth / 8 |
| 679 |
bytes_per_pixel = samples_per_pixel * bytes_per_sample |
| 680 |
io = BytesIO(tag_data) |
| 681 |
io.seek(0, 2) # Position cursor at end |
| 682 |
i = 0 |
| 683 |
for r in range(input_grid_steps): |
| 684 |
if not r: |
| 685 |
i += input_grid_steps * input_grid_steps |
| 686 |
continue |
| 687 |
for g in range(input_grid_steps): |
| 688 |
if not g: |
| 689 |
i += input_grid_steps |
| 690 |
continue |
| 691 |
for b in range(input_grid_steps): |
| 692 |
if not b: |
| 693 |
i += 1 |
| 694 |
continue |
| 695 |
index = i * samples_per_pixel * bytes_per_sample |
| 696 |
bgr = self.LUTDATA[index : index + bytes_per_pixel] |
| 697 |
rgb = bgr[::-1] # BGR little-endian to RGB big-endian byte order |
| 698 |
io.write(rgb) |
| 699 |
i += 1 |
| 700 |
io.write(a2b0.tagData[-output_bytes:]) # Append output curves |
| 701 |
io.seek(0) |
| 702 |
link.tags.A2B0 = ICCProfileTag(io.read(), "A2B0") |
| 703 |
|
| 704 |
link.write(stream) |
| 705 |
|
| 706 |
if isinstance(stream_or_filename, str): |
| 707 |
stream.close() |
| 708 |
|
| 709 |
def write_tiff(self, stream_or_filename: None | str | BinaryIO = None) -> None: |
| 710 |
"""Write 3D LUT to TIFF file. |
| 711 |
|
| 712 |
Args: |
| 713 |
stream_or_filename (None | str | BinaryIO, optional): The file path |
| 714 |
or a binary stream to write the TIFF data to. If None, uses the |
| 715 |
filename from the instance. If a string is provided, it will be |
| 716 |
used as the filename with a ".tif" extension. |
| 717 |
""" |
| 718 |
stream = self._get_stream(stream_or_filename, ".tif") |
| 719 |
|
| 720 |
# Write image data |
| 721 |
# XXX Currently only 8 or 16 bit RGB data is supported |
| 722 |
samples_per_pixel = 3 # RGB |
| 723 |
bytes_per_sample = self.outputBitDepth / 8 |
| 724 |
bytes_per_pixel = samples_per_pixel * bytes_per_sample |
| 725 |
w = 2 ** self.inputBitDepth[0] # Assume equal bitdepth for R, G, B |
| 726 |
h = w * w |
| 727 |
stream.write(tiff_get_header(w, h, samples_per_pixel, self.outputBitDepth)) |
| 728 |
entries = self.lutUncompressedSize / samples_per_pixel / bytes_per_sample |
| 729 |
for i in range(entries): |
| 730 |
index = i * samples_per_pixel * bytes_per_sample |
| 731 |
bgr = self.LUTDATA[index : index + bytes_per_pixel] |
| 732 |
rgb = bgr[::-1] # BGR little-endian to RGB big-endian byte order |
| 733 |
stream.write(rgb) |
| 734 |
|
| 735 |
if isinstance(stream_or_filename, str): |
| 736 |
stream.close() |
| 737 |
|
| 738 |
|
| 739 |
class MadTPGBase: |
| 740 |
"""Generic pattern generator compatibility layer.""" |
| 741 |
|
| 742 |
def wait(self) -> None: |
| 743 |
"""Wait for madTPG to be ready.""" |
| 744 |
self.connect(method2=CM_StartLocalInstance) |
| 745 |
|
| 746 |
def disconnect_client(self) -> None: |
| 747 |
"""Disconnect the client from madTPG.""" |
| 748 |
self.disconnect() |
| 749 |
|
| 750 |
def send( |
| 751 |
self, |
| 752 |
rgb: tuple[float, float, float] = (0, 0, 0), |
| 753 |
bgrgb: tuple[float, float, float] = (0, 0, 0), |
| 754 |
bits: None | int = None, |
| 755 |
use_video_levels: None | bool = None, |
| 756 |
x: int = 0, |
| 757 |
y: int = 0, |
| 758 |
w: int = 1, |
| 759 |
h: int = 1, |
| 760 |
) -> None: |
| 761 |
"""Send RGB values to madTPG. |
| 762 |
|
| 763 |
Args: |
| 764 |
rgb (tuple[float, float, float], optional): RGB values to display, |
| 765 |
each in the range 0-255. |
| 766 |
bgrgb (tuple[float, float, float], optional): BGR values to |
| 767 |
display, each in the range 0-255. |
| 768 |
bits (None | int, optional): Bit depth of the RGB values. Defaults to |
| 769 |
None, which means the default bit depth will be used. |
| 770 |
use_video_levels (None | bool): Whether to use video levels. |
| 771 |
Defaults to None. |
| 772 |
x (int, optional): X position on screen to display the pattern. |
| 773 |
y (int, optional): Y position on screen to display the pattern. |
| 774 |
w (int, optional): Width of the pattern area. |
| 775 |
h (int, optional): Height of the pattern area. |
| 776 |
""" |
| 777 |
cfg = self.get_pattern_config() |
| 778 |
if cfg: |
| 779 |
self.set_pattern_config( |
| 780 |
round((w + h) / 2.0 * 100), |
| 781 |
round(sum(bgrgb) / 3.0 * 100), |
| 782 |
cfg[2], |
| 783 |
cfg[3], |
| 784 |
) |
| 785 |
self.show_rgb(*rgb + bgrgb) |
| 786 |
|
| 787 |
|
| 788 |
class MadTPG(MadTPGBase): |
| 789 |
"""Minimal madTPG controller class.""" |
| 790 |
|
| 791 |
def __init__(self) -> None: |
| 792 |
MadTPGBase.__init__(self) |
| 793 |
self._connection_callbacks = [] |
| 794 |
|
| 795 |
# We only expose stuff we might actually use. |
| 796 |
# Also, as the HDR 3D LUT install API of madVR is relatively recent |
| 797 |
# (September 2017), we do not require it. |
| 798 |
|
| 799 |
# Find madHcNet32.dll |
| 800 |
clsid = "{E1A8B82A-32CE-4B0D-BE0D-AA68C772E423}" |
| 801 |
try: |
| 802 |
key = winreg.OpenKey( |
| 803 |
winreg.HKEY_CLASSES_ROOT, rf"CLSID\{clsid}\InprocServer32" |
| 804 |
) |
| 805 |
value, valuetype = winreg.QueryValueEx(key, "") |
| 806 |
except Exception as e: |
| 807 |
raise RuntimeError(lang.getstr("madvr.not_found")) from e |
| 808 |
bits = 64 if platform.architecture()[0] == "64bit" else 32 |
| 809 |
self.dllpath = os.path.join(os.path.split(value)[0], f"madHcNet{bits}.dll") |
| 810 |
if not value or not os.path.isfile(self.dllpath): |
| 811 |
raise OSError(lang.getstr("not_found", self.dllpath)) |
| 812 |
handle = win32api.LoadLibrary(self.dllpath) |
| 813 |
self.mad = ctypes.WinDLL(self.dllpath, handle=handle) |
| 814 |
|
| 815 |
try: |
| 816 |
# Set expected return value types |
| 817 |
for methodname in _METHOD_NAMES + _AUTONET_METHOD_NAMES: |
| 818 |
if methodname == "AddConnectionCallback": |
| 819 |
continue |
| 820 |
prefix = "AutoNet" if methodname in _AUTONET_METHOD_NAMES else "madVR" |
| 821 |
method = getattr(self.mad, prefix + "_" + methodname, None) |
| 822 |
if not method and not methodname.startswith("LoadHdr3dlut"): |
| 823 |
raise AttributeError(prefix + "_" + methodname) |
| 824 |
method.restype = ctypes.c_bool |
| 825 |
|
| 826 |
# Set expected argument types |
| 827 |
self.mad.madVR_ShowRGB.argtypes = [ctypes.c_double] * 3 |
| 828 |
self.mad.madVR_ShowRGBEx.argtypes = [ctypes.c_double] * 6 |
| 829 |
if hasattr(self.mad, "madVR_LoadHdr3dlutFile"): |
| 830 |
self.mad.madVR_LoadHdr3dlutFile.argtypes = [ |
| 831 |
ctypes.wintypes.LPWSTR, |
| 832 |
ctypes.wintypes.BOOL, |
| 833 |
ctypes.c_int, |
| 834 |
ctypes.c_bool, |
| 835 |
] |
| 836 |
except AttributeError as e: |
| 837 |
raise RuntimeError( |
| 838 |
lang.getstr( |
| 839 |
"madhcnet.outdated", |
| 840 |
tuple(reversed(os.path.split(self.dllpath))) + MIN_VERSION, |
| 841 |
) |
| 842 |
) from e |
| 843 |
|
| 844 |
def __del__(self) -> None: |
| 845 |
"""Destructor to clean up madTPG instance.""" |
| 846 |
if hasattr(self, "mad"): |
| 847 |
self.disconnect() |
| 848 |
|
| 849 |
def __getattr__(self, name: str) -> Callable: |
| 850 |
"""Handle madVR method calls. |
| 851 |
|
| 852 |
This is a generic method to handle madVR method calls. It allows |
| 853 |
dynamic access to madVR methods based on their names. The method |
| 854 |
names are expected to be in a pythonic format (e.g., 'disable_3dlut' |
| 855 |
instead of 'Disable3dlut'). The method converts the pythonic name |
| 856 |
to the appropriate CamelCase format used by madVR and checks if |
| 857 |
the method exists. If it does, it returns the method for further |
| 858 |
invocation. If the method does not exist, it raises an AttributeError. |
| 859 |
This approach avoids the need to write individual method wrappers |
| 860 |
for each madVR method, making the code cleaner and more maintainable. |
| 861 |
|
| 862 |
Args: |
| 863 |
name (str): The name of the madVR method to be called, in a |
| 864 |
pythonic format (e.g., 'disable_3dlut'). |
| 865 |
|
| 866 |
Raises: |
| 867 |
AttributeError: If the method name does not correspond to a |
| 868 |
valid madVR method. |
| 869 |
|
| 870 |
Returns: |
| 871 |
Callable: The madVR method corresponding to the provided name. |
| 872 |
""" |
| 873 |
# Instead of writing individual method wrappers, we use Python's magic |
| 874 |
# to handle this for us. Note that we're sticking to pythonic method |
| 875 |
# names, so 'disable_3dlut' instead of 'Disable3dlut' etc. |
| 876 |
|
| 877 |
# Convert from pythonic method name to CamelCase |
| 878 |
methodname = "".join(part.capitalize() for part in name.split("_")) |
| 879 |
|
| 880 |
# Check if this is a madVR method we support |
| 881 |
if methodname not in _METHOD_NAMES + _AUTONET_METHOD_NAMES: |
| 882 |
raise AttributeError( |
| 883 |
f"{self.__class__.__name__!r} object has no attribute {name!r}" |
| 884 |
) |
| 885 |
|
| 886 |
# Return the method |
| 887 |
prefix = "AutoNet" if methodname in _AUTONET_METHOD_NAMES else "madVR" |
| 888 |
return getattr(self.mad, f"{prefix}_{methodname}") |
| 889 |
|
| 890 |
def add_connection_callback( |
| 891 |
self, |
| 892 |
callback: Callable, |
| 893 |
param: Any, # noqa: ANN401 |
| 894 |
component: str, |
| 895 |
) -> None: |
| 896 |
"""Handle callbacks for added/closed connections to playback components. |
| 897 |
|
| 898 |
Leave "component" empty to get notification about all components. |
| 899 |
|
| 900 |
The callback function has to take eight arguments: |
| 901 |
param, connection, ip, pid, module, component, instance, is_new_instance |
| 902 |
|
| 903 |
Args: |
| 904 |
callback (Callable): The callback function to be called when a |
| 905 |
connection is added or closed. |
| 906 |
param (Any): Additional parameter to be passed to the callback. |
| 907 |
component (str): The name of the component to monitor for |
| 908 |
connections. |
| 909 |
""" |
| 910 |
callback = CALLBACK(callback) |
| 911 |
self.mad.AutoNet_AddConnectionCallback(callback, param, component) |
| 912 |
self._connection_callbacks.append(callback) |
| 913 |
|
| 914 |
def connect( |
| 915 |
self, |
| 916 |
method1: int = CM_ConnectToLocalInstance, |
| 917 |
timeout1: int = 1000, |
| 918 |
method2: int = CM_ConnectToLanInstance, |
| 919 |
timeout2: int = 3000, |
| 920 |
method3: int = CM_ShowListDialog, |
| 921 |
timeout3: int = 0, |
| 922 |
method4: int = CM_Fail, |
| 923 |
timeout4: int = 0, |
| 924 |
parentwindow: None | int = None, |
| 925 |
) -> bool: |
| 926 |
"""Find, select or launch a madTPG instance and connect to it. |
| 927 |
|
| 928 |
Args: |
| 929 |
method1 (int): Connection method for the first attempt. |
| 930 |
timeout1 (int): Timeout in milliseconds for the first attempt. |
| 931 |
method2 (int): Connection method for the second attempt. |
| 932 |
timeout2 (int): Timeout in milliseconds for the second attempt. |
| 933 |
method3 (int): Connection method for the third attempt. |
| 934 |
timeout3 (int): Timeout in milliseconds for the third attempt. |
| 935 |
method4 (int): Connection method for the fourth attempt. |
| 936 |
timeout4 (int): Timeout in milliseconds for the fourth attempt. |
| 937 |
parentwindow (None | int): Parent window handle for dialogs. |
| 938 |
|
| 939 |
Returns: |
| 940 |
bool: True if the connection was successful, False otherwise. |
| 941 |
""" |
| 942 |
return self.mad.madVR_ConnectEx( |
| 943 |
method1, |
| 944 |
timeout1, |
| 945 |
method2, |
| 946 |
timeout2, |
| 947 |
method3, |
| 948 |
timeout3, |
| 949 |
method4, |
| 950 |
timeout4, |
| 951 |
parentwindow, |
| 952 |
) |
| 953 |
|
| 954 |
def get_black_and_white_level(self) -> bool | tuple[int, int]: |
| 955 |
"""Return madVR output level setup. |
| 956 |
|
| 957 |
Returns: |
| 958 |
bool | tuple[int, int]: A tuple containing the black and white |
| 959 |
levels. If the call fails, returns False. |
| 960 |
""" |
| 961 |
blacklvl, whitelvl = ctypes.c_long(), ctypes.c_long() |
| 962 |
result = self.mad.madVR_GetBlackAndWhiteLevel( |
| 963 |
*[ctypes.byref(v) for v in (blacklvl, whitelvl)] |
| 964 |
) |
| 965 |
return result and (blacklvl.value, whitelvl.value) |
| 966 |
|
| 967 |
def get_device_gamma_ramp(self) -> bool | ctypes.Array: |
| 968 |
"""Call the win32 API 'GetDeviceGammaRamp'. |
| 969 |
|
| 970 |
Returns: |
| 971 |
bool | ctypes.Array: A ctypes array containing the gamma ramp |
| 972 |
values for red, green, and blue channels. Each channel has 256 |
| 973 |
entries. If the call fails, returns False. |
| 974 |
""" |
| 975 |
ramp = ((ctypes.c_ushort * 256) * 3)() |
| 976 |
result = self.mad.madVR_GetDeviceGammaRamp(ramp) |
| 977 |
return result and ramp |
| 978 |
|
| 979 |
def get_pattern_config(self) -> bool | tuple[int, int, int, int]: |
| 980 |
"""Return the pattern config as 4-tuple. |
| 981 |
|
| 982 |
Pattern area in percent 1-100 |
| 983 |
Background level in percent 0-100 |
| 984 |
Background mode 0 = constant gray |
| 985 |
1 = APL - gamma light |
| 986 |
2 = APL - linear light |
| 987 |
Black border width in pixels 0-100 |
| 988 |
|
| 989 |
Returns: |
| 990 |
bool | tuple[int, int, int, int]: A tuple containing the pattern |
| 991 |
area, background level, background mode, and black border |
| 992 |
width. If the call fails, returns False. |
| 993 |
""" |
| 994 |
area, bglvl, bgmode, border = [ctypes.c_long() for i in range(4)] |
| 995 |
result = self.mad.madVR_GetPatternConfig( |
| 996 |
*[ctypes.byref(v) for v in (area, bglvl, bgmode, border)] |
| 997 |
) |
| 998 |
return result and (area.value, bglvl.value, bgmode.value, border.value) |
| 999 |
|
| 1000 |
def get_selected_3dlut(self) -> bool | int: |
| 1001 |
"""Return the currently selected 3D LUT ID. |
| 1002 |
|
| 1003 |
Returns: |
| 1004 |
bool | int: The ID of the selected 3D LUT, or None if no LUT is |
| 1005 |
selected. |
| 1006 |
""" |
| 1007 |
thr3dlut = ctypes.c_ulong() |
| 1008 |
result = self.mad.madVR_GetSelected3dlut(ctypes.byref(thr3dlut)) |
| 1009 |
return result and thr3dlut.value |
| 1010 |
|
| 1011 |
def get_version(self) -> bool | tuple[str, str, str, str]: |
| 1012 |
"""Return the madVR version as 4-tuple. |
| 1013 |
|
| 1014 |
Returns: |
| 1015 |
bool | tuple[str, str, str, str]: The madVR version as a tuple of |
| 1016 |
four strings representing the major, minor, patch, and build |
| 1017 |
numbers. |
| 1018 |
""" |
| 1019 |
version = ctypes.c_ulong() |
| 1020 |
result = self.mad.madVR_GetVersion(ctypes.byref(version)) |
| 1021 |
return result and tuple(c for c in struct.pack(">I", version.value)) |
| 1022 |
|
| 1023 |
def show_rgb( |
| 1024 |
self, |
| 1025 |
r: float, |
| 1026 |
g: float, |
| 1027 |
b: float, |
| 1028 |
bgr: None | float = None, |
| 1029 |
bgg: None | float = None, |
| 1030 |
bgb: None | float = None, |
| 1031 |
) -> bool: |
| 1032 |
"""Show a specific RGB color test pattern. |
| 1033 |
|
| 1034 |
Args: |
| 1035 |
r (float): Red component in the range 0.0-255.0. |
| 1036 |
g (float): Green component in the range 0.0-255.0. |
| 1037 |
b (float): Blue component in the range 0.0-255.0. |
| 1038 |
bgr (None | float, optional): Red component for the background |
| 1039 |
color. |
| 1040 |
bgg (None | float, optional): Green component for the background |
| 1041 |
color. |
| 1042 |
bgb (None | float, optional): Blue component for the background |
| 1043 |
color. |
| 1044 |
|
| 1045 |
Returns: |
| 1046 |
bool: True if the operation was successful, False otherwise. |
| 1047 |
""" |
| 1048 |
if None not in (bgr, bgg, bgb): |
| 1049 |
return self.mad.madVR_ShowRGBEx(r, g, b, bgr, bgg, bgb) |
| 1050 |
return self.mad.madVR_ShowRGB(r, g, b) |
| 1051 |
|
| 1052 |
@property |
| 1053 |
def uri(self) -> str: |
| 1054 |
"""Return the URI of the madTPG instance. |
| 1055 |
|
| 1056 |
Returns: |
| 1057 |
str: The URI of the madTPG instance, which is the path to the DLL. |
| 1058 |
""" |
| 1059 |
return self.dllpath |
| 1060 |
|
| 1061 |
|
| 1062 |
class MadTPGNet(MadTPGBase): |
| 1063 |
"""Implementation of madVR network protocol in pure python. |
| 1064 |
|
| 1065 |
Wireshark filter to help ananlyze traffic: |
| 1066 |
|
| 1067 |
(tcp.dstport != 1900 and tcp.dstport != 443) or |
| 1068 |
(udp.dstport != 1900 and udp.dstport != 137 and |
| 1069 |
udp.dstport != 138 and udp.dstport != 5355 and |
| 1070 |
udp.dstport != 547 and udp.dstport != 10111) |
| 1071 |
""" |
| 1072 |
|
| 1073 |
def __init__(self) -> None: |
| 1074 |
MadTPGBase.__init__(self) |
| 1075 |
self._cast_sockets = {} |
| 1076 |
self._casts = [] |
| 1077 |
self._client_sockets = {} |
| 1078 |
self._commandno = 0 |
| 1079 |
self._commands = {} |
| 1080 |
self._host = get_network_addr() |
| 1081 |
self._incoming = {} |
| 1082 |
self._ips = [i[4][0] for i in socket.getaddrinfo(self._host, None)] |
| 1083 |
self._pid = 0 |
| 1084 |
self._reset() |
| 1085 |
self._server_sockets = {} |
| 1086 |
self._threads = [] |
| 1087 |
# self.broadcast_ports = (39568, 41513, 45817, 48591, 48912) |
| 1088 |
self.broadcast_ports = (37018, 10658, 63922, 53181, 4287) |
| 1089 |
self.clients = {} |
| 1090 |
self.debug = 0 |
| 1091 |
self.listening = False |
| 1092 |
# self.multicast_ports = (34761, ) |
| 1093 |
self.multicast_ports = (51591,) |
| 1094 |
self._event_handlers = { |
| 1095 |
"on_client_added": [], |
| 1096 |
"on_client_confirmed": [], |
| 1097 |
"on_client_removed": [], |
| 1098 |
"on_client_updated": [], |
| 1099 |
} |
| 1100 |
# self.server_ports = (37612, 43219, 47815, 48291, 48717) |
| 1101 |
self.server_ports = (60562, 51130, 54184, 41916, 19902) |
| 1102 |
ip = self._host.split(".") |
| 1103 |
ip.pop() |
| 1104 |
ip.append("255") |
| 1105 |
self.broadcast_ip = ".".join(ip) |
| 1106 |
self.multicast_ip = "235.117.220.191" |
| 1107 |
|
| 1108 |
def listen(self) -> None: |
| 1109 |
"""Start listening for incoming connections and broadcasts.""" |
| 1110 |
self.listening = True |
| 1111 |
# Connection listen sockets |
| 1112 |
for port in self.server_ports: |
| 1113 |
if ("", port) in self._server_sockets: |
| 1114 |
continue |
| 1115 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1116 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 1117 |
sock.settimeout(0) |
| 1118 |
try: |
| 1119 |
sock.bind(("", port)) |
| 1120 |
sock.listen(1) |
| 1121 |
thread = threading.Thread( |
| 1122 |
target=self._conn_accept_handler, |
| 1123 |
name=f"madVR.ConnectionHandler[{port}]", |
| 1124 |
args=(sock, "", port), |
| 1125 |
) |
| 1126 |
self._threads.append(thread) |
| 1127 |
thread.start() |
| 1128 |
except OSError as exception: |
| 1129 |
safe_print(f"MadTPG_Net: TCP Port {port}: {exception}") |
| 1130 |
# Broadcast listen sockets |
| 1131 |
for port in self.broadcast_ports: |
| 1132 |
if (self.broadcast_ip, port) in self._cast_sockets: |
| 1133 |
continue |
| 1134 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 1135 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 1136 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) |
| 1137 |
sock.settimeout(0) |
| 1138 |
try: |
| 1139 |
sock.bind(("", port)) |
| 1140 |
thread = threading.Thread( |
| 1141 |
target=self._cast_receive_handler, |
| 1142 |
name=f"madVR.BroadcastHandler[{self.broadcast_ip}:{port}]", |
| 1143 |
args=(sock, self.broadcast_ip, port), |
| 1144 |
) |
| 1145 |
self._threads.append(thread) |
| 1146 |
thread.start() |
| 1147 |
except OSError as exception: |
| 1148 |
safe_print(f"MadTPG_Net: UDP Port {port}: {exception}") |
| 1149 |
# Multicast listen socket |
| 1150 |
for port in self.multicast_ports: |
| 1151 |
if (self.multicast_ip, port) in self._cast_sockets: |
| 1152 |
continue |
| 1153 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 1154 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 1155 |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32) |
| 1156 |
sock.setsockopt( |
| 1157 |
socket.IPPROTO_IP, |
| 1158 |
socket.IP_ADD_MEMBERSHIP, |
| 1159 |
struct.pack( |
| 1160 |
"4sl", socket.inet_aton(self.multicast_ip), socket.INADDR_ANY |
| 1161 |
), |
| 1162 |
) |
| 1163 |
sock.settimeout(0) |
| 1164 |
try: |
| 1165 |
sock.bind(("", port)) |
| 1166 |
thread = threading.Thread( |
| 1167 |
target=self._cast_receive_handler, |
| 1168 |
name=f"madVR.MulticastHandler[{self.multicast_ip}:{port}]", |
| 1169 |
args=(sock, self.multicast_ip, port), |
| 1170 |
) |
| 1171 |
self._threads.append(thread) |
| 1172 |
thread.start() |
| 1173 |
except OSError as exception: |
| 1174 |
safe_print(f"MadTPG_Net: UDP Port {port}: {exception}") |
| 1175 |
|
| 1176 |
def bind(self, event_name: str, handler: Callable) -> None: |
| 1177 |
"""Bind a handler to an event. |
| 1178 |
|
| 1179 |
Args: |
| 1180 |
event_name (str): The name of the event to bind to. |
| 1181 |
handler (Callable): The handler function to bind to the event. |
| 1182 |
""" |
| 1183 |
if event_name not in self._event_handlers: |
| 1184 |
self._event_handlers[event_name] = [] |
| 1185 |
self._event_handlers[event_name].append(handler) |
| 1186 |
|
| 1187 |
def unbind( |
| 1188 |
self, event_name: str, handler: None | Callable = None |
| 1189 |
) -> None | Callable: |
| 1190 |
"""Unbind (remove) a handler from an event. |
| 1191 |
|
| 1192 |
Args: |
| 1193 |
event_name (str): The name of the event to unbind from. |
| 1194 |
handler (None | Callable, optional): The handler to remove. |
| 1195 |
If None, all handlers for the event will be removed. |
| 1196 |
|
| 1197 |
Returns: |
| 1198 |
None | Callable: If handler is specified and found, it is returned. |
| 1199 |
If handler is None, all handlers for the event are removed. |
| 1200 |
If the event has no handlers, None is returned. |
| 1201 |
""" |
| 1202 |
if event_name not in self._event_handlers: |
| 1203 |
return None |
| 1204 |
|
| 1205 |
if handler in self._event_handlers[event_name]: |
| 1206 |
self._event_handlers[event_name].remove(handler) |
| 1207 |
return handler |
| 1208 |
|
| 1209 |
return self._event_handlers.pop(event_name) |
| 1210 |
|
| 1211 |
def _dispatch_event(self, event_name: str, event_data: None | Any = None) -> None: # noqa: ANN401 |
| 1212 |
"""Dispatch events. |
| 1213 |
|
| 1214 |
Args: |
| 1215 |
event_name (str): The name of the event to dispatch. |
| 1216 |
event_data (None | Any, optional): Data associated with the event. |
| 1217 |
Defaults to None. |
| 1218 |
""" |
| 1219 |
if self.debug: |
| 1220 |
safe_print("MadTPG_Net: Dispatching", event_name) |
| 1221 |
for handler in self._event_handlers.get(event_name, []): |
| 1222 |
handler(event_data) |
| 1223 |
|
| 1224 |
def _reset(self) -> None: |
| 1225 |
self._client_socket = None |
| 1226 |
|
| 1227 |
def _conn_accept_handler(self, sock: socket.socket, host: str, port: int) -> None: |
| 1228 |
"""Handle incoming connections on a TCP socket. |
| 1229 |
|
| 1230 |
Args: |
| 1231 |
sock (socket.socket): The socket to accept connections on. |
| 1232 |
host (str): The host address to bind to. |
| 1233 |
port (int): The port to bind to. |
| 1234 |
""" |
| 1235 |
if self.debug: |
| 1236 |
safe_print("MadTPG_Net: Entering incoming connection thread for port", port) |
| 1237 |
self._server_sockets[(host, port)] = sock |
| 1238 |
while getattr(self, "listening", False): |
| 1239 |
try: |
| 1240 |
# Wait for connection |
| 1241 |
conn, addr = sock.accept() |
| 1242 |
except socket.timeout as exception: |
| 1243 |
# Should never happen for non-blocking socket |
| 1244 |
safe_print( |
| 1245 |
f"MadTPG_Net: In incoming connection thread for port {port}:", |
| 1246 |
exception, |
| 1247 |
) |
| 1248 |
continue |
| 1249 |
except OSError as exception: |
| 1250 |
if exception.errno == errno.EWOULDBLOCK: |
| 1251 |
sleep(0.05) |
| 1252 |
continue |
| 1253 |
safe_print( |
| 1254 |
"MadTPG_Net: Exception in incoming connection " |
| 1255 |
f"thread for {addr[0]}:{addr[1]}:", |
| 1256 |
exception, |
| 1257 |
) |
| 1258 |
break |
| 1259 |
conn.settimeout(0) |
| 1260 |
with _LOCK: |
| 1261 |
if self.debug: |
| 1262 |
socket_name = conn.getsockname() |
| 1263 |
safe_print( |
| 1264 |
"MadTPG_Net: Incoming connection from " |
| 1265 |
f"{addr[0]}:{addr[1]} to {socket_name[0]}:{socket_name[1]}" |
| 1266 |
) |
| 1267 |
if addr in self._client_sockets: |
| 1268 |
if self.debug: |
| 1269 |
socket_name = conn.getsockname() |
| 1270 |
safe_print( |
| 1271 |
"MadTPG_Net: Already connected from " |
| 1272 |
f"{addr[0]}:{addr[1]} to {socket_name[0]}:{socket_name[1]}" |
| 1273 |
) |
| 1274 |
self._shutdown(conn, addr) |
| 1275 |
else: |
| 1276 |
self._client_sockets[addr] = conn |
| 1277 |
thread = threading.Thread( |
| 1278 |
target=self._receive_handler, |
| 1279 |
name=f"madVR.Receiver[{addr[0]}:{addr[1]}]", |
| 1280 |
args=( |
| 1281 |
addr, |
| 1282 |
conn, |
| 1283 |
), |
| 1284 |
) |
| 1285 |
self._threads.append(thread) |
| 1286 |
thread.start() |
| 1287 |
self._server_sockets.pop((host, port)) |
| 1288 |
self._shutdown(sock, (host, port)) |
| 1289 |
if self.debug: |
| 1290 |
safe_print("MadTPG_Net: Exiting incoming connection thread for port", port) |
| 1291 |
|
| 1292 |
def _receive_handler(self, addr: tuple, conn: socket.socket) -> None: |
| 1293 |
"""Handle incoming messages from a client connection. |
| 1294 |
|
| 1295 |
Args: |
| 1296 |
addr (tuple): The address of the client (IP, port). |
| 1297 |
conn (socket.socket): The socket connection to the client. |
| 1298 |
""" |
| 1299 |
if self.debug: |
| 1300 |
safe_print(f"MadTPG_Net: Entering receiver thread for {addr[0]}:{addr[1]}") |
| 1301 |
self._incoming[addr] = [] |
| 1302 |
hello = self._hello(conn) |
| 1303 |
blob = b"" |
| 1304 |
send_bye = True |
| 1305 |
while ( |
| 1306 |
hello and addr in self._client_sockets and getattr(self, "listening", False) |
| 1307 |
): |
| 1308 |
# Wait for incoming message |
| 1309 |
try: |
| 1310 |
incoming = conn.recv(4096) |
| 1311 |
except socket.timeout as exception: |
| 1312 |
# Should never happen for non-blocking socket |
| 1313 |
safe_print( |
| 1314 |
f"MadTPG_Net: In receiver thread for {addr[0]}:{addr[1]}:", |
| 1315 |
exception, |
| 1316 |
) |
| 1317 |
continue |
| 1318 |
except OSError as exception: |
| 1319 |
if exception.errno == errno.EWOULDBLOCK: |
| 1320 |
sleep(0.001) |
| 1321 |
continue |
| 1322 |
if exception.errno not in (errno.EBADF, errno.ECONNRESET) or self.debug: |
| 1323 |
safe_print( |
| 1324 |
f"MadTPG_Net: In receiver thread for {addr[0]}:{addr[1]}:", |
| 1325 |
exception, |
| 1326 |
) |
| 1327 |
send_bye = False |
| 1328 |
break |
| 1329 |
else: |
| 1330 |
send_bye, break_early = self._process_client_message( |
| 1331 |
addr, conn, incoming, send_bye, blob |
| 1332 |
) |
| 1333 |
if break_early: |
| 1334 |
break |
| 1335 |
with _LOCK: |
| 1336 |
self._remove_client( |
| 1337 |
addr, send_bye=addr in self._client_sockets and send_bye |
| 1338 |
) |
| 1339 |
self._incoming.pop(addr) |
| 1340 |
if self.debug: |
| 1341 |
safe_print( |
| 1342 |
"MadTPG_Net: Exiting receiver thread for {}:{}".format(*addr[:2]) |
| 1343 |
) |
| 1344 |
|
| 1345 |
def _process_client_message( |
| 1346 |
self, |
| 1347 |
addr: tuple, |
| 1348 |
conn: socket.socket, |
| 1349 |
incoming: bytes, |
| 1350 |
send_bye: bool, |
| 1351 |
blob: bytes, |
| 1352 |
) -> tuple[bool, bool]: |
| 1353 |
"""Process incoming message from a client. |
| 1354 |
|
| 1355 |
Args: |
| 1356 |
addr (tuple): The address of the client (IP, port). |
| 1357 |
conn (socket.socket): The socket connection to the client. |
| 1358 |
incoming (bytes): The incoming data from the client. |
| 1359 |
send_bye (bool): Whether to send a "bye" message on disconnection. |
| 1360 |
blob (bytes): The accumulated data blob for processing. |
| 1361 |
|
| 1362 |
Returns: |
| 1363 |
tuple: A tuple containing the updated send_bye flag and a boolean |
| 1364 |
indicating whether to break early from the processing loop. |
| 1365 |
""" |
| 1366 |
with _LOCK: |
| 1367 |
if not incoming: |
| 1368 |
# Connection broken |
| 1369 |
if self.debug: |
| 1370 |
safe_print( |
| 1371 |
f"MadTPG_Net: Client {addr[0]}:{addr[1]} stopped sending" |
| 1372 |
) |
| 1373 |
send_bye = False |
| 1374 |
return send_bye, True |
| 1375 |
blob += incoming |
| 1376 |
if self.debug: |
| 1377 |
safe_print("MadTPG_Net: Received from {}:{}:".format(*addr[:2])) |
| 1378 |
while blob and addr in self._client_sockets: |
| 1379 |
try: |
| 1380 |
record, blob = self._parse(blob) |
| 1381 |
except ValueError as exception: |
| 1382 |
safe_print("MadTPG_Net:", exception) |
| 1383 |
# Invalid, discard |
| 1384 |
blob = "" |
| 1385 |
else: |
| 1386 |
if record is None: |
| 1387 |
# Need more data |
| 1388 |
break |
| 1389 |
try: |
| 1390 |
self._process(record, conn) |
| 1391 |
except OSError as exception: |
| 1392 |
safe_print("MadTPG_Net:", exception) |
| 1393 |
return send_bye, False |
| 1394 |
|
| 1395 |
def _remove_client(self, addr: tuple, send_bye: bool = True) -> None: |
| 1396 |
"""Remove client from list of connected clients. |
| 1397 |
|
| 1398 |
Args: |
| 1399 |
addr (tuple): The address of the client to be removed. |
| 1400 |
send_bye (bool, optional): Whether to send a "bye" message before |
| 1401 |
removing. Defaults to True. |
| 1402 |
""" |
| 1403 |
if addr not in self._client_sockets: |
| 1404 |
return |
| 1405 |
conn = self._client_sockets.pop(addr) |
| 1406 |
if send_bye: |
| 1407 |
self._send( |
| 1408 |
conn, |
| 1409 |
"bye", |
| 1410 |
component=self.clients.get(addr, {}).get("component", b""), |
| 1411 |
) |
| 1412 |
if addr in self.clients: |
| 1413 |
client = self.clients.pop(addr) |
| 1414 |
if self.debug: |
| 1415 |
safe_print(f"MadTPG_Net: Removed client {addr[0]}:{addr[1]}") |
| 1416 |
self._dispatch_event("on_client_removed", (addr, client)) |
| 1417 |
if self._client_socket and self._client_socket == conn: |
| 1418 |
self._reset() |
| 1419 |
self._shutdown(conn, addr) |
| 1420 |
|
| 1421 |
def _cast_receive_handler( |
| 1422 |
self, |
| 1423 |
sock: socket.socket, |
| 1424 |
host: str, |
| 1425 |
port: int, |
| 1426 |
) -> None: |
| 1427 |
"""Handle incoming broadcasts and multicasts. |
| 1428 |
|
| 1429 |
Args: |
| 1430 |
sock (socket.socket): The socket to listen for broadcasts or multicasts. |
| 1431 |
host (str): The host address for the broadcast or multicast. |
| 1432 |
port (int): The port number for the broadcast or multicast. |
| 1433 |
""" |
| 1434 |
if host == self.broadcast_ip: |
| 1435 |
cast = "broadcast" |
| 1436 |
elif host == self.multicast_ip: |
| 1437 |
cast = "multicast" |
| 1438 |
else: |
| 1439 |
cast = "unknown" |
| 1440 |
if self.debug: |
| 1441 |
safe_print(f"MadTPG_Net: Entering receiver thread for {cast} port {port}") |
| 1442 |
self._cast_sockets[(host, port)] = sock |
| 1443 |
while getattr(self, "listening", False): |
| 1444 |
try: |
| 1445 |
data, addr = sock.recvfrom(4096) |
| 1446 |
except socket.timeout as exception: |
| 1447 |
safe_print( |
| 1448 |
f"MadTPG_Net: In receiver thread for {cast} port {port}:", |
| 1449 |
exception, |
| 1450 |
) |
| 1451 |
continue |
| 1452 |
except OSError as exception: |
| 1453 |
if exception.errno == errno.EWOULDBLOCK: |
| 1454 |
sleep(0.05) |
| 1455 |
continue |
| 1456 |
if exception.errno != errno.ECONNRESET or self.debug: |
| 1457 |
safe_print( |
| 1458 |
f"MadTPG_Net: In receiver thread for {cast} port {port}:", |
| 1459 |
exception, |
| 1460 |
) |
| 1461 |
break |
| 1462 |
else: |
| 1463 |
self._process_incoming_cast(cast, data, addr) |
| 1464 |
self._cast_sockets.pop((host, port)) |
| 1465 |
self._shutdown(sock, (host, port)) |
| 1466 |
if self.debug: |
| 1467 |
safe_print(f"MadTPG_Net: Exiting {cast} receiver thread for port {port}") |
| 1468 |
|
| 1469 |
def _process_incoming_cast(self, cast: str, data: bytes, addr: tuple) -> None: |
| 1470 |
"""Process incoming broadcast or multicast message. |
| 1471 |
|
| 1472 |
Args: |
| 1473 |
cast (str): Type of the cast ("broadcast" or "multicast"). |
| 1474 |
data (bytes): The received data. |
| 1475 |
addr (tuple): The address of the sender (IP, port). |
| 1476 |
""" |
| 1477 |
with _LOCK: |
| 1478 |
if self.debug: |
| 1479 |
safe_print( |
| 1480 |
f"MadTPG_Net: Received {cast} from {addr[0]}:{addr[1]}: {data!r}" |
| 1481 |
) |
| 1482 |
if addr not in self._casts: |
| 1483 |
for c_port in self.server_ports: |
| 1484 |
if (addr[0], c_port) in self._client_sockets: |
| 1485 |
if self.debug: |
| 1486 |
safe_print( |
| 1487 |
f"MadTPG_Net: Already connected to {addr[0]}:{c_port}" |
| 1488 |
) |
| 1489 |
elif ("", c_port) in self._server_sockets and addr[0] in self._ips: |
| 1490 |
if self.debug: |
| 1491 |
safe_print( |
| 1492 |
f"MadTPG_Net: Don't connect to self {addr[0]}:{c_port}" |
| 1493 |
) |
| 1494 |
else: |
| 1495 |
conn = self._get_client_socket(addr[0], c_port) |
| 1496 |
threading.Thread( |
| 1497 |
target=self._connect, |
| 1498 |
name=f"madVR.ConnectToInstance[{addr[0]}:{c_port}]", |
| 1499 |
args=(conn, addr[0], c_port), |
| 1500 |
).start() |
| 1501 |
else: |
| 1502 |
self._casts.remove(addr) |
| 1503 |
if self.debug: |
| 1504 |
safe_print( |
| 1505 |
f"MadTPG_Net: Ignoring own {cast} from {addr[0]}:{addr[1]}" |
| 1506 |
) |
| 1507 |
|
| 1508 |
def __del__(self) -> None: |
| 1509 |
"""Clean up resources on deletion.""" |
| 1510 |
self.shutdown() |
| 1511 |
|
| 1512 |
def _shutdown(self, sock: socket.socket, addr: tuple) -> None: |
| 1513 |
"""Shutdown and close the socket. |
| 1514 |
|
| 1515 |
Args: |
| 1516 |
sock (socket.socket): The socket to be shut down and closed. |
| 1517 |
addr (tuple): The address of the socket, used for logging. |
| 1518 |
""" |
| 1519 |
try: |
| 1520 |
# Will fail if the socket isn't connected, i.e. if there |
| 1521 |
# was an error during the call to connect() |
| 1522 |
sock.shutdown(socket.SHUT_RDWR) |
| 1523 |
except OSError as exception: |
| 1524 |
if exception.errno != errno.ENOTCONN: |
| 1525 |
safe_print( |
| 1526 |
f"MadTPG_Net: SHUT_RDWR for {addr[0]}:{addr[1]} failed:", |
| 1527 |
exception, |
| 1528 |
) |
| 1529 |
sock.close() |
| 1530 |
|
| 1531 |
def shutdown(self) -> None: |
| 1532 |
"""Shutdown the madTPG network connection.""" |
| 1533 |
self.disconnect() |
| 1534 |
self.listening = False |
| 1535 |
while self._threads: |
| 1536 |
thread = self._threads.pop() |
| 1537 |
if thread.is_alive(): |
| 1538 |
thread.join() |
| 1539 |
|
| 1540 |
def __getattr__(self, name: str) -> MadTPGNetSender: |
| 1541 |
"""Get attribute from madVR DLL. |
| 1542 |
|
| 1543 |
Args: |
| 1544 |
name (str): Name of the method to call. |
| 1545 |
|
| 1546 |
Raises: |
| 1547 |
AttributeError: If the method name is not found in the madVR DLL. |
| 1548 |
|
| 1549 |
Returns: |
| 1550 |
MadTPGNetSender: An instance of MadTPGNetSender with the method |
| 1551 |
name set to the specified method. |
| 1552 |
""" |
| 1553 |
# Instead of writing individual method wrappers, we use Python's magic |
| 1554 |
# to handle this for us. Note that we're sticking to pythonic method |
| 1555 |
# names, so 'disable_3dlut' instead of 'Disable3dlut' etc. |
| 1556 |
|
| 1557 |
# Convert from pythonic method name to CamelCase |
| 1558 |
methodname = "".join(part.capitalize() for part in name.split("_")) |
| 1559 |
|
| 1560 |
if methodname == "ShowRgb": |
| 1561 |
methodname = "ShowRGB" |
| 1562 |
|
| 1563 |
# Check if this is a madVR method we support |
| 1564 |
if methodname not in _METHOD_NAMES: |
| 1565 |
raise AttributeError( |
| 1566 |
f"{self.__class__.__name__!r} object has no attribute {name!r}" |
| 1567 |
) |
| 1568 |
|
| 1569 |
# Call the method and return the result |
| 1570 |
return MadTPGNetSender(self, self._client_socket, methodname) |
| 1571 |
|
| 1572 |
def announce(self) -> None: |
| 1573 |
"""Anounce ourselves.""" |
| 1574 |
for port in self.multicast_ports: |
| 1575 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 1576 |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32) |
| 1577 |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0) |
| 1578 |
sock.settimeout(1) |
| 1579 |
sock.connect((self.multicast_ip, port)) |
| 1580 |
addr = sock.getsockname() |
| 1581 |
self._casts.append(addr) |
| 1582 |
if self.debug: |
| 1583 |
safe_print( |
| 1584 |
f"MadTPG_Net: Sending multicast from {addr[0]}:{addr[1]} " |
| 1585 |
f"to port {port}" |
| 1586 |
) |
| 1587 |
sock.sendall(struct.pack("<i", 0)) |
| 1588 |
self._shutdown(sock, (self.multicast_ip, port)) |
| 1589 |
for port in self.broadcast_ports: |
| 1590 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 1591 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) |
| 1592 |
sock.settimeout(1) |
| 1593 |
sock.connect((self.broadcast_ip, port)) |
| 1594 |
addr = sock.getsockname() |
| 1595 |
self._casts.append(addr) |
| 1596 |
if self.debug: |
| 1597 |
safe_print( |
| 1598 |
f"MadTPG_Net: Sending broadcast from {addr[0]}:{addr[1]} " |
| 1599 |
f"to port {port}" |
| 1600 |
) |
| 1601 |
sock.sendall(struct.pack("<i", 0)) |
| 1602 |
self._shutdown(sock, (self.broadcast_ip, port)) |
| 1603 |
|
| 1604 |
def connect( |
| 1605 |
self, |
| 1606 |
method1: int = CM_ConnectToLanInstance, |
| 1607 |
timeout1: int = 4000, |
| 1608 |
method2: int = CM_ShowListDialog, |
| 1609 |
timeout2: int = 0, |
| 1610 |
method3: int = CM_Fail, |
| 1611 |
timeout3: int = 0, |
| 1612 |
method4: int = CM_Fail, |
| 1613 |
timeout4: int = 0, |
| 1614 |
parentwindow: None | int = None, |
| 1615 |
) -> bool: |
| 1616 |
"""Find or select a madTPG instance on the network and connect to it. |
| 1617 |
|
| 1618 |
Args: |
| 1619 |
method1 (int, optional): The first connection method to try. |
| 1620 |
Defaults to CM_ConnectToLanInstance. |
| 1621 |
timeout1 (int, optional): Timeout for the first connection method |
| 1622 |
in milliseconds. Defaults to 4000. |
| 1623 |
method2 (int, optional): The second connection method to try. |
| 1624 |
Defaults to CM_ShowListDialog. |
| 1625 |
timeout2 (int, optional): Timeout for the second connection method |
| 1626 |
in milliseconds. Defaults to 0. |
| 1627 |
method3 (int, optional): The third connection method to try. |
| 1628 |
Defaults to CM_Fail. |
| 1629 |
timeout3 (int, optional): Timeout for the third connection method |
| 1630 |
in milliseconds. Defaults to 0. |
| 1631 |
method4 (int, optional): The fourth connection method to try. |
| 1632 |
Defaults to CM_Fail. |
| 1633 |
timeout4 (int, optional): Timeout for the fourth connection method |
| 1634 |
in milliseconds. Defaults to 0. |
| 1635 |
parentwindow (None | int): The parent window for any dialogs that |
| 1636 |
may be shown. |
| 1637 |
|
| 1638 |
Returns: |
| 1639 |
bool: True if the connection was successful, False otherwise. |
| 1640 |
""" |
| 1641 |
listened = self.listening |
| 1642 |
for method, timeout in [ |
| 1643 |
(method1, timeout1), |
| 1644 |
(method2, timeout2), |
| 1645 |
(method3, timeout3), |
| 1646 |
(method4, timeout4), |
| 1647 |
]: |
| 1648 |
timeout = timeout / 1000.0 |
| 1649 |
if method in (CM_ConnectToLanInstance, CM_ShowListDialog): |
| 1650 |
if not self._cast_sockets and not listened: |
| 1651 |
self.listen() |
| 1652 |
listened = True |
| 1653 |
# Give a little time for the user to acknowledge any |
| 1654 |
# OS firewall prompts |
| 1655 |
sleep(3) |
| 1656 |
if method == CM_ShowListDialog: |
| 1657 |
# TODO: Implement |
| 1658 |
pass |
| 1659 |
elif self.listening: |
| 1660 |
# Re-use existing connection |
| 1661 |
if self._wait_for_client(None, 0.001): |
| 1662 |
return True |
| 1663 |
# Otherwise, announce ourselves |
| 1664 |
self.announce() |
| 1665 |
if self._wait_for_client(None, timeout - 0.001): |
| 1666 |
return True |
| 1667 |
elif method == CM_ShowIpAddrDialog: |
| 1668 |
# TODO: Implement |
| 1669 |
pass |
| 1670 |
return False |
| 1671 |
|
| 1672 |
def connect_to_ip(self, ip: str, timeout: int = 1000) -> bool: |
| 1673 |
"""Connect to madTPG running under a known IP address. |
| 1674 |
|
| 1675 |
Args: |
| 1676 |
ip (str): The IP address of the madTPG instance. |
| 1677 |
timeout (int, optional): Timeout for the connection attempt in |
| 1678 |
milliseconds. Defaults to 1000. |
| 1679 |
|
| 1680 |
Returns: |
| 1681 |
bool: True if the connection was successful, False otherwise. |
| 1682 |
""" |
| 1683 |
ip = socket.gethostbyname(ip) |
| 1684 |
for port in self.server_ports: |
| 1685 |
conn = self._get_client_socket(ip, port) |
| 1686 |
threading.Thread( |
| 1687 |
target=self._connect, |
| 1688 |
name=f"madVR.ConnectToInstance[{ip}:{port}]", |
| 1689 |
args=(conn, ip, port, timeout / 1000.0), |
| 1690 |
).start() |
| 1691 |
return self._wait_for_client((ip, port), timeout / 1000.0) |
| 1692 |
|
| 1693 |
def _get_client_socket( |
| 1694 |
self, host: str, port: int, timeout: float = 1 |
| 1695 |
) -> socket.socket: |
| 1696 |
"""Return a new or existing client socket. |
| 1697 |
|
| 1698 |
Args: |
| 1699 |
host (str): The host IP address. |
| 1700 |
port (int): The port number to connect to. |
| 1701 |
timeout (float): Timeout for the connection attempt in seconds. |
| 1702 |
|
| 1703 |
Returns: |
| 1704 |
socket.socket: The client socket for the specified host and port. |
| 1705 |
""" |
| 1706 |
if (host, port) in self._client_sockets: |
| 1707 |
return self._client_sockets[(host, port)] |
| 1708 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1709 |
sock.settimeout(timeout) |
| 1710 |
self._client_sockets[(host, port)] = sock |
| 1711 |
return sock |
| 1712 |
|
| 1713 |
def _connect( |
| 1714 |
self, sock: socket.socket, host: str, port: int, timeout: float = 1 |
| 1715 |
) -> None: |
| 1716 |
"""Connect to IP:PORT, return socket. |
| 1717 |
|
| 1718 |
Args: |
| 1719 |
sock (socket.socket): The socket to connect. |
| 1720 |
host (str): The host IP address. |
| 1721 |
port (int): The port number to connect to. |
| 1722 |
timeout (float): Timeout for the connection attempt in seconds. |
| 1723 |
|
| 1724 |
Raises: |
| 1725 |
OSError: If the connection fails. |
| 1726 |
""" |
| 1727 |
if self.debug: |
| 1728 |
safe_print(f"MadTPG_Net: Connecting to {host}:{port}...") |
| 1729 |
try: |
| 1730 |
sock.connect((host, port)) |
| 1731 |
except OSError as exception: |
| 1732 |
if self.debug: |
| 1733 |
safe_print( |
| 1734 |
f"MadTPG_Net: Connecting to {host}:{port} failed:", exception |
| 1735 |
) |
| 1736 |
with _LOCK: |
| 1737 |
self._remove_client((host, port), False) |
| 1738 |
else: |
| 1739 |
if self.debug: |
| 1740 |
safe_print(f"MadTPG_Net: Connected to {host}:{port}") |
| 1741 |
sock.settimeout(0) |
| 1742 |
thread = threading.Thread( |
| 1743 |
target=self._receive_handler, |
| 1744 |
name=f"madVR.Receiver[{host}:{port}]", |
| 1745 |
args=( |
| 1746 |
(host, port), |
| 1747 |
sock, |
| 1748 |
), |
| 1749 |
) |
| 1750 |
self._threads.append(thread) |
| 1751 |
thread.start() |
| 1752 |
|
| 1753 |
def disconnect(self, stop: bool = True) -> bool: |
| 1754 |
"""Disconnect from madTPG instance. |
| 1755 |
|
| 1756 |
Args: |
| 1757 |
stop (bool): If True, send 'StopTestPattern' command to madTPG. |
| 1758 |
Defaults to True. |
| 1759 |
|
| 1760 |
Returns: |
| 1761 |
bool: True if the disconnect was successful, False otherwise. |
| 1762 |
""" |
| 1763 |
returnvalue = False |
| 1764 |
conn = self._client_socket |
| 1765 |
if conn: |
| 1766 |
returnvalue = True |
| 1767 |
if stop: |
| 1768 |
returnvalue = self._send(conn, "StopTestPattern") |
| 1769 |
self._reset() |
| 1770 |
return returnvalue |
| 1771 |
|
| 1772 |
def _process(self, record: dict, conn: socket.socket) -> None: |
| 1773 |
"""Process madVR packet. |
| 1774 |
|
| 1775 |
Args: |
| 1776 |
record (dict): The parsed record from the madVR packet. |
| 1777 |
conn (socket.socket): The socket connection from which the packet |
| 1778 |
was received. |
| 1779 |
""" |
| 1780 |
command = record["command"] |
| 1781 |
if command not in ("bye", "confirm", "hello", "reply"): |
| 1782 |
# Ignore |
| 1783 |
return |
| 1784 |
addr = conn.getpeername() |
| 1785 |
commandno = record["commandNo"] |
| 1786 |
component = record["component"] |
| 1787 |
params = record["params"] |
| 1788 |
client = {} |
| 1789 |
client["processId"] = record["processId"] |
| 1790 |
client["module"] = record["module"] |
| 1791 |
client["component"] = component |
| 1792 |
client["instance"] = record["instance"] |
| 1793 |
if command == "reply": |
| 1794 |
if params == "+": |
| 1795 |
params = True |
| 1796 |
elif params == "-": |
| 1797 |
params = False |
| 1798 |
elif command == "confirm": |
| 1799 |
if addr not in self.clients: |
| 1800 |
self.clients[addr] = client |
| 1801 |
self._dispatch_event("on_client_added", (addr, self.clients[addr])) |
| 1802 |
self.clients[addr]["confirmed"] = True |
| 1803 |
self._dispatch_event("on_client_confirmed", (addr, self.clients[addr])) |
| 1804 |
elif command == "hello": |
| 1805 |
is_duplicate_connection = self._process_new_client( |
| 1806 |
conn, addr, params, client |
| 1807 |
) |
| 1808 |
if is_duplicate_connection: |
| 1809 |
# Duplicate connection, ignore |
| 1810 |
return |
| 1811 |
elif command == "bye": |
| 1812 |
if self.debug: |
| 1813 |
safe_print(f"MadTPG_Net: Client {addr[0]}:{addr[1]} disconnected") |
| 1814 |
self._remove_client(addr) |
| 1815 |
self._incoming[addr].append((commandno, command, params, component)) |
| 1816 |
|
| 1817 |
def _process_new_client( |
| 1818 |
self, |
| 1819 |
conn: socket.socket, |
| 1820 |
addr: tuple, |
| 1821 |
params: str, |
| 1822 |
client: dict, |
| 1823 |
) -> bool: |
| 1824 |
"""Process new client connection. |
| 1825 |
|
| 1826 |
Args: |
| 1827 |
conn (socket.socket): The socket connection from which the packet |
| 1828 |
was received. |
| 1829 |
addr (tuple): The address of the client (IP, port). |
| 1830 |
params (str): The parameters from the 'hello' packet. |
| 1831 |
client (dict): The client information extracted from the packet. |
| 1832 |
|
| 1833 |
Returns: |
| 1834 |
bool: True if the connection is a duplicate and should be ignored, |
| 1835 |
False otherwise. |
| 1836 |
""" |
| 1837 |
client.update(params) |
| 1838 |
if addr not in self.clients: |
| 1839 |
self.clients[addr] = client |
| 1840 |
if self._is_master(conn): |
| 1841 |
# Prevent duplicate connections |
| 1842 |
for c_addr in self.clients: |
| 1843 |
c_client = self.clients[c_addr] |
| 1844 |
if ( |
| 1845 |
c_client.get("confirmed") |
| 1846 |
and c_client["processId"] == client["processId"] |
| 1847 |
and c_client["module"] == client["module"] |
| 1848 |
): |
| 1849 |
if self.debug: |
| 1850 |
safe_print( |
| 1851 |
"MadTPG_Net: Preventing duplicate connection " |
| 1852 |
f"{addr[0]}:{addr[1]}" |
| 1853 |
) |
| 1854 |
self._remove_client(addr, False) |
| 1855 |
return True |
| 1856 |
self._dispatch_event("on_client_added", (addr, client)) |
| 1857 |
else: |
| 1858 |
client_copy = self.clients[addr].copy() |
| 1859 |
self.clients[addr].update(client) |
| 1860 |
if self.clients[addr] != client_copy: |
| 1861 |
self._dispatch_event("on_client_updated", (addr, self.clients[addr])) |
| 1862 |
if ( |
| 1863 |
not self.clients[addr].get("confirmed") |
| 1864 |
and self._is_master(conn) |
| 1865 |
and self._send(conn, "confirm", component=b"") |
| 1866 |
): |
| 1867 |
self._sent_confirm_packet_for_master(addr, client) |
| 1868 |
return False |
| 1869 |
|
| 1870 |
def _sent_confirm_packet_for_master(self, addr: tuple, client: dict) -> None: |
| 1871 |
"""Handle actions after sending confirm packet as master. |
| 1872 |
|
| 1873 |
Args: |
| 1874 |
addr (tuple): The address of the client (IP, port). |
| 1875 |
client (dict): The client information extracted from the packet. |
| 1876 |
""" |
| 1877 |
# We are master, sent confirm packet |
| 1878 |
self.clients[addr]["confirmed"] = True |
| 1879 |
self._dispatch_event("on_client_confirmed", (addr, self.clients[addr])) |
| 1880 |
# Close duplicate connections |
| 1881 |
for c_addr in self.clients: |
| 1882 |
c_client = self.clients[c_addr] |
| 1883 |
if ( |
| 1884 |
c_addr != addr |
| 1885 |
and c_client["processId"] == client["processId"] |
| 1886 |
and c_client["module"] == client["module"] |
| 1887 |
): |
| 1888 |
if self.debug: |
| 1889 |
safe_print( |
| 1890 |
"MadTPG_Net: Closing duplicate connection " |
| 1891 |
f"{c_addr[0]}:{c_addr[1]}" |
| 1892 |
) |
| 1893 |
self._remove_client(c_addr) |
| 1894 |
|
| 1895 |
def get_black_and_white_level(self) -> bool | str | tuple[int, int]: |
| 1896 |
"""Return madVR output level setup. |
| 1897 |
|
| 1898 |
Returns: |
| 1899 |
tuple: A tuple containing the black level and white level. |
| 1900 |
""" |
| 1901 |
# XXX: madHcNetXX.dll exports madVR_GetBlackAndWhiteLevel, |
| 1902 |
# but the equivalent madVR network protocol command is |
| 1903 |
# GetBlackWhiteLevel (without the "And")! |
| 1904 |
return MadTPGNetSender(self, self._client_socket, "GetBlackWhiteLevel")() |
| 1905 |
|
| 1906 |
def get_version(self) -> bool | tuple[str, str, str, str]: |
| 1907 |
"""Return madVR version. |
| 1908 |
|
| 1909 |
Returns: |
| 1910 |
bool | tuple[str, str, str, str]: The madVR version as a tuple of |
| 1911 |
four strings representing the major, minor, patch, and build |
| 1912 |
numbers, or False if the version could not be determined. |
| 1913 |
""" |
| 1914 |
try: |
| 1915 |
return ( |
| 1916 |
self._client_socket |
| 1917 |
and self.clients.get(self._client_socket.getpeername(), {}).get( |
| 1918 |
"mvrVersion" |
| 1919 |
) |
| 1920 |
) or False |
| 1921 |
except OSError as exception: |
| 1922 |
if self.debug: |
| 1923 |
safe_print("MadTPG_Net:", exception) |
| 1924 |
return False |
| 1925 |
|
| 1926 |
def _assemble_hello_params(self) -> str: |
| 1927 |
"""Assemble 'hello' packet parameters. |
| 1928 |
|
| 1929 |
Returns: |
| 1930 |
str: The assembled parameters for the 'hello' packet. |
| 1931 |
""" |
| 1932 |
info = [ |
| 1933 |
("computerName", str(socket.gethostname().upper())), |
| 1934 |
("userName", str(getpass.getuser())), |
| 1935 |
("os", f"{platform.system()} {platform.release()}"), |
| 1936 |
("exeFile", os.path.basename(sys.executable)), |
| 1937 |
("exeVersion", VERSION_STRING), |
| 1938 |
("exeDescr", ""), |
| 1939 |
("exeIcon", ""), |
| 1940 |
] |
| 1941 |
params = "" |
| 1942 |
for key, value in info: |
| 1943 |
params += f"{key}={value}\t" |
| 1944 |
return params |
| 1945 |
|
| 1946 |
def _hello(self, conn: socket.socket) -> bool: |
| 1947 |
"""Send 'hello' packet. Return boolean wether send succeeded or not. |
| 1948 |
|
| 1949 |
Args: |
| 1950 |
conn (socket.socket): The socket connection to send the hello |
| 1951 |
packet. |
| 1952 |
|
| 1953 |
Returns: |
| 1954 |
bool: True if the hello packet was sent successfully, False |
| 1955 |
otherwise. |
| 1956 |
""" |
| 1957 |
params = self._assemble_hello_params() |
| 1958 |
return self._send(conn, "hello", params, b"") |
| 1959 |
|
| 1960 |
def _is_master(self, conn: socket.socket) -> bool: |
| 1961 |
"""Return wether our end of the connection is the master or not. |
| 1962 |
|
| 1963 |
Args: |
| 1964 |
conn (socket.socket): The socket connection to check. |
| 1965 |
|
| 1966 |
Returns: |
| 1967 |
bool: True if our end is the master, False otherwise. |
| 1968 |
""" |
| 1969 |
local = conn.getsockname() |
| 1970 |
remote = conn.getpeername() |
| 1971 |
return inet_pton(local[0]) > inet_pton(remote[0]) or ( |
| 1972 |
inet_pton(local[0]) == inet_pton(remote[0]) |
| 1973 |
and self.clients[remote]["processId"] < os.getpid() |
| 1974 |
) |
| 1975 |
|
| 1976 |
def _expect( |
| 1977 |
self, |
| 1978 |
conn: socket.socket, |
| 1979 |
commandno: int = -1, |
| 1980 |
command: None | str = None, |
| 1981 |
params: list | tuple = (), |
| 1982 |
component: str = "", |
| 1983 |
timeout: float = 3, |
| 1984 |
) -> bool: |
| 1985 |
"""Wait until expected reply or timeout. Return reply params or False. |
| 1986 |
|
| 1987 |
Args: |
| 1988 |
conn (socket.socket): The socket connection to wait for replies. |
| 1989 |
commandno (int): The command number to wait for, -1 for any. |
| 1990 |
command (None | str, optional): The command to wait for, None for |
| 1991 |
any. |
| 1992 |
params (list | tuple): The parameters to wait for, empty for any. |
| 1993 |
component (str): The component to wait for, None for any. |
| 1994 |
timeout (float): Timeout in seconds to wait for the reply. |
| 1995 |
|
| 1996 |
Returns: |
| 1997 |
bool: The reply parameters if found, False if timeout exceeded or |
| 1998 |
no reply found. |
| 1999 |
""" |
| 2000 |
if not isinstance(params, (list, tuple)): |
| 2001 |
params = (params,) |
| 2002 |
try: |
| 2003 |
addr = conn.getpeername() |
| 2004 |
except OSError as exception: |
| 2005 |
safe_print("MadTPG_Net:", exception) |
| 2006 |
return False |
| 2007 |
start = end = time() |
| 2008 |
while end - start < timeout: |
| 2009 |
for reply in self._incoming.get(addr, []): |
| 2010 |
r_commandno, r_command, r_params, r_component = reply |
| 2011 |
if ( |
| 2012 |
commandno in (r_commandno, -1) |
| 2013 |
and command in (r_command, None) |
| 2014 |
and not params |
| 2015 |
) or ((r_params in params) and component in (r_component, None)): |
| 2016 |
self._incoming[addr].remove(reply) |
| 2017 |
return r_params |
| 2018 |
sleep(0.001) |
| 2019 |
end = time() |
| 2020 |
if self.debug: |
| 2021 |
safe_print("MadTPG_Net: Timeout exceeded while waiting for reply") |
| 2022 |
return False |
| 2023 |
|
| 2024 |
def _wait_for_client( |
| 2025 |
self, |
| 2026 |
addr: None | tuple = None, |
| 2027 |
timeout: float = 1, |
| 2028 |
) -> bool: |
| 2029 |
"""Wait for (first) madTPG client connection and handshake. |
| 2030 |
|
| 2031 |
Args: |
| 2032 |
addr (tuple): Optional address to wait for, if None, wait for any |
| 2033 |
client. |
| 2034 |
timeout (float): Timeout in seconds to wait for the client. |
| 2035 |
|
| 2036 |
Returns: |
| 2037 |
bool: True if a madTPG client was found and the StartTestPattern |
| 2038 |
command was successfully sent, False otherwise. |
| 2039 |
""" |
| 2040 |
start = end = time() |
| 2041 |
while self.listening and end - start < timeout: |
| 2042 |
clients = self.clients.copy() |
| 2043 |
if clients: |
| 2044 |
c_addrs = [addr] if addr else list(clients.keys()) |
| 2045 |
for c_addr in c_addrs: |
| 2046 |
client = clients.get(c_addr) |
| 2047 |
conn = self._client_sockets.get(c_addr) |
| 2048 |
if not client and not conn: |
| 2049 |
continue |
| 2050 |
component_ = client["component"] |
| 2051 |
if not component_: |
| 2052 |
# not a madvr component so ignore completely |
| 2053 |
continue |
| 2054 |
pid_host = ( |
| 2055 |
f"{client.get('processId', '?')}:" |
| 2056 |
f"{client.get('computerName', '')}" |
| 2057 |
) |
| 2058 |
formatted_client = f"[{component_} {pid_host}]" |
| 2059 |
if component_ != b"madTPG": |
| 2060 |
continue |
| 2061 |
if not client.get("confirmed"): |
| 2062 |
safe_print( |
| 2063 |
f"Ignoring unconfirmed madTPG client : {formatted_client}" |
| 2064 |
) |
| 2065 |
continue |
| 2066 |
safe_print( |
| 2067 |
f"Found madTPG, attempting StartTestPattern : {pid_host}" |
| 2068 |
) |
| 2069 |
if self._send(conn, "StartTestPattern"): |
| 2070 |
self._client_socket = conn |
| 2071 |
safe_print( |
| 2072 |
f"Sent StartTestPattern to MadTPG client : {pid_host}" |
| 2073 |
) |
| 2074 |
return True |
| 2075 |
sleep(0.001) |
| 2076 |
end = time() |
| 2077 |
return False |
| 2078 |
|
| 2079 |
def _parse(self, blob: bytes = b"") -> tuple: |
| 2080 |
"""Consume blob, return record + remaining blob. |
| 2081 |
|
| 2082 |
Args: |
| 2083 |
blob (bytes): The byte string to parse. |
| 2084 |
|
| 2085 |
Returns: |
| 2086 |
tuple: A tuple containing the parsed record and the remaining blob. |
| 2087 |
""" |
| 2088 |
if len(blob) < 12: |
| 2089 |
return None, blob |
| 2090 |
self._validate_crc(blob) |
| 2091 |
datalen = struct.unpack("<i", blob[4:8])[0] |
| 2092 |
if len(blob) < datalen + 12: |
| 2093 |
return None, blob |
| 2094 |
record = { |
| 2095 |
"magic": blob[0:4], |
| 2096 |
"len": struct.unpack("<i", blob[4:8])[0], |
| 2097 |
"crc": struct.unpack("<i", blob[8:12])[0], |
| 2098 |
"processId": struct.unpack("<i", blob[12:16])[0], |
| 2099 |
"module": struct.unpack("<q", blob[16:24])[0], |
| 2100 |
"commandNo": struct.unpack("<i", blob[24:28])[0], |
| 2101 |
"sizeOfComponent": struct.unpack("<i", blob[28:32])[0], |
| 2102 |
} |
| 2103 |
a = 32 |
| 2104 |
b = a + record["sizeOfComponent"] |
| 2105 |
self._validate_component_size(blob, a, b) |
| 2106 |
record["component"] = blob[a:b] |
| 2107 |
a = b + 8 |
| 2108 |
self._validate_instance_size(blob, a, b) |
| 2109 |
record["instance"] = struct.unpack("<q", blob[b:a])[0] |
| 2110 |
b = a + 4 |
| 2111 |
self._validate_size_of_command(blob, a, b) |
| 2112 |
record["sizeOfCommand"] = struct.unpack("<i", blob[a:b])[0] |
| 2113 |
a = b + record["sizeOfCommand"] |
| 2114 |
self._validate_command_size(blob, a, b) |
| 2115 |
record["command"] = command = blob[b:a].decode() |
| 2116 |
b = a + 4 |
| 2117 |
self._validate_param_sizes(blob, a, b) |
| 2118 |
record["sizeOfParams"] = struct.unpack("<i", blob[a:b])[0] |
| 2119 |
a = b + record["sizeOfParams"] |
| 2120 |
self._validate_packet_params(blob, record, a, b) |
| 2121 |
params = blob[b:a] |
| 2122 |
if self.debug > 1: |
| 2123 |
record["rawParams"] = params |
| 2124 |
if command == "hello": |
| 2125 |
params = self._add_version_info_to_params(params) |
| 2126 |
elif command == "reply": |
| 2127 |
params = self._process_command_reply(record, params) |
| 2128 |
record["params"] = params |
| 2129 |
if self.debug: |
| 2130 |
self._log_record_info(record) |
| 2131 |
blob = blob[a:] |
| 2132 |
return record, blob |
| 2133 |
|
| 2134 |
def _validate_crc(self, blob: bytes) -> None: |
| 2135 |
"""Validate CRC of the madVR packet. |
| 2136 |
|
| 2137 |
Args: |
| 2138 |
blob (bytes): The byte string to validate. |
| 2139 |
|
| 2140 |
Raises: |
| 2141 |
ValueError: If the CRC check fails. |
| 2142 |
""" |
| 2143 |
crc = struct.unpack("<I", blob[8:12])[0] |
| 2144 |
# Check CRC |
| 2145 |
check = crc32(blob[:8]) & 0xFFFFFFFF |
| 2146 |
if check != crc: |
| 2147 |
raise ValueError( |
| 2148 |
"MadTPG_Net: Invalid madVR packet: CRC check " |
| 2149 |
f"failed: Expected {crc}, got {check}" |
| 2150 |
) |
| 2151 |
|
| 2152 |
def _validate_component_size(self, blob: bytes, a: int, b: int) -> None: |
| 2153 |
"""Validate component size. |
| 2154 |
|
| 2155 |
Args: |
| 2156 |
blob (bytes): The byte string to validate. |
| 2157 |
a (int): The end index of the component in the blob. |
| 2158 |
b (int): The start index of the component in the blob. |
| 2159 |
|
| 2160 |
Raises: |
| 2161 |
ValueError: If the component size is corrupt or does not match the |
| 2162 |
expected length. |
| 2163 |
""" |
| 2164 |
if b > len(blob): |
| 2165 |
raise ValueError( |
| 2166 |
"Corrupt madVR packet: Expected component " |
| 2167 |
f"len {b - a}, got {len(blob[a:b])}" |
| 2168 |
) |
| 2169 |
|
| 2170 |
def _validate_instance_size(self, blob: bytes, a: int, b: int) -> None: |
| 2171 |
"""Validate instance size. |
| 2172 |
|
| 2173 |
Args: |
| 2174 |
blob (bytes): The byte string to validate. |
| 2175 |
a (int): The end index of the instance in the blob. |
| 2176 |
b (int): The start index of the instance in the blob. |
| 2177 |
|
| 2178 |
Raises: |
| 2179 |
ValueError: If the instance size is corrupt or does not match the |
| 2180 |
expected length. |
| 2181 |
""" |
| 2182 |
if a > len(blob): |
| 2183 |
raise ValueError( |
| 2184 |
"Corrupt madVR packet: Expected instance " |
| 2185 |
f"len {a - b}, got {len(blob[b:a])}" |
| 2186 |
) |
| 2187 |
|
| 2188 |
def _validate_size_of_command(self, blob: bytes, a: int, b: int) -> None: |
| 2189 |
"""Validate size of command. |
| 2190 |
|
| 2191 |
Args: |
| 2192 |
blob (bytes): The byte string to validate. |
| 2193 |
a (int): The end index of the command size in the blob. |
| 2194 |
b (int): The start index of the command size in the blob. |
| 2195 |
|
| 2196 |
Raises: |
| 2197 |
ValueError: If the size of the command is corrupt or does not match |
| 2198 |
the expected length. |
| 2199 |
""" |
| 2200 |
if b > len(blob): |
| 2201 |
raise ValueError( |
| 2202 |
"Corrupt madVR packet: Expected sizeOfCommand " |
| 2203 |
f"len {b - a}, got {len(blob[a:b])}" |
| 2204 |
) |
| 2205 |
|
| 2206 |
def _validate_command_size(self, blob: bytes, a: int, b: int) -> None: |
| 2207 |
"""Validate command size. |
| 2208 |
|
| 2209 |
Args: |
| 2210 |
blob (bytes): The byte string to validate. |
| 2211 |
a (int): The end index of the command in the blob. |
| 2212 |
b (int): The start index of the command in the blob. |
| 2213 |
|
| 2214 |
Raises: |
| 2215 |
ValueError: If the command size is corrupt or does not match the |
| 2216 |
expected length. |
| 2217 |
""" |
| 2218 |
if a > len(blob): |
| 2219 |
raise ValueError( |
| 2220 |
"Corrupt madVR packet: Expected command " |
| 2221 |
f"len {a - b}, got {len(blob[b:a])}" |
| 2222 |
) |
| 2223 |
|
| 2224 |
def _validate_param_sizes(self, blob: bytes, a: int, b: int) -> None: |
| 2225 |
"""Validate parameter sizes. |
| 2226 |
|
| 2227 |
Args: |
| 2228 |
blob (bytes): The byte string to validate. |
| 2229 |
a (int): The end index of the parameters in the blob. |
| 2230 |
b (int): The start index of the parameters in the blob. |
| 2231 |
|
| 2232 |
Raises: |
| 2233 |
ValueError: If the parameter sizes are corrupt or do not match the |
| 2234 |
expected length. |
| 2235 |
""" |
| 2236 |
if b > len(blob): |
| 2237 |
raise ValueError( |
| 2238 |
"Corrupt madVR packet: Expected sizeOfParams " |
| 2239 |
f"len {b - a}, got {len(blob[a:b])}" |
| 2240 |
) |
| 2241 |
|
| 2242 |
def _validate_packet_params( |
| 2243 |
self, blob: bytes, record: dict, a: int, b: int |
| 2244 |
) -> None: |
| 2245 |
"""Validate packet parameters. |
| 2246 |
|
| 2247 |
Args: |
| 2248 |
blob (bytes): The byte string to validate. |
| 2249 |
record (dict): The parsed record from the madVR packet. |
| 2250 |
a (int): The end index of the parameters in the blob. |
| 2251 |
b (int): The start index of the parameters in the blob. |
| 2252 |
|
| 2253 |
Raises: |
| 2254 |
ValueError: If the parameters are corrupt or do not match the |
| 2255 |
expected length. |
| 2256 |
""" |
| 2257 |
if a > record["len"] + 12: |
| 2258 |
raise ValueError( |
| 2259 |
"Corrupt madVR packet: Expected params " |
| 2260 |
f"len {a - b}, got {len(blob[b:a])}" |
| 2261 |
) |
| 2262 |
|
| 2263 |
def _add_version_info_to_params(self, params: bytes) -> dict: |
| 2264 |
"""Add madVR version info to 'hello' packet parameters. |
| 2265 |
|
| 2266 |
Args: |
| 2267 |
params (bytes): The raw parameters from the 'hello' packet. |
| 2268 |
|
| 2269 |
Returns: |
| 2270 |
dict: A dictionary containing the parsed parameters including |
| 2271 |
madVR version information. |
| 2272 |
""" |
| 2273 |
io = StringIO( |
| 2274 |
"[Default]\n" + "\n".join(params.decode("UTF-16-LE").strip().split("\t")) |
| 2275 |
) |
| 2276 |
cfg = CaseSensitiveConfigParser() |
| 2277 |
# cfg.readfp(io) |
| 2278 |
cfg.read_file(io) |
| 2279 |
params = dict(cfg.items("Default")) |
| 2280 |
# Convert version strings to tuples with integers |
| 2281 |
for param in ("mvr", "exe"): |
| 2282 |
param += "Version" |
| 2283 |
if param in params: |
| 2284 |
values = params[param].split(".") |
| 2285 |
for i, value in enumerate(values): |
| 2286 |
with contextlib.suppress(ValueError): |
| 2287 |
values[i] = int(value) |
| 2288 |
params[param] = tuple(values) |
| 2289 |
return params |
| 2290 |
|
| 2291 |
def _process_command_reply( |
| 2292 |
self, |
| 2293 |
record: dict, |
| 2294 |
params: bytes, |
| 2295 |
) -> bool | int | tuple | ctypes.Array: |
| 2296 |
"""Process command reply parameters. |
| 2297 |
|
| 2298 |
Args: |
| 2299 |
record (dict): The parsed record from the madVR packet. |
| 2300 |
params (bytes): The raw parameters from the madVR packet. |
| 2301 |
|
| 2302 |
Returns: |
| 2303 |
bool | int | tuple | ctypes.Array: The processed parameters based |
| 2304 |
on the command that was replied to, or False if the parameters |
| 2305 |
could not be processed. |
| 2306 |
""" |
| 2307 |
commandno = record["commandNo"] |
| 2308 |
replied_command = self._commands.get(commandno) |
| 2309 |
if replied_command: |
| 2310 |
self._commands.pop(commandno) |
| 2311 |
# XXX: madHcNetXX.dll exports madVR_GetBlackAndWhiteLevel, |
| 2312 |
# but the equivalent madVR network protocol command is |
| 2313 |
# GetBlackWhiteLevel (without the "And")! |
| 2314 |
if replied_command == "GetBlackWhiteLevel": |
| 2315 |
params = struct.unpack("<ii", params) if len(params) == 8 else False |
| 2316 |
elif replied_command == "GetDeviceGammaRamp": |
| 2317 |
# Convert to ushort_Array_256_Array_3 |
| 2318 |
ramp = ((ctypes.c_ushort * 256) * 3)() |
| 2319 |
if len(params) == 1536: |
| 2320 |
for j in range(3): |
| 2321 |
for i in range(256): |
| 2322 |
ramp[j][i] = round(struct.unpack("<H", params[:2])[0]) |
| 2323 |
params = params[2:] |
| 2324 |
params = ramp |
| 2325 |
else: |
| 2326 |
params = False |
| 2327 |
elif replied_command == "GetPatternConfig": |
| 2328 |
params = struct.unpack("<iiii", params) if len(params) == 16 else False |
| 2329 |
elif replied_command in ("GetSelected3dlut",): |
| 2330 |
params = ( |
| 2331 |
struct.unpack("<i", params[0:4])[0] if len(params) == 4 else False |
| 2332 |
) |
| 2333 |
elif self.debug: |
| 2334 |
# Got a reply for a command we never issued? |
| 2335 |
safe_print(f"MadTPG_Net: Got reply {commandno} for unknown command") |
| 2336 |
return params |
| 2337 |
|
| 2338 |
def _log_record_info(self, record: dict) -> None: |
| 2339 |
"""Log madVR packet record information. |
| 2340 |
|
| 2341 |
Args: |
| 2342 |
record (dict): The parsed record from the madVR packet. |
| 2343 |
""" |
| 2344 |
with _LOCK: |
| 2345 |
safe_print( |
| 2346 |
record["processId"], |
| 2347 |
record["module"], |
| 2348 |
record["commandNo"], |
| 2349 |
record["component"], |
| 2350 |
record["instance"], |
| 2351 |
record["command"], |
| 2352 |
) |
| 2353 |
for key in record: |
| 2354 |
value = record[key] |
| 2355 |
if key != "params" and self.debug <= 2: |
| 2356 |
continue |
| 2357 |
if isinstance(value, dict): |
| 2358 |
safe_print(f" {key}:") |
| 2359 |
for subkey in value: |
| 2360 |
subvalue = value[subkey] |
| 2361 |
if self.debug < 2 and subkey != "exeFile": |
| 2362 |
continue |
| 2363 |
safe_print(f" {subkey.ljust(16)} = {trunc(subvalue, 56)}") |
| 2364 |
elif self.debug > 1: |
| 2365 |
safe_print(f" {key.ljust(16)} = {trunc(value, 58)}") |
| 2366 |
|
| 2367 |
def _assemble( |
| 2368 |
self, |
| 2369 |
conn: socket.socket, |
| 2370 |
commandno: int = 1, |
| 2371 |
command: str = "", |
| 2372 |
params: bytes | str = "", |
| 2373 |
component: bytes = b"madTPG", |
| 2374 |
) -> bytes: |
| 2375 |
"""Assemble packet. |
| 2376 |
|
| 2377 |
Args: |
| 2378 |
conn (socket.socket): The connection socket to send the command |
| 2379 |
through. |
| 2380 |
commandno (int): The command number, defaults to 1. |
| 2381 |
command (str, optional): The command to send, e.g. "SetOsdText", |
| 2382 |
"ShowRGB", etc. |
| 2383 |
params (bytes | str): Parameters for the command, can be a string |
| 2384 |
or bytes. |
| 2385 |
component (bytes): The component name, defaults to b"madTPG". |
| 2386 |
|
| 2387 |
Raises: |
| 2388 |
OSError: If assembling the command fails. |
| 2389 |
|
| 2390 |
Returns: |
| 2391 |
bytes: The assembled packet ready to be sent. |
| 2392 |
""" |
| 2393 |
magic = b"mad." |
| 2394 |
data = struct.pack("<i", os.getpid()) # processId : 4 |
| 2395 |
data += struct.pack("<q", id(sys.modules[__name__])) # module/DLL handle : 8 |
| 2396 |
data += struct.pack("<i", commandno) # 4 |
| 2397 |
data += struct.pack("<i", len(component)) # sizeOfComponent : 4 |
| 2398 |
data += component |
| 2399 |
if component == b"madTPG": |
| 2400 |
instance = self.clients.get(conn.getpeername(), {}).get("instance", 0) |
| 2401 |
else: |
| 2402 |
instance = 0 |
| 2403 |
data += struct.pack("<q", instance) # instance : 8 |
| 2404 |
data += struct.pack("<i", len(command)) # sizeOfCommand : 4 |
| 2405 |
data += command.encode() |
| 2406 |
data += struct.pack("<i", len(params)) # sizeOfParams : 4 |
| 2407 |
data += params if isinstance(params, bytes) else params.encode("UTF-16-LE") |
| 2408 |
datalen = len(data) |
| 2409 |
packet = magic + struct.pack("<i", datalen) # 4 + 4 |
| 2410 |
packet += struct.pack("<I", crc32(packet) & 0xFFFFFFFF) # 4 |
| 2411 |
packet += data |
| 2412 |
if self.debug > 1: |
| 2413 |
with _LOCK: |
| 2414 |
safe_print("MadTPG_Net: Assembled madVR packet:") |
| 2415 |
self._parse(packet) |
| 2416 |
return packet |
| 2417 |
|
| 2418 |
def _send( |
| 2419 |
self, |
| 2420 |
conn: socket.socket, |
| 2421 |
command: str = "", |
| 2422 |
params: bytes | str = "", |
| 2423 |
component: bytes = b"madTPG", |
| 2424 |
) -> bool: |
| 2425 |
"""Send madTPG command and return reply. |
| 2426 |
|
| 2427 |
Args: |
| 2428 |
conn (socket.socket): The connection socket to send the command |
| 2429 |
through. |
| 2430 |
command (str, optional): The command to send, e.g. "SetOsdText", |
| 2431 |
"ShowRGB", etc. |
| 2432 |
params (bytes | str): Parameters for the command, can be a string |
| 2433 |
or bytes. |
| 2434 |
component (bytes): The component name, defaults to b"madTPG". |
| 2435 |
|
| 2436 |
Raises: |
| 2437 |
OSError: If sending the command fails. |
| 2438 |
|
| 2439 |
Returns: |
| 2440 |
bool: True if the command was sent successfully, False otherwise. |
| 2441 |
""" |
| 2442 |
if not conn: |
| 2443 |
return False |
| 2444 |
self._commandno += 1 |
| 2445 |
commandno = self._commandno |
| 2446 |
try: |
| 2447 |
packet = self._assemble(conn, commandno, command, params, component) |
| 2448 |
bytes_total = len(packet) |
| 2449 |
if self.debug: |
| 2450 |
addr, port = conn.getpeername()[:2] |
| 2451 |
safe_print( |
| 2452 |
f"MadTPG_Net: Sending command {commandno} {command!r} to " |
| 2453 |
f"{addr}:{port}" |
| 2454 |
) |
| 2455 |
bytes_sent_total = bytes_sent = 0 |
| 2456 |
while packet: |
| 2457 |
try: |
| 2458 |
bytes_sent = conn.send(packet) |
| 2459 |
except OSError as exception: |
| 2460 |
if exception.errno in (errno.EAGAIN, errno.EWOULDBLOCK): |
| 2461 |
# Resource temporarily unavailable |
| 2462 |
sleep(0.001) |
| 2463 |
continue |
| 2464 |
raise OSError from exception |
| 2465 |
if bytes_sent == 0: |
| 2466 |
raise OSError(errno.ENOLINK, "Link has been severed") |
| 2467 |
packet = packet[bytes_sent:] |
| 2468 |
bytes_sent_total += bytes_sent |
| 2469 |
if self.debug and bytes_sent != bytes_total: |
| 2470 |
safe_print( |
| 2471 |
f"MadTPG_Net: Command {commandno} {command!r} to {addr}:{port}," |
| 2472 |
f" bytes sent: {bytes_sent_total} of {bytes_total} " |
| 2473 |
f"({bytes_sent_total / float(bytes_total):.2%})" |
| 2474 |
) |
| 2475 |
except OSError as exception: |
| 2476 |
safe_print( |
| 2477 |
f"MadTPG_Net: Sending command {commandno} {command!r} failed", |
| 2478 |
exception, |
| 2479 |
) |
| 2480 |
return False |
| 2481 |
if command not in ( |
| 2482 |
"confirm", |
| 2483 |
"hello", |
| 2484 |
"reply", |
| 2485 |
"bye", |
| 2486 |
) and not command.startswith("store:"): |
| 2487 |
self._commands[commandno] = command |
| 2488 |
# Get reply |
| 2489 |
if self.debug: |
| 2490 |
safe_print( |
| 2491 |
f"MadTPG_Net: Expecting reply for command {commandno} {command!r}" |
| 2492 |
) |
| 2493 |
# Should be enough even for slow wireless |
| 2494 |
timeout = 300 if command in ("Load3dlut", "LoadHdr3dlut") else 3 |
| 2495 |
return self._expect(conn, commandno, "reply", timeout=timeout) |
| 2496 |
return True |
| 2497 |
|
| 2498 |
@property |
| 2499 |
def uri(self) -> str: |
| 2500 |
"""Return the URI of the connected madTPG instance. |
| 2501 |
|
| 2502 |
Returns: |
| 2503 |
str: The URI in the format "IP:PORT". |
| 2504 |
""" |
| 2505 |
try: |
| 2506 |
addr = self._client_socket and self._client_socket.getpeername()[:2] |
| 2507 |
except OSError as exception: |
| 2508 |
safe_print("MadTPG_Net:", exception) |
| 2509 |
addr = None |
| 2510 |
return "{}:{}".format(*addr) if addr else ("0.0.0.0", 0) # noqa: S104 |
| 2511 |
|
| 2512 |
|
| 2513 |
class MadTPGNetSender: |
| 2514 |
"""madTPG network command sender. |
| 2515 |
|
| 2516 |
Args: |
| 2517 |
madtpg (MadTPGNet): Instance of MadTPGNet to send commands to. |
| 2518 |
conn (socket.socket): Connection socket to send commands through. |
| 2519 |
command (str): The command to send, e.g. "SetOsdText", "ShowRGB", etc. |
| 2520 |
""" |
| 2521 |
|
| 2522 |
def __init__(self, madtpg: MadTPGNet, conn: socket.socket, command: str) -> None: |
| 2523 |
self.madtpg = madtpg |
| 2524 |
self._conn = conn |
| 2525 |
if command == "Quit": |
| 2526 |
command = "Exit" |
| 2527 |
self.command = command |
| 2528 |
|
| 2529 |
def __call__(self, *args, **kwargs) -> bool | str | tuple: |
| 2530 |
"""Send command to madTPG instance and return reply. |
| 2531 |
|
| 2532 |
Args: |
| 2533 |
*args: Positional arguments for the command. |
| 2534 |
**kwargs: Keyword arguments for the command. |
| 2535 |
|
| 2536 |
Raises: |
| 2537 |
TypeError: If the command requires more arguments than provided. |
| 2538 |
|
| 2539 |
Returns: |
| 2540 |
bool | str | tuple: The result of the command execution. |
| 2541 |
""" |
| 2542 |
if self.command in ("Load3dlutFile", "LoadHdr3dlutFile"): |
| 2543 |
lut = H3DLUT(args[0]) |
| 2544 |
lutdata = lut.LUTDATA |
| 2545 |
self.command = self.command[:-4] # Strip 'File' from command name |
| 2546 |
elif self.command in ("Load3dlutFromArray256", "LoadHdr3dlutFromArray256"): |
| 2547 |
lutdata = args[0] |
| 2548 |
self.command = self.command[:-12] # Strip 'File' from command name |
| 2549 |
|
| 2550 |
if self.command in ("Load3dlut", "LoadHdr3dlut"): |
| 2551 |
params = struct.pack("<i", args[1]) # Save to settings? |
| 2552 |
params += struct.pack("<i", args[2]) # 3D LUT slot |
| 2553 |
params += lutdata |
| 2554 |
if self.command == "LoadHdr3dlut": |
| 2555 |
params += struct.pack("<i", args[3]) # HDR to SDR? |
| 2556 |
elif self.command == "SetDeviceGammaRamp": |
| 2557 |
self._process_set_device_gamma_ramp_param(args) |
| 2558 |
elif self.command in ( |
| 2559 |
"SetDisableOsdButton", |
| 2560 |
"SetStayOnTopButton", |
| 2561 |
"SetUseFullscreenButton", |
| 2562 |
): |
| 2563 |
params = "+" if args[0] else "-" |
| 2564 |
elif self.command == "SetOsdText": |
| 2565 |
params = args[0].encode("UTF-16-LE") |
| 2566 |
elif self.command in ("SetPatternConfig", "SetProgressBarPos"): |
| 2567 |
params = "|".join(str(v) for v in args) |
| 2568 |
elif self.command == "ShowRGB": |
| 2569 |
params = self._process_show_rgb_param(args, kwargs) |
| 2570 |
else: |
| 2571 |
params = str(*args) |
| 2572 |
|
| 2573 |
return self.madtpg._send( |
| 2574 |
self._conn, |
| 2575 |
self.command, |
| 2576 |
params if isinstance(params, bytes) else params.encode(), |
| 2577 |
) |
| 2578 |
|
| 2579 |
def _process_set_device_gamma_ramp_param(self, args: list | tuple) -> None: |
| 2580 |
"""Process SetDeviceGammaRamp parameters. |
| 2581 |
|
| 2582 |
Args: |
| 2583 |
args (list | tuple): Positional arguments for the |
| 2584 |
SetDeviceGammaRamp command. |
| 2585 |
""" |
| 2586 |
params = b"" |
| 2587 |
for j in range(3): |
| 2588 |
for i in range(256): |
| 2589 |
# Clear device gamma ramp if args[0] is None |
| 2590 |
# else convert ushort_Array_256_Array_3 to string |
| 2591 |
v = i * 257 if args[0] is None else args[0][j][i] |
| 2592 |
params += struct.pack("<H", v) |
| 2593 |
|
| 2594 |
def _process_show_rgb_param(self, args: list | tuple, kwargs: dict) -> str: |
| 2595 |
"""Process ShowRGB parameters and return formatted string. |
| 2596 |
|
| 2597 |
Args: |
| 2598 |
args (list | tuple): Positional arguments for the ShowRGB command. |
| 2599 |
kwargs (dict): Keyword arguments for the ShowRGB command. |
| 2600 |
|
| 2601 |
Raises: |
| 2602 |
TypeError: If required RGB values are not provided. |
| 2603 |
|
| 2604 |
Returns: |
| 2605 |
str: Formatted string of RGB values for the ShowRGB command. |
| 2606 |
""" |
| 2607 |
r = kwargs.get("r") |
| 2608 |
g = kwargs.get("g") |
| 2609 |
b = kwargs.get("b") |
| 2610 |
bgr = kwargs.get("bgr") |
| 2611 |
bgg = kwargs.get("bgg") |
| 2612 |
bgb = kwargs.get("bgb") |
| 2613 |
r, g, b = args[:3] if len(args) >= 3 else (r, g, b) |
| 2614 |
bgr = args[3] if len(args) > 3 else bgr |
| 2615 |
bgg = args[4] if len(args) > 4 else bgg |
| 2616 |
bgb = args[5] if len(args) > 5 else bgb |
| 2617 |
rgb = r, g, b |
| 2618 |
if None not in (bgr, bgg, bgb): |
| 2619 |
self.command += "Ex" |
| 2620 |
rgb += (bgr, bgg, bgb) |
| 2621 |
if None in (r, g, b): |
| 2622 |
raise TypeError( |
| 2623 |
"show_rgb() takes at least 4 arguments " |
| 2624 |
f"({len([v for v in rgb if v])} given)" |
| 2625 |
) |
| 2626 |
return "|".join(str(v) for v in rgb) |
| 2627 |
|
| 2628 |
|
| 2629 |
if __name__ == "__main__": |
| 2630 |
from DisplayCAL import config |
| 2631 |
|
| 2632 |
config.initcfg() |
| 2633 |
lang.init() |
| 2634 |
if sys.platform == "win32": |
| 2635 |
madtpg = MadTPG() |
| 2636 |
else: |
| 2637 |
madtpg = MadTPGNet() |
| 2638 |
try: |
| 2639 |
if madtpg.connect(method3=CM_StartLocalInstance, timeout3=10000): |
| 2640 |
res = madtpg.set_osd_text("Hello there") |
| 2641 |
print(f"RESULT set_osd_text : {res}") |
| 2642 |
# sleep(5) |
| 2643 |
res = madtpg.show_rgb(1, 0, 0) |
| 2644 |
print(f"RESULT show_rgb : {res}") |
| 2645 |
res = madtpg.get_black_and_white_level() |
| 2646 |
print(f"RESULT bw level : {res}") |
| 2647 |
res = madtpg.get_pattern_config() |
| 2648 |
print(f"RESULT pattern_config : {res}") |
| 2649 |
res = madtpg.get_version() |
| 2650 |
print(f"RESULT version : {res}") |
| 2651 |
res = madtpg.get_device_gamma_ramp() |
| 2652 |
print(f"RESULT gamma_ramp : {res}") |
| 2653 |
res = madtpg.enable_3dlut() |
| 2654 |
print(f"RESULT enable_3dlut : {res}") |
| 2655 |
res = madtpg.get_selected_3dlut() |
| 2656 |
print(f"RESULT selected 3dlut : {res}") |
| 2657 |
res = madtpg.disable_3dlut() |
| 2658 |
print(f"RESULT disable_3dlut : {res}") |
| 2659 |
res = madtpg.is_stay_on_top_button_pressed() |
| 2660 |
print(f"RESULT is_stay_on_top_button_pressed : {res}") |
| 2661 |
res = madtpg.is_use_fullscreen_button_pressed() |
| 2662 |
print(f"RESULT is_use_fullscreen_button_pressed : {res}") |
| 2663 |
res = madtpg.is_disable_osd_button_pressed() |
| 2664 |
print(f"RESULT is_disable_osd_button_pressed : {res}") |
| 2665 |
res = madtpg.set_stay_on_top_button(False) |
| 2666 |
print(f"RESULT set_stay_on_top_button : {res}") |
| 2667 |
res = madtpg.set_use_fullscreen_button(False) |
| 2668 |
print(f"RESULT set_use_fullscreen_button : {res}") |
| 2669 |
res = madtpg.set_disable_osd_button(False) |
| 2670 |
print(f"RESULT set_disable_osd_button : {res}") |
| 2671 |
res = madtpg.show_progress_bar(10) |
| 2672 |
print(f"RESULT show_progress_bar : {res}") |
| 2673 |
res = madtpg.set_progress_bar_pos(5, 15) |
| 2674 |
print(f"RESULT set_progress_bar_pos : {res}") |
| 2675 |
res = madtpg.enter_fullscreen() |
| 2676 |
print(f"RESULT enter_fullscreen : {res}") |
| 2677 |
res = madtpg.is_fullscreen() |
| 2678 |
print(f"RESULT is_fullscreen : {res}") |
| 2679 |
res = madtpg.leave_fullscreen() |
| 2680 |
print(f"RESULT leave_fullscreen : {res}") |
| 2681 |
res = madtpg.set_device_gamma_ramp(None) |
| 2682 |
print(f"RESULT set_device_gamma_ramp : {res}") |
| 2683 |
res = madtpg.disconnect() |
| 2684 |
print(f"RESULT disconnect : {res}") |
| 2685 |
res = madtpg.quit() |
| 2686 |
print(f"RESULT quit : {res}") |
| 2687 |
finally: |
| 2688 |
madtpg.shutdown() |