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,1635 @@
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 <algorithm>
8
+ #include <limits>
9
+ #include <map>
10
+ #include <mutex>
11
+ #include <vector>
12
+ #include "StableABICompat.h"
13
+ #include "ValidationUtils.h"
14
+
15
+ #include "BetaCudaDeviceInterface.h"
16
+
17
+ #include "DeviceInterface.h"
18
+ #include "FFMPEGCommon.h"
19
+ #include "Logging.h"
20
+ #include "NVDECCache.h"
21
+
22
+ #include "NVCUVIDRuntimeLoader.h"
23
+ #include "color_conversion.h"
24
+ #include "nvcuvid_include/cuviddec.h"
25
+ #include "nvcuvid_include/nvcuvid.h"
26
+
27
+ extern "C" {
28
+ #include <libavutil/hwcontext_cuda.h>
29
+ #include <libavutil/pixdesc.h>
30
+ }
31
+
32
+ namespace facebook::torchcodec {
33
+
34
+ namespace {
35
+
36
+ // Per-device cache for cuvidGetDecoderCaps results.
37
+ // The key is a tuple of (device index, codec type, chroma format, bit depth
38
+ // minus 8).
39
+ struct DecoderCapsCache {
40
+ using Key =
41
+ std::tuple<int, cudaVideoCodec, cudaVideoChromaFormat, unsigned int>;
42
+ std::map<Key, CUVIDDECODECAPS> cache;
43
+ std::mutex mutex;
44
+
45
+ std::pair<CUresult, CUVIDDECODECAPS> get_decoder_caps(
46
+ int device_index,
47
+ cudaVideoCodec codec_type,
48
+ cudaVideoChromaFormat chroma_format,
49
+ unsigned int bit_depth_minus8) {
50
+ Key key{device_index, codec_type, chroma_format, bit_depth_minus8};
51
+
52
+ std::lock_guard<std::mutex> lock(mutex);
53
+ auto it = cache.find(key);
54
+ if (it != cache.end()) {
55
+ return {CUDA_SUCCESS, it->second};
56
+ }
57
+
58
+ CUVIDDECODECAPS caps = {};
59
+ caps.eCodecType = codec_type;
60
+ caps.eChromaFormat = chroma_format;
61
+ caps.nBitDepthMinus8 = bit_depth_minus8;
62
+
63
+ CUresult result = cuvidGetDecoderCaps(&caps);
64
+ if (result == CUDA_SUCCESS) {
65
+ cache[key] = caps;
66
+ }
67
+ return {result, caps};
68
+ }
69
+ };
70
+
71
+ static DecoderCapsCache& get_decoder_caps_cache() {
72
+ static DecoderCapsCache cache;
73
+ return cache;
74
+ }
75
+
76
+ // NVDEC's output surface formats come in a 4:2:0 and a 4:4:4 flavour, each with
77
+ // an 8-bit and a 16-bit variant. We decode on the surface that respects the
78
+ // source chroma, but we don't respect the source bit depth and instead try to
79
+ // honor the user's requested output dtype:
80
+ // - if the user wants uint8 output, we try to decode on a uint8 surface,
81
+ // including for >8bit sources. It's not always supported by NVDEC, so the
82
+ // caller must fallback to the >8bit surface in such case.
83
+ // - similarly if the user wants float32 output, we try to decode on a >8bit
84
+ // surface, including for 8bit sources. The caller must handle a similar
85
+ // fallback.
86
+ cudaVideoSurfaceFormat get_preferred_surface_format(
87
+ cudaVideoChromaFormat chroma_format,
88
+ OutputDtype output_dtype) {
89
+ bool want_uint8 = output_dtype == OutputDtype::UINT8;
90
+ if (chroma_format == cudaVideoChromaFormat_444) {
91
+ return want_uint8 ? cudaVideoSurfaceFormat_YUV444
92
+ : cudaVideoSurfaceFormat_YUV444_16Bit;
93
+ } else {
94
+ return want_uint8 ? cudaVideoSurfaceFormat_NV12
95
+ : cudaVideoSurfaceFormat_P016;
96
+ }
97
+ }
98
+
99
+ // The AVPixelFormat describing a given surface, for a source of that bit depth.
100
+ // nvdec_pix_fmt() takes our own enum rather than the NVDEC type, so that
101
+ // FFMPEGCommon doesn't have to include the NVDEC headers.
102
+ AVPixelFormat surface_to_pix_fmt(
103
+ cudaVideoSurfaceFormat surface_format,
104
+ int bit_depth) {
105
+ NvdecSurface surface = NvdecSurface::NV12;
106
+ switch (surface_format) {
107
+ case cudaVideoSurfaceFormat_P016:
108
+ surface = NvdecSurface::P016;
109
+ break;
110
+ case cudaVideoSurfaceFormat_YUV444:
111
+ surface = NvdecSurface::YUV444;
112
+ break;
113
+ case cudaVideoSurfaceFormat_YUV444_16Bit:
114
+ surface = NvdecSurface::YUV444_16Bit;
115
+ break;
116
+ default:
117
+ break;
118
+ }
119
+ return nvdec_pix_fmt(surface, bit_depth);
120
+ }
121
+
122
+ bool is_444_surface_format(cudaVideoSurfaceFormat format) {
123
+ return format == cudaVideoSurfaceFormat_YUV444 ||
124
+ format == cudaVideoSurfaceFormat_YUV444_16Bit;
125
+ }
126
+
127
+ bool is_16bit_surface_format(cudaVideoSurfaceFormat format) {
128
+ return format == cudaVideoSurfaceFormat_P016 ||
129
+ format == cudaVideoSurfaceFormat_YUV444_16Bit;
130
+ }
131
+
132
+ bool is_expected_pix_fmt_from_nvdec(AVPixelFormat pix_fmt) {
133
+ return pix_fmt == AV_PIX_FMT_NV12 || is_nvdec_16bit_pix_fmt(pix_fmt) ||
134
+ pix_fmt == AV_PIX_FMT_YUV444P || pix_fmt == AV_PIX_FMT_YUV444P16LE;
135
+ }
136
+
137
+ static bool g_cuda_nvdec = register_device_interface(
138
+ DeviceInterfaceKey(kStableCUDA, /*variant=*/"default"),
139
+ [](const StableDevice& device) {
140
+ return new BetaCudaDeviceInterface(device);
141
+ });
142
+
143
+ static int CUDAAPI
144
+ pfn_sequence_callback(void* p_user_data, CUVIDEOFORMAT* video_format) {
145
+ auto decoder = static_cast<BetaCudaDeviceInterface*>(p_user_data);
146
+ return decoder->stream_property_change(video_format);
147
+ }
148
+
149
+ static int CUDAAPI
150
+ pfn_decode_picture_callback(void* p_user_data, CUVIDPICPARAMS* pic_params) {
151
+ auto decoder = static_cast<BetaCudaDeviceInterface*>(p_user_data);
152
+ return decoder->frame_ready_for_decoding(pic_params);
153
+ }
154
+
155
+ static int CUDAAPI pfn_display_picture_callback(
156
+ void* p_user_data,
157
+ CUVIDPARSERDISPINFO* disp_info) {
158
+ auto decoder = static_cast<BetaCudaDeviceInterface*>(p_user_data);
159
+ return decoder->frame_ready_in_display_order(disp_info);
160
+ }
161
+
162
+ // Whether a single VP9 coded frame is displayed, from the first bits of its
163
+ // uncompressed header. Bit layout matches
164
+ // libavcodec/bsf/vp9_superframe_split.c:
165
+ // frame_marker f(2) (== 2)
166
+ // profile_low_bit f(1)
167
+ // profile_high_bit f(1)
168
+ // [profile == 3] reserved f(1)
169
+ // show_existing_frame f(1) -> if set, this frame IS displayed
170
+ // frame_type f(1)
171
+ // show_frame f(1)
172
+ bool vp9_frame_is_displayed(const uint8_t* data, int size) {
173
+ int bit = 0;
174
+ auto read_bit = [&]() -> int {
175
+ int byte_index = bit >> 3;
176
+ if (byte_index >= size) {
177
+ return 0;
178
+ }
179
+ int value = (data[byte_index] >> (7 - (bit & 7))) & 1;
180
+ bit++;
181
+ return value;
182
+ };
183
+
184
+ if (size < 1) {
185
+ return false;
186
+ }
187
+ read_bit();
188
+ read_bit(); // frame_marker
189
+ int profile = read_bit();
190
+ profile |= read_bit() << 1;
191
+ if (profile == 3) {
192
+ read_bit(); // reserved
193
+ }
194
+ if (read_bit()) {
195
+ return true; // show_existing_frame: re-displays an existing reference
196
+ }
197
+ read_bit(); // frame_type
198
+ return read_bit() != 0; // show_frame
199
+ }
200
+
201
+ // How many frames a VP9 packet will display: 0 (a lone hidden alt-ref), 1
202
+ // (the common case), or more. Returns -1 if the packet looks malformed.
203
+ // Fully claude-generated.
204
+ int count_vp9_displayed_frames(const uint8_t* data, int size) {
205
+ if (data == nullptr || size <= 0) {
206
+ return -1;
207
+ }
208
+
209
+ uint8_t marker = data[size - 1];
210
+ if ((marker & 0xe0) == 0xc0) {
211
+ int length_size = 1 + ((marker >> 3) & 0x3);
212
+ int nb_frames = 1 + (marker & 0x7);
213
+ int index_size = 2 + nb_frames * length_size;
214
+
215
+ if (size >= index_size && data[size - index_size] == marker) {
216
+ const uint8_t* sizes = data + size - index_size + 1;
217
+ int displayed = 0;
218
+ int offset = 0;
219
+ for (int i = 0; i < nb_frames; ++i) {
220
+ int frame_size = 0;
221
+ for (int j = 0; j < length_size; ++j) {
222
+ frame_size |= *sizes++ << (j * 8);
223
+ }
224
+ if (frame_size <= 0 || offset + frame_size > size - index_size) {
225
+ return -1;
226
+ }
227
+ if (vp9_frame_is_displayed(data + offset, frame_size)) {
228
+ displayed++;
229
+ }
230
+ offset += frame_size;
231
+ }
232
+ return displayed;
233
+ }
234
+ }
235
+
236
+ // Not a superframe: a single coded frame, displayed or not.
237
+ return vp9_frame_is_displayed(data, size) ? 1 : 0;
238
+ }
239
+
240
+ static UniqueCUvideodecoder create_decoder(
241
+ CUVIDEOFORMAT* video_format,
242
+ cudaVideoSurfaceFormat surface_format) {
243
+ // Decoder creation parameters, most are taken from DALI
244
+ CUVIDDECODECREATEINFO decoder_params = {};
245
+ decoder_params.bitDepthMinus8 = video_format->bit_depth_luma_minus8;
246
+ decoder_params.ChromaFormat = video_format->chroma_format;
247
+ decoder_params.OutputFormat = surface_format;
248
+ decoder_params.ulCreationFlags = cudaVideoCreate_Default;
249
+ decoder_params.CodecType = video_format->codec;
250
+ decoder_params.ulHeight = video_format->coded_height;
251
+ decoder_params.ulWidth = video_format->coded_width;
252
+ decoder_params.ulMaxHeight = video_format->coded_height;
253
+ decoder_params.ulMaxWidth = video_format->coded_width;
254
+ // We want coded dimensions everywhere. See [NVDEC surface
255
+ // dimensions and cropping].
256
+ decoder_params.ulTargetHeight = video_format->coded_height;
257
+ decoder_params.ulTargetWidth = video_format->coded_width;
258
+ decoder_params.ulNumDecodeSurfaces = video_format->min_num_decode_surfaces;
259
+ // We should only ever need 1 output surface, since we process frames
260
+ // sequentially, and we always unmap the previous frame before mapping a new
261
+ // one.
262
+ // TODONVDEC P3: set this to 2, allow for 2 frames to be mapped at a time, and
263
+ // benchmark to see if this makes any difference.
264
+ decoder_params.ulNumOutputSurfaces = 1;
265
+ decoder_params.display_area.left = 0;
266
+ decoder_params.display_area.right =
267
+ static_cast<short>(video_format->coded_width);
268
+ decoder_params.display_area.top = 0;
269
+ decoder_params.display_area.bottom =
270
+ static_cast<short>(video_format->coded_height);
271
+
272
+ CUvideodecoder* decoder = new CUvideodecoder();
273
+ CUresult result = cuvidCreateDecoder(decoder, &decoder_params);
274
+ STD_TORCH_CHECK(
275
+ result == CUDA_SUCCESS, "Failed to create NVDEC decoder: ", result);
276
+ return UniqueCUvideodecoder(decoder, CUvideoDecoderDeleter{});
277
+ }
278
+
279
+ std::optional<cudaVideoChromaFormat> validate_chroma_support(
280
+ const AVPixFmtDescriptor* desc) {
281
+ // Return the corresponding cudaVideoChromaFormat if supported, std::nullopt
282
+ // otherwise.
283
+ STD_TORCH_CHECK(desc != nullptr, "desc can't be null");
284
+
285
+ if (desc->nb_components == 1) {
286
+ return cudaVideoChromaFormat_Monochrome;
287
+ } else if (desc->nb_components >= 3 && !(desc->flags & AV_PIX_FMT_FLAG_RGB)) {
288
+ // Make sure it's YUV: has chroma planes and isn't RGB
289
+ if (desc->log2_chroma_w == 0 && desc->log2_chroma_h == 0) {
290
+ return cudaVideoChromaFormat_444; // 1x1 subsampling = 4:4:4
291
+ } else if (desc->log2_chroma_w == 1 && desc->log2_chroma_h == 1) {
292
+ return cudaVideoChromaFormat_420; // 2x2 subsampling = 4:2:0
293
+ } else if (desc->log2_chroma_w == 1 && desc->log2_chroma_h == 0) {
294
+ return cudaVideoChromaFormat_422; // 2x1 subsampling = 4:2:2
295
+ }
296
+ }
297
+
298
+ return std::nullopt;
299
+ }
300
+
301
+ std::optional<cudaVideoCodec> validate_codec_support(AVCodecID codec_id) {
302
+ // Return the corresponding cudaVideoCodec if supported, std::nullopt
303
+ // otherwise
304
+ // Note that we currently return nullopt (and thus fallback to CPU) for some
305
+ // codecs that are technically supported by NVDEC, see comment below.
306
+ switch (codec_id) {
307
+ case AV_CODEC_ID_H264:
308
+ return cudaVideoCodec_H264;
309
+ case AV_CODEC_ID_HEVC:
310
+ return cudaVideoCodec_HEVC;
311
+ case AV_CODEC_ID_AV1:
312
+ return cudaVideoCodec_AV1;
313
+ case AV_CODEC_ID_VP9:
314
+ return cudaVideoCodec_VP9;
315
+ case AV_CODEC_ID_VP8:
316
+ return cudaVideoCodec_VP8;
317
+ case AV_CODEC_ID_MPEG4:
318
+ return cudaVideoCodec_MPEG4;
319
+ // Formats below are currently not tested, but they should "mostly" work.
320
+ // MPEG1 was briefly locally tested and it was ok-ish despite duration being
321
+ // off. Since they're far less popular, we keep them disabled by default but
322
+ // we can consider enabling them upon user requests.
323
+ // case AV_CODEC_ID_MPEG1VIDEO:
324
+ // return cudaVideoCodec_MPEG1;
325
+ // case AV_CODEC_ID_MPEG2VIDEO:
326
+ // return cudaVideoCodec_MPEG2;
327
+ // case AV_CODEC_ID_MJPEG:
328
+ // return cudaVideoCodec_JPEG;
329
+ // case AV_CODEC_ID_VC1:
330
+ // return cudaVideoCodec_VC1;
331
+ default:
332
+ return std::nullopt;
333
+ }
334
+ }
335
+
336
+ std::optional<cudaVideoSurfaceFormat> get_nvdec_surface_format(
337
+ const StableDevice& device,
338
+ const SharedAVCodecContext& codec_context,
339
+ OutputDtype output_dtype) {
340
+ // Return the surface format to use for NVDEC decoding if the stream is
341
+ // supported, or nullopt to fall back to CPU.
342
+
343
+ auto codec_type = validate_codec_support(codec_context->codec_id);
344
+ if (!codec_type.has_value()) {
345
+ return std::nullopt;
346
+ }
347
+
348
+ const AVPixFmtDescriptor* desc = av_pix_fmt_desc_get(codec_context->pix_fmt);
349
+ if (!desc) {
350
+ return std::nullopt;
351
+ }
352
+
353
+ auto chroma_format = validate_chroma_support(desc);
354
+ if (!chroma_format.has_value()) {
355
+ return std::nullopt;
356
+ }
357
+
358
+ auto bit_depth_minus8 = static_cast<unsigned int>(desc->comp[0].depth - 8);
359
+ auto [result, caps] = get_decoder_caps_cache().get_decoder_caps(
360
+ get_device_index(device),
361
+ codec_type.value(),
362
+ chroma_format.value(),
363
+ bit_depth_minus8);
364
+ if (result != CUDA_SUCCESS) {
365
+ return std::nullopt;
366
+ }
367
+
368
+ if (!caps.bIsSupported) {
369
+ return std::nullopt;
370
+ }
371
+
372
+ auto coded_width = static_cast<unsigned int>(codec_context->coded_width);
373
+ auto coded_height = static_cast<unsigned int>(codec_context->coded_height);
374
+ if (coded_width < static_cast<unsigned int>(caps.nMinWidth) ||
375
+ coded_height < static_cast<unsigned int>(caps.nMinHeight) ||
376
+ coded_width > caps.nMaxWidth || coded_height > caps.nMaxHeight) {
377
+ return std::nullopt;
378
+ }
379
+
380
+ // See nMaxMBCount in cuviddec.h
381
+ constexpr unsigned int macroblock_constant = 256;
382
+ if (coded_width * coded_height / macroblock_constant > caps.nMaxMBCount) {
383
+ return std::nullopt;
384
+ }
385
+
386
+ auto preferred_format =
387
+ get_preferred_surface_format(chroma_format.value(), output_dtype);
388
+
389
+ auto is_supported = [&](cudaVideoSurfaceFormat format) {
390
+ return ((caps.nOutputFormatMask >> format) & 1) != 0;
391
+ };
392
+
393
+ if (is_supported(preferred_format)) {
394
+ return preferred_format;
395
+ }
396
+
397
+ // The preferred_format heuristic tries to take a shortcut that might cause us
398
+ // to miss valid formats. We fallabck here:
399
+ // if source is 8bit we can try the 8bit surface.
400
+ // if surface is 8bit we can try the 16bit surface.
401
+
402
+ bool source_is_8_bits = bit_depth_minus8 == 0;
403
+ if (is_16bit_surface_format(preferred_format) && source_is_8_bits) {
404
+ auto narrower = preferred_format == cudaVideoSurfaceFormat_YUV444_16Bit
405
+ ? cudaVideoSurfaceFormat_YUV444
406
+ : cudaVideoSurfaceFormat_NV12;
407
+
408
+ if (is_supported(narrower)) {
409
+ return narrower;
410
+ }
411
+ }
412
+ if (!is_16bit_surface_format(preferred_format)) {
413
+ auto wider = preferred_format == cudaVideoSurfaceFormat_YUV444
414
+ ? cudaVideoSurfaceFormat_YUV444_16Bit
415
+ : cudaVideoSurfaceFormat_P016;
416
+
417
+ if (is_supported(wider)) {
418
+ return wider;
419
+ }
420
+ }
421
+
422
+ return std::nullopt;
423
+ }
424
+
425
+ void standalone_frame_free_callback(
426
+ [[maybe_unused]] void* opaque,
427
+ uint8_t* data) {
428
+ delete reinterpret_cast<OwnedFrameStorage*>(data);
429
+ }
430
+
431
+ class CudaContextGuard {
432
+ // There's one CUDA context per process per device. But new threads aren't
433
+ // bound to a context. The binding often happens automatically when calling
434
+ // CUDA APIs (like cudaFree), but some APIs like the NVCUVID ones that we use
435
+ // here aren't automatically binding.
436
+ // So for a thread to be able to use NVCUVID APIs, it must have a context
437
+ // bound to it, and we have to enforce that binding manually.
438
+ // That's what this guard does: it calls cudaFree(nullptr), which is a common
439
+ // near-free way to force the CUDA runtime to bind the context for the current
440
+ // thread. And this call must happen within a device guard to make sure we're
441
+ // binding the context of the device this interface is using.
442
+ // We must call this guard in every public method of the interface that uses
443
+ // NVCUVID APIs, because these methods can, in theory, be called from any
444
+ // thread.
445
+ // Note that none of this was an issue before when our only entry-point was
446
+ // the SingleStreamDecoder: all the entry-points were called from the same
447
+ // thread. Now that we have split the APIs in different stages (PacketDecoder,
448
+ // ColorConverter), each of these stages can be on different threads - and
449
+ // importantly, they can be created in the main thread (where the context is
450
+ // bound by our call to initialize_cuda_context_with_pytorch()), but then used
451
+ // in a different thread that doesn't have the context.
452
+ public:
453
+ explicit CudaContextGuard(int device_index) : device_guard_(device_index) {
454
+ cudaFree(nullptr);
455
+ }
456
+
457
+ private:
458
+ StableDeviceGuard device_guard_;
459
+ };
460
+
461
+ } // namespace
462
+
463
+ BetaCudaDeviceInterface::BetaCudaDeviceInterface(const StableDevice& device)
464
+ : DeviceInterface(device) {
465
+ STD_TORCH_CHECK(g_cuda_nvdec, "NvdecCudaDeviceInterface was not registered!");
466
+ STD_TORCH_CHECK(
467
+ device_.type() == kStableCUDA, "Unsupported device: must be CUDA");
468
+
469
+ device_ = StableDevice(kStableCUDA, get_device_index(device_));
470
+
471
+ // Note: now that we have the CudaContextGuard, we might not need to do that
472
+ // anymore. The comment says we need pytorch to create the context - maybe
473
+ // that's true, but that's a very old comment now.
474
+ initialize_cuda_context_with_pytorch(device_);
475
+
476
+ nvcuvid_available_ = load_nvcuvid_library();
477
+ }
478
+
479
+ BetaCudaDeviceInterface::Mode BetaCudaDeviceInterface::mode() const {
480
+ if (decoding_initialized_ && color_conversion_initialized_) {
481
+ return Mode::Both;
482
+ } else if (decoding_initialized_) {
483
+ return Mode::DecoderOnly;
484
+ } else if (color_conversion_initialized_) {
485
+ return Mode::ColorConverterOnly;
486
+ }
487
+ return Mode::Uninitialized;
488
+ }
489
+
490
+ void BetaCudaDeviceInterface::initialize_color_conversion(
491
+ const VideoStreamOptions& video_stream_options,
492
+ [[maybe_unused]] const std::vector<std::unique_ptr<Transform>>& transforms,
493
+ [[maybe_unused]] const std::optional<FrameDims>& resized_output_dims) {
494
+ output_dtype_ = video_stream_options.output_dtype;
495
+ color_conversion_initialized_ = true;
496
+ }
497
+
498
+ void BetaCudaDeviceInterface::initialize_video_decoding(
499
+ const CodecParameters& codec_parameters,
500
+ const VideoStreamOptions& video_stream_options) {
501
+ CudaContextGuard context_guard(device_.index());
502
+ decoding_initialized_ = true;
503
+ rotation_ = rotation_from_degrees(codec_parameters.get_rotation());
504
+ output_dtype_ = video_stream_options.output_dtype;
505
+
506
+ auto maybe_surface_format = nvcuvid_available_
507
+ ? get_nvdec_surface_format(device_, codec_context_, output_dtype_)
508
+ : std::nullopt;
509
+
510
+ if (!maybe_surface_format.has_value()) {
511
+ if (!nvcuvid_available_) {
512
+ TC_LOG("NVCUVID library not available; falling back to CPU decoding.");
513
+ } else {
514
+ TC_LOG(
515
+ "Video stream not supported by NVDEC; falling back to CPU decoding.");
516
+ }
517
+ decoding_on_cpu_ = true;
518
+ cpu_interface_ = create_device_interface(kStableCPU);
519
+ STD_TORCH_CHECK(
520
+ cpu_interface_ != nullptr, "Failed to create CPU device interface");
521
+ cpu_interface_->initialize(codec_context_);
522
+ cpu_interface_->initialize_video_decoding(
523
+ codec_parameters, video_stream_options);
524
+ return;
525
+ }
526
+
527
+ surface_format_ = maybe_surface_format.value();
528
+ time_base_ = codec_parameters.time_base;
529
+ frame_rate_avg_from_ffmpeg_ = codec_parameters.r_frame_rate;
530
+
531
+ const AVCodecParameters* codec_par = codec_parameters.codecpar.get();
532
+ STD_TORCH_CHECK(codec_par != nullptr, "CodecParameters cannot be null");
533
+
534
+ initialize_bsf(codec_par, codec_parameters.container_format);
535
+
536
+ // On VP9 when there are alt-ref frames, the NVCUVID parser reports incorrect
537
+ // timestamps. We don't know why. It's just incorrect. And because our decode
538
+ // loops heavily rely on pts info, this leads to incorrect behavior:
539
+ // requesting for frame i may return frame i + ~2.
540
+ // So for VP9, we keep track of the pts ourselves. We can do that because VP9
541
+ // doesn't have B-frames: the packets and their corresponding pts values
542
+ // arrive in the same order that the frames will be displayed. So we can just
543
+ // queue the pts valueof the packets that we receive, and pop() those to
544
+ // assign them to the frames that are displayed.
545
+ // test_nvdec_vp9_superframe_seek() is a non-regression test for all this.
546
+ track_pts_ourselves_ = (codec_par->codec_id == AV_CODEC_ID_VP9);
547
+
548
+ // Create parser. Default values that aren't obvious are taken from DALI.
549
+ CUVIDPARSERPARAMS parser_params = {};
550
+ auto codec_type = validate_codec_support(codec_par->codec_id);
551
+ STD_TORCH_CHECK(
552
+ codec_type.has_value(),
553
+ "This should never happen, we should be using the CPU fallback by now. "
554
+ "Please report a bug.");
555
+ parser_params.CodecType = codec_type.value();
556
+ parser_params.ulMaxNumDecodeSurfaces = 8;
557
+ parser_params.ulMaxDisplayDelay = 0;
558
+ // Callback setup, all are triggered by the parser within a call
559
+ // to cuvidParseVideoData
560
+ parser_params.pUserData = this;
561
+ parser_params.pfnSequenceCallback = pfn_sequence_callback;
562
+ parser_params.pfnDecodePicture = pfn_decode_picture_callback;
563
+ parser_params.pfnDisplayPicture = pfn_display_picture_callback;
564
+
565
+ // Some containers (e.g. MP4/MOV) store codec config (H.264 SPS/PPS,
566
+ // MPEG-4 VOS/VOL, etc.) in extradata rather than inline in the
567
+ // bitstream. The NVCUVID parser needs this data to initialize, so we
568
+ // pass it via pExtVideoInfo. Same approach as DALI and FFmpeg cuviddec.
569
+ // DALI does the same thing
570
+ // https://github.com/NVIDIA/DALI/blob/ae79f316ae9b14c464d9cb98465f7f783da9ea89/dali/operators/video/frames_decoder_gpu.cc#L402-L408
571
+ //
572
+ const uint8_t* seqhdr = codec_par->extradata;
573
+ int seqhdr_data_size = codec_par->extradata_size;
574
+ if (bitstream_filter_ && bitstream_filter_->par_out->extradata_size > 0) {
575
+ // when a BSF is used (e.g. h264_mp4toannexb), we must pass the
576
+ // *filtered* extradata!
577
+ seqhdr = bitstream_filter_->par_out->extradata;
578
+ seqhdr_data_size = bitstream_filter_->par_out->extradata_size;
579
+ }
580
+ if (seqhdr_data_size > 0) {
581
+ auto seqhdr_size = std::min(
582
+ static_cast<size_t>(seqhdr_data_size),
583
+ sizeof(parser_ext_info_.raw_seqhdr_data));
584
+ parser_ext_info_.format.seqhdr_data_length = seqhdr_size;
585
+ memcpy(parser_ext_info_.raw_seqhdr_data, seqhdr, seqhdr_size);
586
+ parser_params.pExtVideoInfo = &parser_ext_info_;
587
+ }
588
+
589
+ CUresult result = cuvidCreateVideoParser(&video_parser_, &parser_params);
590
+ STD_TORCH_CHECK(
591
+ result == CUDA_SUCCESS, "Failed to create video parser: ", result);
592
+
593
+ send_seqhdr_packet();
594
+ }
595
+
596
+ void BetaCudaDeviceInterface::send_seqhdr_packet() {
597
+ // This must be called at parser initialization, and after each flush.
598
+ // See https://github.com/meta-pytorch/torchcodec/pull/1503 for details.
599
+ // FFmpeg's nvcuviddec.c does the same thing (not the nvdec.c one, because it
600
+ // doesn't rely on the nvcuvid parser):
601
+ // -
602
+ // https://github.com/FFmpeg/FFmpeg/blob/d244d438c372b76d825be4527fccfd162429010a/libavcodec/cuviddec.c#L1211
603
+ // -
604
+ // https://github.com/FFmpeg/FFmpeg/blob/d244d438c372b76d825be4527fccfd162429010a/libavcodec/cuviddec.c#L1157
605
+ if (parser_ext_info_.format.seqhdr_data_length == 0) {
606
+ return;
607
+ }
608
+ CUVIDSOURCEDATAPACKET seq_pkt = {};
609
+ seq_pkt.payload = parser_ext_info_.raw_seqhdr_data;
610
+ seq_pkt.payload_size = parser_ext_info_.format.seqhdr_data_length;
611
+ send_cuvid_packet(seq_pkt);
612
+ }
613
+
614
+ BetaCudaDeviceInterface::~BetaCudaDeviceInterface() {
615
+ CudaContextGuard context_guard(device_.index());
616
+ if (decoder_) {
617
+ // DALI doesn't seem to do any particular cleanup of the decoder before
618
+ // sending it to the cache, so we probably don't need to do anything either.
619
+ // Just to be safe, we flush.
620
+ // What happens to those decode surfaces that haven't yet been mapped is
621
+ // unclear.
622
+ flush();
623
+ // Whoever picks this decoder up from the cache will map its output surface
624
+ // and overwrite it. We block the host until the last consumer is done
625
+ // reading.
626
+ surface_read_done_.synchronize();
627
+ unmap_previous_frame();
628
+ NVDECCache::get_cache(device_).return_decoder(
629
+ &video_format_, surface_format_, std::move(decoder_));
630
+ }
631
+
632
+ if (video_parser_) {
633
+ cuvidDestroyVideoParser(video_parser_);
634
+ video_parser_ = nullptr;
635
+ }
636
+ }
637
+
638
+ void BetaCudaDeviceInterface::initialize(
639
+ const SharedAVCodecContext& codec_context) {
640
+ codec_context_ = codec_context;
641
+ }
642
+
643
+ void BetaCudaDeviceInterface::initialize_bsf(
644
+ const AVCodecParameters* codec_par,
645
+ const AVInputFormat* container_format) {
646
+ // Setup bit stream filters (BSF):
647
+ // https://ffmpeg.org/doxygen/7.0/group__lavc__bsf.html
648
+ // This is only needed for some formats, like H264 or HEVC.
649
+
650
+ STD_TORCH_CHECK(codec_par != nullptr, "codecPar cannot be null");
651
+ std::string filter_name;
652
+
653
+ if (container_format == nullptr) {
654
+ // The parameters don't come from a Demuxer. We apply the filter the codec
655
+ // may need, and rely on it to pass through the packets that don't need
656
+ // it: the mp4toannexb filters do when the extradata is missing or already
657
+ // Annex B, and mpeg4_unpack_bframes does when B-frames aren't packed.
658
+ switch (codec_par->codec_id) {
659
+ case AV_CODEC_ID_H264:
660
+ filter_name = "h264_mp4toannexb";
661
+ break;
662
+ case AV_CODEC_ID_HEVC:
663
+ filter_name = "hevc_mp4toannexb";
664
+ break;
665
+ case AV_CODEC_ID_MPEG4:
666
+ filter_name = "mpeg4_unpack_bframes";
667
+ break;
668
+ default:
669
+ break;
670
+ }
671
+ } else {
672
+ // Matching logic is taken from DALI
673
+ switch (codec_par->codec_id) {
674
+ case AV_CODEC_ID_H264: {
675
+ const std::string format_name =
676
+ container_format->long_name ? container_format->long_name : "";
677
+
678
+ if (format_name == "QuickTime / MOV" ||
679
+ format_name == "FLV (Flash Video)" ||
680
+ format_name == "Matroska / WebM" ||
681
+ format_name == "raw H.264 video") {
682
+ filter_name = "h264_mp4toannexb";
683
+ }
684
+ break;
685
+ }
686
+
687
+ case AV_CODEC_ID_HEVC: {
688
+ const std::string format_name =
689
+ container_format->long_name ? container_format->long_name : "";
690
+
691
+ if (format_name == "QuickTime / MOV" ||
692
+ format_name == "FLV (Flash Video)" ||
693
+ format_name == "Matroska / WebM" ||
694
+ format_name == "raw HEVC video") {
695
+ filter_name = "hevc_mp4toannexb";
696
+ }
697
+ break;
698
+ }
699
+ case AV_CODEC_ID_MPEG4: {
700
+ const std::string format_name =
701
+ container_format->name ? container_format->name : "";
702
+ if (format_name == "avi") {
703
+ filter_name = "mpeg4_unpack_bframes";
704
+ }
705
+ break;
706
+ }
707
+
708
+ default:
709
+ // No bitstream filter needed for other codecs
710
+ break;
711
+ }
712
+ }
713
+
714
+ if (filter_name.empty()) {
715
+ // Only initialize BSF if we actually need one
716
+ return;
717
+ }
718
+
719
+ const AVBitStreamFilter* av_bsf = av_bsf_get_by_name(filter_name.c_str());
720
+ STD_TORCH_CHECK(
721
+ av_bsf != nullptr, "Failed to find bitstream filter: ", filter_name);
722
+
723
+ AVBSFContext* av_bsf_context = nullptr;
724
+ int ret_val = av_bsf_alloc(av_bsf, &av_bsf_context);
725
+ STD_TORCH_CHECK(
726
+ ret_val >= AVSUCCESS,
727
+ "Failed to allocate bitstream filter: ",
728
+ get_ffmpeg_error_string_from_error_code(ret_val));
729
+
730
+ bitstream_filter_.reset(av_bsf_context);
731
+
732
+ ret_val = avcodec_parameters_copy(bitstream_filter_->par_in, codec_par);
733
+ STD_TORCH_CHECK(
734
+ ret_val >= AVSUCCESS,
735
+ "Failed to copy codec parameters: ",
736
+ get_ffmpeg_error_string_from_error_code(ret_val));
737
+
738
+ ret_val = av_bsf_init(bitstream_filter_.get());
739
+ STD_TORCH_CHECK(
740
+ ret_val == AVSUCCESS,
741
+ "Failed to initialize bitstream filter: ",
742
+ get_ffmpeg_error_string_from_error_code(ret_val));
743
+ }
744
+
745
+ // This callback is called by the parser within cuvidParseVideoData when there
746
+ // is a change in the stream's properties (like resolution change), as specified
747
+ // by CUVIDEOFORMAT. Particularly (but not just!), this is called at the very
748
+ // start of the stream.
749
+ // TODONVDEC P1: Code below mostly assume this is called only once at the start,
750
+ // we should handle the case of multiple calls. Probably need to flush buffers,
751
+ // etc.
752
+ int BetaCudaDeviceInterface::stream_property_change(
753
+ CUVIDEOFORMAT* video_format) {
754
+ STD_TORCH_CHECK(video_format != nullptr, "Invalid video format");
755
+
756
+ video_format_ = *video_format;
757
+
758
+ if (video_format_.min_num_decode_surfaces == 0) {
759
+ // Same as DALI's fallback
760
+ video_format_.min_num_decode_surfaces = 20;
761
+ }
762
+ // We request 4 more surfaces than the minimum, like in pynvvideocodec
763
+ // (ffmpeg's cuviddec.c adds 3). This should help mitigate a bug where NVCUVID
764
+ // re-uses a decode surface that we haven't yet mapped. See
765
+ // test_nvdec_surface_reuse. 32 is the NVDEC maximum.
766
+ video_format_.min_num_decode_surfaces = static_cast<unsigned char>(
767
+ std::min(video_format_.min_num_decode_surfaces + 4, 32));
768
+
769
+ if (!decoder_) {
770
+ decoder_ = NVDECCache::get_cache(device_).get_decoder(
771
+ &video_format_, surface_format_);
772
+
773
+ if (!decoder_) {
774
+ // TODONVDEC P2: consider re-configuring an existing decoder instead of
775
+ // re-creating one. See docs, see DALI. Re-configuration doesn't seem to
776
+ // be enabled in DALI by default.
777
+ decoder_ = create_decoder(&video_format_, surface_format_);
778
+ }
779
+
780
+ STD_TORCH_CHECK(decoder_, "Failed to get or create decoder");
781
+ }
782
+
783
+ // DALI also returns min_num_decode_surfaces from this function. This
784
+ // instructs the parser to reset its ulMaxNumDecodeSurfaces field to this
785
+ // value.
786
+ return static_cast<int>(video_format_.min_num_decode_surfaces);
787
+ }
788
+
789
+ // Moral equivalent of avcodec_send_packet(). Here, we pass the AVPacket down to
790
+ // the NVCUVID parser.
791
+ int BetaCudaDeviceInterface::send_packet(const AVPacket& packet) {
792
+ CudaContextGuard context_guard(device_.index());
793
+ if (decoding_on_cpu_) {
794
+ return cpu_interface_->send_packet(packet);
795
+ }
796
+
797
+ STD_TORCH_CHECK(
798
+ packet.data && packet.size > 0,
799
+ "sendPacket received an empty packet, this is unexpected, please report.");
800
+
801
+ // `filtered_packet` owns the filtered samples for as long as it's in scope,
802
+ // which covers the parser call below.
803
+ UniqueAVPacket filtered_packet = apply_bsf(packet);
804
+ const AVPacket& packet_to_send = filtered_packet ? *filtered_packet : packet;
805
+
806
+ CUVIDSOURCEDATAPACKET cuvid_packet = {};
807
+ cuvid_packet.payload = packet_to_send.data;
808
+ cuvid_packet.payload_size = packet_to_send.size;
809
+ cuvid_packet.flags = CUVID_PKT_TIMESTAMP;
810
+ cuvid_packet.timestamp = packet_to_send.pts;
811
+
812
+ if (packet_to_send.flags & AV_PKT_FLAG_DISCARD) {
813
+ discarded_timestamps_.insert(cuvid_packet.timestamp);
814
+ }
815
+
816
+ if (track_pts_ourselves_) {
817
+ // Push one entry per displayable frame contained within this packet.
818
+ // Each displayed frame inherits the packet's pts, which is what
819
+ // FFmpeg does too.
820
+ int num_displayed =
821
+ count_vp9_displayed_frames(packet_to_send.data, packet_to_send.size);
822
+ if (num_displayed < 0) {
823
+ num_displayed = 1; // Malformed packet: assume the common case.
824
+ }
825
+ for (int i = 0; i < num_displayed; ++i) {
826
+ pending_pts_.push(packet_to_send.pts);
827
+ }
828
+ }
829
+
830
+ return send_cuvid_packet(cuvid_packet);
831
+ }
832
+
833
+ int BetaCudaDeviceInterface::send_eof_packet() {
834
+ CudaContextGuard context_guard(device_.index());
835
+ if (decoding_on_cpu_) {
836
+ return cpu_interface_->send_eof_packet();
837
+ }
838
+
839
+ CUVIDSOURCEDATAPACKET cuvid_packet = {};
840
+ cuvid_packet.flags = CUVID_PKT_ENDOFSTREAM;
841
+ eof_sent_ = true;
842
+
843
+ return send_cuvid_packet(cuvid_packet);
844
+ }
845
+
846
+ int BetaCudaDeviceInterface::send_cuvid_packet(
847
+ CUVIDSOURCEDATAPACKET& cuvid_packet) {
848
+ CUresult result = cuvidParseVideoData(video_parser_, &cuvid_packet);
849
+ return result == CUDA_SUCCESS ? AVSUCCESS : AVERROR_EXTERNAL;
850
+ }
851
+
852
+ UniqueAVPacket BetaCudaDeviceInterface::apply_bsf(const AVPacket& packet) {
853
+ if (!bitstream_filter_) {
854
+ return nullptr;
855
+ }
856
+
857
+ // av_bsf_send_packet() takes ownership of what it is given: it moves the
858
+ // reference out of the packet, leaving it empty. Our caller only lends us
859
+ // theirs, so send a reference of our own instead.
860
+ UniqueAVPacket input_packet(av_packet_alloc());
861
+ STD_TORCH_CHECK(input_packet != nullptr, "Failed to allocate AVPacket");
862
+ int ret_val = av_packet_ref(input_packet.get(), &packet);
863
+ STD_TORCH_CHECK(
864
+ ret_val >= AVSUCCESS,
865
+ "Failed to reference packet for the bitstream filter: ",
866
+ get_ffmpeg_error_string_from_error_code(ret_val));
867
+
868
+ ret_val = av_bsf_send_packet(bitstream_filter_.get(), input_packet.get());
869
+ STD_TORCH_CHECK(
870
+ ret_val >= AVSUCCESS,
871
+ "Failed to send packet to bitstream filter: ",
872
+ get_ffmpeg_error_string_from_error_code(ret_val));
873
+
874
+ UniqueAVPacket filtered_packet(av_packet_alloc());
875
+ STD_TORCH_CHECK(filtered_packet != nullptr, "Failed to allocate AVPacket");
876
+
877
+ // TODO P1: the docs mention there can theoretically be multiple output
878
+ // packets for a single input, i.e. we may need to call av_bsf_receive_packet
879
+ // more than once. We should figure out whether that applies to the BSF we're
880
+ // using.
881
+ ret_val =
882
+ av_bsf_receive_packet(bitstream_filter_.get(), filtered_packet.get());
883
+ STD_TORCH_CHECK(
884
+ ret_val >= AVSUCCESS,
885
+ "Failed to receive packet from bitstream filter: ",
886
+ get_ffmpeg_error_string_from_error_code(ret_val));
887
+
888
+ return filtered_packet;
889
+ }
890
+
891
+ // Parser triggers this callback within cuvidParseVideoData when a frame is
892
+ // ready to be decoded, i.e. the parser received all the necessary packets for a
893
+ // given frame. It means we can send that frame to be decoded by the hardware
894
+ // NVDEC decoder by calling cuvidDecodePicture.
895
+ int BetaCudaDeviceInterface::frame_ready_for_decoding(
896
+ CUVIDPICPARAMS* pic_params) {
897
+ STD_TORCH_CHECK(pic_params != nullptr, "Invalid picture parameters");
898
+ STD_TORCH_CHECK(decoder_, "Decoder not initialized before picture decode");
899
+ // See the comment about surfaces in stream_property_change().
900
+ for (const auto& queued_frame : ready_frames_) {
901
+ if (queued_frame.picture_index == pic_params->CurrPicIdx &&
902
+ discarded_timestamps_.count(queued_frame.timestamp) == 0) {
903
+ TC_LOG(
904
+ "NVDEC is decoding into surface %d, which still holds the frame with "
905
+ "pts %lld that hasn't been returned yet. That frame will be "
906
+ "returned with the wrong content.",
907
+ pic_params->CurrPicIdx,
908
+ static_cast<long long>(queued_frame.timestamp));
909
+ }
910
+ }
911
+
912
+ // Send frame to be decoded by NVDEC. This may or may not block, depending on
913
+ // the internal state of the NVDEC. Presumably, when it blocks, it gets
914
+ // automatically unblocked once a frame has been decoded, although how and
915
+ // when it happens is unclear. The docs say:
916
+ // > cuvidDecodePicture() will stall if wait queue on NVDEC inside driver is
917
+ // full.
918
+ // and cuviddec.h says:
919
+ // > cuvidDecodePicture may block the calling thread if there are too many
920
+ // pictures pending in the decode queue.
921
+ CUresult result = cuvidDecodePicture(*decoder_.get(), pic_params);
922
+
923
+ // Yes, you're reading that right, 0 means error, 1 means success
924
+ return (result == CUDA_SUCCESS);
925
+ }
926
+
927
+ int BetaCudaDeviceInterface::frame_ready_in_display_order(
928
+ CUVIDPARSERDISPINFO* disp_info) {
929
+ if (track_pts_ourselves_ && !pending_pts_.empty()) {
930
+ disp_info->timestamp = pending_pts_.front();
931
+ pending_pts_.pop();
932
+ }
933
+ ready_frames_.push_back(*disp_info);
934
+ return 1; // success
935
+ }
936
+
937
+ // Moral equivalent of avcodec_receive_frame().
938
+ int BetaCudaDeviceInterface::receive_frame(UniqueAVFrame& av_frame) {
939
+ CudaContextGuard context_guard(device_.index());
940
+ if (decoding_on_cpu_) {
941
+ return cpu_interface_->receive_frame(av_frame);
942
+ }
943
+
944
+ // Drop those packets that were marked as discard. We only wanted to decode
945
+ // those, not to return them.
946
+ while (!ready_frames_.empty() &&
947
+ discarded_timestamps_.erase(ready_frames_.front().timestamp) > 0) {
948
+ ready_frames_.pop_front();
949
+ }
950
+
951
+ if (ready_frames_.empty()) {
952
+ // No frame found, instruct caller to try again later after sending more
953
+ // packets, or to stop if EOF was already sent.
954
+ return eof_sent_ ? AVERROR_EOF : AVERROR(EAGAIN);
955
+ }
956
+
957
+ CUVIDPARSERDISPINFO disp_info = ready_frames_.front();
958
+ ready_frames_.pop_front();
959
+
960
+ CUVIDPROCPARAMS proc_params = {};
961
+ proc_params.progressive_frame = disp_info.progressive_frame;
962
+ proc_params.top_field_first = disp_info.top_field_first;
963
+ proc_params.unpaired_field = disp_info.repeat_first_field < 0;
964
+ // We set the NVDEC stream to the current stream, and remember it: consumers
965
+ // of the mapped surface run later and possibly on a different stream, so they
966
+ // need to know which stream produces the surface's content in order to wait
967
+ // on it.
968
+ // Re types: we get a cudaStream_t from PyTorch but it's interchangeable with
969
+ // CUstream
970
+ nvdec_output_stream_ = get_current_cuda_stream(device_.index());
971
+ proc_params.output_stream = reinterpret_cast<CUstream>(nvdec_output_stream_);
972
+
973
+ CUdeviceptr frame_ptr = 0;
974
+ unsigned int pitch = 0;
975
+
976
+ // We know the frame we want was sent to the hardware decoder, but now we need
977
+ // to "map" it to an "output surface" before we can use its data. This is a
978
+ // blocking calls that waits until the frame is fully decoded and ready to be
979
+ // used.
980
+ // When a frame is mapped to an output surface, it needs to be unmapped
981
+ // eventually, so that the decoder can re-use the output surface. Failing to
982
+ // unmap will cause map to eventually fail. DALI unmaps frames almost
983
+ // immediately after mapping them: they do the color-conversion in-between,
984
+ // which involves a copy of the data, so that works.
985
+ // We, OTOH, will do the color-conversion later, outside of receive_frame().
986
+ // So we unmap here: just before mapping a new frame. At that point the
987
+ // previously-mapped frame has been consumed, or at least its consumption has
988
+ // been enqueued:
989
+ // - With SingleStreamDecoder, that frame was either color-converted (with a
990
+ // copy), or that's a frame that was discarded in SingleStreamDecoder.
991
+ // - With the low-level APIs, the PacketDecoder forces a copy in
992
+ // make_frame_standalone().
993
+ // Those reads are asynchronous, so we must wait on them to finish.
994
+ surface_read_done_.make_stream_wait(nvdec_output_stream_);
995
+ unmap_previous_frame();
996
+ CUresult result = cuvidMapVideoFrame(
997
+ *decoder_.get(),
998
+ disp_info.picture_index,
999
+ &frame_ptr,
1000
+ &pitch,
1001
+ &proc_params);
1002
+ if (result != CUDA_SUCCESS) {
1003
+ return AVERROR_EXTERNAL;
1004
+ }
1005
+ previously_mapped_frame_ = frame_ptr;
1006
+
1007
+ nvdec_surface_ready_.record(nvdec_output_stream_);
1008
+
1009
+ av_frame = convert_cuda_frame_to_av_frame(frame_ptr, pitch, disp_info);
1010
+
1011
+ return AVSUCCESS;
1012
+ }
1013
+
1014
+ void BetaCudaDeviceInterface::record_surface_read(cudaStream_t stream) {
1015
+ // Called by every consumer of the mapped surface, once its read has been
1016
+ // enqueued on `stream`.
1017
+ // This sets the surface_read_done_ event that must be waited upon before
1018
+ // mapping a new frame on the surface.
1019
+ surface_read_done_.record(stream);
1020
+ }
1021
+
1022
+ void BetaCudaDeviceInterface::unmap_previous_frame() {
1023
+ if (previously_mapped_frame_ == 0) {
1024
+ return;
1025
+ }
1026
+ CUresult result =
1027
+ cuvidUnmapVideoFrame(*decoder_.get(), previously_mapped_frame_);
1028
+ STD_TORCH_CHECK(
1029
+ result == CUDA_SUCCESS, "Failed to unmap previous frame: ", result);
1030
+ previously_mapped_frame_ = 0;
1031
+ }
1032
+
1033
+ // Where the display area starts within a plane of the surface, in bytes. See
1034
+ // Note: [NVDEC surface dimensions and cropping].
1035
+ BetaCudaDeviceInterface::CropOffsets BetaCudaDeviceInterface::get_crop_offsets(
1036
+ unsigned int pitch) const {
1037
+ int crop_left = video_format_.display_area.left;
1038
+ int crop_top = video_format_.display_area.top;
1039
+ bool is_444 = is_444_surface_format(surface_format_);
1040
+ STD_TORCH_CHECK(
1041
+ is_444 || (crop_left % 2 == 0 && crop_top % 2 == 0),
1042
+ "Subsampled surface with an odd crop offset (",
1043
+ crop_left,
1044
+ ", ",
1045
+ crop_top,
1046
+ "), this is unexpected, please report.");
1047
+
1048
+ int bytes_per_sample = is_16bit_surface_format(surface_format_) ? 2 : 1;
1049
+ unsigned int luma = crop_top * pitch + crop_left * bytes_per_sample;
1050
+ unsigned int chroma =
1051
+ is_444 ? luma : (crop_top / 2) * pitch + crop_left * bytes_per_sample;
1052
+ return {luma, chroma};
1053
+ }
1054
+
1055
+ UniqueAVFrame BetaCudaDeviceInterface::convert_cuda_frame_to_av_frame(
1056
+ CUdeviceptr frame_ptr,
1057
+ unsigned int pitch,
1058
+ const CUVIDPARSERDISPINFO& disp_info) {
1059
+ STD_TORCH_CHECK(frame_ptr != 0, "Invalid CUDA frame pointer");
1060
+
1061
+ // The surface we're given is the entire coded frame; the frame we hand out is
1062
+ // its display area, which we crop to below by offsetting the planes. See
1063
+ // Note: [NVDEC surface dimensions and cropping].
1064
+ int width =
1065
+ video_format_.display_area.right - video_format_.display_area.left;
1066
+ int height =
1067
+ video_format_.display_area.bottom - video_format_.display_area.top;
1068
+
1069
+ STD_TORCH_CHECK(width > 0 && height > 0, "Invalid frame dimensions");
1070
+ STD_TORCH_CHECK(
1071
+ pitch >= static_cast<unsigned int>(width), "Pitch must be >= width");
1072
+
1073
+ UniqueAVFrame av_frame(av_frame_alloc());
1074
+ STD_TORCH_CHECK(av_frame.get() != nullptr, "Failed to allocate AVFrame");
1075
+
1076
+ av_frame->width = width;
1077
+ av_frame->height = height;
1078
+ av_frame->format = surface_to_pix_fmt(
1079
+ surface_format_,
1080
+ static_cast<int>(video_format_.bit_depth_luma_minus8) + 8);
1081
+ av_frame->pts = disp_info.timestamp;
1082
+
1083
+ // TODONVDEC P2: We compute the duration based on average frame rate info, so
1084
+ // so if the video has variable frame rate, the durations may be off. We
1085
+ // should try to see if we can set the duration more accurately. Unfortunately
1086
+ // it's not given by dispInfo. One option would be to set it based on the pts
1087
+ // difference between consecutive frames, if the next frame is already
1088
+ // available.
1089
+ // Note that we used to rely on videoFormat_.frame_rate for this, but that
1090
+ // proved less accurate than FFmpeg.
1091
+ set_duration(
1092
+ *av_frame,
1093
+ compute_safe_duration(frame_rate_avg_from_ffmpeg_, time_base_));
1094
+
1095
+ // We need to assign the frame colorspace. This is crucial for proper color
1096
+ // conversion. NVCUVID stores that in the matrix_coefficients field, but
1097
+ // doesn't document the semantics of the values. Claude code generated this,
1098
+ // which seems to work. Reassuringly, the values seem to match the
1099
+ // corresponding indices in the FFmpeg enum for colorspace conversion
1100
+ // (ff_yuv2rgb_coeffs):
1101
+ // https://ffmpeg.org/doxygen/trunk/yuv2rgb_8c_source.html#l00047
1102
+ switch (video_format_.video_signal_description.matrix_coefficients) {
1103
+ case 1:
1104
+ av_frame->colorspace = AVCOL_SPC_BT709;
1105
+ break;
1106
+ case 6:
1107
+ av_frame->colorspace = AVCOL_SPC_SMPTE170M; // BT.601
1108
+ break;
1109
+ case 9:
1110
+ av_frame->colorspace = AVCOL_SPC_BT2020_NCL;
1111
+ break;
1112
+ case 10:
1113
+ av_frame->colorspace = AVCOL_SPC_BT2020_CL;
1114
+ break;
1115
+ default:
1116
+ // Default to BT.601
1117
+ av_frame->colorspace = AVCOL_SPC_SMPTE170M;
1118
+ break;
1119
+ }
1120
+
1121
+ av_frame->color_range =
1122
+ video_format_.video_signal_description.video_full_range_flag
1123
+ ? AVCOL_RANGE_JPEG
1124
+ : AVCOL_RANGE_MPEG;
1125
+
1126
+ // Unlike matrix_coefficients above, these two are plain H.273 code points,
1127
+ // and FFmpeg's enums are defined to those same values, so they carry over
1128
+ // directly. A value outside the enum ends up named "unknown" rather than
1129
+ // mis-tagged, because av_color_*_name() returns nullptr for it.
1130
+ av_frame->color_primaries = static_cast<AVColorPrimaries>(
1131
+ video_format_.video_signal_description.color_primaries);
1132
+ av_frame->color_trc = static_cast<AVColorTransferCharacteristic>(
1133
+ video_format_.video_signal_description.transfer_characteristics);
1134
+
1135
+ // NVDEC stacks the planes of the coded frame in a single allocation, all with
1136
+ // the same pitch, so consecutive planes start plane_stride bytes apart.
1137
+ // NVIDIA's own NvDecoder addresses the chroma plane the same way:
1138
+ // dpSrcFrame + srcPitch * ((surface_height + 1) & ~1).
1139
+ unsigned int plane_stride = pitch * round_up_to_even(surface_height());
1140
+ bool is_444 = is_444_surface_format(surface_format_);
1141
+
1142
+ CropOffsets crop_offsets = get_crop_offsets(pitch);
1143
+ auto plane = [&](unsigned int index, unsigned int crop_offset) {
1144
+ return reinterpret_cast<uint8_t*>(
1145
+ frame_ptr + (plane_stride * index) + crop_offset);
1146
+ };
1147
+
1148
+ av_frame->data[0] = plane(0, crop_offsets.luma);
1149
+ av_frame->data[1] = plane(1, crop_offsets.chroma);
1150
+ av_frame->data[2] = is_444 ? plane(2, crop_offsets.chroma) : nullptr;
1151
+ av_frame->data[3] = nullptr;
1152
+ STD_TORCH_CHECK(
1153
+ pitch <= static_cast<unsigned int>(std::numeric_limits<int>::max()),
1154
+ "NVDEC returned a pitch of ",
1155
+ pitch,
1156
+ " bytes, which doesn't fit in an AVFrame line size. This should never "
1157
+ "happen, please report.");
1158
+ av_frame->linesize[0] = static_cast<int>(pitch);
1159
+ av_frame->linesize[1] = static_cast<int>(pitch);
1160
+ av_frame->linesize[2] = is_444 ? static_cast<int>(pitch) : 0;
1161
+ av_frame->linesize[3] = 0;
1162
+
1163
+ return av_frame;
1164
+ }
1165
+
1166
+ void BetaCudaDeviceInterface::make_frame_standalone(UniqueAVFrame& av_frame) {
1167
+ // Make the frame standalone, i.e. safely consumable by a user or by a
1168
+ // ColorConverter (potentially a different CUDA stream):
1169
+ // - GPU frames are copied: we copy the frame data so that its surface can be
1170
+ // unmapped in
1171
+ // receive_frame() without losing the data.
1172
+ // - CPU-fallback frames are uploaded here too, so that a PacketDecoder always
1173
+ // hands out frames that live on its own device.
1174
+ // Both are enqueued on the caller's current stream (of
1175
+ // PacketDecoder.decode()) and are async. It's up to the consumer to properly
1176
+ // sync, see our `cuda_streams.py` tutorial.
1177
+ STD_TORCH_CHECK(
1178
+ mode() == Mode::DecoderOnly,
1179
+ "make_frame_standalone() is only valid in decoder-only mode: standalone "
1180
+ "frames are meant to be consumed by a separate ColorConverter.");
1181
+ CudaContextGuard context_guard(device_.index());
1182
+ cudaStream_t current_stream = get_current_cuda_stream(device_.index());
1183
+
1184
+ torch::stable::Tensor storage;
1185
+ if (decoding_on_cpu_) {
1186
+ auto uploaded = upload_cpu_frame_to_gpu(*av_frame, current_stream);
1187
+ av_frame = std::move(uploaded.av_frame);
1188
+ storage = std::move(uploaded.storage);
1189
+ } else {
1190
+ storage = copy_nvdec_surface(av_frame, current_stream);
1191
+ }
1192
+
1193
+ auto attached_data = new OwnedFrameStorage();
1194
+ attached_data->storage = std::move(storage);
1195
+ av_frame->opaque_ref = av_buffer_create(
1196
+ reinterpret_cast<uint8_t*>(attached_data),
1197
+ sizeof(OwnedFrameStorage),
1198
+ standalone_frame_free_callback,
1199
+ nullptr,
1200
+ 0);
1201
+ STD_TORCH_CHECK(
1202
+ av_frame->opaque_ref != nullptr,
1203
+ "Failed to attach standalone frame data");
1204
+ }
1205
+
1206
+ std::optional<torch::stable::Tensor> BetaCudaDeviceInterface::get_frame_storage(
1207
+ const AVFrame& av_frame) const {
1208
+ STD_TORCH_CHECK(
1209
+ // Only decoder-only should reach here, and this should only be called on
1210
+ // frames that went through make_frame_standalone(), which sets
1211
+ // opaque_ref.
1212
+ mode() == Mode::DecoderOnly && av_frame.opaque_ref != nullptr,
1213
+ "Unexpected call to get_frame_storage(), please report a bug ");
1214
+
1215
+ return reinterpret_cast<OwnedFrameStorage*>(av_frame.opaque_ref->data)
1216
+ ->storage;
1217
+ }
1218
+
1219
+ torch::stable::Tensor BetaCudaDeviceInterface::copy_nvdec_surface(
1220
+ UniqueAVFrame& av_frame,
1221
+ cudaStream_t current_stream) {
1222
+ // The amount of bytes an NV12 image takes is:
1223
+ // num_bytes = len(Y) + len(UV)
1224
+ // = num_pixels + num_pixels / 2
1225
+ // = num_pixels * 3 / 2
1226
+ //
1227
+ // where num_pixels = pitch * num_luma_plane_rows, not width * height: the
1228
+ // pitch accounts for both the row padding and the data size (uint8 vs
1229
+ // uint16), and NVDEC rounds the Y plane's row count up to even. A 4:4:4
1230
+ // surface has two full-size chroma planes instead of one half-height one, so
1231
+ // it's num_pixels * 3.
1232
+ int64_t num_luma_plane_rows =
1233
+ static_cast<int64_t>(round_up_to_even(surface_height()));
1234
+ int64_t pitch = static_cast<int64_t>(av_frame->linesize[0]);
1235
+ bool is_444 = is_444_surface_format(surface_format_);
1236
+ int64_t num_bytes = is_444 ? pitch * num_luma_plane_rows * 3
1237
+ : pitch * num_luma_plane_rows * 3 / 2;
1238
+
1239
+ auto* surface_base = av_frame->data[0] -
1240
+ get_crop_offsets(static_cast<unsigned int>(pitch)).luma;
1241
+
1242
+ auto storage =
1243
+ torch::stable::empty({num_bytes}, kStableUInt8, std::nullopt, device_);
1244
+
1245
+ // The surface's content is produced by the mapping post-processing that
1246
+ // receive_frame() enqueued on nvdec_output_stream_, which isn't necessarily
1247
+ // the stream we're copying on.
1248
+ nvdec_surface_ready_.make_stream_wait(current_stream);
1249
+
1250
+ cudaError_t err = cudaMemcpyAsync(
1251
+ storage.mutable_data_ptr(),
1252
+ surface_base,
1253
+ static_cast<size_t>(num_bytes),
1254
+ cudaMemcpyDeviceToDevice,
1255
+ current_stream);
1256
+ STD_TORCH_CHECK(
1257
+ err == cudaSuccess,
1258
+ "Failed to copy NVDEC surface: ",
1259
+ cudaGetErrorString(err));
1260
+
1261
+ // The copy is async, so the next mapping must be ordered after it.
1262
+ record_surface_read(current_stream);
1263
+
1264
+ // Re-point the planes into the copy, preserving where they were within the
1265
+ // surface: those offsets encode both the plane layout and the display area
1266
+ // crop.
1267
+ auto* storage_base = static_cast<uint8_t*>(storage.mutable_data_ptr());
1268
+ int num_planes = is_444 ? 3 : 2;
1269
+ for (int i = 0; i < num_planes; ++i) {
1270
+ av_frame->data[i] = storage_base + (av_frame->data[i] - surface_base);
1271
+ }
1272
+
1273
+ return storage;
1274
+ }
1275
+
1276
+ void BetaCudaDeviceInterface::flush() {
1277
+ CudaContextGuard context_guard(device_.index());
1278
+ if (decoding_on_cpu_) {
1279
+ cpu_interface_->flush();
1280
+ return;
1281
+ }
1282
+
1283
+ // The NVCUVID docs mention that after seeking, i.e. when flush() is called,
1284
+ // we should send a packet with the CUVID_PKT_DISCONTINUITY flag. The docs
1285
+ // don't say whether this should be an empty packet, or whether it should be
1286
+ // a flag on the next non-empty packet. It doesn't matter: neither work :)
1287
+ // Sending an EOF packet, however, does work. So we do that. And we re-set
1288
+ // the eofSent_ flag to false because that's not a true EOF notification.
1289
+ send_eof_packet();
1290
+ eof_sent_ = false;
1291
+
1292
+ ready_frames_.clear();
1293
+ discarded_timestamps_.clear();
1294
+
1295
+ std::queue<int64_t> empty_pts;
1296
+ std::swap(pending_pts_, empty_pts);
1297
+
1298
+ send_seqhdr_packet();
1299
+ }
1300
+
1301
+ GpuFrameAndStorage BetaCudaDeviceInterface::upload_cpu_frame_to_gpu(
1302
+ const AVFrame& cpu_frame,
1303
+ cudaStream_t stream) {
1304
+ // This is called in the context of the CPU fallback: the frame was decoded
1305
+ // on the CPU, and in this function we convert that frame into a format we
1306
+ // can color-convert on the GPU, and send it there.
1307
+ // We do that in 2 steps:
1308
+ // - First we convert the input CPU frame into an intermediate CPU frame in
1309
+ // the target format using sws_scale.
1310
+ // - Then we allocate GPU memory and copy the CPU frame to the GPU on the
1311
+ // given stream.
1312
+ // We return the new AVFrame and its associated GPU storage so that the caller
1313
+ // can handle the memory lifetime. The GPU storage is a torch
1314
+ // Tensor because we want to rely on the torch CUDA allocator.
1315
+
1316
+ const AVPixFmtDescriptor* source_desc =
1317
+ av_pix_fmt_desc_get(static_cast<AVPixelFormat>(cpu_frame.format));
1318
+ STD_TORCH_CHECK(
1319
+ source_desc != nullptr, "Unknown pixel format on decoded frame");
1320
+ int source_bit_depth = source_desc->comp[0].depth;
1321
+
1322
+ // We convert to a format our CUDA color-conversion kernels can read, keeping
1323
+ // the source's chroma and bit depth: 4:2:0 and monochrome go semi-planar,
1324
+ // everything else (4:2:2, 4:1:1, RGB, ...) goes 4:4:4, which is the only
1325
+ // other layout the kernels handle and never reduces chroma. Unlike the decode
1326
+ // path we're not choosing between what NVDEC happens to offer, so the
1327
+ // requested output dtype doesn't come into it: narrowing to uint8, if that's
1328
+ // what was asked for, happens after color conversion.
1329
+ // We go through a cudaVideoSurfaceFormat because that's what
1330
+ // surface_to_pix_fmt, and we need to call that because of the
1331
+ // FFmpeg-version-dependent P012 vs P016 distinction (sad).
1332
+ bool semi_planar_420 = source_desc->nb_components == 1 ||
1333
+ (source_desc->log2_chroma_w == 1 && source_desc->log2_chroma_h == 1);
1334
+ bool want_16bit = source_bit_depth > 8;
1335
+
1336
+ cudaVideoSurfaceFormat surface_format;
1337
+ if (semi_planar_420) {
1338
+ surface_format =
1339
+ want_16bit ? cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
1340
+ } else {
1341
+ surface_format = want_16bit ? cudaVideoSurfaceFormat_YUV444_16Bit
1342
+ : cudaVideoSurfaceFormat_YUV444;
1343
+ }
1344
+ AVPixelFormat target_pix_fmt =
1345
+ surface_to_pix_fmt(surface_format, source_bit_depth);
1346
+
1347
+ int num_planes = semi_planar_420 ? 2 : 3;
1348
+ int bytes_per_sample = want_16bit ? 2 : 1;
1349
+
1350
+ // The 4:2:0 kernel works on 2x2 blocks and never writes a trailing odd row or
1351
+ // column, so its input planes must be even-sized. We allocate the buffer with
1352
+ // even dimensions but keep the frame's real width and height, exactly like
1353
+ // the even-sized surfaces NVDEC hands us for odd-sized videos: the pad
1354
+ // row/column is only read as part of a boundary block, and the color
1355
+ // conversion crops it away. Nothing about the pixel format itself requires
1356
+ // this: FFmpeg is happy with odd-sized 4:2:0 frames. The 4:4:4 kernel is
1357
+ // per-pixel, so those need no padding.
1358
+ int width = cpu_frame.width;
1359
+ int height = cpu_frame.height;
1360
+ int padded_width = semi_planar_420 ? round_up_to_even(width) : width;
1361
+ int padded_height = semi_planar_420 ? round_up_to_even(height) : height;
1362
+
1363
+ UniqueAVFrame intermediate_cpu_frame(av_frame_alloc());
1364
+ STD_TORCH_CHECK(
1365
+ intermediate_cpu_frame != nullptr,
1366
+ "Failed to allocate intermediate CPU frame");
1367
+
1368
+ intermediate_cpu_frame->format = target_pix_fmt;
1369
+ intermediate_cpu_frame->width = padded_width;
1370
+ intermediate_cpu_frame->height = padded_height;
1371
+
1372
+ int ret = av_frame_get_buffer(intermediate_cpu_frame.get(), 0);
1373
+ STD_TORCH_CHECK(
1374
+ ret >= 0,
1375
+ "Failed to allocate intermediate CPU frame buffer: ",
1376
+ get_ffmpeg_error_string_from_error_code(ret));
1377
+
1378
+ // Source and destination dimensions are the same: this is a pixel format
1379
+ // conversion, not a rescale. sws_scale() writes into the even-sized buffer
1380
+ // allocated above but only fills the real width and height.
1381
+ SwsConfig sws_config{
1382
+ .input_width = width,
1383
+ .input_height = height,
1384
+ .input_format = static_cast<AVPixelFormat>(cpu_frame.format),
1385
+ .input_colorspace = cpu_frame.colorspace,
1386
+ .output_width = width,
1387
+ .output_height = height,
1388
+ .output_format = target_pix_fmt,
1389
+ // We have to tell swscale to respect the source's color range because
1390
+ // we're converting to a YUV format, and by default, swscale would assume
1391
+ // limited range only.
1392
+ .output_color_range = cpu_frame.color_range};
1393
+
1394
+ if (!sws_context_ || prev_sws_config_ != sws_config) {
1395
+ // Nothing is rescaled here, so the flags only defines how chroma is
1396
+ // resampled, which happens when the source is subsampled more finely than
1397
+ // the target surface (4:2:2 into 4:4:4, say). SWS_POINT replicates the
1398
+ // chroma, which is what we want here. SWS_BILINEAR would interpolate it,
1399
+ // leading to results that aren't as close to the CPU ref.
1400
+ sws_context_ = create_sws_context(sws_config, SWS_POINT);
1401
+ prev_sws_config_ = sws_config;
1402
+ }
1403
+
1404
+ int converted_height = sws_scale(
1405
+ sws_context_.get(),
1406
+ cpu_frame.data,
1407
+ cpu_frame.linesize,
1408
+ 0,
1409
+ height,
1410
+ intermediate_cpu_frame->data,
1411
+ intermediate_cpu_frame->linesize);
1412
+ STD_TORCH_CHECK(
1413
+ converted_height == height,
1414
+ "sws_scale failed for the CPU-fallback upload conversion");
1415
+
1416
+ // The chroma plane of a semi-planar 4:2:0 frame carries interleaved UV pairs,
1417
+ // so it's as wide as the luma plane but half as tall.
1418
+ int row_bytes = padded_width * bytes_per_sample;
1419
+ int plane_heights[3] = {
1420
+ padded_height,
1421
+ semi_planar_420 ? padded_height / 2 : padded_height,
1422
+ padded_height};
1423
+
1424
+ int64_t plane_offsets[3] = {0, 0, 0};
1425
+ int64_t total_bytes = 0;
1426
+ for (int p = 0; p < num_planes; ++p) {
1427
+ plane_offsets[p] = total_bytes;
1428
+ total_bytes += static_cast<int64_t>(row_bytes) * plane_heights[p];
1429
+ }
1430
+
1431
+ CudaContextGuard context_guard(device_.index());
1432
+ auto storage =
1433
+ torch::stable::empty({total_bytes}, kStableUInt8, std::nullopt, device_);
1434
+ auto storage_ptr = static_cast<uint8_t*>(storage.mutable_data_ptr());
1435
+
1436
+ UniqueAVFrame gpu_frame(av_frame_alloc());
1437
+ STD_TORCH_CHECK(gpu_frame != nullptr, "Failed to allocate GPU AVFrame");
1438
+
1439
+ gpu_frame->format = target_pix_fmt;
1440
+ gpu_frame->width = width;
1441
+ gpu_frame->height = height;
1442
+
1443
+ // One copy per plane: av_frame_get_buffer() allocates each plane with its own
1444
+ // alignment padding, so they are neither contiguous with each other nor
1445
+ // packed, and each has its own height.
1446
+ for (int p = 0; p < num_planes; ++p) {
1447
+ gpu_frame->data[p] = storage_ptr + plane_offsets[p];
1448
+ gpu_frame->linesize[p] = row_bytes;
1449
+
1450
+ // Note that we use cudaMemcpy2DAsync here instead of cudaMemcpyAsync
1451
+ // because the linesizes (strides) may be different than the widths for the
1452
+ // input CPU frame. That's precisely what the 2D variants are for.
1453
+ cudaError_t err = cudaMemcpy2DAsync(
1454
+ gpu_frame->data[p],
1455
+ gpu_frame->linesize[p],
1456
+ intermediate_cpu_frame->data[p],
1457
+ intermediate_cpu_frame->linesize[p],
1458
+ row_bytes,
1459
+ plane_heights[p],
1460
+ cudaMemcpyHostToDevice,
1461
+ stream);
1462
+ STD_TORCH_CHECK(
1463
+ err == cudaSuccess,
1464
+ "Failed to copy plane ",
1465
+ p,
1466
+ " to GPU: ",
1467
+ cudaGetErrorString(err));
1468
+ }
1469
+
1470
+ // intermediate_cpu_frame is freed when this function returns, so we can't
1471
+ // leave the copies in flight, we must wait for it to finish. Making the
1472
+ // upload truly async would mean allocating the intermediate frame in pinned
1473
+ // memory and keeping it alive until the copies complete. Probably not worth
1474
+ // it for this CPU fallback path that is already slow by nature.
1475
+ cudaError_t err = cudaStreamSynchronize(stream);
1476
+ STD_TORCH_CHECK(
1477
+ err == cudaSuccess,
1478
+ "Failed to wait for the CPU-to-GPU upload: ",
1479
+ cudaGetErrorString(err));
1480
+
1481
+ ret = av_frame_copy_props(gpu_frame.get(), &cpu_frame);
1482
+ STD_TORCH_CHECK(
1483
+ ret >= 0,
1484
+ "Failed to copy frame properties: ",
1485
+ get_ffmpeg_error_string_from_error_code(ret));
1486
+
1487
+ // The input CPU frame might be AVCOL_SPC_RGB, and the GPU frame we just
1488
+ // produced is YUV. We set the colorspace of the GPU frame to BT.601, which is
1489
+ // (hopefully??) what libswscale assumed. The alternative would be to let the
1490
+ // GPU frame describe "RGB" as its colorspace which is probably more wrong.
1491
+ if (cpu_frame.colorspace == AVCOL_SPC_RGB) {
1492
+ gpu_frame->colorspace = AVCOL_SPC_SMPTE170M;
1493
+ }
1494
+
1495
+ return {std::move(gpu_frame), std::move(storage)};
1496
+ }
1497
+
1498
+ void BetaCudaDeviceInterface::convert_av_frame_to_frame_output(
1499
+ const AVFrame& av_frame,
1500
+ FrameOutput& frame_output,
1501
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor) {
1502
+ CudaContextGuard context_guard(device_.index());
1503
+ cudaStream_t current_stream = get_current_cuda_stream(device_.index());
1504
+
1505
+ // We may need to upload a frame here in case of the CPU fallback. This is
1506
+ // only needed in Both() mode i.e. with the SingleStreamDecoder. The reason we
1507
+ // do it here and not just after decoding is because the `decode_av_frame()`
1508
+ // loop of the SingleStreamDecoder may discard frames while decoding forward
1509
+ // to a target pts - we don't want to upload these frames that will be
1510
+ // discarded anyway. So we upload as late as possible for those frame we
1511
+ // *know* we must return.
1512
+ //
1513
+ // In contrast, a PacketDecoder will always upload CPU frames before retuning
1514
+ // them because its contract is to respect its device parameter.
1515
+ bool needs_upload = mode() == Mode::Both && decoding_on_cpu_;
1516
+
1517
+ // `uploaded` owns the GPU buffer for as long as it's in scope, which covers
1518
+ // the color conversion below.
1519
+ GpuFrameAndStorage uploaded;
1520
+ if (needs_upload) {
1521
+ uploaded = upload_cpu_frame_to_gpu(av_frame, current_stream);
1522
+ }
1523
+ const AVFrame& gpu_frame = needs_upload ? *uploaded.av_frame : av_frame;
1524
+
1525
+ // Both NVDEC surfaces and uploaded CPU frames may be backed by even-sized
1526
+ // buffers while describing an odd-sized frame; the color conversion crops the
1527
+ // padding away.
1528
+ FrameDims output_dims(gpu_frame.height, gpu_frame.width);
1529
+
1530
+ auto gpu_pix_fmt = static_cast<AVPixelFormat>(gpu_frame.format);
1531
+ STD_TORCH_CHECK(
1532
+ is_expected_pix_fmt_from_nvdec(gpu_pix_fmt),
1533
+ "Expected a pixel format we can color-convert on the GPU, got ",
1534
+ av_get_pix_fmt_name(gpu_pix_fmt));
1535
+
1536
+ if (mode() == Mode::ColorConverterOnly) {
1537
+ STD_TORCH_CHECK(
1538
+ gpu_frame.opaque_ref != nullptr,
1539
+ "ColorConverter received a non-standalone frame; frames fed to a "
1540
+ "standalone ColorConverter must come from a PacketDecoder.");
1541
+ } else {
1542
+ STD_TORCH_CHECK(
1543
+ mode() == Mode::Both,
1544
+ "Color conversion requires the interface to be initialized for color "
1545
+ "conversion.");
1546
+ if (!needs_upload) {
1547
+ // The frame is a mapped NVDEC surface, whose content is produced by the
1548
+ // mapping post-processing that receive_frame() enqueued on
1549
+ // nvdec_output_stream_. An uploaded frame, on the other hand, was
1550
+ // uploaded on current_stream and needs no ordering.
1551
+ // TODO_API_BREAKDOWN CC P2: do we still need this?? We don't do any sync
1552
+ // on behalf of the user anymore for the low-level APIs (see
1553
+ // https://github.com/meta-pytorch/torchcodec/pull/1749) - so why here??
1554
+ nvdec_surface_ready_.make_stream_wait(current_stream);
1555
+ }
1556
+ }
1557
+
1558
+ auto convert_frame = [&](std::optional<torch::stable::Tensor> pre_alloc)
1559
+ -> torch::stable::Tensor {
1560
+ return convert_yuv_frame_to_rgb(
1561
+ gpu_frame,
1562
+ device_,
1563
+ current_stream,
1564
+ pre_alloc,
1565
+ output_dims,
1566
+ static_cast<AVPixelFormat>(gpu_frame.format),
1567
+ cached_color_matrix_);
1568
+ };
1569
+
1570
+ if (rotation_ == Rotation::NONE) {
1571
+ validate_pre_allocated_tensor_shape(
1572
+ pre_allocated_output_tensor, output_dims);
1573
+ frame_output.data = convert_frame(pre_allocated_output_tensor);
1574
+ } else {
1575
+ // preAllocatedOutputTensor has post-rotation dimensions, but the
1576
+ // conversion outputs pre-rotation dimensions, so we can't use it as the
1577
+ // conversion destination or validate it against the frame shape.
1578
+ // Once we support native transforms on the NVDEC CUDA interface,
1579
+ // rotation should be handled as part of the transform pipeline instead.
1580
+ frame_output.data = convert_frame(/*preAlloc=*/std::nullopt);
1581
+ apply_rotation(frame_output, pre_allocated_output_tensor);
1582
+ }
1583
+
1584
+ if (mode() == Mode::Both && !needs_upload) {
1585
+ // The conversion read the mapped surface directly, and did so
1586
+ // asynchronously, so the next mapping must be ordered after it.
1587
+ // This is only needed in Both() mode because in ColorConverterOnly() mode,
1588
+ // the frame is already standalone and doesn't come from the mapped surface.
1589
+ // It's also only needed in the non-fallback mode (needs_upload is false)
1590
+ // because with the fallback, the GPU frame is a copy of the CPU frame, so
1591
+ // the mapped surface isn't read at all.
1592
+ record_surface_read(current_stream);
1593
+ }
1594
+ }
1595
+
1596
+ void BetaCudaDeviceInterface::apply_rotation(
1597
+ FrameOutput& frame_output,
1598
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor) {
1599
+ frame_output.data = rotate_hwc_tensor(frame_output.data, rotation_);
1600
+
1601
+ if (pre_allocated_output_tensor.has_value()) {
1602
+ torch::stable::copy_(
1603
+ pre_allocated_output_tensor.value(), frame_output.data);
1604
+ frame_output.data = pre_allocated_output_tensor.value();
1605
+ }
1606
+ }
1607
+
1608
+ OutputDtype BetaCudaDeviceInterface::get_pre_allocation_dtype(
1609
+ [[maybe_unused]] OutputDtype requested_dtype) const {
1610
+ if (decoding_on_cpu_) {
1611
+ // the upload keeps the source's own depth, see upload_cpu_frame_to_gpu().
1612
+ const AVPixFmtDescriptor* desc =
1613
+ av_pix_fmt_desc_get(codec_context_->pix_fmt);
1614
+ bool is_16bit = desc != nullptr && desc->comp[0].depth > 8;
1615
+ return is_16bit ? OutputDtype::FLOAT32 : OutputDtype::UINT8;
1616
+ } else {
1617
+ return is_16bit_surface_format(surface_format_) ? OutputDtype::FLOAT32
1618
+ : OutputDtype::UINT8;
1619
+ }
1620
+ }
1621
+
1622
+ std::string BetaCudaDeviceInterface::get_details() {
1623
+ std::string details = "NVDEC CUDA Device Interface.";
1624
+ if (decoding_on_cpu_) {
1625
+ details += " Using CPU fallback.";
1626
+ if (!nvcuvid_available_) {
1627
+ details += " NVCUVID not available!";
1628
+ }
1629
+ } else {
1630
+ details += " Using NVDEC.";
1631
+ }
1632
+ return details;
1633
+ }
1634
+
1635
+ } // namespace facebook::torchcodec