torchcodec 0.8.0__cp313-cp313-macosx_12_0_arm64.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.

Potentially problematic release.


This version of torchcodec might be problematic. Click here for more details.

Files changed (82) hide show
  1. torchcodec/.dylibs/libc++.1.0.dylib +0 -0
  2. torchcodec/.dylibs/libpython3.13.dylib +0 -0
  3. torchcodec/__init__.py +16 -0
  4. torchcodec/_core/AVIOContextHolder.cpp +60 -0
  5. torchcodec/_core/AVIOContextHolder.h +64 -0
  6. torchcodec/_core/AVIOFileLikeContext.cpp +98 -0
  7. torchcodec/_core/AVIOFileLikeContext.h +55 -0
  8. torchcodec/_core/AVIOTensorContext.cpp +123 -0
  9. torchcodec/_core/AVIOTensorContext.h +43 -0
  10. torchcodec/_core/BetaCudaDeviceInterface.cpp +636 -0
  11. torchcodec/_core/BetaCudaDeviceInterface.h +191 -0
  12. torchcodec/_core/CMakeLists.txt +325 -0
  13. torchcodec/_core/CUDACommon.cpp +315 -0
  14. torchcodec/_core/CUDACommon.h +46 -0
  15. torchcodec/_core/Cache.h +138 -0
  16. torchcodec/_core/CpuDeviceInterface.cpp +347 -0
  17. torchcodec/_core/CpuDeviceInterface.h +132 -0
  18. torchcodec/_core/CudaDeviceInterface.cpp +357 -0
  19. torchcodec/_core/CudaDeviceInterface.h +64 -0
  20. torchcodec/_core/DeviceInterface.cpp +117 -0
  21. torchcodec/_core/DeviceInterface.h +148 -0
  22. torchcodec/_core/Encoder.cpp +807 -0
  23. torchcodec/_core/Encoder.h +173 -0
  24. torchcodec/_core/FFMPEGCommon.cpp +608 -0
  25. torchcodec/_core/FFMPEGCommon.h +245 -0
  26. torchcodec/_core/FilterGraph.cpp +149 -0
  27. torchcodec/_core/FilterGraph.h +59 -0
  28. torchcodec/_core/Frame.cpp +42 -0
  29. torchcodec/_core/Frame.h +72 -0
  30. torchcodec/_core/Metadata.h +72 -0
  31. torchcodec/_core/NVDECCache.cpp +70 -0
  32. torchcodec/_core/NVDECCache.h +104 -0
  33. torchcodec/_core/SingleStreamDecoder.cpp +1719 -0
  34. torchcodec/_core/SingleStreamDecoder.h +405 -0
  35. torchcodec/_core/StreamOptions.h +63 -0
  36. torchcodec/_core/Transform.cpp +60 -0
  37. torchcodec/_core/Transform.h +59 -0
  38. torchcodec/_core/ValidationUtils.cpp +35 -0
  39. torchcodec/_core/ValidationUtils.h +21 -0
  40. torchcodec/_core/__init__.py +41 -0
  41. torchcodec/_core/_metadata.py +317 -0
  42. torchcodec/_core/custom_ops.cpp +875 -0
  43. torchcodec/_core/fetch_and_expose_non_gpl_ffmpeg_libs.cmake +360 -0
  44. torchcodec/_core/nvcuvid_include/cuviddec.h +1374 -0
  45. torchcodec/_core/nvcuvid_include/nvcuvid.h +610 -0
  46. torchcodec/_core/ops.py +498 -0
  47. torchcodec/_core/pybind_ops.cpp +50 -0
  48. torchcodec/_frame.py +145 -0
  49. torchcodec/_internally_replaced_utils.py +67 -0
  50. torchcodec/_samplers/__init__.py +7 -0
  51. torchcodec/_samplers/video_clip_sampler.py +418 -0
  52. torchcodec/decoders/__init__.py +12 -0
  53. torchcodec/decoders/_audio_decoder.py +177 -0
  54. torchcodec/decoders/_decoder_utils.py +112 -0
  55. torchcodec/decoders/_video_decoder.py +500 -0
  56. torchcodec/encoders/__init__.py +1 -0
  57. torchcodec/encoders/_audio_encoder.py +150 -0
  58. torchcodec/libtorchcodec_core4.dylib +0 -0
  59. torchcodec/libtorchcodec_core5.dylib +0 -0
  60. torchcodec/libtorchcodec_core6.dylib +0 -0
  61. torchcodec/libtorchcodec_core7.dylib +0 -0
  62. torchcodec/libtorchcodec_core8.dylib +0 -0
  63. torchcodec/libtorchcodec_custom_ops4.dylib +0 -0
  64. torchcodec/libtorchcodec_custom_ops5.dylib +0 -0
  65. torchcodec/libtorchcodec_custom_ops6.dylib +0 -0
  66. torchcodec/libtorchcodec_custom_ops7.dylib +0 -0
  67. torchcodec/libtorchcodec_custom_ops8.dylib +0 -0
  68. torchcodec/libtorchcodec_pybind_ops4.so +0 -0
  69. torchcodec/libtorchcodec_pybind_ops5.so +0 -0
  70. torchcodec/libtorchcodec_pybind_ops6.so +0 -0
  71. torchcodec/libtorchcodec_pybind_ops7.so +0 -0
  72. torchcodec/libtorchcodec_pybind_ops8.so +0 -0
  73. torchcodec/samplers/__init__.py +2 -0
  74. torchcodec/samplers/_common.py +84 -0
  75. torchcodec/samplers/_index_based.py +287 -0
  76. torchcodec/samplers/_time_based.py +358 -0
  77. torchcodec/version.py +2 -0
  78. torchcodec-0.8.0.dist-info/METADATA +253 -0
  79. torchcodec-0.8.0.dist-info/RECORD +82 -0
  80. torchcodec-0.8.0.dist-info/WHEEL +5 -0
  81. torchcodec-0.8.0.dist-info/licenses/LICENSE +28 -0
  82. torchcodec-0.8.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,112 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import contextvars
