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,357 @@
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 dataclasses
10
+ from fractions import Fraction
11
+ from typing import Any, Generic, TypeVar
12
+
13
+ import torch
14
+
15
+ from torchcodec._core.ops import (
16
+ _blocks_audio_packet_decoder_receive_frame,
17
+ _blocks_create_packet_decoder,
18
+ _blocks_packet_decoder_receive_frame,
19
+ _blocks_packet_decoder_reset,
20
+ _blocks_packet_decoder_send_eof,
21
+ _blocks_packet_decoder_send_packet,
22
+ )
23
+
24
+ from .._decoder_utils import convert_device_to_str
25
+ from ._codec_parameters import (
26
+ _CodecParameters,
27
+ AudioCodecParameters,
28
+ VideoCodecParameters,
29
+ )
30
+ from ._frame import Packet, RawAudioSamples, RawFrame
31
+ from ._helpers import _bytes_to_tensor, _process_local
32
+
33
+
34
+ # TODO_API_BREAKDOWN DOC P1 revisit every single comment across all low-level APIs
35
+
36
+ _Decoded = TypeVar("_Decoded", RawFrame, RawAudioSamples)
37
+
38
+
39
+ @_process_local(
40
+ "A codec context holds reference frames and entropy state that FFmpeg "
41
+ "cannot serialise. Build one in each process, from the stream's "
42
+ "codec_parameters: those can be pickled."
43
+ )
44
+ class _BasePacketDecoder(Generic[_Decoded]):
45
+ _handle: torch.Tensor
46
+ _drained: bool
47
+ _generation: int | None
48
+
49
+ def _init(
50
+ self,
51
+ codec_parameters: _CodecParameters,
52
+ *,
53
+ media_type: str,
54
+ device_str: str,
55
+ num_ffmpeg_threads: int | None = None,
56
+ ) -> None:
57
+ # The op takes the fields of the codec parameters under their own
58
+ # names, except for coded_side_data, which it takes as two lists.
59
+ kwargs: dict[str, Any] = {}
60
+ for f in dataclasses.fields(codec_parameters):
61
+ value = getattr(codec_parameters, f.name)
62
+ if not f.init or value is None:
63
+ continue
64
+ if isinstance(value, Fraction):
65
+ value = [value.numerator, value.denominator]
66
+ elif isinstance(value, bytes):
67
+ value = _bytes_to_tensor(value)
68
+ elif f.name == "coded_side_data":
69
+ kwargs["coded_side_data_names"] = list(value)
70
+ kwargs["coded_side_data_values"] = [
71
+ _bytes_to_tensor(data) for data in value.values()
72
+ ]
73
+ continue
74
+ kwargs[f.name] = value
75
+ if codec_parameters._container_format_PRIVATE_DO_NOT_USE is not None:
76
+ kwargs["container_format"] = (
77
+ codec_parameters._container_format_PRIVATE_DO_NOT_USE
78
+ )
79
+
80
+ self._handle = _blocks_create_packet_decoder(
81
+ media_type,
82
+ num_threads=num_ffmpeg_threads,
83
+ device=device_str,
84
+ **kwargs,
85
+ )
86
+ self._drained = False
87
+ # The demuxer position these packets come from. None until the first
88
+ # packet, and again after every reset(), so it is adopted rather than
89
+ # tracked: the decoder never needs a reference back to the demuxer.
90
+ self._generation = None
91
+
92
+ def _receive_ready_frames(self) -> list[_Decoded]:
93
+ raise NotImplementedError
94
+
95
+ def decode(self, packet: Packet) -> list[_Decoded]:
96
+ if self._drained:
97
+ raise RuntimeError(
98
+ "This decoder has been drained, and a codec that has been told "
99
+ "the stream ended ignores any further packet. Create a new "
100
+ "decoder to decode another stream."
101
+ )
102
+ if self._generation is None:
103
+ self._generation = packet._generation
104
+ elif self._generation != packet._generation:
105
+ raise RuntimeError(
106
+ "The demuxer seeked since this decoder was last reset(), so "
107
+ "this packet is from a position the codec knows nothing about "
108
+ "- decoding it would produce plausible-looking garbage. Call "
109
+ "reset() on every decoder fed by that demuxer after a seek."
110
+ )
111
+ status = _blocks_packet_decoder_send_packet(self._handle, packet._handle)
112
+ if status < 0:
113
+ raise RuntimeError(f"Failed to send packet to decoder (status {status})")
114
+ return self._receive_ready_frames()
115
+
116
+ def drain(self) -> list[_Decoded]:
117
+ _blocks_packet_decoder_send_eof(self._handle)
118
+ frames = self._receive_ready_frames()
119
+ self._drained = True
120
+ return frames
121
+
122
+ def reset(self) -> None:
123
+ """Drop the codec's buffered state and start over.
124
+
125
+ Needed after a :meth:`Demuxer.seek`, and after :meth:`drain`.
126
+ """
127
+ _blocks_packet_decoder_reset(self._handle)
128
+ self._drained = False
129
+ self._generation = None
130
+
131
+
132
+ class VideoPacketDecoder(_BasePacketDecoder[RawFrame]):
133
+ """Decodes the compressed :class:`Packet`\\ s of one video stream into
134
+ :class:`RawFrame`\\ s.
135
+
136
+ This is a low-level API: for straightforward decoding, use
137
+ :class:`~torchcodec.decoders.VideoDecoder` instead.
138
+
139
+ Build it from the :class:`VideoCodecParameters` of the stream to decode,
140
+ then feed it one packet at a time, and drain it at the end::
141
+
142
+ demuxer = Demuxer("video.mp4")
143
+ decoder = VideoPacketDecoder(demuxer.streams[0].codec_parameters)
144
+
145
+ for packet in demuxer:
146
+ for raw_frame in decoder.decode(packet):
147
+ ...
148
+ for raw_frame in decoder.drain():
149
+ ...
150
+
151
+ The codec parameters can also be pickled, to decode in another process
152
+ than the demuxer, or built by hand, to decode packets that don't come from
153
+ a :class:`Demuxer` (see
154
+ :ref:`sphx_glr_generated_examples_low_level_demuxer_free.py`). Frames come
155
+ out on the device the decoder was built for.
156
+
157
+ It is stateful. It holds the codec's reference-frame buffer, so it expects
158
+ the packets of its own stream, in the order the demuxer produced them.
159
+
160
+ Args:
161
+ codec_parameters (VideoCodecParameters): The parameters of the stream
162
+ to decode, e.g. :attr:`VideoStream.codec_parameters`.
163
+ device (str or torch.device, optional): The device to decode on (cpu or
164
+ CUDA). If ``None`` (default), the current default device is used
165
+ (see ``torch.set_default_device``). With codec parameters you built
166
+ yourself, CUDA needs some fields to be set: see
167
+ :class:`VideoCodecParameters`.
168
+ num_ffmpeg_threads (int, optional): The number of threads to use for
169
+ CPU decoding. This has no effect when decoding on GPU. Use 1 for
170
+ single-threaded decoding, which may be best if you are decoding
171
+ multiple streams in parallel. Use a higher number for
172
+ multi-threaded decoding, which is best for a single stream.
173
+ Passing 0 lets FFmpeg decide on the number of threads.
174
+ Default: 1.
175
+ """
176
+
177
+ def __init__(
178
+ self,
179
+ codec_parameters: VideoCodecParameters,
180
+ device: str | torch.device | None = None,
181
+ *,
182
+ num_ffmpeg_threads: int = 1,
183
+ ):
184
+ if not isinstance(codec_parameters, VideoCodecParameters):
185
+ raise TypeError(
186
+ "codec_parameters must be a VideoCodecParameters, got "
187
+ f"{type(codec_parameters).__name__}."
188
+ )
189
+ if num_ffmpeg_threads is None:
190
+ raise ValueError(f"{num_ffmpeg_threads = } should be an int.")
191
+ self._init(
192
+ codec_parameters,
193
+ media_type="video",
194
+ device_str=convert_device_to_str(device),
195
+ num_ffmpeg_threads=num_ffmpeg_threads,
196
+ )
197
+
198
+ # methods calling super() only to pin the return type down to RawFrame. The
199
+ # base class is generic over _Decoded, which isn't ideal for the rendered
200
+ # docs.
201
+ def decode(self, packet: Packet) -> list[RawFrame]:
202
+ """Send one :class:`Packet` to the codec and return the
203
+ :class:`RawFrame`\\ s that are ready.
204
+
205
+ **This can return zero, one, or more than one** :class:`RawFrame`. What
206
+ comes back is not the decoding of the packet you just passed: a codec
207
+ that is buffering B-frames, or still priming itself, will emit what it owes
208
+ you on a later call.
209
+
210
+ Args:
211
+ packet (Packet): A packet of this decoder's own stream.
212
+
213
+ Returns:
214
+ The possibly empty list of :class:`RawFrame`\\ s that the codec has
215
+ ready, in presentation order.
216
+
217
+ Raises:
218
+ RuntimeError: If this decoder has been drained, or if the demuxer
219
+ seeked without it being :meth:`reset` afterwards.
220
+ """
221
+ return super().decode(packet)
222
+
223
+ def drain(self) -> list[RawFrame]:
224
+ """Tell the codec the stream has ended, and return the
225
+ :class:`RawFrame`\\ s it was still holding.
226
+
227
+ Skipping this loses the tail of the stream. A drained decoder refuses
228
+ any further packet; :meth:`reset` makes it usable again.
229
+
230
+ Returns:
231
+ The possibly empty list of :class:`RawFrame`\\ s that the codec was
232
+ still holding, in presentation order.
233
+ """
234
+ return super().drain()
235
+
236
+ def _receive_ready_frames(self) -> list[RawFrame]:
237
+ frames = []
238
+ while True:
239
+ handle, status, pts, pts_seconds, duration_seconds, storage = (
240
+ _blocks_packet_decoder_receive_frame(self._handle)
241
+ )
242
+ if status != 0: # EAGAIN (need more packets) or EOF: nothing ready
243
+ break
244
+ frames.append(
245
+ RawFrame(
246
+ handle,
247
+ pts,
248
+ pts_seconds,
249
+ duration_seconds,
250
+ storage=storage if storage.numel() > 0 else None,
251
+ )
252
+ )
253
+ return frames
254
+
255
+
256
+ class AudioPacketDecoder(_BasePacketDecoder[RawAudioSamples]):
257
+ """Decodes the compressed :class:`Packet`\\ s of one audio stream into
258
+ :class:`RawAudioSamples`.
259
+
260
+ This is a low-level API: for straightforward decoding, use
261
+ :class:`~torchcodec.decoders.AudioDecoder` instead.
262
+
263
+ Build it from the :class:`AudioCodecParameters` of the stream to decode,
264
+ then feed it one packet at a time, and drain it at the end::
265
+
266
+ demuxer = Demuxer("audio.mp3", streams="audio")
267
+ decoder = AudioPacketDecoder(demuxer.streams[0].codec_parameters)
268
+
269
+ for packet in demuxer:
270
+ for raw_samples in decoder.decode(packet):
271
+ ...
272
+ for raw_samples in decoder.drain():
273
+ ...
274
+
275
+ The codec parameters can also be pickled, to decode in another process
276
+ than the demuxer, or built by hand, to decode packets that don't come from
277
+ a :class:`Demuxer` (see
278
+ :ref:`sphx_glr_generated_examples_low_level_demuxer_free.py`). Audio is
279
+ always decoded on the CPU.
280
+
281
+ It is stateful. A lossy codec carries state from one frame to the next, so
282
+ it expects the packets of its own stream, in the order the demuxer produced
283
+ them. After a :meth:`Demuxer.seek`, :meth:`reset` is necessary but not
284
+ sufficient: the first samples that come out are subtly wrong until the codec
285
+ re-primes, so decode a margin before your target and throw it away.
286
+
287
+ Args:
288
+ codec_parameters (AudioCodecParameters): The parameters of the stream
289
+ to decode, e.g. :attr:`AudioStream.codec_parameters`.
290
+ """
291
+
292
+ def __init__(self, codec_parameters: AudioCodecParameters):
293
+ if not isinstance(codec_parameters, AudioCodecParameters):
294
+ raise TypeError(
295
+ "codec_parameters must be an AudioCodecParameters, got "
296
+ f"{type(codec_parameters).__name__}."
297
+ )
298
+ # No num_ffmpeg_threads: audio is always decoded on a single thread.
299
+ self._init(codec_parameters, media_type="audio", device_str="cpu")
300
+
301
+ # See VideoPacketDecoder: pinning the return type down to RawAudioSamples.
302
+ def decode(self, packet: Packet) -> list[RawAudioSamples]:
303
+ """Send one :class:`Packet` to the codec and return the
304
+ :class:`RawAudioSamples` that are ready.
305
+
306
+ **This can return zero, one, or more than one**
307
+ :class:`RawAudioSamples`. What comes back is not the decoding of the
308
+ packet you just passed: a codec that is still priming itself will emit
309
+ what it owes you on a later call.
310
+
311
+ Args:
312
+ packet (Packet): A packet of this decoder's own stream.
313
+
314
+ Returns:
315
+ The possibly empty list of :class:`RawAudioSamples` that the codec
316
+ has ready, in presentation order.
317
+
318
+ Raises:
319
+ RuntimeError: If this decoder has been drained, or if the demuxer
320
+ seeked without it being :meth:`reset` afterwards.
321
+ """
322
+ return super().decode(packet)
323
+
324
+ def drain(self) -> list[RawAudioSamples]:
325
+ """Tell the codec the stream has ended, and return the
326
+ :class:`RawAudioSamples` it was still holding.
327
+
328
+ Skipping this loses the tail of the stream. A drained decoder refuses
329
+ any further packet; :meth:`reset` makes it usable again.
330
+
331
+ Returns:
332
+ The possibly empty list of :class:`RawAudioSamples` that the codec
333
+ was still holding, in presentation order.
334
+ """
335
+ return super().drain()
336
+
337
+ def _receive_ready_frames(self) -> list[RawAudioSamples]:
338
+ samples = []
339
+ while True:
340
+ data, status, pts, pts_seconds, duration_seconds, sample_rate = (
341
+ _blocks_audio_packet_decoder_receive_frame(self._handle)
342
+ )
343
+ if status != 0: # EAGAIN (need more packets) or EOF: nothing ready
344
+ break
345
+ samples.append(
346
+ RawAudioSamples(
347
+ data=data,
348
+ sample_rate=sample_rate,
349
+ pts=pts,
350
+ pts_seconds=pts_seconds,
351
+ duration_seconds=duration_seconds,
352
+ # Carried onward so AudioConverter can make the same check:
353
+ # a seek invalidates the resampler's state too.
354
+ _generation=self._generation or 0,
355
+ )
356
+ )
357
+ return samples
@@ -0,0 +1,128 @@
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
+
8
+ import contextvars
9
+ from collections.abc import Generator
10
+ from contextlib import contextmanager
11
+
12
+ import torch
13
+
14
+ from torchcodec import _core
15
+
16
+
17
+ # Thread-local and async-safe storage for the current CUDA backend
18
+ _CUDA_BACKEND: contextvars.ContextVar[str] = contextvars.ContextVar(
19
+ "_CUDA_BACKEND", default="default"
20
+ )
21
+
22
+
23
+ @contextmanager
24
+ def set_cuda_backend(backend: str) -> Generator[None, None, None]:
25
+ """Context Manager to set the CUDA backend for :class:`~torchcodec.decoders.VideoDecoder`.
26
+
27
+ This context manager allows you to specify which CUDA backend implementation
28
+ to use when creating :class:`~torchcodec.decoders.VideoDecoder` instances
29
+ with CUDA devices.
30
+
31
+ The default is ``"nvdec"``. An ``"ffmpeg"`` backend is also available.
32
+
33
+ Only the creation of the decoder needs to be inside the context manager, the
34
+ decoding methods can be called outside of it. You still need to pass
35
+ ``device="cuda"`` when creating the
36
+ :class:`~torchcodec.decoders.VideoDecoder` instance. If a CUDA device isn't
37
+ specified, this context manager will have no effect. See example below.
38
+
39
+ This is thread-safe and async-safe.
40
+
41
+ Args:
42
+ backend (str): The CUDA backend to use. Can be ``"nvdec"`` (default) or
43
+ ``"ffmpeg"``.
44
+
45
+ Example:
46
+ >>> with set_cuda_backend("ffmpeg"):
47
+ ... decoder = VideoDecoder("video.mp4", device="cuda")
48
+ ...
49
+ ... # Only the decoder creation needs to be part of the context manager.
50
+ ... # Decoder will use the FFmpeg CUDA implementation:
51
+ ... decoder.get_frame_at(0)
52
+ """
53
+ backend = backend.lower()
54
+ if backend == "beta": # For BC
55
+ backend = "nvdec"
56
+ if backend not in ("nvdec", "ffmpeg"):
57
+ raise ValueError(
58
+ f"Invalid CUDA backend ({backend}). Supported values are 'nvdec' and 'ffmpeg'."
59
+ )
60
+ # "nvdec" is the public-facing name; internally the variant value is
61
+ # "default" (meaning "the default CUDA backend").
62
+ if backend == "nvdec":
63
+ backend = "default"
64
+
65
+ previous_state = _CUDA_BACKEND.set(backend)
66
+ try:
67
+ yield
68
+ finally:
69
+ _CUDA_BACKEND.reset(previous_state)
70
+
71
+
72
+ def _get_cuda_backend() -> str:
73
+ return _CUDA_BACKEND.get()
74
+
75
+
76
+ def set_nvdec_cache_capacity(capacity: int) -> None:
77
+ """Set the maximum number of NVDEC decoders that can be cached (per GPU).
78
+
79
+ The NVDEC decoder cache stores hardware decoders for reuse, avoiding the
80
+ overhead of creating and destructing new decoders for subsequent video
81
+ decoding operations on the same GPU. This function sets the capacity of the
82
+ cache, i.e. the maximum number of decoders that can be cached per device.
83
+ The default capacity is 20 decoders per device. If the cache contains more
84
+ decoders than the target ``capacity``, excess decoders will be evicted
85
+ using a least-recently-used policy.
86
+
87
+ Generally, a decoder can be re-used from the cache if it matches the same
88
+ codec and frame dimensions.
89
+
90
+ See also :func:`~torchcodec.decoders.get_nvdec_cache_capacity`.
91
+
92
+ Args:
93
+ capacity (int): The maximum number of NVDEC decoders that can be cached
94
+ per GPU device. Must be non-negative. Setting to 0 disables caching.
95
+ """
96
+ _core.set_nvdec_cache_capacity(capacity)
97
+
98
+
99
+ def get_nvdec_cache_capacity() -> int:
100
+ """Get the capacity of the per-device NVDEC decoder cache.
101
+
102
+ See also :func:`~torchcodec.decoders.set_nvdec_cache_capacity`.
103
+
104
+ Returns:
105
+ int: The maximum number of NVDEC decoders that can be cached per GPU device.
106
+ """
107
+ return _core.get_nvdec_cache_capacity()
108
+
109
+
110
+ def convert_device_to_str(device: str | torch.device | None) -> str:
111
+ # The core ops take the device as a string. None means "the current default
112
+ # device".
113
+ if device is None:
114
+ device = torch.get_default_device()
115
+ return str(device)
116
+
117
+
118
+ def convert_output_dtype_to_str(output_dtype: torch.dtype | str) -> str:
119
+ # The core ops take the dtype as a string.
120
+ dtype_to_str = {torch.uint8: "uint8", torch.float32: "float32"}
121
+ if output_dtype == "auto":
122
+ return "auto"
123
+ if output_dtype not in dtype_to_str:
124
+ raise ValueError(
125
+ f"Invalid output_dtype ({output_dtype}). "
126
+ f"Supported values are torch.uint8, torch.float32, and 'auto'."
127
+ )
128
+ return dtype_to_str[output_dtype]