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,506 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <memory>
10
+ #include <optional>
11
+ #include <stdexcept>
12
+ #include <string>
13
+ #include <vector>
14
+
15
+ #include "StreamOptions.h"
16
+
17
+ extern "C" {
18
+ #include <libavcodec/avcodec.h>
19
+ #include <libavcodec/bsf.h>
20
+ #include <libavfilter/avfilter.h>
21
+ #include <libavfilter/buffersrc.h>
22
+ #include <libavformat/avformat.h>
23
+ #include <libavformat/avio.h>
24
+ #include <libavutil/audio_fifo.h>
25
+ #include <libavutil/avutil.h>
26
+ #include <libavutil/dict.h>
27
+ #include <libavutil/display.h>
28
+ #include <libavutil/file.h>
29
+ #include <libavutil/opt.h>
30
+ #include <libavutil/pixdesc.h>
31
+ #include <libavutil/pixfmt.h>
32
+ #include <libavutil/version.h>
33
+ #include <libswresample/swresample.h>
34
+ #include <libswscale/swscale.h>
35
+ }
36
+
37
+ // FFmpeg 5.1 replaced the .channels + .channel_layout pair on AVFrame and
38
+ // AVCodecContext with a single AVChannelLayout .ch_layout, and added the
39
+ // av_channel_layout_* / swr_alloc_set_opts2() APIs that go with it.
40
+ // libavutil 57.24 is the real marker, but libavfilter 8.44 is the equivalent
41
+ // and is what this codebase has always tested against.
42
+ #if LIBAVFILTER_VERSION_MAJOR > 8 || \
43
+ (LIBAVFILTER_VERSION_MAJOR == 8 && LIBAVFILTER_VERSION_MINOR >= 44)
44
+ #define FFMPEG_HAS_CH_LAYOUT 1
45
+ #else
46
+ #define FFMPEG_HAS_CH_LAYOUT 0
47
+ #endif
48
+
49
+ // FFmpeg 6 added AV_PIX_FMT_P012, the 12-bit sibling of P010.
50
+ #if LIBAVUTIL_VERSION_MAJOR >= 58
51
+ #define FFMPEG_HAS_P012 1
52
+ #else
53
+ #define FFMPEG_HAS_P012 0
54
+ #endif
55
+
56
+ // FFmpeg 7.1 added avcodec_get_supported_config(), replacing the codec's
57
+ // pix_fmts / sample_fmts / supported_samplerates / ch_layouts arrays.
58
+ #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(61, 13, 100)
59
+ #define FFMPEG_HAS_SUPPORTED_CONFIG 1
60
+ #else
61
+ #define FFMPEG_HAS_SUPPORTED_CONFIG 0
62
+ #endif
63
+
64
+ // FFmpeg 4's sws_setColorspaceDetails() returns -1 when the source and the
65
+ // destination are both YUV or gray, as its way of saying it can't apply a
66
+ // colorspace matrix between the two. It's not a failure: the color ranges it
67
+ // was asked for are still honored, and FFmpeg 5 and above return 0 for the very
68
+ // same conversion, with the very same output.
69
+ #if LIBSWSCALE_VERSION_MAJOR < 6
70
+ #define FFMPEG_SWS_COLORSPACE_DETAILS_FAILS_ON_YUV_TO_YUV 1
71
+ #else
72
+ #define FFMPEG_SWS_COLORSPACE_DETAILS_FAILS_ON_YUV_TO_YUV 0
73
+ #endif
74
+
75
+ // FFmpeg 6 renamed AVFrame.pkt_duration to AVFrame.duration.
76
+ #if LIBAVUTIL_VERSION_MAJOR < 58
77
+ #define FFMPEG_HAS_FRAME_DURATION 0
78
+ #else
79
+ #define FFMPEG_HAS_FRAME_DURATION 1
80
+ #endif
81
+
82
+ // FFmpeg 6.1 moved the stream-level side data, e.g. the display matrix, from
83
+ // AVStream to AVCodecParameters.coded_side_data.
84
+ #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(60, 31, 100)
85
+ #define FFMPEG_HAS_CODED_SIDE_DATA 1
86
+ #else
87
+ #define FFMPEG_HAS_CODED_SIDE_DATA 0
88
+ #endif
89
+
90
+ namespace facebook::torchcodec {
91
+
92
+ // Mirrors cudaVideoSurfaceFormat. Needed here because we don't want to include
93
+ // the CUDA headers in this file, and it is necessary for
94
+ // ffmpeg-version-dependent helpers like nvdec_pix_fmt() and
95
+ // is_nvdec_16bit_pix_fmt().
96
+ enum class NvdecSurface {
97
+ NV12,
98
+ P016,
99
+ YUV444,
100
+ YUV444_16Bit,
101
+ };
102
+
103
+ AVPixelFormat nvdec_pix_fmt(NvdecSurface surface, int bit_depth);
104
+
105
+ bool is_nvdec_16bit_pix_fmt(int format);
106
+
107
+ OutputDtype resolve_output_dtype(
108
+ OutputDtypeConfig output_dtype_config,
109
+ AVPixelFormat pix_fmt);
110
+
111
+ // FFMPEG uses special delete functions for some structures. These template
112
+ // functions are used to pass into unique_ptr as custom deleters so we can
113
+ // wrap FFMPEG structs with unique_ptrs for ease of use.
114
+ template <typename T, typename R, R (*Fn)(T**)>
115
+ struct Deleterp {
116
+ inline void operator()(T* p) const {
117
+ if (p) {
118
+ Fn(&p);
119
+ }
120
+ }
121
+ };
122
+
123
+ template <typename T, typename R, R (*Fn)(void*)>
124
+ struct Deleterv {
125
+ inline void operator()(T* p) const {
126
+ if (p) {
127
+ Fn(&p);
128
+ }
129
+ }
130
+ };
131
+
132
+ template <typename T, typename R, R (*Fn)(T*)>
133
+ struct Deleter {
134
+ inline void operator()(T* p) const {
135
+ if (p) {
136
+ Fn(p);
137
+ }
138
+ }
139
+ };
140
+
141
+ // Unique pointers for FFMPEG structures.
142
+ using UniqueDecodingAVFormatContext = std::unique_ptr<
143
+ AVFormatContext,
144
+ Deleterp<AVFormatContext, void, avformat_close_input>>;
145
+ using UniqueEncodingAVFormatContext = std::unique_ptr<
146
+ AVFormatContext,
147
+ Deleter<AVFormatContext, void, avformat_free_context>>;
148
+ using UniqueAVCodecContext = std::unique_ptr<
149
+ AVCodecContext,
150
+ Deleterp<AVCodecContext, void, avcodec_free_context>>;
151
+ using UniqueAVCodecParameters = std::unique_ptr<
152
+ AVCodecParameters,
153
+ Deleterp<AVCodecParameters, void, avcodec_parameters_free>>;
154
+ using SharedAVCodecContext = std::shared_ptr<AVCodecContext>;
155
+
156
+ // create SharedAVCodecContext with custom deleter
157
+ inline SharedAVCodecContext make_shared_av_codec_context(AVCodecContext* ctx) {
158
+ return SharedAVCodecContext(
159
+ ctx, Deleterp<AVCodecContext, void, avcodec_free_context>{});
160
+ }
161
+
162
+ using UniqueAVFrame =
163
+ std::unique_ptr<AVFrame, Deleterp<AVFrame, void, av_frame_free>>;
164
+ using UniqueAVPacket =
165
+ std::unique_ptr<AVPacket, Deleterp<AVPacket, void, av_packet_free>>;
166
+ using UniqueAVFilterGraph = std::unique_ptr<
167
+ AVFilterGraph,
168
+ Deleterp<AVFilterGraph, void, avfilter_graph_free>>;
169
+ using UniqueAVFilterInOut = std::unique_ptr<
170
+ AVFilterInOut,
171
+ Deleterp<AVFilterInOut, void, avfilter_inout_free>>;
172
+ using UniqueAVIOContext = std::
173
+ unique_ptr<AVIOContext, Deleterp<AVIOContext, void, avio_context_free>>;
174
+ using UniqueSwsContext =
175
+ std::unique_ptr<SwsContext, Deleter<SwsContext, void, sws_freeContext>>;
176
+ using UniqueSwrContext =
177
+ std::unique_ptr<SwrContext, Deleterp<SwrContext, void, swr_free>>;
178
+ using UniqueAVAudioFifo = std::
179
+ unique_ptr<AVAudioFifo, Deleter<AVAudioFifo, void, av_audio_fifo_free>>;
180
+ using UniqueAVBSFContext =
181
+ std::unique_ptr<AVBSFContext, Deleterp<AVBSFContext, void, av_bsf_free>>;
182
+ using UniqueAVBufferRef =
183
+ std::unique_ptr<AVBufferRef, Deleterp<AVBufferRef, void, av_buffer_unref>>;
184
+ using UniqueAVBufferSrcParameters = std::unique_ptr<
185
+ AVBufferSrcParameters,
186
+ Deleterv<AVBufferSrcParameters, void, av_freep>>;
187
+
188
+ // Wrapper class for AVDictionary, similar to unique_ptr, to support FFmpeg's
189
+ // functions that require a double-pointer to AVDictionary, such as av_dict_set.
190
+ // https://ffmpeg.org/doxygen/trunk/group__lavu__dict.html#ga8d9c2de72b310cef8e6a28c9cd3acbbe
191
+ class UniqueAVDictionary {
192
+ private:
193
+ AVDictionary* dict_ = nullptr;
194
+
195
+ public:
196
+ UniqueAVDictionary() = default;
197
+
198
+ ~UniqueAVDictionary() {
199
+ if (dict_) {
200
+ av_dict_free(&dict_);
201
+ }
202
+ }
203
+
204
+ // Explicitly delete copy operator similar to unique_ptr
205
+ UniqueAVDictionary(const UniqueAVDictionary&) = delete;
206
+ UniqueAVDictionary& operator=(const UniqueAVDictionary&) = delete;
207
+ // Explicitly delete move operator, as it is not needed at this time.
208
+ UniqueAVDictionary(UniqueAVDictionary&&) = delete;
209
+ UniqueAVDictionary& operator=(UniqueAVDictionary&&) = delete;
210
+
211
+ // FFmpeg's AVDictionary functions require a AVDictionary** argument.
212
+ // However, unique_ptr's get() function returns a **temporary** pointer to the
213
+ // object, so we cannot get a pointer to the internal AVDictionary pointer.
214
+ // As a result, we implement getAddress() to return a pointer to the internal
215
+ // AVDictionary pointer.
216
+ AVDictionary** get_address() {
217
+ return &dict_;
218
+ }
219
+ };
220
+
221
+ // These 2 classes share the same underlying AVPacket object. They are meant to
222
+ // be used in tandem, like so:
223
+ //
224
+ // AutoAVPacket autoAVPacket; // <-- malloc for AVPacket happens here
225
+ // while(...){
226
+ // ReferenceAVPacket packet(autoAVPacket);
227
+ // av_read_frame(..., packet.get()); <-- av_packet_ref() called by FFmpeg
228
+ // } <-- av_packet_unref() called here
229
+ //
230
+ // This achieves a few desirable things:
231
+ // - Memory allocation of the underlying AVPacket happens only once, when
232
+ // autoAVPacket is created.
233
+ // - av_packet_free() is called when autoAVPacket gets out of scope
234
+ // - av_packet_unref() is automatically called when needed, i.e. at the end of
235
+ // each loop iteration (or when hitting break / continue). This prevents the
236
+ // risk of us forgetting to call it.
237
+ class AutoAVPacket {
238
+ friend class ReferenceAVPacket;
239
+
240
+ private:
241
+ AVPacket* av_packet_;
242
+
243
+ public:
244
+ AutoAVPacket();
245
+ AutoAVPacket(const AutoAVPacket& other) = delete;
246
+ AutoAVPacket& operator=(const AutoAVPacket& other) = delete;
247
+ ~AutoAVPacket();
248
+ };
249
+
250
+ class ReferenceAVPacket {
251
+ private:
252
+ AVPacket* av_packet_;
253
+
254
+ public:
255
+ explicit ReferenceAVPacket(AutoAVPacket& shared);
256
+ ReferenceAVPacket(const ReferenceAVPacket& other) = delete;
257
+ ReferenceAVPacket& operator=(const ReferenceAVPacket& other) = delete;
258
+ ~ReferenceAVPacket();
259
+ AVPacket* get();
260
+ AVPacket& operator*();
261
+ AVPacket* operator->();
262
+ };
263
+
264
+ // av_find_best_stream is not const-correct before commit:
265
+ // https://github.com/FFmpeg/FFmpeg/commit/46dac8cf3d250184ab4247809bc03f60e14f4c0c
266
+ // which was released in FFMPEG version=5.0.3
267
+ // with libavcodec's version=59.18.100
268
+ // (https://www.ffmpeg.org/olddownload.html).
269
+ // Note that the alias is so-named so that it is only used when interacting with
270
+ // av_find_best_stream(). It is not needed elsewhere.
271
+ #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 18, 100)
272
+ using AVCodecOnlyUseForCallingAVFindBestStream = AVCodec*;
273
+ #else
274
+ using AVCodecOnlyUseForCallingAVFindBestStream = const AVCodec*;
275
+ #endif
276
+
277
+ AVCodecOnlyUseForCallingAVFindBestStream
278
+ make_av_codec_only_use_for_calling_av_find_best_stream(const AVCodec* codec);
279
+
280
+ // Success code from FFMPEG is just a 0. We define it to make the code more
281
+ // readable.
282
+ const int AVSUCCESS = 0;
283
+
284
+ // Returns the FFMPEG error as a string using the provided `errorCode`.
285
+ std::string get_ffmpeg_error_string_from_error_code(int error_code);
286
+
287
+ // Returns duration from the frame. Abstracted into a function because the
288
+ // struct member representing duration has changed across the versions we
289
+ // support.
290
+ int64_t get_duration(const AVFrame& frame);
291
+ void set_duration(AVFrame& frame, int64_t duration);
292
+
293
+ // pts accessors that fall back to dts when pts is unset (INT64_MIN). See the
294
+ // definitions for details.
295
+ int64_t get_pts_or_dts(ReferenceAVPacket& packet);
296
+ int64_t get_pts_or_dts(const AVFrame& av_frame);
297
+
298
+ // Fills in a missing pts from the end of the previous frame if missing, and
299
+ // derives the duration from nb_samples, like the ffmpeg CLI does in
300
+ // audio_ts_process():
301
+ // https://github.com/FFmpeg/FFmpeg/blob/d244d438c372b76d825be4527fccfd162429010a/fftools/ffmpeg_dec.c#L246-L281
302
+ // It must see every frame the decoder outputs, in order, and be reset whenever
303
+ // the decoder is flushed.
304
+ class AudioPtsExtrapolator {
305
+ public:
306
+ AudioPtsExtrapolator() = default;
307
+
308
+ explicit AudioPtsExtrapolator(AVRational time_base) : time_base_(time_base) {}
309
+
310
+ void process(AVFrame& av_frame);
311
+
312
+ void reset() {
313
+ next_frame_start_ = INT64_MIN;
314
+ }
315
+
316
+ private:
317
+ // The stream time base, in which frame pts and durations are expressed.
318
+ AVRational time_base_ = {};
319
+ // Where we expect the next frame to start, in samples.
320
+ // INT64_MIN when unknown, e.g. after a seek: we then leave a missing pts
321
+ // unset rather than guessing 0 like the CLI does.
322
+ // We count in samples rather than in the stream time base because the latter
323
+ // may not represent a frame's duration exactly (e.g. MKV's 1ms): adding up
324
+ // rounded durations would make the guessed pts drift further off with every
325
+ // frame.
326
+ int64_t next_frame_start_ = INT64_MIN;
327
+ int sample_rate_ = 0;
328
+ };
329
+
330
+ const int* get_supported_sample_rates(const AVCodec& av_codec);
331
+ const AVSampleFormat* get_supported_output_sample_formats(
332
+ const AVCodec& av_codec);
333
+ const AVPixelFormat* get_supported_pixel_formats(const AVCodec& av_codec);
334
+
335
+ int get_num_channels(const AVFrame& av_frame);
336
+ int get_num_channels(const SharedAVCodecContext& av_codec_context);
337
+ int get_num_channels(const AVCodecParameters* codecpar);
338
+
339
+ void set_default_channel_layout(
340
+ UniqueAVCodecContext& av_codec_context,
341
+ int num_channels);
342
+
343
+ void set_default_channel_layout(AVFrame& av_frame, int num_channels);
344
+
345
+ void validate_num_channels(const AVCodec& av_codec, int num_channels);
346
+
347
+ void set_channel_layout(
348
+ AVFrame& dst_av_frame,
349
+ const AVFrame& src_av_frame,
350
+ int desired_num_channels);
351
+
352
+ UniqueAVFrame allocate_av_frame(
353
+ int num_samples,
354
+ int sample_rate,
355
+ int num_channels,
356
+ AVSampleFormat sample_format);
357
+
358
+ // How a channel layout is spelled, which changed in FFmpeg 5.
359
+ #if FFMPEG_HAS_CH_LAYOUT
360
+ using SwrChannelLayout = AVChannelLayout;
361
+ #else
362
+ using SwrChannelLayout = int64_t;
363
+ #endif
364
+
365
+ SwrContext* create_swr_context(
366
+ AVSampleFormat src_sample_format,
367
+ AVSampleFormat desired_sample_format,
368
+ int src_sample_rate,
369
+ int desired_sample_rate,
370
+ const AVFrame& src_av_frame,
371
+ int desired_num_channels);
372
+
373
+ // Same, for callers that have samples rather than an AVFrame, and so only know
374
+ // how many channels there are. Both layouts are the default one for their
375
+ // channel count, which is what the AVFrame overload also falls back to when the
376
+ // count changes.
377
+ SwrContext* create_swr_context(
378
+ AVSampleFormat src_sample_format,
379
+ AVSampleFormat desired_sample_format,
380
+ int src_sample_rate,
381
+ int desired_sample_rate,
382
+ int src_num_channels,
383
+ int desired_num_channels);
384
+
385
+ // Upper bound on the number of samples swr_convert() can emit for
386
+ // num_src_samples of input, including whatever it still holds buffered. It is
387
+ // only a bound: narrow the output down to what swr_convert() returned.
388
+ int64_t get_swr_output_num_samples_bound(
389
+ const UniqueSwrContext& swr_context,
390
+ int num_src_samples,
391
+ int src_sample_rate,
392
+ int out_sample_rate);
393
+
394
+ // Converts, if needed:
395
+ // - sample format
396
+ // - sample rate
397
+ // - number of channels.
398
+ // createSwrContext must have been previously called with matching parameters.
399
+ UniqueAVFrame convert_audio_av_frame_samples(
400
+ const UniqueSwrContext& swr_context,
401
+ const AVFrame& src_av_frame,
402
+ AVSampleFormat desired_sample_format,
403
+ int desired_sample_rate,
404
+ int desired_num_channels,
405
+ int num_samples_to_skip = 0);
406
+
407
+ // Returns true if sws_scale can handle unaligned data.
408
+ bool can_sws_scale_handle_unaligned_data();
409
+
410
+ void set_ffmpeg_log_level();
411
+
412
+ void forbid_nested_protocols(AVFormatContext* format_context);
413
+
414
+ // These signatures are defined by FFmpeg.
415
+ using AVIOReadFunction = int (*)(void*, uint8_t*, int);
416
+ using AVIOWriteFunction = int (*)(void*, const uint8_t*, int); // FFmpeg >= 7
417
+ using AVIOWriteFunctionOld = int (*)(void*, uint8_t*, int); // FFmpeg < 7
418
+ using AVIOSeekFunction = int64_t (*)(void*, int64_t, int);
419
+
420
+ AVIOContext* avio_alloc_context(
421
+ uint8_t* buffer,
422
+ int buffer_size,
423
+ int write_flag,
424
+ void* opaque,
425
+ AVIOReadFunction read_packet,
426
+ AVIOWriteFunction write_packet,
427
+ AVIOSeekFunction seek);
428
+
429
+ double pts_to_seconds(int64_t pts, const AVRational& time_base);
430
+ int64_t seconds_to_closest_pts(double seconds, const AVRational& time_base);
431
+ int64_t compute_safe_duration(
432
+ const AVRational& frame_rate,
433
+ const AVRational& time_base);
434
+
435
+ // Extracts the rotation angle in degrees from the stream's display matrix
436
+ // side data. The display matrix is used to specify how the video should be
437
+ // rotated for correct display.
438
+ std::optional<double> get_rotation_from_stream(const AVStream* av_stream);
439
+
440
+ // Same, from a frame's own display matrix side data.
441
+ std::optional<double> get_rotation_from_frame(const AVFrame& av_frame);
442
+
443
+ // Same, from a display matrix. nullopt for a null or invalid matrix.
444
+ std::optional<double> get_rotation_from_display_matrix(
445
+ const int32_t* display_matrix);
446
+
447
+ // The stream's raw display matrix, or nullptr when it has none. Points into the
448
+ // stream's side data, so it lives as long as the stream does.
449
+ const int32_t* get_display_matrix_from_stream(const AVStream* av_stream);
450
+
451
+ // FF_PROFILE_UNKNOWN, AV_PROFILE_UNKNOWN and AV_LEVEL_UNKNOWN: they are all
452
+ // -99, but which of these names exist depends on the FFmpeg version.
453
+ constexpr int kUnknownProfileOrLevel = -99;
454
+
455
+ // The frame rate the codec reports, or {0, 1} when it doesn't report one.
456
+ // Always {0, 1} before FFmpeg 6.1, which added AVCodecParameters.framerate.
457
+ AVRational get_framerate(const AVCodecParameters& codecpar);
458
+
459
+ // FFmpeg's description of the channel layout, e.g. "stereo", or nullopt when
460
+ // there are no channels.
461
+ std::optional<std::string> get_channel_layout_name(
462
+ const AVCodecParameters& codecpar);
463
+
464
+ // "progressive", "tt", "bb", "tb" or "bt", which are the names ffprobe uses, or
465
+ // nullptr when the field order is unknown. FFmpeg has no function for these.
466
+ const char* get_field_order_name(AVFieldOrder field_order);
467
+
468
+ // The inverses of the functions above, for building AVCodecParameters. They
469
+ // raise on a name FFmpeg doesn't know, and on a value this FFmpeg version can't
470
+ // hold.
471
+ void set_framerate(AVCodecParameters& codecpar, const AVRational& framerate);
472
+ void set_channel_layout(AVCodecParameters& codecpar, const std::string& name);
473
+ AVFieldOrder get_field_order_from_name(const std::string& name);
474
+ AVPacketSideDataType get_packet_side_data_type_from_name(
475
+ const std::string& name);
476
+
477
+ // Makes `av_frame` carry `display_matrix` (or no display matrix at all, for
478
+ // nullptr), replacing whatever it had.
479
+ void set_display_matrix_on_frame(
480
+ AVFrame& av_frame,
481
+ const int32_t* display_matrix);
482
+
483
+ AVFilterContext* create_av_filter_context_with_options(
484
+ AVFilterGraph* filter_graph,
485
+ const AVFilter* buffer,
486
+ const enum AVPixelFormat output_format);
487
+
488
+ struct SwsConfig {
489
+ int input_width = 0;
490
+ int input_height = 0;
491
+ AVPixelFormat input_format = AV_PIX_FMT_NONE;
492
+ AVColorSpace input_colorspace = AVCOL_SPC_UNSPECIFIED;
493
+ AVColorRange input_color_range = AVCOL_RANGE_UNSPECIFIED;
494
+ int output_width = 0;
495
+ int output_height = 0;
496
+ AVPixelFormat output_format = AV_PIX_FMT_NONE;
497
+ AVColorRange output_color_range = AVCOL_RANGE_UNSPECIFIED;
498
+
499
+ bool operator==(const SwsConfig& other) const;
500
+ bool operator!=(const SwsConfig& other) const;
501
+ };
502
+
503
+ // Utility functions for swscale context management
504
+ UniqueSwsContext create_sws_context(const SwsConfig& sws_config, int sws_flags);
505
+
506
+ } // namespace facebook::torchcodec
@@ -0,0 +1,78 @@
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 "FileIO.h"
8
+
9
+ #include <filesystem>
10
+ #include "StableABICompat.h"
11
+
12
+ namespace facebook::torchcodec {
13
+
14
+ FileIO::FileIO(const std::string& path, Mode mode) : mode_(mode) {
15
+ if (mode_ == Mode::Read) {
16
+ file_.open(path, std::ios::in | std::ios::binary);
17
+ STD_TORCH_CHECK(file_.is_open(), "Failed to open file for reading: ", path);
18
+ try {
19
+ file_size_ = static_cast<int64_t>(std::filesystem::file_size(path));
20
+ } catch (const std::filesystem::filesystem_error& e) {
21
+ STD_TORCH_CHECK(
22
+ false, "Failed to get file size for: ", path, ". Error: ", e.what());
23
+ }
24
+ } else {
25
+ file_.open(path, std::ios::out | std::ios::binary | std::ios::trunc);
26
+ STD_TORCH_CHECK(file_.is_open(), "Failed to open file for writing: ", path);
27
+ }
28
+ }
29
+
30
+ int FileIO::read(uint8_t* buf, int size) {
31
+ STD_TORCH_CHECK(mode_ == Mode::Read, "FileIO was not opened for reading");
32
+ file_.read(reinterpret_cast<char*>(buf), size);
33
+ auto bytes_read = static_cast<int>(file_.gcount());
34
+ if (bytes_read == 0) {
35
+ return -1;
36
+ }
37
+ return bytes_read;
38
+ }
39
+
40
+ int FileIO::write(const uint8_t* buf, int size) {
41
+ STD_TORCH_CHECK(mode_ == Mode::Write, "FileIO was not opened for writing");
42
+ file_.write(reinterpret_cast<const char*>(buf), size);
43
+ STD_TORCH_CHECK(!file_.fail(), "Failed to write to file");
44
+ return size;
45
+ }
46
+
47
+ int64_t FileIO::seek(int64_t offset, int whence) {
48
+ std::ios_base::seekdir dir;
49
+ switch (whence) {
50
+ case SEEK_SET:
51
+ dir = std::ios::beg;
52
+ break;
53
+ case SEEK_CUR:
54
+ dir = std::ios::cur;
55
+ break;
56
+ case SEEK_END:
57
+ dir = std::ios::end;
58
+ break;
59
+ default:
60
+ return -1;
61
+ }
62
+ if (mode_ == Mode::Read) {
63
+ file_.seekg(offset, dir);
64
+ STD_TORCH_CHECK(!file_.fail(), "Failed to seek in file");
65
+ return static_cast<int64_t>(file_.tellg());
66
+ }
67
+ file_.seekp(offset, dir);
68
+ STD_TORCH_CHECK(!file_.fail(), "Failed to seek in file");
69
+ return static_cast<int64_t>(file_.tellp());
70
+ }
71
+
72
+ int64_t FileIO::get_size() {
73
+ STD_TORCH_CHECK(
74
+ mode_ == Mode::Read, "get_size() is only supported when reading");
75
+ return file_size_;
76
+ }
77
+
78
+ } // namespace facebook::torchcodec
@@ -0,0 +1,34 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <fstream>
10
+ #include <string>
11
+ #include "IOInterface.h"
12
+
13
+ namespace facebook::torchcodec {
14
+
15
+ // file I/O on disk, backed by std::fstream. Opened for either
16
+ // reading or writing. Reading is used by consumers that parse bytes themselves
17
+ // (e.g. WavDecoder); writing is used by the image encoders.
18
+ class FileIO : public IOInterface {
19
+ public:
20
+ enum class Mode { Read, Write };
21
+ FileIO(const std::string& path, Mode mode);
22
+
23
+ int read(uint8_t* buf, int size) override;
24
+ int write(const uint8_t* buf, int size) override;
25
+ int64_t seek(int64_t offset, int whence) override;
26
+ int64_t get_size() override;
27
+
28
+ private:
29
+ std::fstream file_;
30
+ Mode mode_;
31
+ int64_t file_size_ = 0;
32
+ };
33
+
34
+ } // namespace facebook::torchcodec
@@ -0,0 +1,76 @@
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 "FileLikeIO.h"
8
+
9
+ #include <algorithm>
10
+ #include <string>
11
+
12
+ #include "StableABICompat.h"
13
+
14
+ namespace facebook::torchcodec {
15
+
16
+ FileLikeIO::FileLikeIO(const FileLikeCallbacks& callbacks)
17
+ : callbacks_(callbacks) {}
18
+
19
+ FileLikeIO::~FileLikeIO() {
20
+ callbacks_.release(callbacks_.id_);
21
+ }
22
+
23
+ void FileLikeIO::check_callback_result(int64_t result, const char* method) {
24
+ if (result != kFileLikeCallbackError) {
25
+ return;
26
+ }
27
+ std::string message(1024, '\0');
28
+ int64_t length = callbacks_.get_error(
29
+ callbacks_.id_, message.data(), static_cast<int64_t>(message.size()));
30
+ // get_error() never returns more than buf_len, but if it ever raised, ctypes
31
+ // would hand us a garbage length.
32
+ length = std::clamp<int64_t>(length, 0, message.size());
33
+ message.resize(static_cast<size_t>(length));
34
+ STD_TORCH_CHECK(
35
+ false,
36
+ "Calling the ",
37
+ method,
38
+ "() method of the file-like object raised an exception: ",
39
+ message);
40
+ }
41
+
42
+ int FileLikeIO::read(uint8_t* buf, int size) {
43
+ // The Python side fills buf unless it reaches EOF.
44
+ int64_t num_bytes_read = callbacks_.read(callbacks_.id_, buf, size);
45
+ check_callback_result(num_bytes_read, "read");
46
+ return num_bytes_read == 0 ? -1 : static_cast<int>(num_bytes_read);
47
+ }
48
+
49
+ int FileLikeIO::write(const uint8_t* buf, int size) {
50
+ int64_t result = callbacks_.write(callbacks_.id_, buf, size);
51
+ check_callback_result(result, "write");
52
+ return static_cast<int>(result);
53
+ }
54
+
55
+ int64_t FileLikeIO::seek(int64_t offset, int whence) {
56
+ int64_t result = callbacks_.seek(callbacks_.id_, offset, whence);
57
+ check_callback_result(result, "seek");
58
+ return result;
59
+ }
60
+
61
+ int64_t FileLikeIO::get_size() {
62
+ // Size of file-like is typically unknown, since the data is potentially
63
+ // streaming.
64
+ return INT64_MAX;
65
+ }
66
+
67
+ std::unique_ptr<IOInterface> adopt_file_like_context(
68
+ int64_t file_like_context) {
69
+ auto* callbacks = reinterpret_cast<const FileLikeCallbacks*>(
70
+ static_cast<intptr_t>(file_like_context));
71
+ STD_TORCH_CHECK(
72
+ callbacks != nullptr, "file_like_context must be a valid pointer");
73
+ return std::make_unique<FileLikeIO>(*callbacks);
74
+ }
75
+
76
+ } // namespace facebook::torchcodec