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,223 @@
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 "EncodeJpeg.h"
8
+
9
+ #include <torch/csrc/stable/library.h>
10
+ #include <torch/csrc/stable/ops.h>
11
+ #include <torch/headeronly/util/Exception.h>
12
+
13
+ #include "StableABICompat.h"
14
+
15
+ #if !TORCHCODEC_ENABLE_JPEG
16
+
17
+ namespace facebook::torchcodec {
18
+
19
+ void encode_jpeg(
20
+ [[maybe_unused]] const torch::stable::Tensor& img,
21
+ [[maybe_unused]] int64_t quality,
22
+ [[maybe_unused]] IOInterface& interface) {
23
+ STD_TORCH_CHECK(
24
+ false,
25
+ "encode_jpeg: torchcodec was not compiled with libjpeg support. Rebuild "
26
+ "torchcodec with TORCHCODEC_BUILD_JPEG=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 <jpeglib.h>
35
+ #include <setjmp.h>
36
+
37
+ #include <cstdint>
38
+ #include <exception>
39
+ #include <vector>
40
+
41
+ namespace facebook::torchcodec {
42
+
43
+ namespace {
44
+
45
+ constexpr int OUTPUT_BUFFER_SIZE = 64 * 1024;
46
+
47
+ // Error context passed to libjpeg. Same shape and rationale as the one in
48
+ // DecodeJpeg.cpp: the jpeg_error_mgr base must be the first field so we can
49
+ // cast the `err` pointer libjpeg hands back to our callbacks into an ErrorCtx*.
50
+ struct ErrorCtx {
51
+ jpeg_error_mgr base;
52
+ char last_error_message[JMSG_LENGTH_MAX];
53
+ jmp_buf setjmp_buffer;
54
+ };
55
+
56
+ void error_exit_cb(j_common_ptr jpeg_ctx) {
57
+ auto* error_ctx = reinterpret_cast<ErrorCtx*>(jpeg_ctx->err);
58
+ error_ctx->base.format_message(jpeg_ctx, error_ctx->last_error_message);
59
+ longjmp(error_ctx->setjmp_buffer, 1);
60
+ }
61
+
62
+ // Custom libjpeg destination manager that streams compressed bytes into an
63
+ // IOInterface. The jpeg_destination_mgr must be the first field so libjpeg's
64
+ // `dest` pointer can be cast back to an IOCtx* in the callbacks.
65
+ struct IOCtx {
66
+ jpeg_destination_mgr jpeg_dest_mgr;
67
+ IOInterface* interface;
68
+ // libjpeg writes to this buffer in chunks, and we flush it to the IOInterface
69
+ // whenever it fills up.
70
+ std::vector<JOCTET> buffer;
71
+ std::exception_ptr interface_exception;
72
+ };
73
+
74
+ // Flushes the first `size` bytes of io_ctx->buffer to the IOInterface. The
75
+ // interface->write() call may throw (e.g. a Python file-like raising, or a disk
76
+ // error), but a C++ exception must not unwind through libjpeg's C stack. So we
77
+ // capture it and abort compression by longjmp-ing to the setjmp point in
78
+ // compress_jpeg, which rethrows it.
79
+ void write_or_longjmp(j_compress_ptr jpeg_ctx, IOCtx* io_ctx, int size) {
80
+ try {
81
+ io_ctx->interface->write(io_ctx->buffer.data(), size);
82
+ return;
83
+ } catch (...) {
84
+ io_ctx->interface_exception = std::current_exception();
85
+ }
86
+ longjmp(reinterpret_cast<ErrorCtx*>(jpeg_ctx->err)->setjmp_buffer, 1);
87
+ }
88
+
89
+ // Called by jpeg_start_compress() before any data is written.
90
+ void init_destination(j_compress_ptr jpeg_ctx) {
91
+ auto* io_ctx = reinterpret_cast<IOCtx*>(jpeg_ctx->dest);
92
+ io_ctx->jpeg_dest_mgr.next_output_byte = io_ctx->buffer.data();
93
+ io_ctx->jpeg_dest_mgr.free_in_buffer = io_ctx->buffer.size();
94
+ }
95
+
96
+ // Called whenever libjpeg runs out of space in the output buffer. We flush the
97
+ // buffer to the IOInterface and reset the buffer.
98
+ boolean empty_output_buffer(j_compress_ptr jpeg_ctx) {
99
+ auto* io_ctx = reinterpret_cast<IOCtx*>(jpeg_ctx->dest);
100
+ write_or_longjmp(jpeg_ctx, io_ctx, static_cast<int>(io_ctx->buffer.size()));
101
+ io_ctx->jpeg_dest_mgr.next_output_byte = io_ctx->buffer.data();
102
+ io_ctx->jpeg_dest_mgr.free_in_buffer = io_ctx->buffer.size();
103
+ return TRUE;
104
+ }
105
+
106
+ // called by jpeg_finish_compress() after all data has been written. There might
107
+ // still be some data in the buffer which needs to be flushed to the
108
+ // IOInterface.
109
+ void term_destination(j_compress_ptr jpeg_ctx) {
110
+ auto* io_ctx = reinterpret_cast<IOCtx*>(jpeg_ctx->dest);
111
+ int size = static_cast<int>(
112
+ io_ctx->buffer.size() - io_ctx->jpeg_dest_mgr.free_in_buffer);
113
+ if (size > 0) {
114
+ write_or_longjmp(jpeg_ctx, io_ctx, size);
115
+ }
116
+ }
117
+
118
+ void compress_jpeg(
119
+ jpeg_compress_struct& jpeg_ctx,
120
+ ErrorCtx& error_ctx,
121
+ IOCtx& io_ctx,
122
+ const uint8_t* input_ptr,
123
+ int width,
124
+ int height,
125
+ int num_channels,
126
+ int quality) {
127
+ if (setjmp(error_ctx.setjmp_buffer)) {
128
+ jpeg_destroy_compress(&jpeg_ctx);
129
+ // We land here on either a libjpeg error (via error_exit_cb) or a failed
130
+ // write (via write_or_longjmp). The latter sets interface_exception, which
131
+ // we rethrow to surface the original exception.
132
+ if (io_ctx.interface_exception) {
133
+ std::rethrow_exception(io_ctx.interface_exception);
134
+ } else {
135
+ STD_TORCH_CHECK(false, error_ctx.last_error_message);
136
+ }
137
+ }
138
+
139
+ jpeg_create_compress(&jpeg_ctx);
140
+
141
+ jpeg_ctx.image_width = static_cast<JDIMENSION>(width);
142
+ jpeg_ctx.image_height = static_cast<JDIMENSION>(height);
143
+ jpeg_ctx.input_components = num_channels;
144
+ jpeg_ctx.in_color_space = num_channels == 1 ? JCS_GRAYSCALE : JCS_RGB;
145
+
146
+ jpeg_set_defaults(&jpeg_ctx);
147
+ jpeg_set_quality(&jpeg_ctx, quality, /*force_baseline=*/TRUE);
148
+
149
+ io_ctx.jpeg_dest_mgr.init_destination = &init_destination;
150
+ io_ctx.jpeg_dest_mgr.empty_output_buffer = &empty_output_buffer;
151
+ io_ctx.jpeg_dest_mgr.term_destination = &term_destination;
152
+ jpeg_ctx.dest = &io_ctx.jpeg_dest_mgr;
153
+
154
+ jpeg_start_compress(&jpeg_ctx, /*write_all_tables=*/TRUE);
155
+
156
+ const int64_t stride = static_cast<int64_t>(width) * num_channels;
157
+ auto* row = const_cast<JSAMPROW>(input_ptr);
158
+ while (jpeg_ctx.next_scanline < jpeg_ctx.image_height) {
159
+ jpeg_write_scanlines(&jpeg_ctx, &row, /*num_lines=*/1);
160
+ row += stride;
161
+ }
162
+
163
+ jpeg_finish_compress(&jpeg_ctx);
164
+ jpeg_destroy_compress(&jpeg_ctx);
165
+ }
166
+
167
+ } // namespace
168
+
169
+ // Important: see Note [libjpeg error handling] in the jpeg decoder: everything
170
+ // applies here too. We must not throw a C++ exception through libjpeg's C stack
171
+ // (and callbacks), and we must not allocate anything that needs proper
172
+ // destruction in a function that defines a setjmp() point. The IOCtx (which
173
+ // owns a std::vector) therefore lives here, outside compress_jpeg's setjmp.
174
+ void encode_jpeg(
175
+ const torch::stable::Tensor& img,
176
+ int64_t quality,
177
+ IOInterface& interface) {
178
+ STD_TORCH_CHECK(
179
+ img.device().type() == kStableCPU,
180
+ "Input tensor must be on the CPU, got a tensor on ",
181
+ device_type_name(img.device().type()),
182
+ ".");
183
+ STD_TORCH_CHECK(
184
+ img.scalar_type() == kStableUInt8, "Input tensor dtype should be uint8");
185
+ STD_TORCH_CHECK(
186
+ img.dim() == 3, "Input data should be a 3-dimensional tensor");
187
+
188
+ const auto num_channels = static_cast<int>(img.size(0));
189
+ const auto height = static_cast<int>(img.size(1));
190
+ const auto width = static_cast<int>(img.size(2));
191
+ STD_TORCH_CHECK(
192
+ num_channels == 1 || num_channels == 3,
193
+ "The number of channels should be 1 or 3, got: ",
194
+ num_channels);
195
+
196
+ // libjpeg consumes samples channels-last (HWC), one contiguous row at a time.
197
+ const auto input = torch::stable::contiguous(stable_permute(img, {1, 2, 0}));
198
+
199
+ // Owned here rather than in compress_jpeg(): that function runs the
200
+ // setjmp/longjmp dance and must keep these alive across it.
201
+ jpeg_compress_struct jpeg_ctx;
202
+ ErrorCtx error_ctx;
203
+ jpeg_ctx.err = jpeg_std_error(&error_ctx.base);
204
+ error_ctx.base.error_exit = error_exit_cb;
205
+
206
+ IOCtx io_ctx;
207
+ io_ctx.interface = &interface;
208
+ io_ctx.buffer.resize(OUTPUT_BUFFER_SIZE);
209
+
210
+ compress_jpeg(
211
+ jpeg_ctx,
212
+ error_ctx,
213
+ io_ctx,
214
+ input.const_data_ptr<uint8_t>(),
215
+ width,
216
+ height,
217
+ num_channels,
218
+ static_cast<int>(quality));
219
+ }
220
+
221
+ } // namespace facebook::torchcodec
222
+
223
+ #endif // !TORCHCODEC_ENABLE_JPEG
@@ -0,0 +1,19 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include "IOInterface.h"
10
+ #include "StableABICompat.h"
11
+
12
+ namespace facebook::torchcodec {
13
+
14
+ FORCE_PUBLIC_VISIBILITY void encode_jpeg(
15
+ const torch::stable::Tensor& img,
16
+ int64_t quality,
17
+ IOInterface& interface);
18
+
19
+ } // namespace facebook::torchcodec
@@ -0,0 +1,272 @@
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 "EncodeJpegCuda.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
+ namespace {
19
+ [[noreturn]] void raise_no_nvjpeg() {
20
+ STD_TORCH_CHECK(
21
+ false,
22
+ "encode_jpeg: torchcodec was not compiled with nvJPEG support, so JPEG "
23
+ "images cannot be encoded on a CUDA device. Rebuild torchcodec with "
24
+ "ENABLE_CUDA=1 and TORCHCODEC_BUILD_NVJPEG=1. If you see this error in a "
25
+ "prebuilt wheel, please report it to the TorchCodec repo.");
26
+ }
27
+ } // namespace
28
+
29
+ void encode_jpeg_cuda(
30
+ [[maybe_unused]] const torch::stable::Tensor& image,
31
+ [[maybe_unused]] int64_t quality,
32
+ [[maybe_unused]] IOInterface& interface) {
33
+ raise_no_nvjpeg();
34
+ }
35
+
36
+ torch::stable::Tensor encode_jpeg_to_tensor_cuda(
37
+ [[maybe_unused]] const torch::stable::Tensor& image,
38
+ [[maybe_unused]] int64_t quality) {
39
+ raise_no_nvjpeg();
40
+ }
41
+
42
+ } // namespace facebook::torchcodec
43
+
44
+ #else
45
+
46
+ #include "CUDACommon.h"
47
+ #include "Cache.h"
48
+
49
+ namespace facebook::torchcodec {
50
+
51
+ namespace {
52
+
53
+ // Encoders are, like the JPEG decoders, expensive to create (~270ms) and cheap
54
+ // to keep resident (~40Mb of GPU memory), so we cache a generous number per
55
+ // device (same cap as the decoder). Caching gives a ~300x speedup over
56
+ // constructing an encoder per call.
57
+ constexpr int kMaxCachedEncodersPerDevice = 32;
58
+
59
+ PerGpuCache<CUDAJpegEncoder>& encoder_cache() {
60
+ // Intentionally leaked (allocated with new, never freed) to avoid calling
61
+ // into CUDA/nvJPEG during static destruction, when the CUDA runtime may
62
+ // already be torn down (same reasoning as NVDECCache): the cached encoders'
63
+ // destructors call nvjpegDestroy, which we must not run at process exit.
64
+ static auto* cache = new PerGpuCache<CUDAJpegEncoder>(
65
+ MAX_CUDA_GPUS, kMaxCachedEncodersPerDevice);
66
+ return *cache;
67
+ }
68
+
69
+ torch::stable::Tensor encode_to_tensor(
70
+ const torch::stable::Tensor& image,
71
+ int64_t quality,
72
+ const torch::stable::Device& output_device) {
73
+ STD_TORCH_CHECK(
74
+ image.device().is_cuda(),
75
+ "Input tensor must be on a CUDA device, got a tensor on ",
76
+ device_type_name(image.device().type()),
77
+ ".");
78
+
79
+ torch::stable::Device device = image.device();
80
+ int device_index = get_device_index(device);
81
+ StableDeviceGuard device_guard(device_index);
82
+
83
+ cudaStream_t current_stream = get_current_cuda_stream(device_index);
84
+
85
+ PerGpuCache<CUDAJpegEncoder>& cache = encoder_cache();
86
+ std::unique_ptr<CUDAJpegEncoder> encoder = cache.get(device);
87
+ if (encoder == nullptr) {
88
+ encoder = std::make_unique<CUDAJpegEncoder>(device);
89
+ }
90
+
91
+ torch::stable::Tensor output =
92
+ encoder->encode_to_tensor(image, quality, current_stream, output_device);
93
+ cache.add_if_cache_has_capacity(device, std::move(encoder));
94
+
95
+ return output;
96
+ }
97
+
98
+ } // namespace
99
+
100
+ // This one is for to_file and to_file_like while encode_jpeg_to_tensor_cuda is
101
+ // a dedicated path to encode to tensor. We have a dedicated path for encoding
102
+ // to tensor, instead of relying on the generic BytesIO().getbuffer() solution,
103
+ // because here the output tensor is on CUDA! And going through BytesIO() would
104
+ // require to send it to the CPU.
105
+ // There are good reasons one would want to keep the encoded data on CUDA, e.g.
106
+ // to use cuFile.
107
+ void encode_jpeg_cuda(
108
+ const torch::stable::Tensor& image,
109
+ int64_t quality,
110
+ IOInterface& interface) {
111
+ torch::stable::Tensor encoded =
112
+ encode_to_tensor(image, quality, torch::stable::Device(kStableCPU));
113
+ interface.write(
114
+ encoded.const_data_ptr<uint8_t>(), static_cast<int>(encoded.numel()));
115
+ }
116
+
117
+ torch::stable::Tensor encode_jpeg_to_tensor_cuda(
118
+ const torch::stable::Tensor& image,
119
+ int64_t quality) {
120
+ return encode_to_tensor(image, quality, image.device());
121
+ }
122
+
123
+ CUDAJpegEncoder::CUDAJpegEncoder(const torch::stable::Device& target_device)
124
+ : target_device_(target_device) {
125
+ StableDeviceGuard device_guard(target_device_.index());
126
+
127
+ nvjpegStatus_t status;
128
+ status = nvjpegCreateSimple(&nvjpeg_handle_);
129
+ STD_TORCH_CHECK(
130
+ status == NVJPEG_STATUS_SUCCESS,
131
+ "Failed to create nvjpeg handle: ",
132
+ status);
133
+
134
+ status = nvjpegEncoderStateCreate(
135
+ nvjpeg_handle_, &nvjpeg_enc_state_, /*stream=*/nullptr);
136
+ STD_TORCH_CHECK(
137
+ status == NVJPEG_STATUS_SUCCESS,
138
+ "Failed to create nvjpeg encoder state: ",
139
+ status);
140
+
141
+ status = nvjpegEncoderParamsCreate(
142
+ nvjpeg_handle_, &nvjpeg_enc_params_, /*stream=*/nullptr);
143
+ STD_TORCH_CHECK(
144
+ status == NVJPEG_STATUS_SUCCESS,
145
+ "Failed to create nvjpeg encoder params: ",
146
+ status);
147
+ }
148
+
149
+ CUDAJpegEncoder::~CUDAJpegEncoder() {
150
+ // Like the JPEG decoder, this destructor only runs when an encoder cannot
151
+ // return to the cache; it's never reached during process teardown, because we
152
+ // leak the entire encoder cache to avoid CUDA teardown issues.
153
+ nvjpegEncoderParamsDestroy(nvjpeg_enc_params_);
154
+ nvjpegEncoderStateDestroy(nvjpeg_enc_state_);
155
+ nvjpegDestroy(nvjpeg_handle_);
156
+ }
157
+
158
+ torch::stable::Tensor CUDAJpegEncoder::encode_to_tensor(
159
+ const torch::stable::Tensor& image,
160
+ int64_t quality,
161
+ cudaStream_t stream,
162
+ const torch::stable::Device& output_device) {
163
+ STD_TORCH_CHECK(
164
+ image.scalar_type() == kStableUInt8,
165
+ "Input tensor dtype should be uint8");
166
+ STD_TORCH_CHECK(
167
+ image.dim() == 3, "Input data should be a 3-dimensional tensor");
168
+
169
+ const int num_channels = static_cast<int>(image.size(0));
170
+ const int height = static_cast<int>(image.size(1));
171
+ const int width = static_cast<int>(image.size(2));
172
+ STD_TORCH_CHECK(
173
+ num_channels == 3,
174
+ "The number of channels should be 3 (RGB) for JPEG encoding on GPU, "
175
+ "got: ",
176
+ num_channels,
177
+ ". Grayscale encoding is only supported on the CPU for now.");
178
+
179
+ // nvJPEG reads each channel as a separate planar buffer, so the input must be
180
+ // contiguous (pitch == width below relies on this).
181
+ const auto input = torch::stable::contiguous(image);
182
+
183
+ nvjpegStatus_t status;
184
+ status = nvjpegEncoderParamsSetQuality(
185
+ nvjpeg_enc_params_, static_cast<int>(quality), stream);
186
+ STD_TORCH_CHECK(
187
+ status == NVJPEG_STATUS_SUCCESS,
188
+ "Failed to set nvjpeg encoder quality: ",
189
+ status);
190
+
191
+ status = nvjpegEncoderParamsSetSamplingFactors(
192
+ nvjpeg_enc_params_, NVJPEG_CSS_444, stream);
193
+ STD_TORCH_CHECK(
194
+ status == NVJPEG_STATUS_SUCCESS,
195
+ "Failed to set nvjpeg encoder sampling factors: ",
196
+ status);
197
+
198
+ nvjpegImage_t nvjpeg_image;
199
+ for (int c = 0; c < num_channels; ++c) {
200
+ nvjpeg_image.channel[c] =
201
+ torch::stable::select(input, 0, c).mutable_data_ptr<uint8_t>();
202
+ nvjpeg_image.pitch[c] = width;
203
+ }
204
+ for (int c = num_channels; c < NVJPEG_MAX_COMPONENT; ++c) {
205
+ nvjpeg_image.channel[c] = nullptr;
206
+ nvjpeg_image.pitch[c] = 0;
207
+ }
208
+
209
+ status = nvjpegEncodeImage(
210
+ nvjpeg_handle_,
211
+ nvjpeg_enc_state_,
212
+ nvjpeg_enc_params_,
213
+ &nvjpeg_image,
214
+ NVJPEG_INPUT_RGB,
215
+ width,
216
+ height,
217
+ stream);
218
+ STD_TORCH_CHECK(
219
+ status == NVJPEG_STATUS_SUCCESS, "Failed to encode image: ", status);
220
+
221
+ // Query the encoded bitstream length (with a null buffer), then allocate the
222
+ // output on `output_device` and retrieve into it.
223
+ size_t length = 0;
224
+ status = nvjpegEncodeRetrieveBitstream(
225
+ nvjpeg_handle_, nvjpeg_enc_state_, nullptr, &length, stream);
226
+ STD_TORCH_CHECK(
227
+ status == NVJPEG_STATUS_SUCCESS,
228
+ "Failed to retrieve encoded bitstream size: ",
229
+ status);
230
+
231
+ cudaError_t cuda_status = cudaStreamSynchronize(stream);
232
+ STD_TORCH_CHECK(
233
+ cuda_status == cudaSuccess,
234
+ "Failed to synchronize CUDA stream: ",
235
+ cuda_status);
236
+
237
+ auto output = torch::stable::empty(
238
+ {static_cast<int64_t>(length)},
239
+ kStableUInt8,
240
+ std::nullopt,
241
+ output_device);
242
+ status = output_device.is_cuda() ? nvjpegEncodeRetrieveBitstreamDevice(
243
+ nvjpeg_handle_,
244
+ nvjpeg_enc_state_,
245
+ output.mutable_data_ptr<uint8_t>(),
246
+ &length,
247
+ stream)
248
+ : nvjpegEncodeRetrieveBitstream(
249
+ nvjpeg_handle_,
250
+ nvjpeg_enc_state_,
251
+ output.mutable_data_ptr<uint8_t>(),
252
+ &length,
253
+ stream);
254
+ STD_TORCH_CHECK(
255
+ status == NVJPEG_STATUS_SUCCESS,
256
+ "Failed to retrieve encoded bitstream: ",
257
+ status);
258
+
259
+ // Sync before returning the encoder to the pool: its internal nvJPEG buffers
260
+ // may be reused by the next call, so the retrieve into `output` must finish.
261
+ cuda_status = cudaStreamSynchronize(stream);
262
+ STD_TORCH_CHECK(
263
+ cuda_status == cudaSuccess,
264
+ "Failed to synchronize CUDA stream: ",
265
+ cuda_status);
266
+
267
+ return output;
268
+ }
269
+
270
+ } // namespace facebook::torchcodec
271
+
272
+ #endif // !TORCHCODEC_ENABLE_NVJPEG
@@ -0,0 +1,56 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <torch/csrc/stable/device.h>
10
+ #include <torch/csrc/stable/tensor.h>
11
+
12
+ #include <cstdint>
13
+
14
+ #include "IOInterface.h"
15
+ #include "StableABICompat.h"
16
+
17
+ #if TORCHCODEC_ENABLE_NVJPEG
18
+ #include <cuda_runtime.h>
19
+ #include <nvjpeg.h>
20
+ #endif
21
+
22
+ namespace facebook::torchcodec {
23
+
24
+ FORCE_PUBLIC_VISIBILITY void encode_jpeg_cuda(
25
+ const torch::stable::Tensor& image,
26
+ int64_t quality,
27
+ IOInterface& interface);
28
+
29
+ FORCE_PUBLIC_VISIBILITY torch::stable::Tensor encode_jpeg_to_tensor_cuda(
30
+ const torch::stable::Tensor& image,
31
+ int64_t quality);
32
+
33
+ #if TORCHCODEC_ENABLE_NVJPEG
34
+
35
+ class CUDAJpegEncoder {
36
+ public:
37
+ explicit CUDAJpegEncoder(const torch::stable::Device& target_device);
38
+ ~CUDAJpegEncoder();
39
+
40
+ torch::stable::Tensor encode_to_tensor(
41
+ const torch::stable::Tensor& image,
42
+ int64_t quality,
43
+ cudaStream_t stream,
44
+ const torch::stable::Device& output_device);
45
+
46
+ private:
47
+ const torch::stable::Device target_device_;
48
+
49
+ nvjpegHandle_t nvjpeg_handle_;
50
+ nvjpegEncoderState_t nvjpeg_enc_state_;
51
+ nvjpegEncoderParams_t nvjpeg_enc_params_;
52
+ };
53
+
54
+ #endif // TORCHCODEC_ENABLE_NVJPEG
55
+
56
+ } // namespace facebook::torchcodec