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,221 @@
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
+ """Expose Python file-like objects to the C++ FileLikeIO through ctypes.
8
+
9
+ See Note [File-like objects through ctypes] below.
10
+ """
11
+
12
+ import ctypes
13
+ from dataclasses import dataclass
14
+ from typing import Any
15
+
16
+ # Note [File-like objects through ctypes]
17
+ #
18
+ # File-like objects are user-specified Python objects with a read, write, and
19
+ # seek method. They can be used as the source or destination of a decoder or
20
+ # encoder, instead of a file on disk.
21
+ #
22
+ # Their read(), write(), and seek() methods are called from C++ by FFmpeg. We do
23
+ # this binding through ctypes (not pybind11! See below why).
24
+ #
25
+ # When a user gives us a file-like object, we create a _FileLikeContext to hold
26
+ # it, and we associate it with a _FileLikeCallbacks struct, which mirrors the
27
+ # C++ FileLikeCallbacks struct. This _FileLikeCallbacks struct **is a C struct
28
+ # in memory!** (that's what ctypes does). It holds callback pointers to the
29
+ # Python functions below (_read, _write, _seek, _release, _get_error). Each of
30
+ # these functions then calls the corresponding method of the file-like object:
31
+ # they know how, because they're given the Python id() of the _FileLikeContext
32
+ # that they must call those methods on.
33
+ #
34
+ # ctypes automatically acquires the GIL for each callback.
35
+ #
36
+ # The _FileLikeContext object is kept alive by Python, not by C++. It
37
+ # is stored in _ALIVE_CONTEXTS until its release() callback is called from C++,
38
+ # upon destruction of its associated FileLikeIO object.
39
+ #
40
+ # A Python exception cannot be raised from within a callback because it cannot
41
+ # cross the C++ boundary. So all callbacks catch exceptions and return a special
42
+ # value instead (_CALLBACK_ERROR). When C++ sees that value, it calls the
43
+ # get_error() callback to fetch the error message, which is then turned into a
44
+ # RuntimeError via STD_TORCH_CHECK(false, the_message).
45
+ #
46
+ # Why go the hard way of using ctypes instead of just using pybind? Mainly
47
+ # because we want our wheels to be py3-none, i.e. we don't want our wheels to be
48
+ # tied to a CPython version. We could use pybind and rely on stable ABIs like
49
+ # abi3/abi3t, but only from 3.15, and we don't want to wait that long.
50
+ #
51
+ # Note that ctypes does call the same Python C APIs that pybind does, so why can
52
+ # we keep our wheels py3-none? The main difference here is that *our* C++
53
+ # doesn't use them (directly or transitively through pybind). We only rely on
54
+ # ctypes, from Python, and C++ has no idea it's talking to Python. ctypes
55
+ # itself *is* compiled against a specific CPython version, just like pybind code
56
+ # would be. But that's fine: ctypes is part of CPython's standard library, so
57
+ # every Python installation ships its own ctypes, compiled for that exact
58
+ # version.
59
+
60
+ # Must match kFileLikeCallbackError in FileLikeIO.h.
61
+ _CALLBACK_ERROR = -(2**63)
62
+ _INT64_MAX = 2**63 - 1
63
+
64
+ _READ_FN_TYPE = ctypes.CFUNCTYPE(
65
+ ctypes.c_int64, ctypes.c_int64, ctypes.c_void_p, ctypes.c_int64
66
+ )
67
+ _WRITE_FN_TYPE = ctypes.CFUNCTYPE(
68
+ ctypes.c_int64, ctypes.c_int64, ctypes.c_void_p, ctypes.c_int64
69
+ )
70
+ _SEEK_FN_TYPE = ctypes.CFUNCTYPE(
71
+ ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64
72
+ )
73
+ _RELEASE_FN_TYPE = ctypes.CFUNCTYPE(None, ctypes.c_int64)
74
+ _GET_ERROR_FN_TYPE = ctypes.CFUNCTYPE(
75
+ ctypes.c_int64, ctypes.c_int64, ctypes.c_void_p, ctypes.c_int64
76
+ )
77
+
78
+
79
+ # Must match the layout of FileLikeCallbacks in FileLikeIO.h.
80
+ class _FileLikeCallbacks(ctypes.Structure):
81
+ _fields_ = [
82
+ ("id_", ctypes.c_int64),
83
+ ("read", _READ_FN_TYPE),
84
+ ("write", _WRITE_FN_TYPE),
85
+ ("seek", _SEEK_FN_TYPE),
86
+ ("release", _RELEASE_FN_TYPE),
87
+ ("get_error", _GET_ERROR_FN_TYPE),
88
+ ]
89
+
90
+
91
+ @dataclass
92
+ class _FileLikeContext:
93
+ file_like: Any
94
+ callbacks: _FileLikeCallbacks | None = None
95
+ error_message: str | None = None
96
+
97
+
98
+ # Keeps the file-like objects alive until C++ calls release(). Keyed by id_.
99
+ _ALIVE_CONTEXTS: dict[int, _FileLikeContext] = {}
100
+
101
+
102
+ def _format_error(e: BaseException) -> str:
103
+ try:
104
+ return f"{type(e).__name__}: {e}"
105
+ except BaseException:
106
+ # e.g. the exception's __str__ raised.
107
+ return "<unprintable exception>"
108
+
109
+
110
+ # NEVER call this outside of a try/except if within a callback
111
+ def _check_int64_result(result: Any, method: str) -> int:
112
+ # ctypes would turn a non-int, e.g. None, into a garbage value.
113
+ if not isinstance(result, int):
114
+ raise TypeError(f"{method}() must return an int, got {type(result).__name__}.")
115
+ # Excludes _CALLBACK_ERROR, which C++ would take for an error. Also excludes
116
+ # values outside the int64 range, which ctypes would silently wrap, e.g.
117
+ # 2**63 would reach C++ as _CALLBACK_ERROR.
118
+ if not _CALLBACK_ERROR < result <= _INT64_MAX:
119
+ raise ValueError(
120
+ f"{method}() returned {result}, which is outside the supported range "
121
+ f"[{_CALLBACK_ERROR + 1}, {_INT64_MAX}]."
122
+ )
123
+ return result
124
+
125
+
126
+ def _read(id_: int, buf: int, size: int) -> int:
127
+ context = _ALIVE_CONTEXTS[id_]
128
+ try:
129
+ # Fill buf unless we reach EOF: read() may return fewer bytes than
130
+ # requested.
131
+ total_num_read = 0
132
+ while total_num_read < size:
133
+ request = size - total_num_read
134
+ data = context.file_like.read(request)
135
+ if not isinstance(data, bytes):
136
+ raise TypeError(
137
+ f"read() must return bytes, got {type(data).__name__} instead."
138
+ )
139
+ num_bytes = len(data)
140
+ if num_bytes == 0:
141
+ break
142
+ # Guards the memmove below against overflowing buf.
143
+ if num_bytes > request:
144
+ raise ValueError(
145
+ f"Requested up to {request} bytes but, received {num_bytes} "
146
+ "bytes. The given object does not conform to read protocol "
147
+ "of file object."
148
+ )
149
+ ctypes.memmove(buf + total_num_read, data, num_bytes)
150
+ total_num_read += num_bytes
151
+ return total_num_read
152
+ except BaseException as e:
153
+ context.error_message = _format_error(e)
154
+ return _CALLBACK_ERROR
155
+
156
+
157
+ def _write(id_: int, buf: int, size: int) -> int:
158
+ context = _ALIVE_CONTEXTS[id_]
159
+ try:
160
+ result = context.file_like.write(ctypes.string_at(buf, size))
161
+ return _check_int64_result(result, "write")
162
+ except BaseException as e:
163
+ context.error_message = _format_error(e)
164
+ return _CALLBACK_ERROR
165
+
166
+
167
+ def _seek(id_: int, offset: int, whence: int) -> int:
168
+ context = _ALIVE_CONTEXTS[id_]
169
+ try:
170
+ result = context.file_like.seek(offset, whence)
171
+ return _check_int64_result(result, "seek")
172
+ except BaseException as e:
173
+ context.error_message = _format_error(e)
174
+ return _CALLBACK_ERROR
175
+
176
+
177
+ def _release(id_: int) -> None:
178
+ _ALIVE_CONTEXTS.pop(id_, None)
179
+
180
+
181
+ def _get_error(id_: int, buf: int, buf_len: int) -> int:
182
+ try:
183
+ context = _ALIVE_CONTEXTS[id_]
184
+ message, context.error_message = context.error_message, None
185
+ encoded = (message or "unknown error").encode(errors="replace")
186
+ # Don't truncate in the middle of a multi-byte UTF-8 sequence: the
187
+ # message must remain valid UTF-8 to be turned back into a Python str.
188
+ encoded = encoded[:buf_len].decode(errors="ignore").encode()
189
+ ctypes.memmove(buf, encoded, len(encoded))
190
+ return len(encoded)
191
+ except BaseException:
192
+ return 0
193
+
194
+
195
+ # These must stay alive for as long as C++ may call them, i.e. forever.
196
+ _read_fn = _READ_FN_TYPE(_read)
197
+ _write_fn = _WRITE_FN_TYPE(_write)
198
+ _seek_fn = _SEEK_FN_TYPE(_seek)
199
+ _release_fn = _RELEASE_FN_TYPE(_release)
200
+ _get_error_fn = _GET_ERROR_FN_TYPE(_get_error)
201
+
202
+
203
+ def create_file_like_context(file_like: Any, is_for_writing: bool) -> int:
204
+ """Create a _FileLikeContext and return the C address of its _FileLikeCallbacks struct."""
205
+ if is_for_writing:
206
+ if not hasattr(file_like, "write"):
207
+ raise RuntimeError(
208
+ "File like object must implement a write method for writing."
209
+ )
210
+ elif not hasattr(file_like, "read"):
211
+ raise RuntimeError("File like object must implement a read method for reading.")
212
+ if not hasattr(file_like, "seek"):
213
+ raise RuntimeError("File like object must implement a seek method.")
214
+
215
+ context = _FileLikeContext(file_like)
216
+ id_ = id(context)
217
+ context.callbacks = _FileLikeCallbacks(
218
+ id_, _read_fn, _write_fn, _seek_fn, _release_fn, _get_error_fn
219
+ )
220
+ _ALIVE_CONTEXTS[id_] = context
221
+ return ctypes.addressof(context.callbacks)
@@ -0,0 +1,402 @@
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 dataclasses
9
+ import json
10
+ import pathlib
11
+ from dataclasses import dataclass
12
+ from fractions import Fraction
13
+ from typing import Any
14
+
15
+ import torch
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
+ """Metadata of a single stream, as reported by the container header.
29
+
30
+ This is everything that is known about a stream without looking at its
31
+ content. Streams that are neither video nor audio (subtitles, data) are
32
+ described by this class and nothing more.
33
+ """
34
+
35
+ duration_seconds_from_header: float | None
36
+ """Duration of the stream, in seconds, obtained from the header (float or
37
+ None). This could be inaccurate."""
38
+ begin_stream_seconds_from_header: float | None
39
+ """Beginning of the stream, in seconds, obtained from the header (float or
40
+ None). Usually, this is equal to 0."""
41
+ bit_rate: float | None
42
+ """Bit rate of the stream, in seconds (float or None)."""
43
+ codec: str | None
44
+ """Codec (str or None)."""
45
+ time_base: Fraction | None
46
+ """The unit of the stream's timestamps, in seconds (Fraction or None): a
47
+ :term:`pts` of ``n`` means ``n * time_base`` seconds. That's the unit of
48
+ the integer timestamps of the low-level APIs, like :attr:`Packet.pts` and
49
+ :attr:`RawFrame.pts`."""
50
+ stream_index: int
51
+ """Index of the stream that this metadata refers to (int)."""
52
+ media_type: str
53
+ """Type of media the stream carries (str). One of ``"video"``, ``"audio"``,
54
+ ``"subtitle"``, ``"data"``, ``"attachment"`` or ``"unknown"``."""
55
+
56
+ def __repr__(self):
57
+ s = self.__class__.__name__ + ":\n"
58
+ for field in dataclasses.fields(self):
59
+ s += f"{SPACES}{field.name}: {getattr(self, field.name)}\n"
60
+ return s
61
+
62
+
63
+ @dataclass
64
+ class VideoStreamHeaderMetadata(StreamMetadata):
65
+ """Metadata of a single video stream, as reported by the container header."""
66
+
67
+ width: int | None
68
+ """Width of the frames (int or None)."""
69
+ height: int | None
70
+ """Height of the frames (int or None)."""
71
+ num_frames_from_header: int | None
72
+ """Number of frames, from the stream's metadata. This is potentially
73
+ inaccurate.
74
+ (int or None)."""
75
+ average_fps_from_header: float | None
76
+ """Averate fps of the stream, obtained from the header (float or None).
77
+ We recommend using the ``average_fps`` attribute instead."""
78
+ pixel_aspect_ratio: Fraction | None
79
+ """Pixel Aspect Ratio (PAR), also known as Sample Aspect Ratio
80
+ (SAR --- not to be confused with Storage Aspect Ratio, also SAR),
81
+ is the ratio between the width and height of each pixel
82
+ (``fractions.Fraction`` or None)."""
83
+ rotation: float | None
84
+ """Rotation angle in degrees (counter-clockwise rounded to the nearest
85
+ multiple of 90 degrees) from the display matrix metadata. This indicates
86
+ how the video should be rotated for correct display. TorchCodec automatically
87
+ applies this rotation during decoding, so the returned frames are in the
88
+ correct orientation (float or None).
89
+
90
+ .. note::
91
+
92
+ The :attr:`~torchcodec.decoders.VideoStreamMetadata.width` and
93
+ :attr:`~torchcodec.decoders.VideoStreamMetadata.height` attributes report
94
+ the **post-rotation** dimensions, i.e., the dimensions of frames as they
95
+ will be returned by TorchCodec's decoding methods. For videos with 90
96
+ or -90 degree rotation, this means width and height are swapped
97
+ compared to the raw encoded dimensions in the container.
98
+ """
99
+ color_primaries: str | None
100
+ """Color primaries as reported by FFmpeg. E.g. ``"bt709"``, ``"bt2020"``."""
101
+ color_space: str | None
102
+ """Color space as reported by FFmpeg. E.g. ``"bt709"``,
103
+ ``"bt2020nc"``."""
104
+ color_transfer_characteristic: str | None
105
+ """Color transfer characteristic as reported by FFmpeg
106
+ E.g. ``"bt709"``, ``"smpte2084"`` (PQ), ``"arib-std-b67"`` (HLG)."""
107
+ pixel_format: str | None
108
+ """The source pixel format of the video as reported by FFmpeg.
109
+ E.g. ``'yuv420p'``, ``'yuv444p'``, etc."""
110
+
111
+ def __repr__(self):
112
+ return super().__repr__()
113
+
114
+
115
+ @dataclass
116
+ class VideoStreamMetadata(VideoStreamHeaderMetadata):
117
+ """Metadata of a single video stream."""
118
+
119
+ begin_stream_seconds_from_content: float | None
120
+ """Beginning of the stream, in seconds (float or None).
121
+ Conceptually, this corresponds to the first frame's :term:`pts`. It is only
122
+ computed when a :term:`scan` is done as min(frame.pts) across all frames in
123
+ the stream. Usually, this is equal to 0."""
124
+ end_stream_seconds_from_content: float | None
125
+ """End of the stream, in seconds (float or None).
126
+ Conceptually, this corresponds to last_frame.pts + last_frame.duration. It
127
+ is only computed when a :term:`scan` is done as max(frame.pts +
128
+ frame.duration) across all frames in the stream. Note that no frame is
129
+ played at this time value, so calling
130
+ :meth:`~torchcodec.decoders.VideoDecoder.get_frame_played_at` with this
131
+ value would result in an error. Retrieving the last frame is best done by
132
+ simply indexing the :class:`~torchcodec.decoders.VideoDecoder` object with
133
+ ``[-1]``.
134
+ """
135
+ num_frames_from_content: int | None
136
+ """Number of frames computed by TorchCodec by scanning the stream's
137
+ content (the scan doesn't involve decoding). This is more accurate
138
+ than ``num_frames_from_header``. We recommend using the
139
+ ``num_frames`` attribute instead. (int or None)."""
140
+
141
+ # Computed fields (computed in C++ with fallback logic)
142
+ duration_seconds: float | None
143
+ """Duration of the stream in seconds. We try to calculate the duration
144
+ from the actual frames if a :term:`scan` was performed. Otherwise we
145
+ fall back to ``duration_seconds_from_header``. If that value is also None,
146
+ we instead calculate the duration from ``num_frames_from_header`` and
147
+ ``average_fps_from_header``. If all of those are unavailable, we fall back
148
+ to the container-level ``duration_seconds_from_header``.
149
+ """
150
+ begin_stream_seconds: float | None
151
+ """Beginning of the stream, in seconds (float). Conceptually, this
152
+ corresponds to the first frame's :term:`pts`. If a :term:`scan` was performed
153
+ and ``begin_stream_seconds_from_content`` is not None, then it is returned.
154
+ Otherwise, this value is 0.
155
+ """
156
+ end_stream_seconds: float | None
157
+ """End of the stream, in seconds (float or None).
158
+ Conceptually, this corresponds to last_frame.pts + last_frame.duration.
159
+ If :term:`scan` was performed and``end_stream_seconds_from_content`` is not None, then that value is
160
+ returned. Otherwise, returns ``duration_seconds``.
161
+ """
162
+ num_frames: int | None
163
+ """Number of frames in the stream (int or None).
164
+ This corresponds to ``num_frames_from_content`` if a :term:`scan` was made,
165
+ otherwise it corresponds to ``num_frames_from_header``. If that value is also
166
+ None, the number of frames is calculated from the duration and the average fps.
167
+ """
168
+ average_fps: float | None
169
+ """Average fps of the stream. If a :term:`scan` was perfomed, this is
170
+ computed from the number of frames and the duration of the stream.
171
+ Otherwise we fall back to ``average_fps_from_header``.
172
+ """
173
+
174
+ def __repr__(self):
175
+ return super().__repr__()
176
+
177
+
178
+ @dataclass
179
+ class AudioStreamHeaderMetadata(StreamMetadata):
180
+ """Metadata of a single audio stream, as reported by the container header."""
181
+
182
+ sample_rate: int | None
183
+ """The original sample rate."""
184
+ num_channels: int | None
185
+ """The number of channels (1 for mono, 2 for stereo, etc.)"""
186
+ sample_format: str | None
187
+ """The original sample format, as described by FFmpeg. E.g. 'fltp', 's32', etc."""
188
+
189
+ def __repr__(self):
190
+ return super().__repr__()
191
+
192
+
193
+ @dataclass
194
+ class AudioStreamMetadata(AudioStreamHeaderMetadata):
195
+ """Metadata of a single audio stream."""
196
+
197
+ # Computed fields (computed in C++ with fallback logic)
198
+ duration_seconds: float | None
199
+ """Duration of the stream in seconds. We try to calculate the duration
200
+ from the actual frames if a :term:`scan` was performed. Otherwise we
201
+ fall back to ``duration_seconds_from_header``. If that value is also None,
202
+ we instead calculate the duration from ``num_frames_from_header`` and
203
+ ``average_fps_from_header``. If all of those are unavailable, we fall back
204
+ to the container-level ``duration_seconds_from_header``.
205
+ """
206
+ begin_stream_seconds: float | None
207
+ """Beginning of the stream, in seconds (float). Conceptually, this
208
+ corresponds to the first frame's :term:`pts`. If a :term:`scan` was performed
209
+ and ``begin_stream_seconds_from_content`` is not None, then it is returned.
210
+ Otherwise, this value is 0.
211
+ """
212
+
213
+ def __repr__(self):
214
+ return super().__repr__()
215
+
216
+
217
+ @dataclass
218
+ class DemuxerMetadata:
219
+ """Container-level metadata, as reported by the header.
220
+
221
+ This is what a :class:`~torchcodec.decoders.Demuxer` can say about
222
+ the container itself.
223
+ """
224
+
225
+ duration_seconds_from_header: float | None
226
+ """Duration of the container, in seconds, obtained from the header (float
227
+ or None)."""
228
+ bit_rate_from_header: float | None
229
+ """Overall bit rate of the container (float or None)."""
230
+ best_video_stream_index: int | None
231
+ """Index of the :term:`best stream` of video type (int or None)."""
232
+ best_audio_stream_index: int | None
233
+ """Index of the :term:`best stream` of audio type (int or None)."""
234
+
235
+ def __repr__(self):
236
+ s = self.__class__.__name__ + ":\n"
237
+ for field in dataclasses.fields(self):
238
+ s += f"{SPACES}{field.name}: {getattr(self, field.name)}\n"
239
+ return s
240
+
241
+
242
+ @dataclass
243
+ class ContainerMetadata(DemuxerMetadata):
244
+ """Metadata of a container and of every stream in it.
245
+
246
+ Unlike :class:`DemuxerMetadata`, which describes the container alone, this
247
+ also lists the streams, including the ones that cannot be decoded.
248
+ """
249
+
250
+ streams: list[StreamMetadata]
251
+ """One entry per stream in the file, indexed by stream index.
252
+
253
+ A video stream comes back as a :class:`VideoStreamHeaderMetadata` and an
254
+ audio stream as an :class:`AudioStreamHeaderMetadata`. The rest will be plain
255
+ :class:`StreamMetadata`. The ``media_type`` attribute tells the
256
+ entries apart."""
257
+
258
+
259
+ def _get_optional_fraction(stream_dict, name):
260
+ try:
261
+ return Fraction(stream_dict[f"{name}Num"], stream_dict[f"{name}Den"])
262
+ except KeyError:
263
+ return None
264
+
265
+
266
+ # TODO-AUDIO: This is user-facing. Should this just be `get_metadata`, without
267
+ # the "container" name in it? Same below.
268
+ def _stream_metadata_from_dict(stream_dict: dict, stream_index: int) -> StreamMetadata:
269
+ """Build the header-tier metadata for one stream, from its JSON dict.
270
+
271
+ Shared by the decoder path, which then adds the content-derived and
272
+ computed fields, and by the building-block path, which has only this tier.
273
+ """
274
+ # Values come out of untyped JSON, so this is Any as far as mypy can tell.
275
+ header_meta: dict[str, Any] = dict(
276
+ duration_seconds_from_header=stream_dict.get("durationSecondsFromHeader"),
277
+ bit_rate=stream_dict.get("bitRate"),
278
+ begin_stream_seconds_from_header=stream_dict.get(
279
+ "beginStreamSecondsFromHeader"
280
+ ),
281
+ codec=stream_dict.get("codec"),
282
+ time_base=_get_optional_fraction(stream_dict, "timeBase"),
283
+ stream_index=stream_index,
284
+ media_type=stream_dict["mediaType"],
285
+ )
286
+ if stream_dict["mediaType"] == "video":
287
+ return VideoStreamHeaderMetadata(
288
+ width=stream_dict.get("width"),
289
+ height=stream_dict.get("height"),
290
+ num_frames_from_header=stream_dict.get("numFramesFromHeader"),
291
+ average_fps_from_header=stream_dict.get("averageFpsFromHeader"),
292
+ pixel_aspect_ratio=_get_optional_fraction(stream_dict, "sampleAspectRatio"),
293
+ rotation=stream_dict.get("rotation"),
294
+ color_primaries=stream_dict.get("colorPrimaries"),
295
+ color_space=stream_dict.get("colorSpace"),
296
+ color_transfer_characteristic=stream_dict.get(
297
+ "colorTransferCharacteristic"
298
+ ),
299
+ pixel_format=stream_dict.get("pixelFormat"),
300
+ **header_meta,
301
+ )
302
+ if stream_dict["mediaType"] == "audio":
303
+ return AudioStreamHeaderMetadata(
304
+ sample_rate=stream_dict.get("sampleRate"),
305
+ num_channels=stream_dict.get("numChannels"),
306
+ sample_format=stream_dict.get("sampleFormat"),
307
+ **header_meta,
308
+ )
309
+ # Neither video nor audio. Could be e.g. subtitles: visible, not decodable.
310
+ return StreamMetadata(**header_meta)
311
+
312
+
313
+ def get_container_metadata(decoder: torch.Tensor) -> ContainerMetadata:
314
+ """Return container metadata from a decoder.
315
+
316
+ The accuracy of the metadata and the availability of some returned fields
317
+ depends on whether a full scan was performed by the decoder.
318
+ """
319
+
320
+ container_dict = json.loads(_get_container_json_metadata(decoder))
321
+ streams_metadata: list[StreamMetadata] = []
322
+ for stream_index in range(container_dict["numStreams"]):
323
+ stream_dict = json.loads(_get_stream_json_metadata(decoder, stream_index))
324
+ header_meta = dict(
325
+ duration_seconds_from_header=stream_dict.get("durationSecondsFromHeader"),
326
+ bit_rate=stream_dict.get("bitRate"),
327
+ begin_stream_seconds_from_header=stream_dict.get(
328
+ "beginStreamSecondsFromHeader"
329
+ ),
330
+ codec=stream_dict.get("codec"),
331
+ time_base=_get_optional_fraction(stream_dict, "timeBase"),
332
+ stream_index=stream_index,
333
+ media_type=stream_dict["mediaType"],
334
+ )
335
+ # Only the video and audio classes have the computed fields; a stream of
336
+ # any other type is described by its header alone.
337
+ computed_meta = dict(
338
+ duration_seconds=stream_dict.get("durationSeconds"),
339
+ begin_stream_seconds=stream_dict.get("beginStreamSeconds"),
340
+ )
341
+ if stream_dict["mediaType"] == "video":
342
+ streams_metadata.append(
343
+ VideoStreamMetadata(
344
+ begin_stream_seconds_from_content=stream_dict.get(
345
+ "beginStreamSecondsFromContent"
346
+ ),
347
+ end_stream_seconds_from_content=stream_dict.get(
348
+ "endStreamSecondsFromContent"
349
+ ),
350
+ end_stream_seconds=stream_dict.get("endStreamSeconds"),
351
+ num_frames=stream_dict.get("numFrames"),
352
+ average_fps=stream_dict.get("averageFps"),
353
+ width=stream_dict.get("width"),
354
+ height=stream_dict.get("height"),
355
+ num_frames_from_header=stream_dict.get("numFramesFromHeader"),
356
+ num_frames_from_content=stream_dict.get("numFramesFromContent"),
357
+ average_fps_from_header=stream_dict.get("averageFpsFromHeader"),
358
+ pixel_aspect_ratio=_get_optional_fraction(
359
+ stream_dict, "sampleAspectRatio"
360
+ ),
361
+ rotation=stream_dict.get("rotation"),
362
+ color_primaries=stream_dict.get("colorPrimaries"),
363
+ color_space=stream_dict.get("colorSpace"),
364
+ color_transfer_characteristic=stream_dict.get(
365
+ "colorTransferCharacteristic"
366
+ ),
367
+ pixel_format=stream_dict.get("pixelFormat"),
368
+ **header_meta,
369
+ **computed_meta,
370
+ )
371
+ )
372
+ elif stream_dict["mediaType"] == "audio":
373
+ streams_metadata.append(
374
+ AudioStreamMetadata(
375
+ sample_rate=stream_dict.get("sampleRate"),
376
+ num_channels=stream_dict.get("numChannels"),
377
+ sample_format=stream_dict.get("sampleFormat"),
378
+ **header_meta,
379
+ **computed_meta,
380
+ )
381
+ )
382
+ else:
383
+ # This is neither a video nor audio stream. Could be e.g. subtitles.
384
+ # We still need to add a dummy entry so that len(streams_metadata)
385
+ # is consistent with the number of streams.
386
+ streams_metadata.append(StreamMetadata(**header_meta))
387
+
388
+ return ContainerMetadata(
389
+ duration_seconds_from_header=container_dict.get("durationSecondsFromHeader"),
390
+ bit_rate_from_header=container_dict.get("bitRate"),
391
+ best_video_stream_index=container_dict.get("bestVideoStreamIndex"),
392
+ best_audio_stream_index=container_dict.get("bestAudioStreamIndex"),
393
+ streams=streams_metadata,
394
+ )
395
+
396
+
397
+ def get_container_metadata_from_header(
398
+ filename: str | pathlib.Path,
399
+ ) -> ContainerMetadata:
400
+ return get_container_metadata(
401
+ create_from_file(str(filename), seek_mode="approximate")
402
+ )