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,1023 @@
1
+ #include <sstream>
2
+
3
+ #include "Encoder.h"
4
+ #include "StableABICompat.h"
5
+
6
+ extern "C" {
7
+ #include <libavutil/hwcontext.h>
8
+ #include <libavutil/opt.h>
9
+ #include <libavutil/pixdesc.h>
10
+ }
11
+
12
+ namespace facebook::torchcodec {
13
+
14
+ namespace {
15
+
16
+ torch::stable::Tensor validate_samples(const torch::stable::Tensor& samples) {
17
+ STD_TORCH_CHECK(
18
+ samples.scalar_type() == kStableFloat32,
19
+ "samples must have float32 dtype, got ",
20
+ (samples.scalar_type()));
21
+ STD_TORCH_CHECK(
22
+ samples.device().type() == kStableCPU,
23
+ "samples must be on CPU, got ",
24
+ device_type_name(samples.device().type()));
25
+ STD_TORCH_CHECK(
26
+ samples.dim() == 2,
27
+ "samples must have 2 dimensions, got ",
28
+ samples.dim());
29
+
30
+ // We enforce this, but if we get user reports we should investigate whether
31
+ // that's actually needed.
32
+ int num_channels = static_cast<int>(samples.sizes()[0]);
33
+ STD_TORCH_CHECK(
34
+ num_channels <= AV_NUM_DATA_POINTERS,
35
+ "Trying to encode ",
36
+ num_channels,
37
+ " channels, but FFmpeg only supports ",
38
+ AV_NUM_DATA_POINTERS,
39
+ " channels per frame.");
40
+
41
+ return torch::stable::contiguous(samples);
42
+ }
43
+
44
+ void validate_sample_rate(const AVCodec& av_codec, int sample_rate) {
45
+ const int* supported_sample_rates = get_supported_sample_rates(av_codec);
46
+ if (supported_sample_rates == nullptr) {
47
+ return;
48
+ }
49
+
50
+ for (auto i = 0; supported_sample_rates[i] != 0; ++i) {
51
+ if (sample_rate == supported_sample_rates[i]) {
52
+ return;
53
+ }
54
+ }
55
+ std::stringstream supported_rates;
56
+ for (auto i = 0; supported_sample_rates[i] != 0; ++i) {
57
+ if (i > 0) {
58
+ supported_rates << ", ";
59
+ }
60
+ supported_rates << supported_sample_rates[i];
61
+ }
62
+
63
+ STD_TORCH_CHECK(
64
+ false,
65
+ "invalid sample rate=",
66
+ sample_rate,
67
+ ". Supported sample rate values are: ",
68
+ supported_rates.str());
69
+ }
70
+
71
+ static const std::vector<AVSampleFormat> preferred_formats_order = {
72
+ AV_SAMPLE_FMT_FLTP,
73
+ AV_SAMPLE_FMT_FLT,
74
+ AV_SAMPLE_FMT_DBLP,
75
+ AV_SAMPLE_FMT_DBL,
76
+ AV_SAMPLE_FMT_S64P,
77
+ AV_SAMPLE_FMT_S64,
78
+ AV_SAMPLE_FMT_S32P,
79
+ AV_SAMPLE_FMT_S32,
80
+ AV_SAMPLE_FMT_S16P,
81
+ AV_SAMPLE_FMT_S16,
82
+ AV_SAMPLE_FMT_U8P,
83
+ AV_SAMPLE_FMT_U8};
84
+
85
+ AVSampleFormat find_best_output_sample_format(const AVCodec& av_codec) {
86
+ const AVSampleFormat* supported_sample_formats =
87
+ get_supported_output_sample_formats(av_codec);
88
+
89
+ // Find a sample format that the encoder supports. We prefer using FLT[P],
90
+ // since this is the format of the input samples. If FLTP isn't supported
91
+ // then we'll need to convert the AVFrame's format. Our heuristic is to encode
92
+ // into the format with the highest resolution.
93
+ if (supported_sample_formats == nullptr) {
94
+ // Can't really validate anything in this case, best we can do is hope that
95
+ // FLTP is supported by the encoder. If not, FFmpeg will raise.
96
+ return AV_SAMPLE_FMT_FLTP;
97
+ }
98
+
99
+ for (AVSampleFormat preferred_format : preferred_formats_order) {
100
+ for (int i = 0; supported_sample_formats[i] != -1; ++i) {
101
+ if (supported_sample_formats[i] == preferred_format) {
102
+ return preferred_format;
103
+ }
104
+ }
105
+ }
106
+ // We should always find a match in preferred_formats_order, so we should
107
+ // always return earlier. But in the event that a future FFmpeg version
108
+ // defines an additional sample format that isn't in preferred_formats_order,
109
+ // we fallback:
110
+ return supported_sample_formats[0];
111
+ }
112
+
113
+ void close_avio_context(
114
+ AVFormatContext* av_format_context,
115
+ AVIOContextHolder* avio_context_holder) {
116
+ if (!av_format_context || !av_format_context->pb) {
117
+ return;
118
+ }
119
+
120
+ if (av_format_context->pb->error == 0) {
121
+ avio_flush(av_format_context->pb);
122
+ }
123
+
124
+ if (!avio_context_holder) {
125
+ if (av_format_context->pb->error == 0) {
126
+ avio_close(av_format_context->pb);
127
+ }
128
+ }
129
+
130
+ av_format_context->pb = nullptr;
131
+ }
132
+
133
+ torch::stable::Tensor validate_frames(
134
+ const torch::stable::Tensor& frames,
135
+ const AVCodecContext* av_codec_context = nullptr,
136
+ DeviceInterface* device_interface = nullptr) {
137
+ STD_TORCH_CHECK(
138
+ frames.scalar_type() == kStableUInt8,
139
+ "frames must have uint8 dtype, got ",
140
+ frames.scalar_type());
141
+ STD_TORCH_CHECK(
142
+ frames.dim() == 4,
143
+ "frames must have 4 dimensions (N, C, H, W), got ",
144
+ frames.dim());
145
+ STD_TORCH_CHECK(
146
+ frames.sizes()[1] == 3,
147
+ "frame must have 3 channels (R, G, B), got ",
148
+ frames.sizes()[1]);
149
+ if (device_interface != nullptr) {
150
+ auto& expected_device = device_interface->device();
151
+ auto frames_device = frames.device();
152
+ STD_TORCH_CHECK(
153
+ frames_device == expected_device,
154
+ "All frames must be on the same device. Expected ",
155
+ device_type_name(expected_device.type()),
156
+ ":",
157
+ expected_device.index(),
158
+ ", got ",
159
+ device_type_name(frames_device.type()),
160
+ ":",
161
+ frames_device.index());
162
+ }
163
+ if (av_codec_context) {
164
+ STD_TORCH_CHECK(
165
+ static_cast<int>(frames.sizes()[2]) == av_codec_context->height &&
166
+ static_cast<int>(frames.sizes()[3]) == av_codec_context->width,
167
+ "All frames must have the same dimensions. Expected height=",
168
+ av_codec_context->height,
169
+ " width=",
170
+ av_codec_context->width,
171
+ ", got height=",
172
+ frames.sizes()[2],
173
+ " width=",
174
+ frames.sizes()[3]);
175
+ }
176
+ return torch::stable::contiguous(frames);
177
+ }
178
+
179
+ void try_to_validate_codec_option(
180
+ const AVCodec& av_codec,
181
+ const char* option_name,
182
+ const std::string& value) {
183
+ if (!av_codec.priv_class) {
184
+ return;
185
+ }
186
+ const AVOption* option = av_opt_find2(
187
+ // Convert obj arg from const AVClass* const* to non-const void*
188
+ // First cast to remove const, then cast to void*
189
+ const_cast<void*>(static_cast<const void*>(&av_codec.priv_class)),
190
+ option_name,
191
+ nullptr,
192
+ 0,
193
+ AV_OPT_SEARCH_FAKE_OBJ,
194
+ nullptr);
195
+ // If option is not found we cannot validate it, let FFmpeg handle it
196
+ if (!option) {
197
+ return;
198
+ }
199
+ // Validate if option is defined as a numeric type
200
+ if (option->type == AV_OPT_TYPE_INT || option->type == AV_OPT_TYPE_INT64 ||
201
+ option->type == AV_OPT_TYPE_FLOAT || option->type == AV_OPT_TYPE_DOUBLE) {
202
+ try {
203
+ double numeric_value = std::stod(value);
204
+ STD_TORCH_CHECK(
205
+ numeric_value >= option->min && numeric_value <= option->max,
206
+ option_name,
207
+ "=",
208
+ numeric_value,
209
+ " is out of valid range [",
210
+ option->min,
211
+ ", ",
212
+ option->max,
213
+ "] for this codec. For more details, run 'ffmpeg -h encoder=",
214
+ av_codec.name,
215
+ "'");
216
+ } catch (const std::invalid_argument&) {
217
+ STD_TORCH_CHECK(
218
+ false,
219
+ "Option ",
220
+ option_name,
221
+ " expects a numeric value but got '",
222
+ value,
223
+ "'");
224
+ }
225
+ }
226
+ }
227
+
228
+ void sort_codec_options(
229
+ const AVFormatContext* av_format_context,
230
+ const std::map<std::string, std::string>& extra_options,
231
+ UniqueAVDictionary& codec_dict,
232
+ UniqueAVDictionary& format_dict) {
233
+ // Accepts a map of options as input, then sorts them into codec options and
234
+ // format options. The sorted options are returned into two separate dicts.
235
+ const AVClass* format_class = avformat_get_class();
236
+ const AVClass* muxer_class = av_format_context->oformat
237
+ ? av_format_context->oformat->priv_class
238
+ : nullptr;
239
+ for (const auto& [key, value] : extra_options) {
240
+ // Check if option is generic format option
241
+ const AVOption* fmt_opt = av_opt_find2(
242
+ &format_class,
243
+ key.c_str(),
244
+ nullptr,
245
+ 0,
246
+ AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ,
247
+ nullptr);
248
+ // Check if option is muxer-specific option
249
+ // (Returned from `ffmpeg -h muxer=mp4`)
250
+ const AVOption* muxer_opt = nullptr;
251
+ if (muxer_class) {
252
+ muxer_opt = av_opt_find2(
253
+ &muxer_class,
254
+ key.c_str(),
255
+ nullptr,
256
+ 0,
257
+ AV_OPT_SEARCH_FAKE_OBJ,
258
+ nullptr);
259
+ }
260
+ if (fmt_opt || muxer_opt) {
261
+ // Pass container-format options to formatDict to be used in
262
+ // avformat_write_header
263
+ av_dict_set(format_dict.get_address(), key.c_str(), value.c_str(), 0);
264
+ } else {
265
+ // By default, pass as codec option to be used in avcodec_open2
266
+ av_dict_set(codec_dict.get_address(), key.c_str(), value.c_str(), 0);
267
+ }
268
+ }
269
+ }
270
+
271
+ } // namespace
272
+
273
+ MultiStreamEncoder::~MultiStreamEncoder() {
274
+ close();
275
+ }
276
+
277
+ MultiStreamEncoder::MultiStreamEncoder() {
278
+ set_ffmpeg_log_level();
279
+ }
280
+
281
+ void MultiStreamEncoder::open(std::string_view file_name) {
282
+ STD_TORCH_CHECK(!closed_, "Cannot open after close() was called.");
283
+ STD_TORCH_CHECK(!header_written_, "open() was already called.");
284
+
285
+ AVFormatContext* av_format_context = nullptr;
286
+ int status = avformat_alloc_output_context2(
287
+ &av_format_context, nullptr, nullptr, file_name.data());
288
+
289
+ STD_TORCH_CHECK(
290
+ av_format_context != nullptr,
291
+ "Couldn't allocate AVFormatContext. ",
292
+ "The destination file is ",
293
+ file_name,
294
+ ", check the desired extension? ",
295
+ get_ffmpeg_error_string_from_error_code(status));
296
+ av_format_context_.reset(av_format_context);
297
+
298
+ status =
299
+ avio_open(&av_format_context_->pb, file_name.data(), AVIO_FLAG_WRITE);
300
+ STD_TORCH_CHECK(
301
+ status >= 0,
302
+ "avio_open failed. The destination file is ",
303
+ file_name,
304
+ ", make sure it's a valid path? ",
305
+ get_ffmpeg_error_string_from_error_code(status));
306
+
307
+ open_streams_and_write_header();
308
+ }
309
+
310
+ void MultiStreamEncoder::open(
311
+ std::string_view format_name,
312
+ std::unique_ptr<AVIOContextHolder> avio_context_holder) {
313
+ STD_TORCH_CHECK(!closed_, "Cannot open after close() was called.");
314
+ STD_TORCH_CHECK(!header_written_, "open() was already called.");
315
+
316
+ avio_context_holder_ = std::move(avio_context_holder);
317
+
318
+ // Map mkv -> matroska when used as format name
319
+ format_name = (format_name == "mkv") ? "matroska" : format_name;
320
+ AVFormatContext* av_format_context = nullptr;
321
+ int status = avformat_alloc_output_context2(
322
+ &av_format_context, nullptr, format_name.data(), nullptr);
323
+
324
+ STD_TORCH_CHECK(
325
+ av_format_context != nullptr,
326
+ "Couldn't allocate AVFormatContext. ",
327
+ "Check the desired format? Got format=",
328
+ format_name,
329
+ ". ",
330
+ get_ffmpeg_error_string_from_error_code(status));
331
+ av_format_context_.reset(av_format_context);
332
+
333
+ av_format_context_->pb = avio_context_holder_->get_avio_context();
334
+
335
+ open_streams_and_write_header();
336
+ }
337
+
338
+ int MultiStreamEncoder::add_video_stream(
339
+ int height,
340
+ int width,
341
+ double frame_rate,
342
+ std::string device,
343
+ std::optional<std::string> codec,
344
+ std::optional<std::string> pixel_format,
345
+ std::optional<double> crf,
346
+ std::optional<std::string> preset,
347
+ std::optional<std::map<std::string, std::string>> extra_options) {
348
+ STD_TORCH_CHECK(height > 0, "height must be > 0, got ", height);
349
+ STD_TORCH_CHECK(width > 0, "width must be > 0, got ", width);
350
+ STD_TORCH_CHECK(frame_rate > 0, "frame_rate must be > 0, got ", frame_rate);
351
+ VideoStream video_stream;
352
+ StableDevice stable_device(std::move(device));
353
+ video_stream.device_interface = create_device_interface(
354
+ stable_device,
355
+ stable_device.type() == kStableCUDA ? "ffmpeg" : "default");
356
+ video_stream.in_height = height;
357
+ video_stream.in_width = width;
358
+ video_stream.in_frame_rate = frame_rate;
359
+ video_stream.options.codec = std::move(codec);
360
+ video_stream.options.pixel_format = std::move(pixel_format);
361
+ video_stream.options.crf = crf;
362
+ video_stream.options.preset = std::move(preset);
363
+ video_stream.options.extra_options = std::move(extra_options);
364
+ video_streams_.push_back(std::move(video_stream));
365
+ return static_cast<int>(video_streams_.size() - 1);
366
+ }
367
+
368
+ int MultiStreamEncoder::add_audio_stream(
369
+ int sample_rate,
370
+ int num_channels,
371
+ std::optional<int> bit_rate,
372
+ std::optional<int> out_num_channels,
373
+ std::optional<int> out_sample_rate) {
374
+ STD_TORCH_CHECK(
375
+ sample_rate > 0, "sample_rate must be > 0, got ", sample_rate);
376
+ STD_TORCH_CHECK(
377
+ num_channels > 0, "num_channels must be > 0, got ", num_channels);
378
+ STD_TORCH_CHECK(
379
+ num_channels <= AV_NUM_DATA_POINTERS,
380
+ "Trying to encode ",
381
+ num_channels,
382
+ " channels, but FFmpeg only supports ",
383
+ AV_NUM_DATA_POINTERS,
384
+ " channels per frame.");
385
+
386
+ AudioStream audio_stream;
387
+ audio_stream.in_sample_rate = sample_rate;
388
+ audio_stream.in_num_channels = num_channels;
389
+ audio_stream.options.bit_rate = bit_rate;
390
+ audio_stream.options.num_channels = out_num_channels;
391
+ audio_stream.options.sample_rate = out_sample_rate;
392
+ audio_streams_.push_back(std::move(audio_stream));
393
+ return static_cast<int>(audio_streams_.size() - 1);
394
+ }
395
+
396
+ void MultiStreamEncoder::initialize_video_stream(VideoStream& video_stream) {
397
+ const AVCodec* av_codec = nullptr;
398
+ // If codec arg is provided, find codec using logic similar to FFmpeg:
399
+ // https://github.com/FFmpeg/FFmpeg/blob/master/fftools/ffmpeg_opt.c#L804-L835
400
+ if (video_stream.options.codec.has_value()) {
401
+ const std::string& codec = video_stream.options.codec.value();
402
+ // Try to find codec by name ("libx264", "libsvtav1")
403
+ av_codec = avcodec_find_encoder_by_name(codec.c_str());
404
+ // Try to find by codec descriptor ("h264", "av1")
405
+ if (!av_codec) {
406
+ const AVCodecDescriptor* desc =
407
+ avcodec_descriptor_get_by_name(codec.c_str());
408
+ if (desc) {
409
+ av_codec = avcodec_find_encoder(desc->id);
410
+ }
411
+ }
412
+ } else {
413
+ STD_TORCH_CHECK(
414
+ av_format_context_->oformat != nullptr,
415
+ "Output format is null, unable to find default codec.");
416
+ // Try to substitute the default codec with its hardware equivalent
417
+ // This will return std::nullopt when device is CPU.
418
+ auto hw_codec = video_stream.device_interface->find_codec(
419
+ av_format_context_->oformat->video_codec, /*isDecoder=*/false);
420
+ if (hw_codec.has_value()) {
421
+ av_codec = hw_codec.value();
422
+ }
423
+ if (!av_codec) {
424
+ av_codec = avcodec_find_encoder(av_format_context_->oformat->video_codec);
425
+ }
426
+ }
427
+ STD_TORCH_CHECK(
428
+ av_codec != nullptr,
429
+ "Video codec ",
430
+ video_stream.options.codec.has_value()
431
+ ? video_stream.options.codec.value() + " "
432
+ : "",
433
+ "not found. To see available codecs, run: ffmpeg -encoders");
434
+
435
+ AVCodecContext* av_codec_context = avcodec_alloc_context3(av_codec);
436
+ STD_TORCH_CHECK(
437
+ av_codec_context != nullptr, "Couldn't allocate codec context.");
438
+ video_stream.av_codec_context.reset(av_codec_context);
439
+
440
+ int out_height = video_stream.in_height;
441
+ int out_width = video_stream.in_width;
442
+ // Pixel-format selection is delegated to the device interface.
443
+ AVPixelFormat out_pixel_format =
444
+ video_stream.device_interface->get_encoding_pixel_format(
445
+ *av_codec, video_stream.options.pixel_format);
446
+
447
+ // Configure codec parameters
448
+ video_stream.av_codec_context->codec_id = av_codec->id;
449
+ video_stream.av_codec_context->width = out_width;
450
+ video_stream.av_codec_context->height = out_height;
451
+ video_stream.av_codec_context->pix_fmt = out_pixel_format;
452
+ video_stream.av_codec_context->framerate =
453
+ av_d2q(video_stream.in_frame_rate, INT_MAX);
454
+ video_stream.av_codec_context->time_base =
455
+ av_inv_q(video_stream.av_codec_context->framerate);
456
+
457
+ // Set flag for containers that require extradata to be in the codec context
458
+ if (av_format_context_->oformat->flags & AVFMT_GLOBALHEADER) {
459
+ video_stream.av_codec_context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
460
+ }
461
+
462
+ // Apply videoStreamOptions
463
+ UniqueAVDictionary av_codec_options;
464
+ if (video_stream.options.extra_options.has_value()) {
465
+ for (const auto& [key, value] :
466
+ video_stream.options.extra_options.value()) {
467
+ try_to_validate_codec_option(*av_codec, key.c_str(), value);
468
+ }
469
+ sort_codec_options(
470
+ av_format_context_.get(),
471
+ video_stream.options.extra_options.value(),
472
+ av_codec_options,
473
+ av_format_options_);
474
+ }
475
+
476
+ if (video_stream.options.crf.has_value()) {
477
+ std::string crf_value = std::to_string(video_stream.options.crf.value());
478
+ try_to_validate_codec_option(*av_codec, "crf", crf_value);
479
+ av_dict_set(av_codec_options.get_address(), "crf", crf_value.c_str(), 0);
480
+ }
481
+
482
+ if (video_stream.options.preset.has_value()) {
483
+ av_dict_set(
484
+ av_codec_options.get_address(),
485
+ "preset",
486
+ video_stream.options.preset.value().c_str(),
487
+ 0);
488
+ }
489
+ // Hardware setup is a no-op on CPU; HW devices override these hooks.
490
+ video_stream.device_interface->register_hardware_device_with_codec(
491
+ video_stream.av_codec_context.get());
492
+ video_stream.device_interface->setup_hardware_frame_context_for_encoding(
493
+ video_stream.av_codec_context.get());
494
+
495
+ int status = avcodec_open2(
496
+ video_stream.av_codec_context.get(),
497
+ av_codec,
498
+ av_codec_options.get_address());
499
+
500
+ STD_TORCH_CHECK(
501
+ status == AVSUCCESS,
502
+ "avcodec_open2 failed: ",
503
+ get_ffmpeg_error_string_from_error_code(status));
504
+
505
+ video_stream.av_stream =
506
+ avformat_new_stream(av_format_context_.get(), nullptr);
507
+ STD_TORCH_CHECK(
508
+ video_stream.av_stream != nullptr, "Couldn't create new stream.");
509
+
510
+ // Set the stream time base to encode correct frame timestamps
511
+ video_stream.av_stream->time_base = video_stream.av_codec_context->time_base;
512
+ // Set the stream frame rate to store correct frame durations for some
513
+ // containers (webm, mkv)
514
+ video_stream.av_stream->r_frame_rate =
515
+ video_stream.av_codec_context->framerate;
516
+
517
+ status = avcodec_parameters_from_context(
518
+ video_stream.av_stream->codecpar, video_stream.av_codec_context.get());
519
+ STD_TORCH_CHECK(
520
+ status == AVSUCCESS,
521
+ "avcodec_parameters_from_context failed: ",
522
+ get_ffmpeg_error_string_from_error_code(status));
523
+ }
524
+
525
+ void MultiStreamEncoder::initialize_audio_stream(AudioStream& audio_stream) {
526
+ // We use the AVFormatContext's default codec for that
527
+ // specific format/container.
528
+ const AVCodec* av_codec =
529
+ avcodec_find_encoder(av_format_context_->oformat->audio_codec);
530
+ STD_TORCH_CHECK(av_codec != nullptr, "Codec not found");
531
+
532
+ AVCodecContext* av_codec_context = avcodec_alloc_context3(av_codec);
533
+ STD_TORCH_CHECK(
534
+ av_codec_context != nullptr, "Couldn't allocate codec context.");
535
+ audio_stream.av_codec_context.reset(av_codec_context);
536
+
537
+ auto desired_bit_rate = audio_stream.options.bit_rate;
538
+ if (desired_bit_rate.has_value()) {
539
+ STD_TORCH_CHECK(
540
+ *desired_bit_rate >= 0,
541
+ "bit_rate=",
542
+ *desired_bit_rate,
543
+ " must be >= 0.");
544
+ // We set the codec_context bit rate only if the user explicitly asks for
545
+ // one. Leaving it unset lets FFmpeg choose the default, like the FFmpeg CLI
546
+ // does when "-b:a" isn't specified.
547
+ audio_stream.av_codec_context->bit_rate = *desired_bit_rate;
548
+ }
549
+
550
+ int out_num_channels =
551
+ audio_stream.options.num_channels.value_or(audio_stream.in_num_channels);
552
+ audio_stream.out_num_channels = out_num_channels;
553
+ validate_num_channels(*av_codec, out_num_channels);
554
+ set_default_channel_layout(audio_stream.av_codec_context, out_num_channels);
555
+
556
+ int out_sample_rate =
557
+ audio_stream.options.sample_rate.value_or(audio_stream.in_sample_rate);
558
+ audio_stream.out_sample_rate = out_sample_rate;
559
+ validate_sample_rate(*av_codec, out_sample_rate);
560
+ audio_stream.av_codec_context->sample_rate = out_sample_rate;
561
+ audio_stream.av_codec_context->time_base = AVRational{1, out_sample_rate};
562
+
563
+ // Input samples are expected to be FLTP. Not all encoders support FLTP, so we
564
+ // may need to convert the samples into a supported output sample format,
565
+ // which is what the `.sample_fmt` defines.
566
+ audio_stream.av_codec_context->sample_fmt =
567
+ find_best_output_sample_format(*av_codec);
568
+
569
+ int status =
570
+ avcodec_open2(audio_stream.av_codec_context.get(), av_codec, nullptr);
571
+ STD_TORCH_CHECK(
572
+ status == AVSUCCESS,
573
+ "avcodec_open2 failed: ",
574
+ get_ffmpeg_error_string_from_error_code(status));
575
+
576
+ // We're allocating the stream here. Streams are meant to be freed by
577
+ // avformat_free_context(avFormatContext), which we call in the
578
+ // avFormatContext_'s destructor.
579
+ audio_stream.av_stream =
580
+ avformat_new_stream(av_format_context_.get(), nullptr);
581
+ STD_TORCH_CHECK(
582
+ audio_stream.av_stream != nullptr, "Couldn't create new audio stream.");
583
+
584
+ status = avcodec_parameters_from_context(
585
+ audio_stream.av_stream->codecpar, audio_stream.av_codec_context.get());
586
+ STD_TORCH_CHECK(
587
+ status == AVSUCCESS,
588
+ "avcodec_parameters_from_context failed: ",
589
+ get_ffmpeg_error_string_from_error_code(status));
590
+
591
+ // If a codec supports variable frame size, frame_size may not be defined, in
592
+ // which case we default to 256 like torchaudio.
593
+ audio_stream.frame_size = audio_stream.av_codec_context->frame_size > 0
594
+ ? audio_stream.av_codec_context->frame_size
595
+ : 256;
596
+
597
+ // We always create a FIFO so that addSamples() can be called multiple times
598
+ // with various chunk sizes that are then buffered and encoded in frame_size
599
+ // sized batches.
600
+ auto av_audio_fifo = av_audio_fifo_alloc(
601
+ audio_stream.av_codec_context->sample_fmt,
602
+ out_num_channels,
603
+ audio_stream.frame_size * 2);
604
+ STD_TORCH_CHECK(av_audio_fifo != nullptr, "Couldn't create AVAudioFifo.");
605
+ audio_stream.av_audio_fifo.reset(av_audio_fifo);
606
+ }
607
+
608
+ void MultiStreamEncoder::open_streams_and_write_header() {
609
+ STD_TORCH_CHECK(
610
+ !video_streams_.empty() || !audio_streams_.empty(),
611
+ "Call addVideoStream() or addAudioStream() before open().");
612
+
613
+ for (auto& video_stream : video_streams_) {
614
+ initialize_video_stream(video_stream);
615
+ }
616
+ for (auto& audio_stream : audio_streams_) {
617
+ initialize_audio_stream(audio_stream);
618
+ }
619
+
620
+ int status = avformat_write_header(
621
+ av_format_context_.get(), av_format_options_.get_address());
622
+ STD_TORCH_CHECK(
623
+ status == AVSUCCESS,
624
+ "Error in avformat_write_header: ",
625
+ get_ffmpeg_error_string_from_error_code(status));
626
+ header_written_ = true;
627
+ }
628
+
629
+ void MultiStreamEncoder::add_frames(
630
+ const torch::stable::Tensor& frames,
631
+ int stream_index) {
632
+ STD_TORCH_CHECK(!closed_, "Cannot add frames after close() was called.");
633
+ STD_TORCH_CHECK(header_written_, "Call open() before addFrames().");
634
+ STD_TORCH_CHECK(
635
+ stream_index >= 0 &&
636
+ stream_index < static_cast<int>(video_streams_.size()),
637
+ "Invalid stream index ",
638
+ stream_index,
639
+ ". Number of video streams: ",
640
+ video_streams_.size());
641
+ auto& video_stream = video_streams_[stream_index];
642
+ auto validated_frames = validate_frames(
643
+ frames,
644
+ video_stream.av_codec_context.get(),
645
+ video_stream.device_interface.get());
646
+
647
+ AutoAVPacket auto_av_packet;
648
+ // TODO MultiStreamEncoder: Consider using accessor for potential performance
649
+ // improvement
650
+ int num_frames = static_cast<int>(validated_frames.sizes()[0]);
651
+ for (int i = 0; i < num_frames; ++i) {
652
+ torch::stable::Tensor curr_frame = select_row(validated_frames, i);
653
+ int frame_index = video_stream.num_encoded_frames + i;
654
+ UniqueAVFrame av_frame =
655
+ video_stream.device_interface->convert_tensor_to_av_frame_for_encoding(
656
+ curr_frame, frame_index, video_stream.av_codec_context.get());
657
+ STD_TORCH_CHECK(
658
+ av_frame != nullptr,
659
+ "convertTensorToAVFrameForEncoding failed for frame ",
660
+ frame_index,
661
+ " on device: ",
662
+ device_type_name(validated_frames.device().type()));
663
+ encode_video_frame(auto_av_packet, av_frame, video_stream);
664
+ }
665
+ video_stream.num_encoded_frames += num_frames;
666
+ }
667
+
668
+ void MultiStreamEncoder::encode_video_frame(
669
+ AutoAVPacket& auto_av_packet,
670
+ const UniqueAVFrame& av_frame,
671
+ VideoStream& video_stream) {
672
+ auto status =
673
+ avcodec_send_frame(video_stream.av_codec_context.get(), av_frame.get());
674
+ STD_TORCH_CHECK(
675
+ status == AVSUCCESS,
676
+ "Error while sending frame: ",
677
+ get_ffmpeg_error_string_from_error_code(status));
678
+
679
+ while (status >= 0) {
680
+ ReferenceAVPacket packet(auto_av_packet);
681
+ status = avcodec_receive_packet(
682
+ video_stream.av_codec_context.get(), packet.get());
683
+ if (status == AVERROR(EAGAIN) || status == AVERROR_EOF) {
684
+ if (status == AVERROR_EOF) {
685
+ // Flush remaining buffered packets
686
+ status = av_interleaved_write_frame(av_format_context_.get(), nullptr);
687
+ STD_TORCH_CHECK(
688
+ status == AVSUCCESS,
689
+ "Failed to flush packet: ",
690
+ get_ffmpeg_error_string_from_error_code(status));
691
+ }
692
+ return;
693
+ }
694
+ STD_TORCH_CHECK(
695
+ status >= 0,
696
+ "Error receiving packet: ",
697
+ get_ffmpeg_error_string_from_error_code(status));
698
+
699
+ // The code below is borrowed from torchaudio:
700
+ // https://github.com/pytorch/audio/blob/b6a3368a45aaafe05f1a6a9f10c68adc5e944d9e/src/libtorio/ffmpeg/stream_writer/encoder.cpp#L46
701
+ // Setting packet->duration to 1 allows the last frame to be properly
702
+ // encoded, and needs to be set before calling av_packet_rescale_ts.
703
+ if (packet->duration == 0) {
704
+ packet->duration = 1;
705
+ }
706
+ av_packet_rescale_ts(
707
+ packet.get(),
708
+ video_stream.av_codec_context->time_base,
709
+ video_stream.av_stream->time_base);
710
+ packet->stream_index = video_stream.av_stream->index;
711
+
712
+ status = av_interleaved_write_frame(av_format_context_.get(), packet.get());
713
+ STD_TORCH_CHECK(
714
+ status == AVSUCCESS,
715
+ "Error in av_interleaved_write_frame: ",
716
+ get_ffmpeg_error_string_from_error_code(status));
717
+ }
718
+ }
719
+
720
+ void MultiStreamEncoder::add_samples(
721
+ const torch::stable::Tensor& samples,
722
+ int stream_index) {
723
+ STD_TORCH_CHECK(!closed_, "Cannot add samples after close() was called.");
724
+ STD_TORCH_CHECK(header_written_, "Call open() before addSamples().");
725
+ STD_TORCH_CHECK(
726
+ stream_index >= 0 &&
727
+ stream_index < static_cast<int>(audio_streams_.size()),
728
+ "Invalid stream index ",
729
+ stream_index,
730
+ ". Number of audio streams: ",
731
+ audio_streams_.size());
732
+ auto& audio_stream = audio_streams_[stream_index];
733
+ auto validated_samples = validate_samples(samples);
734
+ STD_TORCH_CHECK(
735
+ static_cast<int>(validated_samples.sizes()[0]) ==
736
+ audio_stream.in_num_channels,
737
+ "Expected ",
738
+ audio_stream.in_num_channels,
739
+ " channels, got ",
740
+ validated_samples.sizes()[0]);
741
+ encode_audio_samples(validated_samples, audio_stream);
742
+ }
743
+
744
+ void MultiStreamEncoder::encode_audio_samples(
745
+ const torch::stable::Tensor& samples,
746
+ AudioStream& audio_stream) {
747
+ UniqueAVFrame av_frame = allocate_av_frame(
748
+ audio_stream.frame_size,
749
+ audio_stream.in_sample_rate,
750
+ audio_stream.in_num_channels,
751
+ AV_SAMPLE_FMT_FLTP);
752
+
753
+ AutoAVPacket auto_av_packet;
754
+
755
+ const uint8_t* psamples =
756
+ static_cast<const uint8_t*>(samples.const_data_ptr());
757
+ int num_samples = static_cast<int>(samples.sizes()[1]); // per channel
758
+ int num_encoded_samples = 0; // per channel
759
+ int num_bytes_per_sample = static_cast<int>(samples.element_size());
760
+ int num_bytes_per_channel = num_samples * num_bytes_per_sample;
761
+
762
+ while (num_encoded_samples < num_samples) {
763
+ int num_samples_to_encode =
764
+ std::min(audio_stream.frame_size, num_samples - num_encoded_samples);
765
+ int num_bytes_to_encode = num_samples_to_encode * num_bytes_per_sample;
766
+
767
+ for (int ch = 0; ch < audio_stream.in_num_channels; ch++) {
768
+ std::memcpy(
769
+ av_frame->data[ch],
770
+ psamples + ch * num_bytes_per_channel,
771
+ num_bytes_to_encode);
772
+ }
773
+ psamples += num_bytes_to_encode;
774
+
775
+ // Above, we set the AVFrame's .nb_samples to AVCodecContext.frame_size so
776
+ // that the frame buffers are allocated to a big enough size. Here, we reset
777
+ // it to the exact number of samples that need to be encoded, otherwise the
778
+ // encoded frame would contain more samples than necessary and our results
779
+ // wouldn't match the ffmpeg CLI.
780
+ av_frame->nb_samples = num_samples_to_encode;
781
+
782
+ UniqueAVFrame converted_av_frame =
783
+ maybe_convert_audio_av_frame(av_frame, audio_stream);
784
+ encode_audio_frame_through_fifo(
785
+ auto_av_packet, converted_av_frame, audio_stream);
786
+
787
+ num_encoded_samples += num_samples_to_encode;
788
+ }
789
+ STD_TORCH_CHECK(
790
+ num_encoded_samples == num_samples, "Hmmmmmm something went wrong.");
791
+ }
792
+
793
+ UniqueAVFrame MultiStreamEncoder::maybe_convert_audio_av_frame(
794
+ const UniqueAVFrame& av_frame,
795
+ AudioStream& audio_stream) {
796
+ if (static_cast<AVSampleFormat>(av_frame->format) ==
797
+ audio_stream.av_codec_context->sample_fmt &&
798
+ get_num_channels(*av_frame) == audio_stream.out_num_channels &&
799
+ av_frame->sample_rate == audio_stream.out_sample_rate) {
800
+ // Note: the clone references the same underlying data, it's a cheap copy.
801
+ return UniqueAVFrame(av_frame_clone(av_frame.get()));
802
+ }
803
+
804
+ if (!audio_stream.swr_context) {
805
+ audio_stream.swr_context.reset(create_swr_context(
806
+ static_cast<AVSampleFormat>(av_frame->format),
807
+ audio_stream.av_codec_context->sample_fmt,
808
+ av_frame->sample_rate,
809
+ audio_stream.out_sample_rate,
810
+ *av_frame,
811
+ audio_stream.out_num_channels));
812
+ }
813
+ // convertAudioAVFrameSamples uses avFrame's extended_data field, so we ensure
814
+ // it's the same as data. This should always be the case since we validated
815
+ // earlier that we have less than AV_NUM_DATA_POINTERS channels.
816
+ STD_TORCH_CHECK(
817
+ av_frame->data == av_frame->extended_data,
818
+ "Codec context data and extended_data pointers differ, this is unexpected.");
819
+ UniqueAVFrame converted_av_frame = convert_audio_av_frame_samples(
820
+ audio_stream.swr_context,
821
+ *av_frame,
822
+ audio_stream.av_codec_context->sample_fmt,
823
+ audio_stream.out_sample_rate,
824
+ audio_stream.out_num_channels);
825
+
826
+ if (av_frame->sample_rate == audio_stream.out_sample_rate) {
827
+ STD_TORCH_CHECK(
828
+ converted_av_frame->nb_samples == av_frame->nb_samples,
829
+ "convertedAVFrame->nb_samples=",
830
+ converted_av_frame->nb_samples,
831
+ " differs from ",
832
+ "avFrame->nb_samples=",
833
+ av_frame->nb_samples,
834
+ "This is unexpected, please report on the TorchCodec bug tracker.");
835
+ }
836
+ return converted_av_frame;
837
+ }
838
+
839
+ void MultiStreamEncoder::encode_audio_frame_through_fifo(
840
+ AutoAVPacket& auto_av_packet,
841
+ const UniqueAVFrame& av_frame,
842
+ AudioStream& audio_stream,
843
+ // flushFifo is only set to true in maybeFlushSwrAndFifo(), i.e. at the very
844
+ // end of the encoding process when we're flushing buffers. We also want to
845
+ // flush the FIFO so as to not leave any remaining samples in it.
846
+ bool flush_fifo) {
847
+ if (av_frame != nullptr) {
848
+ int num_samples_written = av_audio_fifo_write(
849
+ audio_stream.av_audio_fifo.get(),
850
+ reinterpret_cast<void**>(av_frame->data),
851
+ av_frame->nb_samples);
852
+ STD_TORCH_CHECK(
853
+ num_samples_written == av_frame->nb_samples,
854
+ "Tried to write ",
855
+ av_frame->nb_samples,
856
+ " samples, but only wrote ",
857
+ num_samples_written);
858
+ }
859
+
860
+ UniqueAVFrame newav_frame = allocate_av_frame(
861
+ audio_stream.frame_size,
862
+ audio_stream.av_codec_context->sample_rate,
863
+ audio_stream.out_num_channels,
864
+ audio_stream.av_codec_context->sample_fmt);
865
+
866
+ // Explaining the while bound:
867
+ // - if we're not flushing the FIFO, i.e. in most cases, we want to pull
868
+ // exactly `frame_size` samples from the FIFO, so we have to stop before it
869
+ // contains less than `frame_size` samples.
870
+ // - if we're flushing the FIFO, we want to read from the FIFO until the very
871
+ // last sample it contains.
872
+ //
873
+ // In both cases, for as long as we can, we're trying to pull exactly
874
+ // `frame_size` samples from the FIFO and send each `frame_size`-sized avFrame
875
+ // to encodeAudioFrame(). Only the very last avFrame of the encoding process
876
+ // is allowed to contain less than frame_size samples. That only happens when
877
+ // flushFifo is true.
878
+ while (av_audio_fifo_size(audio_stream.av_audio_fifo.get()) >=
879
+ (flush_fifo ? 1 : audio_stream.frame_size)) {
880
+ int samples_to_read = std::min(
881
+ av_audio_fifo_size(audio_stream.av_audio_fifo.get()),
882
+ newav_frame->nb_samples);
883
+ int num_samples_read = av_audio_fifo_read(
884
+ audio_stream.av_audio_fifo.get(),
885
+ reinterpret_cast<void**>(newav_frame->data),
886
+ samples_to_read);
887
+ STD_TORCH_CHECK(
888
+ num_samples_read == samples_to_read,
889
+ "Tried to read ",
890
+ samples_to_read,
891
+ " samples, but only read ",
892
+ num_samples_read);
893
+
894
+ newav_frame->nb_samples = num_samples_read;
895
+ encode_audio_frame(auto_av_packet, newav_frame, audio_stream);
896
+ }
897
+ }
898
+
899
+ void MultiStreamEncoder::encode_audio_frame(
900
+ AutoAVPacket& auto_av_packet,
901
+ const UniqueAVFrame& av_frame,
902
+ AudioStream& audio_stream) {
903
+ if (av_frame != nullptr) {
904
+ av_frame->pts = audio_stream.last_encoded_av_frame_pts;
905
+ audio_stream.last_encoded_av_frame_pts += av_frame->nb_samples;
906
+ }
907
+
908
+ auto status =
909
+ avcodec_send_frame(audio_stream.av_codec_context.get(), av_frame.get());
910
+ STD_TORCH_CHECK(
911
+ status == AVSUCCESS,
912
+ "Error while sending frame: ",
913
+ get_ffmpeg_error_string_from_error_code(status));
914
+
915
+ while (status >= 0) {
916
+ ReferenceAVPacket packet(auto_av_packet);
917
+ status = avcodec_receive_packet(
918
+ audio_stream.av_codec_context.get(), packet.get());
919
+ if (status == AVERROR(EAGAIN) || status == AVERROR_EOF) {
920
+ if (status == AVERROR_EOF) {
921
+ // Flush the packets that were potentially buffered by
922
+ // av_interleaved_write_frame(). See corresponding block in
923
+ // TorchAudio:
924
+ // https://github.com/pytorch/audio/blob/d60ce09e2c532d5bf2e05619e700ab520543465e/src/libtorio/ffmpeg/stream_writer/encoder.cpp#L21
925
+ status = av_interleaved_write_frame(av_format_context_.get(), nullptr);
926
+ STD_TORCH_CHECK(
927
+ status == AVSUCCESS,
928
+ "Failed to flush packet: ",
929
+ get_ffmpeg_error_string_from_error_code(status));
930
+ }
931
+ return;
932
+ }
933
+ STD_TORCH_CHECK(
934
+ status >= 0,
935
+ "Error receiving packet: ",
936
+ get_ffmpeg_error_string_from_error_code(status));
937
+
938
+ packet->stream_index = audio_stream.av_stream->index;
939
+ av_packet_rescale_ts(
940
+ packet.get(),
941
+ audio_stream.av_codec_context->time_base,
942
+ audio_stream.av_stream->time_base);
943
+
944
+ status = av_interleaved_write_frame(av_format_context_.get(), packet.get());
945
+ STD_TORCH_CHECK(
946
+ status == AVSUCCESS,
947
+ "Error in av_interleaved_write_frame: ",
948
+ get_ffmpeg_error_string_from_error_code(status));
949
+ }
950
+ }
951
+
952
+ void MultiStreamEncoder::maybe_flush_swr_and_fifo(
953
+ AutoAVPacket& auto_av_packet,
954
+ AudioStream& audio_stream) {
955
+ // When sample conversion is involved, libswresample may have buffered some
956
+ // samples that we need to flush into the FIFO before draining it.
957
+ UniqueAVFrame swr_frame(nullptr);
958
+ if (audio_stream.swr_context != nullptr) {
959
+ int num_remaining_samples = // this is an upper bound
960
+ swr_get_out_samples(audio_stream.swr_context.get(), 0);
961
+ if (num_remaining_samples > 0) {
962
+ swr_frame = allocate_av_frame(
963
+ num_remaining_samples,
964
+ audio_stream.out_sample_rate,
965
+ audio_stream.out_num_channels,
966
+ audio_stream.av_codec_context->sample_fmt);
967
+ int actual_num_remaining_samples = swr_convert(
968
+ audio_stream.swr_context.get(),
969
+ swr_frame->data,
970
+ swr_frame->nb_samples,
971
+ nullptr,
972
+ 0);
973
+ swr_frame->nb_samples = actual_num_remaining_samples;
974
+ }
975
+ }
976
+
977
+ // Flush any remaining swr samples into the FIFO, then drain it.
978
+ encode_audio_frame_through_fifo(
979
+ auto_av_packet, swr_frame, audio_stream, /*flushFifo=*/true);
980
+ }
981
+
982
+ void MultiStreamEncoder::flush_buffers() {
983
+ for (auto& audio_stream : audio_streams_) {
984
+ if (audio_stream.av_stream != nullptr) {
985
+ AutoAVPacket audio_av_packet;
986
+ maybe_flush_swr_and_fifo(audio_av_packet, audio_stream);
987
+ encode_audio_frame(audio_av_packet, UniqueAVFrame(nullptr), audio_stream);
988
+ }
989
+ }
990
+ for (auto& video_stream : video_streams_) {
991
+ if (video_stream.av_stream != nullptr) {
992
+ AutoAVPacket video_av_packet;
993
+ encode_video_frame(video_av_packet, UniqueAVFrame(nullptr), video_stream);
994
+ }
995
+ }
996
+ }
997
+
998
+ void MultiStreamEncoder::close() {
999
+ if (closed_) {
1000
+ return;
1001
+ }
1002
+ // TODO MultiStreamEncoder: Revisit if "closed_" flag is useful
1003
+ closed_ = true;
1004
+
1005
+ if (header_written_) {
1006
+ flush_buffers();
1007
+
1008
+ int status = av_write_trailer(av_format_context_.get());
1009
+ // av_write_trailer returns mfra atom size (positive) for fragmented
1010
+ // containers. All FFmpeg errors are negative, so positive is not an error.
1011
+ if (status > 0) {
1012
+ status = AVSUCCESS;
1013
+ }
1014
+ STD_TORCH_CHECK(
1015
+ status == AVSUCCESS,
1016
+ "Error in av_write_trailer: ",
1017
+ get_ffmpeg_error_string_from_error_code(status));
1018
+ }
1019
+
1020
+ close_avio_context(av_format_context_.get(), avio_context_holder_.get());
1021
+ }
1022
+
1023
+ } // namespace facebook::torchcodec