torchcodec 0.7.0__cp312-cp312-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.

Potentially problematic release.


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

Files changed (67) hide show
  1. torchcodec/__init__.py +16 -0
  2. torchcodec/_core/AVIOContextHolder.cpp +60 -0
  3. torchcodec/_core/AVIOContextHolder.h +64 -0
  4. torchcodec/_core/AVIOFileLikeContext.cpp +98 -0
  5. torchcodec/_core/AVIOFileLikeContext.h +55 -0
  6. torchcodec/_core/AVIOTensorContext.cpp +123 -0
  7. torchcodec/_core/AVIOTensorContext.h +43 -0
  8. torchcodec/_core/CMakeLists.txt +292 -0
  9. torchcodec/_core/Cache.h +138 -0
  10. torchcodec/_core/CpuDeviceInterface.cpp +266 -0
  11. torchcodec/_core/CpuDeviceInterface.h +70 -0
  12. torchcodec/_core/CudaDeviceInterface.cpp +514 -0
  13. torchcodec/_core/CudaDeviceInterface.h +37 -0
  14. torchcodec/_core/DeviceInterface.cpp +79 -0
  15. torchcodec/_core/DeviceInterface.h +67 -0
  16. torchcodec/_core/Encoder.cpp +514 -0
  17. torchcodec/_core/Encoder.h +123 -0
  18. torchcodec/_core/FFMPEGCommon.cpp +421 -0
  19. torchcodec/_core/FFMPEGCommon.h +227 -0
  20. torchcodec/_core/FilterGraph.cpp +142 -0
  21. torchcodec/_core/FilterGraph.h +45 -0
  22. torchcodec/_core/Frame.cpp +32 -0
  23. torchcodec/_core/Frame.h +118 -0
  24. torchcodec/_core/Metadata.h +72 -0
  25. torchcodec/_core/SingleStreamDecoder.cpp +1715 -0
  26. torchcodec/_core/SingleStreamDecoder.h +380 -0
  27. torchcodec/_core/StreamOptions.h +53 -0
  28. torchcodec/_core/ValidationUtils.cpp +35 -0
  29. torchcodec/_core/ValidationUtils.h +21 -0
  30. torchcodec/_core/__init__.py +40 -0
  31. torchcodec/_core/_metadata.py +317 -0
  32. torchcodec/_core/custom_ops.cpp +727 -0
  33. torchcodec/_core/fetch_and_expose_non_gpl_ffmpeg_libs.cmake +300 -0
  34. torchcodec/_core/ops.py +455 -0
  35. torchcodec/_core/pybind_ops.cpp +87 -0
  36. torchcodec/_frame.py +145 -0
  37. torchcodec/_internally_replaced_utils.py +67 -0
  38. torchcodec/_samplers/__init__.py +7 -0
  39. torchcodec/_samplers/video_clip_sampler.py +430 -0
  40. torchcodec/decoders/__init__.py +11 -0
  41. torchcodec/decoders/_audio_decoder.py +177 -0
  42. torchcodec/decoders/_decoder_utils.py +52 -0
  43. torchcodec/decoders/_video_decoder.py +464 -0
  44. torchcodec/encoders/__init__.py +1 -0
  45. torchcodec/encoders/_audio_encoder.py +150 -0
  46. torchcodec/libtorchcodec_core4.dll +0 -0
  47. torchcodec/libtorchcodec_core5.dll +0 -0
  48. torchcodec/libtorchcodec_core6.dll +0 -0
  49. torchcodec/libtorchcodec_core7.dll +0 -0
  50. torchcodec/libtorchcodec_custom_ops4.dll +0 -0
  51. torchcodec/libtorchcodec_custom_ops5.dll +0 -0
  52. torchcodec/libtorchcodec_custom_ops6.dll +0 -0
  53. torchcodec/libtorchcodec_custom_ops7.dll +0 -0
  54. torchcodec/libtorchcodec_pybind_ops4.pyd +0 -0
  55. torchcodec/libtorchcodec_pybind_ops5.pyd +0 -0
  56. torchcodec/libtorchcodec_pybind_ops6.pyd +0 -0
  57. torchcodec/libtorchcodec_pybind_ops7.pyd +0 -0
  58. torchcodec/samplers/__init__.py +2 -0
  59. torchcodec/samplers/_common.py +84 -0
  60. torchcodec/samplers/_index_based.py +287 -0
  61. torchcodec/samplers/_time_based.py +350 -0
  62. torchcodec/version.py +2 -0
  63. torchcodec-0.7.0.dist-info/METADATA +242 -0
  64. torchcodec-0.7.0.dist-info/RECORD +67 -0
  65. torchcodec-0.7.0.dist-info/WHEEL +5 -0
  66. torchcodec-0.7.0.dist-info/licenses/LICENSE +28 -0
  67. torchcodec-0.7.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,317 @@
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 dataclasses
8
+ import json
9
+ import pathlib
10
+ from dataclasses import dataclass
11
+ from fractions import Fraction
12
+ from typing import List, Optional, Union
13
+
14
+ import torch
15
+
16
+ from torchcodec._core.ops import (
17
+ _get_container_json_metadata,
18
+ _get_stream_json_metadata,
19
+ create_from_file,
20
+ )
21
+
22
+
23
+ SPACES = " "
24
+
25
+
26
+ @dataclass
27
+ class StreamMetadata:
28
+ duration_seconds_from_header: Optional[float]
29
+ """Duration of the stream, in seconds, obtained from the header (float or
30
+ None). This could be inaccurate."""
31
+ begin_stream_seconds_from_header: Optional[float]
32
+ """Beginning of the stream, in seconds, obtained from the header (float or
33
+ None). Usually, this is equal to 0."""
34
+ bit_rate: Optional[float]
35
+ """Bit rate of the stream, in seconds (float or None)."""
36
+ codec: Optional[str]
37
+ """Codec (str or None)."""
38
+ stream_index: int
39
+ """Index of the stream that this metadata refers to (int)."""
40
+
41
+ def __repr__(self):
42
+ s = self.__class__.__name__ + ":\n"
43
+ for field in dataclasses.fields(self):
44
+ s += f"{SPACES}{field.name}: {getattr(self, field.name)}\n"
45
+ return s
46
+
47
+
48
+ @dataclass
49
+ class VideoStreamMetadata(StreamMetadata):
50
+ """Metadata of a single video stream."""
51
+
52
+ begin_stream_seconds_from_content: Optional[float]
53
+ """Beginning of the stream, in seconds (float or None).
54
+ Conceptually, this corresponds to the first frame's :term:`pts`. It is only
55
+ computed when a :term:`scan` is done as min(frame.pts) across all frames in
56
+ the stream. Usually, this is equal to 0."""
57
+ end_stream_seconds_from_content: Optional[float]
58
+ """End of the stream, in seconds (float or None).
59
+ Conceptually, this corresponds to last_frame.pts + last_frame.duration. It
60
+ is only computed when a :term:`scan` is done as max(frame.pts +
61
+ frame.duration) across all frames in the stream. Note that no frame is
62
+ played at this time value, so calling
63
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frame_played_at` with this
64
+ value would result in an error. Retrieving the last frame is best done by
65
+ simply indexing the :class:`~torchcodec.decoders.VideoDecoder` object with
66
+ ``[-1]``.
67
+ """
68
+ width: Optional[int]
69
+ """Width of the frames (int or None)."""
70
+ height: Optional[int]
71
+ """Height of the frames (int or None)."""
72
+ num_frames_from_header: Optional[int]
73
+ """Number of frames, from the stream's metadata. This is potentially
74
+ inaccurate. We recommend using the ``num_frames`` attribute instead.
75
+ (int or None)."""
76
+ num_frames_from_content: Optional[int]
77
+ """Number of frames computed by TorchCodec by scanning the stream's
78
+ content (the scan doesn't involve decoding). This is more accurate
79
+ than ``num_frames_from_header``. We recommend using the
80
+ ``num_frames`` attribute instead. (int or None)."""
81
+ average_fps_from_header: Optional[float]
82
+ """Averate fps of the stream, obtained from the header (float or None).
83
+ We recommend using the ``average_fps`` attribute instead."""
84
+ pixel_aspect_ratio: Optional[Fraction]
85
+ """Pixel Aspect Ratio (PAR), also known as Sample Aspect Ratio
86
+ (SAR --- not to be confused with Storage Aspect Ratio, also SAR),
87
+ is the ratio between the width and height of each pixel
88
+ (``fractions.Fraction`` or None)."""
89
+
90
+ @property
91
+ def duration_seconds(self) -> Optional[float]:
92
+ """Duration of the stream in seconds. We try to calculate the duration
93
+ from the actual frames if a :term:`scan` was performed. Otherwise we
94
+ fall back to ``duration_seconds_from_header``. If that value is also None,
95
+ we instead calculate the duration from ``num_frames_from_header`` and
96
+ ``average_fps_from_header``.
97
+ """
98
+ if (
99
+ self.end_stream_seconds_from_content is not None
100
+ and self.begin_stream_seconds_from_content is not None
101
+ ):
102
+ return (
103
+ self.end_stream_seconds_from_content
104
+ - self.begin_stream_seconds_from_content
105
+ )
106
+ elif self.duration_seconds_from_header is not None:
107
+ return self.duration_seconds_from_header
108
+ elif (
109
+ self.num_frames_from_header is not None
110
+ and self.average_fps_from_header is not None
111
+ ):
112
+ return self.num_frames_from_header / self.average_fps_from_header
113
+ else:
114
+ return None
115
+
116
+ @property
117
+ def begin_stream_seconds(self) -> float:
118
+ """Beginning of the stream, in seconds (float). Conceptually, this
119
+ corresponds to the first frame's :term:`pts`. If
120
+ ``begin_stream_seconds_from_content`` is not None, then it is returned.
121
+ Otherwise, this value is 0.
122
+ """
123
+ if self.begin_stream_seconds_from_content is None:
124
+ return 0
125
+ else:
126
+ return self.begin_stream_seconds_from_content
127
+
128
+ @property
129
+ def end_stream_seconds(self) -> Optional[float]:
130
+ """End of the stream, in seconds (float or None).
131
+ Conceptually, this corresponds to last_frame.pts + last_frame.duration.
132
+ If ``end_stream_seconds_from_content`` is not None, then that value is
133
+ returned. Otherwise, returns ``duration_seconds``.
134
+ """
135
+ if self.end_stream_seconds_from_content is None:
136
+ return self.duration_seconds
137
+ else:
138
+ return self.end_stream_seconds_from_content
139
+
140
+ @property
141
+ def num_frames(self) -> Optional[int]:
142
+ """Number of frames in the stream (int or None).
143
+ This corresponds to ``num_frames_from_content`` if a :term:`scan` was made,
144
+ otherwise it corresponds to ``num_frames_from_header``. If that value is also
145
+ None, the number of frames is calculated from the duration and the average fps.
146
+ """
147
+ if self.num_frames_from_content is not None:
148
+ return self.num_frames_from_content
149
+ elif self.num_frames_from_header is not None:
150
+ return self.num_frames_from_header
151
+ elif (
152
+ self.average_fps_from_header is not None
153
+ and self.duration_seconds_from_header is not None
154
+ ):
155
+ return int(self.average_fps_from_header * self.duration_seconds_from_header)
156
+ else:
157
+ return None
158
+
159
+ @property
160
+ def average_fps(self) -> Optional[float]:
161
+ """Average fps of the stream. If a :term:`scan` was perfomed, this is
162
+ computed from the number of frames and the duration of the stream.
163
+ Otherwise we fall back to ``average_fps_from_header``.
164
+ """
165
+ if (
166
+ self.end_stream_seconds_from_content is None
167
+ or self.begin_stream_seconds_from_content is None
168
+ or self.num_frames is None
169
+ # Should never happen, but prevents ZeroDivisionError:
170
+ or self.end_stream_seconds_from_content
171
+ == self.begin_stream_seconds_from_content
172
+ ):
173
+ return self.average_fps_from_header
174
+ return self.num_frames / (
175
+ self.end_stream_seconds_from_content
176
+ - self.begin_stream_seconds_from_content
177
+ )
178
+
179
+ def __repr__(self):
180
+ s = super().__repr__()
181
+ s += f"{SPACES}duration_seconds: {self.duration_seconds}\n"
182
+ s += f"{SPACES}begin_stream_seconds: {self.begin_stream_seconds}\n"
183
+ s += f"{SPACES}end_stream_seconds: {self.end_stream_seconds}\n"
184
+ s += f"{SPACES}num_frames: {self.num_frames}\n"
185
+ s += f"{SPACES}average_fps: {self.average_fps}\n"
186
+ return s
187
+
188
+
189
+ @dataclass
190
+ class AudioStreamMetadata(StreamMetadata):
191
+ """Metadata of a single audio stream."""
192
+
193
+ sample_rate: Optional[int]
194
+ """The original sample rate."""
195
+ num_channels: Optional[int]
196
+ """The number of channels (1 for mono, 2 for stereo, etc.)"""
197
+ sample_format: Optional[str]
198
+ """The original sample format, as described by FFmpeg. E.g. 'fltp', 's32', etc."""
199
+
200
+ def __repr__(self):
201
+ return super().__repr__()
202
+
203
+
204
+ @dataclass
205
+ class ContainerMetadata:
206
+ duration_seconds_from_header: Optional[float]
207
+ bit_rate_from_header: Optional[float]
208
+ best_video_stream_index: Optional[int]
209
+ best_audio_stream_index: Optional[int]
210
+
211
+ streams: List[StreamMetadata]
212
+
213
+ @property
214
+ def duration_seconds(self) -> Optional[float]:
215
+ raise NotImplementedError("Decide on logic and implement this!")
216
+
217
+ @property
218
+ def bit_rate(self) -> Optional[float]:
219
+ raise NotImplementedError("Decide on logic and implement this!")
220
+
221
+ @property
222
+ def best_video_stream(self) -> VideoStreamMetadata:
223
+ if self.best_video_stream_index is None:
224
+ raise ValueError("The best video stream is unknown.")
225
+ metadata = self.streams[self.best_video_stream_index]
226
+ assert isinstance(metadata, VideoStreamMetadata) # mypy <3
227
+ return metadata
228
+
229
+ @property
230
+ def best_audio_stream(self) -> AudioStreamMetadata:
231
+ if self.best_audio_stream_index is None:
232
+ raise ValueError("The best audio stream is unknown.")
233
+ metadata = self.streams[self.best_audio_stream_index]
234
+ assert isinstance(metadata, AudioStreamMetadata) # mypy <3
235
+ return metadata
236
+
237
+
238
+ def _get_optional_par_fraction(stream_dict):
239
+ try:
240
+ return Fraction(
241
+ stream_dict["sampleAspectRatioNum"],
242
+ stream_dict["sampleAspectRatioDen"],
243
+ )
244
+ except KeyError:
245
+ return None
246
+
247
+
248
+ # TODO-AUDIO: This is user-facing. Should this just be `get_metadata`, without
249
+ # the "container" name in it? Same below.
250
+ def get_container_metadata(decoder: torch.Tensor) -> ContainerMetadata:
251
+ """Return container metadata from a decoder.
252
+
253
+ The accuracy of the metadata and the availability of some returned fields
254
+ depends on whether a full scan was performed by the decoder.
255
+ """
256
+
257
+ container_dict = json.loads(_get_container_json_metadata(decoder))
258
+ streams_metadata: List[StreamMetadata] = []
259
+ for stream_index in range(container_dict["numStreams"]):
260
+ stream_dict = json.loads(_get_stream_json_metadata(decoder, stream_index))
261
+ common_meta = dict(
262
+ duration_seconds_from_header=stream_dict.get("durationSecondsFromHeader"),
263
+ bit_rate=stream_dict.get("bitRate"),
264
+ begin_stream_seconds_from_header=stream_dict.get(
265
+ "beginStreamSecondsFromHeader"
266
+ ),
267
+ codec=stream_dict.get("codec"),
268
+ stream_index=stream_index,
269
+ )
270
+ if stream_dict["mediaType"] == "video":
271
+ streams_metadata.append(
272
+ VideoStreamMetadata(
273
+ begin_stream_seconds_from_content=stream_dict.get(
274
+ "beginStreamSecondsFromContent"
275
+ ),
276
+ end_stream_seconds_from_content=stream_dict.get(
277
+ "endStreamSecondsFromContent"
278
+ ),
279
+ width=stream_dict.get("width"),
280
+ height=stream_dict.get("height"),
281
+ num_frames_from_header=stream_dict.get("numFramesFromHeader"),
282
+ num_frames_from_content=stream_dict.get("numFramesFromContent"),
283
+ average_fps_from_header=stream_dict.get("averageFpsFromHeader"),
284
+ pixel_aspect_ratio=_get_optional_par_fraction(stream_dict),
285
+ **common_meta,
286
+ )
287
+ )
288
+ elif stream_dict["mediaType"] == "audio":
289
+ streams_metadata.append(
290
+ AudioStreamMetadata(
291
+ sample_rate=stream_dict.get("sampleRate"),
292
+ num_channels=stream_dict.get("numChannels"),
293
+ sample_format=stream_dict.get("sampleFormat"),
294
+ **common_meta,
295
+ )
296
+ )
297
+ else:
298
+ # This is neither a video nor audio stream. Could be e.g. subtitles.
299
+ # We still need to add a dummy entry so that len(streams_metadata)
300
+ # is consistent with the number of streams.
301
+ streams_metadata.append(StreamMetadata(**common_meta))
302
+
303
+ return ContainerMetadata(
304
+ duration_seconds_from_header=container_dict.get("durationSecondsFromHeader"),
305
+ bit_rate_from_header=container_dict.get("bitRate"),
306
+ best_video_stream_index=container_dict.get("bestVideoStreamIndex"),
307
+ best_audio_stream_index=container_dict.get("bestAudioStreamIndex"),
308
+ streams=streams_metadata,
309
+ )
310
+
311
+
312
+ def get_container_metadata_from_header(
313
+ filename: Union[str, pathlib.Path]
314
+ ) -> ContainerMetadata:
315
+ return get_container_metadata(
316
+ create_from_file(str(filename), seek_mode="approximate")
317
+ )