torchcodec 1.0.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. torchcodec/__init__.py +50 -0
  2. torchcodec/_core/AVIOContextHolder.cpp +85 -0
  3. torchcodec/_core/AVIOContextHolder.h +44 -0
  4. torchcodec/_core/AudioCommon.cpp +101 -0
  5. torchcodec/_core/AudioCommon.h +48 -0
  6. torchcodec/_core/AudioConverter.cpp +130 -0
  7. torchcodec/_core/AudioConverter.h +59 -0
  8. torchcodec/_core/BetaCudaDeviceInterface.cpp +1635 -0
  9. torchcodec/_core/BetaCudaDeviceInterface.h +364 -0
  10. torchcodec/_core/CMakeLists.txt +661 -0
  11. torchcodec/_core/CUDACommon.cpp +129 -0
  12. torchcodec/_core/CUDACommon.h +115 -0
  13. torchcodec/_core/Cache.h +126 -0
  14. torchcodec/_core/CodecParameters.cpp +98 -0
  15. torchcodec/_core/CodecParameters.h +59 -0
  16. torchcodec/_core/ColorConverter.cpp +92 -0
  17. torchcodec/_core/ColorConverter.h +40 -0
  18. torchcodec/_core/CpuDeviceInterface.cpp +654 -0
  19. torchcodec/_core/CpuDeviceInterface.h +153 -0
  20. torchcodec/_core/CudaDeviceInterface.cpp +519 -0
  21. torchcodec/_core/CudaDeviceInterface.h +92 -0
  22. torchcodec/_core/DecodeAvif.cpp +284 -0
  23. torchcodec/_core/DecodeAvif.h +28 -0
  24. torchcodec/_core/DecodeGif.cpp +488 -0
  25. torchcodec/_core/DecodeGif.h +32 -0
  26. torchcodec/_core/DecodeHeic.cpp +306 -0
  27. torchcodec/_core/DecodeHeic.h +18 -0
  28. torchcodec/_core/DecodeJpeg.cpp +489 -0
  29. torchcodec/_core/DecodeJpeg.h +17 -0
  30. torchcodec/_core/DecodeJpegCuda.cpp +638 -0
  31. torchcodec/_core/DecodeJpegCuda.h +92 -0
  32. torchcodec/_core/DecodePng.cpp +569 -0
  33. torchcodec/_core/DecodePng.h +31 -0
  34. torchcodec/_core/DecodeWebp.cpp +238 -0
  35. torchcodec/_core/DecodeWebp.h +17 -0
  36. torchcodec/_core/Demuxer.cpp +415 -0
  37. torchcodec/_core/Demuxer.h +158 -0
  38. torchcodec/_core/DeviceInterface.cpp +152 -0
  39. torchcodec/_core/DeviceInterface.h +255 -0
  40. torchcodec/_core/EncodeJpeg.cpp +223 -0
  41. torchcodec/_core/EncodeJpeg.h +19 -0
  42. torchcodec/_core/EncodeJpegCuda.cpp +272 -0
  43. torchcodec/_core/EncodeJpegCuda.h +56 -0
  44. torchcodec/_core/EncodePng.cpp +207 -0
  45. torchcodec/_core/EncodePng.h +19 -0
  46. torchcodec/_core/Encoder.cpp +1023 -0
  47. torchcodec/_core/Encoder.h +144 -0
  48. torchcodec/_core/Exif.h +241 -0
  49. torchcodec/_core/FFMPEGCommon.cpp +1159 -0
  50. torchcodec/_core/FFMPEGCommon.h +506 -0
  51. torchcodec/_core/FileIO.cpp +78 -0
  52. torchcodec/_core/FileIO.h +34 -0
  53. torchcodec/_core/FileLikeIO.cpp +76 -0
  54. torchcodec/_core/FileLikeIO.h +68 -0
  55. torchcodec/_core/FilterGraph.cpp +211 -0
  56. torchcodec/_core/FilterGraph.h +59 -0
  57. torchcodec/_core/Frame.cpp +75 -0
  58. torchcodec/_core/Frame.h +76 -0
  59. torchcodec/_core/IOInterface.h +44 -0
  60. torchcodec/_core/ImageCommon.h +113 -0
  61. torchcodec/_core/Logging.cpp +42 -0
  62. torchcodec/_core/Logging.h +38 -0
  63. torchcodec/_core/Metadata.cpp +312 -0
  64. torchcodec/_core/Metadata.h +115 -0
  65. torchcodec/_core/NVCUVIDRuntimeLoader.cpp +324 -0
  66. torchcodec/_core/NVCUVIDRuntimeLoader.h +14 -0
  67. torchcodec/_core/NVDECCache.cpp +111 -0
  68. torchcodec/_core/NVDECCache.h +136 -0
  69. torchcodec/_core/NVDECCacheConfig.cpp +61 -0
  70. torchcodec/_core/NVDECCacheConfig.h +30 -0
  71. torchcodec/_core/PacketDecoder.cpp +358 -0
  72. torchcodec/_core/PacketDecoder.h +140 -0
  73. torchcodec/_core/SingleStreamDecoder.cpp +1856 -0
  74. torchcodec/_core/SingleStreamDecoder.h +424 -0
  75. torchcodec/_core/StableABICompat.h +213 -0
  76. torchcodec/_core/StreamOptions.h +93 -0
  77. torchcodec/_core/SwScale.cpp +124 -0
  78. torchcodec/_core/SwScale.h +67 -0
  79. torchcodec/_core/TensorIO.cpp +136 -0
  80. torchcodec/_core/TensorIO.h +53 -0
  81. torchcodec/_core/Transform.cpp +207 -0
  82. torchcodec/_core/Transform.h +125 -0
  83. torchcodec/_core/ValidationUtils.cpp +65 -0
  84. torchcodec/_core/ValidationUtils.h +29 -0
  85. torchcodec/_core/WavDecoder.cpp +494 -0
  86. torchcodec/_core/WavDecoder.h +73 -0
  87. torchcodec/_core/__init__.py +45 -0
  88. torchcodec/_core/_decoder_utils.py +258 -0
  89. torchcodec/_core/_ffmpeg_op_names.py +95 -0
  90. torchcodec/_core/_ffmpeg_ops.py +699 -0
  91. torchcodec/_core/_file_like.py +221 -0
  92. torchcodec/_core/_metadata.py +402 -0
  93. torchcodec/_core/color_conversion.cpp +316 -0
  94. torchcodec/_core/color_conversion.cu +391 -0
  95. torchcodec/_core/color_conversion.h +150 -0
  96. torchcodec/_core/custom_ops.cpp +2438 -0
  97. torchcodec/_core/fetch_and_expose_non_gpl_ffmpeg_libs.cmake +192 -0
  98. torchcodec/_core/fetch_avif_from_s3.cmake +81 -0
  99. torchcodec/_core/giflib/README +28 -0
  100. torchcodec/_core/giflib/dgif_lib.c +1313 -0
  101. torchcodec/_core/giflib/gif_hash.c +129 -0
  102. torchcodec/_core/giflib/gif_hash.h +43 -0
  103. torchcodec/_core/giflib/gif_lib.h +292 -0
  104. torchcodec/_core/giflib/gif_lib_private.h +73 -0
  105. torchcodec/_core/giflib/gifalloc.c +426 -0
  106. torchcodec/_core/giflib/openbsd-reallocarray.c +74 -0
  107. torchcodec/_core/heic_custom_ops.cpp +20 -0
  108. torchcodec/_core/image_custom_ops.cpp +137 -0
  109. torchcodec/_core/nvcuvid_include/cuviddec.h +1374 -0
  110. torchcodec/_core/nvcuvid_include/nvcuvid.h +610 -0
  111. torchcodec/_core/ops.py +103 -0
  112. torchcodec/_core/sources.bzl +113 -0
  113. torchcodec/_frame.py +146 -0
  114. torchcodec/_internally_replaced_utils.py +129 -0
  115. torchcodec/_logging.py +59 -0
  116. torchcodec/decoders/__init__.py +50 -0
  117. torchcodec/decoders/_audio_decoder.py +183 -0
  118. torchcodec/decoders/_blocks/__init__.py +48 -0
  119. torchcodec/decoders/_blocks/_audio_converter.py +155 -0
  120. torchcodec/decoders/_blocks/_codec_parameters.py +229 -0
  121. torchcodec/decoders/_blocks/_color_converter.py +107 -0
  122. torchcodec/decoders/_blocks/_demuxer.py +678 -0
  123. torchcodec/decoders/_blocks/_frame.py +577 -0
  124. torchcodec/decoders/_blocks/_helpers.py +53 -0
  125. torchcodec/decoders/_blocks/_packet_decoder.py +357 -0
  126. torchcodec/decoders/_decoder_utils.py +128 -0
  127. torchcodec/decoders/_image_decoders.py +1575 -0
  128. torchcodec/decoders/_video_decoder.py +592 -0
  129. torchcodec/decoders/_wav_decoder.py +131 -0
  130. torchcodec/encoders/__init__.py +4 -0
  131. torchcodec/encoders/_audio_encoder.py +167 -0
  132. torchcodec/encoders/_image_encoders.py +181 -0
  133. torchcodec/encoders/_multi_stream_encoder.py +272 -0
  134. torchcodec/encoders/_video_encoder.py +227 -0
  135. torchcodec/jpeg8.dll +0 -0
  136. torchcodec/libavif.dll +0 -0
  137. torchcodec/libpng16.dll +0 -0
  138. torchcodec/libsharpyuv.dll +0 -0
  139. torchcodec/libtorchcodec_core4.dll +0 -0
  140. torchcodec/libtorchcodec_core5.dll +0 -0
  141. torchcodec/libtorchcodec_core6.dll +0 -0
  142. torchcodec/libtorchcodec_core7.dll +0 -0
  143. torchcodec/libtorchcodec_core8.dll +0 -0
  144. torchcodec/libtorchcodec_core9.dll +0 -0
  145. torchcodec/libtorchcodec_custom_ops4.dll +0 -0
  146. torchcodec/libtorchcodec_custom_ops5.dll +0 -0
  147. torchcodec/libtorchcodec_custom_ops6.dll +0 -0
  148. torchcodec/libtorchcodec_custom_ops7.dll +0 -0
  149. torchcodec/libtorchcodec_custom_ops8.dll +0 -0
  150. torchcodec/libtorchcodec_custom_ops9.dll +0 -0
  151. torchcodec/libtorchcodec_heic.dll +0 -0
  152. torchcodec/libtorchcodec_image.dll +0 -0
  153. torchcodec/libwebp.dll +0 -0
  154. torchcodec/libwebpdecoder.dll +0 -0
  155. torchcodec/libwebpdemux.dll +0 -0
  156. torchcodec/libwebpmux.dll +0 -0
  157. torchcodec/libzstd.dll +0 -0
  158. torchcodec/py.typed +0 -0
  159. torchcodec/samplers/__init__.py +2 -0
  160. torchcodec/samplers/_common.py +83 -0
  161. torchcodec/samplers/_index_based.py +287 -0
  162. torchcodec/samplers/_time_based.py +360 -0
  163. torchcodec/share/cmake/TorchCodec/TorchCodecConfig.cmake +76 -0
  164. torchcodec/share/cmake/TorchCodec/ffmpeg_versions.cmake +128 -0
  165. torchcodec/transforms/__init__.py +12 -0
  166. torchcodec/transforms/_decoder_transforms.py +375 -0
  167. torchcodec/version.py +1 -0
  168. torchcodec/zlib.dll +0 -0
  169. torchcodec-1.0.0.dist-info/METADATA +275 -0
  170. torchcodec-1.0.0.dist-info/RECORD +179 -0
  171. torchcodec-1.0.0.dist-info/WHEEL +5 -0
  172. torchcodec-1.0.0.dist-info/licenses/LICENSE +28 -0
  173. torchcodec-1.0.0.dist-info/licenses/third_party/COPYING.dav1d +23 -0
  174. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libavif +387 -0
  175. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libjpeg-turbo +135 -0
  176. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libpng +134 -0
  177. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libwebp +30 -0
  178. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libyuv +29 -0
  179. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.zlib +22 -0
