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,92 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <torch/csrc/stable/device.h>
10
+ #include <torch/csrc/stable/tensor.h>
11
+
12
+ #include <tuple>
13
+ #include <utility>
14
+ #include <vector>
15
+
16
+ #include "ImageCommon.h"
17
+ #include "StableABICompat.h"
18
+
19
+ #if TORCHCODEC_ENABLE_NVJPEG
20
+ #include <cuda_runtime.h>
21
+ #include <nvjpeg.h>
22
+ #endif
23
+
24
+ namespace facebook::torchcodec {
25
+
26
+ FORCE_PUBLIC_VISIBILITY std::vector<torch::stable::Tensor> decode_jpegs_cuda(
27
+ std::vector<torch::stable::Tensor> encoded_images,
28
+ int64_t mode,
29
+ torch::stable::Device device);
30
+
31
+ #if TORCHCODEC_ENABLE_NVJPEG
32
+
33
+ class CUDAJpegDecoder {
34
+ public:
35
+ explicit CUDAJpegDecoder(const torch::stable::Device& target_device);
36
+ ~CUDAJpegDecoder();
37
+
38
+ std::vector<torch::stable::Tensor> decode_images(
39
+ const std::vector<torch::stable::Tensor>& encoded_images,
40
+ ImageReadMode mode,
41
+ cudaStream_t stream);
42
+
43
+ private:
44
+ std::tuple<torch::stable::Tensor, nvjpegImage_t, nvjpegOutputFormat_t>
45
+ allocate_output(
46
+ const torch::stable::Tensor& encoded_image,
47
+ ImageReadMode mode);
48
+
49
+ std::pair<std::vector<size_t>, std::vector<size_t>> split_images_by_backend(
50
+ const std::vector<torch::stable::Tensor>& encoded_images);
51
+
52
+ void decode_batched_hardware(
53
+ const std::vector<torch::stable::Tensor>& encoded_images,
54
+ const std::vector<size_t>& indices,
55
+ ImageReadMode mode,
56
+ cudaStream_t stream,
57
+ std::vector<torch::stable::Tensor>& output_tensors);
58
+
59
+ void decode_software(
60
+ const std::vector<torch::stable::Tensor>& encoded_images,
61
+ const std::vector<size_t>& indices,
62
+ ImageReadMode mode,
63
+ cudaStream_t stream,
64
+ std::vector<torch::stable::Tensor>& output_tensors);
65
+
66
+ const torch::stable::Device target_device_;
67
+
68
+ // The nvJPEG library handle, and whether this GPU has the fixed-function HW
69
+ // JPEG engine. Both used everywhere.
70
+ nvjpegHandle_t nvjpeg_handle_;
71
+ bool hw_decode_available_{false};
72
+
73
+ // HW path only
74
+ nvjpegJpegState_t nvjpeg_state_hw_;
75
+ nvjpegJpegStream_t nvjpeg_stream_;
76
+
77
+ // SW path, using the decoupled (host / transfer / device) API. Always
78
+ // created, even when the HW engine is available, because not all JPEGs are
79
+ // supported by the HW engine. Consecutive images alternate between the two
80
+ // pinned buffers and jpeg streams. See decode_software().
81
+ nvjpegJpegDecoder_t sw_decoder_;
82
+ nvjpegJpegState_t sw_decoder_state_;
83
+ nvjpegDecodeParams_t sw_decode_params_;
84
+ nvjpegBufferDevice_t sw_device_buffer_;
85
+ static constexpr int kNumSwPinnedBuffers = 2;
86
+ nvjpegBufferPinned_t sw_pinned_buffers_[kNumSwPinnedBuffers];
87
+ nvjpegJpegStream_t sw_jpeg_streams_[kNumSwPinnedBuffers];
88
+ };
89
+
90
+ #endif // TORCHCODEC_ENABLE_NVJPEG
91
+
92
+ } // namespace facebook::torchcodec
@@ -0,0 +1,569 @@
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 "DecodePng.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
+ #include <cstring>
16
+
17
+ #ifdef _WIN32
18
+ #include <fstream>
19
+ #else
20
+ #include <fcntl.h>
21
+ #include <unistd.h>
22
+ #endif
23
+
24
+ #include "ImageCommon.h"
25
+
26
+ namespace facebook::torchcodec {
27
+
28
+ namespace {
29
+
30
+ int64_t read_chunk_length(const uint8_t* header) {
31
+ return (int64_t(header[0]) << 24) | (int64_t(header[1]) << 16) |
32
+ (int64_t(header[2]) << 8) | int64_t(header[3]);
33
+ }
34
+
35
+ } // namespace
36
+
37
+ int64_t png_skip_idat_chunks_from_tensor(
38
+ const torch::stable::Tensor& input,
39
+ int64_t offset) {
40
+ auto contig_input = validate_encoded_data(input);
41
+ auto data = contig_input.const_data_ptr<uint8_t>();
42
+ int64_t size = contig_input.numel();
43
+ STD_TORCH_CHECK(offset >= 0, "offset must be non-negative, got ", offset);
44
+ while (offset + 8 <= size && std::memcmp(data + offset + 4, "IDAT", 4) == 0) {
45
+ offset += 12 + read_chunk_length(data + offset);
46
+ }
47
+ return offset;
48
+ }
49
+
50
+ int64_t png_skip_idat_chunks_from_file(std::string filename, int64_t offset) {
51
+ STD_TORCH_CHECK(offset >= 0, "offset must be non-negative, got ", offset);
52
+ // The chunk headers are usually 8 KB apart (libpng's default), so buffered
53
+ // reads would end up reading the whole file: we do one small unbuffered read
54
+ // per chunk instead.
55
+ uint8_t header[8];
56
+ #ifdef _WIN32
57
+ std::ifstream file;
58
+ file.rdbuf()->pubsetbuf(nullptr, 0);
59
+ file.open(filename, std::ios::binary);
60
+ STD_TORCH_CHECK(
61
+ file.is_open(), "Failed to open file for reading: ", filename);
62
+ while (file.seekg(offset) &&
63
+ file.read(reinterpret_cast<char*>(header), sizeof(header)) &&
64
+ std::memcmp(header + 4, "IDAT", 4) == 0) {
65
+ offset += 12 + read_chunk_length(header);
66
+ }
67
+ #else
68
+ int fd = open(filename.c_str(), O_RDONLY | O_CLOEXEC);
69
+ STD_TORCH_CHECK(fd >= 0, "Failed to open file for reading: ", filename);
70
+ while (pread(fd, header, sizeof(header), offset) ==
71
+ static_cast<ssize_t>(sizeof(header)) &&
72
+ std::memcmp(header + 4, "IDAT", 4) == 0) {
73
+ offset += 12 + read_chunk_length(header);
74
+ }
75
+ close(fd);
76
+ #endif
77
+ return offset;
78
+ }
79
+
80
+ } // namespace facebook::torchcodec
81
+
82
+ #if !TORCHCODEC_ENABLE_PNG
83
+
84
+ namespace facebook::torchcodec {
85
+
86
+ torch::stable::Tensor decode_png(
87
+ [[maybe_unused]] const torch::stable::Tensor& input,
88
+ [[maybe_unused]] int64_t mode,
89
+ [[maybe_unused]] int64_t output_dtype) {
90
+ STD_TORCH_CHECK(
91
+ false,
92
+ "decode_png: torchcodec was not compiled with libpng support. Rebuild "
93
+ "torchcodec with TORCHCODEC_BUILD_PNG=1. If you see this error in a "
94
+ "prebuilt wheel, please report it to the TorchCodec repo.");
95
+ }
96
+
97
+ } // namespace facebook::torchcodec
98
+
99
+ #else
100
+
101
+ #include <png.h>
102
+
103
+ #if !defined(PNG_eXIf_SUPPORTED)
104
+ // We always want to apply exif so we enforce a libpng that has eXIf support.
105
+ // This is a compile-time check, not a runtime check, but since we bundle
106
+ // libpng within our wheel this exif support is guaranteed to users.
107
+ #error \
108
+ "torchcodec requires libpng to be built with eXIf support (PNG_eXIf_SUPPORTED)."
109
+ #endif
110
+
111
+ #include <setjmp.h>
112
+
113
+ #include <algorithm>
114
+ #include <bit>
115
+ #include <cstdint>
116
+ #include <cstdio>
117
+ #include <cstring>
118
+ #include <string_view>
119
+ #include <vector>
120
+
121
+ #include "Exif.h"
122
+ #include "ImageCommon.h"
123
+
124
+ namespace facebook::torchcodec {
125
+
126
+ using namespace exif_private;
127
+
128
+ namespace {
129
+
130
+ struct ErrorCtx {
131
+ char error_message[256] = "";
132
+ };
133
+
134
+ void error_callback(png_structp png_ptr, png_const_charp error_message) {
135
+ auto* error_ctx = static_cast<ErrorCtx*>(png_get_error_ptr(png_ptr));
136
+ if (error_ctx != nullptr) {
137
+ std::snprintf(
138
+ error_ctx->error_message,
139
+ sizeof(error_ctx->error_message),
140
+ "%s",
141
+ error_message);
142
+ }
143
+ png_longjmp(png_ptr, 1);
144
+ }
145
+
146
+ // Decodes the text of an ImageMagick "Raw profile type exif" chunk, i.e.
147
+ // "\nexif\n<length>\n<hex data, over multiple lines>", the way Pillow does:
148
+ // bytes.fromhex("".join(text.split("\n")[3:])). Returns false if the hex data
149
+ // is invalid.
150
+ bool decode_raw_profile_exif(
151
+ std::string_view text,
152
+ std::vector<unsigned char>& exif) {
153
+ for (int i = 0; i < 3; ++i) {
154
+ size_t newline = text.find('\n');
155
+ if (newline == std::string_view::npos) {
156
+ return true;
157
+ }
158
+ text.remove_prefix(newline + 1);
159
+ }
160
+ auto hex_value = [](char c) -> int {
161
+ if (c >= '0' && c <= '9') {
162
+ return c - '0';
163
+ }
164
+ if (c >= 'a' && c <= 'f') {
165
+ return c - 'a' + 10;
166
+ }
167
+ if (c >= 'A' && c <= 'F') {
168
+ return c - 'A' + 10;
169
+ }
170
+ return -1;
171
+ };
172
+ int high_nibble = -1;
173
+ for (char c : text) {
174
+ if (c == '\n') {
175
+ continue;
176
+ }
177
+ if (high_nibble < 0 &&
178
+ std::string_view(" \t\r\v\f").find(c) != std::string_view::npos) {
179
+ continue;
180
+ }
181
+ int value = hex_value(c);
182
+ if (value < 0) {
183
+ return false;
184
+ }
185
+ if (high_nibble < 0) {
186
+ high_nibble = value;
187
+ } else {
188
+ exif.push_back(static_cast<unsigned char>(high_nibble << 4 | value));
189
+ high_nibble = -1;
190
+ }
191
+ }
192
+ return high_nibble < 0;
193
+ }
194
+
195
+ // Finds the orientation the way Pillow's ImageOps.exif_transpose() does, after
196
+ // it loaded the whole file: from the eXIf chunk, or else from an ImageMagick
197
+ // "Raw profile type exif" text chunk. Both can come before or after the image
198
+ // data, i.e. in info_ptr or in end_info.
199
+ ExifOrientation fetch_png_orientation(
200
+ png_structp png_ptr,
201
+ png_infop info_ptr,
202
+ png_infop end_info) {
203
+ png_bytep exif = nullptr;
204
+ png_uint_32 num_exif = 0;
205
+ std::string_view raw_profile_exif;
206
+ bool found_raw_profile_exif = false;
207
+ for (png_infop info : {info_ptr, end_info}) {
208
+ if (info == nullptr) {
209
+ continue;
210
+ }
211
+ if (exif == nullptr && png_get_valid(png_ptr, info, PNG_INFO_eXIf)) {
212
+ png_get_eXIf_1(png_ptr, info, &num_exif, &exif);
213
+ }
214
+ png_textp texts = nullptr;
215
+ int num_texts = png_get_text(png_ptr, info, &texts, nullptr);
216
+ for (int i = 0; i < num_texts; ++i) {
217
+ std::string_view text(
218
+ texts[i].text,
219
+ texts[i].compression >= PNG_ITXT_COMPRESSION_NONE
220
+ ? texts[i].itxt_length
221
+ : texts[i].text_length);
222
+ // Like Pillow, we keep the last chunk with this keyword.
223
+ if (std::strcmp(texts[i].key, "Raw profile type exif") == 0) {
224
+ raw_profile_exif = text;
225
+ found_raw_profile_exif = true;
226
+ }
227
+ }
228
+ }
229
+
230
+ ExifOrientation orientation = ExifOrientation::Unspecified;
231
+ std::vector<unsigned char> decoded_exif;
232
+ if (exif != nullptr && num_exif > 0) {
233
+ orientation = fetch_exif_orientation(exif, num_exif);
234
+ } else if (
235
+ found_raw_profile_exif &&
236
+ decode_raw_profile_exif(raw_profile_exif, decoded_exif)) {
237
+ orientation = fetch_exif_orientation_after_prefixes(
238
+ decoded_exif.data(), decoded_exif.size());
239
+ }
240
+ return orientation;
241
+ }
242
+
243
+ struct SourceCtx {
244
+ png_const_bytep ptr;
245
+ png_size_t count;
246
+ };
247
+
248
+ void read_callback(png_structp png_ptr, png_bytep output, png_size_t bytes) {
249
+ auto* source_ctx = static_cast<SourceCtx*>(png_get_io_ptr(png_ptr));
250
+ if (source_ctx->count < bytes) {
251
+ // trigger our error callback
252
+ png_error(
253
+ png_ptr,
254
+ "Out of bound read in decode_png. The input image might be corrupted?");
255
+ }
256
+ std::copy(source_ctx->ptr, source_ctx->ptr + bytes, output);
257
+ source_ctx->ptr += bytes;
258
+ source_ctx->count -= bytes;
259
+ }
260
+
261
+ struct PngHeader {
262
+ png_uint_32 width;
263
+ png_uint_32 height;
264
+ int num_output_channels;
265
+ bool output_16;
266
+ int num_passes;
267
+ };
268
+
269
+ PngHeader read_header_and_configure(
270
+ png_structp& png_ptr,
271
+ png_infop& info_ptr,
272
+ ErrorCtx& error_ctx,
273
+ SourceCtx& source_ctx,
274
+ ImageReadMode read_mode,
275
+ OutputDtype output_dtype) {
276
+ if (setjmp(png_jmpbuf(png_ptr)) != 0) {
277
+ png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
278
+ STD_TORCH_CHECK(false, "decode_png failed: ", error_ctx.error_message);
279
+ }
280
+
281
+ png_set_read_fn(png_ptr, &source_ctx, read_callback);
282
+ png_read_info(png_ptr, info_ptr);
283
+
284
+ png_uint_32 width, height;
285
+ int bit_depth, color_type;
286
+ int interlace_type;
287
+ auto retval = png_get_IHDR(
288
+ png_ptr,
289
+ info_ptr,
290
+ &width,
291
+ &height,
292
+ &bit_depth,
293
+ &color_type,
294
+ &interlace_type,
295
+ nullptr,
296
+ nullptr);
297
+
298
+ if (retval != 1) {
299
+ png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
300
+ STD_TORCH_CHECK(retval == 1, "Could not read image metadata from content.")
301
+ }
302
+
303
+ if (bit_depth > 8 && bit_depth != 16) {
304
+ png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
305
+ STD_TORCH_CHECK(
306
+ false,
307
+ "bit depth of png image is ",
308
+ bit_depth,
309
+ ". Only <=8 and 16 are supported.")
310
+ }
311
+
312
+ bool output_16 = should_output_uint16(output_dtype, bit_depth == 16);
313
+
314
+ int num_output_channels = png_get_channels(png_ptr, info_ptr);
315
+
316
+ if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
317
+ png_set_expand_gray_1_2_4_to_8(png_ptr);
318
+ }
319
+
320
+ int num_passes;
321
+ if (interlace_type == PNG_INTERLACE_ADAM7) {
322
+ num_passes = png_set_interlace_handling(png_ptr);
323
+ } else {
324
+ num_passes = 1;
325
+ }
326
+
327
+ bool is_palette = (color_type & PNG_COLOR_MASK_PALETTE) != 0;
328
+ // A tRNS chunk encodes transparency without a dedicated alpha channel.
329
+ // png_set_tRNS_to_alpha() expands it into a real alpha channel (it must be
330
+ // called after png_set_palette_to_rgb()).
331
+ bool has_trns = png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) != 0;
332
+
333
+ if (read_mode == ImageReadMode::UNCHANGED) {
334
+ if (is_palette) {
335
+ // A PNG palette (PLTE chunk) is always RGB triplets
336
+ // Note that this path is buggy in torchvision, as TV returns the raw
337
+ // palette indices instead of the expanded RGB values. What we do here is
338
+ // correct, and matches the behavior of PIL.
339
+ png_set_palette_to_rgb(png_ptr);
340
+ num_output_channels = 3;
341
+ if (has_trns) {
342
+ png_set_tRNS_to_alpha(png_ptr);
343
+ num_output_channels = 4;
344
+ }
345
+ } else if (has_trns) {
346
+ png_set_strip_alpha(png_ptr);
347
+ }
348
+ } else {
349
+ bool has_color = (color_type & PNG_COLOR_MASK_COLOR) != 0;
350
+ bool has_alpha = (color_type & PNG_COLOR_MASK_ALPHA) != 0 || has_trns;
351
+
352
+ png_uint_32 opaque_alpha = output_16 ? 65535 : 255;
353
+
354
+ switch (read_mode) {
355
+ case ImageReadMode::GRAY:
356
+ if (is_palette) {
357
+ png_set_palette_to_rgb(png_ptr);
358
+ }
359
+
360
+ if (has_alpha) {
361
+ png_set_strip_alpha(png_ptr);
362
+ }
363
+
364
+ if (has_color) {
365
+ png_set_rgb_to_gray(png_ptr, 1, 0.2989, 0.587);
366
+ }
367
+ num_output_channels = 1;
368
+ break;
369
+ case ImageReadMode::GRAY_ALPHA:
370
+ if (is_palette) {
371
+ png_set_palette_to_rgb(png_ptr);
372
+ }
373
+
374
+ if (has_trns) {
375
+ png_set_tRNS_to_alpha(png_ptr);
376
+ } else if (!has_alpha) {
377
+ png_set_add_alpha(png_ptr, opaque_alpha, PNG_FILLER_AFTER);
378
+ }
379
+
380
+ if (has_color) {
381
+ png_set_rgb_to_gray(png_ptr, 1, 0.2989, 0.587);
382
+ }
383
+ num_output_channels = 2;
384
+ break;
385
+ case ImageReadMode::RGB:
386
+ if (is_palette) {
387
+ png_set_palette_to_rgb(png_ptr);
388
+ } else if (!has_color) {
389
+ png_set_gray_to_rgb(png_ptr);
390
+ }
391
+
392
+ if (has_alpha) {
393
+ png_set_strip_alpha(png_ptr);
394
+ }
395
+ num_output_channels = 3;
396
+ break;
397
+ case ImageReadMode::RGB_ALPHA:
398
+ if (is_palette) {
399
+ png_set_palette_to_rgb(png_ptr);
400
+ } else if (!has_color) {
401
+ png_set_gray_to_rgb(png_ptr);
402
+ }
403
+
404
+ if (has_trns) {
405
+ png_set_tRNS_to_alpha(png_ptr);
406
+ } else if (!has_alpha) {
407
+ png_set_add_alpha(png_ptr, opaque_alpha, PNG_FILLER_AFTER);
408
+ }
409
+ num_output_channels = 4;
410
+ break;
411
+ default:
412
+ png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
413
+ STD_TORCH_CHECK(
414
+ false,
415
+ "Reached an unexpected code path while decoding a PNG file to mode ",
416
+ static_cast<int64_t>(read_mode),
417
+ ". This should never happen, please report a bug to the TorchCodec repo.");
418
+ }
419
+ }
420
+
421
+ // libpng knows how to scale 16-bit samples to 8-bit, and vice versa, so we
422
+ // can use that instead of doing it ourselves.
423
+ if (output_16 && bit_depth != 16) {
424
+ png_set_expand_16(png_ptr);
425
+ } else if (!output_16 && bit_depth == 16) {
426
+ png_set_scale_16(png_ptr);
427
+ }
428
+
429
+ png_read_update_info(png_ptr, info_ptr);
430
+
431
+ // png_read_row() writes as many bytes as libpng's own post-transformation
432
+ // layout dictates, but we size the output tensor from num_output_channels,
433
+ // which we track by hand above. We make sure they agree.
434
+ size_t expected_row_bytes = static_cast<size_t>(width) *
435
+ static_cast<size_t>(num_output_channels) * (output_16 ? 2 : 1);
436
+ size_t actual_row_bytes = png_get_rowbytes(png_ptr, info_ptr);
437
+ if (actual_row_bytes != expected_row_bytes) {
438
+ png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
439
+ STD_TORCH_CHECK(
440
+ false,
441
+ "decode_png: libpng rows are ",
442
+ actual_row_bytes,
443
+ " bytes instead of the expected ",
444
+ expected_row_bytes,
445
+ ". This should never happen, please report a bug to the TorchCodec repo.");
446
+ }
447
+
448
+ return {
449
+ .width = width,
450
+ .height = height,
451
+ .num_output_channels = num_output_channels,
452
+ .output_16 = output_16,
453
+ .num_passes = num_passes};
454
+ }
455
+
456
+ void decode_rows(
457
+ png_structp& png_ptr,
458
+ png_infop& info_ptr,
459
+ ErrorCtx& error_ctx,
460
+ uint8_t* output_ptr,
461
+ png_uint_32 height,
462
+ int num_passes,
463
+ int64_t stride) {
464
+ if (setjmp(png_jmpbuf(png_ptr)) != 0) {
465
+ png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
466
+ STD_TORCH_CHECK(false, "decode_png failed: ", error_ctx.error_message);
467
+ }
468
+
469
+ if (std::endian::native == std::endian::little) {
470
+ png_set_swap(png_ptr);
471
+ }
472
+
473
+ for (int pass = 0; pass < num_passes; pass++) {
474
+ uint8_t* row_ptr = output_ptr;
475
+ for (png_uint_32 i = 0; i < height; ++i) {
476
+ png_read_row(png_ptr, row_ptr, nullptr);
477
+ row_ptr += stride;
478
+ }
479
+ }
480
+ }
481
+
482
+ // Reads the chunks after the image data, which can hold metadata too (into
483
+ // end_info). Unlike the image data, these are optional: on error, e.g. if the
484
+ // file is truncated after IDAT, we keep whatever chunks were read until then.
485
+ void read_end(png_structp png_ptr, png_infop end_info) {
486
+ if (setjmp(png_jmpbuf(png_ptr)) != 0) {
487
+ return;
488
+ }
489
+ png_read_end(png_ptr, end_info);
490
+ }
491
+
492
+ } // namespace
493
+
494
+ // Important: see the [libjpeg error handling] in the jpeg decoder: everything
495
+ // applies here too. Critically, we must not throw a C++ exception through
496
+ // libpng's C stack (and callbacks), and we also shouldn't allocate anything
497
+ // that needs proper destruction in a function that defines a setjmp() point.
498
+ // This is why the output tensor is allocated here in decode_png() and
499
+ // decode_png() does *not* define a setjmp() point.
500
+
501
+ torch::stable::Tensor decode_png(
502
+ const torch::stable::Tensor& input,
503
+ int64_t mode,
504
+ int64_t output_dtype) {
505
+ auto contig_input = validate_encoded_data(input);
506
+
507
+ auto input_ptr = contig_input.const_data_ptr<uint8_t>();
508
+
509
+ auto png_ptr =
510
+ png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
511
+ STD_TORCH_CHECK(
512
+ png_ptr != nullptr, "libpng read structure allocation failed!")
513
+ auto info_ptr = png_create_info_struct(png_ptr);
514
+ if (info_ptr == nullptr) {
515
+ png_destroy_read_struct(&png_ptr, nullptr, nullptr);
516
+ STD_TORCH_CHECK(info_ptr, "libpng info structure allocation failed!")
517
+ }
518
+
519
+ ErrorCtx error_ctx;
520
+ png_set_error_fn(png_ptr, &error_ctx, error_callback, /*warn_fn=*/nullptr);
521
+
522
+ SourceCtx source_ctx;
523
+ source_ctx.ptr = reinterpret_cast<png_const_bytep>(input_ptr);
524
+ source_ctx.count = contig_input.numel();
525
+
526
+ torch::stable::Tensor output;
527
+
528
+ auto header = read_header_and_configure(
529
+ png_ptr,
530
+ info_ptr,
531
+ error_ctx,
532
+ source_ctx,
533
+ static_cast<ImageReadMode>(mode),
534
+ static_cast<OutputDtype>(output_dtype));
535
+
536
+ auto output_16 = header.output_16;
537
+ output = torch::stable::empty(
538
+ {static_cast<int64_t>(header.height),
539
+ static_cast<int64_t>(header.width),
540
+ header.num_output_channels},
541
+ output_16 ? kStableUInt16 : kStableUInt8);
542
+
543
+ int64_t bytes_per_pixel = header.num_output_channels * (output_16 ? 2 : 1);
544
+ int64_t stride = static_cast<int64_t>(header.width) * bytes_per_pixel;
545
+ decode_rows(
546
+ png_ptr,
547
+ info_ptr,
548
+ error_ctx,
549
+ static_cast<uint8_t*>(output.mutable_data_ptr()),
550
+ header.height,
551
+ header.num_passes,
552
+ stride);
553
+
554
+ auto end_info = png_create_info_struct(png_ptr);
555
+ if (end_info != nullptr) {
556
+ read_end(png_ptr, end_info);
557
+ }
558
+ ExifOrientation exif_orientation =
559
+ fetch_png_orientation(png_ptr, info_ptr, end_info);
560
+
561
+ png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
562
+
563
+ return exif_orientation_transform(
564
+ stable_permute(output, {2, 0, 1}), exif_orientation);
565
+ }
566
+
567
+ } // namespace facebook::torchcodec
568
+
569
+ #endif // !TORCHCODEC_ENABLE_PNG
@@ -0,0 +1,31 @@
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 <string>
10
+
11
+ #include "StableABICompat.h"
12
+
13
+ namespace facebook::torchcodec {
14
+
15
+ FORCE_PUBLIC_VISIBILITY torch::stable::Tensor decode_png(
16
+ const torch::stable::Tensor& input,
17
+ int64_t mode,
18
+ int64_t output_dtype);
19
+
20
+ // Returns the offset of the first chunk after the run of consecutive IDAT
21
+ // chunks starting at `offset`, or an offset at or past the end of the input if
22
+ // the run reaches it. get_image_metadata() needs the chunks after the image
23
+ // data, and walking over the (often thousands of) IDAT chunks in Python is
24
+ // slow. These don't need libpng.
25
+ FORCE_PUBLIC_VISIBILITY int64_t png_skip_idat_chunks_from_tensor(
26
+ const torch::stable::Tensor& input,
27
+ int64_t offset);
28
+ FORCE_PUBLIC_VISIBILITY int64_t
29
+ png_skip_idat_chunks_from_file(std::string filename, int64_t offset);
30
+
31
+ } // namespace facebook::torchcodec