torchcodec 0.8.0__cp313-cp313-macosx_12_0_arm64.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.

Potentially problematic release.


This version of torchcodec might be problematic. Click here for more details.

Files changed (82) hide show
  1. torchcodec/.dylibs/libc++.1.0.dylib +0 -0
  2. torchcodec/.dylibs/libpython3.13.dylib +0 -0
  3. torchcodec/__init__.py +16 -0
  4. torchcodec/_core/AVIOContextHolder.cpp +60 -0
  5. torchcodec/_core/AVIOContextHolder.h +64 -0
  6. torchcodec/_core/AVIOFileLikeContext.cpp +98 -0
  7. torchcodec/_core/AVIOFileLikeContext.h +55 -0
  8. torchcodec/_core/AVIOTensorContext.cpp +123 -0
  9. torchcodec/_core/AVIOTensorContext.h +43 -0
  10. torchcodec/_core/BetaCudaDeviceInterface.cpp +636 -0
  11. torchcodec/_core/BetaCudaDeviceInterface.h +191 -0
  12. torchcodec/_core/CMakeLists.txt +325 -0
  13. torchcodec/_core/CUDACommon.cpp +315 -0
  14. torchcodec/_core/CUDACommon.h +46 -0
  15. torchcodec/_core/Cache.h +138 -0
  16. torchcodec/_core/CpuDeviceInterface.cpp +347 -0
  17. torchcodec/_core/CpuDeviceInterface.h +132 -0
  18. torchcodec/_core/CudaDeviceInterface.cpp +357 -0
  19. torchcodec/_core/CudaDeviceInterface.h +64 -0
  20. torchcodec/_core/DeviceInterface.cpp +117 -0
  21. torchcodec/_core/DeviceInterface.h +148 -0
  22. torchcodec/_core/Encoder.cpp +807 -0
  23. torchcodec/_core/Encoder.h +173 -0
  24. torchcodec/_core/FFMPEGCommon.cpp +608 -0
  25. torchcodec/_core/FFMPEGCommon.h +245 -0
  26. torchcodec/_core/FilterGraph.cpp +149 -0
  27. torchcodec/_core/FilterGraph.h +59 -0
  28. torchcodec/_core/Frame.cpp +42 -0
  29. torchcodec/_core/Frame.h +72 -0
  30. torchcodec/_core/Metadata.h +72 -0
  31. torchcodec/_core/NVDECCache.cpp +70 -0
  32. torchcodec/_core/NVDECCache.h +104 -0
  33. torchcodec/_core/SingleStreamDecoder.cpp +1719 -0
  34. torchcodec/_core/SingleStreamDecoder.h +405 -0
  35. torchcodec/_core/StreamOptions.h +63 -0
  36. torchcodec/_core/Transform.cpp +60 -0
  37. torchcodec/_core/Transform.h +59 -0
  38. torchcodec/_core/ValidationUtils.cpp +35 -0
  39. torchcodec/_core/ValidationUtils.h +21 -0
  40. torchcodec/_core/__init__.py +41 -0
  41. torchcodec/_core/_metadata.py +317 -0
  42. torchcodec/_core/custom_ops.cpp +875 -0
  43. torchcodec/_core/fetch_and_expose_non_gpl_ffmpeg_libs.cmake +360 -0
  44. torchcodec/_core/nvcuvid_include/cuviddec.h +1374 -0
  45. torchcodec/_core/nvcuvid_include/nvcuvid.h +610 -0
  46. torchcodec/_core/ops.py +498 -0
  47. torchcodec/_core/pybind_ops.cpp +50 -0
  48. torchcodec/_frame.py +145 -0
  49. torchcodec/_internally_replaced_utils.py +67 -0
  50. torchcodec/_samplers/__init__.py +7 -0
  51. torchcodec/_samplers/video_clip_sampler.py +418 -0
  52. torchcodec/decoders/__init__.py +12 -0
  53. torchcodec/decoders/_audio_decoder.py +177 -0
  54. torchcodec/decoders/_decoder_utils.py +112 -0
  55. torchcodec/decoders/_video_decoder.py +500 -0
  56. torchcodec/encoders/__init__.py +1 -0
  57. torchcodec/encoders/_audio_encoder.py +150 -0
  58. torchcodec/libtorchcodec_core4.dylib +0 -0
  59. torchcodec/libtorchcodec_core5.dylib +0 -0
  60. torchcodec/libtorchcodec_core6.dylib +0 -0
  61. torchcodec/libtorchcodec_core7.dylib +0 -0
  62. torchcodec/libtorchcodec_core8.dylib +0 -0
  63. torchcodec/libtorchcodec_custom_ops4.dylib +0 -0
  64. torchcodec/libtorchcodec_custom_ops5.dylib +0 -0
  65. torchcodec/libtorchcodec_custom_ops6.dylib +0 -0
  66. torchcodec/libtorchcodec_custom_ops7.dylib +0 -0
  67. torchcodec/libtorchcodec_custom_ops8.dylib +0 -0
  68. torchcodec/libtorchcodec_pybind_ops4.so +0 -0
  69. torchcodec/libtorchcodec_pybind_ops5.so +0 -0
  70. torchcodec/libtorchcodec_pybind_ops6.so +0 -0
  71. torchcodec/libtorchcodec_pybind_ops7.so +0 -0
  72. torchcodec/libtorchcodec_pybind_ops8.so +0 -0
  73. torchcodec/samplers/__init__.py +2 -0
  74. torchcodec/samplers/_common.py +84 -0
  75. torchcodec/samplers/_index_based.py +287 -0
  76. torchcodec/samplers/_time_based.py +358 -0
  77. torchcodec/version.py +2 -0
  78. torchcodec-0.8.0.dist-info/METADATA +253 -0
  79. torchcodec-0.8.0.dist-info/RECORD +82 -0
  80. torchcodec-0.8.0.dist-info/WHEEL +5 -0
  81. torchcodec-0.8.0.dist-info/licenses/LICENSE +28 -0
  82. torchcodec-0.8.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,608 @@
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 "src/torchcodec/_core/FFMPEGCommon.h"
8
+
9
+ #include <c10/util/Exception.h>
10
+
11
+ extern "C" {
12
+ #include <libavfilter/avfilter.h>
13
+ #include <libavfilter/buffersink.h>
14
+ }
15
+
16
+ namespace facebook::torchcodec {
17
+
18
+ AutoAVPacket::AutoAVPacket() : avPacket_(av_packet_alloc()) {
19
+ TORCH_CHECK(avPacket_ != nullptr, "Couldn't allocate avPacket.");
20
+ }
21
+
22
+ AutoAVPacket::~AutoAVPacket() {
23
+ av_packet_free(&avPacket_);
24
+ }
25
+
26
+ ReferenceAVPacket::ReferenceAVPacket(AutoAVPacket& shared)
27
+ : avPacket_(shared.avPacket_) {}
28
+
29
+ ReferenceAVPacket::~ReferenceAVPacket() {
30
+ av_packet_unref(avPacket_);
31
+ }
32
+
33
+ AVPacket* ReferenceAVPacket::get() {
34
+ return avPacket_;
35
+ }
36
+
37
+ AVPacket* ReferenceAVPacket::operator->() {
38
+ return avPacket_;
39
+ }
40
+
41
+ AVCodecOnlyUseForCallingAVFindBestStream
42
+ makeAVCodecOnlyUseForCallingAVFindBestStream(const AVCodec* codec) {
43
+ #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 18, 100)
44
+ return const_cast<AVCodec*>(codec);
45
+ #else
46
+ return codec;
47
+ #endif
48
+ }
49
+
50
+ std::string getFFMPEGErrorStringFromErrorCode(int errorCode) {
51
+ char errorBuffer[AV_ERROR_MAX_STRING_SIZE] = {0};
52
+ av_strerror(errorCode, errorBuffer, AV_ERROR_MAX_STRING_SIZE);
53
+ return std::string(errorBuffer);
54
+ }
55
+
56
+ int64_t getDuration(const UniqueAVFrame& avFrame) {
57
+ #if LIBAVUTIL_VERSION_MAJOR < 58
58
+ return avFrame->pkt_duration;
59
+ #else
60
+ return avFrame->duration;
61
+ #endif
62
+ }
63
+
64
+ void setDuration(const UniqueAVFrame& avFrame, int64_t duration) {
65
+ #if LIBAVUTIL_VERSION_MAJOR < 58
66
+ avFrame->pkt_duration = duration;
67
+ #else
68
+ avFrame->duration = duration;
69
+ #endif
70
+ }
71
+
72
+ const int* getSupportedSampleRates(const AVCodec& avCodec) {
73
+ const int* supportedSampleRates = nullptr;
74
+ #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(61, 13, 100) // FFmpeg >= 7.1
75
+ int numSampleRates = 0;
76
+ int ret = avcodec_get_supported_config(
77
+ nullptr,
78
+ &avCodec,
79
+ AV_CODEC_CONFIG_SAMPLE_RATE,
80
+ 0,
81
+ reinterpret_cast<const void**>(&supportedSampleRates),
82
+ &numSampleRates);
83
+ if (ret < 0 || supportedSampleRates == nullptr) {
84
+ // Return nullptr to skip validation in validateSampleRate.
85
+ return nullptr;
86
+ }
87
+ #else
88
+ supportedSampleRates = avCodec.supported_samplerates;
89
+ #endif
90
+ return supportedSampleRates;
91
+ }
92
+
93
+ const AVPixelFormat* getSupportedPixelFormats(const AVCodec& avCodec) {
94
+ const AVPixelFormat* supportedPixelFormats = nullptr;
95
+ #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(61, 13, 100) // FFmpeg >= 7.1
96
+ int numPixelFormats = 0;
97
+ int ret = avcodec_get_supported_config(
98
+ nullptr,
99
+ &avCodec,
100
+ AV_CODEC_CONFIG_PIX_FORMAT,
101
+ 0,
102
+ reinterpret_cast<const void**>(&supportedPixelFormats),
103
+ &numPixelFormats);
104
+ if (ret < 0 || supportedPixelFormats == nullptr) {
105
+ TORCH_CHECK(false, "Couldn't get supported pixel formats from encoder.");
106
+ }
107
+ #else
108
+ supportedPixelFormats = avCodec.pix_fmts;
109
+ #endif
110
+ return supportedPixelFormats;
111
+ }
112
+
113
+ const AVSampleFormat* getSupportedOutputSampleFormats(const AVCodec& avCodec) {
114
+ const AVSampleFormat* supportedSampleFormats = nullptr;
115
+ #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(61, 13, 100) // FFmpeg >= 7.1
116
+ int numSampleFormats = 0;
117
+ int ret = avcodec_get_supported_config(
118
+ nullptr,
119
+ &avCodec,
120
+ AV_CODEC_CONFIG_SAMPLE_FORMAT,
121
+ 0,
122
+ reinterpret_cast<const void**>(&supportedSampleFormats),
123
+ &numSampleFormats);
124
+ if (ret < 0 || supportedSampleFormats == nullptr) {
125
+ // Return nullptr to use default output format in
126
+ // findBestOutputSampleFormat.
127
+ return nullptr;
128
+ }
129
+ #else
130
+ supportedSampleFormats = avCodec.sample_fmts;
131
+ #endif
132
+ return supportedSampleFormats;
133
+ }
134
+
135
+ int getNumChannels(const UniqueAVFrame& avFrame) {
136
+ #if LIBAVFILTER_VERSION_MAJOR > 8 || \
137
+ (LIBAVFILTER_VERSION_MAJOR == 8 && LIBAVFILTER_VERSION_MINOR >= 44)
138
+ return avFrame->ch_layout.nb_channels;
139
+ #else
140
+ int numChannels = av_get_channel_layout_nb_channels(avFrame->channel_layout);
141
+ // Handle FFmpeg 4 bug where channel_layout and numChannels are 0 or unset
142
+ // Set values based on avFrame->channels which appears to be correct
143
+ // to allow successful initialization of SwrContext
144
+ if (numChannels == 0 && avFrame->channels > 0) {
145
+ avFrame->channel_layout = av_get_default_channel_layout(avFrame->channels);
146
+ numChannels = avFrame->channels;
147
+ }
148
+ return numChannels;
149
+ #endif
150
+ }
151
+
152
+ int getNumChannels(const UniqueAVCodecContext& avCodecContext) {
153
+ #if LIBAVFILTER_VERSION_MAJOR > 8 || \
154
+ (LIBAVFILTER_VERSION_MAJOR == 8 && LIBAVFILTER_VERSION_MINOR >= 44)
155
+ return avCodecContext->ch_layout.nb_channels;
156
+ #else
157
+ return avCodecContext->channels;
158
+ #endif
159
+ }
160
+
161
+ void setDefaultChannelLayout(
162
+ UniqueAVCodecContext& avCodecContext,
163
+ int numChannels) {
164
+ #if LIBAVFILTER_VERSION_MAJOR > 7 // FFmpeg > 4
165
+ AVChannelLayout channel_layout;
166
+ av_channel_layout_default(&channel_layout, numChannels);
167
+ avCodecContext->ch_layout = channel_layout;
168
+ #else
169
+ uint64_t channel_layout = av_get_default_channel_layout(numChannels);
170
+ avCodecContext->channel_layout = channel_layout;
171
+ avCodecContext->channels = numChannels;
172
+ #endif
173
+ }
174
+
175
+ void setDefaultChannelLayout(UniqueAVFrame& avFrame, int numChannels) {
176
+ #if LIBAVFILTER_VERSION_MAJOR > 7 // FFmpeg > 4
177
+ AVChannelLayout channel_layout;
178
+ av_channel_layout_default(&channel_layout, numChannels);
179
+ avFrame->ch_layout = channel_layout;
180
+ #else
181
+ uint64_t channel_layout = av_get_default_channel_layout(numChannels);
182
+ avFrame->channel_layout = channel_layout;
183
+ avFrame->channels = numChannels;
184
+ #endif
185
+ }
186
+
187
+ void validateNumChannels(const AVCodec& avCodec, int numChannels) {
188
+ #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(61, 13, 100) // FFmpeg >= 7.1
189
+ std::stringstream supportedNumChannels;
190
+ const AVChannelLayout* supportedLayouts = nullptr;
191
+ int numLayouts = 0;
192
+ int ret = avcodec_get_supported_config(
193
+ nullptr,
194
+ &avCodec,
195
+ AV_CODEC_CONFIG_CHANNEL_LAYOUT,
196
+ 0,
197
+ reinterpret_cast<const void**>(&supportedLayouts),
198
+ &numLayouts);
199
+ if (ret < 0 || supportedLayouts == nullptr) {
200
+ // If we can't validate, we must assume it'll be fine. If not, FFmpeg will
201
+ // eventually raise.
202
+ return;
203
+ }
204
+ for (int i = 0; i < numLayouts; ++i) {
205
+ if (i > 0) {
206
+ supportedNumChannels << ", ";
207
+ }
208
+ supportedNumChannels << supportedLayouts[i].nb_channels;
209
+ if (numChannels == supportedLayouts[i].nb_channels) {
210
+ return;
211
+ }
212
+ }
213
+ #elif LIBAVFILTER_VERSION_MAJOR > 7 // FFmpeg > 4
214
+ if (avCodec.ch_layouts == nullptr) {
215
+ // If we can't validate, we must assume it'll be fine. If not, FFmpeg will
216
+ // eventually raise.
217
+ return;
218
+ }
219
+ // FFmpeg doc indicate that the ch_layouts array is terminated by a zeroed
220
+ // layout, so checking for nb_channels == 0 should indicate its end.
221
+ for (auto i = 0; avCodec.ch_layouts[i].nb_channels != 0; ++i) {
222
+ if (numChannels == avCodec.ch_layouts[i].nb_channels) {
223
+ return;
224
+ }
225
+ }
226
+ // At this point it seems that the encoder doesn't support the requested
227
+ // number of channels, so we error out.
228
+ std::stringstream supportedNumChannels;
229
+ for (auto i = 0; avCodec.ch_layouts[i].nb_channels != 0; ++i) {
230
+ if (i > 0) {
231
+ supportedNumChannels << ", ";
232
+ }
233
+ supportedNumChannels << avCodec.ch_layouts[i].nb_channels;
234
+ }
235
+ #else // FFmpeg <= 4
236
+ if (avCodec.channel_layouts == nullptr) {
237
+ // can't validate, same as above.
238
+ return;
239
+ }
240
+ for (auto i = 0; avCodec.channel_layouts[i] != 0; ++i) {
241
+ if (numChannels ==
242
+ av_get_channel_layout_nb_channels(avCodec.channel_layouts[i])) {
243
+ return;
244
+ }
245
+ }
246
+ // At this point it seems that the encoder doesn't support the requested
247
+ // number of channels, so we error out.
248
+ std::stringstream supportedNumChannels;
249
+ for (auto i = 0; avCodec.channel_layouts[i] != 0; ++i) {
250
+ if (i > 0) {
251
+ supportedNumChannels << ", ";
252
+ }
253
+ supportedNumChannels << av_get_channel_layout_nb_channels(
254
+ avCodec.channel_layouts[i]);
255
+ }
256
+ #endif
257
+ TORCH_CHECK(
258
+ false,
259
+ "Desired number of channels (",
260
+ numChannels,
261
+ ") is not supported by the ",
262
+ "encoder. Supported number of channels are: ",
263
+ supportedNumChannels.str(),
264
+ ".");
265
+ }
266
+
267
+ namespace {
268
+ #if LIBAVFILTER_VERSION_MAJOR > 7 // FFmpeg > 4
269
+
270
+ // Returns:
271
+ // - the srcAVFrame's channel layout if srcAVFrame has outNumChannels
272
+ // - the default channel layout with outNumChannels otherwise.
273
+ AVChannelLayout getOutputChannelLayout(
274
+ int outNumChannels,
275
+ const UniqueAVFrame& srcAVFrame) {
276
+ AVChannelLayout outLayout;
277
+ if (outNumChannels == getNumChannels(srcAVFrame)) {
278
+ outLayout = srcAVFrame->ch_layout;
279
+ } else {
280
+ av_channel_layout_default(&outLayout, outNumChannels);
281
+ }
282
+ return outLayout;
283
+ }
284
+
285
+ #else
286
+
287
+ // Same as above
288
+ int64_t getOutputChannelLayout(
289
+ int outNumChannels,
290
+ const UniqueAVFrame& srcAVFrame) {
291
+ int64_t outLayout;
292
+ if (outNumChannels == getNumChannels(srcAVFrame)) {
293
+ outLayout = srcAVFrame->channel_layout;
294
+ } else {
295
+ outLayout = av_get_default_channel_layout(outNumChannels);
296
+ }
297
+ return outLayout;
298
+ }
299
+ #endif
300
+ } // namespace
301
+
302
+ // Sets dstAVFrame' channel layout to getOutputChannelLayout(): see doc above
303
+ void setChannelLayout(
304
+ UniqueAVFrame& dstAVFrame,
305
+ const UniqueAVFrame& srcAVFrame,
306
+ int outNumChannels) {
307
+ #if LIBAVFILTER_VERSION_MAJOR > 7 // FFmpeg > 4
308
+ AVChannelLayout outLayout =
309
+ getOutputChannelLayout(outNumChannels, srcAVFrame);
310
+ auto status = av_channel_layout_copy(&dstAVFrame->ch_layout, &outLayout);
311
+ TORCH_CHECK(
312
+ status == AVSUCCESS,
313
+ "Couldn't copy channel layout to avFrame: ",
314
+ getFFMPEGErrorStringFromErrorCode(status));
315
+ #else
316
+ dstAVFrame->channel_layout =
317
+ getOutputChannelLayout(outNumChannels, srcAVFrame);
318
+ dstAVFrame->channels = outNumChannels;
319
+ #endif
320
+ }
321
+
322
+ UniqueAVFrame allocateAVFrame(
323
+ int numSamples,
324
+ int sampleRate,
325
+ int numChannels,
326
+ AVSampleFormat sampleFormat) {
327
+ auto avFrame = UniqueAVFrame(av_frame_alloc());
328
+ TORCH_CHECK(avFrame != nullptr, "Couldn't allocate AVFrame.");
329
+
330
+ avFrame->nb_samples = numSamples;
331
+ avFrame->sample_rate = sampleRate;
332
+ setDefaultChannelLayout(avFrame, numChannels);
333
+ avFrame->format = sampleFormat;
334
+ auto status = av_frame_get_buffer(avFrame.get(), 0);
335
+
336
+ TORCH_CHECK(
337
+ status == AVSUCCESS,
338
+ "Couldn't allocate avFrame's buffers: ",
339
+ getFFMPEGErrorStringFromErrorCode(status));
340
+
341
+ status = av_frame_make_writable(avFrame.get());
342
+ TORCH_CHECK(
343
+ status == AVSUCCESS,
344
+ "Couldn't make AVFrame writable: ",
345
+ getFFMPEGErrorStringFromErrorCode(status));
346
+ return avFrame;
347
+ }
348
+
349
+ SwrContext* createSwrContext(
350
+ AVSampleFormat srcSampleFormat,
351
+ AVSampleFormat outSampleFormat,
352
+ int srcSampleRate,
353
+ int outSampleRate,
354
+ const UniqueAVFrame& srcAVFrame,
355
+ int outNumChannels) {
356
+ SwrContext* swrContext = nullptr;
357
+ int status = AVSUCCESS;
358
+ #if LIBAVFILTER_VERSION_MAJOR > 7 // FFmpeg > 4
359
+ AVChannelLayout outLayout =
360
+ getOutputChannelLayout(outNumChannels, srcAVFrame);
361
+ status = swr_alloc_set_opts2(
362
+ &swrContext,
363
+ &outLayout,
364
+ outSampleFormat,
365
+ outSampleRate,
366
+ &srcAVFrame->ch_layout,
367
+ srcSampleFormat,
368
+ srcSampleRate,
369
+ 0,
370
+ nullptr);
371
+
372
+ TORCH_CHECK(
373
+ status == AVSUCCESS,
374
+ "Couldn't create SwrContext: ",
375
+ getFFMPEGErrorStringFromErrorCode(status));
376
+ #else
377
+ int64_t outLayout = getOutputChannelLayout(outNumChannels, srcAVFrame);
378
+ swrContext = swr_alloc_set_opts(
379
+ nullptr,
380
+ outLayout,
381
+ outSampleFormat,
382
+ outSampleRate,
383
+ srcAVFrame->channel_layout,
384
+ srcSampleFormat,
385
+ srcSampleRate,
386
+ 0,
387
+ nullptr);
388
+ #endif
389
+
390
+ TORCH_CHECK(swrContext != nullptr, "Couldn't create swrContext");
391
+ status = swr_init(swrContext);
392
+ TORCH_CHECK(
393
+ status == AVSUCCESS,
394
+ "Couldn't initialize SwrContext: ",
395
+ getFFMPEGErrorStringFromErrorCode(status),
396
+ ". If the error says 'Invalid argument', it's likely that you are using "
397
+ "a buggy FFmpeg version. FFmpeg4 is known to fail here in some "
398
+ "valid scenarios. Try to upgrade FFmpeg?");
399
+ return swrContext;
400
+ }
401
+
402
+ AVFilterContext* createBuffersinkFilter(
403
+ AVFilterGraph* filterGraph,
404
+ enum AVPixelFormat outputFormat) {
405
+ const AVFilter* buffersink = avfilter_get_by_name("buffersink");
406
+ TORCH_CHECK(buffersink != nullptr, "Failed to get buffersink filter.");
407
+
408
+ AVFilterContext* sinkContext = nullptr;
409
+ int status;
410
+ const char* filterName = "out";
411
+
412
+ enum AVPixelFormat pix_fmts[] = {outputFormat, AV_PIX_FMT_NONE};
413
+
414
+ // av_opt_set_int_list was replaced by av_opt_set_array() in FFmpeg 8.
415
+ #if LIBAVUTIL_VERSION_MAJOR >= 60 // FFmpeg >= 8
416
+ // Output options like pixel_formats must be set before filter init
417
+ sinkContext =
418
+ avfilter_graph_alloc_filter(filterGraph, buffersink, filterName);
419
+ TORCH_CHECK(
420
+ sinkContext != nullptr, "Failed to allocate buffersink filter context.");
421
+
422
+ // When setting pix_fmts, only the first element is used, so nb_elems = 1
423
+ // AV_PIX_FMT_NONE acts as a terminator for the array in av_opt_set_int_list
424
+ status = av_opt_set_array(
425
+ sinkContext,
426
+ "pixel_formats",
427
+ AV_OPT_SEARCH_CHILDREN,
428
+ 0, // start_elem
429
+ 1, // nb_elems
430
+ AV_OPT_TYPE_PIXEL_FMT,
431
+ pix_fmts);
432
+ TORCH_CHECK(
433
+ status >= 0,
434
+ "Failed to set pixel format for buffersink filter: ",
435
+ getFFMPEGErrorStringFromErrorCode(status));
436
+
437
+ status = avfilter_init_str(sinkContext, nullptr);
438
+ TORCH_CHECK(
439
+ status >= 0,
440
+ "Failed to initialize buffersink filter: ",
441
+ getFFMPEGErrorStringFromErrorCode(status));
442
+ #else // FFmpeg <= 7
443
+ // For older FFmpeg versions, create filter and then set options
444
+ status = avfilter_graph_create_filter(
445
+ &sinkContext, buffersink, filterName, nullptr, nullptr, filterGraph);
446
+ TORCH_CHECK(
447
+ status >= 0,
448
+ "Failed to create buffersink filter: ",
449
+ getFFMPEGErrorStringFromErrorCode(status));
450
+
451
+ status = av_opt_set_int_list(
452
+ sinkContext,
453
+ "pix_fmts",
454
+ pix_fmts,
455
+ AV_PIX_FMT_NONE,
456
+ AV_OPT_SEARCH_CHILDREN);
457
+ TORCH_CHECK(
458
+ status >= 0,
459
+ "Failed to set pixel formats for buffersink filter: ",
460
+ getFFMPEGErrorStringFromErrorCode(status));
461
+ #endif
462
+
463
+ return sinkContext;
464
+ }
465
+
466
+ UniqueAVFrame convertAudioAVFrameSamples(
467
+ const UniqueSwrContext& swrContext,
468
+ const UniqueAVFrame& srcAVFrame,
469
+ AVSampleFormat outSampleFormat,
470
+ int outSampleRate,
471
+ int outNumChannels) {
472
+ UniqueAVFrame convertedAVFrame(av_frame_alloc());
473
+ TORCH_CHECK(
474
+ convertedAVFrame,
475
+ "Could not allocate frame for sample format conversion.");
476
+
477
+ convertedAVFrame->pts = srcAVFrame->pts;
478
+ convertedAVFrame->format = static_cast<int>(outSampleFormat);
479
+
480
+ convertedAVFrame->sample_rate = outSampleRate;
481
+ int srcSampleRate = srcAVFrame->sample_rate;
482
+ if (srcSampleRate != outSampleRate) {
483
+ // Note that this is an upper bound on the number of output samples.
484
+ // `swr_convert()` will likely not fill convertedAVFrame with that many
485
+ // samples if sample rate conversion is needed. It will buffer the last few
486
+ // ones because those require future samples. That's also why we reset
487
+ // nb_samples after the call to `swr_convert()`.
488
+ // We could also use `swr_get_out_samples()` to determine the number of
489
+ // output samples, but empirically `av_rescale_rnd()` seems to provide a
490
+ // tighter bound.
491
+ convertedAVFrame->nb_samples = av_rescale_rnd(
492
+ swr_get_delay(swrContext.get(), srcSampleRate) + srcAVFrame->nb_samples,
493
+ outSampleRate,
494
+ srcSampleRate,
495
+ AV_ROUND_UP);
496
+ } else {
497
+ convertedAVFrame->nb_samples = srcAVFrame->nb_samples;
498
+ }
499
+
500
+ setChannelLayout(convertedAVFrame, srcAVFrame, outNumChannels);
501
+
502
+ auto status = av_frame_get_buffer(convertedAVFrame.get(), 0);
503
+ TORCH_CHECK(
504
+ status == AVSUCCESS,
505
+ "Could not allocate frame buffers for sample format conversion: ",
506
+ getFFMPEGErrorStringFromErrorCode(status));
507
+
508
+ auto numConvertedSamples = swr_convert(
509
+ swrContext.get(),
510
+ convertedAVFrame->data,
511
+ convertedAVFrame->nb_samples,
512
+ static_cast<const uint8_t**>(
513
+ const_cast<const uint8_t**>(srcAVFrame->data)),
514
+ srcAVFrame->nb_samples);
515
+ // numConvertedSamples can be 0 if we're downsampling by a great factor and
516
+ // the first frame doesn't contain a lot of samples. It should be handled
517
+ // properly by the caller.
518
+ TORCH_CHECK(
519
+ numConvertedSamples >= 0,
520
+ "Error in swr_convert: ",
521
+ getFFMPEGErrorStringFromErrorCode(numConvertedSamples));
522
+
523
+ // See comment above about nb_samples
524
+ convertedAVFrame->nb_samples = numConvertedSamples;
525
+
526
+ return convertedAVFrame;
527
+ }
528
+
529
+ void setFFmpegLogLevel() {
530
+ auto logLevel = AV_LOG_QUIET;
531
+ const char* logLevelEnvPtr = std::getenv("TORCHCODEC_FFMPEG_LOG_LEVEL");
532
+ if (logLevelEnvPtr != nullptr) {
533
+ std::string logLevelEnv(logLevelEnvPtr);
534
+ if (logLevelEnv == "QUIET") {
535
+ logLevel = AV_LOG_QUIET;
536
+ } else if (logLevelEnv == "PANIC") {
537
+ logLevel = AV_LOG_PANIC;
538
+ } else if (logLevelEnv == "FATAL") {
539
+ logLevel = AV_LOG_FATAL;
540
+ } else if (logLevelEnv == "ERROR") {
541
+ logLevel = AV_LOG_ERROR;
542
+ } else if (logLevelEnv == "WARNING") {
543
+ logLevel = AV_LOG_WARNING;
544
+ } else if (logLevelEnv == "INFO") {
545
+ logLevel = AV_LOG_INFO;
546
+ } else if (logLevelEnv == "VERBOSE") {
547
+ logLevel = AV_LOG_VERBOSE;
548
+ } else if (logLevelEnv == "DEBUG") {
549
+ logLevel = AV_LOG_DEBUG;
550
+ } else if (logLevelEnv == "TRACE") {
551
+ logLevel = AV_LOG_TRACE;
552
+ } else {
553
+ TORCH_CHECK(
554
+ false,
555
+ "Invalid TORCHCODEC_FFMPEG_LOG_LEVEL: ",
556
+ logLevelEnv,
557
+ ". Use e.g. 'QUIET', 'PANIC', 'VERBOSE', etc.");
558
+ }
559
+ }
560
+ av_log_set_level(logLevel);
561
+ }
562
+
563
+ AVIOContext* avioAllocContext(
564
+ uint8_t* buffer,
565
+ int buffer_size,
566
+ int write_flag,
567
+ void* opaque,
568
+ AVIOReadFunction read_packet,
569
+ AVIOWriteFunction write_packet,
570
+ AVIOSeekFunction seek) {
571
+ return avio_alloc_context(
572
+ buffer,
573
+ buffer_size,
574
+ write_flag,
575
+ opaque,
576
+ read_packet,
577
+ // The buf parameter of the write function is not const before FFmpeg 7.
578
+ #if LIBAVFILTER_VERSION_MAJOR >= 10 // FFmpeg >= 7
579
+ write_packet,
580
+ #else
581
+ reinterpret_cast<AVIOWriteFunctionOld>(write_packet),
582
+ #endif
583
+ seek);
584
+ }
585
+
586
+ double ptsToSeconds(int64_t pts, const AVRational& timeBase) {
587
+ // To perform the multiplication before the division, av_q2d is not used
588
+ return static_cast<double>(pts) * timeBase.num / timeBase.den;
589
+ }
590
+
591
+ int64_t secondsToClosestPts(double seconds, const AVRational& timeBase) {
592
+ return static_cast<int64_t>(
593
+ std::round(seconds * timeBase.den / timeBase.num));
594
+ }
595
+
596
+ int64_t computeSafeDuration(
597
+ const AVRational& frameRate,
598
+ const AVRational& timeBase) {
599
+ if (frameRate.num <= 0 || frameRate.den <= 0 || timeBase.num <= 0 ||
600
+ timeBase.den <= 0) {
601
+ return 0;
602
+ } else {
603
+ return (static_cast<int64_t>(frameRate.den) * timeBase.den) /
604
+ (static_cast<int64_t>(timeBase.num) * frameRate.num);
605
+ }
606
+ }
607
+
608
+ } // namespace facebook::torchcodec