@@ -0,0 +1,1575 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import ctypes
8
+ import struct
9
+ import warnings
10
+ import zlib
11
+ from dataclasses import dataclass
12
+ from enum import Enum
13
+ from pathlib import Path
14
+ from typing import Literal
15
+
16
+ import torch
17
+ from torchcodec._core.ops import (
18
+ decode_avif as _decode_avif,
19
+ decode_gif as _decode_gif,
20
+ decode_jpeg as _decode_jpeg,
21
+ decode_jpegs_cuda as _decode_jpegs_cuda,
22
+ decode_png as _decode_png,
23
+ decode_webp as _decode_webp,
24
+ get_decode_heic as _get_decode_heic,
25
+ png_skip_idat_chunks_from_file as _png_skip_idat_chunks_from_file,
26
+ png_skip_idat_chunks_from_tensor as _png_skip_idat_chunks_from_tensor,
27
+ probe_avif_from_file as _probe_avif_from_file,
28
+ probe_avif_from_tensor as _probe_avif_from_tensor,
29
+ probe_gif_from_file as _probe_gif_from_file,
30
+ probe_gif_from_tensor as _probe_gif_from_tensor,
31
+ )
32
+
33
+
34
+ class ImageReadMode(Enum):
35
+ """Color mode for image decoding.
36
+
37
+ You don't have to use this, you can just pass strings like "RGB" or "GRAY" instead.
38
+ """
39
+
40
+ UNCHANGED = 0
41
+ GRAY = 1
42
+ GRAY_ALPHA = 2
43
+ RGB = 3
44
+ RGB_ALPHA = 4
45
+ RGBA = 4 # undocumented alias for RGB_ALPHA
46
+
47
+
48
+ def _normalize_mode(
49
+ mode: (
50
+ Literal["UNCHANGED", "GRAY", "GRAY_ALPHA", "RGB", "RGB_ALPHA"] | ImageReadMode
51
+ ),
52
+ ) -> ImageReadMode:
53
+ # Normalize the public `mode` argument (a case-insensitive string, or an
54
+ # ImageReadMode for BC) to an ImageReadMode, which is what the rest of the
55
+ # decoding code works with.
56
+ if isinstance(mode, ImageReadMode):
57
+ return mode
58
+ if isinstance(mode, str):
59
+ try:
60
+ return ImageReadMode[mode.upper()]
61
+ except KeyError:
62
+ valid = ", ".join(repr(m.name) for m in ImageReadMode)
63
+ raise ValueError(
64
+ f"Invalid mode {mode!r}. Supported modes are {valid} "
65
+ "(case-insensitive)."
66
+ ) from None
67
+ raise TypeError(f"mode must be a str (or ImageReadMode), got {type(mode)}.")
68
+
69
+
70
+ def _source_to_tensor(source: str | Path | bytes | torch.Tensor) -> torch.Tensor:
71
+ # Turn any supported source into a 1-D uint8 tensor of encoded bytes.
72
+ if isinstance(source, torch.Tensor):
73
+ # dtype is validated in cpp.
74
+ return source
75
+ if isinstance(source, (str, Path)):
76
+ # We keep the file reading in pure Python (rather than a C++ read_file
77
+ # op like in torchvision): benchmarked against a C++ op, the
78
+ # read is only ~1-1.5% of total decode time.
79
+ source = Path(source).read_bytes()
80
+ if isinstance(source, (bytes, bytearray)):
81
+ with warnings.catch_warnings():
82
+ # torch.frombuffer warns that the underlying buffer is non-writable;
83
+ # we only read from the resulting tensor, so this is safe to ignore.
84
+ warnings.filterwarnings("ignore", category=UserWarning)
85
+ return torch.frombuffer(source, dtype=torch.uint8)
86
+
87
+ raise TypeError(
88
+ f"Unknown source type: {type(source)}. "
89
+ "Supported types are str, Path, bytes and torch.Tensor."
90
+ )
91
+
92
+
93
+ # Output modes each native codec can produce directly, for any input. Any output
94
+ # mode not listed here is obtained via a post-decode conversion.
95
+ _JPEG_NATIVE_OUTPUT_MODES = frozenset(
96
+ (ImageReadMode.UNCHANGED, ImageReadMode.GRAY, ImageReadMode.RGB)
97
+ )
98
+ _PNG_NATIVE_OUTPUT_MODES = frozenset(ImageReadMode)
99
+ _WEBP_NATIVE_OUTPUT_MODES = _GIF_NATIVE_OUTPUT_MODES = _AVIF_NATIVE_OUTPUT_MODES = (
100
+ _HEIC_NATIVE_OUTPUT_MODES
101
+ ) = frozenset((ImageReadMode.UNCHANGED, ImageReadMode.RGB, ImageReadMode.RGB_ALPHA))
102
+
103
+
104
+ def _append_opaque_alpha(img: torch.Tensor) -> torch.Tensor:
105
+ # Append a fully-opaque alpha channel on the channel dim
106
+ # works on CHW and NCHW tensors.
107
+ alpha_shape = list(img.shape)
108
+ alpha_shape[-3] = 1
109
+ alpha = torch.full(
110
+ alpha_shape, torch.iinfo(img.dtype).max, dtype=img.dtype, device=img.device
111
+ )
112
+ return torch.cat([img, alpha], dim=-3)
113
+
114
+
115
+ def _rgb_to_gray(img: torch.Tensor) -> torch.Tensor:
116
+ # ITU-R 601-2 luma weights, matching torchvision's rgb_to_grayscale.
117
+ # works on CHW and NCHW tensors.
118
+ weights = torch.tensor([0.2989, 0.587, 0.114])
119
+ gray = (img.to(torch.float32) * weights[:, None, None]).sum(dim=-3, keepdim=True)
120
+ return gray.round().clamp(0, torch.iinfo(img.dtype).max).to(img.dtype)
121
+
122
+
123
+ def _decode_to_mode(decode_fn, data, mode, native_output_modes) -> torch.Tensor:
124
+ if mode in native_output_modes:
125
+ return decode_fn(data, mode.value)
126
+
127
+ if mode is ImageReadMode.GRAY:
128
+ return _rgb_to_gray(decode_fn(data, ImageReadMode.RGB.value))
129
+ elif mode is ImageReadMode.RGB_ALPHA:
130
+ return _append_opaque_alpha(decode_fn(data, ImageReadMode.RGB.value))
131
+ elif mode is ImageReadMode.GRAY_ALPHA:
132
+ if ImageReadMode.RGB_ALPHA in native_output_modes:
133
+ # Real alpha available (e.g. webp): decode RGBA and reduce the color
134
+ # channels to luma while preserving the alpha channel.
135
+ rgba = decode_fn(data, ImageReadMode.RGB_ALPHA.value)
136
+ rgb, alpha = rgba[..., :3, :, :], rgba[..., 3:, :, :]
137
+ return torch.cat([_rgb_to_gray(rgb), alpha], dim=-3)
138
+ elif ImageReadMode.GRAY in native_output_modes:
139
+ return _append_opaque_alpha(decode_fn(data, ImageReadMode.GRAY.value))
140
+ else:
141
+ gray = _rgb_to_gray(decode_fn(data, ImageReadMode.RGB.value))
142
+ return _append_opaque_alpha(gray)
143
+ else:
144
+ raise RuntimeError(
145
+ f"Reached an unexpected code path while decoding to mode {mode}. "
146
+ "This should never happen, please report a bug to the TorchCodec repo."
147
+ )
148
+
149
+
150
+ def _validate_output_dtype(output_dtype) -> int:
151
+ # Validates output_dtype and returns the integer code understood by the C++
152
+ # decoders. Must be kept in-sync with the OutputDtype enum in ImageCommon.h.
153
+ output_dtype_to_code = {torch.uint8: 0, torch.uint16: 1, "auto": 2}
154
+ if output_dtype not in output_dtype_to_code:
155
+ raise ValueError(
156
+ f"Invalid output_dtype ({output_dtype}). "
157
+ "Supported values are torch.uint8, torch.uint16, and 'auto'."
158
+ )
159
+ return output_dtype_to_code[output_dtype]
160
+
161
+
162
+ def _to_output_dtype(
163
+ decoded: torch.Tensor, output_dtype: torch.dtype | str
164
+ ) -> torch.Tensor:
165
+ if output_dtype == "auto" or decoded.dtype == output_dtype:
166
+ return decoded
167
+ elif output_dtype == torch.uint16:
168
+ if decoded.dtype != torch.uint8:
169
+ raise RuntimeError("Oops, please report a bug to the TorchCodec repo.")
170
+ return (decoded.to(torch.int32) * 257).to(torch.uint16)
171
+ elif output_dtype == torch.uint8:
172
+ if decoded.dtype != torch.uint16:
173
+ raise RuntimeError("Oops, please report a bug to the TorchCodec repo.")
174
+ return (decoded.to(torch.float32) / 257).round().clamp(0, 255).to(torch.uint8)
175
+ else:
176
+ raise RuntimeError(
177
+ "This should never happen, please report a bug to the TorchCodec repo."
178
+ )
179
+
180
+
181
+ def _decode_jpegs_cuda_with_mode(
182
+ tensors: list[torch.Tensor], mode: ImageReadMode, device: torch.device
183
+ ) -> list[torch.Tensor]:
184
+ # Batched GPU equivalent of _decode_to_mode for JPEG: decode the whole
185
+ # batch in one nvJPEG call using a native mode, then emulate the alpha modes
186
+ # per-image in Python (nvJPEG natively supports UNCHANGED, GRAY and RGB, same
187
+ # as libjpeg on CPU).
188
+ if mode in _JPEG_NATIVE_OUTPUT_MODES:
189
+ return _decode_jpegs_cuda(tensors, mode.value, device)
190
+ if mode is ImageReadMode.RGB_ALPHA:
191
+ decoded = _decode_jpegs_cuda(tensors, ImageReadMode.RGB.value, device)
192
+ return [_append_opaque_alpha(img) for img in decoded]
193
+ if mode is ImageReadMode.GRAY_ALPHA:
194
+ decoded = _decode_jpegs_cuda(tensors, ImageReadMode.GRAY.value, device)
195
+ return [_append_opaque_alpha(img) for img in decoded]
196
+ raise RuntimeError(
197
+ f"Reached an unexpected code path while decoding to mode {mode}. "
198
+ "This should never happen, please report a bug to the TorchCodec repo."
199
+ )
200
+
201
+
202
+ def decode_jpeg(
203
+ source: str | Path | bytes | torch.Tensor | list,
204
+ *,
205
+ mode: (
206
+ Literal["UNCHANGED", "GRAY", "GRAY_ALPHA", "RGB", "RGB_ALPHA"] | ImageReadMode
207
+ ) = "RGB",
208
+ output_dtype: torch.dtype | Literal["auto"] = torch.uint8,
209
+ device: str | torch.device = "cpu",
210
+ ) -> torch.Tensor | list[torch.Tensor]:
211
+ """Decode a JPEG image into a ``CHW`` tensor, on CPU or CUDA.
212
+
213
+ .. note::
214
+
215
+ For CUDA decoding, prefer passing a batch (a list of sources) in a
216
+ single call: the whole batch is decoded in one nvJPEG call, which is
217
+ much faster than decoding images one at a time.
218
+ Passing a batch of sources is supported on CPU too, but it won't be
219
+ faster than decoding them one at a time.
220
+
221
+ Example:
222
+
223
+ .. code-block:: python
224
+
225
+ from torchcodec.decoders import decode_jpeg
226
+
227
+ img = decode_jpeg("image.jpg")
228
+ img = decode_jpeg("image.jpg", device="cuda") # decode on GPU
229
+
230
+ Args:
231
+ source (str, ``pathlib.Path``, bytes, ``torch.Tensor``, or list of these):
232
+ The encoded JPEG data: a path (``str`` or ``pathlib.Path``), a
233
+ ``bytes`` object, or a 1-D uint8 ``torch.Tensor`` of the raw encoded
234
+ bytes. Pass a list (or tuple) to decode a batch, in which case a list of
235
+ tensors is returned instead of a single tensor. The encoded bytes must
236
+ live on CPU, even when decoding to a CUDA device.
237
+ mode (str or ImageReadMode, optional): Desired color mode of the output
238
+ image. Can be one of ``"UNCHANGED"``, ``"GRAY"``, ``"GRAY_ALPHA"``,
239
+ ``"RGB"``, or ``"RGB_ALPHA"``. Default is ``"RGB"``.
240
+ output_dtype (torch.dtype or ``"auto"``, optional): desired dtype of the
241
+ output image tensor. Accepted values are ``torch.uint8`` (default),
242
+ ``torch.uint16``, and ``"auto"``. Since JPEG is an 8-bit format,
243
+ ``"auto"`` and ``torch.uint8`` are equivalent. ``torch.uint16``
244
+ emulates a 16-bit output by scaling the 8-bit values to the full
245
+ 16-bit range (0-255 -> 0-65535).
246
+ device (str or torch.device, optional): Device to decode on, ``"cpu"``
247
+ (default) or a CUDA device. CUDA decoding uses nvJPEG. We recommend
248
+ passing a batch of sources when decoding on CUDA, for speed.
249
+
250
+ Returns:
251
+ torch.Tensor or list of torch.Tensor of shape ``C, H, W``: The decoded
252
+ image(s). A single tensor for a single source, or a list of tensors for
253
+ a batch.
254
+ """
255
+ _validate_output_dtype(output_dtype)
256
+ mode = _normalize_mode(mode)
257
+ device = torch.device(device)
258
+
259
+ is_batch = isinstance(source, (list, tuple))
260
+ sources: list = list(source) if is_batch else [source] # type: ignore[arg-type]
261
+
262
+ if device.type == "cpu":
263
+ decoded_list = [
264
+ _to_output_dtype(
265
+ _decode_to_mode(
266
+ _decode_jpeg,
267
+ _source_to_tensor(s),
268
+ mode,
269
+ _JPEG_NATIVE_OUTPUT_MODES,
270
+ ),
271
+ output_dtype,
272
+ )
273
+ for s in sources
274
+ ]
275
+ else:
276
+ tensors = [_source_to_tensor(s) for s in sources]
277
+ decoded_list = _decode_jpegs_cuda_with_mode(tensors, mode, device)
278
+ decoded_list = [_to_output_dtype(img, output_dtype) for img in decoded_list]
279
+
280
+ return decoded_list if is_batch else decoded_list[0]
281
+
282
+
283
+ def decode_png(
284
+ source: str | Path | bytes | torch.Tensor,
285
+ *,
286
+ mode: (
287
+ Literal["UNCHANGED", "GRAY", "GRAY_ALPHA", "RGB", "RGB_ALPHA"] | ImageReadMode
288
+ ) = "RGB",
289
+ output_dtype: torch.dtype | Literal["auto"] = torch.uint8,
290
+ ) -> torch.Tensor:
291
+ """Decode a PNG image into a ``CHW`` tensor.
292
+
293
+ Example:
294
+
295
+ .. code-block:: python
296
+
297
+ from torchcodec.decoders import decode_png
298
+
299
+ img = decode_png("image.png")
300
+
301
+ Args:
302
+ source (str, ``pathlib.Path``, bytes, or ``torch.Tensor``):
303
+ The encoded PNG data: a path (``str`` or ``pathlib.Path``), a
304
+ ``bytes`` object, or a 1-D uint8 ``torch.Tensor`` of the raw encoded
305
+ bytes.
306
+ mode (str or ImageReadMode, optional): Desired color mode of the output
307
+ image. Can be one of ``"UNCHANGED"``, ``"GRAY"``, ``"GRAY_ALPHA"``,
308
+ ``"RGB"``, or ``"RGB_ALPHA"``. Default is ``"RGB"``.
309
+ output_dtype (torch.dtype or ``"auto"``, optional): desired dtype of the
310
+ output image tensor. Accepted values are ``torch.uint8`` (default),
311
+ ``torch.uint16``, and ``"auto"``. PNG images can natively store
312
+ 16-bit samples: ``torch.uint16`` preserves that precision (8-bit
313
+ sources are scaled up, 0-255 -> 0-65535), while ``torch.uint8``
314
+ scales 16-bit sources down. ``"auto"`` keeps the source's native bit
315
+ depth, yielding uint8 for 8-bit PNGs and uint16 for 16-bit ones.
316
+
317
+ Returns:
318
+ torch.Tensor: The decoded image, of shape ``(C, H, W)``.
319
+ """
320
+ output_dtype_code = _validate_output_dtype(output_dtype)
321
+ mode = _normalize_mode(mode)
322
+ data = _source_to_tensor(source)
323
+ return _decode_to_mode(
324
+ lambda d, m: _decode_png(d, m, output_dtype_code),
325
+ data,
326
+ mode,
327
+ _PNG_NATIVE_OUTPUT_MODES,
328
+ )
329
+
330
+
331
+ def decode_webp(
332
+ source: str | Path | bytes | torch.Tensor,
333
+ *,
334
+ mode: (
335
+ Literal["UNCHANGED", "GRAY", "GRAY_ALPHA", "RGB", "RGB_ALPHA"] | ImageReadMode
336
+ ) = "RGB",
337
+ output_dtype: torch.dtype | Literal["auto"] = torch.uint8,
338
+ ) -> torch.Tensor:
339
+ """Decode a WebP image into a ``[N]CHW`` tensor.
340
+
341
+ The output shape is ``(C, H, W)`` for a still WebP and ``(N, C, H, W)`` for
342
+ an animated one (N frames).
343
+
344
+ Example:
345
+
346
+ .. code-block:: python
347
+
348
+ from torchcodec.decoders import decode_webp
349
+
350
+ img = decode_webp("image.webp")
351
+
352
+ Args:
353
+ source (str, ``pathlib.Path``, bytes, or ``torch.Tensor``):
354
+ The encoded WebP data: a path (``str`` or ``pathlib.Path``), a
355
+ ``bytes`` object, or a 1-D uint8 ``torch.Tensor`` of the raw encoded
356
+ bytes.
357
+ mode (str or ImageReadMode, optional): Desired color mode of the output
358
+ image. Can be one of ``"UNCHANGED"``, ``"GRAY"``, ``"GRAY_ALPHA"``,
359
+ ``"RGB"``, or ``"RGB_ALPHA"``. Default is ``"RGB"``.
360
+ output_dtype (torch.dtype or ``"auto"``, optional): desired dtype of the
361
+ output image tensor. Accepted values are ``torch.uint8`` (default),
362
+ ``torch.uint16``, and ``"auto"``. Since WebP is an 8-bit format,
363
+ ``"auto"`` and ``torch.uint8`` are equivalent. ``torch.uint16``
364
+ emulates a 16-bit output by scaling the 8-bit values to the full
365
+ 16-bit range (0-255 -> 0-65535).
366
+
367
+ Returns:
368
+ torch.Tensor: The decoded image, of shape ``(C, H, W)`` (still) or
369
+ ``(N, C, H, W)`` (animated).
370
+ """
371
+ _validate_output_dtype(output_dtype)
372
+ mode = _normalize_mode(mode)
373
+ data = _source_to_tensor(source)
374
+ decoded = _decode_to_mode(_decode_webp, data, mode, _WEBP_NATIVE_OUTPUT_MODES)
375
+ return _to_output_dtype(decoded, output_dtype)
376
+
377
+
378
+ def decode_gif(
379
+ source: str | Path | bytes | torch.Tensor,
380
+ *,
381
+ mode: (
382
+ Literal["UNCHANGED", "GRAY", "GRAY_ALPHA", "RGB", "RGB_ALPHA"] | ImageReadMode
383
+ ) = "RGB",
384
+ output_dtype: torch.dtype | Literal["auto"] = torch.uint8,
385
+ ) -> torch.Tensor:
386
+ """Decode a GIF image into a ``[N]CHW`` tensor.
387
+
388
+ The output shape is ``(C, H, W)`` for a still GIF and ``(N, C, H, W)`` for
389
+ an animated one (N frames).
390
+
391
+ Example:
392
+
393
+ .. code-block:: python
394
+
395
+ from torchcodec.decoders import decode_gif
396
+
397
+ img = decode_gif("image.gif")
398
+
399
+ Args:
400
+ source (str, ``pathlib.Path``, bytes, or ``torch.Tensor``):
401
+ The encoded GIF data: a path (``str`` or ``pathlib.Path``), a
402
+ ``bytes`` object, or a 1-D uint8 ``torch.Tensor`` of the raw encoded
403
+ bytes.
404
+ mode (str or ImageReadMode, optional): Desired color mode of the output
405
+ image. Can be one of ``"UNCHANGED"``, ``"GRAY"``, ``"GRAY_ALPHA"``,
406
+ ``"RGB"``, or ``"RGB_ALPHA"``. Default is ``"RGB"``.
407
+ output_dtype (torch.dtype or ``"auto"``, optional): desired dtype of the
408
+ output image tensor. Accepted values are ``torch.uint8`` (default),
409
+ ``torch.uint16``, and ``"auto"``. Since GIF is an 8-bit format,
410
+ ``"auto"`` and ``torch.uint8`` are equivalent. ``torch.uint16``
411
+ emulates a 16-bit output by scaling the 8-bit values to the full
412
+ 16-bit range (0-255 -> 0-65535).
413
+
414
+ Returns:
415
+ torch.Tensor: The decoded image, of shape ``(C, H, W)`` (still) or
416
+ ``(N, C, H, W)`` (animated).
417
+ """
418
+ _validate_output_dtype(output_dtype)
419
+ mode = _normalize_mode(mode)
420
+ data = _source_to_tensor(source)
421
+ decoded = _decode_to_mode(_decode_gif, data, mode, _GIF_NATIVE_OUTPUT_MODES)
422
+ return _to_output_dtype(decoded, output_dtype)
423
+
424
+
425
+ def decode_avif(
426
+ source: str | Path | bytes | torch.Tensor,
427
+ *,
428
+ mode: (
429
+ Literal["UNCHANGED", "GRAY", "GRAY_ALPHA", "RGB", "RGB_ALPHA"] | ImageReadMode
430
+ ) = "RGB",
431
+ output_dtype: torch.dtype | Literal["auto"] = torch.uint8,
432
+ num_threads: int = 1,
433
+ ) -> torch.Tensor:
434
+ """Decode an AVIF image into a ``[N]CHW`` tensor.
435
+
436
+ The output shape is ``(C, H, W)`` for a still AVIF and ``(N, C, H, W)`` for
437
+ an animated one (N frames).
438
+
439
+ Example:
440
+
441
+ .. code-block:: python
442
+
443
+ from torchcodec.decoders import decode_avif
444
+
445
+ img = decode_avif("image.avif")
446
+
447
+ Args:
448
+ source (str, ``pathlib.Path``, bytes, or ``torch.Tensor``):
449
+ The encoded AVIF data: a path (``str`` or ``pathlib.Path``), a
450
+ ``bytes`` object, or a 1-D uint8 ``torch.Tensor`` of the raw encoded
451
+ bytes.
452
+ mode (str or ImageReadMode, optional): Desired color mode of the output
453
+ image. Can be one of ``"UNCHANGED"``, ``"GRAY"``, ``"GRAY_ALPHA"``,
454
+ ``"RGB"``, or ``"RGB_ALPHA"``. Default is ``"RGB"``.
455
+ output_dtype (torch.dtype or ``"auto"``, optional): desired dtype of the
456
+ output image tensor. Accepted values are ``torch.uint8`` (default),
457
+ ``torch.uint16``, and ``"auto"``. AVIF can store more than 8 bits per
458
+ channel (e.g. 10- or 12-bit sources). ``torch.uint16`` always scales
459
+ the samples up to fill the full 16-bit range ``[0, 65535]`` (8-bit
460
+ 0-255, 10-bit 0-1023 and 12-bit 0-4095 sources are all upscaled),
461
+ while ``torch.uint8`` scales higher-bit sources down. ``"auto"``
462
+ yields uint8 for 8-bit AVIFs and uint16 (again filling ``[0, 65535]``)
463
+ for higher-bit ones.
464
+ num_threads (int, optional): Number of threads to use for decoding,
465
+ directly passed to libavif. Default is 1.
466
+
467
+ Returns:
468
+ torch.Tensor: The decoded image, of shape ``(C, H, W)`` (still) or
469
+ ``(N, C, H, W)`` (animated).
470
+ """
471
+ output_dtype_code = _validate_output_dtype(output_dtype)
472
+ mode = _normalize_mode(mode)
473
+ data = _source_to_tensor(source)
474
+ return _decode_to_mode(
475
+ lambda d, m: _decode_avif(d, m, output_dtype_code, num_threads),
476
+ data,
477
+ mode,
478
+ _AVIF_NATIVE_OUTPUT_MODES,
479
+ )
480
+
481
+
482
+ def decode_heic(
483
+ source: str | Path | bytes | torch.Tensor,
484
+ *,
485
+ mode: (
486
+ Literal["UNCHANGED", "GRAY", "GRAY_ALPHA", "RGB", "RGB_ALPHA"] | ImageReadMode
487
+ ) = "RGB",
488
+ output_dtype: torch.dtype | Literal["auto"] = torch.uint8,
489
+ ) -> torch.Tensor:
490
+ """Decode an HEIC/HEIF image into a ``[N]CHW`` tensor - requires ``libheif``!
491
+
492
+ The output shape is ``(C, H, W)`` for a single-image HEIC and
493
+ ``(N, C, H, W)`` for a multi-image one. All images must share the same
494
+ dimensions and bit depth.
495
+
496
+ .. important::
497
+
498
+ HEIC decoding requires **libheif** to be installed and discoverable at
499
+ runtime. TorchCodec does not bundle it (libheif is LGPL): install it via
500
+ e.g. ``conda install -c conda-forge libheif``.
501
+
502
+ Example:
503
+
504
+ .. code-block:: python
505
+
506
+ from torchcodec.decoders import decode_heic
507
+
508
+ img = decode_heic("image.heic")
509
+
510
+ Args:
511
+ source (str, ``pathlib.Path``, bytes, or ``torch.Tensor``):
512
+ The encoded HEIC/HEIF data: a path (``str`` or ``pathlib.Path``), a
513
+ ``bytes`` object, or a 1-D uint8 ``torch.Tensor`` of the raw encoded
514
+ bytes.
515
+ mode (str or ImageReadMode, optional): Desired color mode of the output
516
+ image. Can be one of ``"UNCHANGED"``, ``"GRAY"``, ``"GRAY_ALPHA"``,
517
+ ``"RGB"``, or ``"RGB_ALPHA"``. Default is ``"RGB"``.
518
+ output_dtype (torch.dtype or ``"auto"``, optional): desired dtype of the
519
+ output image tensor. Accepted values are ``torch.uint8`` (default),
520
+ ``torch.uint16``, and ``"auto"``. HEIC can store more than 8 bits per
521
+ channel (e.g. 10- or 12-bit sources). ``torch.uint16`` always scales
522
+ the samples up to fill the full 16-bit range ``[0, 65535]`` (8-bit
523
+ 0-255, 10-bit 0-1023 and 12-bit 0-4095 sources are all upscaled),
524
+ while ``torch.uint8`` scales higher-bit sources down. ``"auto"``
525
+ yields uint8 for 8-bit HEICs and uint16 (again filling ``[0, 65535]``)
526
+ for higher-bit ones.
527
+
528
+ Returns:
529
+ torch.Tensor: The decoded image, of shape ``(C, H, W)`` (single-image)
530
+ or ``(N, C, H, W)`` (multi-image).
531
+ """
532
+ output_dtype_code = _validate_output_dtype(output_dtype)
533
+ mode = _normalize_mode(mode)
534
+ data = _source_to_tensor(source)
535
+ decode_heic_op = _get_decode_heic()
536
+ decoded = _decode_to_mode(
537
+ lambda d, m: decode_heic_op(d, m, output_dtype_code),
538
+ data,
539
+ mode,
540
+ _HEIC_NATIVE_OUTPUT_MODES,
541
+ )
542
+ return _to_output_dtype(decoded, output_dtype)
543
+
544
+
545
+ def _detect_image_format(data: torch.Tensor) -> str:
546
+ # Sniff the codec from the leading "magic" bytes of the encoded data.
547
+ # This used to be implemented in C++ in torchvision, but benchmarks show
548
+ # this is negligible in Python
549
+ return _detect_image_format_from_header(bytes(data[:64].tolist()))
550
+
551
+
552
+ def _detect_image_format_from_header(header: bytes) -> str:
553
+ if header[:3] == b"\xff\xd8\xff":
554
+ return "jpeg"
555
+ if header[:8] == b"\x89PNG\r\n\x1a\n":
556
+ return "png"
557
+ if header[:6] in (b"GIF87a", b"GIF89a"):
558
+ return "gif"
559
+ if header[:4] == b"RIFF" and header[8:12] == b"WEBP":
560
+ return "webp"
561
+ if header[4:8] == b"ftyp":
562
+ # ISOBMFF container (AVIF/HEIC/...). The major brand is at [8:12], with
563
+ # compatible brands following. AVIF uses the "avif" (still) or "avis"
564
+ # (animated) brands; HEIC/HEIF uses "heic"/"heix" (HEVC-coded) and the
565
+ # generic "mif1"/"msf1" brands. We check avif first (it can also carry
566
+ # mif1/msf1), then fall back to the HEIC-specific brands.
567
+ brands = header[8:]
568
+ if b"avif" in brands or b"avis" in brands:
569
+ return "avif"
570
+ if (
571
+ b"heic" in brands
572
+ or b"heix" in brands
573
+ or b"heim" in brands
574
+ or b"heis" in brands
575
+ or b"hevc" in brands
576
+ or b"hevx" in brands
577
+ or b"mif1" in brands
578
+ or b"msf1" in brands
579
+ ):
580
+ return "heic"
581
+ raise ValueError(
582
+ "Unsupported or unrecognized image format. Supported formats are "
583
+ "JPEG, PNG, WebP, GIF, AVIF and HEIC. If you know you have a valid "
584
+ "image, try using the dedicated decode_* functions like decode_jpeg() "
585
+ "instead."
586
+ )
587
+
588
+
589
+ # Design note: the parameters of decode_image must apply to *all* codecs
590
+ # uniformly. That's why all modes are supported by decode_image even though not
591
+ # all codec would natively support all mode - e.g. jpeg has no alpha support, so
592
+ # we prepend an opaque alpha channel as a post-processing step. As a resut, all
593
+ # codec-specific entry points like decode_jpeg, decode_png etc. must still
594
+ # expose the same parameters that decode_image exposes. The codec-specific
595
+ # parameters should live in the codec-specific entry points, e.g. decode_avif
596
+ # has its `num_threads`, decode_jpeg has `device`, etc.
597
+ def decode_image(
598
+ source: str | Path | bytes | torch.Tensor,
599
+ *,
600
+ mode: (
601
+ Literal["UNCHANGED", "GRAY", "GRAY_ALPHA", "RGB", "RGB_ALPHA"] | ImageReadMode
602
+ ) = "RGB",
603
+ output_dtype: torch.dtype | Literal["auto"] = torch.uint8,
604
+ ) -> torch.Tensor:
605
+ """Decode an image into a ``[N]CHW`` tensor, detecting the format automatically.
606
+
607
+ The format is detected from the encoded data (not the file extension), and
608
+ decoding is delegated to the matching format-specific decoder. Supported
609
+ formats are JPEG, PNG, WebP, GIF, AVIF and HEIC (requires ``libheif``). The
610
+ output shape is ``(C, H, W)`` for a single image and ``(N, C, H, W)`` for
611
+ animated or multi-image formats (WebP, GIF, AVIF, HEIC).
612
+
613
+ For finer control, or for format-specific options (e.g. ``device`` for CUDA
614
+ JPEG decoding, ``num_threads`` for AVIF), use the dedicated decoders
615
+ directly: :func:`decode_jpeg`, :func:`decode_png`, :func:`decode_webp`,
616
+ :func:`decode_gif`, :func:`decode_avif`, :func:`decode_heic`.
617
+
618
+ To get the dimensions, number of frames, etc. of an image without decoding
619
+ it, use :func:`get_image_metadata`.
620
+
621
+ Example:
622
+
623
+ .. code-block:: python
624
+
625
+ from torchcodec.decoders import decode_image
626
+
627
+ jpeg_img = decode_image("image.jpg")
628
+ png_img = decode_image("image.png")
629
+
630
+ Args:
631
+ source (str, ``pathlib.Path``, bytes, or ``torch.Tensor``):
632
+ The encoded image data: a path (``str`` or ``pathlib.Path``), a
633
+ ``bytes`` object, or a 1-D uint8 ``torch.Tensor`` of the raw encoded
634
+ bytes.
635
+ mode (str or ImageReadMode, optional): Desired color mode of the output
636
+ image. Can be one of ``"UNCHANGED"``, ``"GRAY"``, ``"GRAY_ALPHA"``,
637
+ ``"RGB"``, or ``"RGB_ALPHA"``. Default is ``"RGB"``.
638
+ output_dtype (torch.dtype or ``"auto"``, optional): desired dtype of the
639
+ output image tensor. Accepted values are ``torch.uint8`` (default),
640
+ ``torch.uint16``, and ``"auto"``. Formats that can carry more than 8
641
+ bits per channel (PNG, AVIF, HEIC) preserve that precision with
642
+ ``torch.uint16`` and ``"auto"``. See the format-specific decoders
643
+ for details.
644
+
645
+ Returns:
646
+ torch.Tensor: The decoded image, of shape ``[N]CHW``.
647
+ """
648
+ data = _source_to_tensor(source)
649
+ format_to_decoder = {
650
+ "jpeg": decode_jpeg,
651
+ "png": decode_png,
652
+ "webp": decode_webp,
653
+ "gif": decode_gif,
654
+ "avif": decode_avif,
655
+ "heic": decode_heic,
656
+ }
657
+ fmt = _detect_image_format(data)
658
+ return format_to_decoder[fmt](data, mode=mode, output_dtype=output_dtype) # type: ignore[operator]
659
+
660
+
661
+ @dataclass(frozen=True)
662
+ class ImageMetadata:
663
+ """Metadata of an encoded image, as returned by :func:`get_image_metadata`.
664
+
665
+ Every attribute describes the tensor that :func:`decode_image` (or the
666
+ matching format-specific decoder) returns for this image.
667
+ """
668
+
669
+ format: str
670
+ """The image format, e.g. ``"jpeg"``."""
671
+ width: int
672
+ """Width of the decoded image, **post-rotation**. This is the width of the
673
+ tensor returned by :func:`decode_image` or the format-specific decoders,
674
+ which always apply the orientation metadata."""
675
+ height: int
676
+ """Height of the decoded image, **post-rotation**. This is the height of the
677
+ tensor returned by :func:`decode_image` or the format-specific decoders,
678
+ which always apply the orientation metadata."""
679
+ num_channels: int
680
+ """Number of channels of the image. This is the number of channels
681
+ of the decoded image when decoding with ``mode="UNCHANGED"``."""
682
+ bit_depth: int
683
+ """Number of bits per channel in the encoded image. When greater than 8,
684
+ decoding with ``output_dtype="auto"`` returns a ``torch.uint16`` tensor."""
685
+ num_frames: int
686
+ """Number of frames (or images) in the file: 1 for still images, and the
687
+ size of the leading ``N`` dimension of the decoded tensor for animated or
688
+ multi-image files."""
689
+ rotation: float | None
690
+ """Rotation angle in degrees (counter-clockwise: one of 0, 90, -90 or 180)
691
+ from the orientation metadata, or None if the image has no orientation
692
+ metadata. The decoders always apply it, so the returned images are in the
693
+ correct orientation.
694
+
695
+ The orientation metadata can also specify a mirroring, which the decoders
696
+ apply too but isn't reported here, since it doesn't change the image
697
+ dimensions."""
698
+
699
+
700
+ class _ByteSource:
701
+ # Random access over the encoded bytes. Paths are read lazily, so probing a
702
+ # large file usually only reads its first few KB.
703
+
704
+ def __init__(self, source):
705
+ self.source = source
706
+ self._file = None
707
+ if isinstance(source, (str, Path)):
708
+ self._file = open(source, "rb")
709
+ self._buf = None
710
+ self.size = Path(source).stat().st_size
711
+ elif isinstance(source, (bytes, bytearray)):
712
+ self._buf = memoryview(source)
713
+ self.size = len(source)
714
+ elif isinstance(source, torch.Tensor):
715
+ if (
716
+ source.dtype != torch.uint8
717
+ or source.ndim != 1
718
+ or source.device.type != "cpu"
719
+ ):
720
+ raise ValueError(
721
+ "Input tensor must be a 1-dimensional uint8 CPU tensor, got "
722
+ f"dtype={source.dtype}, ndim={source.ndim}, device={source.device}."
723
+ )
724
+ # Zero-copy view of the tensor's data. The view doesn't own the
725
+ # memory, so we keep a reference to the tensor. Slightly crazy, but
726
+ # this is what gets us bytes (the python type) instead of
727
+ # torch.uint8 which we'd have to copy to bytes.
728
+ self._tensor = source.contiguous()
729
+ self._buf = memoryview(
730
+ (ctypes.c_ubyte * self._tensor.numel()).from_address(
731
+ self._tensor.data_ptr()
732
+ )
733
+ )
734
+ self.size = len(self._buf)
735
+ else:
736
+ raise TypeError(
737
+ f"Unknown source type: {type(source)}. "
738
+ "Supported types are str, Path, bytes and torch.Tensor."
739
+ )
740
+
741
+ def read(self, offset: int, size: int) -> bytes:
742
+ # Returns fewer than `size` bytes when reading past the end.
743
+ if self._buf is not None:
744
+ return bytes(self._buf[offset : offset + size])
745
+ assert self._file is not None
746
+ self._file.seek(offset)
747
+ return self._file.read(size)
748
+
749
+ def read_exact(self, offset: int, size: int) -> bytes:
750
+ data = self.read(offset, size)
751
+ if len(data) != size:
752
+ raise RuntimeError("Image is truncated or corrupted.")
753
+ return data
754
+
755
+ def __enter__(self):
756
+ return self
757
+
758
+ def __exit__(self, *exc_info):
759
+ if self._file is not None:
760
+ self._file.close()
761
+
762
+
763
+ _EXIF_INCORRECT_TAG = 0xFFFF
764
+
765
+
766
+ def _exif_orientation(tiff: bytes) -> int | None:
767
+ # Port of fetch_exif_orientation() from Exif.h, quirks included, so that we
768
+ # report exactly the orientation the decoders apply. `tiff` starts at the
769
+ # TIFF header (i.e. after any "Exif\0\0" prefix). Returns the EXIF
770
+ # orientation in [1, 8], or None if there's none (or it's invalid, in which
771
+ # case the decoders don't apply anything either).
772
+ n = len(tiff)
773
+ byte_order = "<" if tiff[:2] == b"II" else ">"
774
+
775
+ def u16(offset):
776
+ if offset + 1 >= n:
777
+ return _EXIF_INCORRECT_TAG
778
+ return struct.unpack_from(byte_order + "H", tiff, offset)[0]
779
+
780
+ if u16(2) != 0x2A:
781
+ return None
782
+ offset = (
783
+ _EXIF_INCORRECT_TAG
784
+ if 7 >= n
785
+ else struct.unpack_from(byte_order + "I", tiff, 4)[0]
786
+ )
787
+ num_entries = u16(offset)
788
+ offset += 2
789
+ for _ in range(num_entries):
790
+ tag = u16(offset)
791
+ if tag == _EXIF_INCORRECT_TAG:
792
+ break
793
+ if tag == 0x0112:
794
+ orientation = u16(offset + 8)
795
+ return orientation if 1 <= orientation <= 8 else None
796
+ offset += 12
797
+ return None
798
+
799
+
800
+ def _exif_orientation_after_prefixes(exif: bytes) -> int | None:
801
+ # Like Pillow's Exif.load(), skips any number of "Exif\0\0" prefixes.
802
+ while exif.startswith(b"Exif\x00\x00"):
803
+ exif = exif[6:]
804
+ return _exif_orientation(exif) if exif else None
805
+
806
+
807
+ # Rotation of each EXIF orientation, when decomposed into an optional
808
+ # left-to-right mirroring followed by a rotation.
809
+ _ROTATION_FROM_EXIF_ORIENTATION = {
810
+ None: None,
811
+ -1: None, # ExifOrientation::Unspecified, returned by the C++ probes.
812
+ 1: 0.0,
813
+ 2: 0.0,
814
+ 3: 180.0,
815
+ 4: 180.0,
816
+ 5: 90.0,
817
+ 6: -90.0,
818
+ 7: -90.0,
819
+ 8: 90.0,
820
+ }
821
+
822
+
823
+ # ----------------------------------------------------------------------------
824
+ # JPEG
825
+ # ----------------------------------------------------------------------------
826
+
827
+ # SOFn markers that libjpeg-turbo can decode. The other SOFn markers
828
+ # (hierarchical, and the reserved JPG marker) make jpeg_read_header() fail.
829
+ _JPEG_SUPPORTED_SOF = frozenset((0xC0, 0xC1, 0xC2, 0xC3, 0xC9, 0xCA, 0xCB))
830
+ _JPEG_UNSUPPORTED_SOF = frozenset((0xC5, 0xC6, 0xC7, 0xC8, 0xCD, 0xCE, 0xCF))
831
+
832
+
833
+ def _probe_jpeg(src: _ByteSource) -> ImageMetadata:
834
+ # Walks the markers up to the first SOS, like jpeg_read_header(). The
835
+ # decoder takes the EXIF orientation from the first APP1 segment that starts
836
+ # with the "Exif\0\0" header.
837
+ pos = 2 # skip SOI, already checked by the format sniffer
838
+ sof = None
839
+ orientation = None
840
+ seen_exif = False
841
+ while True:
842
+ chunk = src.read(pos, 4)
843
+ if len(chunk) < 2:
844
+ raise RuntimeError("JPEG is truncated: no SOS marker found.")
845
+ if chunk[0] != 0xFF:
846
+ # libjpeg skips garbage bytes between markers.
847
+ window = src.read(pos, 4096)
848
+ idx = window.find(b"\xff")
849
+ pos += idx if idx > 0 else len(window)
850
+ continue
851
+ marker = chunk[1]
852
+ if marker == 0xFF: # fill byte
853
+ pos += 1
854
+ continue
855
+ if marker == 0xDA: # SOS
856
+ break
857
+ if marker == 0xD9: # EOI
858
+ raise RuntimeError("JPEG has no image data.")
859
+ if marker == 0x01 or 0xD0 <= marker <= 0xD7: # standalone markers
860
+ pos += 2
861
+ continue
862
+ if len(chunk) < 4:
863
+ raise RuntimeError("JPEG is truncated.")
864
+ segment_length = (chunk[2] << 8) | chunk[3]
865
+ if segment_length < 2:
866
+ raise RuntimeError("Invalid JPEG marker segment length.")
867
+ if marker in _JPEG_SUPPORTED_SOF:
868
+ if sof is not None:
869
+ raise RuntimeError("JPEG has more than one SOF marker.")
870
+ precision, height, width, num_components = struct.unpack(
871
+ ">BHHB", src.read_exact(pos + 4, 6)
872
+ )
873
+ if segment_length != 8 + 3 * num_components:
874
+ raise RuntimeError("Invalid JPEG SOF marker length.")
875
+ if height == 0 or width == 0 or num_components == 0:
876
+ raise RuntimeError("Empty JPEG image (DNL not supported).")
877
+ sof = (precision, height, width, num_components)
878
+ elif marker in _JPEG_UNSUPPORTED_SOF:
879
+ raise RuntimeError(f"Unsupported JPEG process: SOF type 0x{marker:02x}.")
880
+ elif marker == 0xE1 and not seen_exif:
881
+ payload = src.read_exact(pos + 4, segment_length - 2)
882
+ if len(payload) > 6 and payload[:6] == b"Exif\x00\x00":
883
+ seen_exif = True
884
+ orientation = _exif_orientation_after_prefixes(payload)
885
+ pos += 2 + segment_length
886
+
887
+ if sof is None:
888
+ raise RuntimeError("JPEG has no SOF marker before SOS.")
889
+ precision, height, width, num_components = sof
890
+ if orientation is not None and 5 <= orientation <= 8:
891
+ width, height = height, width
892
+ return ImageMetadata(
893
+ format="jpeg",
894
+ width=width,
895
+ height=height,
896
+ num_channels=num_components,
897
+ bit_depth=precision,
898
+ num_frames=1,
899
+ rotation=_ROTATION_FROM_EXIF_ORIENTATION[orientation],
900
+ )
901
+
902
+
903
+ # ----------------------------------------------------------------------------
904
+ # PNG
905
+ # ----------------------------------------------------------------------------
906
+
907
+ _PNG_VALID_BIT_DEPTHS = {
908
+ 0: (1, 2, 4, 8, 16), # gray
909
+ 2: (8, 16), # RGB
910
+ 3: (1, 2, 4, 8), # palette
911
+ 4: (8, 16), # gray + alpha
912
+ 6: (8, 16), # RGBA
913
+ }
914
+
915
+
916
+ # libpng's default PNG_USER_CHUNK_MALLOC_MAX: it drops text chunks that
917
+ # decompress to more than that.
918
+ _PNG_MAX_TEXT_SIZE = 8_000_000
919
+
920
+
921
+ def _png_decompress_text(data: bytes) -> bytes | None:
922
+ decompressor = zlib.decompressobj()
923
+ try:
924
+ text = decompressor.decompress(data, _PNG_MAX_TEXT_SIZE)
925
+ except zlib.error:
926
+ return None
927
+ if decompressor.unconsumed_tail or not decompressor.eof:
928
+ return None
929
+ return text
930
+
931
+
932
+ def _png_text(chunk_type: bytes, payload: bytes) -> tuple[bytes, bytes] | None:
933
+ # Returns the keyword and (decompressed) text of a tEXt, zTXt or iTXt
934
+ # chunk, or None if the chunk is malformed.
935
+ keyword, sep, rest = payload.partition(b"\x00")
936
+ if not sep:
937
+ return None
938
+ if chunk_type == b"tEXt":
939
+ return keyword, rest
940
+ if chunk_type == b"zTXt":
941
+ # The only compression method is zlib (0).
942
+ text = _png_decompress_text(rest[1:]) if rest[:1] == b"\x00" else None
943
+ else:
944
+ # iTXt: compression flag and method, then the language tag, the
945
+ # translated keyword and the text.
946
+ fields = rest[2:].split(b"\x00", 2)
947
+ if len(rest) < 2 or len(fields) != 3:
948
+ return None
949
+ compression_flag, compression_method = rest[0], rest[1]
950
+ text = fields[2]
951
+ if compression_flag:
952
+ text = _png_decompress_text(text) if compression_method == 0 else None
953
+ return None if text is None else (keyword, text)
954
+
955
+
956
+ def _probe_png(src: _ByteSource) -> ImageMetadata:
957
+ # Reads IHDR and walks the chunks up to the first IDAT, which is what
958
+ # png_read_info() sees, and then the chunks after the image data, which is
959
+ # what png_read_end() sees: those only matter for the orientation.
960
+ ihdr = src.read_exact(8, 8 + 13)
961
+ length, chunk_type = struct.unpack_from(">I4s", ihdr)
962
+ if chunk_type != b"IHDR" or length != 13:
963
+ raise RuntimeError("PNG is missing its IHDR chunk.")
964
+ width, height, bit_depth, color_type = struct.unpack_from(">IIBB", ihdr, 8)
965
+ if not (0 < width < 2**31 and 0 < height < 2**31):
966
+ raise RuntimeError(f"Invalid PNG dimensions: {width}x{height}.")
967
+ if bit_depth not in _PNG_VALID_BIT_DEPTHS.get(color_type, ()):
968
+ raise RuntimeError(
969
+ f"Invalid PNG color type ({color_type}) and bit depth ({bit_depth})."
970
+ )
971
+
972
+ pos = 8 + 12 + 13
973
+ num_palette = None
974
+ has_trns = False
975
+ exif = None
976
+ raw_profile = None
977
+ seen_idat = False
978
+ while True:
979
+ header = src.read(pos, 8)
980
+ if len(header) < 8:
981
+ if seen_idat:
982
+ break
983
+ raise RuntimeError("Image is truncated or corrupted.")
984
+ length, chunk_type = struct.unpack(">I4s", header)
985
+ if chunk_type == b"IEND":
986
+ if not seen_idat:
987
+ raise RuntimeError("PNG has no IDAT chunk.")
988
+ break
989
+ if chunk_type == b"IDAT" and not seen_idat:
990
+ seen_idat = True
991
+ if color_type == 3 and num_palette is None:
992
+ raise RuntimeError("PNG palette image has no PLTE chunk before IDAT.")
993
+ if exif is not None:
994
+ # The chunks after the image data can't change the orientation.
995
+ break
996
+ if src.read(pos + 12 + length + 4, 4) == b"IDAT":
997
+ # Walking over the (often thousands of) IDAT chunks is slow in
998
+ # Python.
999
+ if isinstance(src.source, (str, Path)):
1000
+ pos = _png_skip_idat_chunks_from_file(str(src.source), pos)
1001
+ else:
1002
+ pos = _png_skip_idat_chunks_from_tensor(
1003
+ _source_to_tensor(src.source), pos
1004
+ )
1005
+ continue
1006
+ elif chunk_type == b"PLTE" and not seen_idat:
1007
+ num_palette = length // 3
1008
+ elif chunk_type == b"tRNS" and not seen_idat and not has_trns:
1009
+ # libpng ignores (with a warning) tRNS chunks that are invalid for
1010
+ # the color type.
1011
+ if color_type == 3:
1012
+ has_trns = num_palette is not None and 0 < length <= num_palette
1013
+ elif color_type == 0:
1014
+ has_trns = length == 2
1015
+ elif color_type == 2:
1016
+ has_trns = length == 6
1017
+ elif chunk_type == b"eXIf" and exif is None and length >= 2:
1018
+ payload = src.read(pos + 8, length)
1019
+ if (
1020
+ len(payload) == length
1021
+ and payload[0] == payload[1]
1022
+ and payload[0] in b"MI"
1023
+ ):
1024
+ exif = payload
1025
+ elif chunk_type in (b"tEXt", b"zTXt", b"iTXt"):
1026
+ payload = src.read(pos + 8, length)
1027
+ text = _png_text(chunk_type, payload) if len(payload) == length else None
1028
+ # Like Pillow, we keep the last chunk with this keyword.
1029
+ if text is not None and text[0] == b"Raw profile type exif":
1030
+ raw_profile = text[1]
1031
+ pos += 12 + length
1032
+
1033
+ # Same logic as fetch_png_orientation() in DecodePng.cpp.
1034
+ orientation = None
1035
+ if exif is not None:
1036
+ orientation = _exif_orientation(exif)
1037
+ elif raw_profile is not None:
1038
+ # Same parsing as Pillow, which decode_raw_profile_exif() in
1039
+ # DecodePng.cpp mirrors. Pillow raises on invalid hex data, we ignore it.
1040
+ try:
1041
+ raw_profile_exif = bytes.fromhex(
1042
+ b"".join(raw_profile.split(b"\n")[3:]).decode("ascii")
1043
+ )
1044
+ except ValueError:
1045
+ pass
1046
+ else:
1047
+ orientation = _exif_orientation_after_prefixes(raw_profile_exif)
1048
+ if orientation is not None and 5 <= orientation <= 8:
1049
+ width, height = height, width
1050
+ if color_type == 3:
1051
+ num_channels = 4 if has_trns else 3
1052
+ bit_depth = 8 # palette entries are 8-bit RGB(A)
1053
+ else:
1054
+ num_channels = {0: 1, 2: 3, 4: 2, 6: 4}[color_type]
1055
+ return ImageMetadata(
1056
+ format="png",
1057
+ width=width,
1058
+ height=height,
1059
+ num_channels=num_channels,
1060
+ bit_depth=bit_depth,
1061
+ num_frames=1,
1062
+ rotation=_ROTATION_FROM_EXIF_ORIENTATION[orientation],
1063
+ )
1064
+
1065
+
1066
+ # ----------------------------------------------------------------------------
1067
+ # WebP
1068
+ # ----------------------------------------------------------------------------
1069
+
1070
+ _WEBP_ANIMATION_FLAG = 0x02
1071
+ _WEBP_EXIF_FLAG = 0x08
1072
+ _WEBP_ALPHA_FLAG = 0x10
1073
+
1074
+
1075
+ def _vp8_dimensions(src: _ByteSource, payload_pos: int) -> tuple[int, int]:
1076
+ header = src.read_exact(payload_pos, 10)
1077
+ if header[3:6] != b"\x9d\x01\x2a":
1078
+ raise RuntimeError("Invalid VP8 bitstream signature.")
1079
+ width, height = struct.unpack_from("<HH", header, 6)
1080
+ width, height = width & 0x3FFF, height & 0x3FFF
1081
+ if width == 0 or height == 0:
1082
+ raise RuntimeError("Invalid VP8 dimensions.")
1083
+ return width, height
1084
+
1085
+
1086
+ def _vp8l_info(src: _ByteSource, payload_pos: int) -> tuple[int, int, bool]:
1087
+ header = src.read_exact(payload_pos, 5)
1088
+ if header[0] != 0x2F:
1089
+ raise RuntimeError("Invalid VP8L bitstream signature.")
1090
+ (bits,) = struct.unpack_from("<I", header, 1)
1091
+ if bits >> 29 != 0:
1092
+ raise RuntimeError("Invalid VP8L version.")
1093
+ width = (bits & 0x3FFF) + 1
1094
+ height = ((bits >> 14) & 0x3FFF) + 1
1095
+ has_alpha = bool((bits >> 28) & 1)
1096
+ return width, height, has_alpha
1097
+
1098
+
1099
+ def _probe_webp(src: _ByteSource) -> ImageMetadata:
1100
+ # Mirrors WebPGetFeatures() (dimensions and alpha), WebPAnimDecoder (frame
1101
+ # count and canvas size) and WebPDemux (the EXIF chunk, which libwebpdemux
1102
+ # only exposes when the VP8X EXIF flag is set).
1103
+ first_type, first_size = struct.unpack("<4sI", src.read_exact(12, 8))
1104
+ orientation = None
1105
+ if first_type == b"VP8 ":
1106
+ width, height = _vp8_dimensions(src, 20)
1107
+ has_alpha = False
1108
+ num_frames = 1
1109
+ elif first_type == b"VP8L":
1110
+ width, height, has_alpha = _vp8l_info(src, 20)
1111
+ num_frames = 1
1112
+ elif first_type == b"VP8X":
1113
+ vp8x = src.read_exact(20, 10)
1114
+ flags = vp8x[0]
1115
+ canvas_width = int.from_bytes(vp8x[4:7], "little") + 1
1116
+ canvas_height = int.from_bytes(vp8x[7:10], "little") + 1
1117
+ is_animated = bool(flags & _WEBP_ANIMATION_FLAG)
1118
+
1119
+ num_anmf = 0
1120
+ seen_alph = False
1121
+ bitstream = None # (width, height, vp8l_alpha_or_None) of first image
1122
+ exif = None
1123
+ pos = 20 + first_size + (first_size & 1)
1124
+ while True:
1125
+ header = src.read(pos, 8)
1126
+ if len(header) < 8:
1127
+ break
1128
+ chunk_type, chunk_size = struct.unpack("<4sI", header)
1129
+ if chunk_type == b"ANMF":
1130
+ num_anmf += 1
1131
+ elif not is_animated and bitstream is None:
1132
+ if chunk_type == b"ALPH":
1133
+ seen_alph = True
1134
+ elif chunk_type == b"VP8 ":
1135
+ bitstream = (*_vp8_dimensions(src, pos + 8), None)
1136
+ elif chunk_type == b"VP8L":
1137
+ bitstream = _vp8l_info(src, pos + 8)
1138
+ if chunk_type == b"EXIF" and exif is None and flags & _WEBP_EXIF_FLAG:
1139
+ exif = src.read_exact(pos + 8, chunk_size)
1140
+ pos += 8 + chunk_size + (chunk_size & 1)
1141
+
1142
+ if exif is not None:
1143
+ orientation = _exif_orientation_after_prefixes(exif)
1144
+
1145
+ if is_animated:
1146
+ if num_anmf == 0:
1147
+ raise RuntimeError("Animated WebP has no frames.")
1148
+ width, height = canvas_width, canvas_height
1149
+ has_alpha = bool(flags & _WEBP_ALPHA_FLAG)
1150
+ num_frames = num_anmf
1151
+ else:
1152
+ if bitstream is None:
1153
+ raise RuntimeError("WebP has no VP8 or VP8L bitstream.")
1154
+ width, height, vp8l_alpha = bitstream
1155
+ if (width, height) != (canvas_width, canvas_height):
1156
+ raise RuntimeError("WebP canvas and bitstream dimensions differ.")
1157
+ if vp8l_alpha is None:
1158
+ has_alpha = bool(flags & _WEBP_ALPHA_FLAG) or seen_alph
1159
+ else:
1160
+ has_alpha = vp8l_alpha or seen_alph
1161
+ num_frames = 1
1162
+ else:
1163
+ raise RuntimeError(f"Unexpected first WebP chunk: {first_type!r}.")
1164
+
1165
+ if orientation is not None and 5 <= orientation <= 8:
1166
+ width, height = height, width
1167
+ return ImageMetadata(
1168
+ format="webp",
1169
+ width=width,
1170
+ height=height,
1171
+ num_channels=4 if has_alpha else 3,
1172
+ bit_depth=8,
1173
+ num_frames=num_frames,
1174
+ rotation=_ROTATION_FROM_EXIF_ORIENTATION[orientation],
1175
+ )
1176
+
1177
+
1178
+ # ----------------------------------------------------------------------------
1179
+ # HEIC (ISOBMFF / HEIF)
1180
+ # ----------------------------------------------------------------------------
1181
+
1182
+
1183
+ def _iter_boxes(data: bytes, start: int, end: int):
1184
+ # Yields (box_type, payload_start, payload_end) for the boxes in
1185
+ # data[start:end].
1186
+ pos = start
1187
+ while pos + 8 <= end:
1188
+ size, box_type = struct.unpack_from(">I4s", data, pos)
1189
+ header_size = 8
1190
+ if size == 1:
1191
+ if pos + 16 > end:
1192
+ raise RuntimeError("ISOBMFF box is truncated.")
1193
+ (size,) = struct.unpack_from(">Q", data, pos + 8)
1194
+ header_size = 16
1195
+ elif size == 0:
1196
+ size = end - pos
1197
+ if box_type == b"uuid":
1198
+ header_size += 16
1199
+ if size < header_size or pos + size > end:
1200
+ raise RuntimeError("Invalid or truncated ISOBMFF box.")
1201
+ yield box_type, pos + header_size, pos + size
1202
+ pos += size
1203
+
1204
+
1205
+ def _iter_top_level_boxes(src: _ByteSource):
1206
+ # Like _iter_boxes, over the whole file, reading only box headers and the
1207
+ # payloads we ask for. Yields (box_type, payload_start, payload_end).
1208
+ pos = 0
1209
+ while True:
1210
+ header = src.read(pos, 16)
1211
+ if len(header) < 8:
1212
+ return
1213
+ size, box_type = struct.unpack_from(">I4s", header)
1214
+ header_size = 8
1215
+ if size == 1:
1216
+ if len(header) < 16:
1217
+ raise RuntimeError("ISOBMFF box is truncated.")
1218
+ (size,) = struct.unpack_from(">Q", header, 8)
1219
+ header_size = 16
1220
+ elif size == 0: # the box extends to the end of the file
1221
+ size = src.size - pos
1222
+ if size < header_size:
1223
+ raise RuntimeError("Invalid ISOBMFF box size.")
1224
+ yield box_type, pos + header_size, pos + size
1225
+ pos += size
1226
+
1227
+
1228
+ class _HeifMeta:
1229
+ # The parts of a 'meta' box we need: items, their references, and their
1230
+ # associated properties (in association order).
1231
+
1232
+ def __init__(self, data: bytes):
1233
+ self.primary_id = None
1234
+ self.item_types: dict[int, bytes] = {}
1235
+ self.hidden: set[int] = set()
1236
+ # refs[ref_type][from_id] = [to_ids...], in file order
1237
+ self.refs: dict[bytes, dict[int, list[int]]] = {}
1238
+ self._refs_to: dict[bytes, dict[int, list[int]]] = {}
1239
+ self._properties: list[tuple[bytes, bytes]] = []
1240
+ self._associations: dict[int, list[int]] = {}
1241
+
1242
+ for box_type, start, end in _iter_boxes(data, 4, len(data)):
1243
+ if box_type == b"pitm":
1244
+ version = data[start]
1245
+ fmt = ">H" if version == 0 else ">I"
1246
+ (self.primary_id,) = struct.unpack_from(fmt, data, start + 4)
1247
+ elif box_type == b"iinf":
1248
+ version = data[start]
1249
+ entries_start = start + 4 + (2 if version == 0 else 4)
1250
+ for infe_type, s, e in _iter_boxes(data, entries_start, end):
1251
+ if infe_type == b"infe":
1252
+ self._parse_infe(data, s, e)
1253
+ elif box_type == b"iref":
1254
+ version = data[start]
1255
+ id_fmt, id_size = (">H", 2) if version == 0 else (">I", 4)
1256
+ for ref_type, s, e in _iter_boxes(data, start + 4, end):
1257
+ (from_id,) = struct.unpack_from(id_fmt, data, s)
1258
+ (count,) = struct.unpack_from(">H", data, s + id_size)
1259
+ first = s + id_size + 2
1260
+ if first + count * id_size > e:
1261
+ raise RuntimeError("Invalid 'iref' box.")
1262
+ to_ids = [
1263
+ struct.unpack_from(id_fmt, data, first + i * id_size)[0]
1264
+ for i in range(count)
1265
+ ]
1266
+ self.refs.setdefault(ref_type, {}).setdefault(from_id, []).extend(
1267
+ to_ids
1268
+ )
1269
+ for to_id in to_ids:
1270
+ self._refs_to.setdefault(ref_type, {}).setdefault(
1271
+ to_id, []
1272
+ ).append(from_id)
1273
+ elif box_type == b"iprp":
1274
+ for iprp_type, s, e in _iter_boxes(data, start, end):
1275
+ if iprp_type == b"ipco":
1276
+ self._properties = [
1277
+ (t, data[ps:pe]) for t, ps, pe in _iter_boxes(data, s, e)
1278
+ ]
1279
+ elif iprp_type == b"ipma":
1280
+ self._parse_ipma(data, s, e)
1281
+
1282
+ def _parse_infe(self, data, start, end):
1283
+ version = data[start]
1284
+ if version < 2:
1285
+ return
1286
+ flags = int.from_bytes(data[start + 1 : start + 4], "big")
1287
+ if version == 2:
1288
+ (item_id,) = struct.unpack_from(">H", data, start + 4)
1289
+ item_type = data[start + 8 : start + 12]
1290
+ else:
1291
+ (item_id,) = struct.unpack_from(">I", data, start + 4)
1292
+ item_type = data[start + 10 : start + 14]
1293
+ self.item_types[item_id] = bytes(item_type)
1294
+ if flags & 1:
1295
+ self.hidden.add(item_id)
1296
+
1297
+ def _parse_ipma(self, data, start, end):
1298
+ version = data[start]
1299
+ flags = int.from_bytes(data[start + 1 : start + 4], "big")
1300
+ (entry_count,) = struct.unpack_from(">I", data, start + 4)
1301
+ pos = start + 8
1302
+ for _ in range(entry_count):
1303
+ if version < 1:
1304
+ (item_id,) = struct.unpack_from(">H", data, pos)
1305
+ pos += 2
1306
+ else:
1307
+ (item_id,) = struct.unpack_from(">I", data, pos)
1308
+ pos += 4
1309
+ num_associations = data[pos]
1310
+ pos += 1
1311
+ indices = self._associations.setdefault(item_id, [])
1312
+ for _ in range(num_associations):
1313
+ if flags & 1:
1314
+ (value,) = struct.unpack_from(">H", data, pos)
1315
+ pos += 2
1316
+ indices.append(value & 0x7FFF)
1317
+ else:
1318
+ indices.append(data[pos] & 0x7F)
1319
+ pos += 1
1320
+
1321
+ def properties(self, item_id: int) -> list[tuple[bytes, bytes]]:
1322
+ # (property_type, property_payload) pairs, in association order.
1323
+ # Property indices are 1-based; 0 means "no property".
1324
+ return [
1325
+ self._properties[i - 1]
1326
+ for i in self._associations.get(item_id, ())
1327
+ if 0 < i <= len(self._properties)
1328
+ ]
1329
+
1330
+ def find_property(self, item_id: int, property_type: bytes) -> bytes | None:
1331
+ for t, payload in self.properties(item_id):
1332
+ if t == property_type:
1333
+ return payload
1334
+ return None
1335
+
1336
+ def refs_from(self, ref_type: bytes, from_id: int) -> list[int]:
1337
+ return self.refs.get(ref_type, {}).get(from_id, [])
1338
+
1339
+ def refs_to(self, ref_type: bytes, to_id: int) -> list[int]:
1340
+ return self._refs_to.get(ref_type, {}).get(to_id, [])
1341
+
1342
+
1343
+ _HEIC_ALPHA_URNS = (
1344
+ b"urn:mpeg:avc:2015:auxid:1",
1345
+ b"urn:mpeg:hevc:2015:auxid:1",
1346
+ b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha",
1347
+ )
1348
+
1349
+
1350
+ def _aux_type(auxc_payload: bytes | None) -> bytes | None:
1351
+ # auxC is a FullBox holding a null-terminated URN.
1352
+ if auxc_payload is None:
1353
+ return None
1354
+ return auxc_payload[4:].split(b"\x00", 1)[0]
1355
+
1356
+
1357
+ def _ispe_size(meta: _HeifMeta, item_id: int) -> tuple[int, int]:
1358
+ ispe = meta.find_property(item_id, b"ispe")
1359
+ if ispe is None or len(ispe) < 12:
1360
+ raise RuntimeError(f"Image item {item_id} has no valid 'ispe' property.")
1361
+ return struct.unpack_from(">II", ispe, 4)
1362
+
1363
+
1364
+ def _read_meta_box(src: _ByteSource) -> bytes:
1365
+ # Returns the payload of the top-level 'meta' box, skipping everything else
1366
+ # (e.g. 'mdat') without reading it.
1367
+ for box_type, start, end in _iter_top_level_boxes(src):
1368
+ if box_type == b"meta":
1369
+ return src.read_exact(start, end - start)
1370
+ raise RuntimeError("HEIC has no 'meta' box.")
1371
+
1372
+
1373
+ def _av1c_depth(av1c: bytes) -> int:
1374
+ flags = av1c[2]
1375
+ if flags & 0x20: # twelve_bit
1376
+ return 12
1377
+ if flags & 0x40: # high_bitdepth
1378
+ return 10
1379
+ return 8
1380
+
1381
+
1382
+ # EXIF orientation of the irot angle (counter-clockwise quarter turns) and imir
1383
+ # axis (None if there's no imir). The HEIF spec mandates that irot comes before
1384
+ # imir. Same as avif_exif_orientation() in DecodeAvif.cpp.
1385
+ _EXIF_ORIENTATION_FROM_IROT_IMIR = {
1386
+ (0, None): 1,
1387
+ (0, 0): 4,
1388
+ (0, 1): 2,
1389
+ (1, None): 8,
1390
+ (1, 0): 5,
1391
+ (1, 1): 7,
1392
+ (2, None): 3,
1393
+ (2, 0): 2,
1394
+ (2, 1): 4,
1395
+ (3, None): 6,
1396
+ (3, 0): 7,
1397
+ (3, 1): 5,
1398
+ }
1399
+
1400
+
1401
+ _HEIC_IMAGE_ITEM_TYPES = frozenset(
1402
+ (
1403
+ b"jpeg",
1404
+ b"hvc1",
1405
+ b"av01",
1406
+ b"vvc1",
1407
+ b"avc1",
1408
+ b"unci",
1409
+ b"j2k1",
1410
+ b"mski",
1411
+ b"grid",
1412
+ b"iovl",
1413
+ b"iden",
1414
+ b"tili",
1415
+ )
1416
+ )
1417
+ _HEIC_DERIVED_ITEM_TYPES = frozenset((b"grid", b"iovl", b"iden"))
1418
+
1419
+
1420
+ def _probe_heic(src: _ByteSource) -> ImageMetadata:
1421
+ # Mirrors libheif: the top-level images are the non-hidden image items that
1422
+ # aren't thumbnails or auxiliary images, in item-ID order. The decoder uses
1423
+ # the first one's geometry (and requires every other one to match).
1424
+ meta = _HeifMeta(_read_meta_box(src))
1425
+
1426
+ image_ids = sorted(
1427
+ i for i, t in meta.item_types.items() if t in _HEIC_IMAGE_ITEM_TYPES
1428
+ )
1429
+ if meta.primary_id not in image_ids or meta.primary_id in meta.hidden:
1430
+ raise RuntimeError(
1431
+ "'pitm' box references an unsupported or non-existing image."
1432
+ )
1433
+ top_level = [
1434
+ i
1435
+ for i in image_ids
1436
+ if i not in meta.hidden
1437
+ and not meta.refs_from(b"thmb", i)
1438
+ and not meta.refs_from(b"auxl", i)
1439
+ ]
1440
+ if not top_level:
1441
+ raise RuntimeError("HEIC file should contain at least one top-level image.")
1442
+ item_id = top_level[0]
1443
+
1444
+ width, height = _ispe_size(meta, item_id)
1445
+ irot = imir = None
1446
+ for prop_type, payload in meta.properties(item_id):
1447
+ if prop_type == b"clap":
1448
+ w_num, w_den, h_num, h_den = struct.unpack_from(">iIiI", payload)
1449
+ if w_den == 0 or h_den == 0:
1450
+ raise RuntimeError("Invalid 'clap' property.")
1451
+ width = (w_num + w_den // 2) // w_den
1452
+ height = (h_num + h_den // 2) // h_den
1453
+ elif prop_type == b"irot":
1454
+ irot = payload[0] & 0x03
1455
+ if irot in (1, 3):
1456
+ width, height = height, width
1457
+ elif prop_type == b"imir":
1458
+ imir = payload[0] & 0x01
1459
+ if irot is None and imir is None:
1460
+ orientation = None
1461
+ else:
1462
+ orientation = _EXIF_ORIENTATION_FROM_IROT_IMIR[(irot or 0, imir)]
1463
+
1464
+ # Luma bit depth, from the first non-derived image down the 'dimg' chain.
1465
+ coded_id = item_id
1466
+ for _ in range(len(meta.item_types) + 1):
1467
+ if meta.item_types.get(coded_id) not in _HEIC_DERIVED_ITEM_TYPES:
1468
+ break
1469
+ children = meta.refs_from(b"dimg", coded_id)
1470
+ if not children:
1471
+ raise RuntimeError("Derived HEIC image has no input image.")
1472
+ coded_id = children[0]
1473
+ coded_type = meta.item_types.get(coded_id)
1474
+ if coded_type == b"hvc1":
1475
+ hvcc = meta.find_property(coded_id, b"hvcC")
1476
+ if hvcc is None or len(hvcc) < 18:
1477
+ raise RuntimeError("No hvcC property in hvc1 type image.")
1478
+ bit_depth = (hvcc[17] & 0x07) + 8
1479
+ elif coded_type == b"av01":
1480
+ av1c = meta.find_property(coded_id, b"av1C")
1481
+ if av1c is None:
1482
+ raise RuntimeError("No av1C property in av01 type image.")
1483
+ bit_depth = _av1c_depth(av1c)
1484
+ elif coded_type == b"jpeg":
1485
+ bit_depth = 8
1486
+ else:
1487
+ raise RuntimeError(f"Unsupported HEIC image item type: {coded_type!r}.")
1488
+
1489
+ def has_alpha_aux(image_id):
1490
+ return any(
1491
+ _aux_type(meta.find_property(i, b"auxC")) in _HEIC_ALPHA_URNS
1492
+ for i in meta.refs_to(b"auxl", image_id)
1493
+ )
1494
+
1495
+ has_alpha = has_alpha_aux(item_id) or (
1496
+ meta.item_types[item_id] == b"grid"
1497
+ and any(has_alpha_aux(t) for t in meta.refs_from(b"dimg", item_id))
1498
+ )
1499
+ return ImageMetadata(
1500
+ format="heic",
1501
+ width=width,
1502
+ height=height,
1503
+ num_channels=4 if has_alpha else 3,
1504
+ bit_depth=bit_depth,
1505
+ num_frames=len(top_level),
1506
+ rotation=_ROTATION_FROM_EXIF_ORIENTATION[orientation],
1507
+ )
1508
+
1509
+
1510
+ _PY_PROBES = {
1511
+ "jpeg": _probe_jpeg,
1512
+ "png": _probe_png,
1513
+ "webp": _probe_webp,
1514
+ "heic": _probe_heic,
1515
+ }
1516
+
1517
+ _CPP_PROBES = {
1518
+ "gif": (_probe_gif_from_tensor, _probe_gif_from_file),
1519
+ "avif": (_probe_avif_from_tensor, _probe_avif_from_file),
1520
+ }
1521
+
1522
+
1523
+ def _cpp_probe(fmt: str, source: str | Path | bytes | torch.Tensor) -> ImageMetadata:
1524
+ probe, probe_from_file = _CPP_PROBES[fmt]
1525
+ if isinstance(source, (str, Path)):
1526
+ result = probe_from_file(str(source))
1527
+ else:
1528
+ result = probe(_source_to_tensor(source))
1529
+ width, height, num_channels, bit_depth, num_frames, orientation = result
1530
+ return ImageMetadata(
1531
+ format=fmt,
1532
+ width=width,
1533
+ height=height,
1534
+ num_channels=num_channels,
1535
+ bit_depth=bit_depth,
1536
+ num_frames=num_frames,
1537
+ rotation=_ROTATION_FROM_EXIF_ORIENTATION[orientation],
1538
+ )
1539
+
1540
+
1541
+ def get_image_metadata(source: str | Path | bytes | torch.Tensor) -> ImageMetadata:
1542
+ """Get the metadata of an encoded image, without decoding it.
1543
+
1544
+ The format is detected from the encoded data, like in
1545
+ :func:`~torchcodec.decoders.decode_image`.
1546
+
1547
+ See :class:`ImageMetadata` for the returned attributes, which all describe
1548
+ the output of the decoders.
1549
+
1550
+ Example:
1551
+
1552
+ .. code-block:: python
1553
+
1554
+ from torchcodec.decoders import get_image_metadata
1555
+
1556
+ metadata = get_image_metadata("image.jpg")
1557
+ print(metadata.width, metadata.height)
1558
+
1559
+ Args:
1560
+ source (str, ``pathlib.Path``, bytes, or ``torch.Tensor``):
1561
+ The encoded image data: a path (``str`` or ``pathlib.Path``), a
1562
+ ``bytes`` object, or a 1-D uint8 ``torch.Tensor`` of the raw encoded
1563
+ bytes.
1564
+
1565
+ Returns:
1566
+ ImageMetadata: The image metadata.
1567
+ """
1568
+ with _ByteSource(source) as src:
1569
+ fmt = _detect_image_format_from_header(src.read(0, 64))
1570
+ if fmt in _CPP_PROBES:
1571
+ return _cpp_probe(fmt, source)
1572
+ try:
1573
+ return _PY_PROBES[fmt](src)
1574
+ except (struct.error, IndexError):
1575
+ raise RuntimeError("Image is truncated or corrupted.") from None