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,103 @@
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 os
9
+ import shutil
10
+ import sys
11
+ from contextlib import nullcontext
12
+ from pathlib import Path
13
+
14
+ import torch
15
+ from torchcodec._core._ffmpeg_op_names import FFMPEG_OP_NAMES
16
+ from torchcodec._core._file_like import create_file_like_context # noqa: F401
17
+ from torchcodec._internally_replaced_utils import ( # @manual=//pytorch/torchcodec/src:internally_replaced_utils
18
+ load_core_libraries,
19
+ load_heic_library,
20
+ load_image_library,
21
+ )
22
+
23
+ expose_ffmpeg_dlls = nullcontext
24
+ if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
25
+ # On windows we try to locate the FFmpeg DLLs and temporarily add them to
26
+ # the DLL search path. This seems to be needed on some users machine, but
27
+ # not on our CI. We don't know why.
28
+ if ffmpeg_path := shutil.which("ffmpeg"):
29
+
30
+ def expose_ffmpeg_dlls(): # noqa: F811
31
+ ffmpeg_dir = Path(ffmpeg_path).parent.absolute()
32
+ return os.add_dll_directory(str(ffmpeg_dir)) # that's the actual CM
33
+
34
+
35
+ load_image_library()
36
+
37
+ decode_jpeg = torch.ops.torchcodec_ns.decode_jpeg.default
38
+ decode_jpegs_cuda = torch.ops.torchcodec_ns.decode_jpegs_cuda.default
39
+ decode_png = torch.ops.torchcodec_ns.decode_png.default
40
+ decode_webp = torch.ops.torchcodec_ns.decode_webp.default
41
+ decode_gif = torch.ops.torchcodec_ns.decode_gif.default
42
+ decode_avif = torch.ops.torchcodec_ns.decode_avif.default
43
+ encode_png_to_file = torch.ops.torchcodec_ns.encode_png_to_file.default
44
+ encode_png_to_file_like = torch.ops.torchcodec_ns.encode_png_to_file_like.default
45
+ encode_jpeg_to_file = torch.ops.torchcodec_ns.encode_jpeg_to_file.default
46
+ encode_jpeg_to_file_like = torch.ops.torchcodec_ns.encode_jpeg_to_file_like.default
47
+ encode_jpeg_to_tensor_cuda = torch.ops.torchcodec_ns.encode_jpeg_to_tensor_cuda.default
48
+ probe_gif_from_tensor = torch.ops.torchcodec_ns.probe_gif_from_tensor.default
49
+ probe_gif_from_file = torch.ops.torchcodec_ns.probe_gif_from_file.default
50
+ probe_avif_from_tensor = torch.ops.torchcodec_ns.probe_avif_from_tensor.default
51
+ probe_avif_from_file = torch.ops.torchcodec_ns.probe_avif_from_file.default
52
+ png_skip_idat_chunks_from_tensor = (
53
+ torch.ops.torchcodec_ns.png_skip_idat_chunks_from_tensor.default
54
+ )
55
+ png_skip_idat_chunks_from_file = (
56
+ torch.ops.torchcodec_ns.png_skip_idat_chunks_from_file.default
57
+ )
58
+
59
+
60
+ def get_decode_heic():
61
+ # decode_heic lives in the separate, lazily-loaded libtorchcodec_heic (see
62
+ # load_heic_library), so its op isn't registered until that library loads,
63
+ # and loading fails if the user hasn't installed libheif. Turn that into an
64
+ # actionable error.
65
+ try:
66
+ load_heic_library()
67
+ except Exception as e:
68
+ raise ImportError(
69
+ "Failed to load the HEIC decoding library. HEIC decoding requires "
70
+ "libheif to be installed and discoverable at runtime; TorchCodec "
71
+ "does not bundle it (it's LGPL). Install it, e.g. with "
72
+ "`conda install -c conda-forge libheif`, `apt install libheif1`, or "
73
+ "`brew install libheif`."
74
+ ) from e
75
+ return torch.ops.torchcodec_ns.decode_heic.default
76
+
77
+
78
+ # FFmpeg is now an optional dependency, since the image decoders above don't
79
+ # need it, and we want users to be able to use them without having FFmpeg
80
+ # installed. We try to load the ffmpeg-dependent ops at import time and bind
81
+ # their names to the actual implementation. If it doesn't work
82
+ # (_FFMPEG_AVAILABLE is then False), we bind the names to a dummy lambda that
83
+ # will raise a proper error when called.
84
+ try:
85
+ with expose_ffmpeg_dlls():
86
+ ffmpeg_major_version, core_library_path = load_core_libraries()
87
+ _FFMPEG_AVAILABLE = True
88
+ except Exception:
89
+ _FFMPEG_AVAILABLE = False
90
+ ffmpeg_major_version = None
91
+ core_library_path = None
92
+
93
+
94
+ if _FFMPEG_AVAILABLE:
95
+ from torchcodec._core._ffmpeg_ops import * # noqa: F401,F403
96
+ else:
97
+
98
+ def __getattr__(name):
99
+ # Mocks all names in FFMPEG_OP_NAMES to raise an error when called, if
100
+ # FFmpeg is not available.
101
+ if name in FFMPEG_OP_NAMES:
102
+ return lambda *args, **kwargs: load_core_libraries()
103
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,113 @@
1
+ # Single source of truth for torchcodec's _core C++ source file lists.
2
+ #
3
+ # These lists are consumed by BOTH build systems so that adding or removing a
4
+ # source file only requires editing this one file:
5
+ # - CMake (the GitHub/OSS build) reads it from CMakeLists.txt in this directory.
6
+ # - Buck (the internal Meta build) loads it from src/BUCK.
7
+ #
8
+ # This file must stay syntactically valid as BOTH Starlark (so Buck can `load()`
9
+ # it) and Python (CMake execs it with the Python interpreter to extract the
10
+ # lists). Only plain list literals and list comprehensions are allowed here: no
11
+ # functions, no `load()`, no `select()`, no f-strings, no Starlark-only or
12
+ # Python-only constructs.
13
+ #
14
+ # Filenames are listed WITHOUT a directory prefix: they live next to this file
15
+ # in src/torchcodec/_core/. CMake runs from this directory and uses them as-is;
16
+ # Buck prepends the "torchcodec/_core/" path prefix at load time.
17
+ #
18
+ # The lists are intentionally fine-grained building blocks so each build system
19
+ # can compose exactly the targets it needs without changing what gets compiled.
20
+ # The two builds group these differently (e.g. CMake compiles FFMPEGCommon.cpp
21
+ # into the core library while Buck builds it as a separate target), so do not
22
+ # merge the lists.
23
+
24
+ # CPU sources for the core decoder library. Does NOT include FFMPEGCommon.cpp
25
+ # (see ffmpeg_common_sources): the Buck build compiles that into a separate
26
+ # "core_common" target.
27
+ decoder_core_sources = [
28
+ "AVIOContextHolder.cpp",
29
+ "TensorIO.cpp",
30
+ "FilterGraph.cpp",
31
+ "Frame.cpp",
32
+ "DeviceInterface.cpp",
33
+ "CpuDeviceInterface.cpp",
34
+ "CodecParameters.cpp",
35
+ "Demuxer.cpp",
36
+ "PacketDecoder.cpp",
37
+ "AudioCommon.cpp",
38
+ "ColorConverter.cpp",
39
+ "AudioConverter.cpp",
40
+ "SingleStreamDecoder.cpp",
41
+ "Encoder.cpp",
42
+ "ValidationUtils.cpp",
43
+ "Transform.cpp",
44
+ "Metadata.cpp",
45
+ "SwScale.cpp",
46
+ "WavDecoder.cpp",
47
+ "NVDECCacheConfig.cpp",
48
+ "Logging.cpp",
49
+ ]
50
+
51
+ # FFmpeg glue. Part of the core library under CMake; a standalone "core_common"
52
+ # target under Buck.
53
+ ffmpeg_common_sources = [
54
+ "FFMPEGCommon.cpp",
55
+ ]
56
+
57
+ io_sources = [
58
+ "FileIO.cpp",
59
+ ]
60
+
61
+ # CUDA sources, added to the core library only for CUDA-enabled builds.
62
+ decoder_core_cuda_sources = [
63
+ "CudaDeviceInterface.cpp",
64
+ "BetaCudaDeviceInterface.cpp",
65
+ "NVDECCache.cpp",
66
+ "CUDACommon.cpp",
67
+ "NVCUVIDRuntimeLoader.cpp",
68
+ "color_conversion.cpp",
69
+ "color_conversion.cu",
70
+ ]
71
+
72
+ file_like_context_sources = [
73
+ "FileLikeIO.cpp",
74
+ ]
75
+
76
+ # PyTorch custom ops registration.
77
+ custom_ops_sources = [
78
+ "custom_ops.cpp",
79
+ ]
80
+
81
+ image_sources = [
82
+ "DecodeJpeg.cpp",
83
+ "DecodeJpegCuda.cpp",
84
+ "DecodePng.cpp",
85
+ "DecodeWebp.cpp",
86
+ "DecodeGif.cpp",
87
+ "DecodeAvif.cpp",
88
+ "EncodePng.cpp",
89
+ "EncodeJpeg.cpp",
90
+ "EncodeJpegCuda.cpp",
91
+ ]
92
+
93
+ image_ops_sources = [
94
+ "image_custom_ops.cpp",
95
+ ]
96
+
97
+ heic_sources = [
98
+ "DecodeHeic.cpp",
99
+ ]
100
+
101
+ heic_ops_sources = [
102
+ "heic_custom_ops.cpp",
103
+ ]
104
+
105
+ # Vendored giflib (decode-only subset, MIT licensed). Compiled directly from
106
+ # source into the image library, so the GIF decoder needs no external dependency.
107
+ # See giflib/README for the license and local mods.
108
+ giflib_sources = [
109
+ "giflib/dgif_lib.c",
110
+ "giflib/gifalloc.c",
111
+ "giflib/gif_hash.c",
112
+ "giflib/openbsd-reallocarray.c",
113
+ ]
torchcodec/_frame.py ADDED
@@ -0,0 +1,146 @@
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
+ from collections.abc import Iterable, Iterator
10
+ from dataclasses import dataclass
11
+
12
+ from torch import Tensor
13
+
14
+
15
+ def _frame_repr(self):
16
+ # Utility to replace __repr__ method of dataclasses below. This prints the
17
+ # shape of the .data tensor rather than printing the (potentially very long)
18
+ # data tensor itself.
19
+ s = self.__class__.__name__ + ":\n"
20
+ spaces = " "
21
+ for field in dataclasses.fields(self):
22
+ field_name = field.name
23
+ field_val = getattr(self, field_name)
24
+ if field_name == "data":
25
+ field_name = "data (shape)"
26
+ field_val = field_val.shape
27
+ s += f"{spaces}{field_name}: {field_val}\n"
28
+ return s
29
+
30
+
31
+ @dataclass
32
+ class Frame(Iterable):
33
+ """A single video frame with associated metadata."""
34
+
35
+ data: Tensor
36
+ """The frame data as (3-D ``torch.Tensor``)."""
37
+ pts_seconds: float
38
+ """The :term:`pts` of the frame, in seconds (float)."""
39
+ duration_seconds: float
40
+ """The duration of the frame, in seconds (float)."""
41
+
42
+ def __post_init__(self):
43
+ # This is called after __init__() when a Frame is created. We can run
44
+ # input validation checks here.
45
+ if not self.data.ndim == 3:
46
+ raise ValueError(f"data must be 3-dimensional, got {self.data.shape = }")
47
+ self.pts_seconds = float(self.pts_seconds)
48
+ self.duration_seconds = float(self.duration_seconds)
49
+
50
+ def __iter__(self) -> Iterator[Tensor | float]:
51
+ for field in dataclasses.fields(self):
52
+ yield getattr(self, field.name)
53
+
54
+ def __repr__(self):
55
+ return _frame_repr(self)
56
+
57
+
58
+ @dataclass
59
+ class FrameBatch(Iterable):
60
+ """Multiple video frames with associated metadata.
61
+
62
+ The ``data`` tensor is typically 4D for sequences of frames (NHWC or NCHW),
63
+ or 5D for sequences of clips, as returned by the :ref:`samplers
64
+ <sphx_glr_generated_examples_decoding_sampling.py>`. When ``data`` is 4D (resp. 5D)
65
+ the ``pts_seconds`` and ``duration_seconds`` tensors are 1D (resp. 2D).
66
+
67
+ .. note::
68
+ The ``pts_seconds`` and ``duration_seconds`` Tensors are always returned
69
+ on CPU, even if ``data`` is on GPU.
70
+ """
71
+
72
+ data: Tensor
73
+ """The frames data (``torch.Tensor`` of uint8 in [0, 255] or float in [0, 1])."""
74
+ pts_seconds: Tensor
75
+ """The :term:`pts` of the frame, in seconds (``torch.Tensor`` of floats)."""
76
+ duration_seconds: Tensor
77
+ """The duration of the frame, in seconds (``torch.Tensor`` of floats)."""
78
+
79
+ def __post_init__(self):
80
+ # This is called after __init__() when a FrameBatch is created. We can
81
+ # run input validation checks here.
82
+ if self.data.ndim < 3:
83
+ raise ValueError(
84
+ f"data must be at least 3-dimensional, got {self.data.shape = }"
85
+ )
86
+
87
+ leading_dims = self.data.shape[:-3]
88
+ if not (leading_dims == self.pts_seconds.shape == self.duration_seconds.shape):
89
+ raise ValueError(
90
+ "Tried to create a FrameBatch but the leading dimensions of the inputs do not match. "
91
+ f"Got {self.data.shape = } so we expected the shape of pts_seconds and "
92
+ f"duration_seconds to be {leading_dims = }, but got "
93
+ f"{self.pts_seconds.shape = } and {self.duration_seconds.shape = }."
94
+ )
95
+
96
+ def __iter__(self) -> Iterator["FrameBatch"]:
97
+ for data, pts_seconds, duration_seconds in zip(
98
+ self.data, self.pts_seconds, self.duration_seconds
99
+ ):
100
+ yield FrameBatch(
101
+ data=data,
102
+ pts_seconds=pts_seconds,
103
+ duration_seconds=duration_seconds,
104
+ )
105
+
106
+ def __getitem__(self, key) -> "FrameBatch":
107
+ return FrameBatch(
108
+ data=self.data[key],
109
+ pts_seconds=self.pts_seconds[key],
110
+ duration_seconds=self.duration_seconds[key],
111
+ )
112
+
113
+ def __len__(self):
114
+ return len(self.data)
115
+
116
+ def __repr__(self):
117
+ return _frame_repr(self)
118
+
119
+
120
+ @dataclass
121
+ class AudioSamples(Iterable):
122
+ """Audio samples with associated metadata."""
123
+
124
+ data: Tensor
125
+ """The sample data (``torch.Tensor`` of float in [-1, 1], shape is ``(num_channels, num_samples)``)."""
126
+ pts_seconds: float
127
+ """The :term:`pts` of the first sample, in seconds."""
128
+ duration_seconds: float
129
+ """The duration of the samples, in seconds."""
130
+ sample_rate: int
131
+ """The sample rate of the samples, in Hz."""
132
+
133
+ def __post_init__(self):
134
+ # This is called after __init__() when a Frame is created. We can run
135
+ # input validation checks here.
136
+ if not self.data.ndim == 2:
137
+ raise ValueError(f"data must be 2-dimensional, got {self.data.shape = }")
138
+ self.pts_seconds = float(self.pts_seconds)
139
+ self.sample_rate = int(self.sample_rate)
140
+
141
+ def __iter__(self) -> Iterator[Tensor | float]:
142
+ for field in dataclasses.fields(self):
143
+ yield getattr(self, field.name)
144
+
145
+ def __repr__(self):
146
+ return _frame_repr(self)
@@ -0,0 +1,129 @@
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 functools
8
+ import importlib
9
+ import importlib.machinery
10
+ import sys
11
+ import traceback
12
+ from pathlib import Path
13
+
14
+ import torch
15
+
16
+
17
+ # Copy pasted from torchvision
18
+ # https://github.com/pytorch/vision/blob/947ae1dc71867f28021d5bc0ff3a19c249236e2a/torchvision/_internally_replaced_utils.py#L25
19
+ def _get_extension_path(lib_name: str) -> str:
20
+ extension_suffixes = []
21
+ if sys.platform == "linux" or sys.platform.startswith("freebsd"):
22
+ extension_suffixes = importlib.machinery.EXTENSION_SUFFIXES
23
+ elif sys.platform == "darwin":
24
+ extension_suffixes = importlib.machinery.EXTENSION_SUFFIXES + [".dylib"]
25
+ elif sys.platform in ("win32", "cygwin"):
26
+ extension_suffixes = importlib.machinery.EXTENSION_SUFFIXES + [".dll", ".pyd"]
27
+ else:
28
+ raise NotImplementedError(f"{sys.platform = } is not not supported")
29
+ loader_details = (
30
+ importlib.machinery.ExtensionFileLoader,
31
+ extension_suffixes,
32
+ )
33
+
34
+ extfinder = importlib.machinery.FileFinder(
35
+ str(Path(__file__).parent), loader_details
36
+ )
37
+ ext_specs = extfinder.find_spec(lib_name)
38
+ if ext_specs is None:
39
+ raise ImportError(f"No spec found for {lib_name}")
40
+
41
+ if ext_specs.origin is None:
42
+ raise ImportError(f"Existing spec found for {lib_name} does not have an origin")
43
+
44
+ return ext_specs.origin
45
+
46
+
47
+ def load_image_library() -> None:
48
+ """Load the FFmpeg-free image library"""
49
+ image_library_path = _get_extension_path("libtorchcodec_image")
50
+ torch.ops.load_library(image_library_path)
51
+
52
+
53
+ @functools.cache
54
+ def load_heic_library() -> None:
55
+ """Load the HEIC library (libtorchcodec_heic).
56
+
57
+ It's loaded lazily, only when HEIC decoding is requested, never at import:
58
+ because it links libheif, an optional runtime dependency we don't bundle.
59
+ importing torchcodec must not require libheif to be installed.
60
+ """
61
+ torch.ops.load_library(_get_extension_path("libtorchcodec_heic"))
62
+
63
+
64
+ @functools.cache
65
+ def load_core_libraries() -> tuple[int, str]:
66
+ """Load the FFmpeg-dependent shared libraries, memoizing the result.
67
+
68
+ This raises if the libraries cannot be loaded, typically because FFmpeg
69
+ couldn't be found. This is called:
70
+ - at import time (import torchcodec) within a try/except, to determine
71
+ whether FFmpeg is available, and then load the corresponding ops if it is.
72
+ If FFmpeg isn't available, we don't propagate the exception and
73
+ `import torchcodec` still works: we still want to support the image
74
+ decoders, which don't need FFmpeg.
75
+ - at runtime in all FFmpeg-dependent public entry-points like VideoDecoder,
76
+ so that if FFmpeg isn't available the user gets a clear error message.
77
+
78
+ Since this is @functools.cache'd, the libraries are only ever loaded once on
79
+ success. Failures are *not* cached (functools.cache only caches return
80
+ values), so when FFmpeg is missing the load is retried and re-raises on each
81
+ call. That's fine, it only happens on the error path.
82
+
83
+
84
+
85
+ We successively try to load the shared libraries for each version of FFmpeg
86
+ that we support, starting with the highest version and working our way down.
87
+ Once we can load the core and custom-ops libraries for a version of FFmpeg,
88
+ we have succeeded and we stop.
89
+
90
+ We load them via torch.ops.load_library(), which registers the custom ops
91
+ with PyTorch's runtime so they're accessible through torch.ops.
92
+ """
93
+ exceptions = []
94
+ for ffmpeg_major_version in (9, 8, 7, 6, 5, 4):
95
+ core_library_name = f"libtorchcodec_core{ffmpeg_major_version}"
96
+ custom_ops_library_name = f"libtorchcodec_custom_ops{ffmpeg_major_version}"
97
+ try:
98
+ core_library_path = _get_extension_path(core_library_name)
99
+ torch.ops.load_library(core_library_path)
100
+ torch.ops.load_library(_get_extension_path(custom_ops_library_name))
101
+ return (ffmpeg_major_version, core_library_path)
102
+ except Exception:
103
+ # Capture the full traceback for this exception
104
+ exc_traceback = traceback.format_exc()
105
+ exceptions.append((ffmpeg_major_version, exc_traceback))
106
+
107
+ traceback_info = (
108
+ "\n[start of libtorchcodec loading traceback]\n"
109
+ + "\n".join(f"FFmpeg version {v}:\n{tb}" for v, tb in exceptions)
110
+ + "[end of libtorchcodec loading traceback]."
111
+ )
112
+ raise RuntimeError(
113
+ f"""Could not load libtorchcodec. Likely causes:
114
+ 1. FFmpeg is not properly installed in your environment. We support
115
+ versions 4, 5, 6, 7, 8, and 9, and we attempt to load libtorchcodec
116
+ for each of those versions. Errors for versions not installed on
117
+ your system are expected; only the error for your installed FFmpeg
118
+ version is relevant. On Windows, ensure you've installed the
119
+ "full-shared" version which ships DLLs.
120
+ 2. The PyTorch version ({torch.__version__}) is not compatible with
121
+ this version of TorchCodec. Refer to the version compatibility
122
+ table:
123
+ https://github.com/pytorch/torchcodec?tab=readme-ov-file#installing-torchcodec.
124
+ 3. Another runtime dependency; see exceptions below.
125
+
126
+ The following exceptions were raised as we tried to load libtorchcodec:
127
+ """
128
+ f"{traceback_info}"
129
+ )
torchcodec/_logging.py ADDED
@@ -0,0 +1,59 @@
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 enum
8
+ import logging
9
+ from typing import Literal
10
+
11
+ from torchcodec._core.ops import _get_log_level, _set_cpp_log_level
12
+
13
+ _LG = logging.getLogger("torchcodec")
14
+ _handler = logging.StreamHandler()
15
+ _handler.setFormatter(
16
+ logging.Formatter("[torchcodec %(filename)s:%(lineno)d] %(message)s")
17
+ )
18
+ _LG.addHandler(_handler)
19
+
20
+ _OFF_LEVEL = logging.CRITICAL + 1
21
+ _LG.setLevel(_OFF_LEVEL)
22
+
23
+
24
+ # Keep in sync with LogLevel in torchcodec/_core/Logging.h.
25
+ class _LogLevel(enum.Enum):
26
+ OFF = 0
27
+ ALL = 1
28
+
29
+
30
+ def set_log_level(level: Literal["OFF", "ALL"]) -> None:
31
+ """Set the torchcodec log level.
32
+
33
+ Supported levels: "OFF", "ALL".
34
+ """
35
+ level = level.upper()
36
+ try:
37
+ log_level = _LogLevel[level]
38
+ except KeyError as e:
39
+ raise ValueError(
40
+ f"Invalid log level: {level!r}. Supported levels: {[lvl.name for lvl in _LogLevel]}"
41
+ ) from e
42
+ _set_cpp_log_level(log_level.value)
43
+ # Probably not thread-safe, and probably OK still.
44
+ if log_level == _LogLevel.OFF:
45
+ _LG.setLevel(_OFF_LEVEL)
46
+ else:
47
+ _LG.setLevel(logging.DEBUG)
48
+
49
+
50
+ def get_log_level() -> str:
51
+ """Return the current torchcodec log level as a string."""
52
+ level_int = _get_log_level()
53
+ try:
54
+ return _LogLevel(level_int).name
55
+ except ValueError:
56
+ raise RuntimeError(
57
+ f"C++ log level {level_int} has no matching Python level name. "
58
+ "Please report a bug in the TorchCodec repo"
59
+ )
@@ -0,0 +1,50 @@
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 .._core import AudioStreamMetadata, VideoStreamMetadata
8
+ from ._audio_decoder import AudioDecoder # noqa
9
+ from ._blocks import ( # noqa
10
+ AudioCodecParameters,
11
+ AudioConverter,
12
+ AudioPacketDecoder,
13
+ AudioStream,
14
+ AudioStreamHeaderMetadata,
15
+ ColorConverter,
16
+ ContainerMetadata,
17
+ Demuxer,
18
+ DemuxerMetadata,
19
+ FrameIndex,
20
+ get_container_metadata,
21
+ Packet,
22
+ RawAudioSamples,
23
+ RawFrame,
24
+ StreamMetadata,
25
+ VideoCodecParameters,
26
+ VideoPacketDecoder,
27
+ VideoStream,
28
+ VideoStreamHeaderMetadata,
29
+ )
30
+ from ._decoder_utils import ( # noqa
31
+ get_nvdec_cache_capacity,
32
+ set_cuda_backend,
33
+ set_nvdec_cache_capacity,
34
+ )
35
+ from ._image_decoders import ( # noqa
36
+ decode_avif,
37
+ decode_gif,
38
+ decode_heic,
39
+ decode_image,
40
+ decode_jpeg,
41
+ decode_png,
42
+ decode_webp,
43
+ get_image_metadata,
44
+ ImageMetadata,
45
+ ImageReadMode,
46
+ )
47
+ from ._video_decoder import CpuFallbackStatus, VideoDecoder # noqa
48
+ from ._wav_decoder import WavDecoder # noqa
49
+
50
+ SimpleVideoDecoder = VideoDecoder