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,358 @@
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 "PacketDecoder.h"
8
+
9
+ #include "AudioCommon.h"
10
+
11
+ #include <algorithm>
12
+ #include <cstring>
13
+
14
+ namespace facebook::torchcodec {
15
+
16
+ namespace {
17
+ SharedAVCodecContext open_codec_context(
18
+ const AVCodecParameters& codecpar,
19
+ const AVRational& time_base,
20
+ const AVCodec* av_codec,
21
+ DeviceInterface* device_interface,
22
+ std::optional<int> thread_count) {
23
+ AVCodecContext* raw_codec_context = avcodec_alloc_context3(av_codec);
24
+ STD_TORCH_CHECK(
25
+ raw_codec_context != nullptr, "Failed to allocate codec context");
26
+ SharedAVCodecContext codec_context =
27
+ make_shared_av_codec_context(raw_codec_context);
28
+
29
+ int ret = avcodec_parameters_to_context(codec_context.get(), &codecpar);
30
+ STD_TORCH_CHECK(ret == AVSUCCESS, "avcodec_parameters_to_context failed");
31
+
32
+ codec_context->thread_count = thread_count.value_or(0);
33
+ codec_context->pkt_timebase = time_base;
34
+
35
+ // We must register the hardware device context with the codec context before
36
+ // calling avcodec_open2(). Otherwise, decoding will happen on the CPU and not
37
+ // the hardware device.
38
+ device_interface->register_hardware_device_with_codec(codec_context.get());
39
+ ret = avcodec_open2(codec_context.get(), av_codec, nullptr);
40
+ STD_TORCH_CHECK(
41
+ ret >= AVSUCCESS, get_ffmpeg_error_string_from_error_code(ret));
42
+
43
+ codec_context->time_base = time_base;
44
+ return codec_context;
45
+ }
46
+
47
+ const AVCodec* find_decoder(
48
+ const AVCodecParameters& codecpar,
49
+ DeviceInterface* device_interface) {
50
+ const AVCodec* av_codec = avcodec_find_decoder(codecpar.codec_id);
51
+ STD_TORCH_CHECK(av_codec != nullptr, "Codec not found");
52
+ if (codecpar.codec_type == AVMEDIA_TYPE_VIDEO) {
53
+ av_codec =
54
+ device_interface->find_codec(codecpar.codec_id).value_or(av_codec);
55
+ }
56
+ return av_codec;
57
+ }
58
+ } // namespace
59
+
60
+ SharedAVCodecContext create_and_open_codec_context(
61
+ const CodecParameters& codec_parameters,
62
+ const AVCodec* av_codec,
63
+ DeviceInterface* device_interface,
64
+ std::optional<int> thread_count) {
65
+ return open_codec_context(
66
+ *codec_parameters.codecpar,
67
+ codec_parameters.time_base,
68
+ av_codec,
69
+ device_interface,
70
+ thread_count);
71
+ }
72
+
73
+ SharedAVCodecContext create_and_open_codec_context(
74
+ AVStream* stream,
75
+ const AVCodec* av_codec,
76
+ DeviceInterface* device_interface,
77
+ std::optional<int> thread_count) {
78
+ return open_codec_context(
79
+ *stream->codecpar,
80
+ stream->time_base,
81
+ av_codec,
82
+ device_interface,
83
+ thread_count);
84
+ }
85
+
86
+ PacketDecoder::PacketDecoder(
87
+ const CodecParameters& codec_parameters,
88
+ const StableDevice& device,
89
+ std::optional<int> ffmpeg_thread_count) {
90
+ const AVCodecParameters& codecpar = *codec_parameters.codecpar;
91
+ media_type_ = codecpar.codec_type;
92
+
93
+ bool is_audio = media_type_ == AVMEDIA_TYPE_AUDIO;
94
+ STD_TORCH_CHECK(
95
+ !is_audio || device.type() == kStableCPU,
96
+ "Audio can only be decoded on the CPU.");
97
+
98
+ device_interface_ = create_device_interface(device);
99
+ STD_TORCH_CHECK(
100
+ device_interface_ != nullptr,
101
+ "Failed to create device interface. This should never happen, please report.");
102
+
103
+ time_base_ = codec_parameters.time_base;
104
+
105
+ is_mpeg_ps_ = codec_parameters.container_format != nullptr &&
106
+ std::string_view(codec_parameters.container_format->name) == "mpeg";
107
+
108
+ if (is_audio) {
109
+ // Audio codecs are hardcoded to a single FFmpeg thread, see
110
+ // https://github.com/pytorch/torchcodec/issues/1253.
111
+ ffmpeg_thread_count = 1;
112
+ audio_pts_extrapolator_ = AudioPtsExtrapolator(time_base_);
113
+ } else {
114
+ display_matrix_ = codec_parameters.display_matrix;
115
+ }
116
+
117
+ const AVCodec* av_codec = find_decoder(codecpar, device_interface_.get());
118
+ codec_context_ = create_and_open_codec_context(
119
+ codec_parameters, av_codec, device_interface_.get(), ffmpeg_thread_count);
120
+ device_interface_->initialize(codec_context_);
121
+
122
+ if (is_audio) {
123
+ // Nothing else to set up: unlike video, we hand out the samples in the
124
+ // codec's own format, so no conversion state is needed here. Note we
125
+ // deliberately do NOT set request_sample_fmt: what SingleStreamDecoder
126
+ // asks for (FLTP) is an optimization for its own conversion, and here it
127
+ // would hide what the codec natively produces.
128
+ return;
129
+ }
130
+
131
+ const AVPixFmtDescriptor* stream_desc =
132
+ av_pix_fmt_desc_get(codec_context_->pix_fmt);
133
+ int stream_bit_depth = stream_desc ? stream_desc->comp[0].depth : 8;
134
+
135
+ VideoStreamOptions options;
136
+ options.device = device;
137
+ // This is ugly: what we actually mean is "let the device interface decode
138
+ // into the native surface", which matters for NVDEC.
139
+ // TODO_API_BREAKDOWN CC P1: Find a cleaner way to express this?
140
+ options.output_dtype =
141
+ stream_bit_depth > 8 ? OutputDtype::FLOAT32 : OutputDtype::UINT8;
142
+
143
+ device_interface_->initialize_video_decoding(codec_parameters, options);
144
+ }
145
+
146
+ int PacketDecoder::send_packet(const AVPacket& packet) {
147
+ int status = device_interface_->send_packet(packet);
148
+
149
+ if (status == AVERROR_INVALIDDATA && packet_data_may_be_misaligned_) {
150
+ // Seeking in an MPEG program stream lands on a container-level byte offset,
151
+ // so the parser resumes mid-frame and the packets it rebuilds are garbage
152
+ // until it resyncs. Report those as consumed rather than as a corrupt file:
153
+ // dropping them is exactly what resyncing means.
154
+ return AVSUCCESS;
155
+ }
156
+ if (status >= AVSUCCESS) {
157
+ // The decoder accepted a packet, so we're aligned again: from now on
158
+ // invalid data means the file is corrupt, and we want to report it.
159
+ packet_data_may_be_misaligned_ = false;
160
+ }
161
+ return status;
162
+ }
163
+
164
+ int PacketDecoder::send_eof() {
165
+ return device_interface_->send_eof_packet();
166
+ }
167
+
168
+ void PacketDecoder::reset() {
169
+ device_interface_->flush();
170
+ audio_pts_extrapolator_.reset();
171
+ packet_data_may_be_misaligned_ = is_mpeg_ps_;
172
+ }
173
+
174
+ int PacketDecoder::receive_frame(UniqueAVFrame& av_frame) {
175
+ int status = device_interface_->receive_frame(av_frame);
176
+ if (status == AVSUCCESS) {
177
+ device_interface_->make_frame_standalone(av_frame);
178
+ if (media_type_ == AVMEDIA_TYPE_AUDIO) {
179
+ audio_pts_extrapolator_.process(*av_frame);
180
+ } else if (media_type_ == AVMEDIA_TYPE_VIDEO) {
181
+ // Attach a copy of the display matrix to the frame, so the ColorConverter
182
+ // can use it.
183
+ set_display_matrix_on_frame(
184
+ *av_frame, display_matrix_ ? display_matrix_->data() : nullptr);
185
+ }
186
+ }
187
+ return status;
188
+ }
189
+
190
+ namespace {
191
+ const AVPixFmtDescriptor* get_pix_fmt_desc(const AVFrame& av_frame) {
192
+ const AVPixFmtDescriptor* desc =
193
+ av_pix_fmt_desc_get(static_cast<AVPixelFormat>(av_frame.format));
194
+ STD_TORCH_CHECK(desc != nullptr, "Unknown pixel format on decoded frame");
195
+ return desc;
196
+ }
197
+
198
+ std::string get_pix_fmt_name(const AVFrame& av_frame) {
199
+ const char* name =
200
+ av_get_pix_fmt_name(static_cast<AVPixelFormat>(av_frame.format));
201
+ return name ? name : "unknown";
202
+ }
203
+ } // namespace
204
+
205
+ FrameMetadata get_frame_metadata(const AVFrame& av_frame) {
206
+ const AVPixFmtDescriptor* desc = get_pix_fmt_desc(av_frame);
207
+
208
+ FrameMetadata result;
209
+ result.pixel_format = static_cast<AVPixelFormat>(av_frame.format);
210
+ result.color_space = av_frame.colorspace;
211
+ result.color_range = av_frame.color_range;
212
+ result.color_primaries = av_frame.color_primaries;
213
+ result.color_transfer_characteristic = av_frame.color_trc;
214
+ result.bit_depth = desc->comp[0].depth;
215
+ result.width = av_frame.width;
216
+ result.height = av_frame.height;
217
+ result.rotation = get_rotation_from_frame(av_frame).value_or(0);
218
+ return result;
219
+ }
220
+
221
+ std::vector<torch::stable::Tensor> get_frame_planes(
222
+ const AVFrame& av_frame,
223
+ const StableDevice& device,
224
+ const torch::stable::Tensor& tensor_handle) {
225
+ const AVPixFmtDescriptor* desc = get_pix_fmt_desc(av_frame);
226
+ std::string fmt_name = get_pix_fmt_name(av_frame);
227
+
228
+ STD_TORCH_CHECK(
229
+ !(desc->flags &
230
+ (AV_PIX_FMT_FLAG_BITSTREAM | AV_PIX_FMT_FLAG_PAL |
231
+ AV_PIX_FMT_FLAG_FLOAT)),
232
+ "Cannot expose ",
233
+ fmt_name,
234
+ " as a view: sub-byte-packed, palettised, and float pixel formats need a copy.");
235
+ STD_TORCH_CHECK(
236
+ desc->nb_components >= 1 && desc->nb_components <= 4,
237
+ fmt_name,
238
+ " has an unsupported number of components.");
239
+
240
+ std::vector<torch::stable::Tensor> planes;
241
+ for (int c = 0; c < desc->nb_components; ++c) {
242
+ const AVComponentDescriptor& comp = desc->comp[c];
243
+ int64_t bytes_per_sample = (comp.depth > 8) ? 2 : 1;
244
+ int64_t linesize = av_frame.linesize[comp.plane];
245
+ STD_TORCH_CHECK(
246
+ comp.depth <= 16 && linesize > 0 && comp.step % bytes_per_sample == 0 &&
247
+ linesize % bytes_per_sample == 0,
248
+ "Cannot expose component ",
249
+ c,
250
+ " of ",
251
+ fmt_name,
252
+ " as a view: its samples aren't a whole number of bytes, or the frame "
253
+ "is stored bottom-up (negative line size).");
254
+
255
+ // Each plan is output as a 2D tensor. Y is full size while U/V (the chroma)
256
+ // are potentially subsampled by 2.
257
+ // Only the chroma components are subsampled; luma and alpha are full size.
258
+ bool is_chroma = !(desc->flags & AV_PIX_FMT_FLAG_RGB) && (c == 1 || c == 2);
259
+ int64_t height = is_chroma
260
+ ? AV_CEIL_RSHIFT(av_frame.height, desc->log2_chroma_h)
261
+ : av_frame.height;
262
+ int64_t width = is_chroma
263
+ ? AV_CEIL_RSHIFT(av_frame.width, desc->log2_chroma_w)
264
+ : av_frame.width;
265
+
266
+ int64_t sizes[] = {height, width};
267
+ int64_t strides[] = {
268
+ linesize / bytes_per_sample, comp.step / bytes_per_sample};
269
+
270
+ // The planes are views on the AVFrame's data. The AVFrame and its data are
271
+ // owned by the tensor_handle. We want the planes to outlive the Python
272
+ // tensor handle (see test_planes_outlive_frame). So for each plane, we
273
+ // create a (shallow) copy of the tensor handle, and capture it in the
274
+ // plane's deleter. As long as a handle [copy] lives, the AVFrame and its
275
+ // data are alive.
276
+ torch::stable::Tensor handle_copy = tensor_handle;
277
+ planes.push_back(torch::stable::from_blob(
278
+ av_frame.data[comp.plane] + comp.offset,
279
+ {sizes, 2},
280
+ {strides, 2},
281
+ device,
282
+ (comp.depth > 8) ? kStableUInt16 : kStableUInt8,
283
+ [handle_copy](void*) {}));
284
+ }
285
+
286
+ return planes;
287
+ }
288
+
289
+ namespace {
290
+ // Scatters `num_channels`-interleaved samples into one contiguous row per
291
+ // channel. Templated on an integer of the right width rather than the actual
292
+ // sample type: we're only moving bytes around, so all that matters is size.
293
+ template <typename T>
294
+ void deinterleave(
295
+ const uint8_t* src,
296
+ uint8_t* dst,
297
+ int num_channels,
298
+ int num_samples) {
299
+ const T* in = reinterpret_cast<const T*>(src);
300
+ T* out = reinterpret_cast<T*>(dst);
301
+ for (int channel = 0; channel < num_channels; ++channel) {
302
+ T* row = out + static_cast<int64_t>(channel) * num_samples;
303
+ for (int sample = 0; sample < num_samples; ++sample) {
304
+ row[sample] = in[static_cast<int64_t>(sample) * num_channels + channel];
305
+ }
306
+ }
307
+ }
308
+ } // namespace
309
+
310
+ torch::stable::Tensor get_audio_samples(const AVFrame& av_frame) {
311
+ auto sample_format = static_cast<AVSampleFormat>(av_frame.format);
312
+ int num_channels = get_num_channels(av_frame);
313
+ int64_t num_samples = av_frame.nb_samples;
314
+
315
+ torch::stable::Tensor samples = torch::stable::empty(
316
+ {num_channels, num_samples}, sample_format_dtype(sample_format));
317
+ if (num_samples == 0) {
318
+ return samples;
319
+ }
320
+
321
+ int bytes_per_sample = av_get_bytes_per_sample(sample_format);
322
+ auto* dst = static_cast<uint8_t*>(samples.mutable_data_ptr());
323
+ int64_t bytes_per_channel = num_samples * bytes_per_sample;
324
+
325
+ if (av_sample_fmt_is_planar(sample_format)) {
326
+ for (int channel = 0; channel < num_channels; ++channel) {
327
+ // extended_data rather than data: the latter only holds
328
+ // AV_NUM_DATA_POINTERS (8) pointers, and we support more channels.
329
+ std::memcpy(
330
+ dst + channel * bytes_per_channel,
331
+ av_frame.extended_data[channel],
332
+ bytes_per_channel);
333
+ }
334
+ } else {
335
+ const uint8_t* src = av_frame.extended_data[0];
336
+ int num_samples_int = static_cast<int>(num_samples);
337
+ switch (bytes_per_sample) {
338
+ case 1:
339
+ deinterleave<uint8_t>(src, dst, num_channels, num_samples_int);
340
+ break;
341
+ case 2:
342
+ deinterleave<uint16_t>(src, dst, num_channels, num_samples_int);
343
+ break;
344
+ case 4:
345
+ deinterleave<uint32_t>(src, dst, num_channels, num_samples_int);
346
+ break;
347
+ case 8:
348
+ deinterleave<uint64_t>(src, dst, num_channels, num_samples_int);
349
+ break;
350
+ default:
351
+ STD_TORCH_CHECK(
352
+ false, "Unexpected sample width: ", bytes_per_sample, " bytes.");
353
+ }
354
+ }
355
+ return samples;
356
+ }
357
+
358
+ } // namespace facebook::torchcodec
@@ -0,0 +1,140 @@
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 <array>
10
+ #include <memory>
11
+ #include <optional>
12
+ #include <string>
13
+ #include <string_view>
14
+ #include <vector>
15
+
16
+ #include "CodecParameters.h"
17
+ #include "DeviceInterface.h"
18
+ #include "FFMPEGCommon.h"
19
+ #include "StableABICompat.h"
20
+
21
+ namespace facebook::torchcodec {
22
+
23
+ // Creates, configures and opens a codec context for `codec_parameters` using
24
+ // `av_codec`, registering the hardware device (if any) via `device_interface`.
25
+ SharedAVCodecContext create_and_open_codec_context(
26
+ const CodecParameters& codec_parameters,
27
+ const AVCodec* av_codec,
28
+ DeviceInterface* device_interface,
29
+ std::optional<int> thread_count);
30
+
31
+ // Same, for a demuxed stream. SingleStreamDecoder uses this overload and
32
+ // PacketDecoder the one above, so that they share the codec setup instead of
33
+ // duplicating it.
34
+ SharedAVCodecContext create_and_open_codec_context(
35
+ AVStream* stream,
36
+ const AVCodec* av_codec,
37
+ DeviceInterface* device_interface,
38
+ std::optional<int> thread_count);
39
+
40
+ // Decode building block: turns compressed packets into decoded frames - (YUV)
41
+ // pictures for a video stream, samples in the codec's own format for an audio
42
+ // one. Configured from a stream's CodecParameters; stateful. Not thread-safe.
43
+ class FORCE_PUBLIC_VISIBILITY PacketDecoder {
44
+ public:
45
+ explicit PacketDecoder(
46
+ const CodecParameters& codec_parameters,
47
+ const StableDevice& device = StableDevice(kStableCPU),
48
+ std::optional<int> ffmpeg_thread_count = std::nullopt);
49
+
50
+ // Feed one packet to the decoder. Borrows `packet` (does not take ownership).
51
+ int send_packet(const AVPacket& packet);
52
+ // Signal end-of-stream so the decoder flushes its remaining frames.
53
+ int send_eof();
54
+ // Pull one frame. Returns AVSUCCESS with `av_frame` filled, AVERROR(EAGAIN)
55
+ // if more input is needed, AVERROR_EOF at end, or a negative error code.
56
+ int receive_frame(UniqueAVFrame& av_frame);
57
+ // Drop the codec's buffered state (reference frames, in-flight frames) and
58
+ // start over. Needed after the demuxer seeked, and after send_eof(), which
59
+ // otherwise leaves the codec permanently in its drained state.
60
+ // This is called 'reset()' and not 'flush()', because this is publicly
61
+ // exposed flush() is slightly ambiguous and could mean 'flush the frames out
62
+ // of the decoder' rather than meaning 'flush the decoder internal state'.
63
+ void reset();
64
+
65
+ std::optional<torch::stable::Tensor> get_frame_storage(
66
+ const AVFrame& av_frame) const {
67
+ return device_interface_->get_frame_storage(av_frame);
68
+ }
69
+
70
+ // The stream time base, used to convert frame pts/duration to seconds.
71
+ AVRational time_base() const {
72
+ return time_base_;
73
+ }
74
+
75
+ AVMediaType media_type() const {
76
+ return media_type_;
77
+ }
78
+
79
+ private:
80
+ std::unique_ptr<DeviceInterface> device_interface_;
81
+ SharedAVCodecContext codec_context_;
82
+ AVRational time_base_ = {};
83
+ AVMediaType media_type_ = AVMEDIA_TYPE_VIDEO;
84
+ // Stamped onto every frame we hand out, so downstream stages can read the
85
+ // rotation off the frame itself instead of knowing about the stream.
86
+ std::optional<std::array<int32_t, 9>> display_matrix_;
87
+ // The MPEG-PS demuxer doesn't return proper packets just after a seek, so the
88
+ // first ones we're fed may not be decodable. See send_packet().
89
+ bool is_mpeg_ps_ = false;
90
+ bool packet_data_may_be_misaligned_ = false;
91
+ AudioPtsExtrapolator audio_pts_extrapolator_;
92
+ };
93
+
94
+ // How a decoded frame's samples are laid out and how they should be
95
+ // interpreted, before any color conversion.
96
+ struct FrameMetadata {
97
+ AVPixelFormat pixel_format = AV_PIX_FMT_NONE;
98
+ AVColorSpace color_space = AVCOL_SPC_UNSPECIFIED;
99
+ AVColorRange color_range = AVCOL_RANGE_UNSPECIFIED;
100
+ AVColorPrimaries color_primaries = AVCOL_PRI_UNSPECIFIED;
101
+ AVColorTransferCharacteristic color_transfer_characteristic =
102
+ AVCOL_TRC_UNSPECIFIED;
103
+ int64_t bit_depth = 8;
104
+ // The dimensions of the samples as they were decoded, i.e. before rotation.
105
+ int64_t width = 0;
106
+ int64_t height = 0;
107
+ // Degrees counter-clockwise needed to make the frame upright. 0 when the
108
+ // frame carries no display matrix.
109
+ double rotation = 0;
110
+ };
111
+
112
+ // Describes `av_frame` without touching its samples. Unlike get_frame_planes(),
113
+ // this works for every pixel format, so callers can ask what a frame is before
114
+ // asking for views they may not be able to get.
115
+ FORCE_PUBLIC_VISIBILITY FrameMetadata
116
+ get_frame_metadata(const AVFrame& av_frame);
117
+
118
+ // A decoded frame's own samples, before any color conversion: one view per
119
+ // component, in the frame's native order: (Y, U, V) for YUV, (R, G, B) for RGB
120
+ // codecs, (Y,) for grayscale, plus a trailing alpha view when the format has
121
+ // one.
122
+ FORCE_PUBLIC_VISIBILITY std::vector<torch::stable::Tensor> get_frame_planes(
123
+ const AVFrame& av_frame,
124
+ const StableDevice& device,
125
+ const torch::stable::Tensor& tensor_handle);
126
+
127
+ // A decoded audio frame's samples as a contiguous [num_channels, num_samples]
128
+ // tensor whose dtype is the frame's own sample type: uint8 for u8, int16 for
129
+ // s16, float32 for flt, and so on, planar or not. This is a copy rather than a
130
+ // view: planar formats put each channel in its own allocation and packed ones
131
+ // interleave them, so neither is a [C, N] tensor as it stands. An audio frame
132
+ // is a few kB, so normalizing here buys a uniform layout for the price of a
133
+ // memcpy - and it means a converter can treat the result as planar-of-dtype.
134
+ // Copying is also what lets the samples be handed out as a plain tensor instead
135
+ // of an opaque handle the way a video frame is, so nothing has to be kept alive
136
+ // to keep them readable.
137
+ FORCE_PUBLIC_VISIBILITY torch::stable::Tensor get_audio_samples(
138
+ const AVFrame& av_frame);
139
+
140
+ } // namespace facebook::torchcodec