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,678 @@
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 io
10
+ import json
11
+ from collections.abc import Iterable
12
+ from dataclasses import dataclass
13
+ from fractions import Fraction
14
+ from functools import cached_property
15
+ from pathlib import Path
16
+ from typing import Any, cast
17
+
18
+ import torch
19
+ from torch import Tensor
20
+
21
+ from torchcodec._core._decoder_utils import create_demuxer
22
+ from torchcodec._core._metadata import (
23
+ _stream_metadata_from_dict,
24
+ AudioStreamHeaderMetadata,
25
+ ContainerMetadata,
26
+ DemuxerMetadata,
27
+ StreamMetadata,
28
+ VideoStreamHeaderMetadata,
29
+ )
30
+ from torchcodec._core.ops import (
31
+ _blocks_demuxer_add_stream,
32
+ _blocks_demuxer_container_json_metadata,
33
+ _blocks_demuxer_get_audio_video_stream_indices,
34
+ _blocks_demuxer_get_codec_parameters,
35
+ _blocks_demuxer_next_packet,
36
+ _blocks_demuxer_scan,
37
+ _blocks_demuxer_seek,
38
+ _blocks_demuxer_stream_json_metadata,
39
+ )
40
+
41
+ from ._codec_parameters import AudioCodecParameters, VideoCodecParameters
42
+ from ._frame import Packet
43
+ from ._helpers import _process_local, _tensor_to_bytes
44
+ from ._packet_decoder import AudioPacketDecoder, VideoPacketDecoder
45
+
46
+ # TODO_API_BREAKDOWN FEAT PERF Do we want / need to support 'batch-like' APIs
47
+ # were containers are pre-allocated for perf? Like if a user wants to decode
48
+ # specific timestamps for sampling?
49
+
50
+
51
+ # FFmpeg's AV_NOPTS_VALUE.
52
+ _NO_PTS = -(2**63)
53
+
54
+
55
+ @dataclass
56
+ class FrameIndex:
57
+ """What the packets of a video stream say about its frames, as returned by
58
+ a :term:`scan` (:meth:`VideoStream.scan`).
59
+
60
+ Its members come in three shapes:
61
+
62
+ - **Per-frame tensors**, of shape ``[N]`` where ``N`` is the number of
63
+ frames: one entry per frame, in presentation order. These are
64
+ :attr:`is_key_frame`, :attr:`pts_seconds` and :attr:`duration_seconds`.
65
+ - **Keyframe positions**, :attr:`key_frame_indices`, of shape ``[K]`` where
66
+ ``K`` is the number of keyframes. These are indices into the per-frame
67
+ tensors, not frames themselves.
68
+ - **Stream-level metadata scalars**, one value for the whole stream:
69
+ :attr:`num_frames_from_content`,
70
+ :attr:`begin_stream_seconds_from_content`,
71
+ :attr:`end_stream_seconds_from_content` and
72
+ :attr:`average_fps_from_content`.
73
+
74
+ :meth:`index_at` and :meth:`key_frame_seconds_for` are convenience methods
75
+ that search those tensors so that you don't have to. Together with
76
+ :meth:`Demuxer.seek`, they are what an exact seek is built from::
77
+
78
+ frame_index = video_stream.scan()
79
+
80
+ # Reach the frame displayed at 12.5 seconds
81
+ target = frame_index.pts_seconds[frame_index.index_at(12.5)]
82
+ demuxer.seek(frame_index.key_frame_seconds_for(target))
83
+ packet_decoder.reset()
84
+ # ... then decode forward, dropping the frames before `target`
85
+
86
+ Everything here is derived from the stream's packets rather than from the
87
+ container header, so it is exact where the header is only a claim. That is
88
+ what the ``_from_content`` suffixes mark, against the ``_from_header`` ones
89
+ on :attr:`VideoStream.metadata`.
90
+ """
91
+
92
+ _is_key_frame: Tensor
93
+ _pts: Tensor
94
+ _duration: Tensor
95
+ _time_base_num: int
96
+ _time_base_den: int
97
+
98
+ def __len__(self) -> int:
99
+ """The number of frames in the stream."""
100
+ return self._is_key_frame.shape[0]
101
+
102
+ @property
103
+ def is_key_frame(self) -> Tensor:
104
+ """Bool tensor of shape ``[N]``, whether each frame is a keyframe."""
105
+ self._check_has_timestamps()
106
+ return self._is_key_frame
107
+
108
+ @property
109
+ def num_frames_from_content(self) -> int:
110
+ """The number of frames in the stream."""
111
+ return len(self)
112
+
113
+ @cached_property
114
+ def pts_seconds(self) -> Tensor:
115
+ """Float64 tensor of shape ``[N]``, the :term:`pts` of each frame.
116
+
117
+ ``NaN`` for the frames whose packet has no pts. Streams like raw H.264
118
+ or HEVC streams have none at all, so their frames can't be put in
119
+ presentation order: :attr:`is_key_frame`, :attr:`key_frame_indices`,
120
+ :meth:`index_at` and :meth:`key_frame_seconds_for` raise on them.
121
+ """
122
+ return self._to_seconds(self._pts).masked_fill(
123
+ self._pts == _NO_PTS, float("nan")
124
+ )
125
+
126
+ @cached_property
127
+ def duration_seconds(self) -> Tensor:
128
+ """Float64 tensor of shape ``[N]``, how long each frame is displayed
129
+ for."""
130
+ return self._to_seconds(self._duration)
131
+
132
+ @cached_property
133
+ def key_frame_indices(self) -> Tensor:
134
+ """Int64 tensor of shape ``[K]``, the indices of the keyframes."""
135
+ return self.is_key_frame.nonzero().squeeze(1)
136
+
137
+ @cached_property
138
+ def begin_stream_seconds_from_content(self) -> float:
139
+ """The :term:`pts` of the first frame."""
140
+ return float(self.pts_seconds[0])
141
+
142
+ @cached_property
143
+ def end_stream_seconds_from_content(self) -> float:
144
+ """The time at which the last frame stops being displayed.
145
+
146
+ This is the largest ``pts + duration`` across the stream, not the last
147
+ frame's own end time. Durations vary, so the frame that finishes last
148
+ isn't necessarily the one that starts last.
149
+ """
150
+ return float(self._end_seconds_so_far[-1])
151
+
152
+ @property
153
+ def average_fps_from_content(self) -> float:
154
+ """The average number of frames per second over the stream."""
155
+ return len(self) / (
156
+ self.end_stream_seconds_from_content
157
+ - self.begin_stream_seconds_from_content
158
+ )
159
+
160
+ def index_at(self, seconds: float | Tensor) -> int | Tensor:
161
+ """The index of the frame being displayed at ``seconds``.
162
+
163
+ A frame is displayed from its own :term:`pts` until that plus its
164
+ duration, so this is the frame whose interval contains ``seconds``.
165
+
166
+ Args:
167
+ seconds (float or Tensor): The timestamp(s) to look up. A value
168
+ outside the stream gives the closest frame, i.e. the first or
169
+ the last one.
170
+
171
+ Returns:
172
+ int or Tensor: The index of that frame. A tensor of timestamps
173
+ gives an int64 tensor of indices of the same shape.
174
+ """
175
+ self._check_has_timestamps()
176
+ # First frame that hasn't finished playing by `seconds`, which is
177
+ # get_frame_played_at()'s criterion (frame_start <= t < frame_end,
178
+ # SingleStreamDecoder.cpp) expressed as a search rather than a scan of
179
+ # decoded frames. Note it is *not* seconds_to_index_lower_bound(), which
180
+ # compares against next_pts and so answers differently for a timestamp
181
+ # falling in a gap between two frames.
182
+ indices = torch.searchsorted(
183
+ self._end_seconds_so_far,
184
+ torch.as_tensor(seconds, dtype=torch.float64),
185
+ right=True,
186
+ ).clamp(max=len(self) - 1)
187
+ return indices if isinstance(seconds, Tensor) else int(indices)
188
+
189
+ # TODO_API_BREAKDOWN DESIGN P1: Still kinda hate this name
190
+ def key_frame_seconds_for(self, seconds: float) -> float:
191
+ """The timestamp of the last keyframe at or before ``seconds``.
192
+
193
+ Args:
194
+ seconds (float): The timestamp you want to reach.
195
+
196
+ Returns:
197
+ float: The timestamp to seek to.
198
+ """
199
+ self._check_has_timestamps()
200
+ # Same search as get_key_frame_index_for_pts_using_scanned_index()
201
+ # (SingleStreamDecoder.cpp): upper_bound minus one, i.e. the last
202
+ # keyframe at or before the target, and -1 when there is none.
203
+ position = (
204
+ int(torch.searchsorted(self._key_frame_seconds, seconds, right=True)) - 1
205
+ )
206
+ if position < 0:
207
+ # No keyframe at or before the target: the one it decodes from was
208
+ # trimmed away by an edit list, so it isn't in this index. Aim at
209
+ # the start of the stream and let FFmpeg find it, which is what
210
+ # exact mode does when that search returns -1.
211
+ return float(self.pts_seconds[0])
212
+ return float(self._key_frame_seconds[position])
213
+
214
+ @cached_property
215
+ def _has_timestamps(self) -> bool:
216
+ return not bool((self._pts == _NO_PTS).all())
217
+
218
+ def _check_has_timestamps(self) -> None:
219
+ if not self._has_timestamps:
220
+ raise ValueError(
221
+ "This stream has no timestamps (e.g. it is a raw H.264 or HEVC "
222
+ "stream), so its frames can't be put in presentation order, nor "
223
+ "looked up by time."
224
+ )
225
+
226
+ def _to_seconds(self, value: Tensor) -> Tensor:
227
+ # pts_to_seconds() (FFMPEGCommon.cpp), and it has to stay bit-for-bit
228
+ # identical to it: float64 is C++ `double`, and the multiplication comes
229
+ # before the division on both sides. Timestamps from a FrameIndex are
230
+ # compared against, and fed back into, values the C++ produced.
231
+ return value.to(torch.float64) * self._time_base_num / self._time_base_den
232
+
233
+ @cached_property
234
+ def _end_seconds_so_far(self) -> Tensor:
235
+ # A running max, because the raw end times aren't necessarily sorted: a
236
+ # frame whose duration overruns the start of the next one finishes after
237
+ # it. We need this to be sorted for the binary search in index_at() to
238
+ # work.
239
+ return self._to_seconds(self._pts + self._duration).cummax(dim=0).values
240
+
241
+ @cached_property
242
+ def _key_frame_seconds(self) -> Tensor:
243
+ return self.pts_seconds[self.key_frame_indices]
244
+
245
+
246
+ _CODEC_PARAMETERS_TEXT_FIELDS = (
247
+ "codec",
248
+ "pixel_format",
249
+ "field_order",
250
+ "color_range",
251
+ "color_primaries",
252
+ "color_transfer_characteristic",
253
+ "color_space",
254
+ "chroma_location",
255
+ "sample_format",
256
+ "channel_layout",
257
+ "container_format",
258
+ )
259
+
260
+
261
+ @_process_local("Reach it through a Demuxer built in that process.")
262
+ class _Stream:
263
+ _media_type: str
264
+
265
+ def __init__(self, demuxer: Demuxer, index: int):
266
+ self._demuxer = demuxer
267
+ self.index = index
268
+
269
+ def _read_metadata(self) -> StreamMetadata:
270
+ return _stream_metadata_from_dict(
271
+ json.loads(
272
+ _blocks_demuxer_stream_json_metadata(self._demuxer._handle, self.index)
273
+ ),
274
+ self.index,
275
+ )
276
+
277
+ def _get_codec_parameters(
278
+ self, cls: type[VideoCodecParameters] | type[AudioCodecParameters]
279
+ ):
280
+ """Get the raw values from the C++ side, then massage them into the right
281
+ types for the dataclass constructor."""
282
+ outputs = _blocks_demuxer_get_codec_parameters(
283
+ self._demuxer._handle, self.index
284
+ )
285
+ names = [r.name for r in _blocks_demuxer_get_codec_parameters._schema.returns]
286
+ fields: dict[str, Any] = dict(zip(names, outputs))
287
+ # The text fields come as UTF-8 bytes in uint8 CPU tensors, see
288
+ # Note [Returning text from ops] in custom_ops.cpp.
289
+ for name in _CODEC_PARAMETERS_TEXT_FIELDS:
290
+ if fields[name] is not None:
291
+ fields[name] = _tensor_to_bytes(fields[name]).decode()
292
+ container_format = fields.pop("container_format")
293
+
294
+ # The binary fields come as contiguous uint8 CPU tensors, we want them
295
+ # to be bytes (the Python type).
296
+ side_data_names = fields.pop("coded_side_data_names")
297
+ side_data_values = fields.pop("coded_side_data_values")
298
+ if side_data_names:
299
+ fields["coded_side_data"] = {
300
+ _tensor_to_bytes(name).decode(): _tensor_to_bytes(value)
301
+ for name, value in zip(side_data_names, side_data_values)
302
+ }
303
+ extradata = fields["extradata"]
304
+ if extradata is not None:
305
+ fields["extradata"] = _tensor_to_bytes(extradata)
306
+ # The rationals come as [num, den] lists.
307
+ kwargs: dict[str, Any] = {
308
+ name: Fraction(*value) if isinstance(value, list) else value
309
+ for name, value in fields.items()
310
+ if value is not None
311
+ }
312
+ params = cls(**kwargs)
313
+ object.__setattr__(
314
+ params, "_container_format_PRIVATE_DO_NOT_USE", container_format
315
+ )
316
+ return params
317
+
318
+ def __repr__(self) -> str:
319
+ return f"{type(self).__name__}(index={self.index})"
320
+
321
+
322
+ class VideoStream(_Stream):
323
+ """A video stream followed by a :class:`Demuxer`.
324
+
325
+ You should not build one yourself: a ``Demuxer`` creates one for you.
326
+
327
+ Attributes:
328
+ index (int): The stream's index within the container, absolute across
329
+ all media types. This is what a :class:`Packet`'s ``stream_index``
330
+ can be compared against.
331
+ """
332
+
333
+ _media_type = "video"
334
+
335
+ def __init__(self, demuxer: Demuxer, index: int):
336
+ super().__init__(demuxer, index)
337
+ self._frame_index: FrameIndex | None = None
338
+
339
+ @cached_property
340
+ def metadata(self) -> VideoStreamHeaderMetadata:
341
+ """What the container header says about this video stream.
342
+
343
+ From the header only. This stream's exact frame count, timestamps and
344
+ keyframe positions aren't in there - those come from :meth:`scan`, and
345
+ that is the distinction the ``_from_header`` and ``_from_content``
346
+ suffixes mark.
347
+ """
348
+ return cast(VideoStreamHeaderMetadata, self._read_metadata())
349
+
350
+ @cached_property
351
+ def codec_parameters(self) -> VideoCodecParameters:
352
+ """What a decoder needs to know to decode this stream's packets.
353
+
354
+ Pass them to a :class:`VideoPacketDecoder`, or pickle them to build the decoder in
355
+ another process. To read the stream's properties, use :attr:`metadata`
356
+ instead. See :class:`VideoCodecParameters`.
357
+ """
358
+ return self._get_codec_parameters(VideoCodecParameters)
359
+
360
+ def scan(self) -> FrameIndex:
361
+ """Demux this stream from end to end, without decoding it (a
362
+ :term:`scan`), and return its :class:`FrameIndex`.
363
+
364
+ This is the only way to know a stream's exact frame count, timestamps
365
+ and keyframe positions: the container header can be wrong about all
366
+ three.
367
+
368
+ You can call this on multiple video streams from the same demuxer. The
369
+ first call scans the entire video once, and subsequent calls on other
370
+ streams are free.
371
+
372
+ .. important::
373
+
374
+ If called, then this must be called before any packets are read from
375
+ the demuxer.
376
+
377
+ Returns:
378
+ FrameIndex: the frame index for this stream, describing its keyframes and frame positions.
379
+ """
380
+ if self._frame_index is None:
381
+ pts, duration, is_key_frame, time_base_num, time_base_den = (
382
+ _blocks_demuxer_scan(self._demuxer._handle, self.index)
383
+ )
384
+ self._frame_index = FrameIndex(
385
+ _is_key_frame=is_key_frame,
386
+ _pts=pts,
387
+ _duration=duration,
388
+ _time_base_num=time_base_num,
389
+ _time_base_den=time_base_den,
390
+ )
391
+ return self._frame_index
392
+
393
+ def make_decoder(
394
+ self,
395
+ device: str | torch.device | None = None,
396
+ *,
397
+ num_ffmpeg_threads: int = 1,
398
+ ) -> VideoPacketDecoder:
399
+ """[DISCOURAGED]
400
+
401
+ Still available so that existing code keeps working. The recommended
402
+ way to build a :class:`VideoPacketDecoder` is to instantiate it
403
+ directly, from the stream's codec parameters:
404
+ ``VideoPacketDecoder(stream.codec_parameters, ...)``.
405
+ """
406
+ return VideoPacketDecoder(
407
+ self.codec_parameters, device, num_ffmpeg_threads=num_ffmpeg_threads
408
+ )
409
+
410
+
411
+ class AudioStream(_Stream):
412
+ """An audio stream followed by a :class:`Demuxer`.
413
+
414
+ You should not build one yourself: a ``Demuxer`` creates one for you.
415
+
416
+ Attributes:
417
+ index (int): The stream's index within the container, absolute across
418
+ all media types. This is what a :class:`Packet`'s ``stream_index``
419
+ can be compared against.
420
+ """
421
+
422
+ _media_type = "audio"
423
+
424
+ @cached_property
425
+ def metadata(self) -> AudioStreamHeaderMetadata:
426
+ """What the container header says about this audio stream.
427
+
428
+ From the header only.
429
+ """
430
+ return cast(AudioStreamHeaderMetadata, self._read_metadata())
431
+
432
+ @cached_property
433
+ def codec_parameters(self) -> AudioCodecParameters:
434
+ """What a decoder needs to know to decode this stream's packets.
435
+
436
+ Pass them to a :class:`AudioPacketDecoder`, or pickle them to build the decoder in
437
+ another process. To read the stream's properties, use :attr:`metadata`
438
+ instead. See :class:`AudioCodecParameters`.
439
+ """
440
+ return self._get_codec_parameters(AudioCodecParameters)
441
+
442
+ def make_decoder(self) -> AudioPacketDecoder:
443
+ """[DISCOURAGED]
444
+
445
+ Still available so that existing code keeps working. The recommended
446
+ way to build an :class:`AudioPacketDecoder` is to instantiate it
447
+ directly, from the stream's codec parameters:
448
+ ``AudioPacketDecoder(stream.codec_parameters)``.
449
+ """
450
+ return AudioPacketDecoder(self.codec_parameters)
451
+
452
+
453
+ @_process_local(
454
+ "It owns an open container and the file descriptor behind it. Construct "
455
+ "one in each process, from the same source."
456
+ )
457
+ class Demuxer:
458
+ """Reads one or more video and audio streams from a container, and produces their compressed :class:`Packet`\\ s.
459
+
460
+ This is a low-level API: for straightforward decoding, use
461
+ :class:`~torchcodec.decoders.VideoDecoder` or
462
+ :class:`~torchcodec.decoders.AudioDecoder` instead.
463
+
464
+ Packets come out interleaved, and :attr:`Packet.stream_index` says which
465
+ stream each one belongs to::
466
+
467
+ demuxer = Demuxer("video.mp4", streams=("video", "audio"))
468
+ video, audio = demuxer.streams
469
+ decoders = {
470
+ video.index: VideoPacketDecoder(video.codec_parameters, device="cuda"),
471
+ audio.index: AudioPacketDecoder(audio.codec_parameters),
472
+ }
473
+
474
+ for packet in demuxer:
475
+ for output in decoders[packet.stream_index].decode(packet):
476
+ ...
477
+
478
+ Args:
479
+ source (str, ``Pathlib.path``, bytes, ``torch.Tensor`` or file-like object): The source of the media:
480
+
481
+ - If ``str``: a local path or a URL to a media file.
482
+ - If ``Pathlib.path``: a path to a local media file.
483
+ - If ``bytes`` object or ``torch.Tensor``: the raw encoded data.
484
+ - If file-like object: we read data from the object on demand. The
485
+ object must expose the methods `read(self, size: int) -> bytes`
486
+ and `seek(self, offset: int, whence: int) -> int`.
487
+ streams (str, int or tuple, optional): Which streams to follow, as a
488
+ single selector or a tuple of them. A selector is either
489
+ ``"video"`` or ``"audio"`` for the :term:`best stream` of that
490
+ type, or an ``int`` for a stream index, absolute across all media
491
+ types. ``"all"`` follows every audio and video stream in container
492
+ order, skipping the rest, and can only be used on its own. Default:
493
+ ``"video"``.
494
+
495
+ Attributes:
496
+ streams (tuple): The :class:`VideoStream` and :class:`AudioStream`
497
+ objects being followed, in the order the ``streams`` parameter
498
+ named them. Packet decoders are built from these.
499
+ metadata (DemuxerMetadata): What the container header says about the
500
+ container itself. What it says about a given stream is on
501
+ ``demuxer.streams[i].metadata``.
502
+ """
503
+
504
+ def __init__(
505
+ self,
506
+ source: str | Path | bytes | Tensor | io.RawIOBase | io.BufferedReader,
507
+ *,
508
+ streams: str | int | tuple[str | int, ...] = "video",
509
+ ):
510
+ self._handle = create_demuxer(source=source)
511
+ # _generation is bumped on every seek and stamped on every packet, so
512
+ # that a decoder can tell if the user forgot to `reset()` it.
513
+ self._generation = 0
514
+ try:
515
+ self.streams = tuple(
516
+ self._add_stream(selector) for selector in self._parse_streams(streams)
517
+ )
518
+ except RuntimeError as e:
519
+ # Just to be nice, we convert the C++ RuntimeErrors into ValueError
520
+ # so all stream validation errors are consistently ValueError.
521
+ raise ValueError(str(e)) from None
522
+
523
+ @cached_property
524
+ def metadata(self) -> DemuxerMetadata:
525
+ return DemuxerMetadata(**_container_fields(self._handle))
526
+
527
+ def _parse_streams(self, streams) -> list[int | str]:
528
+ if streams == "all":
529
+ return [
530
+ int(index)
531
+ for index in _blocks_demuxer_get_audio_video_stream_indices(
532
+ self._handle
533
+ )
534
+ ]
535
+
536
+ if isinstance(streams, (str, int)) or not isinstance(streams, Iterable):
537
+ streams = (streams,)
538
+ streams = tuple(streams)
539
+ if not streams:
540
+ raise ValueError(
541
+ "streams is empty, so this demuxer would have nothing to demux."
542
+ )
543
+
544
+ for selector in streams:
545
+ if selector in ("video", "audio"):
546
+ continue
547
+ if selector == "all":
548
+ raise ValueError(
549
+ "streams='all' can only be used on its own, not alongside "
550
+ f"other selectors: got {streams!r}."
551
+ )
552
+ if not isinstance(selector, int) or isinstance(selector, bool):
553
+ raise ValueError(
554
+ f"Invalid stream selector {selector!r}. Expected 'video', "
555
+ "'audio', or an int stream index."
556
+ )
557
+ return list(streams)
558
+
559
+ def _add_stream(self, selector: int | str) -> _Stream:
560
+ index, is_video = _blocks_demuxer_add_stream(
561
+ self._handle,
562
+ selector if isinstance(selector, int) else None,
563
+ selector if isinstance(selector, str) else None,
564
+ )
565
+ stream_class = VideoStream if is_video else AudioStream
566
+ return stream_class(self, index)
567
+
568
+ def __iter__(self) -> Demuxer:
569
+ return self
570
+
571
+ def __next__(self) -> Packet:
572
+ """Read and return the next :class:`Packet`.
573
+
574
+ Packets come out interleaved across the streams being followed, in the
575
+ order the container stores them, so this is where
576
+ :attr:`Packet.stream_index` matters: it is what routes each packet to
577
+ the decoder of its own stream.
578
+
579
+ Returns:
580
+ Packet: The next packet.
581
+ """
582
+ handle, is_eof, stream_index = _blocks_demuxer_next_packet(self._handle)
583
+ if is_eof:
584
+ raise StopIteration
585
+ return Packet(handle, stream_index, generation=self._generation)
586
+
587
+ # Note: could consider adding int-based APIs? Not sure if needed for seek
588
+ # but we could at least expose the int-based pts values along with the time
589
+ # base, etc.
590
+ def seek(
591
+ self, seconds: float, *, stream: VideoStream | AudioStream | None = None
592
+ ) -> None:
593
+ """Move the demuxer to ``seconds``.
594
+
595
+ This moves *every* stream being followed. For videos, this lands on the
596
+ keyframe at or before ``seconds``. For audio, a lossy codec's first
597
+ frames after a seek are typically slightly wrong until the codec
598
+ re-primes. This is especially true when resampling is involved (via an
599
+ :class:`AudioConverter`). Pre-rolling a margin of audio before the
600
+ target is up to you.
601
+
602
+ A stream without timestamps, like a raw H.264 or HEVC stream, can only
603
+ be rewound to its start, with ``seek(0)``.
604
+
605
+ There is no ``seek_mode`` to choose from: seeking straight to
606
+ ``seconds`` is what :class:`~torchcodec.decoders.VideoDecoder` calls
607
+ ``seek_mode="approximate"``. To get the ``seek_mode="exact"`` behavior,
608
+ :term:`scan` the stream and seek to
609
+ :meth:`FrameIndex.key_frame_seconds_for` of your target instead.
610
+
611
+ .. important::
612
+
613
+ You must call :meth:`VideoPacketDecoder.reset` or
614
+ :meth:`AudioPacketDecoder.reset` on every decoder fed by this
615
+ demuxer afterwards, and :meth:`AudioConverter.reset` on every
616
+ converter too: a seek invalidates a codec and resampler states.
617
+
618
+ Args:
619
+ seconds (float): The position to seek to.
620
+ stream (VideoStream or AudioStream, optional): The stream the
621
+ target ``seconds`` is resolved against. FFmpeg resolves a seek in a single
622
+ stream's time base and lands on *that* stream's keyframes, the
623
+ other streams merely resuming from wherever the container ends
624
+ up - so a second video stream may land mid-GOP and decode
625
+ garbage until its next keyframe. Defaults to the first of
626
+ :attr:`streams`, as passed to the constructor.
627
+ """
628
+ _blocks_demuxer_seek(
629
+ self._handle,
630
+ float(seconds),
631
+ None if stream is None else stream.index,
632
+ )
633
+ self._generation += 1
634
+
635
+
636
+ def _container_fields(handle: Tensor) -> dict:
637
+ container_dict = json.loads(_blocks_demuxer_container_json_metadata(handle))
638
+ return dict(
639
+ duration_seconds_from_header=container_dict.get("durationSecondsFromHeader"),
640
+ bit_rate_from_header=container_dict.get("bitRate"),
641
+ best_video_stream_index=container_dict.get("bestVideoStreamIndex"),
642
+ best_audio_stream_index=container_dict.get("bestAudioStreamIndex"),
643
+ )
644
+
645
+
646
+ def get_container_metadata(
647
+ source: str | Path | bytes | Tensor | io.RawIOBase | io.BufferedReader,
648
+ ) -> ContainerMetadata:
649
+ """Describe a container and every stream in it, without decoding anything.
650
+
651
+ .. code-block:: python
652
+
653
+ metadata = get_container_metadata("video.mp4")
654
+ metadata.duration_seconds_from_header
655
+ metadata.streams[metadata.best_video_stream_index].width
656
+
657
+ Only the header is read, so this is what to reach for before you know what a
658
+ file holds, and therefore which streams to ask a :class:`Demuxer` for.
659
+
660
+ Args:
661
+ source (str, ``Pathlib.path``, bytes, ``torch.Tensor`` or file-like object):
662
+ The source of the media, as for :class:`Demuxer`.
663
+
664
+ Returns:
665
+ ContainerMetadata: The container's own metadata, plus one entry per
666
+ stream, indexed by stream index.
667
+ """
668
+
669
+ handle = create_demuxer(source=source)
670
+ container_dict = json.loads(_blocks_demuxer_container_json_metadata(handle))
671
+ streams = [
672
+ _stream_metadata_from_dict(
673
+ json.loads(_blocks_demuxer_stream_json_metadata(handle, stream_index)),
674
+ stream_index,
675
+ )
676
+ for stream_index in range(int(container_dict["numStreams"]))
677
+ ]
678
+ return ContainerMetadata(**_container_fields(handle), streams=streams)