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,153 @@
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 "DeviceInterface.h"
10
+ #include "FFMPEGCommon.h"
11
+ #include "FilterGraph.h"
12
+ #include "SwScale.h"
13
+
14
+ namespace facebook::torchcodec {
15
+
16
+ class CpuDeviceInterface : public DeviceInterface {
17
+ public:
18
+ CpuDeviceInterface(const StableDevice& device);
19
+
20
+ virtual ~CpuDeviceInterface() {}
21
+
22
+ std::optional<const AVCodec*> find_codec(
23
+ [[maybe_unused]] const AVCodecID& codec_id,
24
+ [[maybe_unused]] bool is_decoder = true) override {
25
+ return std::nullopt;
26
+ }
27
+
28
+ virtual void initialize(const SharedAVCodecContext& codec_context) override;
29
+
30
+ using DeviceInterface::initialize_video_decoding;
31
+ virtual void initialize_video_decoding(
32
+ const CodecParameters& codec_parameters,
33
+ const VideoStreamOptions& video_stream_options) override;
34
+
35
+ virtual void initialize_color_conversion(
36
+ const VideoStreamOptions& video_stream_options,
37
+ const std::vector<std::unique_ptr<Transform>>& transforms,
38
+ const std::optional<FrameDims>& resized_output_dims) override;
39
+
40
+ virtual void initialize_audio(
41
+ const AudioStreamOptions& audio_stream_options,
42
+ double stream_start_seconds = 0.0) override;
43
+
44
+ virtual std::optional<torch::stable::Tensor> maybe_flush_audio_buffers()
45
+ override;
46
+
47
+ void flush() override;
48
+
49
+ void convert_av_frame_to_frame_output(
50
+ const AVFrame& av_frame,
51
+ FrameOutput& frame_output,
52
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor)
53
+ override;
54
+
55
+ UniqueAVFrame convert_tensor_to_av_frame_for_encoding(
56
+ const torch::stable::Tensor& tensor,
57
+ int frame_index,
58
+ AVCodecContext* codec_context) override;
59
+
60
+ AVPixelFormat get_encoding_pixel_format(
61
+ const AVCodec& av_codec,
62
+ const std::optional<std::string>& user_pixel_format) const override;
63
+
64
+ std::string get_details() override;
65
+
66
+ private:
67
+ void convert_audio_av_frame_to_frame_output(
68
+ const AVFrame& src_av_frame,
69
+ FrameOutput& frame_output);
70
+
71
+ void convert_video_av_frame_to_frame_output(
72
+ const AVFrame& av_frame,
73
+ FrameOutput& frame_output,
74
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor);
75
+
76
+ torch::stable::Tensor convert_av_frame_to_tensor_using_filter_graph(
77
+ const AVFrame& av_frame,
78
+ const FrameDims& output_dims);
79
+
80
+ ColorConversionLibrary get_color_conversion_library(
81
+ const FrameDims& input_dims,
82
+ const FrameDims& output_dims) const;
83
+
84
+ VideoStreamOptions video_stream_options_;
85
+ // Default used when color conversion runs standalone (no stream to derive it
86
+ // from, e.g. the ColorConverter block API). initialize_video_decoding()
87
+ // overrides it from the stream when there is one. Its value doesn't matter on
88
+ // color-conversion-only mode, but filtergraph still expects it.
89
+ AVRational time_base_ = {1, AV_TIME_BASE};
90
+ AVPixelFormat output_pixel_format_;
91
+
92
+ // If the resized output dimensions are present, then we always use those as
93
+ // the output frame's dimensions. If they are not present, then we use the
94
+ // dimensions of the raw decoded frame. Note that we do not know the
95
+ // dimensions of the raw decoded frame until very late; we learn it in
96
+ // convertAVFrameToFrameOutput(). Deciding the final output frame's actual
97
+ // dimensions late allows us to handle video streams with variable
98
+ // resolutions.
99
+ std::optional<FrameDims> resized_output_dims_;
100
+
101
+ // Color-conversion objects. Only one of filterGraph_ and swScale_ should
102
+ // be non-null. Which one we use is determined dynamically in
103
+ // getColorConversionLibrary() each time we decode a frame.
104
+ //
105
+ // Creating both filterGraph_ and swScale_ is relatively expensive, so we
106
+ // reuse them across frames. However, it is possible that subsequent frames
107
+ // are different enough (change in dimensions) that we can't reuse the color
108
+ // conversion object. We store the relevant frame config from the frame used
109
+ // to create the object last time. We always compare the current frame's info
110
+ // against the previous one to determine if we need to recreate the color
111
+ // conversion object.
112
+ std::unique_ptr<FilterGraph> filter_graph_;
113
+ FiltersConfig prev_filters_config_;
114
+ std::unique_ptr<SwScale> sw_scale_;
115
+
116
+ // Cached swscale context for encoding (tensor -> AVFrame pixel format
117
+ // conversion).
118
+ UniqueSwsContext encoding_sws_context_;
119
+
120
+ // We pass these filters to FFmpeg's filtergraph API. It is a simple pipeline
121
+ // of what FFmpeg calls "filters" to apply to decoded frames before returning
122
+ // them. In the PyTorch ecosystem, we call these "transforms". During
123
+ // initialization, we convert the user-supplied transforms into this string of
124
+ // filters.
125
+ //
126
+ // Note that if there are no user-supplied transforms, then the default filter
127
+ // we use is the copy filter, which is just an identity: it emits the output
128
+ // frame unchanged. We supply such a filter because we can't supply just the
129
+ // empty-string; we must supply SOME filter.
130
+ //
131
+ // See also [Tranform and Format Conversion Order] for more on filters.
132
+ std::string filters_ = "copy";
133
+
134
+ // Values set during initialization and referred to in
135
+ // getColorConversionLibrary().
136
+ bool are_transforms_sw_scale_compatible_;
137
+ bool user_requested_sw_scale_;
138
+
139
+ // The flags we supply to the resize swscale context. The flags control the
140
+ // resizing algorithm. We default to bilinear. Users can override this with a
141
+ // ResizeTransform that specifies a different interpolation mode.
142
+ int sws_flags_ = SWS_BILINEAR;
143
+
144
+ bool initialized_ = false;
145
+
146
+ // Audio-specific members
147
+ AudioStreamOptions audio_stream_options_;
148
+ UniqueSwrContext swr_context_;
149
+
150
+ double audio_stream_start_seconds_ = 0.0;
151
+ };
152
+
153
+ } // namespace facebook::torchcodec
@@ -0,0 +1,519 @@
1
+ #include <cuda_runtime.h>
2
+ #include <mutex>
3
+
4
+ #include "Cache.h"
5
+ #include "CudaDeviceInterface.h"
6
+ #include "FFMPEGCommon.h"
7
+ #include "StableABICompat.h"
8
+ #include "ValidationUtils.h"
9
+
10
+ extern "C" {
11
+ #include <libavutil/hwcontext_cuda.h>
12
+ #include <libavutil/pixdesc.h>
13
+ }
14
+
15
+ namespace facebook::torchcodec {
16
+ namespace {
17
+
18
+ static bool g_cuda = register_device_interface(
19
+ DeviceInterfaceKey(kStableCUDA, /*variant=*/"ffmpeg"),
20
+ [](const StableDevice& device) { return new CudaDeviceInterface(device); });
21
+
22
+ // We reuse cuda contexts across VideoDeoder instances. This is because
23
+ // creating a cuda context is expensive. The cache mechanism is as follows:
24
+ // 1. There is a cache of size MAX_CONTEXTS_PER_GPU_IN_CACHE cuda contexts for
25
+ // each GPU.
26
+ // 2. When we destroy a SingleStreamDecoder instance we release the cuda context
27
+ // to
28
+ // the cache if the cache is not full.
29
+ // 3. When we create a SingleStreamDecoder instance we try to get a cuda context
30
+ // from
31
+ // the cache. If the cache is empty we create a new cuda context.
32
+
33
+ // Set to -1 to have an infinitely sized cache. Set it to 0 to disable caching.
34
+ // Set to a positive number to have a cache of that size.
35
+ const int MAX_CONTEXTS_PER_GPU_IN_CACHE = -1;
36
+ PerGpuCache<AVBufferRef, Deleterp<AVBufferRef, void, av_buffer_unref>>
37
+ g_cached_hw_device_ctxs(MAX_CUDA_GPUS, MAX_CONTEXTS_PER_GPU_IN_CACHE);
38
+
39
+ int get_flags_av_hardware_device_context_create() {
40
+ // 58.26.100 introduced the concept of reusing the existing cuda context
41
+ // which is much faster and lower memory than creating a new cuda context.
42
+ #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(58, 26, 100)
43
+ return AV_CUDA_USE_CURRENT_CONTEXT;
44
+ #else
45
+ return 0;
46
+ #endif
47
+ }
48
+
49
+ UniqueAVBufferRef get_hardware_device_context(const StableDevice& device) {
50
+ enum AVHWDeviceType type = av_hwdevice_find_type_by_name("cuda");
51
+ STD_TORCH_CHECK(type != AV_HWDEVICE_TYPE_NONE, "Failed to find cuda device");
52
+ int device_index = get_device_index(device);
53
+
54
+ UniqueAVBufferRef hardware_device_ctx = g_cached_hw_device_ctxs.get(device);
55
+ if (hardware_device_ctx) {
56
+ return hardware_device_ctx;
57
+ }
58
+
59
+ // Create hardware device context
60
+ StableDeviceGuard device_guard(device.index());
61
+ // We set the device because we may be called from a different thread than
62
+ // the one that initialized the cuda context.
63
+ STD_TORCH_CHECK(
64
+ cudaSetDevice(device_index) == cudaSuccess, "Failed to set CUDA device");
65
+ AVBufferRef* hardware_device_ctx_raw = nullptr;
66
+ std::string device_ordinal = std::to_string(device_index);
67
+
68
+ int err = av_hwdevice_ctx_create(
69
+ &hardware_device_ctx_raw,
70
+ type,
71
+ device_ordinal.c_str(),
72
+ nullptr,
73
+ get_flags_av_hardware_device_context_create());
74
+
75
+ if (err < 0) {
76
+ /* clang-format off */
77
+ STD_TORCH_CHECK(
78
+ false,
79
+ "Failed to create specified HW device. This typically happens when ",
80
+ "your installed FFmpeg doesn't support CUDA (see ",
81
+ "https://github.com/pytorch/torchcodec#installing-cuda-enabled-torchcodec",
82
+ "). FFmpeg error: ", get_ffmpeg_error_string_from_error_code(err));
83
+ /* clang-format on */
84
+ }
85
+
86
+ return UniqueAVBufferRef(hardware_device_ctx_raw);
87
+ }
88
+
89
+ } // namespace
90
+
91
+ CudaDeviceInterface::CudaDeviceInterface(const StableDevice& device)
92
+ : DeviceInterface(device) {
93
+ STD_TORCH_CHECK(g_cuda, "CudaDeviceInterface was not registered!");
94
+ STD_TORCH_CHECK(
95
+ device_.type() == kStableCUDA, "Unsupported device: must be CUDA");
96
+
97
+ // Resolve unspecified device index (-1) to the actual current CUDA device.
98
+ device_.set_index(get_device_index(device_));
99
+
100
+ initialize_cuda_context_with_pytorch(device_);
101
+
102
+ hardware_device_ctx_ = get_hardware_device_context(device_);
103
+ }
104
+
105
+ CudaDeviceInterface::~CudaDeviceInterface() {
106
+ if (hardware_device_ctx_) {
107
+ g_cached_hw_device_ctxs.add_if_cache_has_capacity(
108
+ device_, std::move(hardware_device_ctx_));
109
+ }
110
+ }
111
+
112
+ void CudaDeviceInterface::initialize(
113
+ const SharedAVCodecContext& codec_context) {
114
+ codec_context_ = codec_context;
115
+ }
116
+
117
+ void CudaDeviceInterface::initialize_video_decoding(
118
+ const CodecParameters& codec_parameters,
119
+ [[maybe_unused]] const VideoStreamOptions& video_stream_options) {
120
+ time_base_ = codec_parameters.time_base;
121
+
122
+ cpu_interface_ = create_device_interface(kStableCPU);
123
+ STD_TORCH_CHECK(
124
+ cpu_interface_ != nullptr, "Failed to create CPU device interface");
125
+ cpu_interface_->initialize(codec_context_);
126
+ cpu_interface_->initialize_video_decoding(
127
+ codec_parameters, VideoStreamOptions());
128
+ cpu_interface_->initialize_color_conversion(
129
+ VideoStreamOptions(), {}, /*resizedOutputDims=*/std::nullopt);
130
+ }
131
+
132
+ void CudaDeviceInterface::initialize_color_conversion(
133
+ const VideoStreamOptions& video_stream_options,
134
+ [[maybe_unused]] const std::vector<std::unique_ptr<Transform>>& transforms,
135
+ [[maybe_unused]] const std::optional<FrameDims>& resized_output_dims) {
136
+ video_stream_options_ = video_stream_options;
137
+ }
138
+
139
+ void CudaDeviceInterface::register_hardware_device_with_codec(
140
+ AVCodecContext* codec_context) {
141
+ STD_TORCH_CHECK(
142
+ hardware_device_ctx_, "Hardware device context has not been initialized");
143
+ STD_TORCH_CHECK(codec_context != nullptr, "codecContext is null");
144
+ codec_context->hw_device_ctx = av_buffer_ref(hardware_device_ctx_.get());
145
+ }
146
+
147
+ UniqueAVFrame CudaDeviceInterface::maybe_convert_av_frame_to_nv12_or_rgb24(
148
+ const AVFrame& av_frame) {
149
+ // We need FFmpeg filters to handle those conversion cases which are not
150
+ // directly implemented in CUDA or CPU device interface (in case of a
151
+ // fallback).
152
+
153
+ // Input frame is on CPU, we will just pass it to CPU device interface, so
154
+ // skipping filters context as CPU device interface will handle everything for
155
+ // us.
156
+ if (av_frame.format != AV_PIX_FMT_CUDA) {
157
+ return UniqueAVFrame{};
158
+ }
159
+
160
+ auto hw_frames_ctx =
161
+ reinterpret_cast<AVHWFramesContext*>(av_frame.hw_frames_ctx->data);
162
+ STD_TORCH_CHECK(
163
+ hw_frames_ctx != nullptr,
164
+ "The AVFrame does not have a hw_frames_ctx. "
165
+ "That's unexpected, please report this to the TorchCodec repo.");
166
+
167
+ AVPixelFormat actual_format = hw_frames_ctx->sw_format;
168
+
169
+ // If the frame is already in NV12 format, we don't need to do anything.
170
+ if (actual_format == AV_PIX_FMT_NV12) {
171
+ return UniqueAVFrame{};
172
+ }
173
+
174
+ AVPixelFormat output_format;
175
+ std::stringstream filters;
176
+
177
+ unsigned version_int = avfilter_version();
178
+ if (version_int < AV_VERSION_INT(8, 0, 103)) {
179
+ // Color conversion support ('format=' option) was added to scale_cuda from
180
+ // n5.0. With the earlier version of ffmpeg we have no choice but use CPU
181
+ // filters. See:
182
+ // https://github.com/FFmpeg/FFmpeg/commit/62dc5df941f5e196164c151691e4274195523e95
183
+ output_format = AV_PIX_FMT_RGB24;
184
+
185
+ auto actual_format_name = av_get_pix_fmt_name(actual_format);
186
+ STD_TORCH_CHECK(
187
+ actual_format_name != nullptr,
188
+ "The actual format of a frame is unknown to FFmpeg. "
189
+ "That's unexpected, please report this to the TorchCodec repo.");
190
+
191
+ filters << "hwdownload,format=" << actual_format_name;
192
+ } else {
193
+ // Actual output color format will be set via filter options
194
+ output_format = AV_PIX_FMT_CUDA;
195
+
196
+ filters << "scale_cuda=format=nv12:interp_algo=bilinear";
197
+ }
198
+
199
+ enum AVPixelFormat frame_format =
200
+ static_cast<enum AVPixelFormat>(av_frame.format);
201
+
202
+ auto new_config = std::make_unique<FiltersConfig>(
203
+ av_frame.width,
204
+ av_frame.height,
205
+ frame_format,
206
+ av_frame.sample_aspect_ratio,
207
+ av_frame.width,
208
+ av_frame.height,
209
+ output_format,
210
+ filters.str(),
211
+ time_base_,
212
+ av_buffer_ref(av_frame.hw_frames_ctx));
213
+
214
+ if (!nv12_conversion_ || *nv12_conversion_config_ != *new_config) {
215
+ nv12_conversion_ =
216
+ std::make_unique<FilterGraph>(*new_config, video_stream_options_);
217
+ nv12_conversion_config_ = std::move(new_config);
218
+ }
219
+ auto filtered_av_frame = nv12_conversion_->convert(av_frame);
220
+
221
+ // If this check fails it means the frame wasn't
222
+ // reshaped to its expected dimensions by filtergraph.
223
+ STD_TORCH_CHECK(
224
+ (filtered_av_frame->width == nv12_conversion_config_->output_width) &&
225
+ (filtered_av_frame->height == nv12_conversion_config_->output_height),
226
+ "Expected frame from filter graph of ",
227
+ nv12_conversion_config_->output_width,
228
+ "x",
229
+ nv12_conversion_config_->output_height,
230
+ ", got ",
231
+ filtered_av_frame->width,
232
+ "x",
233
+ filtered_av_frame->height);
234
+
235
+ return filtered_av_frame;
236
+ }
237
+
238
+ void CudaDeviceInterface::convert_av_frame_to_frame_output(
239
+ const AVFrame& input_av_frame,
240
+ FrameOutput& frame_output,
241
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor) {
242
+ validate_pre_allocated_tensor_shape(
243
+ pre_allocated_output_tensor,
244
+ FrameDims(input_av_frame.height, input_av_frame.width));
245
+
246
+ has_decoded_frame_ = true;
247
+
248
+ // All of our CUDA decoding assumes NV12 format. We handle non-NV12 formats by
249
+ // converting them to NV12.
250
+ UniqueAVFrame converted_av_frame =
251
+ maybe_convert_av_frame_to_nv12_or_rgb24(input_av_frame);
252
+ const AVFrame& av_frame =
253
+ converted_av_frame ? *converted_av_frame : input_av_frame;
254
+
255
+ if (av_frame.format != AV_PIX_FMT_CUDA) {
256
+ // The frame's format is AV_PIX_FMT_CUDA if and only if its content is on
257
+ // the GPU. In this branch, the frame is on the CPU. There are two possible
258
+ // reasons:
259
+ //
260
+ // 1. During maybeConvertAVFrameToNV12OrRGB24(), we had a non-NV12 format
261
+ // frame and we're on FFmpeg 4.4 or earlier. In such cases, we had to
262
+ // use CPU filters and we just converted the frame to RGB24.
263
+ // 2. This is what NVDEC gave us if it wasn't able to decode a frame, for
264
+ // whatever reason. Typically that happens if the video's encoder isn't
265
+ // supported by NVDEC.
266
+ //
267
+ // In both cases, we have a frame on the CPU. We send the frame back to the
268
+ // CUDA device when we're done.
269
+
270
+ enum AVPixelFormat frame_format =
271
+ static_cast<enum AVPixelFormat>(av_frame.format);
272
+
273
+ FrameOutput cpu_frame_output;
274
+ if (frame_format == AV_PIX_FMT_RGB24) {
275
+ // Reason 1 above. The frame is already in RGB24, we just need to convert
276
+ // it to a tensor.
277
+ cpu_frame_output.data = rgb_av_frame_to_tensor(av_frame);
278
+ } else {
279
+ // Reason 2 above. We need to do a full conversion which requires an
280
+ // actual CPU device.
281
+ cpu_interface_->convert_av_frame_to_frame_output(
282
+ av_frame, cpu_frame_output);
283
+ }
284
+
285
+ // Finally, we need to send the frame back to the GPU. Note that the
286
+ // pre-allocated tensor is on the GPU, so we can't send that to the CPU
287
+ // device interface. We copy it over here.
288
+ if (pre_allocated_output_tensor.has_value()) {
289
+ torch::stable::copy_(
290
+ pre_allocated_output_tensor.value(), cpu_frame_output.data);
291
+ frame_output.data = pre_allocated_output_tensor.value();
292
+ } else {
293
+ frame_output.data = torch::stable::to(cpu_frame_output.data, device_);
294
+ }
295
+
296
+ using_cpu_fallback_ = true;
297
+ return;
298
+ }
299
+
300
+ using_cpu_fallback_ = false;
301
+
302
+ // Above we checked that the AVFrame was on GPU, but that's not enough, we
303
+ // also need to check that the AVFrame is in AV_PIX_FMT_NV12 format (8 bits),
304
+ // because this is what our color conversion kernel expects. This SHOULD
305
+ // be enforced by our call to maybeConvertAVFrameToNV12OrRGB24() above.
306
+ STD_TORCH_CHECK(
307
+ av_frame.hw_frames_ctx != nullptr,
308
+ "The AVFrame does not have a hw_frames_ctx. This should never happen");
309
+ AVHWFramesContext* hw_frames_ctx =
310
+ reinterpret_cast<AVHWFramesContext*>(av_frame.hw_frames_ctx->data);
311
+ STD_TORCH_CHECK(
312
+ hw_frames_ctx != nullptr,
313
+ "The AVFrame does not have a valid hw_frames_ctx. This should never happen");
314
+
315
+ AVPixelFormat actual_format = hw_frames_ctx->sw_format;
316
+ STD_TORCH_CHECK(
317
+ actual_format == AV_PIX_FMT_NV12,
318
+ "The AVFrame is ",
319
+ (av_get_pix_fmt_name(actual_format) ? av_get_pix_fmt_name(actual_format)
320
+ : "unknown"),
321
+ ", but we expected AV_PIX_FMT_NV12. "
322
+ "That's unexpected, please report this to the TorchCodec repo.");
323
+
324
+ // Figure out the NVDEC stream from the avFrame's hardware context.
325
+ // In reality, we know that this stream is hardcoded to be the default stream
326
+ // by FFmpeg:
327
+ // https://github.com/FFmpeg/FFmpeg/blob/66e40840d15b514f275ce3ce2a4bf72ec68c7311/libavutil/hwcontext_cuda.c#L387-L388
328
+ STD_TORCH_CHECK(
329
+ hw_frames_ctx->device_ctx != nullptr,
330
+ "The AVFrame's hw_frames_ctx does not have a device_ctx. ");
331
+ auto cuda_device_ctx =
332
+ static_cast<AVCUDADeviceContext*>(hw_frames_ctx->device_ctx->hwctx);
333
+ STD_TORCH_CHECK(cuda_device_ctx != nullptr, "The hardware context is null");
334
+
335
+ cudaStream_t nvdec_stream = // That's always the default stream. Sad.
336
+ cuda_device_ctx->stream;
337
+
338
+ // FFmpeg gives us no hook to record an event when it's done producing this
339
+ // particular frame, so the best we can do is wait on everything it has
340
+ // enqueued so far.
341
+ cudaStream_t current_stream = get_current_cuda_stream(device_.index());
342
+ sync_streams(
343
+ /*running_stream=*/nvdec_stream, /*waiting_stream=*/current_stream);
344
+
345
+ frame_output.data = convert_yuv_frame_to_rgb(
346
+ av_frame,
347
+ device_,
348
+ current_stream,
349
+ pre_allocated_output_tensor,
350
+ FrameDims(av_frame.height, av_frame.width),
351
+ actual_format,
352
+ cached_color_matrix_);
353
+ }
354
+
355
+ // inspired by https://github.com/FFmpeg/FFmpeg/commit/ad67ea9
356
+ // we have to do this because of an FFmpeg bug where hardware decoding is not
357
+ // appropriately set, so we just go off and find the matching codec for the CUDA
358
+ // device
359
+ std::optional<const AVCodec*> CudaDeviceInterface::find_codec(
360
+ const AVCodecID& codec_id,
361
+ bool is_decoder) {
362
+ void* i = nullptr;
363
+ const AVCodec* codec = nullptr;
364
+ while ((codec = av_codec_iterate(&i)) != nullptr) {
365
+ STD_TORCH_CHECK(
366
+ codec != nullptr,
367
+ "codec returned by av_codec_iterate should not be null");
368
+ if (is_decoder) {
369
+ if (codec->id != codec_id || !av_codec_is_decoder(codec)) {
370
+ continue;
371
+ }
372
+ } else {
373
+ if (codec->id != codec_id || !av_codec_is_encoder(codec)) {
374
+ continue;
375
+ }
376
+ }
377
+
378
+ const AVCodecHWConfig* config = nullptr;
379
+ for (int j = 0; (config = avcodec_get_hw_config(codec, j)) != nullptr;
380
+ ++j) {
381
+ if (config->device_type == AV_HWDEVICE_TYPE_CUDA) {
382
+ return codec;
383
+ }
384
+ }
385
+ }
386
+
387
+ return std::nullopt;
388
+ }
389
+
390
+ std::string CudaDeviceInterface::get_details() {
391
+ // Note: for this interface specifically the fallback is only known after a
392
+ // frame has been decoded, not before: that's when FFmpeg decides to fallback,
393
+ // so we can't know earlier.
394
+ if (!has_decoded_frame_) {
395
+ return std::string(
396
+ "FFmpeg CUDA Device Interface. Fallback status unknown (no frames decoded).");
397
+ }
398
+ return std::string("FFmpeg CUDA Device Interface. Using ") +
399
+ (using_cpu_fallback_ ? "CPU fallback." : "NVDEC.");
400
+ }
401
+
402
+ // --------------------------------------------------------------------------
403
+ // Below are methods exclusive to video encoding:
404
+ // --------------------------------------------------------------------------
405
+
406
+ AVPixelFormat CudaDeviceInterface::get_encoding_pixel_format(
407
+ [[maybe_unused]] const AVCodec& av_codec,
408
+ const std::optional<std::string>& user_pixel_format) const {
409
+ STD_TORCH_CHECK(
410
+ !user_pixel_format.has_value(),
411
+ "Video encoding on GPU currently only supports the nv12 pixel format. "
412
+ "Do not set pixel_format to use nv12 by default.");
413
+ return CudaDeviceInterface::CUDA_ENCODING_PIXEL_FORMAT;
414
+ }
415
+
416
+ UniqueAVFrame CudaDeviceInterface::convert_tensor_to_av_frame_for_encoding(
417
+ const torch::stable::Tensor& tensor,
418
+ int frame_index,
419
+ AVCodecContext* codec_context) {
420
+ STD_TORCH_CHECK(
421
+ tensor.dim() == 3 && tensor.sizes()[0] == 3,
422
+ "Expected 3D RGB tensor (CHW format), got ",
423
+ tensor.dim(),
424
+ "D tensor");
425
+ STD_TORCH_CHECK(
426
+ tensor.device().type() == kStableCUDA,
427
+ "Expected tensor on CUDA device, got: ",
428
+ device_type_name(tensor.device().type()));
429
+
430
+ UniqueAVFrame av_frame(av_frame_alloc());
431
+ STD_TORCH_CHECK(av_frame != nullptr, "Failed to allocate AVFrame");
432
+ int height = static_cast<int>(tensor.sizes()[1]);
433
+ int width = static_cast<int>(tensor.sizes()[2]);
434
+
435
+ // TODO-VideoEncoder: (P1) Unify AVFrame creation with CPU method
436
+ av_frame->format = AV_PIX_FMT_CUDA;
437
+ av_frame->height = height;
438
+ av_frame->width = width;
439
+ av_frame->pts = frame_index;
440
+
441
+ // FFmpeg's av_hwframe_get_buffer is used to allocate memory on CUDA device.
442
+ // TODO-VideoEncoder: (P2) Consider using pytorch to allocate CUDA memory for
443
+ // efficiency
444
+ int ret =
445
+ av_hwframe_get_buffer(codec_context->hw_frames_ctx, av_frame.get(), 0);
446
+ STD_TORCH_CHECK(
447
+ ret >= 0,
448
+ "Failed to allocate hardware frame: ",
449
+ get_ffmpeg_error_string_from_error_code(ret));
450
+
451
+ STD_TORCH_CHECK(
452
+ av_frame != nullptr && av_frame->data[0] != nullptr,
453
+ "avFrame must be pre-allocated with CUDA memory");
454
+
455
+ // TODO VideoEncoder: Investigate ways to avoid this copy
456
+ torch::stable::Tensor hwc_frame =
457
+ torch::stable::contiguous(stable_permute(tensor, {1, 2, 0}));
458
+
459
+ float rgb_to_yuv_matrix[3][4];
460
+ compute_rgb_to_yuv_matrix(
461
+ codec_context->colorspace, codec_context->color_range, rgb_to_yuv_matrix);
462
+
463
+ cudaStream_t stream = get_current_cuda_stream(device_.index());
464
+ launch_rgb_to_nv12_kernel(
465
+ hwc_frame.const_data_ptr<uint8_t>(),
466
+ av_frame->data[0],
467
+ av_frame->data[1],
468
+ width,
469
+ height,
470
+ validate_int64_to_int(
471
+ hwc_frame.stride(0) * static_cast<int64_t>(hwc_frame.element_size()),
472
+ "rgbPitch"),
473
+ av_frame->linesize[0],
474
+ av_frame->linesize[1],
475
+ rgb_to_yuv_matrix,
476
+ stream);
477
+
478
+ av_frame->colorspace = codec_context->colorspace;
479
+ av_frame->color_range = codec_context->color_range;
480
+ return av_frame;
481
+ }
482
+
483
+ // Allocates and initializes AVHWFramesContext, and sets pixel format fields
484
+ // to enable encoding with CUDA device. The hw_frames_ctx field is needed by
485
+ // FFmpeg to allocate frames on GPU's memory.
486
+ void CudaDeviceInterface::setup_hardware_frame_context_for_encoding(
487
+ AVCodecContext* codec_context) {
488
+ STD_TORCH_CHECK(codec_context != nullptr, "codecContext is null");
489
+ STD_TORCH_CHECK(
490
+ hardware_device_ctx_, "Hardware device context has not been initialized");
491
+
492
+ AVBufferRef* hw_frames_ctx_ref =
493
+ av_hwframe_ctx_alloc(hardware_device_ctx_.get());
494
+ STD_TORCH_CHECK(
495
+ hw_frames_ctx_ref != nullptr,
496
+ "Failed to allocate hardware frames context for codec");
497
+
498
+ codec_context->sw_pix_fmt = CudaDeviceInterface::CUDA_ENCODING_PIXEL_FORMAT;
499
+ // Always set pixel format to support CUDA encoding.
500
+ codec_context->pix_fmt = AV_PIX_FMT_CUDA;
501
+
502
+ AVHWFramesContext* hw_frames_ctx =
503
+ reinterpret_cast<AVHWFramesContext*>(hw_frames_ctx_ref->data);
504
+ hw_frames_ctx->format = codec_context->pix_fmt;
505
+ hw_frames_ctx->sw_format = codec_context->sw_pix_fmt;
506
+ hw_frames_ctx->width = codec_context->width;
507
+ hw_frames_ctx->height = codec_context->height;
508
+
509
+ int ret = av_hwframe_ctx_init(hw_frames_ctx_ref);
510
+ if (ret < 0) {
511
+ av_buffer_unref(&hw_frames_ctx_ref);
512
+ STD_TORCH_CHECK(
513
+ false,
514
+ "Failed to initialize CUDA frames context for codec: ",
515
+ get_ffmpeg_error_string_from_error_code(ret));
516
+ }
517
+ codec_context->hw_frames_ctx = hw_frames_ctx_ref;
518
+ }
519
+ } // namespace facebook::torchcodec