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,238 @@
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 "DecodeWebp.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_WEBP
16
+
17
+ namespace facebook::torchcodec {
18
+
19
+ torch::stable::Tensor decode_webp(
20
+ [[maybe_unused]] const torch::stable::Tensor& input,
21
+ [[maybe_unused]] int64_t mode) {
22
+ STD_TORCH_CHECK(
23
+ false,
24
+ "decode_webp: torchcodec was not compiled with libwebp support. Rebuild "
25
+ "torchcodec with TORCHCODEC_BUILD_WEBP=1. If you see this error in a "
26
+ "prebuilt wheel, please report it to the TorchCodec repo.");
27
+ }
28
+
29
+ } // namespace facebook::torchcodec
30
+
31
+ #else
32
+
33
+ #include "webp/decode.h"
34
+ #include "webp/demux.h"
35
+ #include "webp/types.h"
36
+
37
+ #include <torch/headeronly/core/MemoryFormat.h>
38
+
39
+ #include <algorithm>
40
+
41
+ #include "Exif.h"
42
+ #include "ImageCommon.h"
43
+
44
+ namespace facebook::torchcodec {
45
+
46
+ using namespace exif_private;
47
+
48
+ namespace {
49
+
50
+ // Find the EXIF orientation by asking libwebpdemux for the "EXIF" chunk (which
51
+ // only exists in extended VP8X files and holds raw TIFF-formatted EXIF data).
52
+ // Returns Unspecified (i.e. no rotation) when there's no usable EXIF chunk.
53
+ ExifOrientation fetch_webp_exif_orientation(const uint8_t* data, size_t size) {
54
+ WebPData webp_data;
55
+ WebPDataInit(&webp_data);
56
+ webp_data.bytes = data;
57
+ webp_data.size = size;
58
+
59
+ WebPDemuxer* demux = WebPDemux(&webp_data);
60
+ if (demux == nullptr) {
61
+ return ExifOrientation::Unspecified;
62
+ }
63
+
64
+ ExifOrientation orientation = ExifOrientation::Unspecified;
65
+ WebPChunkIterator chunk_iter;
66
+ if (WebPDemuxGetChunk(demux, "EXIF", 1, &chunk_iter)) {
67
+ // Some encoders prefix the payload with the "Exif\0\0" marker (like the
68
+ // JPEG APP1 segment).
69
+ orientation = fetch_exif_orientation_after_prefixes(
70
+ chunk_iter.chunk.bytes, chunk_iter.chunk.size);
71
+ WebPDemuxReleaseChunkIterator(&chunk_iter);
72
+ }
73
+
74
+ WebPDemuxDelete(demux);
75
+ return orientation;
76
+ }
77
+
78
+ torch::stable::Tensor decode_animated_webp(
79
+ const uint8_t* input_ptr,
80
+ size_t input_size,
81
+ int64_t mode,
82
+ bool has_alpha) {
83
+ bool return_rgb =
84
+ should_return_rgb(static_cast<ImageReadMode>(mode), has_alpha);
85
+ int num_output_channels = return_rgb ? 3 : 4;
86
+
87
+ WebPData webp_data;
88
+ WebPDataInit(&webp_data);
89
+ webp_data.bytes = input_ptr;
90
+ webp_data.size = input_size;
91
+
92
+ WebPAnimDecoderOptions dec_options;
93
+ STD_TORCH_CHECK(
94
+ WebPAnimDecoderOptionsInit(&dec_options),
95
+ "WebPAnimDecoderOptionsInit failed. This is likely a version mismatch "
96
+ "with libwebpdemux.");
97
+ // WebPAnimDecoder can only emit RGBA/BGRA (no 3-channel RGB), so we always
98
+ // decode RGBA and skip the alpha below if the user wants RGB.
99
+ dec_options.color_mode = MODE_RGBA;
100
+
101
+ WebPAnimDecoder* dec = WebPAnimDecoderNew(&webp_data, &dec_options);
102
+ STD_TORCH_CHECK(
103
+ dec != nullptr,
104
+ "WebPAnimDecoderNew failed. The file is likely corrupted or truncated.");
105
+
106
+ WebPAnimInfo anim_info;
107
+ if (!WebPAnimDecoderGetInfo(dec, &anim_info)) {
108
+ WebPAnimDecoderDelete(dec);
109
+ STD_TORCH_CHECK(false, "WebPAnimDecoderGetInfo failed.");
110
+ }
111
+
112
+ auto num_frames = static_cast<int64_t>(anim_info.frame_count);
113
+ auto height = static_cast<int64_t>(anim_info.canvas_height);
114
+ auto width = static_cast<int64_t>(anim_info.canvas_width);
115
+
116
+ auto output = torch::stable::empty(
117
+ {num_frames, num_output_channels, height, width},
118
+ kStableUInt8,
119
+ std::nullopt,
120
+ std::nullopt,
121
+ std::nullopt,
122
+ torch::headeronly::MemoryFormat::ChannelsLast);
123
+ auto output_a = mutable_accessor<uint8_t, 4>(output);
124
+ uint8_t* output_ptr = output.mutable_data_ptr<uint8_t>();
125
+ const int64_t frame_num_bytes =
126
+ static_cast<int64_t>(num_output_channels) * height * width;
127
+
128
+ int64_t frame_index = 0;
129
+ while (WebPAnimDecoderHasMoreFrames(dec)) {
130
+ if (frame_index >= num_frames) {
131
+ // Guard against the decoder yielding more frames than it reported, which
132
+ // would write past the output tensor.
133
+ break;
134
+ }
135
+
136
+ // frame_rgba is an internal buffer owned by dec: we must not free it, and
137
+ // it's overwritten on the next GetNext call (and released by
138
+ // WebPAnimDecoderDelete), so we copy each frame out below.
139
+ uint8_t* frame_rgba = nullptr;
140
+ int timestamp = 0; // in ms. unused for now (we return plain tensors).
141
+ if (!WebPAnimDecoderGetNext(dec, &frame_rgba, &timestamp)) {
142
+ WebPAnimDecoderDelete(dec);
143
+ STD_TORCH_CHECK(
144
+ false,
145
+ "WebPAnimDecoderGetNext failed at frame ",
146
+ frame_index,
147
+ ". The file is likely corrupted or truncated.");
148
+ }
149
+ if (!return_rgb) {
150
+ std::copy(
151
+ frame_rgba,
152
+ frame_rgba + frame_num_bytes,
153
+ output_ptr + frame_index * frame_num_bytes);
154
+ } else {
155
+ // We're dropping the decoder's alpha, so we can't std::copy.
156
+ for (int64_t y = 0; y < height; ++y) {
157
+ for (int64_t x = 0; x < width; ++x) {
158
+ const uint8_t* px = frame_rgba + (y * width + x) * 4;
159
+ output_a[frame_index][0][y][x] = px[0];
160
+ output_a[frame_index][1][y][x] = px[1];
161
+ output_a[frame_index][2][y][x] = px[2];
162
+ }
163
+ }
164
+ }
165
+ ++frame_index;
166
+ }
167
+
168
+ WebPAnimDecoderDelete(dec);
169
+
170
+ STD_TORCH_CHECK(
171
+ frame_index == num_frames,
172
+ "Decoded ",
173
+ frame_index,
174
+ " webp frame(s) but expected ",
175
+ num_frames,
176
+ ". The file is likely corrupted or truncated.");
177
+
178
+ return output;
179
+ }
180
+
181
+ torch::stable::Tensor decode_still_webp(
182
+ const uint8_t* input_ptr,
183
+ size_t input_size,
184
+ int64_t mode,
185
+ bool has_alpha) {
186
+ bool return_rgb =
187
+ should_return_rgb(static_cast<ImageReadMode>(mode), has_alpha);
188
+
189
+ auto decoding_func = return_rgb ? WebPDecodeRGB : WebPDecodeRGBA;
190
+ int num_output_channels = return_rgb ? 3 : 4;
191
+
192
+ int width = 0;
193
+ int height = 0;
194
+ auto decoded_data = decoding_func(input_ptr, input_size, &width, &height);
195
+ STD_TORCH_CHECK(
196
+ decoded_data != nullptr,
197
+ "Failed to decode the WebP bitstream. "
198
+ "The file is likely corrupted or truncated.");
199
+
200
+ auto deleter = [decoded_data](void*) { WebPFree(decoded_data); };
201
+ auto output = torch::stable::from_blob(
202
+ decoded_data,
203
+ {height, width, num_output_channels},
204
+ {width * num_output_channels, num_output_channels, 1},
205
+ StableDevice(kStableCPU),
206
+ kStableUInt8,
207
+ deleter);
208
+
209
+ return stable_permute(output, {2, 0, 1});
210
+ }
211
+
212
+ } // namespace
213
+
214
+ torch::stable::Tensor decode_webp(
215
+ const torch::stable::Tensor& input,
216
+ int64_t mode) {
217
+ auto contig_input = validate_encoded_data(input);
218
+
219
+ auto input_ptr = contig_input.const_data_ptr<uint8_t>();
220
+ auto input_size = contig_input.numel();
221
+
222
+ WebPBitstreamFeatures features;
223
+ auto res = WebPGetFeatures(input_ptr, input_size, &features);
224
+ STD_TORCH_CHECK(
225
+ res == VP8_STATUS_OK, "WebPGetFeatures failed with error code ", res);
226
+
227
+ auto output = features.has_animation
228
+ ? decode_animated_webp(input_ptr, input_size, mode, features.has_alpha)
229
+ : decode_still_webp(input_ptr, input_size, mode, features.has_alpha);
230
+
231
+ ExifOrientation exif_orientation =
232
+ fetch_webp_exif_orientation(input_ptr, input_size);
233
+ return exif_orientation_transform(output, exif_orientation);
234
+ }
235
+
236
+ } // namespace facebook::torchcodec
237
+
238
+ #endif // !TORCHCODEC_ENABLE_WEBP
@@ -0,0 +1,17 @@
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 "StableABICompat.h"
10
+
11
+ namespace facebook::torchcodec {
12
+
13
+ FORCE_PUBLIC_VISIBILITY torch::stable::Tensor decode_webp(
14
+ const torch::stable::Tensor& input,
15
+ int64_t mode);
16
+
17
+ } // namespace facebook::torchcodec
@@ -0,0 +1,415 @@
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 "Demuxer.h"
8
+
9
+ #include <algorithm>
10
+ #include <sstream>
11
+
12
+ #include "StableABICompat.h"
13
+
14
+ namespace facebook::torchcodec {
15
+
16
+ // FFmpeg reports "this seek cannot be performed" as a bare -1, i.e. EPERM,
17
+ // which renders as the very misleading "Operation not permitted". It covers
18
+ // both a target that the demuxer can't reach and a demuxer with no seeking
19
+ // support whatsoever.
20
+ std::string get_seek_error_message(
21
+ const AVFormatContext* format_context,
22
+ int64_t desired_pts,
23
+ int status) {
24
+ std::stringstream ss;
25
+ ss << "Could not seek file to pts=" << desired_pts << ": "
26
+ << get_ffmpeg_error_string_from_error_code(status) << ".";
27
+ if (status == AVERROR(EPERM)) {
28
+ ss << " This is either because that timestamp is out of range, or because"
29
+ << " the '" << format_context->iformat->name << "' format does not"
30
+ << " support seeking.";
31
+ }
32
+ return ss.str();
33
+ }
34
+
35
+ namespace {
36
+ template <typename IsActive>
37
+ int read_next_active_packet(
38
+ AVFormatContext* format_context,
39
+ AVPacket& packet,
40
+ IsActive is_active) {
41
+ int status = AVSUCCESS;
42
+ do {
43
+ // av_read_frame() requires a packet with nothing to free in it, so drop
44
+ // what the previous iteration read from a stream we're not following. A
45
+ // no-op on the first iteration.
46
+ av_packet_unref(&packet);
47
+ status = av_read_frame(format_context, &packet);
48
+ if (status == AVERROR_EOF || status < AVSUCCESS) {
49
+ return status;
50
+ }
51
+ } while (!is_active(packet.stream_index));
52
+ return AVSUCCESS;
53
+ }
54
+ } // namespace
55
+
56
+ int read_next_packet(
57
+ AVFormatContext* format_context,
58
+ int active_stream_index,
59
+ AVPacket& packet) {
60
+ return read_next_active_packet(
61
+ format_context, packet, [active_stream_index](int stream_index) {
62
+ return stream_index == active_stream_index;
63
+ });
64
+ }
65
+
66
+ int read_next_packet(
67
+ AVFormatContext* format_context,
68
+ const std::vector<int>& active_stream_indices,
69
+ AVPacket& packet) {
70
+ return read_next_active_packet(
71
+ format_context, packet, [&active_stream_indices](int stream_index) {
72
+ return std::find(
73
+ active_stream_indices.begin(),
74
+ active_stream_indices.end(),
75
+ stream_index) != active_stream_indices.end();
76
+ });
77
+ }
78
+
79
+ namespace {
80
+ // "video" / "audio", for error messages.
81
+ const char* printable(AVMediaType media_type) {
82
+ const char* name = av_get_media_type_string(media_type);
83
+ return name == nullptr ? "unknown" : name;
84
+ }
85
+ } // namespace
86
+
87
+ Demuxer::Demuxer(const std::string& file_path) {
88
+ set_ffmpeg_log_level();
89
+
90
+ AVFormatContext* raw_context = nullptr;
91
+ int status =
92
+ avformat_open_input(&raw_context, file_path.c_str(), nullptr, nullptr);
93
+ STD_TORCH_CHECK(
94
+ status == 0,
95
+ "Could not open input file: " + file_path + " " +
96
+ get_ffmpeg_error_string_from_error_code(status));
97
+ STD_TORCH_CHECK(raw_context != nullptr, "Failed to allocate AVFormatContext");
98
+ format_context_.reset(raw_context);
99
+
100
+ find_stream_info();
101
+ }
102
+
103
+ Demuxer::Demuxer(std::unique_ptr<AVIOContextHolder> avio_context_holder)
104
+ : avio_context_holder_(std::move(avio_context_holder)) {
105
+ set_ffmpeg_log_level();
106
+
107
+ STD_TORCH_CHECK(avio_context_holder_ != nullptr, "Context holder is null");
108
+
109
+ // FFmpeg takes a reference to the pointer in the call to open, so we can't
110
+ // hand it a unique_ptr. That means we must free the context ourselves if the
111
+ // open fails.
112
+ AVFormatContext* raw_context = avformat_alloc_context();
113
+ STD_TORCH_CHECK(raw_context != nullptr, "Failed to allocate AVFormatContext");
114
+ raw_context->pb = avio_context_holder_->get_avio_context();
115
+ forbid_nested_protocols(raw_context);
116
+
117
+ int status = avformat_open_input(&raw_context, nullptr, nullptr, nullptr);
118
+ if (status != 0) {
119
+ avformat_free_context(raw_context);
120
+ STD_TORCH_CHECK(
121
+ false,
122
+ "Could not open input buffer: " +
123
+ get_ffmpeg_error_string_from_error_code(status));
124
+ }
125
+ format_context_.reset(raw_context);
126
+
127
+ find_stream_info();
128
+ }
129
+
130
+ void Demuxer::find_stream_info() {
131
+ int status = avformat_find_stream_info(format_context_.get(), nullptr);
132
+ STD_TORCH_CHECK(
133
+ status >= 0,
134
+ "Failed to find stream info: ",
135
+ get_ffmpeg_error_string_from_error_code(status));
136
+
137
+ // We only want packets from the streams we're asked to follow, so discard
138
+ // every stream until add_stream() says otherwise. Note av_read_frame() may
139
+ // still return some of them under certain conditions, which is why
140
+ // read_next_packet() also filters by stream index.
141
+ for (unsigned int i = 0; i < format_context_->nb_streams; ++i) {
142
+ format_context_->streams[i]->discard = AVDISCARD_ALL;
143
+ }
144
+ }
145
+
146
+ void Demuxer::validate_requested_stream(int stream_index) {
147
+ int num_streams = static_cast<int>(format_context_->nb_streams);
148
+ STD_TORCH_CHECK(
149
+ stream_index >= 0 && stream_index < num_streams,
150
+ "The stream index ",
151
+ stream_index,
152
+ " is not a valid stream. The file has ",
153
+ num_streams,
154
+ " streams, so the index must be in [0, ",
155
+ num_streams - 1,
156
+ "].");
157
+
158
+ AVMediaType stream_media_type =
159
+ format_context_->streams[stream_index]->codecpar->codec_type;
160
+ STD_TORCH_CHECK(
161
+ stream_media_type == AVMEDIA_TYPE_VIDEO ||
162
+ stream_media_type == AVMEDIA_TYPE_AUDIO,
163
+ "The stream at index ",
164
+ stream_index,
165
+ " is of type '",
166
+ printable(stream_media_type),
167
+ "', which cannot be decoded. Only audio and video streams can.");
168
+ }
169
+
170
+ std::pair<int, AVMediaType> Demuxer::add_stream(
171
+ std::optional<int> stream_index,
172
+ std::optional<AVMediaType> media_type) {
173
+ STD_TORCH_CHECK(
174
+ stream_index.has_value() != media_type.has_value(),
175
+ "A stream must be identified by either its index or its media type, "
176
+ "not both and not neither.");
177
+ STD_TORCH_CHECK(
178
+ !has_demuxed_,
179
+ "Streams must all be added before the first packet is demuxed: a stream "
180
+ "added now would start at wherever the container currently is, not at "
181
+ "the beginning.");
182
+
183
+ int index;
184
+ if (stream_index.has_value()) {
185
+ validate_requested_stream(*stream_index);
186
+ index = *stream_index;
187
+ } else {
188
+ index = av_find_best_stream(
189
+ format_context_.get(),
190
+ *media_type,
191
+ /*wanted_stream_nb=*/-1,
192
+ /*related_stream=*/-1,
193
+ /*decoder_ret=*/nullptr,
194
+ /*flags=*/0);
195
+ STD_TORCH_CHECK(
196
+ index >= 0,
197
+ "No valid ",
198
+ printable(*media_type),
199
+ " stream found in input file.");
200
+ }
201
+
202
+ STD_TORCH_CHECK(
203
+ std::find(
204
+ active_stream_indices_.begin(),
205
+ active_stream_indices_.end(),
206
+ index) == active_stream_indices_.end(),
207
+ "The stream at index ",
208
+ index,
209
+ " is already being demuxed.");
210
+
211
+ format_context_->streams[index]->discard = AVDISCARD_DEFAULT;
212
+ active_stream_indices_.push_back(index);
213
+ return {index, format_context_->streams[index]->codecpar->codec_type};
214
+ }
215
+
216
+ torch::stable::Tensor Demuxer::get_audio_video_stream_indices() const {
217
+ std::vector<int> indices;
218
+ for (unsigned int i = 0; i < format_context_->nb_streams; ++i) {
219
+ AVMediaType type = format_context_->streams[i]->codecpar->codec_type;
220
+ if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO) {
221
+ indices.push_back(static_cast<int>(i));
222
+ }
223
+ }
224
+ STD_TORCH_CHECK(
225
+ !indices.empty(),
226
+ "This container has no audio or video stream at all, so there is "
227
+ "nothing that could be demuxed.");
228
+
229
+ auto out = torch::stable::empty(
230
+ {static_cast<int64_t>(indices.size())}, kStableInt64);
231
+ auto accessor = mutable_accessor<int64_t, 1>(out);
232
+ for (size_t i = 0; i < indices.size(); ++i) {
233
+ accessor[i] = indices[i];
234
+ }
235
+ return out;
236
+ }
237
+
238
+ CodecParameters Demuxer::get_codec_parameters(
239
+ std::optional<int> stream_index) const {
240
+ return CodecParameters(
241
+ *format_context_->streams[resolve_stream_index(stream_index)],
242
+ format_context_->iformat);
243
+ }
244
+
245
+ int Demuxer::resolve_stream_index(std::optional<int> stream_index) const {
246
+ if (stream_index.has_value()) {
247
+ STD_TORCH_CHECK(
248
+ std::find(
249
+ active_stream_indices_.begin(),
250
+ active_stream_indices_.end(),
251
+ *stream_index) != active_stream_indices_.end(),
252
+ "The stream at index ",
253
+ *stream_index,
254
+ " is not being demuxed.");
255
+ return *stream_index;
256
+ }
257
+ STD_TORCH_CHECK(
258
+ active_stream_indices_.size() == 1,
259
+ "This demuxer follows ",
260
+ active_stream_indices_.size(),
261
+ " streams, so the stream index must be specified.");
262
+ return active_stream_indices_[0];
263
+ }
264
+
265
+ AVStream* Demuxer::get_reference_stream() const {
266
+ STD_TORCH_CHECK(
267
+ !active_stream_indices_.empty(),
268
+ "This demuxer isn't following any stream yet.");
269
+ return format_context_->streams[active_stream_indices_[0]];
270
+ }
271
+
272
+ void Demuxer::seek(double seconds, std::optional<int> stream_index) {
273
+ AVStream* reference = stream_index.has_value()
274
+ ? format_context_->streams[resolve_stream_index(stream_index)]
275
+ : get_reference_stream();
276
+ int64_t desired_pts = seconds_to_closest_pts(seconds, reference->time_base);
277
+
278
+ int status = avformat_seek_file(
279
+ format_context_.get(),
280
+ reference->index,
281
+ INT64_MIN,
282
+ desired_pts,
283
+ desired_pts,
284
+ 0);
285
+ bool can_seek_bytes = !(format_context_->iformat->flags & AVFMT_NO_BYTE_SEEK);
286
+ if (status < 0 && can_seek_bytes && seconds == 0) {
287
+ // Streams without timestamps, like raw H.264 or HEVC streams, can't seek
288
+ // to a timestamp, but they can still be rewound to their start.
289
+ status = avformat_seek_file(
290
+ format_context_.get(), -1, 0, 0, 0, AVSEEK_FLAG_BYTE);
291
+ }
292
+ STD_TORCH_CHECK(
293
+ status >= 0,
294
+ get_seek_error_message(format_context_.get(), desired_pts, status),
295
+ can_seek_bytes ? " If this stream has no timestamps (e.g. a raw H.264 "
296
+ "or HEVC stream), it can only be rewound to its start, "
297
+ "by seeking to 0."
298
+ : "");
299
+ }
300
+
301
+ void Demuxer::scan_all_video_streams() {
302
+ if (has_scanned_) {
303
+ return;
304
+ }
305
+ STD_TORCH_CHECK(
306
+ !has_demuxed_,
307
+ "A scan reads the container from end to end and rewinds it, so it has to "
308
+ "happen before any packet is demuxed. Scan up front, or build a second "
309
+ "demuxer for it.");
310
+
311
+ std::vector<int> video_stream_indices;
312
+ for (int index : active_stream_indices_) {
313
+ AVStream* candidate = format_context_->streams[index];
314
+ if (candidate->codecpar->codec_type != AVMEDIA_TYPE_VIDEO) {
315
+ continue;
316
+ }
317
+ video_stream_indices.push_back(index);
318
+ auto& packets = scanned_packets_[index];
319
+ if (candidate->nb_frames > 0) {
320
+ packets.reserve(static_cast<size_t>(candidate->nb_frames));
321
+ }
322
+ }
323
+
324
+ seek(0);
325
+
326
+ // One pass, however many video streams are being followed: the I/O is what a
327
+ // scan costs, and it is the same read for all of them.
328
+ while (true) {
329
+ ReferenceAVPacket packet(auto_packet_);
330
+ int status =
331
+ read_next_packet(format_context_.get(), video_stream_indices, *packet);
332
+ if (status == AVERROR_EOF) {
333
+ break;
334
+ }
335
+ STD_TORCH_CHECK(
336
+ status >= AVSUCCESS,
337
+ "Could not read frame from input file: ",
338
+ get_ffmpeg_error_string_from_error_code(status));
339
+
340
+ if (packet->flags & AV_PKT_FLAG_DISCARD) {
341
+ continue;
342
+ }
343
+
344
+ scanned_packets_[packet->stream_index].push_back(
345
+ {get_pts_or_dts(packet),
346
+ packet->duration,
347
+ (packet->flags & AV_PKT_FLAG_KEY) != 0});
348
+ }
349
+
350
+ seek(0);
351
+ has_scanned_ = true;
352
+ }
353
+
354
+ FrameIndex Demuxer::scan(std::optional<int> stream_index) {
355
+ AVStream* scanned_stream =
356
+ format_context_->streams[resolve_stream_index(stream_index)];
357
+ STD_TORCH_CHECK(
358
+ scanned_stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO,
359
+ "Only a video stream can be scanned: a frame index describes keyframes "
360
+ "and frame positions, and the stream at index ",
361
+ scanned_stream->index,
362
+ " has neither.");
363
+
364
+ scan_all_video_streams();
365
+
366
+ // Sorting and building the tensors is per-stream work, so it is only done for
367
+ // the streams whose index is actually asked for.
368
+ std::vector<FrameInfo>& packets = scanned_packets_.at(scanned_stream->index);
369
+ std::stable_sort(
370
+ packets.begin(),
371
+ packets.end(),
372
+ [](const FrameInfo& a, const FrameInfo& b) { return a.pts < b.pts; });
373
+
374
+ auto num_frames = static_cast<int64_t>(packets.size());
375
+ FrameIndex index{
376
+ torch::stable::empty({num_frames}, kStableInt64),
377
+ torch::stable::empty({num_frames}, kStableInt64),
378
+ torch::stable::empty({num_frames}, kStableBool),
379
+ scanned_stream->time_base};
380
+
381
+ auto pts = mutable_accessor<int64_t, 1>(index.pts);
382
+ auto duration = mutable_accessor<int64_t, 1>(index.duration);
383
+ auto is_key_frame = mutable_accessor<bool, 1>(index.is_key_frame);
384
+ for (int64_t i = 0; i < num_frames; ++i) {
385
+ pts[i] = packets[i].pts;
386
+ duration[i] = packets[i].duration;
387
+ is_key_frame[i] = packets[i].is_key_frame;
388
+ }
389
+
390
+ return index;
391
+ }
392
+
393
+ UniqueAVPacket Demuxer::next_packet() {
394
+ STD_TORCH_CHECK(
395
+ !active_stream_indices_.empty(),
396
+ "This demuxer isn't following any stream yet.");
397
+ has_demuxed_ = true;
398
+
399
+ UniqueAVPacket packet(av_packet_alloc());
400
+ STD_TORCH_CHECK(packet != nullptr, "Failed to allocate AVPacket");
401
+
402
+ int status =
403
+ read_next_packet(format_context_.get(), active_stream_indices_, *packet);
404
+ if (status == AVERROR_EOF) {
405
+ return UniqueAVPacket{};
406
+ }
407
+ STD_TORCH_CHECK(
408
+ status >= AVSUCCESS,
409
+ "Could not read frame from input file: ",
410
+ get_ffmpeg_error_string_from_error_code(status));
411
+
412
+ return packet;
413
+ }
414
+
415
+ } // namespace facebook::torchcodec