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,654 @@
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 "CpuDeviceInterface.h"
8
+
9
+ #include <algorithm>
10
+ #include <cmath>
11
+ #include <numeric>
12
+ #include <sstream>
13
+ #include "AudioCommon.h"
14
+
15
+ namespace facebook::torchcodec {
16
+
17
+ namespace {
18
+
19
+ AVPixelFormat validate_pixel_format(
20
+ const AVCodec& av_codec,
21
+ const std::string& target_pixel_format) {
22
+ AVPixelFormat pixel_format = av_get_pix_fmt(target_pixel_format.c_str());
23
+ const AVPixelFormat* supported_formats =
24
+ get_supported_pixel_formats(av_codec);
25
+ if (supported_formats != nullptr) {
26
+ for (int i = 0; supported_formats[i] != AV_PIX_FMT_NONE; ++i) {
27
+ if (supported_formats[i] == pixel_format) {
28
+ return pixel_format;
29
+ }
30
+ }
31
+ }
32
+ std::stringstream error_msg;
33
+ if (pixel_format == AV_PIX_FMT_NONE) {
34
+ error_msg << "Unknown pixel format: " << target_pixel_format;
35
+ } else {
36
+ error_msg << "Specified pixel format " << target_pixel_format
37
+ << " is not supported by the " << av_codec.name << " encoder.";
38
+ }
39
+ error_msg << "\nSupported pixel formats for " << av_codec.name << ":";
40
+ if (supported_formats != nullptr) {
41
+ for (int i = 0; supported_formats[i] != AV_PIX_FMT_NONE; ++i) {
42
+ error_msg << " " << av_get_pix_fmt_name(supported_formats[i]);
43
+ }
44
+ }
45
+ STD_TORCH_CHECK(false, error_msg.str());
46
+ }
47
+
48
+ AVPixelFormat get_output_pixel_format(OutputDtype output_dtype) {
49
+ return output_dtype == OutputDtype::FLOAT32 ? AV_PIX_FMT_RGB48
50
+ : AV_PIX_FMT_RGB24;
51
+ }
52
+
53
+ // Returns the format filter string for the given output pixel format.
54
+ std::string get_format_filter_string(AVPixelFormat output_format) {
55
+ return (output_format == AV_PIX_FMT_RGB48) ? "format=rgb48,"
56
+ : "format=rgb24,";
57
+ }
58
+
59
+ static bool g_cpu = register_device_interface(
60
+ DeviceInterfaceKey(kStableCPU),
61
+ [](const StableDevice& device) { return new CpuDeviceInterface(device); });
62
+
63
+ } // namespace
64
+
65
+ AVPixelFormat CpuDeviceInterface::get_encoding_pixel_format(
66
+ const AVCodec& av_codec,
67
+ const std::optional<std::string>& user_pixel_format) const {
68
+ if (user_pixel_format.has_value()) {
69
+ return validate_pixel_format(av_codec, user_pixel_format.value());
70
+ }
71
+ const AVPixelFormat* formats = get_supported_pixel_formats(av_codec);
72
+ // Pick the codec's first supported format (often yuv420p), else fall back.
73
+ return (formats && formats[0] != AV_PIX_FMT_NONE) ? formats[0]
74
+ : AV_PIX_FMT_YUV420P;
75
+ }
76
+
77
+ CpuDeviceInterface::CpuDeviceInterface(const StableDevice& device)
78
+ : DeviceInterface(device) {
79
+ STD_TORCH_CHECK(g_cpu, "CpuDeviceInterface was not registered!");
80
+ STD_TORCH_CHECK(
81
+ device_.type() == kStableCPU, "Unsupported device: must be CPU");
82
+ }
83
+
84
+ void CpuDeviceInterface::initialize(const SharedAVCodecContext& codec_context) {
85
+ codec_context_ = codec_context;
86
+ }
87
+
88
+ void CpuDeviceInterface::initialize_video_decoding(
89
+ const CodecParameters& codec_parameters,
90
+ [[maybe_unused]] const VideoStreamOptions& video_stream_options) {
91
+ time_base_ = codec_parameters.time_base;
92
+ }
93
+
94
+ void CpuDeviceInterface::initialize_color_conversion(
95
+ const VideoStreamOptions& video_stream_options,
96
+ const std::vector<std::unique_ptr<Transform>>& transforms,
97
+ const std::optional<FrameDims>& resized_output_dims) {
98
+ av_media_type_ = AVMEDIA_TYPE_VIDEO;
99
+ video_stream_options_ = video_stream_options;
100
+ resized_output_dims_ = resized_output_dims;
101
+ output_pixel_format_ =
102
+ get_output_pixel_format(video_stream_options_.output_dtype);
103
+
104
+ // We can use swscale when we have a single resize transform.
105
+ // With a single resize, we use swscale twice:
106
+ // first for color conversion (YUV->RGB24), then for resize in RGB24 space.
107
+ //
108
+ // Note that this means swscale will not support the case of having several,
109
+ // back-to-back resizes or other transforms.
110
+ //
111
+ // We calculate this value during initialization but we don't refer to it
112
+ // until getColorConversionLibrary() is called. Calculating this value during
113
+ // initialization saves us from having to save all of the transforms.
114
+ are_transforms_sw_scale_compatible_ = transforms.empty() ||
115
+ (transforms.size() == 1 && transforms[0]->is_resize());
116
+
117
+ // Note that we do not expose this capability in the public API, only through
118
+ // the core API.
119
+ //
120
+ // Same as above, we calculate this value during initialization and refer to
121
+ // it in getColorConversionLibrary().
122
+ user_requested_sw_scale_ = video_stream_options_.color_conversion_library ==
123
+ ColorConversionLibrary::SWSCALE;
124
+
125
+ // We can only use swscale when we have a single resize transform. Note that
126
+ // we actually decide on whether or not to actually use swscale at the last
127
+ // possible moment, when we actually convert the frame. This is because we
128
+ // need to know the actual frame dimensions.
129
+ if (transforms.size() == 1 && transforms[0]->is_resize()) {
130
+ auto resize = dynamic_cast<ResizeTransform*>(transforms[0].get());
131
+ STD_TORCH_CHECK(
132
+ resize != nullptr, "ResizeTransform expected but not found!");
133
+ sws_flags_ = resize->get_sws_flags();
134
+ }
135
+
136
+ // If we have any transforms, replace filters_ with the filter strings from
137
+ // the transforms. As noted above, we decide between swscale and filtergraph
138
+ // when we actually decode a frame.
139
+ std::stringstream filters;
140
+ bool first = true;
141
+ for (const auto& transform : transforms) {
142
+ if (!first) {
143
+ filters << ",";
144
+ }
145
+ filters << transform->get_filter_graph_cpu();
146
+ first = false;
147
+ }
148
+ if (!transforms.empty()) {
149
+ // Note [Transform and Format Conversion Order]
150
+ // We have to ensure that all user filters happen AFTER the explicit format
151
+ // conversion. That is, we want the filters to be applied in the output RGB
152
+ // color space, not the pixel format of the input frame.
153
+ //
154
+ // The output frame will always be in the output RGB format (RGB24 or
155
+ // RGB48), as we specify the sink node with the appropriate format.
156
+ // Filtergraph will automatically insert a format conversion to ensure the
157
+ // output frame matches the pixel format specified in the sink. But by
158
+ // default, it will insert it after the user filters. We need an explicit
159
+ // format conversion to get the behavior we want.
160
+ filters_ = get_format_filter_string(output_pixel_format_) + filters.str();
161
+ }
162
+
163
+ initialized_ = true;
164
+ }
165
+
166
+ void CpuDeviceInterface::initialize_audio(
167
+ const AudioStreamOptions& audio_stream_options,
168
+ double stream_start_seconds) {
169
+ av_media_type_ = AVMEDIA_TYPE_AUDIO;
170
+ audio_stream_options_ = audio_stream_options;
171
+ audio_stream_start_seconds_ = stream_start_seconds;
172
+ initialized_ = true;
173
+ }
174
+
175
+ ColorConversionLibrary CpuDeviceInterface::get_color_conversion_library(
176
+ const FrameDims& input_dims,
177
+ const FrameDims& output_dims) const {
178
+ // swscale requires widths to be multiples of 32:
179
+ // https://stackoverflow.com/questions/74351955/turn-off-sw-scale-conversion-to-planar-yuv-32-byte-alignment-requirements
180
+ bool are_widths_sw_scale_compatible =
181
+ (input_dims.width % 32) == 0 && (output_dims.width % 32) == 0;
182
+
183
+ // We want to use swscale for color conversion if possible because it is
184
+ // faster than filtergraph. The following are the conditions we need to meet
185
+ // to use it.
186
+ //
187
+ // Note that we treat the transform limitation differently from the width
188
+ // limitation. That is, we consider the transforms being compatible with
189
+ // swscale as a hard requirement. If the transforms are not compatiable,
190
+ // then we will end up not applying the transforms, and that is wrong.
191
+ //
192
+ // The width requirement, however, is a soft requirement. Even if we don't
193
+ // meet it, we let the user override it. We have tests that depend on this
194
+ // behavior. Since we don't expose the ability to choose swscale or
195
+ // filtergraph in our public API, this is probably okay. It's also the only
196
+ // way that we can be certain we are testing one versus the other.
197
+ if (are_transforms_sw_scale_compatible_ &&
198
+ (user_requested_sw_scale_ || are_widths_sw_scale_compatible)) {
199
+ return ColorConversionLibrary::SWSCALE;
200
+ } else {
201
+ return ColorConversionLibrary::FILTERGRAPH;
202
+ }
203
+ }
204
+
205
+ void CpuDeviceInterface::convert_av_frame_to_frame_output(
206
+ const AVFrame& av_frame,
207
+ FrameOutput& frame_output,
208
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor) {
209
+ STD_TORCH_CHECK(initialized_, "CpuDeviceInterface was not initialized.");
210
+
211
+ if (av_media_type_ == AVMEDIA_TYPE_AUDIO) {
212
+ convert_audio_av_frame_to_frame_output(av_frame, frame_output);
213
+ } else {
214
+ convert_video_av_frame_to_frame_output(
215
+ av_frame, frame_output, pre_allocated_output_tensor);
216
+ }
217
+ }
218
+
219
+ // Note [preAllocatedOutputTensor with swscale and filtergraph]:
220
+ // Callers may pass a pre-allocated tensor, where the output.data tensor will
221
+ // be stored. This parameter is honored in any case, but it only leads to a
222
+ // speed-up when swscale is used. With swscale, we can tell ffmpeg to place the
223
+ // decoded frame directly into `preAllocatedtensor.mutable_data_ptr()`. We
224
+ // haven't yet found a way to do that with filtegraph.
225
+ // TODO: Figure out whether that's possible!
226
+ // Dimension order of the preAllocatedOutputTensor must be HWC, regardless of
227
+ // `dimension_order` parameter. It's up to callers to re-shape it if needed.
228
+ void CpuDeviceInterface::convert_video_av_frame_to_frame_output(
229
+ const AVFrame& av_frame,
230
+ FrameOutput& frame_output,
231
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor) {
232
+ // Note that we ignore the dimensions from the metadata; we don't even bother
233
+ // storing them. The resized dimensions take priority. If we don't have any,
234
+ // then we use the dimensions from the actual decoded frame. We use the actual
235
+ // decoded frame and not the metadata for two reasons:
236
+ //
237
+ // 1. Metadata may be wrong. If we access to more accurate information, we
238
+ // should use it.
239
+ // 2. Video streams can have variable resolution. This fact is not captured
240
+ // in the stream metadata.
241
+ //
242
+ // Both cases cause problems for our batch APIs, as we allocate
243
+ // FrameBatchOutputs based on the the stream metadata. But single-frame APIs
244
+ // can still work in such situations, so they should.
245
+ auto input_dims = FrameDims(av_frame.height, av_frame.width);
246
+ auto output_dims = resized_output_dims_.value_or(input_dims);
247
+
248
+ if (pre_allocated_output_tensor.has_value()) {
249
+ auto shape = pre_allocated_output_tensor.value().sizes();
250
+ STD_TORCH_CHECK(
251
+ (shape.size() == 3) && (shape[0] == output_dims.height) &&
252
+ (shape[1] == output_dims.width) && (shape[2] == 3),
253
+ "Expected pre-allocated tensor of shape ",
254
+ output_dims.height,
255
+ "x",
256
+ output_dims.width,
257
+ "x3, got ",
258
+ int_array_ref_to_string(shape));
259
+ }
260
+
261
+ auto color_conversion_library =
262
+ get_color_conversion_library(input_dims, output_dims);
263
+ torch::stable::Tensor output_tensor;
264
+
265
+ if (color_conversion_library == ColorConversionLibrary::SWSCALE) {
266
+ output_tensor =
267
+ pre_allocated_output_tensor.value_or(allocate_empty_hwc_tensor(
268
+ output_dims, kStableCPU, video_stream_options_.output_dtype));
269
+
270
+ auto av_frame_format = static_cast<AVPixelFormat>(av_frame.format);
271
+ SwsConfig sws_config{
272
+ .input_width = av_frame.width,
273
+ .input_height = av_frame.height,
274
+ .input_format = av_frame_format,
275
+ .input_colorspace = av_frame.colorspace,
276
+ .input_color_range = av_frame.color_range,
277
+ .output_width = output_dims.width,
278
+ .output_height = output_dims.height,
279
+ .output_format = output_pixel_format_};
280
+
281
+ if (!sw_scale_ || sw_scale_->get_config() != sws_config) {
282
+ sw_scale_ = std::make_unique<SwScale>(sws_config, sws_flags_);
283
+ }
284
+
285
+ int result_height = sw_scale_->convert(av_frame, output_tensor);
286
+
287
+ // If this check failed, it would mean that the frame wasn't reshaped to
288
+ // the expected height.
289
+ // TODO: Can we do the same check for width?
290
+ STD_TORCH_CHECK(
291
+ result_height == output_dims.height,
292
+ "resultHeight != outputDims.height: ",
293
+ result_height,
294
+ " != ",
295
+ output_dims.height);
296
+
297
+ frame_output.data = output_tensor;
298
+ } else if (color_conversion_library == ColorConversionLibrary::FILTERGRAPH) {
299
+ output_tensor =
300
+ convert_av_frame_to_tensor_using_filter_graph(av_frame, output_dims);
301
+
302
+ // Similarly to above, if this check fails it means the frame wasn't
303
+ // reshaped to its expected dimensions by filtergraph.
304
+ auto shape = output_tensor.sizes();
305
+ STD_TORCH_CHECK(
306
+ (shape.size() == 3) && (shape[0] == output_dims.height) &&
307
+ (shape[1] == output_dims.width) && (shape[2] == 3),
308
+ "Expected output tensor of shape ",
309
+ output_dims.height,
310
+ "x",
311
+ output_dims.width,
312
+ "x3, got ",
313
+ int_array_ref_to_string(shape));
314
+
315
+ if (pre_allocated_output_tensor.has_value()) {
316
+ // We have already validated that preAllocatedOutputTensor and
317
+ // outputTensor have the same shape.
318
+ torch::stable::copy_(pre_allocated_output_tensor.value(), output_tensor);
319
+ frame_output.data = pre_allocated_output_tensor.value();
320
+ } else {
321
+ frame_output.data = output_tensor;
322
+ }
323
+ } else {
324
+ STD_TORCH_CHECK(
325
+ false,
326
+ "Invalid color conversion library: ",
327
+ static_cast<int>(color_conversion_library));
328
+ }
329
+ }
330
+
331
+ torch::stable::Tensor
332
+ CpuDeviceInterface::convert_av_frame_to_tensor_using_filter_graph(
333
+ const AVFrame& av_frame,
334
+ const FrameDims& output_dims) {
335
+ auto av_frame_format = static_cast<AVPixelFormat>(av_frame.format);
336
+
337
+ FiltersConfig filters_config(
338
+ av_frame.width,
339
+ av_frame.height,
340
+ av_frame_format,
341
+ av_frame.sample_aspect_ratio,
342
+ output_dims.width,
343
+ output_dims.height,
344
+ output_pixel_format_,
345
+ filters_,
346
+ time_base_);
347
+
348
+ if (!filter_graph_ || prev_filters_config_ != filters_config) {
349
+ filter_graph_ =
350
+ std::make_unique<FilterGraph>(filters_config, video_stream_options_);
351
+ prev_filters_config_ = std::move(filters_config);
352
+ }
353
+ return rgb_av_frame_to_tensor(*filter_graph_->convert(av_frame));
354
+ }
355
+
356
+ // clang-format off
357
+ // Note [Audio resampling and frame alignment]
358
+ //
359
+ // Say we have some audio at 24kHz that we resample at 16kHz. We want to honor
360
+ // the natural property that `get_all_samples()` should be equal to the
361
+ // concatenation of calls to `get_samples_played_in_range(a, b)` where all the
362
+ // (a, b) pairs are a full partition of the duration.
363
+ //
364
+ // `get_all_samples()` will return this:
365
+ //
366
+ // 0s 1s
367
+ // 0 12 24
368
+ // || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || 24Hz
369
+ // || | || | || | || | || | || | || | || | || | || | || | || | || 16Hz
370
+ // 0 8 16
371
+ //
372
+ // Now, the calls to `get_samples_played_in_range(a, b)`. If we don't do
373
+ // something special, we'd get the following.
374
+ //
375
+ // 0s x 1s
376
+ // 0 [ sample frame ] 12 24
377
+ // || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || 24Hz
378
+ // || | || | || | || | || | || | || | || | || | || | || | || | || 16Hz
379
+ // 0 || ^ || 8 16
380
+ // || |
381
+ // || x', not aligned with output grid!
382
+ // ||
383
+ // ||
384
+ // ||
385
+ // ||
386
+ // we tell the resampler to start here! On a sample that is aligned in input and output space.
387
+ //
388
+ // (side note: the frame above is drawn as containing very few samples,
389
+ // real frames have much more, it doesn't matter for the point being made.)
390
+ //
391
+ // Say we request `get_samples_played_in_range(a, b)` where a is somewhere
392
+ // within the `[sample frame]` - it doesn't matter where it is exactly. Since
393
+ // FFmpeg starts decoding from a frame start, it will start decoding from x:
394
+ // the sample in the input space where that frame starts.
395
+ //
396
+ //
397
+ // **THE PROBLEM** is that this sample `x` in the input space is NOT aligned
398
+ // with a sample boundary in the output space! See how x' doesn't align with a
399
+ // sample that the single call to `get_all_samples()` would have returned?
400
+ // Nothing breaks, the decoder and the resampler happily oblige, but they start
401
+ // returning an output that is stamped with a pts that we would have otherwise
402
+ // never gotten - and all the resulting samples boundaries are shifted by that
403
+ // offset. This breaks our desired property.
404
+ //
405
+ // To fix this, we tell the resampler to NOT start at x, but to start instead
406
+ // at a sample that is aligned in both input space and output space: the ones
407
+ // that start with ||. We know where these samples are: their index is a
408
+ // multiple of k in input space, and of k' in output space, where:
409
+ //
410
+ // - k = isr / gcd(isr, osr) -- every 3 samples in input space, since
411
+ // gcd = 8 and 24 = 8 * 3
412
+ // - k' = osr / gcd(isr, osr) -- every 2 samples in output space, since
413
+ // gcd = 8 and 16 = 8 * 2
414
+ //
415
+ // In practice, we tell the resampler to *drop* some samples. We can do that
416
+ // because in practice, we start feeding it much earlier than the target `a`,
417
+ // because of the pre-roll (see [Audio pre-roll and post-roll]). The
418
+ // pre-roll is large enough such that the aligned sample we land on is always at
419
+ // or before `a`. Whether it is before the frame containing `a`, as drawn above,
420
+ // or inside that frame depends on how far into that frame `a` falls - but it is
421
+ // never past `a`, so the samples we drop are never samples the caller asked
422
+ // for.
423
+ // clang-format on
424
+ void CpuDeviceInterface::convert_audio_av_frame_to_frame_output(
425
+ const AVFrame& src_av_frame,
426
+ FrameOutput& frame_output) {
427
+ AVSampleFormat src_sample_format =
428
+ static_cast<AVSampleFormat>(src_av_frame.format);
429
+ AVSampleFormat out_sample_format = AV_SAMPLE_FMT_FLTP;
430
+
431
+ int src_sample_rate = src_av_frame.sample_rate;
432
+ int out_sample_rate =
433
+ audio_stream_options_.sample_rate.value_or(src_sample_rate);
434
+
435
+ int src_num_channels = get_num_channels(codec_context_);
436
+ STD_TORCH_CHECK(
437
+ src_num_channels == get_num_channels(src_av_frame),
438
+ "The frame has ",
439
+ get_num_channels(src_av_frame),
440
+ " channels, expected ",
441
+ src_num_channels,
442
+ ". If you are hitting this, it may be because you are using "
443
+ "a buggy FFmpeg version. FFmpeg4 is known to fail here in some "
444
+ "valid scenarios. Try to upgrade FFmpeg?");
445
+ int out_num_channels =
446
+ audio_stream_options_.num_channels.value_or(src_num_channels);
447
+
448
+ bool must_convert =
449
+ (src_sample_format != out_sample_format ||
450
+ src_sample_rate != out_sample_rate ||
451
+ src_num_channels != out_num_channels);
452
+
453
+ UniqueAVFrame converted_av_frame;
454
+ if (must_convert) {
455
+ int64_t num_samples_to_skip = 0;
456
+ if (!swr_context_) {
457
+ // See [Audio resampling and frame alignment].
458
+ int64_t frame_sample_index = std::llround(
459
+ (frame_output.pts_seconds - audio_stream_start_seconds_) *
460
+ src_sample_rate);
461
+ int64_t alignment = // k in the note
462
+ src_sample_rate / std::gcd(src_sample_rate, out_sample_rate);
463
+ int64_t remainder = frame_sample_index % alignment;
464
+ if (remainder < 0) {
465
+ remainder += alignment;
466
+ }
467
+ int64_t next_aligned_sample =
468
+ frame_sample_index + (remainder == 0 ? 0 : alignment - remainder);
469
+ num_samples_to_skip = next_aligned_sample - frame_sample_index;
470
+
471
+ // The pts_seconds field was set upstream to the pts of src_av_frame, but
472
+ // must adjust it to report the pts of the aligned sample, since this is
473
+ // where the resampler will start producing output.
474
+ frame_output.pts_seconds = audio_stream_start_seconds_ +
475
+ static_cast<double>(next_aligned_sample) / src_sample_rate;
476
+
477
+ if (num_samples_to_skip >= src_av_frame.nb_samples) {
478
+ // The aligned sample isn't in this frame. Skipping it whole leaves the
479
+ // next one to compute the same aligned sample and land on it.
480
+ // Yes, it may happen that we have to skip more than one frame worth of
481
+ // samples in degenerate cases.
482
+ frame_output.data = torch::stable::empty({out_num_channels, 0});
483
+ return;
484
+ }
485
+
486
+ swr_context_.reset(create_swr_context(
487
+ src_sample_format,
488
+ out_sample_format,
489
+ src_sample_rate,
490
+ out_sample_rate,
491
+ src_av_frame,
492
+ out_num_channels));
493
+ }
494
+
495
+ converted_av_frame = convert_audio_av_frame_samples(
496
+ swr_context_,
497
+ src_av_frame,
498
+ out_sample_format,
499
+ out_sample_rate,
500
+ out_num_channels,
501
+ static_cast<int>(num_samples_to_skip));
502
+ }
503
+ const AVFrame& av_frame = must_convert ? *converted_av_frame : src_av_frame;
504
+
505
+ AVSampleFormat format = static_cast<AVSampleFormat>(av_frame.format);
506
+ STD_TORCH_CHECK(
507
+ format == out_sample_format,
508
+ "Something went wrong, the frame didn't get converted to the desired format. ",
509
+ "Desired format = ",
510
+ av_get_sample_fmt_name(out_sample_format),
511
+ "source format = ",
512
+ av_get_sample_fmt_name(format));
513
+
514
+ int num_channels = get_num_channels(av_frame);
515
+ STD_TORCH_CHECK(
516
+ num_channels == out_num_channels,
517
+ "Something went wrong, the frame didn't get converted to the desired ",
518
+ "number of channels = ",
519
+ out_num_channels,
520
+ ". Got ",
521
+ num_channels,
522
+ " instead.");
523
+
524
+ auto num_samples = av_frame.nb_samples;
525
+
526
+ frame_output.data = torch::stable::empty({num_channels, num_samples});
527
+
528
+ if (num_samples > 0) {
529
+ uint8_t* output_channel_data =
530
+ static_cast<uint8_t*>(frame_output.data.mutable_data_ptr());
531
+ auto num_bytes_per_channel = num_samples * av_get_bytes_per_sample(format);
532
+ for (auto channel = 0; channel < num_channels;
533
+ ++channel, output_channel_data += num_bytes_per_channel) {
534
+ std::memcpy(
535
+ output_channel_data,
536
+ av_frame.extended_data[channel],
537
+ num_bytes_per_channel);
538
+ }
539
+ }
540
+ }
541
+
542
+ std::optional<torch::stable::Tensor>
543
+ CpuDeviceInterface::maybe_flush_audio_buffers() {
544
+ // When sample rate conversion is involved, swresample buffers some of the
545
+ // samples in-between calls to swr_convert (see the libswresample docs).
546
+ // That's because the last few samples in a given frame require future
547
+ // samples from the next frame to be properly converted. This function
548
+ // flushes out the samples that are stored in swresample's buffers.
549
+ if (!swr_context_) {
550
+ return std::nullopt;
551
+ }
552
+ auto num_remaining_samples = // this is an upper bound
553
+ swr_get_out_samples(swr_context_.get(), 0);
554
+
555
+ if (num_remaining_samples == 0) {
556
+ return std::nullopt;
557
+ }
558
+
559
+ int num_channels = audio_stream_options_.num_channels.value_or(
560
+ get_num_channels(codec_context_));
561
+ return swr_convert_to_tensor(
562
+ swr_context_,
563
+ /*src_planes=*/nullptr,
564
+ /*num_src_samples=*/0,
565
+ num_channels,
566
+ num_remaining_samples);
567
+ }
568
+
569
+ void CpuDeviceInterface::flush() {
570
+ DeviceInterface::flush();
571
+ swr_context_.reset();
572
+ }
573
+
574
+ std::string CpuDeviceInterface::get_details() {
575
+ return std::string("CPU Device Interface.");
576
+ }
577
+
578
+ UniqueAVFrame CpuDeviceInterface::convert_tensor_to_av_frame_for_encoding(
579
+ const torch::stable::Tensor& frame,
580
+ int frame_index,
581
+ AVCodecContext* codec_context) {
582
+ int in_height = static_cast<int>(frame.sizes()[1]);
583
+ int in_width = static_cast<int>(frame.sizes()[2]);
584
+ AVPixelFormat in_pixel_format = AV_PIX_FMT_GBRP;
585
+ int out_width = codec_context->width;
586
+ int out_height = codec_context->height;
587
+ AVPixelFormat out_pixel_format = codec_context->pix_fmt;
588
+
589
+ // Initialize and cache scaling context if it does not exist
590
+ if (!encoding_sws_context_) {
591
+ SwsConfig sws_config{
592
+ .input_width = in_width,
593
+ .input_height = in_height,
594
+ .input_format = in_pixel_format,
595
+ .input_colorspace = codec_context->colorspace,
596
+ .output_width = out_width,
597
+ .output_height = out_height,
598
+ .output_format = out_pixel_format,
599
+ .output_color_range = codec_context->color_range};
600
+
601
+ encoding_sws_context_ =
602
+ create_sws_context(sws_config, SWS_BICUBIC); // Used by FFmpeg CLI
603
+ }
604
+
605
+ UniqueAVFrame av_frame(av_frame_alloc());
606
+ STD_TORCH_CHECK(av_frame != nullptr, "Failed to allocate AVFrame");
607
+
608
+ // Set output frame properties
609
+ av_frame->format = out_pixel_format;
610
+ av_frame->width = out_width;
611
+ av_frame->height = out_height;
612
+ av_frame->pts = frame_index;
613
+ av_frame->colorspace = codec_context->colorspace;
614
+ av_frame->color_range = codec_context->color_range;
615
+
616
+ int status = av_frame_get_buffer(av_frame.get(), 0);
617
+ STD_TORCH_CHECK(status >= 0, "Failed to allocate frame buffer");
618
+
619
+ // Need to convert/scale the frame
620
+ // Create temporary frame with input format
621
+ UniqueAVFrame input_frame(av_frame_alloc());
622
+ STD_TORCH_CHECK(input_frame != nullptr, "Failed to allocate input AVFrame");
623
+
624
+ input_frame->format = in_pixel_format;
625
+ input_frame->width = in_width;
626
+ input_frame->height = in_height;
627
+
628
+ uint8_t* tensor_data = static_cast<uint8_t*>(frame.mutable_data_ptr());
629
+
630
+ int channel_size = in_height * in_width;
631
+ // Since frames tensor is in NCHW, we must use a planar format.
632
+ // FFmpeg only provides AV_PIX_FMT_GBRP for planar RGB,
633
+ // so we reorder RGB -> GBR.
634
+ input_frame->data[0] = tensor_data + channel_size;
635
+ input_frame->data[1] = tensor_data + (2 * channel_size);
636
+ input_frame->data[2] = tensor_data;
637
+
638
+ input_frame->linesize[0] = in_width;
639
+ input_frame->linesize[1] = in_width;
640
+ input_frame->linesize[2] = in_width;
641
+
642
+ status = sws_scale(
643
+ encoding_sws_context_.get(),
644
+ input_frame->data,
645
+ input_frame->linesize,
646
+ 0,
647
+ input_frame->height,
648
+ av_frame->data,
649
+ av_frame->linesize);
650
+ STD_TORCH_CHECK(status == out_height, "sws_scale failed");
651
+ return av_frame;
652
+ }
653
+
654
+ } // namespace facebook::torchcodec