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,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
+ #include "CUDACommon.h"
8
+ #include "Frame.h"
9
+ #include "StableABICompat.h"
10
+ #include "ValidationUtils.h"
11
+
12
+ namespace facebook::torchcodec {
13
+
14
+ void sync_streams(cudaStream_t running_stream, cudaStream_t waiting_stream) {
15
+ if (running_stream == waiting_stream) {
16
+ return;
17
+ }
18
+
19
+ cudaEvent_t event;
20
+ cudaError_t err = cudaEventCreateWithFlags(&event, cudaEventDisableTiming);
21
+ STD_TORCH_CHECK(
22
+ err == cudaSuccess,
23
+ "cudaEventCreateWithFlags failed: ",
24
+ cudaGetErrorString(err));
25
+
26
+ err = cudaEventRecord(event, running_stream);
27
+ STD_TORCH_CHECK(
28
+ err == cudaSuccess, "cudaEventRecord failed: ", cudaGetErrorString(err));
29
+
30
+ err = cudaStreamWaitEvent(waiting_stream, event, 0);
31
+ STD_TORCH_CHECK(
32
+ err == cudaSuccess,
33
+ "cudaStreamWaitEvent failed: ",
34
+ cudaGetErrorString(err));
35
+
36
+ cudaEventDestroy(event);
37
+ }
38
+
39
+ CudaEvent::~CudaEvent() {
40
+ if (event_ != nullptr) {
41
+ // Destroying an event that hasn't completed yet is fine: CUDA frees it once
42
+ // it does.
43
+ cudaEventDestroy(event_);
44
+ }
45
+ }
46
+
47
+ CudaEvent::CudaEvent(CudaEvent&& other) noexcept
48
+ : event_(other.event_), recorded_on_(other.recorded_on_) {
49
+ other.event_ = nullptr;
50
+ other.recorded_on_ = nullptr;
51
+ }
52
+
53
+ CudaEvent& CudaEvent::operator=(CudaEvent&& other) noexcept {
54
+ if (this != &other) {
55
+ if (event_ != nullptr) {
56
+ cudaEventDestroy(event_);
57
+ }
58
+ event_ = other.event_;
59
+ recorded_on_ = other.recorded_on_;
60
+ other.event_ = nullptr;
61
+ other.recorded_on_ = nullptr;
62
+ }
63
+ return *this;
64
+ }
65
+
66
+ void CudaEvent::record(cudaStream_t running_stream) {
67
+ if (event_ == nullptr) {
68
+ cudaError_t err = cudaEventCreateWithFlags(&event_, cudaEventDisableTiming);
69
+ STD_TORCH_CHECK(
70
+ err == cudaSuccess,
71
+ "cudaEventCreateWithFlags failed: ",
72
+ cudaGetErrorString(err));
73
+ }
74
+ cudaError_t err = cudaEventRecord(event_, running_stream);
75
+ STD_TORCH_CHECK(
76
+ err == cudaSuccess, "cudaEventRecord failed: ", cudaGetErrorString(err));
77
+ recorded_on_ = running_stream;
78
+ }
79
+
80
+ void CudaEvent::make_stream_wait(cudaStream_t waiting_stream) const {
81
+ if (event_ == nullptr || waiting_stream == recorded_on_) {
82
+ return;
83
+ }
84
+ cudaError_t err = cudaStreamWaitEvent(waiting_stream, event_, 0);
85
+ STD_TORCH_CHECK(
86
+ err == cudaSuccess,
87
+ "cudaStreamWaitEvent failed: ",
88
+ cudaGetErrorString(err));
89
+ }
90
+
91
+ void CudaEvent::synchronize() const {
92
+ if (event_ == nullptr) {
93
+ return;
94
+ }
95
+ cudaError_t err = cudaEventSynchronize(event_);
96
+ STD_TORCH_CHECK(
97
+ err == cudaSuccess,
98
+ "cudaEventSynchronize failed: ",
99
+ cudaGetErrorString(err));
100
+ }
101
+
102
+ void initialize_cuda_context_with_pytorch(const StableDevice& device) {
103
+ // It is important for pytorch itself to create the cuda context. If ffmpeg
104
+ // creates the context it may not be compatible with pytorch.
105
+ // This is a dummy tensor to initialize the cuda context.
106
+ torch::stable::Tensor dummy_tensor_for_cuda_initialization =
107
+ torch::stable::empty(
108
+ {1}, kStableUInt8, std::nullopt, StableDevice(device));
109
+ torch::stable::zero_(dummy_tensor_for_cuda_initialization);
110
+ }
111
+
112
+ void validate_pre_allocated_tensor_shape(
113
+ const std::optional<torch::stable::Tensor>& pre_allocated_output_tensor,
114
+ const FrameDims& frame_dims) {
115
+ if (pre_allocated_output_tensor.has_value()) {
116
+ auto shape = pre_allocated_output_tensor.value().sizes();
117
+ STD_TORCH_CHECK(
118
+ (shape.size() == 3) && (shape[0] == frame_dims.height) &&
119
+ (shape[1] == frame_dims.width) && (shape[2] == 3),
120
+ "Expected tensor of shape ",
121
+ frame_dims.height,
122
+ "x",
123
+ frame_dims.width,
124
+ "x3, got ",
125
+ int_array_ref_to_string(shape));
126
+ }
127
+ }
128
+
129
+ } // namespace facebook::torchcodec
@@ -0,0 +1,115 @@
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
+ #pragma once
8
+
9
+ #include <cuda_runtime.h>
10
+ #include <torch/csrc/inductor/aoti_torch/c/shim.h>
11
+ #include <torch/headeronly/util/Exception.h>
12
+
13
+ #include <optional>
14
+
15
+ #include "StableABICompat.h"
16
+
17
+ namespace facebook::torchcodec {
18
+
19
+ struct FrameDims;
20
+
21
+ // Pytorch can only handle up to 128 GPUs.
22
+ // https://github.com/pytorch/pytorch/blob/e30c55ee527b40d67555464b9e402b4b7ce03737/c10/cuda/CUDAMacros.h#L44
23
+ constexpr int MAX_CUDA_GPUS = 128;
24
+
25
+ // NV12 requires even dimensions. This rounds up to the nearest even value.
26
+ inline int round_up_to_even(int value) {
27
+ return (value + 1) & ~1;
28
+ }
29
+
30
+ // Defined inline (rather than in CUDACommon.cpp) so libtorchcodec_image, which
31
+ // does not link the core library, can use it too.
32
+ inline int get_device_index(const StableDevice& device) {
33
+ // PyTorch uses int8_t as its torch::DeviceIndex, but FFmpeg and CUDA
34
+ // libraries use int. So we use int, too.
35
+ int device_index = static_cast<int>(device.index());
36
+ STD_TORCH_CHECK(
37
+ device_index >= -1 && device_index < MAX_CUDA_GPUS,
38
+ "Invalid device index = ",
39
+ device_index);
40
+
41
+ if (device_index == -1) {
42
+ STD_TORCH_CHECK(
43
+ cudaGetDevice(&device_index) == cudaSuccess,
44
+ "Failed to get current CUDA device.");
45
+ }
46
+ return device_index;
47
+ }
48
+
49
+ // Defined inline (rather than in CUDACommon.cpp) so libtorchcodec_image, which
50
+ // does not link the core library, can use it too.
51
+ inline cudaStream_t get_current_cuda_stream(int32_t device_index) {
52
+ // This is the documented and blessed way to get the current CUDA stream with
53
+ // the stable ABI. aoti_torch_get_current_cuda_stream, TORCH_ERROR_CODE_CHECK,
54
+ // and the corresponding torch/csrc/inductor/aoti_torch/c/shim.h header are
55
+ // all safe to use:
56
+ // https://github.com/pytorch/pytorch/blob/7bc8d4b0648e1d364dce0104c3aea2e7e3c1640a/docs/cpp/source/stable.rst?plain=1#L172-L179
57
+ void* stream = nullptr;
58
+ TORCH_ERROR_CODE_CHECK(
59
+ aoti_torch_get_current_cuda_stream(device_index, &stream));
60
+ // Note: no need for checking against nullptr stream, it's a valid default
61
+ // stream value.
62
+ return static_cast<cudaStream_t>(stream);
63
+ }
64
+
65
+ // Make waitingStream wait until all work currently enqueued on runningStream
66
+ // has completed.
67
+ // Prefer a CudaEvent recorded by the producer where you can: this snapshots
68
+ // runningStream at the *waiter's* convenience, so it also waits for anything
69
+ // the producer enqueued after the work the waiter actually cares about.
70
+ void sync_streams(cudaStream_t running_stream, cudaStream_t waiting_stream);
71
+
72
+ // A cudaEvent_t with a destructor. The underlying event is created on the first
73
+ // record() and reused by subsequent ones, always with timing disabled: we only
74
+ // ever use events for ordering, and the timing-enabled flavour is the more
75
+ // expensive one.
76
+ //
77
+ // An event marks a *point* in a stream, so it expresses "wait for the work that
78
+ // was enqueued up to here" and nothing more. Producers should record() as soon
79
+ // as the work they're advertising is enqueued, and consumers call
80
+ // make_stream_wait() on that.
81
+ class CudaEvent {
82
+ public:
83
+ CudaEvent() = default;
84
+ ~CudaEvent();
85
+
86
+ CudaEvent(CudaEvent&& other) noexcept;
87
+ CudaEvent& operator=(CudaEvent&& other) noexcept;
88
+ CudaEvent(const CudaEvent&) = delete;
89
+ CudaEvent& operator=(const CudaEvent&) = delete;
90
+
91
+ // Mark the current point in `running_stream`. Work enqueued on it after this
92
+ // call is *not* covered.
93
+ void record(cudaStream_t running_stream);
94
+
95
+ // Order `waiting_stream` after the work marked by the last record(). Doesn't
96
+ // block the host. No-op if record() was never called, or if `waiting_stream`
97
+ // is the stream that was recorded on.
98
+ void make_stream_wait(cudaStream_t waiting_stream) const;
99
+
100
+ // Block the host until the marked work has completed. No-op if record() was
101
+ // never called.
102
+ void synchronize() const;
103
+
104
+ private:
105
+ cudaEvent_t event_ = nullptr;
106
+ cudaStream_t recorded_on_ = nullptr;
107
+ };
108
+
109
+ void initialize_cuda_context_with_pytorch(const StableDevice& device);
110
+
111
+ void validate_pre_allocated_tensor_shape(
112
+ const std::optional<torch::stable::Tensor>& pre_allocated_output_tensor,
113
+ const FrameDims& frame_dims);
114
+
115
+ } // namespace facebook::torchcodec
@@ -0,0 +1,126 @@
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
+ #pragma once
8
+
9
+ #include <memory>
10
+ #include <mutex>
11
+ #include "StableABICompat.h"
12
+
13
+ namespace facebook::torchcodec {
14
+
15
+ // This header defines simple cache class primitives to store reusable objects
16
+ // across TorchCodec stream instances. Intended usage is to store hardware
17
+ // contexts creation of which is expensive. The cache mechanism is as follows:
18
+ // 1. 'PerGpuCache' provides a dynamic cache with the specified maximum capacity
19
+ // for the given number of GPUs.
20
+ // 2. When stream object (e.g. SingleStreamDecoder) is destoyed cachable object
21
+ // must be released to the cache. Cache will accept the object if it is not
22
+ // full.
23
+ // 3. When stream object (e.g. SingleStreamDecoder) is created cachable object
24
+ // must be first queried from the cache. If the cache is empty then new
25
+ // object must be created.
26
+
27
+ template <typename T, typename D = std::default_delete<T>>
28
+ class Cache {
29
+ public:
30
+ using element_type = std::unique_ptr<T, D>;
31
+
32
+ explicit Cache(int capacity) : capacity_(capacity) {}
33
+
34
+ // Adds an object to the cache if the cache has capacity. Returns true
35
+ // if object was added and false otherwise.
36
+ bool add_if_cache_has_capacity(element_type&& obj);
37
+
38
+ // Returns an object from the cache. Cache does not hold a reference
39
+ // to the object after this call.
40
+ element_type get();
41
+
42
+ private:
43
+ int capacity_;
44
+ std::mutex mutex_;
45
+ std::vector<element_type> cache_;
46
+ };
47
+
48
+ template <typename T, typename D>
49
+ bool Cache<T, D>::add_if_cache_has_capacity(element_type&& obj) {
50
+ std::scoped_lock lock(mutex_);
51
+ if (capacity_ >= 0 && cache_.size() >= static_cast<size_t>(capacity_)) {
52
+ return false;
53
+ }
54
+ cache_.push_back(std::move(obj));
55
+ return true;
56
+ }
57
+
58
+ template <typename T, typename D>
59
+ typename Cache<T, D>::element_type Cache<T, D>::get() {
60
+ std::scoped_lock lock(mutex_);
61
+ if (cache_.empty()) {
62
+ return nullptr;
63
+ }
64
+
65
+ element_type obj = std::move(cache_.back());
66
+ cache_.pop_back();
67
+ return obj;
68
+ }
69
+
70
+ template <typename T, typename D = std::default_delete<T>>
71
+ class PerGpuCache {
72
+ public:
73
+ using element_type = typename Cache<T, D>::element_type;
74
+
75
+ // Initializes 'maxGpus' number of caches. Each cache can hold no
76
+ // more than 'capacity' items. If 'capacity' <0 cache size is unlimited.
77
+ PerGpuCache(int max_gpus, int capacity) {
78
+ STD_TORCH_CHECK(max_gpus > 0, "maxGpus for PerGpuCache must be >0");
79
+ for (int i = 0; i < max_gpus; ++i) {
80
+ cache_.emplace_back(std::make_unique<Cache<T, D>>(capacity));
81
+ }
82
+ }
83
+
84
+ // Adds an object to the specified device cache if the cache has
85
+ // capacity. Returns true if object was added and false otherwise.
86
+ bool add_if_cache_has_capacity(
87
+ const StableDevice& device,
88
+ element_type&& obj);
89
+
90
+ // Returns an object from the cache of the specified device. Cache
91
+ // does not hold a reference to the object after this call.
92
+ element_type get(const StableDevice& device);
93
+
94
+ private:
95
+ // 'Cache' class implementation contains mutex which makes it non-movable
96
+ // and non-copyable, so we need to wrap it in std::unique_ptr.
97
+ std::vector<std::unique_ptr<Cache<T, D>>> cache_;
98
+ };
99
+
100
+ // Forward declaration of get_device_index which exists in CUDACommon.h
101
+ // This avoids circular dependency between Cache.h and CUDACommon.cpp which also
102
+ // needs to include Cache.h
103
+ int get_device_index(const StableDevice& device);
104
+
105
+ template <typename T, typename D>
106
+ bool PerGpuCache<T, D>::add_if_cache_has_capacity(
107
+ const StableDevice& device,
108
+ element_type&& obj) {
109
+ int device_index = get_device_index(device);
110
+ STD_TORCH_CHECK(
111
+ static_cast<size_t>(device_index) < cache_.size(),
112
+ "Device index out of range");
113
+ return cache_[device_index]->add_if_cache_has_capacity(std::move(obj));
114
+ }
115
+
116
+ template <typename T, typename D>
117
+ typename PerGpuCache<T, D>::element_type PerGpuCache<T, D>::get(
118
+ const StableDevice& device) {
119
+ int device_index = get_device_index(device);
120
+ STD_TORCH_CHECK(
121
+ static_cast<size_t>(device_index) < cache_.size(),
122
+ "Device index out of range");
123
+ return cache_[device_index]->get();
124
+ }
125
+
126
+ } // namespace facebook::torchcodec
@@ -0,0 +1,98 @@
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
+ #include "CodecParameters.h"
8
+
9
+ #include <algorithm>
10
+ #include <cstring>
11
+
12
+ namespace facebook::torchcodec {
13
+
14
+ CodecParameters::CodecParameters() : codecpar(avcodec_parameters_alloc()) {
15
+ STD_TORCH_CHECK(codecpar != nullptr, "Failed to allocate AVCodecParameters.");
16
+ }
17
+
18
+ CodecParameters::CodecParameters(
19
+ const AVStream& av_stream,
20
+ const AVInputFormat* container_format)
21
+ : codecpar(avcodec_parameters_alloc()),
22
+ time_base(av_stream.time_base),
23
+ r_frame_rate(av_stream.r_frame_rate),
24
+ container_format(container_format) {
25
+ STD_TORCH_CHECK(codecpar != nullptr, "Failed to allocate AVCodecParameters.");
26
+ int status = avcodec_parameters_copy(codecpar.get(), av_stream.codecpar);
27
+ STD_TORCH_CHECK(
28
+ status >= 0,
29
+ "Failed to copy the codec parameters: ",
30
+ get_ffmpeg_error_string_from_error_code(status));
31
+ // From FFmpeg 6.1, this reads the display matrix from the coded side data,
32
+ // which we just copied into codecpar. Before that, it reads it from the
33
+ // AVStream, and display_matrix is the only place where we keep it: see
34
+ // get_stream_side_data().
35
+ if (const int32_t* matrix = get_display_matrix_from_stream(&av_stream)) {
36
+ display_matrix.emplace();
37
+ std::copy(matrix, matrix + display_matrix->size(), display_matrix->begin());
38
+ }
39
+ }
40
+
41
+ std::optional<double> CodecParameters::get_rotation() const {
42
+ return get_rotation_from_display_matrix(
43
+ display_matrix.has_value() ? display_matrix->data() : nullptr);
44
+ }
45
+
46
+ std::vector<AVPacketSideData> CodecParameters::get_stream_side_data() const {
47
+ std::vector<AVPacketSideData> entries;
48
+ #if FFMPEG_HAS_CODED_SIDE_DATA
49
+ // The display matrix, if any, is one of them.
50
+ for (int i = 0; i < codecpar->nb_coded_side_data; ++i) {
51
+ entries.push_back(codecpar->coded_side_data[i]);
52
+ }
53
+ #else
54
+ // AVCodecParameters has no side data before FFmpeg 6.1: it was on the
55
+ // AVStream, and the display matrix is the only one we keep.
56
+ if (display_matrix.has_value()) {
57
+ AVPacketSideData entry = {};
58
+ entry.data = reinterpret_cast<uint8_t*>(
59
+ const_cast<int32_t*>(display_matrix->data()));
60
+ entry.size = sizeof(*display_matrix);
61
+ entry.type = AV_PKT_DATA_DISPLAYMATRIX;
62
+ entries.push_back(entry);
63
+ }
64
+ #endif
65
+ return entries;
66
+ }
67
+
68
+ void CodecParameters::add_stream_side_data(
69
+ AVPacketSideDataType type,
70
+ const uint8_t* data,
71
+ size_t size) {
72
+ if (type == AV_PKT_DATA_DISPLAYMATRIX) {
73
+ STD_TORCH_CHECK(
74
+ size == sizeof(std::array<int32_t, 9>),
75
+ "The display matrix must be 36 bytes, got ",
76
+ size,
77
+ ".");
78
+ display_matrix.emplace();
79
+ std::memcpy(display_matrix->data(), data, size);
80
+ }
81
+ #if FFMPEG_HAS_CODED_SIDE_DATA
82
+ AVPacketSideData* entry = av_packet_side_data_new(
83
+ &codecpar->coded_side_data, &codecpar->nb_coded_side_data, type, size, 0);
84
+ STD_TORCH_CHECK(entry != nullptr, "Failed to allocate coded side data.");
85
+ std::memcpy(entry->data, data, size);
86
+ #else
87
+ // AVCodecParameters has no side data before FFmpeg 6.1, and the display
88
+ // matrix is the only one we keep, in display_matrix.
89
+ STD_TORCH_CHECK(
90
+ type == AV_PKT_DATA_DISPLAYMATRIX,
91
+ "Coded side data other than the display matrix requires FFmpeg 6.1 or "
92
+ "above, got ",
93
+ av_packet_side_data_name(type),
94
+ ".");
95
+ #endif
96
+ }
97
+
98
+ } // namespace facebook::torchcodec
@@ -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
+ #pragma once
8
+
9
+ #include <array>
10
+ #include <optional>
11
+ #include <vector>
12
+
13
+ #include "FFMPEGCommon.h"
14
+
15
+ namespace facebook::torchcodec {
16
+
17
+ // What a decoder is built from: a stream's AVCodecParameters, plus the
18
+ // properties of the stream and of its container that aren't in
19
+ // AVCodecParameters.
20
+ struct CodecParameters {
21
+ // FFmpeg's default values, for a stream that wasn't demuxed by us.
22
+ CodecParameters();
23
+
24
+ explicit CodecParameters(
25
+ const AVStream& av_stream,
26
+ const AVInputFormat* container_format);
27
+
28
+ // Degrees counter-clockwise needed to make the frames upright, from the
29
+ // display matrix.
30
+ std::optional<double> get_rotation() const;
31
+
32
+ // The stream's side data, pointing into this object. From FFmpeg 6.1, that's
33
+ // codecpar->coded_side_data. Before, it's only the display matrix, which was
34
+ // on the AVStream: it's the only one of the AVStream's side data that we
35
+ // keep.
36
+ std::vector<AVPacketSideData> get_stream_side_data() const;
37
+
38
+ // The inverse of get_stream_side_data(): adds one entry of the stream's side
39
+ // data, copying `data`.
40
+ void add_stream_side_data(
41
+ AVPacketSideDataType type,
42
+ const uint8_t* data,
43
+ size_t size);
44
+
45
+ UniqueAVCodecParameters codecpar;
46
+ AVRational time_base = {};
47
+ // libavformat's guess at the stream's frame rate.
48
+ AVRational r_frame_rate = {};
49
+ // The single source of truth for the display matrix: read it from here, not
50
+ // from codecpar. It's filled from codecpar->coded_side_data from FFmpeg 6.1,
51
+ // and from the AVStream's side data before, when AVCodecParameters had no
52
+ // side data.
53
+ std::optional<std::array<int32_t, 9>> display_matrix;
54
+ // The format of the container the stream was demuxed from. Statically
55
+ // allocated by FFmpeg.
56
+ const AVInputFormat* container_format = nullptr;
57
+ };
58
+
59
+ } // namespace facebook::torchcodec
@@ -0,0 +1,92 @@
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
+ #include "ColorConverter.h"
8
+
9
+ #include <optional>
10
+ #include <vector>
11
+
12
+ #include "Frame.h"
13
+ #include "StreamOptions.h"
14
+ #include "Transform.h"
15
+
16
+ namespace facebook::torchcodec {
17
+
18
+ namespace {
19
+ // Only ever used to name a device in the error message below.
20
+ std::string printable(const StableDevice& device) {
21
+ std::string name = device_type_name(device.type());
22
+ if (device.type() != kStableCPU && device.index() >= 0) {
23
+ name += ":" + std::to_string(device.index());
24
+ }
25
+ return name;
26
+ }
27
+ } // namespace
28
+
29
+ ColorConverter::ColorConverter(
30
+ const StableDevice& device,
31
+ OutputDtypeConfig output_dtype_config)
32
+ : device_(device), output_dtype_config_(output_dtype_config) {
33
+ device_interface_ = create_device_interface(device);
34
+ STD_TORCH_CHECK(
35
+ device_interface_ != nullptr,
36
+ "Failed to create device interface. This should never happen, please report.");
37
+ device_ = device_interface_->device(); // resolved, so we don't have to
38
+ }
39
+
40
+ void ColorConverter::maybe_initialize_interface(OutputDtype output_dtype) {
41
+ // Interface initialization is done per-frame, not in the constructor: with
42
+ // AUTO, the desired output dtype is only known once we see a frame, and it
43
+ // can differ from one frame to the next.
44
+ if (initialized_output_dtype_.has_value() &&
45
+ *initialized_output_dtype_ == output_dtype) {
46
+ return;
47
+ }
48
+
49
+ VideoStreamOptions options;
50
+ options.output_dtype = output_dtype;
51
+ options.device = device_;
52
+
53
+ std::vector<std::unique_ptr<Transform>> no_transforms;
54
+ device_interface_->initialize_color_conversion(
55
+ options, no_transforms, /*resized_output_dims=*/std::nullopt);
56
+ initialized_output_dtype_ = output_dtype;
57
+ }
58
+
59
+ torch::stable::Tensor ColorConverter::convert(
60
+ const AVFrame& av_frame,
61
+ const StableDevice& frame_device) {
62
+ // We explicitly pass the frame_device so that we can run the check below
63
+ // (which is very important). Alternatively we could infer the device from the
64
+ // AVFrame based on its storage attached data - we choose to resolve that
65
+ // logic in Python for now.
66
+ STD_TORCH_CHECK(
67
+ frame_device == device_,
68
+ "This ColorConverter is on ",
69
+ printable(device_),
70
+ " but the frame's samples are on ",
71
+ printable(frame_device),
72
+ ". A ColorConverter only converts frames that are already on its own "
73
+ "device: create one per device, or move the RGB output afterwards.");
74
+
75
+ OutputDtype output_dtype = resolve_output_dtype(
76
+ output_dtype_config_, static_cast<AVPixelFormat>(av_frame.format));
77
+ maybe_initialize_interface(output_dtype);
78
+
79
+ FrameOutput frame_output;
80
+ device_interface_->convert_av_frame_to_frame_output(
81
+ av_frame, frame_output, std::nullopt);
82
+
83
+ // TODO_API_BREAKDOWN PERF P2: on CPU this is a lot slower than the filter
84
+ // graph's transpose.
85
+ frame_output.data = rotate_hwc_tensor(
86
+ frame_output.data,
87
+ rotation_from_degrees(get_rotation_from_frame(av_frame)));
88
+
89
+ return convert_to_output_dtype(frame_output.data, output_dtype);
90
+ }
91
+
92
+ } // namespace facebook::torchcodec
@@ -0,0 +1,40 @@
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
+ #pragma once
8
+
9
+ #include <memory>
10
+ #include <optional>
11
+ #include <string>
12
+ #include <string_view>
13
+
14
+ #include "DeviceInterface.h"
15
+ #include "FFMPEGCommon.h"
16
+ #include "StableABICompat.h"
17
+ #include "StreamOptions.h"
18
+
19
+ namespace facebook::torchcodec {
20
+
21
+ class FORCE_PUBLIC_VISIBILITY ColorConverter {
22
+ public:
23
+ explicit ColorConverter(
24
+ const StableDevice& device = StableDevice(kStableCPU),
25
+ OutputDtypeConfig output_dtype_config = OutputDtypeConfig::UINT8);
26
+
27
+ torch::stable::Tensor convert(
28
+ const AVFrame& av_frame,
29
+ const StableDevice& frame_device);
30
+
31
+ private:
32
+ void maybe_initialize_interface(OutputDtype output_dtype);
33
+
34
+ std::unique_ptr<DeviceInterface> device_interface_;
35
+ StableDevice device_;
36
+ OutputDtypeConfig output_dtype_config_;
37
+ std::optional<OutputDtype> initialized_output_dtype_;
38
+ };
39
+
40
+ } // namespace facebook::torchcodec