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,638 @@
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 "DecodeJpegCuda.h"
8
+
9
+ #include <torch/csrc/stable/ops.h>
10
+ #include <torch/headeronly/util/Exception.h>
11
+
12
+ #include "StableABICompat.h"
13
+
14
+ #if !TORCHCODEC_ENABLE_NVJPEG
15
+
16
+ namespace facebook::torchcodec {
17
+
18
+ std::vector<torch::stable::Tensor> decode_jpegs_cuda(
19
+ [[maybe_unused]] std::vector<torch::stable::Tensor> encoded_images,
20
+ [[maybe_unused]] int64_t mode,
21
+ [[maybe_unused]] torch::stable::Device device) {
22
+ STD_TORCH_CHECK(
23
+ false,
24
+ "decode_jpeg: torchcodec was not compiled with nvJPEG support, so JPEG "
25
+ "images cannot be decoded on a CUDA device. Rebuild torchcodec with "
26
+ "ENABLE_CUDA=1 and TORCHCODEC_BUILD_NVJPEG=1. If you see this error in a "
27
+ "prebuilt wheel, please report it to the TorchCodec repo.");
28
+ }
29
+
30
+ } // namespace facebook::torchcodec
31
+
32
+ #else
33
+
34
+ #include <cstring>
35
+
36
+ #include "CUDACommon.h"
37
+ #include "Cache.h"
38
+ #include "Exif.h"
39
+ #include "ImageCommon.h"
40
+
41
+ namespace facebook::torchcodec {
42
+
43
+ // number of cores / nvdec
44
+ //
45
+ //
46
+ // There are two main paths for decoding JPEGs with nvJPEG: the hardware path
47
+ // (which uses the built-in silicon 'fixed function' JPEG engine), and the
48
+ // software path with will use a mix of CPU and GPU kernels (the software path
49
+ // is NOT CPU-only). The software path has 'backends' which determine how to
50
+ // split the work between CPU and GPU.
51
+ //
52
+ // In our implementation, we try to use the HW path if it's available via
53
+ // nvjpegDecodeBatched(), and we fallback to the SW path with the 'default
54
+ // backend' if HW isn't available, or for those (typically progressive) JPEGs
55
+ // that the HW path doesn't support.
56
+ //
57
+ // A few things worth nothing:
58
+ // - Not super clear from the docs, but nvjpegDecodeBatched() seems to be the
59
+ // only
60
+ // entry-point for the HW path.
61
+ // - nvjpegDecode(), which we use for the SW path, does not seem to support the
62
+ // HW path (but we don't need it to)
63
+ // - Calling nvjpegDecodeBatched() on batch_size is much faster than calling it
64
+ // N times on batch_size // N. This justifies why we publicly expose a batched
65
+ // API and batched inputs.
66
+ // - Even for a single image, calling nvjpegDecodeBatched() is not slower than
67
+ // the SW path, so there's no reason to have a smart dispatching logic based
68
+ // on batch size. We always route through the HW path when we can.
69
+
70
+ using namespace exif_private;
71
+
72
+ namespace {
73
+
74
+ // Scan a JPEG bitstream for the APP1/EXIF segment and return its orientation.
75
+ // On the CPU jpeg decoder, we rely on libjpeg for that. Here, we have to parse
76
+ // it ourselves.
77
+ ExifOrientation fetch_exif_orientation_from_jpeg_bytes(
78
+ const unsigned char* jpeg,
79
+ size_t size) {
80
+ constexpr unsigned char MARKER_PREFIX = 0xFF;
81
+ constexpr unsigned char SOI = 0xD8;
82
+ constexpr unsigned char SOS = 0xDA; // start of scan: no more metadata markers
83
+ constexpr unsigned char EOI = 0xD9;
84
+ constexpr unsigned char APP1 = 0xE1;
85
+ constexpr size_t exif_header_size = 6; // "Exif\0\0"
86
+
87
+ if (size < 2 || jpeg[0] != MARKER_PREFIX || jpeg[1] != SOI) {
88
+ return ExifOrientation::Unspecified;
89
+ }
90
+
91
+ size_t pos = 2;
92
+ while (pos + 4 <= size && jpeg[pos] == MARKER_PREFIX) {
93
+ unsigned char marker = jpeg[pos + 1];
94
+ if (marker == SOS || marker == EOI) {
95
+ break;
96
+ }
97
+ // Segment length is big-endian and includes the 2 length bytes themselves.
98
+ size_t segment_length =
99
+ (size_t(jpeg[pos + 2]) << 8) | size_t(jpeg[pos + 3]);
100
+ if (segment_length < 2 || pos + 2 + segment_length > size) {
101
+ break;
102
+ }
103
+
104
+ if (marker == APP1 && segment_length >= 2 + exif_header_size) {
105
+ const unsigned char* payload = jpeg + pos + 4;
106
+ if (std::memcmp(payload, "Exif\0\0", exif_header_size) == 0) {
107
+ return fetch_exif_orientation_after_prefixes(
108
+ payload, segment_length - 2);
109
+ }
110
+ }
111
+ pos += 2 + segment_length;
112
+ }
113
+ return ExifOrientation::Unspecified;
114
+ }
115
+
116
+ // We cache decoder objects for the same reason we cache NVDEC decoders: they're
117
+ // expensive to create and destroy. To determine the ideal cache size, I ran
118
+ // benchmarks on a A100 where each thread calls its own decode_jpeg():
119
+ // - The best throughput is achieved when num_threads ==
120
+ // kMaxCachedDecodersPerDevice. As soon as num_threads >
121
+ // kMaxCachedDecodersPerDevice, throughput collapses sharply, because the cost
122
+ // of creating a new decoder is so prohibitive.
123
+ // - Provided the batch size is large enough, num_threads=1 in the HW path is
124
+ // pretty close to the roofline already (~6k fps @ 720p) because
125
+ // jpegDecodeBatched() will dispatch to the jpeg cores itself. So the benefits
126
+ // of multithreading the jpeg decoding is small-ish anyway.
127
+ //
128
+ // One decoder takes <30Mb of GPU memory and RAM, so it's fairly cheap. Since
129
+ // the downside of not being able to cache a decoder is so high, we allow a
130
+ // generous amount of decoders in the cache. This isn't exposed for now, it
131
+ // probably shouldn't be.
132
+ constexpr int kMaxCachedDecodersPerDevice = 32;
133
+
134
+ PerGpuCache<CUDAJpegDecoder>& decoder_cache() {
135
+ // Intentionally leaked (allocated with new, never freed) to avoid calling
136
+ // into CUDA/nvJPEG during static destruction, when the CUDA runtime may
137
+ // already be torn down (same reasoning as NVDECCache): the cached decoders'
138
+ // destructors call nvjpegDestroy, which we must not run at process exit.
139
+ static auto* cache = new PerGpuCache<CUDAJpegDecoder>(
140
+ MAX_CUDA_GPUS, kMaxCachedDecodersPerDevice);
141
+ return *cache;
142
+ }
143
+
144
+ } // namespace
145
+
146
+ std::vector<torch::stable::Tensor> decode_jpegs_cuda(
147
+ std::vector<torch::stable::Tensor> encoded_images,
148
+ int64_t mode,
149
+ torch::stable::Device device) {
150
+ STD_TORCH_CHECK(
151
+ device.is_cuda(), "Expected the device parameter to be a cuda device");
152
+ STD_TORCH_CHECK(
153
+ !encoded_images.empty(), "Expected at least one image to decode");
154
+
155
+ std::vector<torch::stable::Tensor> contig_images;
156
+ contig_images.reserve(encoded_images.size());
157
+ std::vector<ExifOrientation> orientations;
158
+ orientations.reserve(encoded_images.size());
159
+
160
+ for (const auto& encoded_image : encoded_images) {
161
+ auto contig = validate_encoded_data(encoded_image);
162
+ orientations.push_back(fetch_exif_orientation_from_jpeg_bytes(
163
+ contig.const_data_ptr<uint8_t>(), contig.numel()));
164
+ contig_images.push_back(std::move(contig));
165
+ }
166
+
167
+ int device_index = get_device_index(device);
168
+ StableDeviceGuard device_guard(device_index);
169
+
170
+ cudaStream_t current_stream = get_current_cuda_stream(device_index);
171
+
172
+ PerGpuCache<CUDAJpegDecoder>& cache = decoder_cache();
173
+ std::unique_ptr<CUDAJpegDecoder> decoder = cache.get(device);
174
+ if (decoder == nullptr) {
175
+ decoder = std::make_unique<CUDAJpegDecoder>(device);
176
+ }
177
+
178
+ std::vector<torch::stable::Tensor> output = decoder->decode_images(
179
+ contig_images, static_cast<ImageReadMode>(mode), current_stream);
180
+ cache.add_if_cache_has_capacity(device, std::move(decoder));
181
+
182
+ for (size_t i = 0; i < output.size(); ++i) {
183
+ output[i] = exif_orientation_transform(output[i], orientations[i]);
184
+ }
185
+ return output;
186
+ }
187
+
188
+ CUDAJpegDecoder::CUDAJpegDecoder(const torch::stable::Device& target_device)
189
+ : target_device_(target_device) {
190
+ StableDeviceGuard device_guard(target_device_.index());
191
+
192
+ nvjpegStatus_t status;
193
+
194
+ hw_decode_available_ = true;
195
+ status = nvjpegCreateEx(
196
+ NVJPEG_BACKEND_HARDWARE,
197
+ NULL,
198
+ NULL,
199
+ NVJPEG_FLAGS_DEFAULT,
200
+ &nvjpeg_handle_);
201
+ if (status == NVJPEG_STATUS_ARCH_MISMATCH) {
202
+ // No hardware JPEG decoder on this GPU (pre-A100); fall back to the default
203
+ // (software) backend.
204
+ status = nvjpegCreateEx(
205
+ NVJPEG_BACKEND_DEFAULT,
206
+ NULL,
207
+ NULL,
208
+ NVJPEG_FLAGS_DEFAULT,
209
+ &nvjpeg_handle_);
210
+ STD_TORCH_CHECK(
211
+ status == NVJPEG_STATUS_SUCCESS,
212
+ "Failed to initialize nvjpeg with default backend: ",
213
+ status);
214
+ hw_decode_available_ = false;
215
+ } else {
216
+ STD_TORCH_CHECK(
217
+ status == NVJPEG_STATUS_SUCCESS,
218
+ "Failed to initialize nvjpeg with hardware backend: ",
219
+ status);
220
+ }
221
+
222
+ if (hw_decode_available_) {
223
+ status = nvjpegJpegStateCreate(nvjpeg_handle_, &nvjpeg_state_hw_);
224
+ STD_TORCH_CHECK(
225
+ status == NVJPEG_STATUS_SUCCESS,
226
+ "Failed to create nvjpeg state: ",
227
+ status);
228
+
229
+ status = nvjpegJpegStreamCreate(nvjpeg_handle_, &nvjpeg_stream_);
230
+ STD_TORCH_CHECK(
231
+ status == NVJPEG_STATUS_SUCCESS,
232
+ "Failed to create jpeg stream: ",
233
+ status);
234
+ }
235
+
236
+ // Software path objects, used for progressive JPEGs and for everything when
237
+ // there's no HW engine.
238
+ status =
239
+ nvjpegDecoderCreate(nvjpeg_handle_, NVJPEG_BACKEND_DEFAULT, &sw_decoder_);
240
+ STD_TORCH_CHECK(
241
+ status == NVJPEG_STATUS_SUCCESS,
242
+ "Failed to create nvjpeg decoder: ",
243
+ status);
244
+
245
+ status =
246
+ nvjpegDecoderStateCreate(nvjpeg_handle_, sw_decoder_, &sw_decoder_state_);
247
+ STD_TORCH_CHECK(
248
+ status == NVJPEG_STATUS_SUCCESS,
249
+ "Failed to create nvjpeg decoder state: ",
250
+ status);
251
+
252
+ status = nvjpegDecodeParamsCreate(nvjpeg_handle_, &sw_decode_params_);
253
+ STD_TORCH_CHECK(
254
+ status == NVJPEG_STATUS_SUCCESS,
255
+ "Failed to create nvjpeg decode params: ",
256
+ status);
257
+
258
+ status = nvjpegBufferDeviceCreate(nvjpeg_handle_, NULL, &sw_device_buffer_);
259
+ STD_TORCH_CHECK(
260
+ status == NVJPEG_STATUS_SUCCESS,
261
+ "Failed to create nvjpeg device buffer: ",
262
+ status);
263
+
264
+ status = nvjpegStateAttachDeviceBuffer(sw_decoder_state_, sw_device_buffer_);
265
+ STD_TORCH_CHECK(
266
+ status == NVJPEG_STATUS_SUCCESS,
267
+ "Failed to attach nvjpeg device buffer: ",
268
+ status);
269
+
270
+ for (int i = 0; i < kNumSwPinnedBuffers; ++i) {
271
+ status =
272
+ nvjpegBufferPinnedCreate(nvjpeg_handle_, NULL, &sw_pinned_buffers_[i]);
273
+ STD_TORCH_CHECK(
274
+ status == NVJPEG_STATUS_SUCCESS,
275
+ "Failed to create nvjpeg pinned buffer: ",
276
+ status);
277
+
278
+ status = nvjpegJpegStreamCreate(nvjpeg_handle_, &sw_jpeg_streams_[i]);
279
+ STD_TORCH_CHECK(
280
+ status == NVJPEG_STATUS_SUCCESS,
281
+ "Failed to create jpeg stream: ",
282
+ status);
283
+ }
284
+ }
285
+
286
+ CUDAJpegDecoder::~CUDAJpegDecoder() {
287
+ // We properly destroy the nvjpeg stuff here. Note that this destructor is
288
+ // only called when a decoder cannot return to the cache. This is never
289
+ // reached during normal process teardown, because we just leak the entire
290
+ // decoder cache, just like we leak the NVDEC cache to avoid weird CUDA
291
+ // teardown issues.
292
+ for (int i = 0; i < kNumSwPinnedBuffers; ++i) {
293
+ nvjpegJpegStreamDestroy(sw_jpeg_streams_[i]);
294
+ nvjpegBufferPinnedDestroy(sw_pinned_buffers_[i]);
295
+ }
296
+ nvjpegJpegStateDestroy(sw_decoder_state_);
297
+ nvjpegBufferDeviceDestroy(sw_device_buffer_);
298
+ nvjpegDecodeParamsDestroy(sw_decode_params_);
299
+ nvjpegDecoderDestroy(sw_decoder_);
300
+ if (hw_decode_available_) {
301
+ nvjpegJpegStreamDestroy(nvjpeg_stream_);
302
+ nvjpegJpegStateDestroy(nvjpeg_state_hw_);
303
+ }
304
+ nvjpegDestroy(nvjpeg_handle_);
305
+ }
306
+
307
+ // Allocates the output tensor and creates its corresponding nvjpegImage_t for a
308
+ // single encoded image. Also figures out the output mode (nvjpegOutputFormat_t)
309
+ // based on the requested ImageReadMode and the source.
310
+ std::tuple<torch::stable::Tensor, nvjpegImage_t, nvjpegOutputFormat_t>
311
+ CUDAJpegDecoder::allocate_output(
312
+ const torch::stable::Tensor& encoded_image,
313
+ ImageReadMode mode) {
314
+ int widths[NVJPEG_MAX_COMPONENT];
315
+ int heights[NVJPEG_MAX_COMPONENT];
316
+ int source_channels = 0;
317
+ nvjpegChromaSubsampling_t subsampling;
318
+ nvjpegStatus_t status = nvjpegGetImageInfo(
319
+ nvjpeg_handle_,
320
+ encoded_image.const_data_ptr<uint8_t>(),
321
+ encoded_image.numel(),
322
+ &source_channels,
323
+ &subsampling,
324
+ widths,
325
+ heights);
326
+ STD_TORCH_CHECK(
327
+ status == NVJPEG_STATUS_SUCCESS, "Failed to get image info: ", status);
328
+ STD_TORCH_CHECK(
329
+ subsampling != NVJPEG_CSS_UNKNOWN, "Unknown chroma subsampling");
330
+
331
+ nvjpegOutputFormat_t output_format;
332
+ switch (mode) {
333
+ case ImageReadMode::GRAY:
334
+ output_format = NVJPEG_OUTPUT_Y;
335
+ break;
336
+ case ImageReadMode::RGB:
337
+ output_format = NVJPEG_OUTPUT_RGB;
338
+ break;
339
+ case ImageReadMode::UNCHANGED:
340
+ output_format =
341
+ source_channels == 1 ? NVJPEG_OUTPUT_Y : NVJPEG_OUTPUT_RGB;
342
+ break;
343
+ default:
344
+ STD_TORCH_CHECK(
345
+ false,
346
+ "The provided mode is not supported for JPEG decoding on GPU. "
347
+ "Supported modes are UNCHANGED, GRAY and RGB; alpha modes are "
348
+ "emulated in Python.");
349
+ }
350
+ int output_channels = (output_format == NVJPEG_OUTPUT_Y) ? 1 : 3;
351
+
352
+ auto output_tensor = torch::stable::empty(
353
+ {int64_t(output_channels), int64_t(heights[0]), int64_t(widths[0])},
354
+ kStableUInt8,
355
+ std::nullopt,
356
+ target_device_);
357
+
358
+ nvjpegImage_t nvjpeg_image;
359
+ for (int c = 0; c < output_channels; ++c) {
360
+ nvjpeg_image.channel[c] =
361
+ torch::stable::select(output_tensor, 0, c).mutable_data_ptr<uint8_t>();
362
+ nvjpeg_image.pitch[c] = widths[0];
363
+ }
364
+ for (int c = output_channels; c < NVJPEG_MAX_COMPONENT; ++c) {
365
+ nvjpeg_image.channel[c] = nullptr;
366
+ nvjpeg_image.pitch[c] = 0;
367
+ }
368
+ return {output_tensor, nvjpeg_image, output_format};
369
+ }
370
+
371
+ // Split image indices into the hardware-batched group (baseline JPEGs when
372
+ // the HW engine is available) and the software group (everything else).
373
+ // Returns {hw_indices, sw_indices} into encoded_images / output_tensors.
374
+ std::pair<std::vector<size_t>, std::vector<size_t>>
375
+ CUDAJpegDecoder::split_images_by_backend(
376
+ const std::vector<torch::stable::Tensor>& encoded_images) {
377
+ // Baseline JPEGs (hardware-batch decodable on A100+) go to the hardware
378
+ // group; everything else (e.g. progressive), and all images when there's no
379
+ // HW engine, go to the software group. See
380
+ // https://github.com/NVIDIA/CUDALibrarySamples/blob/f17940ac4e705bf47a8c39f5365925c1665f6c98/nvJPEG/nvJPEG-Decoder/nvjpegDecoder.cpp#L33
381
+ std::vector<size_t> hw_indices, sw_indices;
382
+ for (size_t i = 0; i < encoded_images.size(); ++i) {
383
+ bool supports_hw = false;
384
+ if (hw_decode_available_) {
385
+ nvjpegJpegStreamParseHeader(
386
+ nvjpeg_handle_,
387
+ encoded_images[i].const_data_ptr<uint8_t>(),
388
+ encoded_images[i].numel(),
389
+ nvjpeg_stream_);
390
+ int is_supported = -1;
391
+ nvjpegDecodeBatchedSupported(
392
+ nvjpeg_handle_, nvjpeg_stream_, &is_supported);
393
+ supports_hw = is_supported == 0; // nvJPEG sets 0 when supported
394
+ }
395
+ (supports_hw ? hw_indices : sw_indices).push_back(i);
396
+ }
397
+ return {std::move(hw_indices), std::move(sw_indices)};
398
+ }
399
+
400
+ void CUDAJpegDecoder::decode_batched_hardware(
401
+ const std::vector<torch::stable::Tensor>& encoded_images,
402
+ const std::vector<size_t>& indices,
403
+ ImageReadMode mode,
404
+ cudaStream_t stream,
405
+ std::vector<torch::stable::Tensor>& output_tensors) {
406
+ std::vector<const unsigned char*> inputs;
407
+ std::vector<size_t> sizes;
408
+ std::vector<nvjpegImage_t> nvjpeg_images;
409
+ std::vector<nvjpegOutputFormat_t> formats;
410
+ inputs.reserve(indices.size());
411
+ sizes.reserve(indices.size());
412
+ nvjpeg_images.reserve(indices.size());
413
+ formats.reserve(indices.size());
414
+ for (size_t idx : indices) {
415
+ auto [output_tensor, nvjpeg_image, output_format] =
416
+ allocate_output(encoded_images[idx], mode);
417
+ output_tensors[idx] = output_tensor;
418
+ inputs.push_back(encoded_images[idx].const_data_ptr<uint8_t>());
419
+ sizes.push_back(encoded_images[idx].numel());
420
+ nvjpeg_images.push_back(nvjpeg_image);
421
+ formats.push_back(output_format);
422
+ }
423
+
424
+ // The presync below is a workaround for a bug in nvJPEG, not a bug of ours:
425
+ // its hardware engine does not honour the stream it is given. With work
426
+ // already queued on `stream`, nvjpegDecodeBatched() may write its destination
427
+ // buffers *before* that work has run, thus potentially overriding buffers.
428
+ // The bug is reproducible on H100, not on the A100 we tried. There's a test
429
+ // for that: test_cuda_jpeg_waits_for_callers_stream. We force a CPU sync
430
+ // which is is essentially free today ONLY because decode_images() already
431
+ // host-synchronizes `stream` before returning. If that trailing sync is
432
+ // ever removed to make decoding asynchronous, the synx here turns into a real
433
+ // stall that stops the CPU from running ahead, and it should be reconsidered.
434
+ // The software path is unaffected, only the hardware path.
435
+ cudaError_t presync_status = cudaStreamSynchronize(stream);
436
+ STD_TORCH_CHECK(
437
+ presync_status == cudaSuccess,
438
+ "Failed to synchronize CUDA stream: ",
439
+ presync_status);
440
+
441
+ // The batch nvjpeg API only support a single output format per call, but we
442
+ // may want both grayscale and RGB images here. So we need to split the input
443
+ // into two groups and decode them separately. To be safe, we add stream sync
444
+ // point between the groups: the calls of the first group may read/write
445
+ // scratch buffers inside the shared nvjpeg_state_hw_, and the second group's
446
+ // nvjpegDecodeBatchedInitialize can reconfigure that same state. This is an
447
+ // assumption, but the sync point shouldn't hurt perf.
448
+ bool needs_sync = false;
449
+ for (nvjpegOutputFormat_t group_format :
450
+ {NVJPEG_OUTPUT_Y, NVJPEG_OUTPUT_RGB}) {
451
+ std::vector<const unsigned char*> group_inputs;
452
+ std::vector<size_t> group_sizes;
453
+ std::vector<nvjpegImage_t> group_images;
454
+ for (size_t i = 0; i < formats.size(); ++i) {
455
+ if (formats[i] == group_format) {
456
+ group_inputs.push_back(inputs[i]);
457
+ group_sizes.push_back(sizes[i]);
458
+ group_images.push_back(nvjpeg_images[i]);
459
+ }
460
+ }
461
+ if (group_inputs.empty()) {
462
+ continue;
463
+ }
464
+
465
+ if (needs_sync) {
466
+ cudaError_t cuda_status = cudaStreamSynchronize(stream);
467
+ STD_TORCH_CHECK(
468
+ cuda_status == cudaSuccess,
469
+ "Failed to synchronize CUDA stream: ",
470
+ cuda_status);
471
+ }
472
+
473
+ // Should we expose max_cpu_threads????
474
+ nvjpegStatus_t status = nvjpegDecodeBatchedInitialize(
475
+ nvjpeg_handle_,
476
+ nvjpeg_state_hw_,
477
+ group_images.size(),
478
+ /*max_cpu_threads=*/1,
479
+ group_format);
480
+ STD_TORCH_CHECK(
481
+ status == NVJPEG_STATUS_SUCCESS,
482
+ "Failed to initialize batch decoding: ",
483
+ status);
484
+
485
+ status = nvjpegDecodeBatched(
486
+ nvjpeg_handle_,
487
+ nvjpeg_state_hw_,
488
+ group_inputs.data(),
489
+ group_sizes.data(),
490
+ group_images.data(),
491
+ stream);
492
+ STD_TORCH_CHECK(
493
+ status == NVJPEG_STATUS_SUCCESS, "Failed to decode batch: ", status);
494
+
495
+ needs_sync = true;
496
+ }
497
+ }
498
+
499
+ void CUDAJpegDecoder::decode_software(
500
+ const std::vector<torch::stable::Tensor>& encoded_images,
501
+ const std::vector<size_t>& indices,
502
+ ImageReadMode mode,
503
+ cudaStream_t stream,
504
+ std::vector<torch::stable::Tensor>& output_tensors) {
505
+ int buffer_index = 0;
506
+ bool needs_sync = false;
507
+ for (size_t idx : indices) {
508
+ auto [output_tensor, nvjpeg_image, output_format] =
509
+ allocate_output(encoded_images[idx], mode);
510
+
511
+ // Decode each image straight to its own native format (see
512
+ // output_format_for_image), so grayscale sources stay single-channel.
513
+ nvjpegStatus_t status =
514
+ nvjpegDecodeParamsSetOutputFormat(sw_decode_params_, output_format);
515
+ STD_TORCH_CHECK(
516
+ status == NVJPEG_STATUS_SUCCESS,
517
+ "Failed to set nvjpeg output format: ",
518
+ status);
519
+
520
+ status = nvjpegJpegStreamParse(
521
+ nvjpeg_handle_,
522
+ encoded_images[idx].const_data_ptr<uint8_t>(),
523
+ encoded_images[idx].numel(),
524
+ /*save_metadata=*/0,
525
+ /*save_stream=*/0,
526
+ sw_jpeg_streams_[buffer_index]);
527
+ STD_TORCH_CHECK(
528
+ status == NVJPEG_STATUS_SUCCESS,
529
+ "Failed to decode JPEG (nvjpegJpegStreamParse): ",
530
+ status);
531
+
532
+ status = nvjpegStateAttachPinnedBuffer(
533
+ sw_decoder_state_, sw_pinned_buffers_[buffer_index]);
534
+ STD_TORCH_CHECK(
535
+ status == NVJPEG_STATUS_SUCCESS,
536
+ "Failed to attach nvjpeg pinned buffer: ",
537
+ status);
538
+
539
+ status = nvjpegDecodeJpegHost(
540
+ nvjpeg_handle_,
541
+ sw_decoder_,
542
+ sw_decoder_state_,
543
+ sw_decode_params_,
544
+ sw_jpeg_streams_[buffer_index]);
545
+ STD_TORCH_CHECK(
546
+ status == NVJPEG_STATUS_SUCCESS,
547
+ "Failed to decode JPEG (nvjpegDecodeJpegHost): ",
548
+ status);
549
+
550
+ if (needs_sync) {
551
+ // Why this sync exists:
552
+ //
553
+ // The nvjpeg software path is a 3 stage process:
554
+ // - CPU partial decoding into a pinned buffer
555
+ // - CPU -> GPU transfer
556
+ // - GPU final decode
557
+ //
558
+ // The supposedly simple nvjpegDecode() API does all three in one
559
+ // call. But it is not safe and doesn't work when decoding multiple images
560
+ // in succession: this isn't documented by nvjpeg, but the CPU partial
561
+ // decoding of image i would be re-using the CPU buffer of image i-1
562
+ // before the CPU->GPU transfer has finished. This is what caused #1802
563
+ //
564
+ // So we use the lower-level APIs and we:
565
+ // - rely on 2 pinned buffers (A and B below) instead of 1, always
566
+ // alternating between them
567
+ // - add a cudaStreamSynchronize() between the CPU decoding and the
568
+ // CPU->GPU transfer.
569
+ //
570
+ // Effectively, the sync means that before enqueing the CPU->GPU transfer
571
+ // of image i on buffer A, we wait for the completion of the CPU->GPU
572
+ // transfer and GPU decoding work of image i-1 from buffer B. Which means
573
+ // that buffer B will be safe to use by image i+1, *and* it still allows
574
+ // us to overlap the GPU work of image i with the CPU work of image i+1.
575
+ cudaError_t cuda_status = cudaStreamSynchronize(stream);
576
+ STD_TORCH_CHECK(
577
+ cuda_status == cudaSuccess,
578
+ "Failed to synchronize CUDA stream: ",
579
+ cuda_status);
580
+ }
581
+
582
+ status = nvjpegDecodeJpegTransferToDevice(
583
+ nvjpeg_handle_,
584
+ sw_decoder_,
585
+ sw_decoder_state_,
586
+ sw_jpeg_streams_[buffer_index],
587
+ stream);
588
+ STD_TORCH_CHECK(
589
+ status == NVJPEG_STATUS_SUCCESS,
590
+ "Failed to decode JPEG (nvjpegDecodeJpegTransferToDevice): ",
591
+ status);
592
+
593
+ status = nvjpegDecodeJpegDevice(
594
+ nvjpeg_handle_, sw_decoder_, sw_decoder_state_, &nvjpeg_image, stream);
595
+ STD_TORCH_CHECK(
596
+ status == NVJPEG_STATUS_SUCCESS,
597
+ "Failed to decode JPEG (nvjpegDecodeJpegDevice): ",
598
+ status);
599
+
600
+ output_tensors[idx] = output_tensor;
601
+ buffer_index = (buffer_index + 1) % kNumSwPinnedBuffers;
602
+ needs_sync = true;
603
+ }
604
+ }
605
+
606
+ std::vector<torch::stable::Tensor> CUDAJpegDecoder::decode_images(
607
+ const std::vector<torch::stable::Tensor>& encoded_images,
608
+ ImageReadMode mode,
609
+ cudaStream_t stream) {
610
+ std::vector<torch::stable::Tensor> output_tensors(encoded_images.size());
611
+
612
+ auto [hw_indices, sw_indices] = split_images_by_backend(encoded_images);
613
+ if (!hw_indices.empty()) {
614
+ decode_batched_hardware(
615
+ encoded_images, hw_indices, mode, stream, output_tensors);
616
+ }
617
+ if (!sw_indices.empty()) {
618
+ decode_software(encoded_images, sw_indices, mode, stream, output_tensors);
619
+ }
620
+
621
+ // Host-synchronize before returning: the decoder (and its internal nvJPEG
622
+ // buffers) goes back to the pool and may be reused immediately by the next
623
+ // call, so all GPU work using them must complete first.
624
+ // TODO_IMAGE: Should we? What does the NVDEC decoder do?
625
+ // NOTE: decode_batched_hardware() leans on this sync, see bug workardound
626
+ // note there.
627
+ cudaError_t cuda_status = cudaStreamSynchronize(stream);
628
+ STD_TORCH_CHECK(
629
+ cuda_status == cudaSuccess,
630
+ "Failed to synchronize CUDA stream: ",
631
+ cuda_status);
632
+
633
+ return output_tensors;
634
+ }
635
+
636
+ } // namespace facebook::torchcodec
637
+
638
+ #endif // !TORCHCODEC_ENABLE_NVJPEG