Debian Codegraph @

DisplayCAL/worker_base.py

raw
1 """Base classes and utilities for calibration and profiling workflows.
2
3 It includes base worker classes, multiprocessing support, and methods for
4 interacting with Argyll CMS utilities like `xicclu`. The module also handles
5 subprocess management, logging, and temporary directory creation.
6 """
7
8 from __future__ import annotations
9
10 import contextlib
11 import math
12 import os
13 import shlex
14 import shutil
15 import struct
16 import subprocess as sp
17 import sys
18 import tempfile
19 import textwrap
20 import traceback
21 from binascii import hexlify
22 from typing import TYPE_CHECKING
23
24 if TYPE_CHECKING:
25 if sys.version_info >= (3, 11):
26 from typing import Self
27 else:
28 from typing_extensions import Self
29
30 if sys.platform == "win32":
31 import win32api
32
33
34 from DisplayCAL import (
35 colormath,
36 config,
37 )
38 from DisplayCAL import (
39 localization as lang,
40 )
41 from DisplayCAL.argyll import get_argyll_util, get_argyll_version
42 from DisplayCAL.cgats import CGATS
43 from DisplayCAL.colormath import (
44 VidRGB_to_cLUT65,
45 VidRGB_to_eeColor,
46 eeColor_to_VidRGB,
47 )
48 from DisplayCAL.config import (
49 # exe_ext,
50 # fs_enc,
51 # get_data_path,
52 # getcfg,
53 PROFILE_EXT,
54 )
55 from DisplayCAL.debughelpers import (
56 Error,
57 Info,
58 # UnloggedError,
59 # UnloggedInfo,
60 # UnloggedWarning,
61 # Warn,
62 )
63 from DisplayCAL.icc_profile import (
64 ICCProfile,
65 LUT16Type,
66 )
67 from DisplayCAL.log import LogFile
68 from DisplayCAL.meta import NAME as APPNAME
69 from DisplayCAL.multiprocess import MAX_CPUS, mp, pool_slice
70 from DisplayCAL.options import DEBUG, VERBOSE
71 from DisplayCAL.util_os import quote_args
72 from DisplayCAL.util_str import make_filename_safe, safe_basestring, safe_str
73
74
75 def _xicclu_mp(
76 chunk,
77 thread_abort_event,
78 progress_queue,
79 profile_filename,
80 intent="r",
81 direction="f",
82 order="n",
83 pcs=None,
84 scale=1,
85 cwd=None,
86 startupinfo=None,
87 use_icclu=False,
88 use_cam_clipping=False,
89 logfile=None,
90 show_actual_if_clipped=False,
91 input_encoding=None,
92 output_encoding=None,
93 abortmessage="Aborted",
94 output_format=None,
95 reverse=False,
96 convert_video_rgb_to_clut65=False,
97 verbose=1,
98 ):
99 """Xicclu multiprocessing worker."""
100 if not config.CFG.items(config.configparser.DEFAULTSECT):
101 config.initcfg()
102 profile = ICCProfile(profile_filename)
103 xicclu = Xicclu(
104 profile,
105 intent,
106 direction,
107 order,
108 pcs,
109 scale,
110 cwd,
111 startupinfo,
112 use_icclu,
113 use_cam_clipping,
114 logfile,
115 None,
116 show_actual_if_clipped,
117 input_encoding,
118 output_encoding,
119 convert_video_rgb_to_clut65,
120 verbose,
121 )
122 prevperc = 0
123 start = 0
124 num_subchunks = 50
125 subchunksize = float(len(chunk)) / num_subchunks
126 for i in range(num_subchunks):
127 if (
128 thread_abort_event is not None
129 and getattr(sys, "_sigbreak", False)
130 and not thread_abort_event.is_set()
131 ):
132 thread_abort_event.set()
133 print("Got SIGBREAK, aborting thread...")
134 if thread_abort_event is not None and thread_abort_event.is_set():
135 xicclu.exit(raise_exception=False)
136 return Info(abortmessage)
137 end = math.ceil(subchunksize * (i + 1))
138 xicclu(chunk[start:end])
139 start = end
140 perc = round((i + 1.0) / num_subchunks * 100)
141 if progress_queue and perc > prevperc:
142 progress_queue.put(perc - prevperc)
143 prevperc = perc
144 xicclu.exit()
145 return xicclu.get(output_format=output_format, reverse=reverse)
146
147
148 def _mp_generate_B2A_clut(
149 chunk,
150 thread_abort_event,
151 progress_queue,
152 profile_filename,
153 intent,
154 direction,
155 pcs,
156 use_cam_clipping,
157 clutres,
158 step,
159 threshold,
160 threshold2,
161 interp,
162 Linterp,
163 m2,
164 XYZbp,
165 XYZwp,
166 bpc,
167 abortmessage="Aborted",
168 ):
169 """B2A cLUT generation worker.
170
171 This should be spawned as a multiprocessing process
172
173 """
174 if DEBUG:
175 print("comtypes?", "comtypes" in str(list(sys.modules.keys())))
176 print("numpy?", "numpy" in str(list(sys.modules.keys())))
177 print("wx?", "wx" in str(list(sys.modules.keys())))
178 print("x3dom?", "x3dom" in str(list(sys.modules.keys())))
179 if not config.CFG.items(config.configparser.DEFAULTSECT):
180 config.initcfg()
181 idata = []
182 abmaxval = 255 + (255 / 256.0)
183 profile = ICCProfile(profile_filename)
184 xicclu1 = Xicclu(profile, intent, direction, "n", pcs, 100)
185 xicclu2 = xicclu1
186 if use_cam_clipping:
187 # Use CAM Jab for clipping for cLUT grid points after a given
188 # threshold
189 xicclu2 = Xicclu(
190 profile, intent, direction, "n", pcs, 100, use_cam_clipping=True
191 )
192 prevperc = 0
193 count = 0
194 chunksize = len(chunk)
195 for interp_tuple in (interp, Linterp):
196 if interp_tuple:
197 # Use numpy for speed
198 if interp_tuple is interp:
199 interp_list = list(interp_tuple)
200 else:
201 interp_list = [interp_tuple]
202 for i, ointerp in enumerate(interp_list):
203 interp_list[i] = colormath.Interp(
204 ointerp.xp, ointerp.fp, use_numpy=True
205 )
206 if interp_tuple is interp:
207 interp = interp_list
208 else:
209 Linterp = interp_list[0]
210 m2i = m2
211 if profile.connectionColorSpace == b"XYZ":
212 m2i = m2.inverted()
213 # Accumulate points and hand them to xicclu in batches instead of one at
214 # a time. Each call writes to and flushes the xicclu subprocess's stdin
215 # pipe, so calling it per grid point (up to clutres**3 times) turns into
216 # a syscall-bound hot loop. Flush each batch once it reaches
217 # xicclu_batch_size rather than waiting for the whole worker chunk, so
218 # xicclu1 and xicclu2 (which run as separate subprocesses and can
219 # compute concurrently) both keep receiving work throughout the loop
220 # instead of xicclu2 sitting idle until all of xicclu1's input is sent.
221 xicclu_batch_size = 1000
222 xicclu1_batch = []
223 xicclu2_batch = []
224 for a in chunk:
225 if thread_abort_event.is_set():
226 if use_cam_clipping:
227 xicclu2.exit()
228 xicclu1.exit()
229 return Info(abortmessage)
230 for b in range(clutres):
231 for c in range(clutres):
232 d, e, f = [v * step for v in (a, b, c)]
233 if profile.connectionColorSpace == b"XYZ":
234 # Apply TRC to XYZ values to distribute them optimally
235 # across cLUT grid points.
236 XYZ = [interp[i](v) for i, v in enumerate((d, e, f))]
237 # print "%3.6f %3.6f %3.6f" % tuple(XYZ), '->',
238 # Scale into PCS
239 v = m2i * XYZ
240 if bpc and XYZbp != [0, 0, 0]:
241 v = colormath.blend_blackpoint(v[0], v[1], v[2], None, XYZbp)
242 # print "%3.6f %3.6f %3.6f" % tuple(v)
243 # raw_input()
244 if intent == "a":
245 v = colormath.adapt(
246 *[*v, XYZwp, list(profile.tags.wtpt.ir.values())]
247 )
248 else:
249 # Legacy CIELAB
250 L = Linterp(d * 100)
251 v = L, -128 + e * abmaxval, -128 + f * abmaxval
252 idata.append("{:.6f} {:.6f} {:.6f}".format(*tuple(v)))
253 # Lookup CIE -> device values through profile using xicclu
254 if not use_cam_clipping or (
255 pcs == "x" and a <= threshold and b <= threshold and c <= threshold
256 ):
257 xicclu1_batch.append(v)
258 if len(xicclu1_batch) >= xicclu_batch_size:
259 xicclu1(xicclu1_batch)
260 xicclu1_batch = []
261 if use_cam_clipping and (
262 pcs == "l" or a > threshold2 or b > threshold2 or c > threshold2
263 ):
264 xicclu2_batch.append(v)
265 if len(xicclu2_batch) >= xicclu_batch_size:
266 xicclu2(xicclu2_batch)
267 xicclu2_batch = []
268 count += 1.0
269 perc = round(count / (chunksize * clutres**2) * 100)
270 if progress_queue and perc > prevperc:
271 progress_queue.put(perc - prevperc)
272 prevperc = perc
273 if xicclu1_batch:
274 xicclu1(xicclu1_batch)
275 if use_cam_clipping:
276 if xicclu2_batch:
277 xicclu2(xicclu2_batch)
278 xicclu2.exit()
279 data2 = xicclu2.get()
280 else:
281 data2 = []
282 xicclu1.exit()
283 data1 = xicclu1.get()
284 return idata, data1, data2
285
286
287 def printcmdline(cmd, args=None, fn=None, cwd=None):
288 """Pretty-print a command line."""
289 if fn is None:
290 fn = print
291 if args is None:
292 args = []
293 if cwd is None:
294 cwd = os.getcwd()
295 fn(f" {cmd}")
296 lines = []
297 for item in args:
298 # convert all args to str
299 if not isinstance(item, str):
300 if isinstance(item, bytes):
301 item = item.decode("utf-8")
302 item = str(item)
303 if item.find(os.path.sep) > -1 and os.path.dirname(item) == cwd:
304 item = os.path.basename(item)
305 if sys.platform == "win32":
306 item = sp.list2cmdline([item])
307 if not item.startswith('"'):
308 item = quote_args([item])[0]
309 else:
310 item = shlex.quote(item)
311 lines.append(item)
312 for line in lines:
313 fn(
314 textwrap.fill(
315 line,
316 80,
317 expand_tabs=False,
318 replace_whitespace=False,
319 initial_indent=" ",
320 subsequent_indent=" ",
321 )
322 )
323
324
325 class ThreadAbort:
326 """Thread abort event class."""
327
328 def __init__(self):
329 self.event = mp.Event()
330
331 def __bool__(self) -> bool:
332 """Check if the event is set.
333
334 Returns:
335 bool: True if the event is set, False otherwise.
336 """
337 return self.event.is_set()
338
339 def __cmp__(self, other):
340 """Compare the event state with another value.
341
342 Args:
343 other: The value to compare with.
344
345 Returns:
346 int: -1 if the event is set and other is not, 1 if the event is not
347 set and other is, 0 if both are in the same state.
348 """
349 if self.event.is_set() < other:
350 return -1
351 if self.event.is_set() > other:
352 return 1
353 return 0
354
355
356 class WorkerBase:
357 """Base worker class for calibration and profiling tasks."""
358
359 def __init__(self):
360 self.sessionlogfile = None
361 self.subprocess_abort = False
362 self.tempdir = None
363 self._thread_abort = ThreadAbort()
364
365 def create_tempdir(self):
366 """Create a temporary working directory and return its path.
367
368 Returns:
369 str | Exception: The path to the temporary directory, or an Error
370 if creation fails.
371 """
372 if not self.tempdir or not os.path.isdir(self.tempdir):
373 # we create the tempdir once each calibrating/profiling run
374 # (deleted by 'wrapup' after each run)
375 if VERBOSE >= 2:
376 if not self.tempdir:
377 msg = "there is none"
378 else:
379 msg = f"the previous ({self.tempdir}) no longer exists"
380 print(f"{APPNAME}: Creating a new temporary directory because", msg)
381 try:
382 self.tempdir = tempfile.mkdtemp(prefix=f"{APPNAME}-")
383 except Exception as exception:
384 self.tempdir = None
385 return Error(
386 "Error - couldn't create temporary directory: "
387 f"{safe_str(exception)}"
388 )
389 return self.tempdir
390
391 def isalive(self, subprocess=None):
392 """Check if subprocess is still alive.
393
394 Args:
395 subprocess: The subprocess to check (default: None, uses self.subprocess).
396 """
397 if not subprocess:
398 subprocess = getattr(self, "subprocess", None)
399 return subprocess and (
400 (hasattr(subprocess, "poll") and subprocess.poll() is None)
401 or (hasattr(subprocess, "isalive") and subprocess.isalive())
402 )
403
404 def log(self, *args, **kwargs):
405 """Log to global logfile and session logfile (if any)."""
406 # if we have any exceptions print the traceback, so we bust'em.
407 if any(isinstance(arg, BaseException) for arg in args):
408 traceback.print_exc()
409 msg = " ".join(safe_basestring(arg) for arg in args)
410 fn = kwargs.get("fn", print)
411 fn(msg)
412 if self.sessionlogfile:
413 self.sessionlogfile.write(f"{msg}\n")
414
415 @property
416 def thread_abort(self):
417 """Get the thread abort event.
418
419 Returns:
420 ThreadAbort: The thread abort event, which can be used to signal
421 that the thread should be aborted.
422 """
423 return self._thread_abort
424
425 @thread_abort.setter
426 def thread_abort(self, abort):
427 """Set the thread abort event.
428
429 Args:
430 abort (bool): If True, set the thread abort event to signal
431 that the thread should be aborted.
432 """
433 if abort:
434 self._thread_abort.event.set()
435 else:
436 self._thread_abort.event.clear()
437
438 def xicclu(
439 self,
440 profile,
441 idata,
442 intent="r",
443 direction="f",
444 order="n",
445 pcs=None,
446 scale=1,
447 cwd=None,
448 startupinfo=None,
449 raw=False,
450 logfile=None,
451 use_icclu=False,
452 use_cam_clipping=False,
453 get_clip=False,
454 show_actual_if_clipped=False,
455 input_encoding=None,
456 output_encoding=None,
457 ):
458 """Call xicclu, feed input floats into stdin, return output floats.
459
460 input data needs to be a list of 3-tuples (or lists) with floats,
461 alternatively a list of strings.
462 output data will be returned in same format, or as list of strings
463 if 'raw' is true.
464
465 Args:
466 profile (ICCProfile or CGATS): The ICC profile to use.
467 idata (list): Input data to be processed by xicclu.
468 intent (str): The rendering intent to use (default: "r").
469 direction (str): The direction of the transformation (default: "f").
470 order (str): The order of the transformation (default: "n").
471 pcs (str): The PCS to use (default: None).
472 scale (int): The scale factor for the transformation (default: 1).
473 cwd (str): The current working directory (default: None).
474 startupinfo: Startup information for subprocesses (default: None).
475 raw (bool): If True, return raw output as a list of strings.
476 logfile: Log file for output messages (default: None).
477 use_icclu (bool): Whether to use icclu instead of xicclu
478 (default: False).
479 use_cam_clipping (bool): Whether to use CAM clipping
480 (default: False).
481 get_clip (bool): If True, include clipping information in the
482 output.
483 show_actual_if_clipped (bool): Whether to show actual values if clipped
484 (default: False).
485 input_encoding (str): Input encoding for xicclu
486 (default: None).
487 output_encoding (str): Output encoding for xicclu
488 (default: None).
489 """
490 with Xicclu(
491 profile,
492 intent,
493 direction,
494 order,
495 pcs,
496 scale,
497 cwd,
498 startupinfo,
499 use_icclu,
500 use_cam_clipping,
501 logfile,
502 self,
503 show_actual_if_clipped,
504 input_encoding,
505 output_encoding,
506 ) as xicclu:
507 xicclu(idata)
508 return xicclu.get(raw, get_clip)
509
510
511 class Xicclu(WorkerBase):
512 """Xicclu worker class.
513
514 Args:
515 profile (ICCProfile or CGATS): The ICC profile to use.
516 intent (str): The rendering intent to use (default: "r").
517 direction (str): The direction of the transformation (default: "f").
518 order (str): The order of the transformation (default: "n").
519 pcs (str): The PCS to use (default: None).
520 scale (int): The scale factor for the transformation (default: 1).
521 cwd (str): The current working directory (default: None).
522 startupinfo: Startup information for subprocesses (default: None).
523 use_icclu (bool): Whether to use icclu instead of xicclu (default: False).
524 use_cam_clipping (bool): Whether to use CAM clipping (default: False).
525 logfile: Log file for output messages (default: None).
526 worker: Worker instance for multiprocessing (default: None).
527 show_actual_if_clipped (bool): Whether to show actual values if clipped
528 (default: False).
529 input_encoding (str): Input encoding for xicclu (default: None).
530 output_encoding (str): Output encoding for xicclu (default: None).
531 convert_video_rgb_to_clut65 (bool): Whether to convert video RGB
532 values to cLUT65 format.
533 verbose (int): Verbosity level for logging.
534 """
535
536 def __init__(
537 self,
538 profile,
539 intent="r",
540 direction="f",
541 order="n",
542 pcs=None,
543 scale=1,
544 cwd=None,
545 startupinfo=None,
546 use_icclu=False,
547 use_cam_clipping=False,
548 logfile=None,
549 worker=None,
550 show_actual_if_clipped=False,
551 input_encoding=None,
552 output_encoding=None,
553 convert_video_rgb_to_clut65=False,
554 verbose=1,
555 ):
556 if not profile:
557 raise Error(f"Xicclu: Profile is {profile!r}")
558 WorkerBase.__init__(self)
559 self.scale = scale
560 self.convert_video_rgb_to_clut65 = convert_video_rgb_to_clut65
561 self.logfile = logfile
562 self.worker = worker
563 self.temp = False
564 utilname = "icclu" if use_icclu else "xicclu"
565 xicclu = get_argyll_util(utilname)
566 if not xicclu:
567 raise Error(lang.getstr("argyll.util.not_found", utilname))
568 if not isinstance(profile, (CGATS, ICCProfile)):
569 if profile.lower().endswith(".cal"):
570 profile = CGATS(profile)
571 else:
572 profile = ICCProfile(profile)
573 is_profile = isinstance(profile, ICCProfile)
574 if (
575 is_profile
576 and profile.version >= 4
577 and not profile.convert_iccv4_tags_to_iccv2()
578 ):
579 raise Error(
580 "\n".join(
581 [lang.getstr("profile.iccv4.unsupported"), profile.getDescription()]
582 )
583 )
584 if not profile.filename or not os.path.isfile(profile.filename):
585 if profile.filename:
586 prefix = os.path.basename(profile.filename)
587 elif is_profile:
588 prefix = (
589 make_filename_safe(profile.getDescription(), concat=False)
590 + PROFILE_EXT
591 )
592 else:
593 # CGATS (.cal)
594 prefix = "cal"
595 prefix += "-"
596 if not cwd:
597 cwd = self.create_tempdir()
598 if isinstance(cwd, Exception):
599 raise cwd
600 fd, profile.filename = tempfile.mkstemp("", prefix, dir=cwd)
601 with os.fdopen(fd, "wb") as stream:
602 profile.write(stream)
603 self.temp = True
604 elif not cwd:
605 cwd = os.path.dirname(profile.filename)
606 profile_basename = os.path.basename(profile.filename)
607 profile_path = profile.filename
608 if sys.platform == "win32":
609 profile_path = win32api.GetShortPathName(profile_path)
610 self.profile_path = safe_str(profile_path)
611 if sys.platform == "win32" and not startupinfo:
612 startupinfo = sp.STARTUPINFO()
613 startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW
614 startupinfo.wShowWindow = sp.SW_HIDE
615 xicclu = safe_str(xicclu)
616 cwd = safe_str(cwd)
617 self.verbose = verbose
618 args = [xicclu, f"-v{verbose}", f"-s{scale}"]
619 self.show_actual_if_clipped = False
620 if utilname == "xicclu":
621 if (
622 is_profile
623 and show_actual_if_clipped
624 and "A2B0" in profile.tags
625 and ("B2A0" in profile.tags or direction == "if")
626 ):
627 args.append("-a")
628 self.show_actual_if_clipped = True
629 if use_cam_clipping:
630 args.append("-b")
631 if get_argyll_version("xicclu") >= [1, 6]:
632 # Add encoding parameters
633 # Note: Not adding -e -E can cause problems due to unitialized
634 # in_tvenc and out_tvenc variables in xicclu.c for Argyll 1.6.x
635 if not input_encoding:
636 input_encoding = "n"
637 if not output_encoding:
638 output_encoding = "n"
639 args += [
640 "-e" + safe_str(input_encoding),
641 "-E" + safe_str(output_encoding),
642 ]
643 args.append("-f" + direction)
644 self.output_scale = 1.0
645 if is_profile:
646 if profile.profileClass not in (b"abst", b"link"):
647 if intent:
648 args.append(f"-i{intent}")
649 if order != "n":
650 args.append("-o" + order)
651 if profile.profileClass != b"link":
652 if direction in ("f", "ib") and (
653 pcs == "x" or (profile.connectionColorSpace == b"XYZ" and not pcs)
654 ):
655 # In case of forward lookup with XYZ PCS, use 0..100 scaling
656 # internally so we get extra precision from xicclu for the
657 # decimal part. Scale back to 0..1 later.
658 pcs = "X"
659 self.output_scale = 100.0
660 if pcs:
661 args.append("-p" + pcs)
662 args.append(self.profile_path)
663 if DEBUG or verbose > 1:
664 self.sessionlogfile = LogFile(
665 profile_basename + ".xicclu", os.path.dirname(profile.filename)
666 )
667 if is_profile:
668 profile_act = ICCProfile(profile.filename)
669 self.sessionlogfile.write(
670 f"Profile ID {hexlify(profile.ID)} "
671 f"(actual {hexlify(profile_act.calculate_id(False))})"
672 )
673 if cwd:
674 self.log(lang.getstr("working_dir"))
675 indent = " "
676 for name in cwd.split(os.path.sep):
677 self.log(
678 textwrap.fill(
679 name + os.path.sep,
680 80,
681 expand_tabs=False,
682 replace_whitespace=False,
683 initial_indent=indent,
684 subsequent_indent=indent,
685 )
686 )
687 indent += " "
688 self.log("")
689 self.log(lang.getstr("commandline"))
690 printcmdline(xicclu, args[1:], fn=self.log, cwd=cwd)
691 self.log("")
692 self.startupinfo = startupinfo
693 self.args = args
694 self.cwd = cwd
695 self.spawn()
696
697 def spawn(self):
698 """Spawn the xicclu subprocess."""
699 self.closed = False
700 self.output = []
701 self.errors = []
702 self.stdout = tempfile.SpooledTemporaryFile() # noqa: SIM115
703 self.stderr = tempfile.SpooledTemporaryFile() # noqa: SIM115
704 self.subprocess = sp.Popen(
705 self.args,
706 stdin=sp.PIPE,
707 stdout=self.stdout,
708 stderr=self.stderr,
709 cwd=self.cwd,
710 startupinfo=self.startupinfo,
711 )
712
713 def devi_devip(self, n):
714 """Convert device value to device-independent value.
715
716 Args:
717 n (float): The device value to convert.
718
719 Returns:
720 float: The converted device-independent value.
721 """
722 if n > 236 / 256.0:
723 n = colormath.convert_range(n, 236 / 256.0, 1, 236 / 256.0, 255 / 256.0)
724 return VidRGB_to_cLUT65(eeColor_to_VidRGB(n))
725
726 def __call__(self, idata):
727 """Call the xicclu worker with input data.
728
729 Args:
730 idata (list or str): Input data to be processed by the xicclu worker.
731
732 Returns:
733 None: The method processes the input data and sends it to the
734 xicclu subprocess.
735 """
736 if not isinstance(idata, str):
737 verbose = self.verbose
738 if self.convert_video_rgb_to_clut65:
739 devi_devip = self.devi_devip
740 else:
741
742 def devi_devip(v):
743 return v
744
745 scale = float(self.scale)
746 idata = list(idata) # Make a copy
747 for i, v in enumerate(idata):
748 if isinstance(v, (float, int)):
749 self([idata])
750 return
751 if not isinstance(v, str):
752 if verbose:
753 for n in v:
754 if not isinstance(n, (float, int)):
755 raise TypeError(
756 "xicclu: Expecting list of "
757 "strings or n-tuples with "
758 "floats"
759 )
760 idata[i] = " ".join(str(devi_devip(n / scale) * scale) for n in v)
761 else:
762 idata = idata.splitlines()
763 numrows = len(idata)
764 chunklen = 1000
765 i = 0
766 p = self.subprocess
767 prevperc = -1
768 while True:
769 # Process in chunks to prevent broken pipe if input data is too
770 # large
771 if getattr(sys, "_sigbreak", False) and not self.subprocess_abort:
772 self.subprocess_abort = True
773 print("Got SIGBREAK, aborting subprocess...")
774 if self.subprocess_abort or self.thread_abort:
775 if p.poll() is None:
776 p.stdin.write(b"\n")
777 p.stdin.close()
778 p.wait()
779 raise Info(lang.getstr("aborted"))
780 if p.poll() is None:
781 # We don't use communicate() because it will end the
782 # process
783 joined_data = "\n".join(idata[chunklen * i : chunklen * (i + 1)]) + "\n"
784 p.stdin.write(joined_data.encode())
785 p.stdin.flush()
786 else:
787 # Error
788 break
789 perc = round(chunklen * (i + 1) / float(numrows) * 100)
790 if perc > prevperc and self.logfile:
791 self.logfile.write(f"\r{int(min(perc, 100))}%")
792 prevperc = perc
793 if chunklen * (i + 1) > numrows - 1:
794 break
795 i += 1
796
797 def __enter__(self) -> Self:
798 """Enter the runtime context related to this object.
799
800 Returns:
801 Xicclu: The current instance of the Xicclu class.
802 """
803 return self
804
805 def __exit__(self, exc_type, exec_value, traceback_):
806 """Exit the runtime context related to this object.
807
808 Args:
809 exc_type: The exception type.
810 exec_value: The exception value.
811 traceback_: The traceback object.
812
813 Returns:
814 bool: True if the exception should be suppressed, False otherwise.
815 """
816 self.exit()
817 return not traceback_
818
819 def close(self, raise_exception=True):
820 """Close the xicclu worker process.
821
822 Args:
823 raise_exception (bool): If True, raise an exception if the worker
824 has errors.
825
826 Raises:
827 OSError: If the worker has errors and raise_exception is True.
828 """
829 if self.closed:
830 return
831 p = self.subprocess
832 if p.poll() is None:
833 with contextlib.suppress(OSError):
834 p.stdin.write(b"\n")
835 p.stdin.close()
836 p.wait()
837 self.stdout.seek(0)
838 self.output = self.stdout.readlines()
839 self.stdout.close()
840 self.stderr.seek(0)
841 self.errors = self.stderr.readlines()
842 self.stderr.close()
843 if self.sessionlogfile and self.errors:
844 self.sessionlogfile.write(b"\n".join(self.errors))
845 if self.logfile:
846 self.logfile.write(b"\n")
847 self.closed = True
848 if p.returncode and raise_exception:
849 # Error
850 raise OSError(b"\n".join(self.errors))
851
852 def exit(self, raise_exception=True):
853 """Exit the xicclu worker process.
854
855 Args:
856 raise_exception (bool): If True, raise an exception if the worker
857 has errors.
858 """
859 self.close(raise_exception)
860 if self.temp and os.path.isfile(self.profile_path):
861 os.remove(self.profile_path)
862 if self.tempdir and not os.listdir(self.tempdir):
863 try:
864 shutil.rmtree(self.tempdir, True)
865 except Exception as exception:
866 print(
867 f"Warning - temporary directory '{self.tempdir}' "
868 f"could not be removed: {exception}"
869 )
870
871 def get(self, raw=False, get_clip=False, output_format=None, reverse=False):
872 """Get the output from xicclu.
873
874 Args:
875 raw (bool): If True, return raw output as a list of strings.
876 get_clip (bool): If True, include clipping information in the
877 output.
878 output_format (tuple): A tuple specifying the output format.
879 reverse (bool): If True, reverse the order of the output.
880
881 Returns:
882 list: The processed output from xicclu, either as raw strings or
883 formatted data.
884 """
885 if raw:
886 if self.sessionlogfile:
887 self.sessionlogfile.write("\n".join(self.output))
888 self.sessionlogfile.close()
889 return self.output
890 parsed = []
891 j = 0
892 verbose = self.verbose
893 scale = float(self.scale)
894 output_scale = float(self.output_scale)
895 if self.convert_video_rgb_to_clut65:
896 devop_devo = VidRGB_to_eeColor
897 else:
898
899 def devop_devo(v):
900 return v
901
902 fmt = ""
903 maxv = ""
904 if output_format:
905 fmt = output_format[0]
906 maxv = output_format[1]
907 # Interesting: In CPython, testing for 'if not x' is slightly quicker
908 # than testing for 'if x'. (EOY: Yeah I measured it is ~3% faster)
909 # Also, struct.pack is faster if the second argument is passed as an integer.
910 clip = None
911 for line in self.output:
912 if verbose:
913 line = line.strip()
914 if line.startswith(b"["):
915 if parsed and get_clip and self.show_actual_if_clipped:
916 parts = line.strip(b"[]").split(b",")
917 actual = [float(v) for v in parts[0].split()[1:4]] # Actual CIE
918 actual.append(float(parts[1].split()[-1])) # deltaE
919 parsed[-1].append(actual)
920 elif self.sessionlogfile:
921 self.sessionlogfile.write(line)
922 continue
923 if b"->" not in line:
924 if self.sessionlogfile and line:
925 self.sessionlogfile.write(line)
926 continue
927 if self.sessionlogfile:
928 self.sessionlogfile.write(f"#{j} {line}")
929 parts = line.split(b"->")[-1].strip().split()
930 clip = parts.pop() == b"(clip)"
931 if clip:
932 parts.pop()
933 j += 1
934 else:
935 parts = line.split()
936 if reverse:
937 parts = reversed(parts)
938 if not output_format:
939 out = [devop_devo(float(v) / output_scale) for v in parts]
940 if get_clip and not self.show_actual_if_clipped:
941 out.append(clip)
942 else:
943 out = b"".join(
944 struct.pack(fmt, round(devop_devo(float(v) / scale) * maxv))
945 for v in parts
946 )
947 parsed.append(out)
948 if self.sessionlogfile:
949 self.sessionlogfile.close()
950 return parsed
951
952 @property
953 def subprocess_abort(self):
954 """Get the subprocess abort flag.
955
956 Returns:
957 bool: True if the subprocess abort flag is set, False otherwise.
958 """
959 if self.worker:
960 return self.worker.subprocess_abort
961 return False
962
963 @subprocess_abort.setter
964 def subprocess_abort(self, v):
965 """Set the subprocess abort flag.
966
967 Args:
968 v (bool): If True, set the subprocess abort flag to signal
969 that the subprocess should be aborted.
970 """
971
972 @property
973 def thread_abort(self):
974 """Get the thread abort event.
975
976 Returns:
977 ThreadAbort: The thread abort event, which can be used to signal
978 that the thread should be aborted.
979 """
980 if self.worker:
981 return self.worker.thread_abort
982 return None
983
984 @thread_abort.setter
985 def thread_abort(self, v):
986 """Set the thread abort event.
987
988 Args:
989 v (bool): If True, set the thread abort event to signal
990 that the thread should be aborted.
991 """
992
993
994 class XiccluMP(Xicclu):
995 """Xicclu multiprocessing worker.
996
997 Args:
998 profile (ICCProfile): The ICC profile to use.
999 intent (str): The rendering intent to use (default: "r").
1000 direction (str): The direction of the transformation (default: "f").
1001 order (str): The order of the transformation (default: "n").
1002 pcs (str): The PCS to use (default: None).
1003 scale (int): The scale factor for the transformation (default: 1).
1004 cwd (str): The current working directory (default: None).
1005 startupinfo: Startup information for subprocesses (default: None).
1006 use_icclu (bool): Whether to use icclu instead of xicclu (default: False).
1007 use_cam_clipping (bool): Whether to use CAM clipping (default: False).
1008 logfile: Log file for output messages (default: None).
1009 worker: Worker instance for multiprocessing (default: None).
1010 show_actual_if_clipped (bool): Whether to show actual values if clipped
1011 (default: False).
1012 input_encoding (str): Input encoding for xicclu (default: None).
1013 output_encoding (str): Output encoding for xicclu (default: None).
1014 output_format (tuple): Output format for xicclu results
1015 (default: None).
1016 reverse (bool): Whether to reverse the output order
1017 (default: False).
1018 output_stream: Stream to write output to, if any
1019 (default: None).
1020 convert_video_rgb_to_clut65 (bool): Whether to convert video RGB
1021 values to cLUT65 format.
1022 verbose (int): Verbosity level for logging.
1023 """
1024
1025 def __init__(
1026 self,
1027 profile,
1028 intent="r",
1029 direction="f",
1030 order="n",
1031 pcs=None,
1032 scale=1,
1033 cwd=None,
1034 startupinfo=None,
1035 use_icclu=False,
1036 use_cam_clipping=False,
1037 logfile=None,
1038 worker=None,
1039 show_actual_if_clipped=False,
1040 input_encoding=None,
1041 output_encoding=None,
1042 output_format=None,
1043 reverse=False,
1044 output_stream=None,
1045 convert_video_rgb_to_clut65=False,
1046 verbose=1,
1047 ):
1048 WorkerBase.__init__(self)
1049 self.logfile = logfile
1050 self.worker = worker
1051 self.output_stream = output_stream
1052 self._in = []
1053 self._args = (
1054 profile.filename,
1055 intent,
1056 direction,
1057 order,
1058 pcs,
1059 scale,
1060 cwd,
1061 startupinfo,
1062 use_icclu,
1063 use_cam_clipping,
1064 None,
1065 show_actual_if_clipped,
1066 input_encoding,
1067 output_encoding,
1068 lang.getstr("aborted"),
1069 output_format,
1070 reverse,
1071 convert_video_rgb_to_clut65,
1072 verbose,
1073 )
1074 self._out = []
1075
1076 num_cpus = min(mp.cpu_count(), MAX_CPUS)
1077 if isinstance(profile.tags.get("A2B0"), LUT16Type):
1078 size = profile.tags.A2B0.clut_grid_steps
1079 self.num_workers = min(max(num_cpus, 1), size)
1080 if num_cpus > 2:
1081 self.num_workers = int(self.num_workers * 0.75)
1082 self.num_batches = size // 9
1083 else:
1084 if num_cpus > 2:
1085 self.num_workers = 2
1086 else:
1087 self.num_workers = num_cpus
1088 self.num_batches = 1
1089
1090 def __call__(self, idata):
1091 """Call the xicclu worker with input data.
1092
1093 Args:
1094 idata (list): Input data to be processed by the xicclu worker.
1095 """
1096 self._in.append(idata)
1097
1098 def close(self, raise_exception=True):
1099 """Close the xicclu worker process.
1100
1101 Args:
1102 raise_exception (bool): If True, raise an exception if the worker
1103 has errors.
1104 """
1105
1106 def exit(self, raise_exception=True):
1107 """Exit the xicclu worker process.
1108
1109 Args:
1110 raise_exception (bool): If True, raise an exception if the worker
1111 has errors.
1112 """
1113
1114 def spawn(self):
1115 """Spawn the xicclu worker process."""
1116
1117 def get(self, raw=False, get_clip=False, output_format=None, reverse=False):
1118 """Get the output from the xicclu worker.
1119
1120 Args:
1121 raw (bool): If True, return raw output as a list of strings.
1122 get_clip (bool): If True, include clipping information in the
1123 output.
1124 output_format (tuple): A tuple specifying the output format.
1125 reverse (bool): If True, reverse the order of the output.
1126
1127 Returns:
1128 list: The processed output from the xicclu worker, either as raw
1129 strings or formatted data.
1130 """
1131 for slices in pool_slice(
1132 _xicclu_mp,
1133 self._in,
1134 self._args,
1135 {},
1136 self.num_workers,
1137 self.thread_abort,
1138 self.logfile,
1139 num_batches=self.num_batches,
1140 ):
1141 if self.output_stream:
1142 for row in slices:
1143 self.output_stream.write(row)
1144 else:
1145 self._out.extend(slices)
1146 return self._out