Debian Codegraph @

DisplayCAL/eecolor_to_madvr.py

raw
1 """Convert eeColor 65^3 3D LUTs to madVR 256^3 3D LUTs (video levels in/out).
2
3 Command-line tool. Author of the original conversion algorithm: Florian
4 Hoech, licensed under the GPL version 3.
5 """
6
7 from __future__ import annotations
8
9 import multiprocessing as mp
10 import os
11 import signal
12 import sys
13
14 from DisplayCAL import config
15 from DisplayCAL.icc_profile import (
16 ICCProfile,
17 LUT16Type,
18 TextDescriptionType,
19 TextType,
20 )
21 from DisplayCAL.madvr import icc_device_link_to_madvr
22 from DisplayCAL.safe_print import safe_print
23
24
25 def _sigbreak_handler(sig, frame) -> None:
26 sys._sigbreak = True
27
28
29 def eecolor_to_icc_devicelink(eecolor_3dlut_filename: str, unity: bool = False) -> str:
30 """Convert an eeColor 3D LUT text file to an ICC device link profile.
31
32 Args:
33 eecolor_3dlut_filename (str): Filename of the eeColor 3D LUT file.
34 unity (bool, optional): Skip conversion, only compute the output
35 filename. Default is False.
36
37 Returns:
38 str: Filename of the (written) ICC device link profile.
39 """
40 filename, ext = os.path.splitext(eecolor_3dlut_filename)
41 icc_filename = filename + ".icc"
42
43 if not unity:
44 # Read in eeColor 3D LUT data
45 safe_print("Reading in eeColor 3D LUT", '"%s"' % eecolor_3dlut_filename)
46 eecolor_3dlut_data = []
47 with open(eecolor_3dlut_filename, "rb") as eecolor_3dlut:
48 for line in eecolor_3dlut:
49 line = line.strip().decode()
50 if not line or line.startswith("#"):
51 continue
52 values = [float(v) for v in line.split()]
53 eecolor_3dlut_data.append(values)
54
55 clutres = int(round(len(eecolor_3dlut_data) ** (1.0 / 3.0)))
56 clutmax = clutres - 1.0
57
58 # Fix input values (eeColor BRG) so sorting produces correct result
59 n = 0
60 for B in range(clutres):
61 for R in range(clutres):
62 for G in range(clutres):
63 eecolor_3dlut_data[n][:3] = (v / clutmax for v in (R, G, B))
64 n += 1
65
66 # Sort eeColor 3D LUT data
67 # (fastest increasing column from right to left: B -> G -> R)
68 eecolor_3dlut_data.sort()
69
70 # Create ICC device link profile from eeColor 3D LUT data
71 safe_print("Creating device link from eeColor 3D LUT data...")
72 link = ICCProfile()
73 link.connectionColorSpace = b"RGB"
74 link.profileClass = b"link"
75 link.tags.desc = TextDescriptionType()
76 link.tags.desc.ASCII = os.path.basename(filename)
77 link.tags.cprt = TextType(b"text\0\0\0\0No copyright", b"cprt")
78 link.tags.A2B0 = LUT16Type()
79 link.tags.A2B0.input = link.tags.A2B0.output = [[0, 65535]] * 3
80 link.tags.A2B0.matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
81 link.tags.A2B0.clut = []
82
83 # Fill cLUT
84 row = 0
85 for _a in range(clutres):
86 for _b in range(clutres):
87 link.tags.A2B0.clut.append([])
88 for _c in range(clutres):
89 values = [v * 65535 for v in eecolor_3dlut_data[row][3:]]
90 link.tags.A2B0.clut[-1].append(values)
91 row += 1
92
93 # Write device link
94 link.write(icc_filename)
95
96 return icc_filename
97
98
99 def eecolor_to_madvr(
100 eecolor_3dlut_filename,
101 unity=False,
102 colorspace=None,
103 hdr=None,
104 logfile=sys.stdout,
105 convert_video_rgb_to_clut65=False,
106 append_linear_cal=True,
107 ):
108 """Convert eeColor 65^3 3D LUT to madVR 256^3 3D LUT using interpolation.
109
110 madVR 3D LUT will be written to:
111 <eeColor 3D LUT filename without extension> + '.3dlut'
112 """
113 icc_filename = eecolor_to_icc_devicelink(eecolor_3dlut_filename, unity)
114
115 return icc_device_link_to_madvr(
116 icc_filename,
117 unity=unity,
118 colorspace=colorspace,
119 hdr=hdr,
120 logfile=logfile,
121 convert_video_rgb_to_clut65=convert_video_rgb_to_clut65,
122 append_linear_cal=append_linear_cal,
123 )
124
125
126 def main() -> None:
127 """Entry point for the eeColor to madVR 3D LUT converter CLI."""
128 mp.freeze_support()
129 # SIGBREAK is Windows only. Use SIGINT as fallback
130 signal.signal(getattr(signal, "SIGBREAK", signal.SIGINT), _sigbreak_handler)
131
132 result = None
133 if sys.argv[1:] and "--help" not in sys.argv[1:]:
134 config.initcfg()
135 colorspace = None
136 hdr = None
137 for arg in sys.argv[1:]:
138 if arg.lower().endswith(".txt"):
139 fn = eecolor_to_madvr
140 elif arg.lower().endswith(".icc") or arg.lower().endswith(".icm"):
141 fn = icc_device_link_to_madvr
142 else:
143 if arg.startswith("--colorspace="):
144 colorspace = [float(v) for v in arg[13:].split(",")]
145 if arg.startswith("--hdr="):
146 hdr = int(arg[6:])
147 continue
148 if not os.path.isabs(arg):
149 arg = os.path.abspath(arg)
150 if not os.path.isfile(arg) and "--unity" not in sys.argv[1:]:
151 safe_print("Error: File not found:", arg)
152 result = False
153 break
154 if result is not None:
155 # Already processed some input file(s)
156 safe_print("")
157 try:
158 result = fn(
159 arg,
160 unity="--unity" in sys.argv[1:],
161 colorspace=colorspace,
162 hdr=hdr,
163 convert_video_rgb_to_clut65="--convert-video-rgb-to-clut65"
164 in sys.argv[1:],
165 append_linear_cal="--append-linear-cal" in sys.argv[1:],
166 )
167 except Exception as exception:
168 safe_print(exception)
169 result = exception
170 if result is None:
171 safe_print("No filename given.")
172 else:
173 safe_print(
174 "Convert eeColor 65^3 to madVR 256^3 3D LUT (video levels in, video levels out)"
175 )
176 safe_print("Author: Florian Hoech, licensed under the GPL version 3")
177 safe_print(
178 "Usage: %s [--unity] [--batch] <name>.<target color space>.txt"
179 % os.path.basename(sys.argv[0])
180 )
181 safe_print(
182 "Possible target color spaces: BT709, SMPTE_C, EBU_PAL, BT2020, DCI_P3"
183 )
184 safe_print("Write output to <name>.<target color space>.3dlut")
185 safe_print("")
186 safe_print(" --unity Create unity (in = out) 3D LUT")
187 safe_print(" --append-linear-cal Append linear calibration")
188 safe_print(" --batch Don't pause after processing")
189 safe_print("")
190 safe_print("Examples:")
191 safe_print(" Convert SDR BT709 eeColor 3D LUT")
192 safe_print(" %s eeColor.BT709.txt" % os.path.basename(sys.argv[0]))
193 safe_print("")
194 safe_print(" Convert HDR BT2020 eeColor 3D LUT")
195 safe_print(" %s eeColor.BT2020.HDR.txt" % os.path.basename(sys.argv[0]))
196 safe_print("")
197 safe_print(" Convert HDR to SDR BT2020 eeColor 3D LUT")
198 safe_print(" %s eeColor.BT2020.HDR2SDR.txt" % os.path.basename(sys.argv[0]))
199 if sys.stdout.isatty() and "--batch" not in sys.argv[1:]:
200 input("Press RETURN to exit")
201 sys.exit(int(not result))
202
203
204 if __name__ == "__main__":
205 main()