8
+ import io
9
+ from contextlib import contextmanager
10
+ from pathlib import Path
11
+
12
+ from typing import Generator, Union
13
+
14
+ from torch import Tensor
15
+ from torchcodec import _core as core
16
+
17
+ ERROR_REPORTING_INSTRUCTIONS = """
18
+ This should never happen. Please report an issue following the steps in
19
+ https://github.com/pytorch/torchcodec/issues/new?assignees=&labels=&projects=&template=bug-report.yml.
20
+ """
21
+
22
+
23
+ def create_decoder(
24
+ *,
25
+ source: Union[str, Path, io.RawIOBase, io.BufferedReader, bytes, Tensor],
26
+ seek_mode: str,
27
+ ) -> Tensor:
28
+ if isinstance(source, str):
29
+ return core.create_from_file(source, seek_mode)
30
+ elif isinstance(source, Path):
31
+ return core.create_from_file(str(source), seek_mode)
32
+ elif isinstance(source, io.RawIOBase) or isinstance(source, io.BufferedReader):
33
+ return core.create_from_file_like(source, seek_mode)
34
+ elif isinstance(source, bytes):
35
+ return core.create_from_bytes(source, seek_mode)
36
+ elif isinstance(source, Tensor):
37
+ return core.create_from_tensor(source, seek_mode)
38
+ elif isinstance(source, io.TextIOBase):
39
+ raise TypeError(
40
+ "source is for reading text, likely from open(..., 'r'). Try with 'rb' for binary reading?"
41
+ )
42
+ elif hasattr(source, "read") and hasattr(source, "seek"):
43
+ # This check must be after checking for text-based reading. Also placing
44
+ # it last in general to be defensive: hasattr is a blunt instrument. We
45
+ # could use the inspect module to check for methods with the right
46
+ # signature.
47
+ return core.create_from_file_like(source, seek_mode)
48
+
49
+ raise TypeError(
50
+ f"Unknown source type: {type(source)}. "
51
+ "Supported types are str, Path, bytes, Tensor and file-like objects with "
52
+ "read(self, size: int) -> bytes and "
53
+ "seek(self, offset: int, whence: int) -> int methods."
54
+ )
55
+
56
+
57
+ # Thread-local and async-safe storage for the current CUDA backend
58
+ _CUDA_BACKEND: contextvars.ContextVar[str] = contextvars.ContextVar(
59
+ "_CUDA_BACKEND", default="ffmpeg"
60
+ )
61
+
62
+
63
+ @contextmanager
64
+ def set_cuda_backend(backend: str) -> Generator[None, None, None]:
65
+ """Context Manager to set the CUDA backend for :class:`~torchcodec.decoders.VideoDecoder`.
66
+
67
+ This context manager allows you to specify which CUDA backend implementation
68
+ to use when creating :class:`~torchcodec.decoders.VideoDecoder` instances
69
+ with CUDA devices.
70
+
71
+ .. note::
72
+ **We recommend trying the "beta" backend instead of the default "ffmpeg"
73
+ backend!** The beta backend is faster, and will eventually become the
74
+ default in future versions. It may have rough edges that we'll polish
75
+ over time, but it's already quite stable and ready for adoption. Let us
76
+ know what you think!
77
+
78
+ Only the creation of the decoder needs to be inside the context manager, the
79
+ decoding methods can be called outside of it. You still need to pass
80
+ ``device="cuda"`` when creating the
81
+ :class:`~torchcodec.decoders.VideoDecoder` instance. If a CUDA device isn't
82
+ specified, this context manager will have no effect. See example below.
83
+
84
+ This is thread-safe and async-safe.
85
+
86
+ Args:
87
+ backend (str): The CUDA backend to use. Can be "ffmpeg" (default) or
88
+ "beta". We recommend trying "beta" as it's faster!
89
+
90
+ Example:
91
+ >>> with set_cuda_backend("beta"):
92
+ ... decoder = VideoDecoder("video.mp4", device="cuda")
93
+ ...
94
+ ... # Only the decoder creation needs to be part of the context manager.
95
+ ... # Decoder will now the beta CUDA implementation:
96
+ ... decoder.get_frame_at(0)
97
+ """
98
+ backend = backend.lower()
99
+ if backend not in ("ffmpeg", "beta"):
100
+ raise ValueError(
101
+ f"Invalid CUDA backend ({backend}). Supported values are 'ffmpeg' and 'beta'."
102
+ )
103
+
104
+ previous_state = _CUDA_BACKEND.set(backend)
105
+ try:
106
+ yield
107
+ finally:
108
+ _CUDA_BACKEND.reset(previous_state)
109
+
110
+
111
+ def _get_cuda_backend() -> str:
112
+ return _CUDA_BACKEND.get()
@@ -0,0 +1,500 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import io
8
+ import json
9
+ import numbers
10
+ from pathlib import Path
11
+ from typing import Literal, Optional, Tuple, Union
12
+
13
+ import torch
14
+ from torch import device as torch_device, Tensor
15
+
16
+ from torchcodec import _core as core, Frame, FrameBatch
17
+ from torchcodec.decoders._decoder_utils import (
18
+ _get_cuda_backend,
19
+ create_decoder,
20
+ ERROR_REPORTING_INSTRUCTIONS,
21
+ )
22
+
23
+
24
+ class VideoDecoder:
25
+ """A single-stream video decoder.
26
+
27
+ Args:
28
+ source (str, ``Pathlib.path``, bytes, ``torch.Tensor`` or file-like object): The source of the video:
29
+
30
+ - If ``str``: a local path or a URL to a video file.
31
+ - If ``Pathlib.path``: a path to a local video file.
32
+ - If ``bytes`` object or ``torch.Tensor``: the raw encoded video data.
33
+ - If file-like object: we read video data from the object on demand. The object must
34
+ expose the methods `read(self, size: int) -> bytes` and
35
+ `seek(self, offset: int, whence: int) -> int`. Read more in:
36
+ :ref:`sphx_glr_generated_examples_decoding_file_like.py`.
37
+ stream_index (int, optional): Specifies which stream in the video to decode frames from.
38
+ Note that this index is absolute across all media types. If left unspecified, then
39
+ the :term:`best stream` is used.
40
+ dimension_order(str, optional): The dimension order of the decoded frames.
41
+ This can be either "NCHW" (default) or "NHWC", where N is the batch
42
+ size, C is the number of channels, H is the height, and W is the
43
+ width of the frames.
44
+
45
+ .. note::
46
+
47
+ Frames are natively decoded in NHWC format by the underlying
48
+ FFmpeg implementation. Converting those into NCHW format is a
49
+ cheap no-copy operation that allows these frames to be
50
+ transformed using the `torchvision transforms
51
+ <https://pytorch.org/vision/stable/transforms.html>`_.
52
+ num_ffmpeg_threads (int, optional): The number of threads to use for decoding.
53
+ Use 1 for single-threaded decoding which may be best if you are running multiple
54
+ instances of ``VideoDecoder`` in parallel. Use a higher number for multi-threaded
55
+ decoding which is best if you are running a single instance of ``VideoDecoder``.
56
+ Passing 0 lets FFmpeg decide on the number of threads.
57
+ Default: 1.
58
+ device (str or torch.device, optional): The device to use for decoding. Default: "cpu".
59
+ If you pass a CUDA device, we recommend trying the "beta" CUDA
60
+ backend which is faster! See :func:`~torchcodec.decoders.set_cuda_backend`.
61
+ seek_mode (str, optional): Determines if frame access will be "exact" or
62
+ "approximate". Exact guarantees that requesting frame i will always
63
+ return frame i, but doing so requires an initial :term:`scan` of the
64
+ file. Approximate is faster as it avoids scanning the file, but less
65
+ accurate as it uses the file's metadata to calculate where i
66
+ probably is. Default: "exact".
67
+ Read more about this parameter in:
68
+ :ref:`sphx_glr_generated_examples_decoding_approximate_mode.py`
69
+ custom_frame_mappings (str, bytes, or file-like object, optional):
70
+ Mapping of frames to their metadata, typically generated via ffprobe.
71
+ This enables accurate frame seeking without requiring a full video scan.
72
+ Do not set seek_mode when custom_frame_mappings is provided.
73
+ Expected JSON format:
74
+
75
+ .. code-block:: json
76
+
77
+ {
78
+ "frames": [
79
+ {
80
+ "pts": 0,
81
+ "duration": 1001,
82
+ "key_frame": 1
83
+ }
84
+ ]
85
+ }
86
+
87
+ Alternative field names "pkt_pts" and "pkt_duration" are also supported.
88
+ Read more about this parameter in:
89
+ :ref:`sphx_glr_generated_examples_decoding_custom_frame_mappings.py`
90
+
91
+ Attributes:
92
+ metadata (VideoStreamMetadata): Metadata of the video stream.
93
+ stream_index (int): The stream index that this decoder is retrieving frames from. If a
94
+ stream index was provided at initialization, this is the same value. If it was left
95
+ unspecified, this is the :term:`best stream`.
96
+ """
97
+
98
+ def __init__(
99
+ self,
100
+ source: Union[str, Path, io.RawIOBase, io.BufferedReader, bytes, Tensor],
101
+ *,
102
+ stream_index: Optional[int] = None,
103
+ dimension_order: Literal["NCHW", "NHWC"] = "NCHW",
104
+ num_ffmpeg_threads: int = 1,
105
+ device: Optional[Union[str, torch_device]] = "cpu",
106
+ seek_mode: Literal["exact", "approximate"] = "exact",
107
+ custom_frame_mappings: Optional[
108
+ Union[str, bytes, io.RawIOBase, io.BufferedReader]
109
+ ] = None,
110
+ ):
111
+ torch._C._log_api_usage_once("torchcodec.decoders.VideoDecoder")
112
+ allowed_seek_modes = ("exact", "approximate")
113
+ if seek_mode not in allowed_seek_modes:
114
+ raise ValueError(
115
+ f"Invalid seek mode ({seek_mode}). "
116
+ f"Supported values are {', '.join(allowed_seek_modes)}."
117
+ )
118
+
119
+ # Validate seek_mode and custom_frame_mappings are not mismatched
120
+ if custom_frame_mappings is not None and seek_mode == "approximate":
121
+ raise ValueError(
122
+ "custom_frame_mappings is incompatible with seek_mode='approximate'. "
123
+ "Use seek_mode='custom_frame_mappings' or leave it unspecified to automatically use custom frame mappings."
124
+ )
125
+
126
+ # Auto-select custom_frame_mappings seek_mode and process data when mappings are provided
127
+ custom_frame_mappings_data = None
128
+ if custom_frame_mappings is not None:
129
+ seek_mode = "custom_frame_mappings" # type: ignore[assignment]
130
+ custom_frame_mappings_data = _read_custom_frame_mappings(
131
+ custom_frame_mappings
132
+ )
133
+
134
+ self._decoder = create_decoder(source=source, seek_mode=seek_mode)
135
+
136
+ allowed_dimension_orders = ("NCHW", "NHWC")
137
+ if dimension_order not in allowed_dimension_orders:
138
+ raise ValueError(
139
+ f"Invalid dimension order ({dimension_order}). "
140
+ f"Supported values are {', '.join(allowed_dimension_orders)}."
141
+ )
142
+
143
+ if num_ffmpeg_threads is None:
144
+ raise ValueError(f"{num_ffmpeg_threads = } should be an int.")
145
+
146
+ if isinstance(device, torch_device):
147
+ device = str(device)
148
+
149
+ device_variant = _get_cuda_backend()
150
+ if device_variant == "ffmpeg":
151
+ # TODONVDEC P2 rename 'default' into 'ffmpeg' everywhere.
152
+ device_variant = "default"
153
+
154
+ # Legacy support for device="cuda:0:beta" syntax
155
+ # TODONVDEC P2: remove support for this everywhere. This will require
156
+ # updating our tests.
157
+ if device == "cuda:0:beta":
158
+ device = "cuda:0"
159
+ device_variant = "beta"
160
+
161
+ core.add_video_stream(
162
+ self._decoder,
163
+ stream_index=stream_index,
164
+ dimension_order=dimension_order,
165
+ num_threads=num_ffmpeg_threads,
166
+ device=device,
167
+ device_variant=device_variant,
168
+ custom_frame_mappings=custom_frame_mappings_data,
169
+ )
170
+
171
+ (
172
+ self.metadata,
173
+ self.stream_index,
174
+ self._begin_stream_seconds,
175
+ self._end_stream_seconds,
176
+ self._num_frames,
177
+ ) = _get_and_validate_stream_metadata(
178
+ decoder=self._decoder, stream_index=stream_index
179
+ )
180
+
181
+ def __len__(self) -> int:
182
+ return self._num_frames
183
+
184
+ def _getitem_int(self, key: int) -> Tensor:
185
+ assert isinstance(key, int)
186
+
187
+ frame_data, *_ = core.get_frame_at_index(self._decoder, frame_index=key)
188
+ return frame_data
189
+
190
+ def _getitem_slice(self, key: slice) -> Tensor:
191
+ assert isinstance(key, slice)
192
+
193
+ start, stop, step = key.indices(len(self))
194
+ frame_data, *_ = core.get_frames_in_range(
195
+ self._decoder,
196
+ start=start,
197
+ stop=stop,
198
+ step=step,
199
+ )
200
+ return frame_data
201
+
202
+ def __getitem__(self, key: Union[numbers.Integral, slice]) -> Tensor:
203
+ """Return frame or frames as tensors, at the given index or range.
204
+
205
+ .. note::
206
+
207
+ If you need to decode multiple frames, we recommend using the batch
208
+ methods instead, since they are faster:
209
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_at`,
210
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_in_range`,
211
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_played_at`, and
212
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_played_in_range`.
213
+
214
+ Args:
215
+ key(int or slice): The index or range of frame(s) to retrieve.
216
+
217
+ Returns:
218
+ torch.Tensor: The frame or frames at the given index or range.
219
+ """
220
+ if isinstance(key, numbers.Integral):
221
+ return self._getitem_int(int(key))
222
+ elif isinstance(key, slice):
223
+ return self._getitem_slice(key)
224
+
225
+ raise TypeError(
226
+ f"Unsupported key type: {type(key)}. Supported types are int and slice."
227
+ )
228
+
229
+ def _get_key_frame_indices(self) -> list[int]:
230
+ return core._get_key_frame_indices(self._decoder)
231
+
232
+ def get_frame_at(self, index: int) -> Frame:
233
+ """Return a single frame at the given index.
234
+
235
+ .. note::
236
+
237
+ If you need to decode multiple frames, we recommend using the batch
238
+ methods instead, since they are faster:
239
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_at`,
240
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_in_range`,
241
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_played_at`,
242
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_played_in_range`.
243
+
244
+ Args:
245
+ index (int): The index of the frame to retrieve.
246
+
247
+ Returns:
248
+ Frame: The frame at the given index.
249
+ """
250
+ data, pts_seconds, duration_seconds = core.get_frame_at_index(
251
+ self._decoder, frame_index=index
252
+ )
253
+ return Frame(
254
+ data=data,
255
+ pts_seconds=pts_seconds.item(),
256
+ duration_seconds=duration_seconds.item(),
257
+ )
258
+
259
+ def get_frames_at(self, indices: Union[torch.Tensor, list[int]]) -> FrameBatch:
260
+ """Return frames at the given indices.
261
+
262
+ Args:
263
+ indices (torch.Tensor or list of int): The indices of the frames to retrieve.
264
+
265
+ Returns:
266
+ FrameBatch: The frames at the given indices.
267
+ """
268
+
269
+ data, pts_seconds, duration_seconds = core.get_frames_at_indices(
270
+ self._decoder, frame_indices=indices
271
+ )
272
+
273
+ return FrameBatch(
274
+ data=data,
275
+ pts_seconds=pts_seconds,
276
+ duration_seconds=duration_seconds,
277
+ )
278
+
279
+ def get_frames_in_range(self, start: int, stop: int, step: int = 1) -> FrameBatch:
280
+ """Return multiple frames at the given index range.
281
+
282
+ Frames are in [start, stop).
283
+
284
+ Args:
285
+ start (int): Index of the first frame to retrieve.
286
+ stop (int): End of indexing range (exclusive, as per Python
287
+ conventions).
288
+ step (int, optional): Step size between frames. Default: 1.
289
+
290
+ Returns:
291
+ FrameBatch: The frames within the specified range.
292
+ """
293
+ # Adjust start / stop indices to enable indexing semantics, ex. [-10, 1000] returns the last 10 frames
294
+ start, stop, step = slice(start, stop, step).indices(self._num_frames)
295
+ frames = core.get_frames_in_range(
296
+ self._decoder,
297
+ start=start,
298
+ stop=stop,
299
+ step=step,
300
+ )
301
+ return FrameBatch(*frames)
302
+
303
+ def get_frame_played_at(self, seconds: float) -> Frame:
304
+ """Return a single frame played at the given timestamp in seconds.
305
+
306
+ .. note::
307
+
308
+ If you need to decode multiple frames, we recommend using the batch
309
+ methods instead, since they are faster:
310
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_at`,
311
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_in_range`,
312
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_played_at`,
313
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frames_played_in_range`.
314
+
315
+ Args:
316
+ seconds (float): The time stamp in seconds when the frame is played.
317
+
318
+ Returns:
319
+ Frame: The frame that is played at ``seconds``.
320
+ """
321
+ if not self._begin_stream_seconds <= seconds < self._end_stream_seconds:
322
+ raise IndexError(
323
+ f"Invalid pts in seconds: {seconds}. "
324
+ f"It must be greater than or equal to {self._begin_stream_seconds} "
325
+ f"and less than {self._end_stream_seconds}."
326
+ )
327
+ data, pts_seconds, duration_seconds = core.get_frame_at_pts(
328
+ self._decoder, seconds
329
+ )
330
+ return Frame(
331
+ data=data,
332
+ pts_seconds=pts_seconds.item(),
333
+ duration_seconds=duration_seconds.item(),
334
+ )
335
+
336
+ def get_frames_played_at(
337
+ self, seconds: Union[torch.Tensor, list[float]]
338
+ ) -> FrameBatch:
339
+ """Return frames played at the given timestamps in seconds.
340
+
341
+ Args:
342
+ seconds (torch.Tensor or list of float): The timestamps in seconds when the frames are played.
343
+
344
+ Returns:
345
+ FrameBatch: The frames that are played at ``seconds``.
346
+ """
347
+
348
+ data, pts_seconds, duration_seconds = core.get_frames_by_pts(
349
+ self._decoder, timestamps=seconds
350
+ )
351
+ return FrameBatch(
352
+ data=data,
353
+ pts_seconds=pts_seconds,
354
+ duration_seconds=duration_seconds,
355
+ )
356
+
357
+ def get_frames_played_in_range(
358
+ self, start_seconds: float, stop_seconds: float
359
+ ) -> FrameBatch:
360
+ """Returns multiple frames in the given range.
361
+
362
+ Frames are in the half open range [start_seconds, stop_seconds). Each
363
+ returned frame's :term:`pts`, in seconds, is inside of the half open
364
+ range.
365
+
366
+ Args:
367
+ start_seconds (float): Time, in seconds, of the start of the
368
+ range.
369
+ stop_seconds (float): Time, in seconds, of the end of the
370
+ range. As a half open range, the end is excluded.
371
+
372
+ Returns:
373
+ FrameBatch: The frames within the specified range.
374
+ """
375
+ if not start_seconds <= stop_seconds:
376
+ raise ValueError(
377
+ f"Invalid start seconds: {start_seconds}. It must be less than or equal to stop seconds ({stop_seconds})."
378
+ )
379
+ if not self._begin_stream_seconds <= start_seconds < self._end_stream_seconds:
380
+ raise ValueError(
381
+ f"Invalid start seconds: {start_seconds}. "
382
+ f"It must be greater than or equal to {self._begin_stream_seconds} "
383
+ f"and less than or equal to {self._end_stream_seconds}."
384
+ )
385
+ if not stop_seconds <= self._end_stream_seconds:
386
+ raise ValueError(
387
+ f"Invalid stop seconds: {stop_seconds}. "
388
+ f"It must be less than or equal to {self._end_stream_seconds}."
389
+ )
390
+ frames = core.get_frames_by_pts_in_range(
391
+ self._decoder,
392
+ start_seconds=start_seconds,
393
+ stop_seconds=stop_seconds,
394
+ )
395
+ return FrameBatch(*frames)
396
+
397
+
398
+ def _get_and_validate_stream_metadata(
399
+ *,
400
+ decoder: Tensor,
401
+ stream_index: Optional[int] = None,
402
+ ) -> Tuple[core._metadata.VideoStreamMetadata, int, float, float, int]:
403
+
404
+ container_metadata = core.get_container_metadata(decoder)
405
+
406
+ if stream_index is None:
407
+ if (stream_index := container_metadata.best_video_stream_index) is None:
408
+ raise ValueError(
409
+ "The best video stream is unknown and there is no specified stream. "
410
+ + ERROR_REPORTING_INSTRUCTIONS
411
+ )
412
+
413
+ metadata = container_metadata.streams[stream_index]
414
+ assert isinstance(metadata, core._metadata.VideoStreamMetadata) # mypy
415
+
416
+ if metadata.begin_stream_seconds is None:
417
+ raise ValueError(
418
+ "The minimum pts value in seconds is unknown. "
419
+ + ERROR_REPORTING_INSTRUCTIONS
420
+ )
421
+ begin_stream_seconds = metadata.begin_stream_seconds
422
+
423
+ if metadata.end_stream_seconds is None:
424
+ raise ValueError(
425
+ "The maximum pts value in seconds is unknown. "
426
+ + ERROR_REPORTING_INSTRUCTIONS
427
+ )
428
+ end_stream_seconds = metadata.end_stream_seconds
429
+
430
+ if metadata.num_frames is None:
431
+ raise ValueError(
432
+ "The number of frames is unknown. " + ERROR_REPORTING_INSTRUCTIONS
433
+ )
434
+ num_frames = metadata.num_frames
435
+
436
+ return (
437
+ metadata,
438
+ stream_index,
439
+ begin_stream_seconds,
440
+ end_stream_seconds,
441
+ num_frames,
442
+ )
443
+
444
+
445
+ def _read_custom_frame_mappings(
446
+ custom_frame_mappings: Union[str, bytes, io.RawIOBase, io.BufferedReader]
447
+ ) -> tuple[Tensor, Tensor, Tensor]:
448
+ """Parse custom frame mappings from JSON data and extract frame metadata.
449
+
450
+ Args:
451
+ custom_frame_mappings: JSON data containing frame metadata, provided as:
452
+ - A JSON string (str, bytes)
453
+ - A file-like object with a read() method
454
+
455
+ Returns:
456
+ A tuple of three tensors:
457
+ - all_frames (Tensor): Presentation timestamps (PTS) for each frame
458
+ - is_key_frame (Tensor): Boolean tensor indicating which frames are key frames
459
+ - duration (Tensor): Duration of each frame
460
+ """
461
+ try:
462
+ input_data = (
463
+ json.load(custom_frame_mappings)
464
+ if hasattr(custom_frame_mappings, "read")
465
+ else json.loads(custom_frame_mappings)
466
+ )
467
+ except json.JSONDecodeError as e:
468
+ raise ValueError(
469
+ f"Invalid custom frame mappings: {e}. It should be a valid JSON string or a file-like object."
470
+ ) from e
471
+
472
+ if not input_data or "frames" not in input_data:
473
+ raise ValueError(
474
+ "Invalid custom frame mappings. The input is empty or missing the required 'frames' key."
475
+ )
476
+
477
+ first_frame = input_data["frames"][0]
478
+ pts_key = next((key for key in ("pts", "pkt_pts") if key in first_frame), None)
479
+ duration_key = next(
480
+ (key for key in ("duration", "pkt_duration") if key in first_frame), None
481
+ )
482
+ key_frame_present = "key_frame" in first_frame
483
+
484
+ if not pts_key or not duration_key or not key_frame_present:
485
+ raise ValueError(
486
+ "Invalid custom frame mappings. The 'pts'/'pkt_pts', 'duration'/'pkt_duration', and 'key_frame' keys are required in the frame metadata."
487
+ )
488
+
489
+ all_frames = torch.tensor(
490
+ [int(frame[pts_key]) for frame in input_data["frames"]], dtype=torch.int64
491
+ )
492
+ is_key_frame = torch.tensor(
493
+ [int(frame["key_frame"]) for frame in input_data["frames"]], dtype=torch.bool
494
+ )
495
+ duration = torch.tensor(
496
+ [int(frame[duration_key]) for frame in input_data["frames"]], dtype=torch.int64
497
+ )
498
+ if not (len(all_frames) == len(is_key_frame) == len(duration)):
499
+ raise ValueError("Mismatched lengths in frame index data")
500
+ return all_frames, is_key_frame, duration
@@ -0,0 +1 @@
1
+ from ._audio_encoder import AudioEncoder # noqa