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,577 @@
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
+ from __future__ import annotations
8
+
9
+ import enum
10
+ import functools
11
+ from dataclasses import dataclass
12
+ from typing import NamedTuple
13
+
14
+ import torch
15
+
16
+ from torchcodec._core.ops import (
17
+ _blocks_create_packet,
18
+ _blocks_frame_metadata,
19
+ _blocks_frame_planes,
20
+ _blocks_get_ffmpeg_enum_name,
21
+ _blocks_packet_get_fields,
22
+ )
23
+
24
+ from ._helpers import _bytes_to_tensor, _process_local, _tensor_to_bytes
25
+
26
+
27
+ # Must match FFmpegEnum in custom_ops.cpp.
28
+ class _FFmpegEnum(enum.IntEnum):
29
+ PIXEL_FORMAT = 0
30
+ COLOR_SPACE = 1
31
+ COLOR_RANGE = 2
32
+ COLOR_PRIMARIES = 3
33
+ COLOR_TRANSFER_CHARACTERISTIC = 4
34
+ PACKET_SIDE_DATA_TYPE = 5
35
+
36
+
37
+ # See Note [Returning text from ops] in custom_ops.cpp.
38
+ @functools.cache
39
+ def _get_ffmpeg_enum_name(*, kind: _FFmpegEnum, value: int) -> str:
40
+ return _blocks_get_ffmpeg_enum_name(kind=int(kind), value=value)
41
+
42
+
43
+ class _Metadata(NamedTuple):
44
+ # The fields of the `_blocks_frame_metadata` op, in order.
45
+ pixel_format: str
46
+ color_space: str
47
+ color_range: str
48
+ color_primaries: str
49
+ color_transfer_characteristic: str
50
+ bit_depth: int
51
+ width: int
52
+ height: int
53
+ rotation: float
54
+
55
+
56
+ class Packet:
57
+ """One compressed packet of one stream.
58
+
59
+ A :class:`Demuxer` creates them, and a :class:`VideoPacketDecoder` or an
60
+ :class:`AudioPacketDecoder` consumes them. You can also build one from
61
+ compressed data that doesn't come from a ``Demuxer``, with
62
+ :meth:`from_bytes` or :meth:`from_tensor`.
63
+
64
+ Packets can be pickled, e.g. to be decoded in another process. The pickles
65
+ are only guaranteed to be readable by the same version of TorchCodec.
66
+ """
67
+
68
+ stream_index: int
69
+ """The index of the stream this packet belongs to, absolute across all
70
+ media types. When a demuxer follows more than one stream, this is what
71
+ routes each packet to the right decoder."""
72
+
73
+ def __init__(
74
+ self,
75
+ handle: torch.Tensor,
76
+ stream_index: int,
77
+ *,
78
+ generation: int = 0,
79
+ ):
80
+ self._handle = handle
81
+ self.stream_index = stream_index
82
+ # Which side of the demuxer's last seek this packet came from. Private:
83
+ # it exists so a decoder can catch a missing reset(), not for callers to
84
+ # reason about. See _BasePacketDecoder.decode().
85
+ self._generation = generation
86
+ # Load fields only once, on demand (it matters for perf on
87
+ # multi-threaded pipelines)
88
+ self._fields_loaded = False
89
+
90
+ @classmethod
91
+ def from_bytes(
92
+ cls,
93
+ data: bytes | bytearray | memoryview,
94
+ *,
95
+ pts: int | None = None,
96
+ dts: int | None = None,
97
+ duration: int = 0,
98
+ flags: int = 0,
99
+ side_data: dict[str, bytes] | None = None,
100
+ stream_index: int = 0,
101
+ ) -> Packet:
102
+ """Build a packet from compressed data, e.g. read from a database or
103
+ received from the network.
104
+
105
+ Only ``data`` is required: most codecs need nothing else to decode it.
106
+
107
+ Args:
108
+ data (bytes, bytearray or memoryview): The compressed data of one
109
+ packet. It is copied. Each packet must contain exactly one
110
+ access unit, which is what a demuxer such as :class:`Demuxer`
111
+ or FFmpeg's produces.
112
+ pts (int, optional): The :term:`pts`, in units of the stream's time
113
+ base (:attr:`StreamMetadata.time_base`). The decoded frames'
114
+ :attr:`RawFrame.pts` come from it.
115
+ ``None`` (default) if unknown.
116
+ dts (int, optional): The decoding timestamp, in units of the
117
+ stream's time base. ``None`` (default) if unknown.
118
+ duration (int, optional): How long the packet lasts, in units of
119
+ the stream's time base. Default: 0, for unknown.
120
+ flags (int, optional): FFmpeg's ``AV_PKT_FLAG_*`` bits, e.g. 1
121
+ (``AV_PKT_FLAG_KEY``) for a keyframe. ``AV_PKT_FLAG_TRUSTED``
122
+ (8) isn't allowed. Default: 0.
123
+ side_data (dict, optional): Extra data about the packet, keyed by
124
+ FFmpeg's names for its types, e.g. ``"Skip Samples"``.
125
+ stream_index (int, optional): See :attr:`stream_index`. Default: 0.
126
+
127
+ Returns:
128
+ Packet: The packet.
129
+ """
130
+ if not isinstance(data, (bytes, bytearray, memoryview)):
131
+ raise TypeError(
132
+ f"data must be bytes, bytearray or memoryview, got {type(data)}."
133
+ )
134
+ return cls.from_tensor(
135
+ _bytes_to_tensor(data),
136
+ pts=pts,
137
+ dts=dts,
138
+ duration=duration,
139
+ flags=flags,
140
+ side_data=side_data,
141
+ stream_index=stream_index,
142
+ )
143
+
144
+ @classmethod
145
+ def from_tensor(
146
+ cls,
147
+ data: torch.Tensor,
148
+ *,
149
+ pts: int | None = None,
150
+ dts: int | None = None,
151
+ duration: int = 0,
152
+ flags: int = 0,
153
+ side_data: dict[str, bytes] | None = None,
154
+ stream_index: int = 0,
155
+ ) -> Packet:
156
+ """Build a packet from compressed data in a tensor.
157
+
158
+ Same as :meth:`from_bytes`, except for ``data``.
159
+
160
+ Args:
161
+ data (torch.Tensor): The compressed data of one packet, as a
162
+ contiguous 1D uint8 CPU tensor. It is copied. Each packet
163
+ must contain exactly one access unit, which is what a
164
+ demuxer such as :class:`Demuxer` or FFmpeg's produces.
165
+ pts (int, optional): See :meth:`from_bytes`.
166
+ dts (int, optional): See :meth:`from_bytes`.
167
+ duration (int, optional): See :meth:`from_bytes`.
168
+ flags (int, optional): See :meth:`from_bytes`.
169
+ side_data (dict, optional): See :meth:`from_bytes`.
170
+ stream_index (int, optional): See :meth:`from_bytes`.
171
+
172
+ Returns:
173
+ Packet: The packet.
174
+ """
175
+ if not isinstance(data, torch.Tensor):
176
+ raise TypeError(f"data must be a tensor, got {type(data)}.")
177
+ side_data = side_data or {}
178
+ handle = _blocks_create_packet(
179
+ data,
180
+ pts=pts,
181
+ dts=dts,
182
+ duration=duration,
183
+ flags=flags,
184
+ side_data_names=list(side_data),
185
+ side_data_values=[_bytes_to_tensor(v) for v in side_data.values()],
186
+ )
187
+ return cls(handle, stream_index)
188
+
189
+ def _load_fields(self) -> None:
190
+ (
191
+ self._data,
192
+ self._pts,
193
+ self._dts,
194
+ self._duration,
195
+ self._flags,
196
+ self._side_data_types,
197
+ self._side_data_values,
198
+ ) = _blocks_packet_get_fields(self._handle)
199
+ self._fields_loaded = True
200
+
201
+ def __reduce__(self):
202
+ kwargs = {
203
+ "pts": self.pts,
204
+ "dts": self.dts,
205
+ "duration": self.duration,
206
+ "flags": self.flags,
207
+ "side_data": self.side_data,
208
+ "stream_index": self.stream_index,
209
+ }
210
+ # The data is pickled as bytes rather than as the data tensor. Under
211
+ # torch.multiprocessing (mp.Queue, DataLoader workers...), a tensor is
212
+ # copied into a shared memory file, which the receiver gets through a
213
+ # file descriptor. That has a fixed cost of a few hundred microseconds,
214
+ # which only pays off above a few MB, while a packet is usually a few
215
+ # KB: copying its bytes into the pickle is about 10x faster. And every
216
+ # tensor in flight holds a file descriptor, so sending a few thousand
217
+ # packets at once would hit the open files limit.
218
+ #
219
+ # The generation is kept so that a decoder in another process still
220
+ # catches a missing reset() after a seek.
221
+ return (
222
+ _unpickle_packet,
223
+ (_tensor_to_bytes(self.data), kwargs, self._generation),
224
+ )
225
+
226
+ @property
227
+ def data(self) -> torch.Tensor:
228
+ """The compressed data, as a 1D uint8 CPU tensor.
229
+
230
+ It is a view on the packet's data: writing to it modifies the packet,
231
+ so ``.clone()`` it first.
232
+ """
233
+ if not self._fields_loaded:
234
+ self._load_fields()
235
+ return self._data
236
+
237
+ @property
238
+ def pts(self) -> int | None:
239
+ """The :term:`pts`, in units of the stream's time base
240
+ (:attr:`StreamMetadata.time_base`). ``None`` if unknown."""
241
+ if not self._fields_loaded:
242
+ self._load_fields()
243
+ return self._pts
244
+
245
+ @property
246
+ def dts(self) -> int | None:
247
+ """The decoding timestamp, in units of the stream's time base. ``None``
248
+ if unknown."""
249
+ if not self._fields_loaded:
250
+ self._load_fields()
251
+ return self._dts
252
+
253
+ @property
254
+ def duration(self) -> int:
255
+ """How long the packet lasts, in units of the stream's time base. 0 if
256
+ unknown."""
257
+ if not self._fields_loaded:
258
+ self._load_fields()
259
+ return self._duration
260
+
261
+ @property
262
+ def flags(self) -> int:
263
+ """FFmpeg's ``AV_PKT_FLAG_*`` bits, e.g. ``flags & 1`` is set for
264
+ keyframes."""
265
+ if not self._fields_loaded:
266
+ self._load_fields()
267
+ return self._flags
268
+
269
+ @property
270
+ def side_data(self) -> dict[str, bytes]:
271
+ """Extra data about the packet, keyed by FFmpeg's names for its types,
272
+ e.g. ``"Skip Samples"``."""
273
+ if not self._fields_loaded:
274
+ self._load_fields()
275
+ return {
276
+ _get_ffmpeg_enum_name(
277
+ kind=_FFmpegEnum.PACKET_SIDE_DATA_TYPE, value=type_
278
+ ): (_tensor_to_bytes(value))
279
+ for type_, value in zip(self._side_data_types, self._side_data_values)
280
+ }
281
+
282
+
283
+ def _unpickle_packet(data: bytes, kwargs: dict, generation: int) -> Packet:
284
+ packet = Packet.from_bytes(data, **kwargs)
285
+ packet._generation = generation
286
+ return packet
287
+
288
+
289
+ @_process_local(
290
+ "Its planes are views on FFmpeg's own memory. To send the samples, copy "
291
+ "them out first - tuple(p.clone() for p in raw_frame.planes) - or convert "
292
+ "them with a ColorConverter and send the resulting Frame."
293
+ )
294
+ class RawFrame:
295
+ """One decoded video frame, exactly as the decoder produced it.
296
+
297
+ You cannot build one yourself: a :class:`VideoPacketDecoder` creates
298
+ them. Use a :class:`ColorConverter` to turn them into RGB
299
+ :class:`~torchcodec.Frame`\\ s, or you can read and transform the raw
300
+ samples directly from :attr:`planes`::
301
+
302
+
303
+ for packet in demuxer:
304
+ for raw_frame in packet_decoder.decode(packet):
305
+ y, u, v = raw_frame.planes
306
+ # For a 480x270 yuv420p frame, y is [270, 480] uint8, and the
307
+ # chroma is subsampled: u and v are [135, 240] each.
308
+ print(y.shape, u.shape, v.shape)
309
+
310
+ Nothing here has been converted. The samples are in the codec's own pixel
311
+ format (typically YUV), on the device of the :class:`VideoPacketDecoder`
312
+ that decoded them, and
313
+ :attr:`width`, :attr:`height` and :attr:`planes` are all pre-rotation:
314
+ :attr:`rotation` is what a :class:`ColorConverter` applies for you, and
315
+ what you have to apply yourself if you convert :attr:`planes` on your own.
316
+
317
+ .. important::
318
+
319
+ On CUDA, the samples are produced on the CUDA stream that was current when
320
+ you called :meth:`VideoPacketDecoder.decode`, and all of that work is
321
+ enqueued by the time the call returns. If you consume them on any other stream
322
+ (via :class:`ColorConverter` or by reading :attr:`planes`), you must
323
+ handle synchronization yourself. See
324
+ :ref:`sphx_glr_generated_examples_low_level_cuda_streams.py`.
325
+ """
326
+
327
+ pts: int | None
328
+ """The :term:`pts` of this frame, in units of the stream's time base
329
+ (:attr:`StreamMetadata.time_base`), like the :attr:`Packet.pts` it comes
330
+ from. ``None`` if the frame has no
331
+ timestamp (e.g. in raw H.264 streams).
332
+
333
+ Unlike :attr:`pts_seconds`, it is exact: use it to match a frame to the
334
+ timestamp of a packet."""
335
+ pts_seconds: float
336
+ """The :term:`pts` of this frame, in seconds. ``NaN`` if the frame has no
337
+ timestamp (e.g. in raw H.264 streams)."""
338
+ duration_seconds: float
339
+ """How long this frame is displayed for, in seconds."""
340
+ storage_cuda: torch.Tensor | None
341
+ """The CUDA allocation backing :attr:`planes`, or ``None`` on CPU.
342
+
343
+ This tensor is exposed for one purpose, which is to let you call
344
+ :meth:`torch.Tensor.record_stream` if you want to. See
345
+ :ref:`sphx_glr_generated_examples_low_level_cuda_streams.py` for more details.
346
+ You shouldn't read or write this tensor directly.
347
+ """
348
+
349
+ def __init__(
350
+ self,
351
+ handle: torch.Tensor,
352
+ pts: int | None,
353
+ pts_seconds: float,
354
+ duration_seconds: float,
355
+ storage: torch.Tensor | None = None,
356
+ ):
357
+ self._handle = handle
358
+ self.storage_cuda = storage
359
+ self.pts = pts
360
+ self.pts_seconds = pts_seconds
361
+ self.duration_seconds = duration_seconds
362
+ self._metadata: _Metadata | None = None
363
+ self._planes: tuple[torch.Tensor, ...] | None = None
364
+
365
+ @property
366
+ def _device(self) -> torch.device:
367
+ return (
368
+ self.storage_cuda.device
369
+ if self.storage_cuda is not None
370
+ else torch.device("cpu")
371
+ )
372
+
373
+ def _get_metadata(self) -> _Metadata:
374
+ if self._metadata is None:
375
+ (
376
+ pixel_format,
377
+ color_space,
378
+ color_range,
379
+ color_primaries,
380
+ color_transfer_characteristic,
381
+ *rest,
382
+ ) = _blocks_frame_metadata(self._handle)
383
+ self._metadata = _Metadata(
384
+ _get_ffmpeg_enum_name(
385
+ kind=_FFmpegEnum.PIXEL_FORMAT, value=pixel_format
386
+ ),
387
+ _get_ffmpeg_enum_name(kind=_FFmpegEnum.COLOR_SPACE, value=color_space),
388
+ _get_ffmpeg_enum_name(kind=_FFmpegEnum.COLOR_RANGE, value=color_range),
389
+ _get_ffmpeg_enum_name(
390
+ kind=_FFmpegEnum.COLOR_PRIMARIES, value=color_primaries
391
+ ),
392
+ _get_ffmpeg_enum_name(
393
+ kind=_FFmpegEnum.COLOR_TRANSFER_CHARACTERISTIC,
394
+ value=color_transfer_characteristic,
395
+ ),
396
+ *rest,
397
+ )
398
+ return self._metadata
399
+
400
+ @property
401
+ def pixel_format(self) -> str:
402
+ """The FFmpeg pixel-format name, e.g. ``"yuv420p"``.
403
+
404
+ On CPU this is the source's own format. On CUDA it is always one of the
405
+ NVDEC surface formats: ``"nv12"``, ``"p010le"``, ``"p012le"``,
406
+ ``"p016le"``, ``"yuv444p"`` or ``"yuv444p16le"``.
407
+ """
408
+ return self._get_metadata().pixel_format
409
+
410
+ @property
411
+ def color_space(self) -> str:
412
+ """The FFmpeg color space name, e.g. ``"bt709"``, or ``"unspecified"``.
413
+
414
+ This describes :attr:`planes`, which is not always how the source is
415
+ tagged: a CUDA decoder that falls back to the CPU converts an RGB frame
416
+ into a YUV surface format, and this reports the color space of that
417
+ conversion. Prefer it over
418
+ :attr:`VideoStreamHeaderMetadata.color_space
419
+ <torchcodec.decoders.VideoStreamMetadata.color_space>` when you convert
420
+ the samples yourself.
421
+ """
422
+ return self._get_metadata().color_space
423
+
424
+ @property
425
+ def color_range(self) -> str:
426
+ """``"tv"`` for limited range, ``"pc"`` for full range."""
427
+ return self._get_metadata().color_range
428
+
429
+ @property
430
+ def color_primaries(self) -> str:
431
+ """The FFmpeg color primaries name, e.g. ``"bt709"``, ``"bt2020"``, or
432
+ ``"unspecified"``."""
433
+
434
+ return self._get_metadata().color_primaries
435
+
436
+ @property
437
+ def color_transfer_characteristic(self) -> str:
438
+ """The FFmpeg transfer characteristic name, e.g. ``"bt709"``,
439
+ ``"smpte2084"`` (PQ), ``"arib-std-b67"`` (HLG), or ``"unspecified"``."""
440
+ return self._get_metadata().color_transfer_characteristic
441
+
442
+ @property
443
+ def bit_depth(self) -> int:
444
+ """How many bits of each :attr:`planes` sample are meaningful.
445
+
446
+ In almost every case this is just the bit depth of the source: 8 for an
447
+ 8-bit video, 10 for a 10-bit one. It is worth having because a plane's
448
+ dtype only tells you its storage width, ``uint8`` or ``uint16``, while
449
+ this tells you the range of the values held in it. So it is what you
450
+ shift or scale by to reach a range of your own -
451
+ ``y >> (frame.bit_depth - 8)`` for 8 bits, or
452
+ ``y / (2 ** frame.bit_depth - 1)`` to normalise.
453
+
454
+ Two CUDA surface formats report more than their source: a 10-bit 4:4:4
455
+ source is uploaded as ``yuv444p16le``, and a 12-bit source is tagged
456
+ ``p016le`` on FFmpeg < 6, which has no ``p012le``. Both report 16 where
457
+ CPU decoding would report 10 and 12. Their samples are msb-aligned, so
458
+ they genuinely are 16-bit values with zeroed low bits, and the
459
+ arithmetic above still holds.
460
+ """
461
+ return self._get_metadata().bit_depth
462
+
463
+ @property
464
+ def width(self) -> int:
465
+ """The width of the decoded samples, before rotation."""
466
+ return self._get_metadata().width
467
+
468
+ @property
469
+ def height(self) -> int:
470
+ """The height of the decoded samples, before rotation."""
471
+ return self._get_metadata().height
472
+
473
+ @property
474
+ def rotation(self) -> float:
475
+ """How many degrees counter-clockwise the frame has to be rotated to be
476
+ upright, or 0 if the container asks for no rotation.
477
+
478
+ This is *not* applied to :attr:`planes`. A :class:`ColorConverter`
479
+ applies it, rounded to the nearest multiple of 90, to its output.
480
+ """
481
+ return self._get_metadata().rotation
482
+
483
+ @property
484
+ def planes(self) -> tuple[torch.Tensor, ...]:
485
+ """The decoder's own samples, as 2D tensor views.
486
+
487
+ There is exactly one tensor per *component*
488
+ of :attr:`pixel_format`, in the order that format describes, of dtype
489
+ ``uint8`` or ``uint16`` depending on :attr:`bit_depth`. So ``yuv420p``
490
+ and ``nv12`` both give three (``y, u, v = planes``), ``yuva420p`` four
491
+ (``y, u, v, a = planes``) and ``gray`` one (``(y,) = planes``).
492
+
493
+ They are always on the device of the :class:`VideoPacketDecoder` that
494
+ decoded them, including when a CUDA decoder has to
495
+ fall back to decoding on the CPU: it uploads those frames before handing
496
+ them out.
497
+
498
+ Only the luma and alpha components are :attr:`height` by :attr:`width`.
499
+ The chroma ones are subsampled by whatever :attr:`pixel_format` says: half in
500
+ both directions for a 4:2:0 format, half the width for 4:2:2, full size
501
+ for 4:4:4 and for the RGB formats. Odd sizes round up, so the chroma of
502
+ a 4:2:0 frame 481 samples wide is 241 wide.
503
+
504
+ .. note::
505
+
506
+ None of these views is contiguous in general. FFmpeg pads each row
507
+ out to a line size of its own choosing, so even a luma plane is
508
+ usually strided, and the semi-planar formats (``nv12``, ``p010le``,
509
+ and the other NVDEC surface formats) store U and V interleaved in a
510
+ single allocation, which forces those two to be strided views into
511
+ it.
512
+
513
+ Raises:
514
+ RuntimeError: For the pixel formats that can't be viewed without a
515
+ copy - sub-byte-packed, palettised and float ones - and for
516
+ frames stored bottom-up. Check :attr:`pixel_format` first if you are
517
+ decoding something exotic.
518
+ """
519
+ if self._planes is None:
520
+ planes = _blocks_frame_planes(self._handle, self._device)
521
+ # The op's schema is fixed-arity, so it pads with empty tensors up
522
+ # to the 4 components of the widest format.
523
+ self._planes = tuple(p for p in planes if p.numel() > 0)
524
+ return self._planes
525
+
526
+
527
+ @dataclass
528
+ class RawAudioSamples:
529
+ """One decoded audio frame's samples, exactly as the decoder produced them.
530
+
531
+ You cannot build one yourself: an :class:`AudioPacketDecoder` creates them.
532
+ Use an :class:`AudioConverter` to turn them into normalised float32
533
+ :class:`~torchcodec.AudioSamples`, or read :attr:`data` directly::
534
+
535
+ for packet in demuxer:
536
+ for raw_samples in audio_packet_decoder.decode(packet):
537
+ print(raw_samples.data.shape) # e.g. [2, 1024]
538
+ print(raw_samples.data.dtype) # e.g. float32, for an fltp source
539
+ print(raw_samples.sample_rate) # e.g. 16000
540
+ """
541
+
542
+ data: torch.Tensor
543
+ """Always a contiguous ``[num_channels, num_samples]`` tensor, whatever the
544
+ source's sample format. Planar and packed sources alike come out with that
545
+ same shape and layout (they are copied).
546
+
547
+ The dtype is whichever one holds the source's samples exactly: ``uint8``
548
+ for ``u8``, ``int16`` for ``s16``, ``int32`` for ``s32``, ``int64`` for
549
+ ``s64``, ``float32`` for ``flt`` and ``float64`` for ``dbl``. The integer
550
+ ones are *not* normalised to ``[-1, 1]``; that is what an
551
+ :class:`AudioConverter` does."""
552
+ sample_rate: int
553
+ """The source's sample rate, in Hz."""
554
+ pts: int | None
555
+ """The :term:`pts` of the first sample, in units of the stream's time base
556
+ (:attr:`StreamMetadata.time_base`), like the :attr:`Packet.pts` it comes
557
+ from. ``None`` if it is unknown.
558
+
559
+ Unlike :attr:`pts_seconds`, it is exact: use it to match samples to the
560
+ timestamp of a packet."""
561
+ pts_seconds: float
562
+ """The :term:`pts` of the first sample, in seconds. ``NaN`` if it is
563
+ unknown."""
564
+ duration_seconds: float
565
+ """How long these samples last, in seconds."""
566
+ # See Packet._generation.
567
+ _generation: int = 0
568
+
569
+ @property
570
+ def num_channels(self) -> int:
571
+ """The number of channels, i.e. ``data.shape[0]``."""
572
+ return self.data.shape[0]
573
+
574
+ @property
575
+ def num_samples(self) -> int:
576
+ """The number of samples per channel, i.e. ``data.shape[1]``."""
577
+ return self.data.shape[1]
@@ -0,0 +1,53 @@
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
+ from __future__ import annotations
8
+
9
+ import ctypes
10
+
11
+ import torch
12
+
13
+
14
+ def _bytes_to_tensor(data: bytes | bytearray | memoryview) -> torch.Tensor:
15
+ # torch.frombuffer() rejects an empty buffer.
16
+ if not data:
17
+ return torch.empty(0, dtype=torch.uint8)
18
+ return torch.frombuffer(bytearray(data), dtype=torch.uint8)
19
+
20
+
21
+ def _tensor_to_bytes(tensor: torch.Tensor) -> bytes:
22
+ """The inverse of _bytes_to_tensor(), for a contiguous uint8 CPU tensor."""
23
+ # ctypes.string_at() avoids depending on numpy, and is much faster than
24
+ # going through tensor.tolist().
25
+ return ctypes.string_at(tensor.data_ptr(), tensor.numel())
26
+
27
+
28
+ def _process_local(hint: str):
29
+ """Class decorator refusing to pickle, copy or deepcopy the instances.
30
+
31
+ These objects carry a pointer to an FFmpeg object as their payload: the
32
+ handle tensor's *data* is the address (see ``wrap_pointer_to_tensor`` in
33
+ ``custom_ops.cpp``). Pickle would copy those 8 bytes into another process
34
+ without complaining, and nothing validates a handle before dereferencing
35
+ it, so the result would be a wild pointer rather than an error. ``copy``
36
+ and ``deepcopy`` are just as wrong: the copy holds the same address without
37
+ holding the deleter that keeps the FFmpeg object alive.
38
+
39
+ Overriding ``__reduce__`` covers all of those, and ``torch.save`` too.
40
+ """
41
+
42
+ def decorator(cls):
43
+ def __reduce__(self):
44
+ raise TypeError(
45
+ f"{type(self).__name__} cannot be pickled, copied or sent to "
46
+ f"another process: it is a handle to an FFmpeg object that "
47
+ f"only exists in this one. {hint}"
48
+ )
49
+
50
+ cls.__reduce__ = __reduce__
51
+ return cls
52
+
53
+ return decorator