Debian Codegraph @

DisplayCAL/imfile.py

raw
1 """Write image data to TIFF, PNG, or DPX files.
2
3 Supports 8-bit and 16-bit image data, optimized for single-color or
4 specific-dimension images.
5 """
6
7 from __future__ import annotations
8
9 import math
10 import os
11 import struct
12 import time
13 import zlib
14 from typing import BinaryIO
15
16 from DisplayCAL.meta import NAME as APPNAME
17 from DisplayCAL.meta import VERSION_STRING
18 from DisplayCAL.util_str import safe_str
19
20 TIFF_TAG_TYPE_BYTE = 1
21 TIFF_TAG_TYPE_ASCII = 2
22 TIFF_TAG_TYPE_WORD = 3
23 TIFF_TAG_TYPE_DWORD = 4
24 TIFF_TAG_TYPE_RATIONAL = 5 # 2 DWORDs
25
26
27 def tiff_get_header(w: int, h: int, samples_per_pixel: int, bitdepth: int) -> bytes:
28 """Return TIFF header for given width, height, samples per pixel and bitdepth.
29
30 Args:
31 w (int): Width of the image.
32 h (int): Height of the image.
33 samples_per_pixel (int): Number of samples per pixel.
34 bitdepth (int): Bit depth of the image.
35
36 Returns:
37 bytes: TIFF header as bytes.
38 """
39 # Very helpful: http://www.fileformat.info/format/tiff/corion.htm
40
41 header = []
42 header.append(b"MM\0*") # Note: We use big-endian byte order
43
44 # Offset of image directory
45 header.append(b"\0\0\0\x08")
46
47 pixelcount = w * h * samples_per_pixel
48 bytecount = pixelcount * 2 if bitdepth == 16 else pixelcount
49
50 # Image file directory (IFD)
51
52 # PhotometricInterpretation
53 # RGB if samples_per_pixel == 3 else Separated (usually CMYK)
54 pmi = 2 if samples_per_pixel == 3 else 5
55
56 # Tag, type, length, offset or data, is data (otherwise offset)
57 tag_type_w = TIFF_TAG_TYPE_DWORD if w > 65535 else TIFF_TAG_TYPE_WORD
58 tag_type_h = TIFF_TAG_TYPE_DWORD if h > 65535 else TIFF_TAG_TYPE_WORD
59 ifd = [
60 (0x100, tag_type_w, 1, w, True), # ImageWidth
61 (0x101, tag_type_h, 1, h, True), # ImageLength
62 (0x106, TIFF_TAG_TYPE_WORD, 1, pmi, True), # PhotometricInterpretation
63 (0x115, TIFF_TAG_TYPE_WORD, 1, samples_per_pixel, True), # SamplesPerPixel
64 (0x117, TIFF_TAG_TYPE_DWORD, 1, bytecount, True), # StripByteCounts
65 ]
66 # BitsPerSample
67 ifd.append((0x102, TIFF_TAG_TYPE_WORD, 3, 10 + (len(ifd) + 2) * 12 + 4, False))
68 # StripOffsets
69 ifd.append((0x111, TIFF_TAG_TYPE_WORD, 1, 10 + (len(ifd) + 1) * 12 + 4 + 6, True))
70
71 ifd.sort() # Must be ascending order!
72
73 header.append(struct.pack(">H", len(ifd))) # Number of entries
74
75 for tag, tagtype, length, payload, is_data in ifd:
76 header.append(struct.pack(">H", tag))
77 header.append(struct.pack(">H", tagtype))
78 header.append(struct.pack(">I", length))
79 if is_data and tagtype == 3:
80 # A word left-aligned in a dword
81 header.append(struct.pack(">H", payload))
82 header.append(b"\0\0")
83 else:
84 header.append(struct.pack(">I", payload))
85
86 # PlanarConfiguration default is 1 = RGBRGBRGB...
87
88 # End of IFD
89 header.append(b"\0" * 4)
90
91 # BitsPerSample (6 bytes)
92 header.append(struct.pack(">H", bitdepth) * 3)
93
94 return b"".join(header)
95
96
97 def write(
98 data: list,
99 stream_or_filename: str | BinaryIO,
100 bitdepth: int = 16,
101 file_format: None | str = None,
102 dimensions: None | tuple[int, int] = None,
103 extrainfo: None | dict = None,
104 ) -> None:
105 """Write image data to a file.
106
107 Args:
108 data (list): The image data to write.
109 stream_or_filename (str | BinaryIO): The output filename or stream.
110 bitdepth (int, optional): The bit depth of the image (default: 16).
111 file_format (None | str, optional): The file format to use (default:
112 None, which infers from filename).
113 dimensions (None | tuple[int, int]): The dimensions of the image
114 (width, height).
115 extrainfo (None | dict, optional): Additional information for the image.
116 """
117 Image(data, bitdepth, extrainfo).write(stream_or_filename, file_format, dimensions)
118
119
120 def write_rgb_clut(
121 stream_or_filename: str | BinaryIO,
122 clutres: int = 33,
123 bitdepth: int = 16,
124 file_format: None | str = None,
125 ) -> None:
126 """Write a color lookup table (CLUT) to a file.
127
128 Args:
129 stream_or_filename (str | BinaryIO): The output file or stream.
130 clutres (int, optional): The resolution of the CLUT (default: 33).
131 bitdepth (int, optional): The bit depth of the CLUT (default: 16).
132 file_format (str, optional): The file format to use (default: None,
133 which infers from filename).
134 """
135 clut = []
136 for r in range(clutres):
137 for g in range(clutres):
138 clut.append([])
139 for b in range(clutres):
140 rgb = [v * (1.0 / (clutres - 1)) for v in (r, g, b)]
141 clut[-1].append([v * (2**bitdepth - 1) for v in rgb])
142 write(clut, stream_or_filename, bitdepth, file_format)
143
144
145 class Image:
146 """Write 8 or 16 bit image files in DPX, PNG or TIFF format.
147
148 Writing of single color images is highly optimized when using a single
149 pixel as image data and setting dimensions explicitly.
150
151 Args:
152 data (list): The image data to write, structured as a list of scanlines,
153 where each scanline is a list of RGB tuples.
154 bitdepth (int): The bit depth of the image (default: 16).
155 extrainfo (dict): Additional information for the image, such as
156 dimensions, offsets, and metadata.
157 """
158
159 def __init__(
160 self, data: list, bitdepth: int = 16, extrainfo: None | dict = None
161 ) -> None:
162 self.bitdepth = bitdepth
163 self.data = data
164 self.extrainfo = extrainfo or {}
165
166 def _pack(self, n: float) -> bytes:
167 """Pack a single sample value into bytes according to the bit depth.
168
169 Args:
170 n (float): The sample value to pack.
171
172 Raises:
173 ValueError: If the bit depth is unsupported.
174
175 Returns:
176 bytes: The packed sample value as bytes.
177 """
178 n = round(n)
179 if self.bitdepth == 16:
180 data = struct.pack(">H", n)
181 elif self.bitdepth == 8:
182 data = n.to_bytes(1, "big")
183 else:
184 raise ValueError(f"Unsupported bitdepth: {self.bitdepth!r}")
185 return data
186
187 def _write_dpx(
188 self, stream: BinaryIO, dimensions: None | tuple[int, int] = None
189 ) -> None:
190 """Write image data to a DPX file.
191
192 Args:
193 stream (BinaryIO): The output stream to write to.
194 dimensions (None | tuple[int, int], optional): The dimensions of
195 the image (width, height). When `None`, dimensions are inferred
196 from the data. If the data is a single pixel, dimensions should
197 be provided explicitly for optimization.
198 """
199 # Very helpful: http://www.fileformat.info/format/dpx/egff.htm
200 # http://www.simplesystems.org/users/bfriesen/dpx/S268M_Revised.pdf
201
202 # Generic file header (768 bytes)
203 stream.write(b"SDPX") # Magic number
204 stream.write(struct.pack(">I", 8192)) # Offset to image data
205 stream.write(b"V2.0\0\0\0\0") # ASCII version
206
207 # Optimize for single color
208 optimize = len(self.data) == 1 and len(self.data[0]) == 1 and dimensions
209
210 # Image data
211 imgdata = []
212 # 10-bit code adapted from GraphicsMagick dpx.c:WriteSamples
213 if self.bitdepth == 10:
214 shifts = (22, 12, 2) # RGB
215 for _i, scanline in enumerate(self.data):
216 if self.bitdepth == 10:
217 packed = []
218 for RGB in scanline: # noqa: N806
219 packed_u32 = 0
220 for datum, sample in enumerate(RGB):
221 packed_u32 |= sample << shifts[datum]
222 packed.append(struct.pack(">I", packed_u32))
223 scanline = b"".join(packed)
224 else:
225 scanline = b"".join(
226 b"".join(self._pack(v) for v in RGB) for RGB in scanline
227 )
228 if not optimize:
229 # Pad lines with binary zeros so they end on 4-byte boundaries
230 scanline = scanline.ljust(math.ceil(len(scanline) / 4.0) * 4, b"\0")
231 imgdata.append(scanline)
232 imgdata = "".join(imgdata)
233 if optimize:
234 # Optimize for single color
235 imgdata *= dimensions[0]
236 # Pad lines with binary zeros so they end on 4-byte boundaries
237 imgdata = imgdata.ljust(math.ceil(len(imgdata) / 4.0) * 4, b"\0")
238 imgdata *= dimensions[1]
239 w, h = dimensions
240 else:
241 w, h = len(self.data[0]), len(self.data)
242
243 # Generic file header (cont.)
244 stream.write(struct.pack(">I", 8192 + len(imgdata))) # File size
245 stream.write(b"\0\0\0\1") # DittoKey (1 = not same as previous frame)
246 stream.write(
247 struct.pack(">I", 768 + 640 + 256)
248 ) # Generic section header length
249 stream.write(
250 struct.pack(">I", 256 + 128)
251 ) # Industry-specific section header length
252 stream.write(struct.pack(">I", 0)) # User-defined data length
253 stream.write(safe_str(stream.name or b"").ljust(100, b"\0")[-100:]) # File name
254 # Date & timestamp
255 tzoffset = round(
256 (time.mktime(time.localtime()) - time.mktime(time.gmtime())) / 60.0 / 60.0
257 )
258 tzoffset = b"%.2i" % tzoffset if tzoffset < 0 else b"+%.2i" % tzoffset
259 stream.write(
260 time.strftime("%Y:%m:%d:%H:%M:%S").encode() + tzoffset.encode() + b"\0\0"
261 )
262 stream.write(
263 safe_str(f"{APPNAME} {VERSION_STRING}".encode()).ljust(100, b"\0")
264 ) # Creator
265 stream.write(b"\0" * 200) # Project
266 stream.write(b"\0" * 200) # Copyright
267 stream.write(b"\xff" * 4) # EncryptKey 0xffffffff = not encrypted
268 stream.write(b"\0" * 104) # Reserved
269
270 # Generic image header (640 bytes)
271 stream.write(b"\0\0") # Orientation 0 = left to right, top to bottom
272 stream.write(b"\0\1") # Number of image elements
273 stream.write(struct.pack(">I", w)) # Pixels per line
274 stream.write(struct.pack(">I", h)) # Lines per image element
275
276 # Generic image header - image element
277 stream.write(b"\0" * 4) # 0 = unsigned data
278 stream.write(b"\0" * 4) # Reference low data code value
279 stream.write(b"\xff" * 4) # Reference low quantity
280 stream.write(
281 struct.pack(">I", 2**self.bitdepth - 1)
282 ) # Reference high data code value
283 stream.write(b"\xff" * 4) # Reference high quantity
284 stream.write(chr(50).encode()) # Descriptor 50 = RGB
285 stream.write(b"\2") # Transfer 2 = linear
286 stream.write(b"\2") # Colorimetric 2 = not applicable
287 stream.write(chr(self.bitdepth).encode()) # BitSize
288 stream.write(b"\0\1") # Packing 1 = filled 32-bit words
289 stream.write(b"\0\0") # Encoding 0 = not encoded
290 stream.write(struct.pack(">I", 8192)) # Image data offset
291 stream.write(b"\0" * 4) # End of line padding
292 stream.write(b"\0" * 4) # End of image padding
293 stream.write(b"RGB / Linear".ljust(32, b"\0")) # Description
294
295 # Seven additional unused image elements
296 stream.write(b"\0" * 72 * 7)
297
298 # Generic image header (cont.)
299 stream.write(b"\0" * 52) # Reserved
300
301 # Generic image source header (256 bytes)
302 sw = self.extrainfo.get("original_width", w)
303 sh = self.extrainfo.get("original_height", h)
304
305 # X offset
306 stream.write(struct.pack(">I", self.extrainfo.get("offset_x", (sw - w) / 2)))
307 # Y offset
308 stream.write(struct.pack(">I", self.extrainfo.get("offset_y", (sh - h) / 2)))
309 # X center
310 stream.write(struct.pack(">f", self.extrainfo.get("center_x", sw / 2.0)))
311 # Y center
312 stream.write(struct.pack(">f", self.extrainfo.get("center_y", sh / 2.0)))
313 stream.write(struct.pack(">I", sw)) # X original size
314 stream.write(struct.pack(">I", sh)) # Y original size
315 stream.write(b"\0" * 100) # Source image file name
316 stream.write(b"\0" * 24) # Source image date & timestamp
317 stream.write(b"\0" * 32) # Input device name
318 stream.write(b"\0" * 32) # Input device serial number
319 stream.write(b"\0" * 2 * 4) # Border
320 stream.write(b"\0\0\0\1" * 2) # Pixel aspect ratio
321 stream.write(b"\xff" * 4) # X scanned size
322 stream.write(b"\xff" * 4) # Y scanned size
323 stream.write(b"\0" * 20) # Reserved
324
325 # Industry-specific film info header (256 bytes)
326 stream.write(b"\0" * 2) # Film mfg. ID code
327 stream.write(b"\0" * 2) # Film type
328 stream.write(b"\0" * 2) # Offset in perfs
329 stream.write(b"\0" * 6) # Prefix
330 stream.write(b"\0" * 4) # Count
331 stream.write(b"\0" * 32) # Format
332 # Frame position in sequence
333 stream.write(struct.pack(">I", self.extrainfo.get("frame_position", 2**32 - 1)))
334 # Sequence length
335 stream.write(
336 struct.pack(">I", self.extrainfo.get("sequence_length", 2**32 - 1))
337 )
338 # Held count
339 stream.write(struct.pack(">I", self.extrainfo.get("held_count", 1)))
340 # Frame rate of original
341 if "frame_rate" in self.extrainfo:
342 stream.write(struct.pack(">f", self.extrainfo["frame_rate"]))
343 else:
344 stream.write(b"\xff" * 4)
345 # Shutter angle of camera in degrees
346 stream.write(b"\xff" * 4)
347 stream.write(b"\0" * 32) # Frame identification - e.g. keyframe
348 stream.write(b"\0" * 100) # Slate
349 stream.write(b"\0" * 56) # Reserved
350
351 # Industry-specific TV info header (128 bytes)
352 # SMPTE time code
353 stream.write(
354 b"".join(
355 chr(int(str(v), 16)).encode()
356 for v in self.extrainfo.get("timecode", [b"ff"] * 4)
357 )
358 )
359 stream.write(b"\xff" * 4) # User bits
360 stream.write(b"\xff") # Interlace
361 stream.write(b"\xff") # Field number
362 stream.write(b"\xff") # Video signal standard
363 stream.write(b"\0") # Zero for byte alignment
364 stream.write(b"\xff" * 4) # H sampling rate Hz
365 stream.write(b"\xff" * 4) # V sampling rate Hz
366 # Temporal sampling or frame rate Hz
367 if "frame_rate" in self.extrainfo:
368 stream.write(struct.pack(">f", self.extrainfo["frame_rate"]))
369 else:
370 stream.write(b"\xff" * 4)
371 stream.write(b"\xff" * 4) # Time offset in ms from sync to 1st pixel
372 stream.write(b"\xff" * 4) # Gamma
373 stream.write(b"\xff" * 4) # Black level code value
374 stream.write(b"\xff" * 4) # Black gain
375 stream.write(b"\xff" * 4) # Breakpoint
376 stream.write(b"\xff" * 4) # Reference white level code value
377 stream.write(b"\xff" * 4) # Integration time in s
378 stream.write(b"\0" * 76) # Reserved
379
380 # Padding so image data begins at 8K boundary
381 stream.write("\0" * 6144)
382
383 # Write image data
384 stream.write(imgdata)
385
386 def _write_png(
387 self, stream: BinaryIO, dimensions: None | tuple[int, int] = None
388 ) -> None:
389 """Write image data to a PNG file.
390
391 Args:
392 stream (BinaryIO): The output stream to write to.
393 dimensions (None | tuple[int, int], optional): The dimensions of
394 the image (width, height). When `None`, dimensions are inferred
395 from the data. If the data is a single pixel, dimensions should
396 be provided explicitly for optimization.
397 """
398 # Header
399 stream.write(b"\x89PNG\r\n\x1a\n")
400 # IHDR image header length
401 stream.write(struct.pack(">I", 13))
402 # IHDR image header chunk type
403 ihdr = [b"IHDR"]
404 # Optimize for single color
405 optimize = len(self.data) == 1 and len(self.data[0]) == 1 and dimensions
406 # IHDR: width, height
407 if optimize:
408 w, h = dimensions
409 else:
410 w, h = len(self.data[0]), len(self.data)
411 ihdr.extend([struct.pack(">I", w), struct.pack(">I", h)])
412 # IHDR: Bit depth
413 ihdr.append(self.bitdepth.to_bytes(1, "big"))
414 # IHDR: Color type 2 (truecolor)
415 ihdr.append(b"\2")
416 # IHDR: Compression method 0 (deflate)
417 ihdr.append(b"\0")
418 # IHDR: Filter method 0 (adaptive)
419 ihdr.append(b"\0")
420 # IHDR: Interlace method 0 (none)
421 ihdr.append(b"\0")
422 ihdr = b"".join(ihdr)
423 stream.write(ihdr)
424 stream.write(struct.pack(">I", zlib.crc32(ihdr) & 0xFFFFFFFF))
425 # IDAT image data chunk type
426 imgdata = []
427 for _i, scanline in enumerate(self.data):
428 # Add a scanline, filter type 0
429 imgdata.append(b"\0")
430 for RGB in scanline: # noqa: N806
431 RGB = b"".join(self._pack(v) for v in RGB) # noqa: N806
432 if optimize:
433 RGB *= dimensions[0] # noqa: N806
434 imgdata.append(RGB)
435 imgdata = b"".join(imgdata)
436 if optimize:
437 imgdata *= dimensions[1]
438 imgdata = zlib.compress(imgdata, 9)
439 stream.write(struct.pack(">I", len(imgdata)))
440 idat = [b"IDAT"]
441 idat.append(imgdata)
442 idat = b"".join(idat)
443 stream.write(idat)
444 stream.write(struct.pack(">I", zlib.crc32(idat) & 0xFFFFFFFF))
445 # IEND chunk
446 stream.write(b"\0" * 4)
447 stream.write(b"IEND")
448 stream.write(struct.pack(">I", zlib.crc32(b"IEND") & 0xFFFFFFFF))
449
450 def _write_tiff(
451 self, stream: BinaryIO, dimensions: None | tuple[int, int] = None
452 ) -> None:
453 """Write image data to a TIFF file.
454
455 Args:
456 stream (BinaryIO): The output stream to write to.
457 dimensions (None | tuple[int, int], optional): The dimensions of
458 the image (width, height). When `None`, dimensions are inferred
459 from the data. If the data is a single pixel, dimensions should
460 be provided explicitly for optimization.
461 """
462 # Very helpful: http://www.fileformat.info/format/tiff/corion.htm
463
464 # Image data
465 if len(self.data) == 1 and len(self.data[0]) == 1 and dimensions:
466 # Optimize for single color
467 w, h = dimensions
468 imgdata = list(self.data)
469 imgdata[0] *= w
470 imgdata *= h
471 else:
472 imgdata = self.data
473 w, h = len(self.data[0]), len(self.data)
474
475 samples_per_pixel = len(self.data[0][0])
476
477 # Header
478 stream.write(tiff_get_header(w, h, samples_per_pixel, self.bitdepth))
479
480 # Write image data
481 for _i, scanline in enumerate(imgdata):
482 for sample in scanline:
483 stream.write(b"".join(self._pack(v) for v in sample))
484
485 def write(
486 self,
487 stream_or_filename: str | BinaryIO,
488 file_format: None | str = None,
489 dimensions: None | tuple[int, int] = None,
490 ) -> None:
491 """Write the image data to a file or stream.
492
493 Args:
494 stream_or_filename (str | BinaryIO): The output file name or stream.
495 file_format (None | str, optional): The file format to use.
496 Defaults to None, which infers from filename).
497 dimensions (None | tuple[int, int], optional): The dimensions of
498 the image (width, height).
499
500 Raises:
501 ValueError: If the specified file format is unsupported.
502 """
503 if not file_format:
504 if isinstance(stream_or_filename, str):
505 file_format = (
506 os.path.splitext(stream_or_filename)[1].lstrip(".").upper()
507 )
508 if file_format == "TIF":
509 file_format += "F"
510 else:
511 file_format = "PNG"
512 if not hasattr(self, f"_write_{file_format.lower()}"):
513 raise ValueError(f"Unsupported format: {file_format!r}")
514 if isinstance(stream_or_filename, str):
515 stream = open(stream_or_filename, "wb") # noqa: SIM115
516 else:
517 stream = stream_or_filename
518 with stream:
519 getattr(self, f"_write_{file_format.lower()}")(stream, dimensions)