| 1 |
"""Utilities for working with Argyll CMS CGATS files and calibration data. |
| 2 |
|
| 3 |
It includes functions for manipulating CGATS data, extracting calibration |
| 4 |
information, and creating or modifying ICC profiles with embedded calibration |
| 5 |
data. |
| 6 |
""" |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
# import decimal |
| 11 |
# Decimal = decimal.Decimal |
| 12 |
import contextlib |
| 13 |
import decimal |
| 14 |
import os |
| 15 |
import traceback |
| 16 |
from decimal import Decimal |
| 17 |
from io import BytesIO |
| 18 |
from time import strftime |
| 19 |
|
| 20 |
from DisplayCAL import colormath |
| 21 |
from DisplayCAL import localization as lang |
| 22 |
from DisplayCAL.cgats import ( |
| 23 |
CGATS, |
| 24 |
CGATSError, |
| 25 |
CGATSInvalidError, |
| 26 |
CGATSInvalidOperationError, |
| 27 |
CGATSKeyError, |
| 28 |
CGATSTypeError, |
| 29 |
CGATSValueError, |
| 30 |
) |
| 31 |
from DisplayCAL.debughelpers import Error |
| 32 |
from DisplayCAL.icc_profile import ( |
| 33 |
ICCProfile, |
| 34 |
ICCProfileInvalidError, |
| 35 |
Text, |
| 36 |
TextDescriptionType, |
| 37 |
VideoCardGammaTableType, |
| 38 |
VideoCardGammaType, |
| 39 |
WcsProfilesTagType, |
| 40 |
) |
| 41 |
from DisplayCAL.options import DEBUG |
| 42 |
|
| 43 |
CALS = {} |
| 44 |
|
| 45 |
|
| 46 |
def quote_nonoption_args(args: list[str]) -> list[bytes]: |
| 47 |
"""Put quotes around all arguments which are not options. |
| 48 |
|
| 49 |
(ie. which do not start with a hyphen '-') |
| 50 |
|
| 51 |
Args: |
| 52 |
args (list[str]): A list of arguments to be quoted. |
| 53 |
|
| 54 |
Returns: |
| 55 |
list[bytes]: A list of quoted arguments, where each argument that does not |
| 56 |
start with a hyphen is wrapped in quotes. |
| 57 |
""" |
| 58 |
args = list(args) |
| 59 |
for i, arg in enumerate(args): |
| 60 |
# first convert everything to bytes |
| 61 |
if not isinstance(arg, bytes): |
| 62 |
arg = bytes(str(arg), "utf-8") |
| 63 |
args[i] = b'"%s"' % arg if arg[:1] != b"-" else arg |
| 64 |
return args |
| 65 |
|
| 66 |
|
| 67 |
def add_dispcal_options_to_cal(cal: str | CGATS, options_dispcal: list[str]) -> CGATS: |
| 68 |
"""Add dispcal options to cal. |
| 69 |
|
| 70 |
Args: |
| 71 |
cal (str | CGATS): The input CAL file or CGATS instance. |
| 72 |
options_dispcal (list[str]): List of dispcal options to add. |
| 73 |
|
| 74 |
Returns: |
| 75 |
CGATS: The modified CGATS instance with added options. |
| 76 |
""" |
| 77 |
# Add dispcal options to cal |
| 78 |
options_dispcal = quote_nonoption_args(options_dispcal) |
| 79 |
try: |
| 80 |
cgats = CGATS(cal) |
| 81 |
cgats[0].add_section("ARGYLL_DISPCAL_ARGS", b" ".join(options_dispcal)) |
| 82 |
return cgats |
| 83 |
except Exception: |
| 84 |
print(traceback.format_exc()) |
| 85 |
|
| 86 |
|
| 87 |
def add_options_to_ti3( |
| 88 |
ti3: str | CGATS, |
| 89 |
options_dispcal: None | list[str] = None, |
| 90 |
options_colprof: None | list[str] = None, |
| 91 |
) -> CGATS: |
| 92 |
"""Add dispcal and colprof options to ti3. |
| 93 |
|
| 94 |
Args: |
| 95 |
ti3 (str or CGATS): The input TI3 file or CGATS instance. |
| 96 |
options_dispcal (list): List of dispcal options to add. |
| 97 |
options_colprof (list): List of colprof options to add. |
| 98 |
|
| 99 |
Returns: |
| 100 |
CGATS: The modified CGATS instance with added options. |
| 101 |
""" |
| 102 |
# Add dispcal and colprof options to ti3 |
| 103 |
try: |
| 104 |
cgats = CGATS(ti3) |
| 105 |
if options_colprof: |
| 106 |
options_colprof = quote_nonoption_args(options_colprof) |
| 107 |
cgats[0].add_section( |
| 108 |
"ARGYLL_COLPROF_ARGS", |
| 109 |
b" ".join(options_colprof), |
| 110 |
) |
| 111 |
|
| 112 |
if options_dispcal and 1 in cgats: |
| 113 |
options_dispcal = quote_nonoption_args(options_dispcal) |
| 114 |
cgats[1].add_section( |
| 115 |
"ARGYLL_DISPCAL_ARGS", |
| 116 |
b" ".join(options_dispcal), |
| 117 |
) |
| 118 |
return cgats |
| 119 |
except BaseException: |
| 120 |
print(traceback.format_exc()) |
| 121 |
|
| 122 |
|
| 123 |
def cal_to_fake_profile(cal: str | CGATS) -> None | ICCProfile: |
| 124 |
"""Create and return a 'fake' ICCProfile with just a vcgt tag. |
| 125 |
|
| 126 |
cal must refer to a valid Argyll CAL file and can be a CGATS instance |
| 127 |
or a filename. |
| 128 |
|
| 129 |
Args: |
| 130 |
cal (str | CGATS): The input CAL file or CGATS instance. |
| 131 |
|
| 132 |
Returns: |
| 133 |
None | ICCProfile: Returns an ICCProfile instance with a vcgt tag |
| 134 |
containing the calibration data, or None if the input is invalid |
| 135 |
or required fields are missing. |
| 136 |
""" |
| 137 |
if not (cal := validate_cgats(cal)) or not (vcgt := cal_to_vcgt(cal)): |
| 138 |
return None |
| 139 |
profile = ICCProfile() |
| 140 |
profile.filename = cal.filename |
| 141 |
profile._data = b"\0" * 128 |
| 142 |
profile._tags.desc = TextDescriptionType(b"", "desc") |
| 143 |
profile._tags.desc.ASCII = str(os.path.basename(cal.filename)).encode( |
| 144 |
"ascii", "asciize" |
| 145 |
) |
| 146 |
profile._tags.desc.Unicode = str(os.path.basename(cal.filename)) |
| 147 |
profile._tags.vcgt = vcgt |
| 148 |
profile.size = len(profile.data) |
| 149 |
profile.is_loaded = True |
| 150 |
return profile |
| 151 |
|
| 152 |
|
| 153 |
def cal_to_vcgt(cal: str | CGATS) -> None | VideoCardGammaTableType: |
| 154 |
"""Create a vcgt tag from calibration data. |
| 155 |
|
| 156 |
Args: |
| 157 |
cal (str | CGATS): The input CAL file or CGATS instance. It must refer |
| 158 |
to a valid Argyll CAL file or can be a CGATS instance or a |
| 159 |
filename. |
| 160 |
|
| 161 |
Returns: |
| 162 |
None | VideoCardGammaTableType: Returns a VideoCardGammaTableType |
| 163 |
instance containing the `vcgt` data. Returns None if the input is |
| 164 |
invalid or required fields are missing. |
| 165 |
""" |
| 166 |
if not (cal := validate_cgats(cal)): |
| 167 |
return None |
| 168 |
|
| 169 |
required_fields = ("RGB_I", "RGB_R", "RGB_G", "RGB_B") |
| 170 |
if data_format := cal.queryv1("DATA_FORMAT"): |
| 171 |
for field in required_fields: |
| 172 |
if field.encode("utf-8") not in list(data_format.values()): |
| 173 |
if DEBUG: |
| 174 |
print(f"[D] Missing required field: {field}") |
| 175 |
return None |
| 176 |
for field in list(data_format.values()): |
| 177 |
if field.decode("utf-8") not in required_fields: |
| 178 |
if DEBUG: |
| 179 |
print(f"[D] Unknown field: {field}") |
| 180 |
return None |
| 181 |
entries = cal.queryv(required_fields) |
| 182 |
if len(entries) < 1: |
| 183 |
if DEBUG: |
| 184 |
print(f"[D] No entries found in calibration {cal.filename}") |
| 185 |
return None |
| 186 |
vcgt = VideoCardGammaTableType(b"", "vcgt") |
| 187 |
vcgt.update( |
| 188 |
{ |
| 189 |
"channels": 3, |
| 190 |
"entryCount": len(entries), |
| 191 |
"entrySize": 2, |
| 192 |
"data": [[], [], []], |
| 193 |
} |
| 194 |
) |
| 195 |
for n in entries: |
| 196 |
for i in range(3): |
| 197 |
vcgt.data[i].append(entries[n][i + 1] * 65535.0) |
| 198 |
return vcgt |
| 199 |
|
| 200 |
|
| 201 |
def validate_cgats(cal: str | CGATS) -> CGATS: |
| 202 |
"""Validate and return a CGATS instance. |
| 203 |
|
| 204 |
Args: |
| 205 |
cal (str | CGATS): The input CAL file or CGATS instance. |
| 206 |
|
| 207 |
Returns: |
| 208 |
CGATS: A validated CGATS instance. |
| 209 |
""" |
| 210 |
if not isinstance(cal, CGATS): |
| 211 |
try: |
| 212 |
cal = CGATS(cal) |
| 213 |
except ( |
| 214 |
OSError, |
| 215 |
CGATSInvalidError, |
| 216 |
CGATSInvalidOperationError, |
| 217 |
CGATSKeyError, |
| 218 |
CGATSTypeError, |
| 219 |
CGATSValueError, |
| 220 |
) as exception: |
| 221 |
print(f"Warning - couldn't process CGATS file '{cal}': {exception}") |
| 222 |
return None |
| 223 |
return cal |
| 224 |
|
| 225 |
|
| 226 |
def can_update_cal(path: str) -> bool: |
| 227 |
"""Check if cal can be updated by checking for required fields. |
| 228 |
|
| 229 |
Args: |
| 230 |
path (str): The path to the CGATS file. |
| 231 |
|
| 232 |
Returns: |
| 233 |
bool: True if the CGATS file can be updated, False otherwise. |
| 234 |
""" |
| 235 |
try: |
| 236 |
calstat = os.stat(path) |
| 237 |
except Exception as exception: |
| 238 |
print(f"Warning - os.stat('{path}') failed: {exception}") |
| 239 |
return False |
| 240 |
if path not in CALS or CALS[path].mtime != calstat.st_mtime: |
| 241 |
try: |
| 242 |
cal = CGATS(path) |
| 243 |
except ( |
| 244 |
OSError, |
| 245 |
CGATSInvalidError, |
| 246 |
CGATSInvalidOperationError, |
| 247 |
CGATSKeyError, |
| 248 |
CGATSTypeError, |
| 249 |
CGATSValueError, |
| 250 |
) as exception: |
| 251 |
CALS.pop(path, None) |
| 252 |
print(f"Warning - couldn't process CGATS file '{path}': {exception}") |
| 253 |
else: |
| 254 |
if cal.queryv1("DEVICE_CLASS") == "DISPLAY" and None not in ( |
| 255 |
cal.queryv1("TARGET_WHITE_XYZ"), |
| 256 |
cal.queryv1("TARGET_GAMMA"), |
| 257 |
cal.queryv1("BLACK_POINT_CORRECTION"), |
| 258 |
cal.queryv1("QUALITY"), |
| 259 |
): |
| 260 |
CALS[path] = cal |
| 261 |
return path in CALS and CALS[path].mtime == calstat.st_mtime |
| 262 |
|
| 263 |
|
| 264 |
def extract_cal_from_profile( |
| 265 |
profile: ICCProfile, |
| 266 |
out_cal_path: None | str = None, |
| 267 |
raise_on_missing_cal: bool = True, |
| 268 |
prefer_cal: bool = False, |
| 269 |
) -> bool | CGATS: |
| 270 |
"""Extract calibration from 'targ' tag in profile or vcgt as fallback. |
| 271 |
|
| 272 |
Args: |
| 273 |
profile (ICCProfile): The ICCProfile to extract the data from. |
| 274 |
out_cal_path (str, optional): If provided, the extracted calibration |
| 275 |
data will be saved to this path as a CGATS file. |
| 276 |
raise_on_missing_cal (bool): If True, raises an error if no calibration |
| 277 |
data is found in the profile. If False, returns False instead. |
| 278 |
prefer_cal (bool): If True, prefers the calibration data from the |
| 279 |
'targ' tag over the 'vcgt' tag, if both are present. If False, |
| 280 |
prefers the 'vcgt' tag if it is nonlinear. |
| 281 |
|
| 282 |
Raises: |
| 283 |
Error: If the calibration extraction fails or if no calibration data |
| 284 |
is found and `raise_on_missing_cal` is True. |
| 285 |
|
| 286 |
Returns: |
| 287 |
bool | CGATS: Returns a CGATS instance containing the calibration data |
| 288 |
if successful, or False if no calibration data is found and |
| 289 |
`raise_on_missing_cal` is False. |
| 290 |
""" |
| 291 |
white = False |
| 292 |
|
| 293 |
# Check if calibration is included in TI3 |
| 294 |
targ = profile.tags.get("targ", profile.tags.get("CIED")) |
| 295 |
cal = None |
| 296 |
cgats_builder = None |
| 297 |
if isinstance(targ, Text) and (cal := extract_cal_from_ti3(targ)): |
| 298 |
check = cal |
| 299 |
cgats_builder = CGATS |
| 300 |
arg = cal |
| 301 |
|
| 302 |
if not cal: |
| 303 |
check, cgats_builder, arg = convert_cal_info_from_embedded_wcs_profile(profile) |
| 304 |
|
| 305 |
if check: |
| 306 |
try: |
| 307 |
cgats = cgats_builder(arg) |
| 308 |
except (OSError, CGATSError) as e: |
| 309 |
traceback.print_exc() |
| 310 |
raise Error(lang.getstr("cal_extraction_failed")) from e |
| 311 |
elif raise_on_missing_cal: |
| 312 |
raise Error(lang.getstr("profile.no_vcgt")) |
| 313 |
else: |
| 314 |
return False |
| 315 |
|
| 316 |
if ( |
| 317 |
not cal |
| 318 |
or prefer_cal |
| 319 |
or not isinstance(profile.tags.get("vcgt"), VideoCardGammaType) |
| 320 |
): |
| 321 |
if out_cal_path: |
| 322 |
cgats.write(out_cal_path) |
| 323 |
return cgats |
| 324 |
|
| 325 |
black, white = get_black_and_white_levels(cgats) |
| 326 |
cgats = vcgt_to_cal(profile) |
| 327 |
cgats = unscale_vcgt_from_video_levels(profile, cgats, black, white) |
| 328 |
if out_cal_path: |
| 329 |
cgats.write(out_cal_path) |
| 330 |
return cgats |
| 331 |
|
| 332 |
|
| 333 |
def get_black_and_white_levels(cgats: CGATS) -> None | tuple[float, float]: |
| 334 |
"""Get black and white levels for video encoding. |
| 335 |
|
| 336 |
Args: |
| 337 |
cgats (CGATS): The CGATS instance to query for black and white levels. |
| 338 |
|
| 339 |
Returns: |
| 340 |
tuple[float, float]: A tuple containing the black and white levels. |
| 341 |
""" |
| 342 |
# When vcgt is nonlinear, prefer it |
| 343 |
# Check for video levels encoding |
| 344 |
black = None |
| 345 |
white = None |
| 346 |
if cgats.queryv1("TV_OUTPUT_ENCODING") == b"YES": |
| 347 |
black, white = (16, 235) |
| 348 |
elif output_enc := cgats.queryv1("OUTPUT_ENCODING"): |
| 349 |
try: |
| 350 |
black, white = (float(v) for v in output_enc.split()) |
| 351 |
except (TypeError, ValueError): |
| 352 |
white = False |
| 353 |
|
| 354 |
return black, white |
| 355 |
|
| 356 |
|
| 357 |
def convert_cal_info_from_embedded_wcs_profile( |
| 358 |
profile: ICCProfile, |
| 359 |
) -> tuple[bool, callable, ICCProfile]: |
| 360 |
"""Convert calibration info from embedded WCS profile to vcgt if missing. |
| 361 |
|
| 362 |
Args: |
| 363 |
profile (ICCProfile): The ICCProfile to extract the calibration data from. |
| 364 |
|
| 365 |
Returns: |
| 366 |
tuple[bool, callable, ICCProfile]: A tuple containing: |
| 367 |
- bool: True if the profile has a vcgt tag or can be converted to one, |
| 368 |
- callable: A function to convert the vcgt tag to calibration data, |
| 369 |
- ICCProfile: The ICCProfile instance with the vcgt tag. |
| 370 |
""" |
| 371 |
if ( |
| 372 |
isinstance(profile.tags.get("MS00"), WcsProfilesTagType) |
| 373 |
and "vcgt" not in profile.tags |
| 374 |
): |
| 375 |
profile.tags["vcgt"] = profile.tags["MS00"].get_vcgt() |
| 376 |
|
| 377 |
# Get the calibration from profile vcgt |
| 378 |
check = isinstance(profile.tags.get("vcgt"), VideoCardGammaType) |
| 379 |
cgats_builder = vcgt_to_cal |
| 380 |
arg = profile |
| 381 |
return check, cgats_builder, arg |
| 382 |
|
| 383 |
|
| 384 |
def unscale_vcgt_from_video_levels( |
| 385 |
profile: ICCProfile, cgats: CGATS, black: float, white: float |
| 386 |
) -> CGATS: |
| 387 |
"""Un-scale vcgt from video levels. |
| 388 |
|
| 389 |
Args: |
| 390 |
profile (ICCProfile): The ICC profile containing the vcgt tag. |
| 391 |
cgats (CGATS): The CGATS instance to apply scaling to. |
| 392 |
black (float): The black level for video encoding. |
| 393 |
white (float): The white level for video encoding. |
| 394 |
|
| 395 |
Returns: |
| 396 |
CGATS: The CGATS instance with applied video level scaling. |
| 397 |
""" |
| 398 |
if not white or (black, white) == (0, 255): |
| 399 |
print( |
| 400 |
"No need to un-scale vcgt from video levels as black and white " |
| 401 |
f"levels are ({black}..{white})" |
| 402 |
) |
| 403 |
return cgats |
| 404 |
print(f"Need to un-scale vcgt from video levels ({black}..{white})") |
| 405 |
|
| 406 |
# Need to un-scale video levels |
| 407 |
if not (data := cgats.queryv1("DATA")): |
| 408 |
print("Warning - no un-scaling applied - no calibration data!") |
| 409 |
return cgats |
| 410 |
|
| 411 |
print(f"Un-scaling vcgt from video levels ({black}..{white})") |
| 412 |
encoding_mismatch = False |
| 413 |
# For video encoding the extra bits of |
| 414 |
# precision are created by bit shifting rather |
| 415 |
# than scaling, so we need to scale the fp |
| 416 |
# value to account for this |
| 417 |
old_min = (black / 256.0) * (65536 / 65535.0) |
| 418 |
old_max = (white / 256.0) * (65536 / 65535.0) |
| 419 |
for entry in data.values(): |
| 420 |
for column in "RGB": |
| 421 |
v_old = entry[f"RGB_{column}"] |
| 422 |
lvl = round(v_old * (65535 / 65536.0) * 256, 2) |
| 423 |
if lvl < round(black, 2) or lvl > round(white, 2): |
| 424 |
# Can't be right. Metadata says it's video encoded, |
| 425 |
# but clearly exceeds the encoding range. |
| 426 |
print( |
| 427 |
f"Warning: Metadata claims video levels (" |
| 428 |
f"{round(black, 2)}..{round(white, 2)}) but " |
| 429 |
f"vcgt value {lvl} exceeds encoding range. " |
| 430 |
f"Using values as-is." |
| 431 |
) |
| 432 |
encoding_mismatch = True |
| 433 |
break |
| 434 |
v_new = colormath.convert_range(v_old, old_min, old_max, 0, 1) |
| 435 |
entry[f"RGB_{column}"] = min(max(v_new, 0), 1) |
| 436 |
if encoding_mismatch: |
| 437 |
break |
| 438 |
if encoding_mismatch: |
| 439 |
cgats = vcgt_to_cal(profile) |
| 440 |
# Add video levels hint to CGATS |
| 441 |
elif (black, white) == (16, 235): |
| 442 |
cgats[0].add_keyword("TV_OUTPUT_ENCODING", "YES") |
| 443 |
else: |
| 444 |
cgats[0].add_keyword( |
| 445 |
"OUTPUT_ENCODING", |
| 446 |
b" ".join(bytes(str(v), "utf-8") for v in (black, white)), |
| 447 |
) |
| 448 |
return cgats |
| 449 |
|
| 450 |
|
| 451 |
def extract_cal_from_ti3(ti3: str | BytesIO) -> bytes: |
| 452 |
"""Extract and return the CAL section of a TI3. |
| 453 |
|
| 454 |
ti3 can be a file object or a string holding the data. |
| 455 |
|
| 456 |
Returns: |
| 457 |
bytes: The extracted data. |
| 458 |
""" |
| 459 |
if isinstance(ti3, CGATS): |
| 460 |
ti3 = bytes(ti3) |
| 461 |
if isinstance(ti3, bytes): |
| 462 |
ti3 = BytesIO(ti3) |
| 463 |
cal = False |
| 464 |
cal_lines = [] |
| 465 |
for line in ti3: |
| 466 |
line = line.strip() |
| 467 |
if line == b"CAL": |
| 468 |
line = b"CAL " # Make sure CGATS file identifiers are |
| 469 |
# always a minimum of 7 characters |
| 470 |
cal = True |
| 471 |
if cal: |
| 472 |
cal_lines.append(line) |
| 473 |
if line == b"END_DATA": |
| 474 |
break |
| 475 |
with contextlib.suppress(AttributeError): |
| 476 |
ti3.close() |
| 477 |
|
| 478 |
return b"\n".join(cal_lines) |
| 479 |
|
| 480 |
|
| 481 |
def extract_fix_copy_cal( |
| 482 |
source_filename: str, target_filename: None | str = None |
| 483 |
) -> None | list[str] | Exception: |
| 484 |
"""Return the CAL section from a profile's embedded measurement data. |
| 485 |
|
| 486 |
Try to 'fix it' (add information needed to make the resulting .cal file |
| 487 |
'updatable') and optionally copy it to target_filename. |
| 488 |
|
| 489 |
Args: |
| 490 |
source_filename (str): The path to the source profile file. |
| 491 |
target_filename (str, optional): The path to save the fixed CAL data. |
| 492 |
If None, the data is not saved to a file. |
| 493 |
|
| 494 |
Returns: |
| 495 |
None | list[str] | Exception: Returns a list of CAL lines if found and |
| 496 |
None if not and Exception if any exception is raised. |
| 497 |
""" |
| 498 |
from DisplayCAL.worker import get_options_from_profile |
| 499 |
|
| 500 |
try: |
| 501 |
profile = ICCProfile(source_filename) |
| 502 |
except (OSError, ICCProfileInvalidError) as exception: |
| 503 |
return exception |
| 504 |
if "CIED" not in profile.tags and "targ" not in profile.tags: |
| 505 |
return None |
| 506 |
cal_lines = [] |
| 507 |
with BytesIO(profile.tags.get("CIED", b"") or profile.tags.get("targ", b"")) as ti3: |
| 508 |
ti3_lines = [line.strip() for line in ti3] |
| 509 |
|
| 510 |
cal_found = False |
| 511 |
for line in ti3_lines: |
| 512 |
if line == b"CAL": |
| 513 |
# Make sure CGATS file identifiers are always a minimum of 7 characters long |
| 514 |
line = line.ljust(7) |
| 515 |
cal_found = True |
| 516 |
if not cal_found: |
| 517 |
continue |
| 518 |
cal_lines.append(line) |
| 519 |
if line != b'DEVICE_CLASS "DISPLAY"': |
| 520 |
continue |
| 521 |
options_dispcal = get_options_from_profile(profile)[0] |
| 522 |
if not options_dispcal: |
| 523 |
continue |
| 524 |
# b = profile.tags.lumi.Y |
| 525 |
cal_lines = build_cal_from_profile(cal_lines, options_dispcal) |
| 526 |
|
| 527 |
if cal_lines: |
| 528 |
if target_filename: |
| 529 |
try: |
| 530 |
with open(target_filename, "wb") as f: |
| 531 |
f.write(b"\n".join(cal_lines)) |
| 532 |
except Exception as exception: |
| 533 |
return exception |
| 534 |
return cal_lines |
| 535 |
return None |
| 536 |
|
| 537 |
|
| 538 |
def build_cal_from_profile( |
| 539 |
cal_lines: list[bytes], options_dispcal: list |
| 540 |
) -> list[bytes]: |
| 541 |
"""Build a CAL section from profile options. |
| 542 |
|
| 543 |
Args: |
| 544 |
cal_lines (list[bytes]): The list to append CAL lines to. |
| 545 |
options_dispcal (list): List of dispcal options to add to the CAL section. |
| 546 |
""" |
| 547 |
whitepoint = False |
| 548 |
for option in options_dispcal: |
| 549 |
if option[0] == b"y": |
| 550 |
cal_lines.extend( |
| 551 |
[ |
| 552 |
b'KEYWORD "DEVICE_TYPE"', |
| 553 |
{b"c": b'DEVICE_TYPE "CRT"'}.get(option[1], b'DEVICE_TYPE "LCD"'), |
| 554 |
] |
| 555 |
) |
| 556 |
continue |
| 557 |
if option[0] in (b"t", b"T", b"w"): |
| 558 |
continue |
| 559 |
if option[0] in (b"g", b"G"): |
| 560 |
trc = { |
| 561 |
b"240": b"SMPTE240M", |
| 562 |
b"709": b"REC709", |
| 563 |
b"l": b"L_STAR", |
| 564 |
b"s": b"sRGB", |
| 565 |
}.get(option[1:], option[1:]) |
| 566 |
if trc == option[1:] and option[0] == b"G": |
| 567 |
try: |
| 568 |
trc = 0 - Decimal(trc) |
| 569 |
except decimal.InvalidOperation: |
| 570 |
continue |
| 571 |
cal_lines.extend((b'KEYWORD "TARGET_GAMMA"', b'TARGET_GAMMA "%s"' % trc)) |
| 572 |
continue |
| 573 |
|
| 574 |
to_extend = { |
| 575 |
b"f": ( |
| 576 |
b'KEYWORD "DEGREE_OF_BLACK_OUTPUT_OFFSET"', |
| 577 |
b'DEGREE_OF_BLACK_OUTPUT_OFFSET "%s"' % option[1:], |
| 578 |
), |
| 579 |
b"k": ( |
| 580 |
b'KEYWORD "BLACK_POINT_CORRECTION"', |
| 581 |
b'BLACK_POINT_CORRECTION "%s"' % option[1:], |
| 582 |
), |
| 583 |
b"B": ( |
| 584 |
b'KEYWORD "TARGET_BLACK_BRIGHTNESS"', |
| 585 |
b'TARGET_BLACK_BRIGHTNESS "%s"' % option[1:], |
| 586 |
), |
| 587 |
}.get(option[0:1], None) |
| 588 |
if to_extend: |
| 589 |
cal_lines.extend(to_extend) |
| 590 |
continue |
| 591 |
|
| 592 |
if option[0] == b"q": |
| 593 |
q = { |
| 594 |
b"l": b"low", |
| 595 |
b"m": b"medium", |
| 596 |
}.get(option[1:2], b"high") |
| 597 |
cal_lines.extend((b'KEYWORD "QUALITY"', b'QUALITY "%s"' % q)) |
| 598 |
cal_lines.extend( |
| 599 |
( |
| 600 |
b'KEYWORD "NATIVE_TARGET_WHITE"', |
| 601 |
b'NATIVE_TARGET_WHITE ""', |
| 602 |
) |
| 603 |
if not whitepoint |
| 604 |
else () |
| 605 |
) |
| 606 |
return cal_lines |
| 607 |
|
| 608 |
|
| 609 |
def extract_device_gray_primaries( |
| 610 |
ti3: CGATS, |
| 611 |
gray: bool = True, |
| 612 |
logfn: None | bool = None, |
| 613 |
include_neutrals: bool = False, |
| 614 |
neutrals_ab_threshold: float = 0.1, |
| 615 |
) -> tuple[CGATS, dict, dict]: |
| 616 |
"""Extract gray or primaries into new TI3. |
| 617 |
|
| 618 |
Args: |
| 619 |
ti3 (CGATS): The CGATS instance containing the TI3 data. |
| 620 |
gray (bool): If True, extract gray neutrals, otherwise extract RGB primaries. |
| 621 |
logfn (callable): A logging function to call with messages. |
| 622 |
include_neutrals (bool): If True, include neutral readings in the extraction. |
| 623 |
neutrals_ab_threshold (float): Threshold for neutral readings in Lab space. |
| 624 |
|
| 625 |
Returns: |
| 626 |
tuple: A tuple containing: |
| 627 |
- CGATS: The extracted TI3 data. |
| 628 |
- dict: A mapping of extracted RGB to XYZ values. |
| 629 |
- dict: A mapping of remaining RGB to XYZ values. |
| 630 |
""" |
| 631 |
filename = ti3.filename |
| 632 |
ti3 = ti3.queryi1("DATA") |
| 633 |
ti3.filename = filename |
| 634 |
ti3_extracted = CGATS( |
| 635 |
b"""CTI3 |
| 636 |
DEVICE_CLASS "DISPLAY" |
| 637 |
COLOR_REP "RGB_XYZ" |
| 638 |
BEGIN_DATA_FORMAT |
| 639 |
END_DATA_FORMAT |
| 640 |
BEGIN_DATA |
| 641 |
END_DATA""" |
| 642 |
)[0] |
| 643 |
ti3_extracted.DATA_FORMAT.update(ti3.DATA_FORMAT) |
| 644 |
subset = [(100.0, 100.0, 100.0), (0.0, 0.0, 0.0)] |
| 645 |
if not gray: |
| 646 |
subset.extend( |
| 647 |
[ |
| 648 |
(100.0, 0.0, 0.0), |
| 649 |
(0.0, 100.0, 0.0), |
| 650 |
(0.0, 0.0, 100.0), |
| 651 |
(50.0, 50.0, 50.0), |
| 652 |
] |
| 653 |
) |
| 654 |
if logfn: |
| 655 |
logfn(f"Extracting neutrals and primaries from {ti3.filename}") |
| 656 |
elif logfn: |
| 657 |
logfn(f"Extracting neutrals from {ti3.filename}") |
| 658 |
|
| 659 |
ti3_extracted, rgb_xyz_extracted, rgb_xyz_remaining, dupes = extract_rgb_xyz_data( |
| 660 |
ti3, |
| 661 |
gray, |
| 662 |
include_neutrals, |
| 663 |
neutrals_ab_threshold, |
| 664 |
ti3_extracted, |
| 665 |
subset, |
| 666 |
) |
| 667 |
|
| 668 |
for rgb, count in dupes.items(): |
| 669 |
for rgb_xyz in (rgb_xyz_extracted, rgb_xyz_remaining): |
| 670 |
if rgb in rgb_xyz: |
| 671 |
# Average values |
| 672 |
xyz = tuple(rgb_xyz[rgb][i] / count for i in range(3)) |
| 673 |
rgb_xyz[rgb] = xyz |
| 674 |
return ti3_extracted, rgb_xyz_extracted, rgb_xyz_remaining |
| 675 |
|
| 676 |
|
| 677 |
def extract_rgb_xyz_data( |
| 678 |
ti3: CGATS, |
| 679 |
gray: bool, |
| 680 |
include_neutrals: bool, |
| 681 |
neutrals_ab_threshold: float, |
| 682 |
ti3_extracted: CGATS, |
| 683 |
subset: list[tuple[float, float, float]], |
| 684 |
) -> CGATS: |
| 685 |
"""Extract RGB and XYZ data from TI3. |
| 686 |
|
| 687 |
Args: |
| 688 |
ti3 (CGATS): The CGATS instance containing the TI3 data. |
| 689 |
gray (bool): If True, extract gray neutrals, otherwise extract RGB primaries. |
| 690 |
include_neutrals (bool): If True, include neutral readings in the extraction. |
| 691 |
neutrals_ab_threshold (float): Threshold for neutral readings in Lab space. |
| 692 |
ti3_extracted (CGATS): The CGATS instance to store extracted data. |
| 693 |
subset (list): List of RGB values to be included in the extraction. |
| 694 |
|
| 695 |
Raises: |
| 696 |
Error: If required fields are missing in the TI3 data. |
| 697 |
|
| 698 |
Returns: |
| 699 |
tuple[CGATS, dict, dict, dict]: The CGATS instance containing the |
| 700 |
extracted data, the dictionary of extracted RGB to XYZ mappings, |
| 701 |
the dictionary of remaining RGB to XYZ mappings, and the dictionary |
| 702 |
of duplicate RGB values. |
| 703 |
""" |
| 704 |
rgb_xyz_extracted = {} |
| 705 |
rgb_xyz_remaining = {} |
| 706 |
dupes = {} |
| 707 |
|
| 708 |
if include_neutrals: |
| 709 |
white = ti3.get_white_cie("XYZ") |
| 710 |
str_thresh = str(neutrals_ab_threshold) |
| 711 |
round_digits = len(str_thresh[str_thresh.find(".") + 1 :]) |
| 712 |
|
| 713 |
for i in ti3.DATA: |
| 714 |
item = ti3.DATA[i] |
| 715 |
if not i: # don't validate the header |
| 716 |
validate_ti3_item(ti3, item) |
| 717 |
rgb = (item["RGB_R"], item["RGB_G"], item["RGB_B"]) |
| 718 |
xyz = (item["XYZ_X"], item["XYZ_Y"], item["XYZ_Z"]) |
| 719 |
for rgb_xyz in (rgb_xyz_extracted, rgb_xyz_remaining): |
| 720 |
if rgb not in rgb_xyz: |
| 721 |
continue |
| 722 |
if rgb != (100.0, 100.0, 100.0): |
| 723 |
# Add to existing values for averaging later |
| 724 |
# if it's not white (all other readings are scaled to the |
| 725 |
# white Y by dispread, so we don't alter it. Note that it's |
| 726 |
# always the first encountered white that will have Y = 100, |
| 727 |
# even if subsequent white readings may be higher) |
| 728 |
xyz = tuple(rgb_xyz[rgb][i] + xyz[i] for i in range(3)) |
| 729 |
if rgb not in dupes: |
| 730 |
dupes[rgb] = 1.0 |
| 731 |
dupes[rgb] += 1.0 |
| 732 |
elif rgb in subset: |
| 733 |
# We have white already, remove it from the subset so any |
| 734 |
# additional white readings we encounter are ignored |
| 735 |
subset.remove(rgb) |
| 736 |
if ( |
| 737 |
gray |
| 738 |
and ( |
| 739 |
item["RGB_R"] == item["RGB_G"] == item["RGB_B"] |
| 740 |
or ( |
| 741 |
include_neutrals |
| 742 |
and all( |
| 743 |
round(abs(v), round_digits) <= neutrals_ab_threshold |
| 744 |
for v in colormath.XYZ2Lab( |
| 745 |
item["XYZ_X"], |
| 746 |
item["XYZ_Y"], |
| 747 |
item["XYZ_Z"], |
| 748 |
whitepoint=white, |
| 749 |
)[1:] |
| 750 |
) |
| 751 |
) |
| 752 |
) |
| 753 |
and rgb not in [(100.0, 100.0, 100.0), (0.0, 0.0, 0.0)] |
| 754 |
) or rgb in subset: |
| 755 |
ti3_extracted.DATA.add_data(item) |
| 756 |
rgb_xyz_extracted[rgb] = xyz |
| 757 |
elif rgb not in [(100.0, 100.0, 100.0), (0.0, 0.0, 0.0)]: |
| 758 |
rgb_xyz_remaining[rgb] = xyz |
| 759 |
|
| 760 |
return ti3_extracted, rgb_xyz_extracted, rgb_xyz_remaining, dupes |
| 761 |
|
| 762 |
|
| 763 |
def validate_ti3_item(ti3: CGATS, item: dict) -> None: |
| 764 |
"""Validate a TI3 item to ensure it contains required fields. |
| 765 |
|
| 766 |
Args: |
| 767 |
ti3 (CGATS): The CGATS instance containing the TI3 data. |
| 768 |
item (dict): The TI3 item to validate. |
| 769 |
|
| 770 |
Raises: |
| 771 |
Error: If required fields are missing in the TI3 item. |
| 772 |
""" |
| 773 |
# Check if fields are missing |
| 774 |
required_fields = ("RGB_R", "RGB_G", "RGB_B", "XYZ_X", "XYZ_Y", "XYZ_Z") |
| 775 |
for field in required_fields: |
| 776 |
if field not in item: |
| 777 |
lang.getstr("error.testchart.missing_fields", (ti3.filename, field)) |
| 778 |
|
| 779 |
|
| 780 |
def ti3_to_ti1(ti3_data: str | list[str] | BytesIO) -> bytes: |
| 781 |
"""Create and return TI1 data converted from TI3. |
| 782 |
|
| 783 |
Args: |
| 784 |
ti3_data (str | list[str] | BytesIO): Can be a file object, a list of |
| 785 |
strings or a string holding the data. |
| 786 |
|
| 787 |
Returns: |
| 788 |
bytes: The converted TI1 data as bytes. |
| 789 |
""" |
| 790 |
ti3 = CGATS(ti3_data) |
| 791 |
if not ti3: |
| 792 |
return "" |
| 793 |
ti3[0].type = b"CTI1" |
| 794 |
ti3[0].DESCRIPTOR = b"Argyll Calibration Target chart information 1" |
| 795 |
ti3[0].ORIGINATOR = b"Argyll targen" |
| 796 |
if hasattr(ti3[0], "COLOR_REP"): |
| 797 |
color_rep = ti3[0].COLOR_REP.split(b"_")[0] |
| 798 |
else: |
| 799 |
color_rep = b"RGB" |
| 800 |
ti3[0].add_keyword("COLOR_REP", color_rep) |
| 801 |
ti3[0].remove_keyword("DEVICE_CLASS") |
| 802 |
if hasattr(ti3[0], "LUMINANCE_XYZ_CDM2"): |
| 803 |
ti3[0].remove_keyword("LUMINANCE_XYZ_CDM2") |
| 804 |
if hasattr(ti3[0], "ARGYLL_COLPROF_ARGS"): |
| 805 |
del ti3[0].ARGYLL_COLPROF_ARGS |
| 806 |
return bytes(ti3[0]) |
| 807 |
|
| 808 |
|
| 809 |
def vcgt_to_cal(profile: ICCProfile) -> CGATS: |
| 810 |
"""Return a CAL (CGATS instance) from vcgt. |
| 811 |
|
| 812 |
Args: |
| 813 |
profile (ICCProfile): The ICC profile containing the vcgt tag. |
| 814 |
|
| 815 |
Returns: |
| 816 |
CGATS: A CGATS instance representing the calibration data. |
| 817 |
""" |
| 818 |
cgats = CGATS(file_identifier=b"CAL") |
| 819 |
context = cgats.add_data({"DESCRIPTOR": b"Argyll Device Calibration State"}) |
| 820 |
context.add_data({"ORIGINATOR": b"vcgt"}) |
| 821 |
context.add_data( |
| 822 |
{ |
| 823 |
"CREATED": bytes( |
| 824 |
strftime("%a %b %d %H:%M:%S %Y", profile.dateTime.timetuple()), |
| 825 |
"utf-8", |
| 826 |
"replace", |
| 827 |
) |
| 828 |
} |
| 829 |
) |
| 830 |
context.add_keyword("DEVICE_CLASS", b"DISPLAY") |
| 831 |
context.add_keyword("COLOR_REP", b"RGB") |
| 832 |
context.add_keyword("RGB_I") |
| 833 |
key = "DATA_FORMAT" |
| 834 |
context[key] = CGATS() |
| 835 |
context[key].key = key |
| 836 |
context[key].parent = context |
| 837 |
context[key].root = cgats |
| 838 |
context[key].type = key.encode("utf-8") |
| 839 |
context[key].add_data((b"RGB_I", b"RGB_R", b"RGB_G", b"RGB_B")) |
| 840 |
key = "DATA" |
| 841 |
context[key] = CGATS() |
| 842 |
context[key].key = key |
| 843 |
context[key].parent = context |
| 844 |
context[key].root = cgats |
| 845 |
context[key].type = key.encode("utf-8") |
| 846 |
values = profile.tags.vcgt.getNormalizedValues() |
| 847 |
for i, triplet in enumerate(values): |
| 848 |
context[key].add_data((b"%.7f" % (i / float(len(values) - 1)), *triplet)) |
| 849 |
return cgats |
| 850 |
|
| 851 |
|
| 852 |
def verify_cgats( |
| 853 |
cgats: CGATS, required: tuple[str], ignore_unknown: bool = True |
| 854 |
) -> CGATS: |
| 855 |
"""Verify and return a CGATS instance or None on failure. |
| 856 |
|
| 857 |
Verify if a CGATS instance has a section with all required fields. |
| 858 |
Return the section as CGATS instance on success, None on failure. |
| 859 |
|
| 860 |
If ignore_unknown evaluates to True, ignore fields which are not required. |
| 861 |
Otherwise, the CGATS data must contain only the required fields, no more, |
| 862 |
no less. |
| 863 |
|
| 864 |
Args: |
| 865 |
cgats (CGATS): The CGATS instance to verify. |
| 866 |
required (tuple[str]): A tuple of required field names. |
| 867 |
ignore_unknown (bool): Whether to ignore unknown fields. |
| 868 |
|
| 869 |
Raises: |
| 870 |
CGATSKeyError: If a required field is missing. |
| 871 |
CGATSInvalidError: If the CGATS data is invalid or incomplete. |
| 872 |
CGATSError: If an unknown field is found and ignore_unknown is False. |
| 873 |
|
| 874 |
Returns: |
| 875 |
CGATS: The verified CGATS instance containing the required section, |
| 876 |
or raises an error if verification fails. |
| 877 |
""" |
| 878 |
cgats_1 = cgats.queryi1(required) |
| 879 |
if not cgats_1 or not cgats_1.parent or not cgats_1.parent.parent: |
| 880 |
raise CGATSKeyError(f"Missing required fields: {', '.join(required)}") |
| 881 |
cgats_1 = cgats_1.parent.parent |
| 882 |
if not cgats_1.queryv1("NUMBER_OF_SETS"): |
| 883 |
raise CGATSInvalidError("Missing NUMBER_OF_SETS") |
| 884 |
if not cgats_1.queryv1("DATA_FORMAT"): |
| 885 |
raise CGATSInvalidError("Missing DATA_FORMAT") |
| 886 |
for field in required: |
| 887 |
if field.encode("utf-8") not in list(cgats_1.queryv1("DATA_FORMAT").values()): |
| 888 |
raise CGATSKeyError(f"Missing required field: {field}") |
| 889 |
if not ignore_unknown: |
| 890 |
for field in list(cgats_1.queryv1("DATA_FORMAT").values()): |
| 891 |
if field not in required: |
| 892 |
raise CGATSError(f"Unknown field: {field}") |
| 893 |
modified = cgats_1.modified |
| 894 |
cgats_1.filename = cgats.filename |
| 895 |
cgats_1.modified = modified |
| 896 |
return cgats_1 |
| 897 |
|
| 898 |
|
| 899 |
def verify_ti1_rgb_xyz(cgats: CGATS) -> None | CGATS: |
| 900 |
"""Verify and return a CGATS instance or None on failure. |
| 901 |
|
| 902 |
Verify if a CGATS instance has a TI1 section with all required fields |
| 903 |
for RGB devices. Return the TI1 section as CGATS instance on success, |
| 904 |
None on failure. |
| 905 |
|
| 906 |
Args: |
| 907 |
cgats (CGATS): The CGATS instance to verify. |
| 908 |
|
| 909 |
Returns: |
| 910 |
None | CGATS: The verified CGATS instance containing the TI1 section, or None |
| 911 |
if verification fails. |
| 912 |
""" |
| 913 |
return verify_cgats(cgats, ("RGB_R", "RGB_B", "RGB_G", "XYZ_X", "XYZ_Y", "XYZ_Z")) |