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,1856 @@
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 "SingleStreamDecoder.h"
8
+ #include <algorithm>
9
+ #include <cmath>
10
+ #include <cstdint>
11
+ #include <cstdio>
12
+ #include <iostream>
13
+ #include <limits>
14
+ #include <numeric>
15
+ #include <sstream>
16
+ #include <string_view>
17
+ #include "Demuxer.h"
18
+ #include "Metadata.h"
19
+ #include "PacketDecoder.h"
20
+ #include "StableABICompat.h"
21
+
22
+ extern "C" {
23
+ #include <libavutil/pixdesc.h>
24
+ }
25
+
26
+ namespace facebook::torchcodec {
27
+
28
+ // --------------------------------------------------------------------------
29
+ // CONSTRUCTORS, INITIALIZATION, DESTRUCTORS
30
+ // --------------------------------------------------------------------------
31
+
32
+ SingleStreamDecoder::SingleStreamDecoder(
33
+ const std::string& video_file_path,
34
+ SeekMode seek_mode)
35
+ : seek_mode_(seek_mode) {
36
+ set_ffmpeg_log_level();
37
+
38
+ AVFormatContext* raw_context = nullptr;
39
+ int status = avformat_open_input(
40
+ &raw_context, video_file_path.c_str(), nullptr, nullptr);
41
+ STD_TORCH_CHECK(
42
+ status == 0,
43
+ "Could not open input file: " + video_file_path + " " +
44
+ get_ffmpeg_error_string_from_error_code(status));
45
+ STD_TORCH_CHECK(raw_context != nullptr, "Failed to allocate AVFormatContext");
46
+ format_context_.reset(raw_context);
47
+
48
+ initialize_decoder();
49
+ }
50
+
51
+ SingleStreamDecoder::SingleStreamDecoder(
52
+ std::unique_ptr<AVIOContextHolder> context,
53
+ SeekMode seek_mode)
54
+ : seek_mode_(seek_mode), avio_context_holder_(std::move(context)) {
55
+ set_ffmpeg_log_level();
56
+
57
+ STD_TORCH_CHECK(avio_context_holder_, "Context holder cannot be null");
58
+
59
+ // Because FFmpeg requires a reference to a pointer in the call to open, we
60
+ // can't use a unique pointer here. Note that means we must call free if open
61
+ // fails.
62
+ AVFormatContext* raw_context = avformat_alloc_context();
63
+ STD_TORCH_CHECK(raw_context != nullptr, "Unable to alloc avformat context");
64
+
65
+ raw_context->pb = avio_context_holder_->get_avio_context();
66
+ forbid_nested_protocols(raw_context);
67
+ int status = avformat_open_input(&raw_context, nullptr, nullptr, nullptr);
68
+ if (status != 0) {
69
+ avformat_free_context(raw_context);
70
+ STD_TORCH_CHECK(
71
+ false,
72
+ "Failed to open input buffer: " +
73
+ get_ffmpeg_error_string_from_error_code(status));
74
+ }
75
+
76
+ format_context_.reset(raw_context);
77
+
78
+ initialize_decoder();
79
+ }
80
+
81
+ void SingleStreamDecoder::initialize_decoder() {
82
+ STD_TORCH_CHECK(!initialized_, "Attempted double initialization.");
83
+
84
+ is_mpeg_ps_ = std::string_view(format_context_->iformat->name) == "mpeg";
85
+
86
+ // In principle, the AVFormatContext should be filled in by the call to
87
+ // avformat_open_input() which reads the header. However, some formats do not
88
+ // store enough info in the header, so we call avformat_find_stream_info()
89
+ // which decodes a few frames to get missing info. For more, see:
90
+ // https://ffmpeg.org/doxygen/7.0/group__lavf__decoding.html
91
+ int status = avformat_find_stream_info(format_context_.get(), nullptr);
92
+ STD_TORCH_CHECK(
93
+ status >= 0,
94
+ "Failed to find stream info: ",
95
+ get_ffmpeg_error_string_from_error_code(status));
96
+
97
+ container_metadata_ =
98
+ get_container_metadata_from_format_context(format_context_.get());
99
+
100
+ if (seek_mode_ == SeekMode::exact) {
101
+ scan_file_and_update_metadata_and_index();
102
+ }
103
+
104
+ initialized_ = true;
105
+ }
106
+
107
+ // --------------------------------------------------------------------------
108
+ // VIDEO METADATA QUERY API
109
+ // --------------------------------------------------------------------------
110
+
111
+ void SingleStreamDecoder::sort_all_frames() {
112
+ // Sort the allFrames and keyFrames vecs in each stream, and also sets
113
+ // additional fields of the FrameInfo entries like nextPts and frameIndex
114
+ // This is called at the end of a scan, or when setting a user-defined frame
115
+ // mapping.
116
+ for (auto& [stream_index, stream_info] : stream_infos_) {
117
+ std::sort(
118
+ stream_info.key_frames.begin(),
119
+ stream_info.key_frames.end(),
120
+ [](const FrameInfo& frame_info1, const FrameInfo& frame_info2) {
121
+ return frame_info1.pts < frame_info2.pts;
122
+ });
123
+ std::sort(
124
+ stream_info.all_frames.begin(),
125
+ stream_info.all_frames.end(),
126
+ [](const FrameInfo& frame_info1, const FrameInfo& frame_info2) {
127
+ return frame_info1.pts < frame_info2.pts;
128
+ });
129
+
130
+ size_t key_frame_index = 0;
131
+ for (size_t i = 0; i < stream_info.all_frames.size(); ++i) {
132
+ stream_info.all_frames[i].frame_index = i;
133
+ if (stream_info.all_frames[i].is_key_frame) {
134
+ STD_TORCH_CHECK(
135
+ key_frame_index < stream_info.key_frames.size(),
136
+ "The allFrames vec claims it has MORE keyFrames than the keyFrames vec. There's a bug in torchcodec.");
137
+ stream_info.key_frames[key_frame_index].frame_index = i;
138
+ ++key_frame_index;
139
+ }
140
+ if (i + 1 < stream_info.all_frames.size()) {
141
+ stream_info.all_frames[i].next_pts = stream_info.all_frames[i + 1].pts;
142
+ }
143
+ }
144
+ STD_TORCH_CHECK(
145
+ key_frame_index == stream_info.key_frames.size(),
146
+ "The allFrames vec claims it has LESS keyFrames than the keyFrames vec. There's a bug in torchcodec.");
147
+ }
148
+ }
149
+
150
+ void SingleStreamDecoder::scan_file_and_update_metadata_and_index() {
151
+ if (scanned_all_streams_) {
152
+ return;
153
+ }
154
+
155
+ AutoAVPacket auto_av_packet;
156
+ while (true) {
157
+ ReferenceAVPacket packet(auto_av_packet);
158
+
159
+ // av_read_frame is a misleading name: it gets the next **packet**.
160
+ int status = av_read_frame(format_context_.get(), packet.get());
161
+
162
+ if (status == AVERROR_EOF) {
163
+ break;
164
+ }
165
+
166
+ STD_TORCH_CHECK(
167
+ status == AVSUCCESS,
168
+ "Failed to read frame from input file: ",
169
+ get_ffmpeg_error_string_from_error_code(status));
170
+
171
+ if (packet->flags & AV_PKT_FLAG_DISCARD) {
172
+ continue;
173
+ }
174
+
175
+ // We got a valid packet. Let's figure out what stream it belongs to and
176
+ // record its relevant metadata.
177
+ int stream_index = packet->stream_index;
178
+ if (stream_index < 0 ||
179
+ stream_index >=
180
+ static_cast<int>(container_metadata_.all_stream_metadata.size())) {
181
+ // in theory, a video may add a stream midway through the file, which
182
+ // could cause OOB access. See D124080592.
183
+ continue;
184
+ }
185
+
186
+ auto& stream_metadata =
187
+ container_metadata_.all_stream_metadata[stream_index];
188
+ stream_metadata.begin_stream_pts_from_content = std::min(
189
+ stream_metadata.begin_stream_pts_from_content.value_or(INT64_MAX),
190
+ get_pts_or_dts(packet));
191
+ stream_metadata.end_stream_pts_from_content = std::max(
192
+ stream_metadata.end_stream_pts_from_content.value_or(INT64_MIN),
193
+ get_pts_or_dts(packet) + packet->duration);
194
+ stream_metadata.num_frames_from_content =
195
+ stream_metadata.num_frames_from_content.value_or(0) + 1;
196
+
197
+ // Note that we set the other value in this struct, nextPts, only after
198
+ // we have scanned all packets and sorted by pts.
199
+ FrameInfo frame_info = {get_pts_or_dts(packet)};
200
+ if (packet->flags & AV_PKT_FLAG_KEY) {
201
+ frame_info.is_key_frame = true;
202
+ stream_infos_[stream_index].key_frames.push_back(frame_info);
203
+ }
204
+ stream_infos_[stream_index].all_frames.push_back(frame_info);
205
+ }
206
+
207
+ // Set all per-stream metadata that requires knowing the content of all
208
+ // packets.
209
+ for (size_t stream_index = 0;
210
+ stream_index < container_metadata_.all_stream_metadata.size();
211
+ ++stream_index) {
212
+ auto& stream_metadata =
213
+ container_metadata_.all_stream_metadata[stream_index];
214
+ auto av_stream = format_context_->streams[stream_index];
215
+
216
+ stream_metadata.num_frames_from_content =
217
+ stream_infos_[stream_index].all_frames.size();
218
+
219
+ // This ensures that we are robust in handling cases where
220
+ // we are decoding in exact mode and numFrames is 0. The current metadata
221
+ // validation logic assumes that these values should not be None
222
+ if (stream_metadata.num_frames_from_content.value() == 0) {
223
+ stream_metadata.begin_stream_pts_from_content = 0;
224
+ stream_metadata.end_stream_pts_from_content = 0;
225
+ }
226
+
227
+ if (stream_metadata.begin_stream_pts_from_content.has_value()) {
228
+ stream_metadata.begin_stream_pts_seconds_from_content = pts_to_seconds(
229
+ *stream_metadata.begin_stream_pts_from_content, av_stream->time_base);
230
+ }
231
+ if (stream_metadata.end_stream_pts_from_content.has_value()) {
232
+ stream_metadata.end_stream_pts_seconds_from_content = pts_to_seconds(
233
+ *stream_metadata.end_stream_pts_from_content, av_stream->time_base);
234
+ }
235
+ }
236
+
237
+ // Reset the seek-cursor back to the beginning.
238
+ int status = avformat_seek_file(format_context_.get(), 0, INT64_MIN, 0, 0, 0);
239
+ STD_TORCH_CHECK(
240
+ status >= 0, get_seek_error_message(format_context_.get(), 0, status));
241
+
242
+ // Sort all frames by their pts.
243
+ sort_all_frames();
244
+ scanned_all_streams_ = true;
245
+ }
246
+
247
+ void SingleStreamDecoder::read_custom_frame_mappings_update_metadata_and_index(
248
+ int stream_index,
249
+ FrameMappings custom_frame_mappings) {
250
+ STD_TORCH_CHECK(
251
+ custom_frame_mappings.all_frames.scalar_type() == kStableInt64 &&
252
+ custom_frame_mappings.is_key_frame.scalar_type() == kStableBool &&
253
+ custom_frame_mappings.duration.scalar_type() == kStableInt64,
254
+ "all_frames and duration tensors must be int64 dtype, and is_key_frame tensor must be a bool dtype.");
255
+ const torch::stable::Tensor& all_frames = custom_frame_mappings.all_frames;
256
+ const torch::stable::Tensor& is_key_frame =
257
+ custom_frame_mappings.is_key_frame;
258
+ const torch::stable::Tensor& duration = custom_frame_mappings.duration;
259
+ STD_TORCH_CHECK(
260
+ all_frames.sizes()[0] == is_key_frame.sizes()[0] &&
261
+ is_key_frame.sizes()[0] == duration.sizes()[0],
262
+ "all_frames, is_key_frame, and duration from custom_frame_mappings were not same size.");
263
+
264
+ // Allocate vectors using num frames to reduce reallocations
265
+ int64_t num_frames = all_frames.sizes()[0];
266
+ stream_infos_[stream_index].all_frames.reserve(num_frames);
267
+ stream_infos_[stream_index].key_frames.reserve(num_frames);
268
+ auto pts_data = const_accessor<int64_t, 1>(all_frames);
269
+ auto is_key_frame_data = const_accessor<bool, 1>(is_key_frame);
270
+ auto duration_data = const_accessor<int64_t, 1>(duration);
271
+
272
+ auto& stream_metadata = container_metadata_.all_stream_metadata[stream_index];
273
+
274
+ stream_metadata.begin_stream_pts_from_content = pts_data[0];
275
+ stream_metadata.end_stream_pts_from_content =
276
+ pts_data[num_frames - 1] + duration_data[num_frames - 1];
277
+
278
+ auto av_stream = format_context_->streams[stream_index];
279
+ stream_metadata.begin_stream_pts_seconds_from_content = pts_to_seconds(
280
+ *stream_metadata.begin_stream_pts_from_content, av_stream->time_base);
281
+
282
+ stream_metadata.end_stream_pts_seconds_from_content = pts_to_seconds(
283
+ *stream_metadata.end_stream_pts_from_content, av_stream->time_base);
284
+
285
+ stream_metadata.num_frames_from_content = num_frames;
286
+ for (int64_t i = 0; i < num_frames; ++i) {
287
+ FrameInfo frame_info;
288
+ frame_info.pts = pts_data[i];
289
+ frame_info.is_key_frame = is_key_frame_data[i];
290
+ stream_infos_[stream_index].all_frames.push_back(frame_info);
291
+ if (frame_info.is_key_frame) {
292
+ stream_infos_[stream_index].key_frames.push_back(frame_info);
293
+ }
294
+ }
295
+ sort_all_frames();
296
+ }
297
+
298
+ ContainerMetadata SingleStreamDecoder::get_container_metadata() const {
299
+ return container_metadata_;
300
+ }
301
+
302
+ SeekMode SingleStreamDecoder::get_seek_mode() const {
303
+ return seek_mode_;
304
+ }
305
+
306
+ int SingleStreamDecoder::get_active_stream_index() const {
307
+ return active_stream_index_;
308
+ }
309
+
310
+ torch::stable::Tensor SingleStreamDecoder::get_key_frame_indices() {
311
+ validate_active_stream(AVMEDIA_TYPE_VIDEO);
312
+ validate_scanned_all_streams("getKeyFrameIndices");
313
+
314
+ const std::vector<FrameInfo>& key_frames =
315
+ stream_infos_[active_stream_index_].key_frames;
316
+ torch::stable::Tensor key_frame_indices = torch::stable::empty(
317
+ {static_cast<int64_t>(key_frames.size())}, kStableInt64);
318
+ auto key_frame_indices_accessor =
319
+ mutable_accessor<int64_t, 1>(key_frame_indices);
320
+ for (size_t i = 0; i < key_frames.size(); ++i) {
321
+ key_frame_indices_accessor[i] = key_frames[i].frame_index;
322
+ }
323
+
324
+ return key_frame_indices;
325
+ }
326
+
327
+ // --------------------------------------------------------------------------
328
+ // ADDING STREAMS API
329
+ // --------------------------------------------------------------------------
330
+
331
+ void SingleStreamDecoder::add_stream(
332
+ int stream_index,
333
+ AVMediaType media_type,
334
+ const StableDevice& device,
335
+ const std::string_view device_variant,
336
+ std::optional<int> ffmpeg_thread_count) {
337
+ STD_TORCH_CHECK(
338
+ active_stream_index_ == no_active_stream_,
339
+ "Can only add one single stream.");
340
+ STD_TORCH_CHECK(
341
+ media_type == AVMEDIA_TYPE_VIDEO || media_type == AVMEDIA_TYPE_AUDIO,
342
+ "Can only add video or audio streams.");
343
+ STD_TORCH_CHECK(format_context_.get() != nullptr, "Format context is null");
344
+
345
+ AVCodecOnlyUseForCallingAVFindBestStream av_codec = nullptr;
346
+
347
+ active_stream_index_ = av_find_best_stream(
348
+ format_context_.get(), media_type, stream_index, -1, &av_codec, 0);
349
+
350
+ STD_TORCH_CHECK(
351
+ active_stream_index_ >= 0,
352
+ "No valid stream found in input file. Is ",
353
+ stream_index,
354
+ " of the desired media type?");
355
+
356
+ STD_TORCH_CHECK(av_codec != nullptr, "Codec not found");
357
+
358
+ StreamInfo& stream_info = stream_infos_[active_stream_index_];
359
+ stream_info.stream_index = active_stream_index_;
360
+ stream_info.time_base =
361
+ format_context_->streams[active_stream_index_]->time_base;
362
+ stream_info.stream = format_context_->streams[active_stream_index_];
363
+ stream_info.av_media_type = media_type;
364
+
365
+ // This should never happen, checking just to be safe.
366
+ STD_TORCH_CHECK(
367
+ stream_info.stream->codecpar->codec_type == media_type,
368
+ "FFmpeg found stream with index ",
369
+ active_stream_index_,
370
+ " which is of the wrong media type.");
371
+
372
+ device_interface_ = create_device_interface(device, device_variant);
373
+ STD_TORCH_CHECK(
374
+ device_interface_ != nullptr,
375
+ "Failed to create device interface. This should never happen, please report.");
376
+
377
+ // TODO_CODE_QUALITY it's pretty meh to have a video-specific logic within
378
+ // addStream() which is supposed to be generic
379
+ if (media_type == AVMEDIA_TYPE_VIDEO) {
380
+ av_codec = make_av_codec_only_use_for_calling_av_find_best_stream(
381
+ device_interface_->find_codec(stream_info.stream->codecpar->codec_id)
382
+ .value_or(av_codec));
383
+ }
384
+
385
+ // Create + configure + open the codec context (shared with PacketDecoder).
386
+ stream_info.codec_context = create_and_open_codec_context(
387
+ stream_info.stream,
388
+ av_codec,
389
+ device_interface_.get(),
390
+ ffmpeg_thread_count);
391
+
392
+ // Initialize the device interface with the codec context
393
+ device_interface_->initialize(stream_info.codec_context);
394
+
395
+ container_metadata_.all_stream_metadata[active_stream_index_].codec_name =
396
+ std::string(avcodec_get_name(stream_info.codec_context->codec_id));
397
+
398
+ // We will only need packets from the active stream, so we tell FFmpeg to
399
+ // discard packets from the other streams. Note that av_read_frame() may still
400
+ // return some of those un-desired packet under some conditions, so it's still
401
+ // important to discard/demux correctly in the inner decoding loop.
402
+ for (unsigned int i = 0; i < format_context_->nb_streams; ++i) {
403
+ if (i != static_cast<unsigned int>(active_stream_index_)) {
404
+ format_context_->streams[i]->discard = AVDISCARD_ALL;
405
+ }
406
+ }
407
+ }
408
+
409
+ void SingleStreamDecoder::add_video_stream(
410
+ int stream_index,
411
+ std::vector<Transform*>& transforms,
412
+ const VideoStreamOptions& video_stream_options,
413
+ std::optional<FrameMappings> custom_frame_mappings) {
414
+ STD_TORCH_CHECK(
415
+ transforms.empty() || video_stream_options.device == kStableCPU,
416
+ " Transforms are only supported for CPU devices.");
417
+
418
+ add_stream(
419
+ stream_index,
420
+ AVMEDIA_TYPE_VIDEO,
421
+ video_stream_options.device,
422
+ video_stream_options.device_variant,
423
+ video_stream_options.ffmpeg_thread_count);
424
+
425
+ auto& stream_metadata =
426
+ container_metadata_.all_stream_metadata[active_stream_index_];
427
+
428
+ if (seek_mode_ == SeekMode::approximate) {
429
+ STD_TORCH_CHECK(
430
+ stream_metadata.average_fps_from_header.has_value(),
431
+ "Seek mode is approximate, but stream ",
432
+ std::to_string(active_stream_index_),
433
+ " does not have an average fps in its metadata.");
434
+ }
435
+
436
+ auto& stream_info = stream_infos_[active_stream_index_];
437
+ stream_info.video_stream_options = video_stream_options;
438
+
439
+ if (seek_mode_ == SeekMode::custom_frame_mappings) {
440
+ STD_TORCH_CHECK(
441
+ custom_frame_mappings.has_value(),
442
+ "Missing frame mappings when custom_frame_mappings seek mode is set.");
443
+ read_custom_frame_mappings_update_metadata_and_index(
444
+ active_stream_index_, custom_frame_mappings.value());
445
+ }
446
+
447
+ stream_info.video_stream_options.output_dtype = resolve_output_dtype(
448
+ stream_info.video_stream_options.output_dtype_config,
449
+ static_cast<AVPixelFormat>(stream_info.stream->codecpar->format));
450
+
451
+ // Set preRotationDims_ for the active stream. These are the raw encoded
452
+ // dimensions from FFmpeg, used as a fallback for tensor pre-allocation when
453
+ // no resize/rotation transforms are applied.
454
+ pre_rotation_dims_ = FrameDims(
455
+ stream_info.stream->codecpar->height,
456
+ stream_info.stream->codecpar->width);
457
+
458
+ FrameDims curr_input_dims = pre_rotation_dims_;
459
+
460
+ // If there's rotation, prepend a RotationTransform to handle it in the
461
+ // filter graph. This way user transforms (resize, crop) operate in
462
+ // post-rotation coordinate space, preserving x/y coordinates for crops.
463
+ //
464
+ // It is critical to apply the rotation *before* any user-supplied
465
+ // transforms. By design, we want:
466
+ // A: VideoDecoder(..., transforms=tv_transforms)[i]
467
+ // to be equivalent to:
468
+ // B: tv_transforms(VideoDecoder(...)[i])
469
+ // In B, rotation is applied before transforms, so A must behave the same.
470
+ //
471
+ // TODO: benchmark the performance of doing this additional filtergraph
472
+ // transform
473
+ Rotation rotation = rotation_from_degrees(stream_metadata.rotation);
474
+ if (rotation != Rotation::NONE) {
475
+ auto rotation_transform =
476
+ std::make_unique<RotationTransform>(rotation, curr_input_dims);
477
+ curr_input_dims = rotation_transform->get_output_frame_dims().value();
478
+ resized_output_dims_ = curr_input_dims;
479
+ transforms_.push_back(std::move(rotation_transform));
480
+ }
481
+
482
+ // Note that we are claiming ownership of the transform objects passed in to
483
+ // us.
484
+ // Validate and add user transforms
485
+ for (auto& transform : transforms) {
486
+ STD_TORCH_CHECK(
487
+ transform != nullptr, "Transforms should never be nullptr!");
488
+ transform->validate(curr_input_dims);
489
+ if (transform->get_output_frame_dims().has_value()) {
490
+ resized_output_dims_ = transform->get_output_frame_dims().value();
491
+ curr_input_dims = resized_output_dims_.value();
492
+ }
493
+ transforms_.push_back(std::unique_ptr<Transform>(transform));
494
+ }
495
+
496
+ // Pass the resolved options (AUTO -> UINT8/FLOAT32) so the device interface
497
+ // sees a definite OutputDtype.
498
+ device_interface_->initialize_video(
499
+ stream_info.stream,
500
+ format_context_,
501
+ stream_info.video_stream_options,
502
+ transforms_,
503
+ resized_output_dims_);
504
+ }
505
+
506
+ void SingleStreamDecoder::add_audio_stream(
507
+ int stream_index,
508
+ const AudioStreamOptions& audio_stream_options) {
509
+ STD_TORCH_CHECK(
510
+ seek_mode_ == SeekMode::approximate,
511
+ "seek_mode must be 'approximate' for audio streams.");
512
+ if (audio_stream_options.num_channels.has_value()) {
513
+ STD_TORCH_CHECK(
514
+ *audio_stream_options.num_channels > 0,
515
+ "num_channels must be > 0. Got: ",
516
+ *audio_stream_options.num_channels);
517
+ }
518
+
519
+ // We hardcode ffmpegThreadCount=1 for audio, see
520
+ // https://github.com/pytorch/torchcodec/issues/1253 and
521
+ // https://github.com/pytorch/torchcodec/pull/1254
522
+ add_stream(
523
+ stream_index, AVMEDIA_TYPE_AUDIO, StableDevice(kStableCPU), "default", 1);
524
+
525
+ auto& stream_info = stream_infos_[active_stream_index_];
526
+ stream_info.audio_stream_options = audio_stream_options;
527
+ audio_pts_extrapolator_ = AudioPtsExtrapolator(stream_info.time_base);
528
+
529
+ // FFmpeg docs say that the decoder will try to decode natively in this
530
+ // format, if it can. Docs don't say what the decoder does when it doesn't
531
+ // support that format, but it looks like it does nothing, so this probably
532
+ // doesn't hurt.
533
+ stream_info.codec_context->request_sample_fmt = AV_SAMPLE_FMT_FLTP;
534
+
535
+ // Initialize device interface for audio
536
+ double stream_start_seconds = stream_info.stream->start_time != AV_NOPTS_VALUE
537
+ ? pts_to_seconds(stream_info.stream->start_time, stream_info.time_base)
538
+ : 0.0;
539
+ device_interface_->initialize_audio(
540
+ audio_stream_options, stream_start_seconds);
541
+ }
542
+
543
+ // --------------------------------------------------------------------------
544
+ // HIGH-LEVEL DECODING ENTRY-POINTS
545
+ // --------------------------------------------------------------------------
546
+
547
+ FrameOutput SingleStreamDecoder::get_next_frame() {
548
+ auto output = get_next_frame_internal();
549
+ if (stream_infos_[active_stream_index_].av_media_type == AVMEDIA_TYPE_VIDEO) {
550
+ output.data = maybe_permute_and_convert_dtype(output.data);
551
+ }
552
+ return output;
553
+ }
554
+
555
+ FrameOutput SingleStreamDecoder::get_next_frame_internal(
556
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor) {
557
+ validate_active_stream();
558
+ UniqueAVFrame av_frame = decode_av_frame([this](const AVFrame& av_frame) {
559
+ return get_pts_or_dts(av_frame) >= cursor_;
560
+ });
561
+ return convert_av_frame_to_frame_output(
562
+ *av_frame, pre_allocated_output_tensor);
563
+ }
564
+
565
+ FrameOutput SingleStreamDecoder::get_frame_at_index(int64_t frame_index) {
566
+ auto frame_output = get_frame_at_index_internal(frame_index);
567
+ frame_output.data = maybe_permute_and_convert_dtype(frame_output.data);
568
+ return frame_output;
569
+ }
570
+
571
+ FrameOutput SingleStreamDecoder::get_frame_at_index_internal(
572
+ int64_t frame_index,
573
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor) {
574
+ validate_active_stream(AVMEDIA_TYPE_VIDEO);
575
+
576
+ const auto& stream_info = stream_infos_[active_stream_index_];
577
+ const auto& stream_metadata =
578
+ container_metadata_.all_stream_metadata[active_stream_index_];
579
+
580
+ std::optional<int64_t> num_frames =
581
+ stream_metadata.get_num_frames(seek_mode_);
582
+ if (num_frames.has_value()) {
583
+ // If the frameIndex is negative, we convert it to a positive index
584
+ frame_index =
585
+ frame_index >= 0 ? frame_index : frame_index + num_frames.value();
586
+ }
587
+ validate_frame_index(stream_metadata, frame_index);
588
+
589
+ int64_t pts = get_pts(frame_index);
590
+ set_cursor_pts_in_seconds(pts_to_seconds(pts, stream_info.time_base));
591
+ return get_next_frame_internal(pre_allocated_output_tensor);
592
+ }
593
+
594
+ FrameBatchOutput SingleStreamDecoder::get_frames_at_indices(
595
+ const torch::stable::Tensor& frame_indices) {
596
+ validate_active_stream(AVMEDIA_TYPE_VIDEO);
597
+
598
+ auto frame_indices_data = const_accessor<int64_t, 1>(frame_indices);
599
+
600
+ bool indices_are_sorted = true;
601
+ for (int64_t i = 1; i < frame_indices.numel(); ++i) {
602
+ if (frame_indices_data[i] < frame_indices_data[i - 1]) {
603
+ indices_are_sorted = false;
604
+ break;
605
+ }
606
+ }
607
+
608
+ std::vector<size_t> argsort;
609
+ if (!indices_are_sorted) {
610
+ // if frameIndices is [13, 10, 12, 11]
611
+ // when sorted, it's [10, 11, 12, 13] <-- this is the sorted order we want
612
+ // to use to decode the frames
613
+ // and argsort is [ 1, 3, 2, 0]
614
+ argsort.resize(frame_indices.numel());
615
+ for (size_t i = 0; i < argsort.size(); ++i) {
616
+ argsort[i] = i;
617
+ }
618
+ std::sort(
619
+ argsort.begin(),
620
+ argsort.end(),
621
+ [&frame_indices_data](size_t a, size_t b) {
622
+ return frame_indices_data[a] < frame_indices_data[b];
623
+ });
624
+ }
625
+
626
+ const auto& stream_info = stream_infos_[active_stream_index_];
627
+ const auto& video_stream_options = stream_info.video_stream_options;
628
+ FrameBatchOutput frame_batch_output(
629
+ frame_indices.numel(),
630
+ get_output_dims(),
631
+ video_stream_options.device,
632
+ device_interface_->get_pre_allocation_dtype(
633
+ video_stream_options.output_dtype));
634
+
635
+ auto frame_batch_output_pts_seconds =
636
+ mutable_accessor<double, 1>(frame_batch_output.pts_seconds);
637
+ auto frame_batch_output_duration_seconds =
638
+ mutable_accessor<double, 1>(frame_batch_output.duration_seconds);
639
+
640
+ auto previous_index_in_video = -1;
641
+ for (int64_t f = 0; f < frame_indices.numel(); ++f) {
642
+ auto index_in_output = indices_are_sorted ? f : argsort[f];
643
+ auto index_in_video = frame_indices_data[index_in_output];
644
+
645
+ if ((f > 0) && (index_in_video == previous_index_in_video)) {
646
+ // Avoid decoding the same frame twice
647
+ auto previous_index_in_output =
648
+ indices_are_sorted ? f - 1 : argsort[f - 1];
649
+ copy_frame(
650
+ frame_batch_output.data,
651
+ index_in_output,
652
+ frame_batch_output.data,
653
+ previous_index_in_output);
654
+ frame_batch_output_pts_seconds[index_in_output] =
655
+ frame_batch_output_pts_seconds[previous_index_in_output];
656
+ frame_batch_output_duration_seconds[index_in_output] =
657
+ frame_batch_output_duration_seconds[previous_index_in_output];
658
+ } else {
659
+ FrameOutput frame_output = get_frame_at_index_internal(
660
+ index_in_video, select_row(frame_batch_output.data, index_in_output));
661
+ frame_batch_output_pts_seconds[index_in_output] =
662
+ frame_output.pts_seconds;
663
+ frame_batch_output_duration_seconds[index_in_output] =
664
+ frame_output.duration_seconds;
665
+ }
666
+ previous_index_in_video = index_in_video;
667
+ }
668
+ frame_batch_output.data =
669
+ maybe_permute_and_convert_dtype(frame_batch_output.data);
670
+ return frame_batch_output;
671
+ }
672
+
673
+ FrameBatchOutput SingleStreamDecoder::get_frames_in_range(
674
+ int64_t start,
675
+ int64_t stop,
676
+ int64_t step) {
677
+ validate_active_stream(AVMEDIA_TYPE_VIDEO);
678
+
679
+ const auto& stream_metadata =
680
+ container_metadata_.all_stream_metadata[active_stream_index_];
681
+ const auto& stream_info = stream_infos_[active_stream_index_];
682
+ STD_TORCH_CHECK(
683
+ start >= 0, "Range start, " + std::to_string(start) + " is less than 0.");
684
+ STD_TORCH_CHECK(
685
+ step > 0, "Step must be greater than 0; is " + std::to_string(step));
686
+
687
+ // Note that if we do not have the number of frames available in our
688
+ // metadata, then we assume that the upper part of the range is valid.
689
+ std::optional<int64_t> num_frames =
690
+ stream_metadata.get_num_frames(seek_mode_);
691
+ if (num_frames.has_value()) {
692
+ STD_TORCH_CHECK(
693
+ stop <= num_frames.value(),
694
+ "Range stop, " + std::to_string(stop) +
695
+ ", is more than the number of frames, " +
696
+ std::to_string(num_frames.value()));
697
+ }
698
+
699
+ int64_t num_output_frames = std::ceil((stop - start) / double(step));
700
+ const auto& video_stream_options = stream_info.video_stream_options;
701
+ FrameBatchOutput frame_batch_output(
702
+ num_output_frames,
703
+ get_output_dims(),
704
+ video_stream_options.device,
705
+ device_interface_->get_pre_allocation_dtype(
706
+ video_stream_options.output_dtype));
707
+
708
+ auto frame_batch_output_pts_seconds =
709
+ mutable_accessor<double, 1>(frame_batch_output.pts_seconds);
710
+ auto frame_batch_output_duration_seconds =
711
+ mutable_accessor<double, 1>(frame_batch_output.duration_seconds);
712
+ for (int64_t i = start, f = 0; i < stop; i += step, ++f) {
713
+ FrameOutput frame_output =
714
+ get_frame_at_index_internal(i, select_row(frame_batch_output.data, f));
715
+ frame_batch_output_pts_seconds[f] = frame_output.pts_seconds;
716
+ frame_batch_output_duration_seconds[f] = frame_output.duration_seconds;
717
+ }
718
+ frame_batch_output.data =
719
+ maybe_permute_and_convert_dtype(frame_batch_output.data);
720
+ return frame_batch_output;
721
+ }
722
+
723
+ FrameOutput SingleStreamDecoder::get_frame_played_at(double seconds) {
724
+ validate_active_stream(AVMEDIA_TYPE_VIDEO);
725
+ StreamInfo& stream_info = stream_infos_[active_stream_index_];
726
+ double last_decoded_start_time =
727
+ pts_to_seconds(last_decoded_av_frame_pts_, stream_info.time_base);
728
+ double last_decoded_end_time =
729
+ pts_to_seconds(last_decoded_av_frame_end_pts(), stream_info.time_base);
730
+ if (seconds >= last_decoded_start_time && seconds < last_decoded_end_time) {
731
+ // We are in the same frame as the one we just returned. However, since we
732
+ // don't cache it locally, we have to rewind back.
733
+ seconds = last_decoded_start_time;
734
+ }
735
+
736
+ set_cursor_pts_in_seconds(seconds);
737
+ UniqueAVFrame av_frame =
738
+ decode_av_frame([seconds, this](const AVFrame& av_frame) {
739
+ StreamInfo& stream_info = stream_infos_[active_stream_index_];
740
+ double frame_start_time =
741
+ pts_to_seconds(get_pts_or_dts(av_frame), stream_info.time_base);
742
+ double frame_end_time = pts_to_seconds(
743
+ get_pts_or_dts(av_frame) + get_duration(av_frame),
744
+ stream_info.time_base);
745
+ if (frame_start_time > seconds) {
746
+ // FFMPEG seeked past the frame we are looking for even though we
747
+ // set max_ts to be our needed timestamp in avformat_seek_file()
748
+ // in maybeSeekToBeforeDesiredPts().
749
+ // This could be a bug in FFMPEG:
750
+ // https://trac.ffmpeg.org/ticket/11137 In this case we return the
751
+ // very next frame instead of throwing an exception.
752
+ // TODO: Maybe log to stderr for Debug builds?
753
+ return true;
754
+ }
755
+ return seconds >= frame_start_time && seconds < frame_end_time;
756
+ });
757
+
758
+ // Convert the frame to tensor.
759
+ FrameOutput frame_output = convert_av_frame_to_frame_output(*av_frame);
760
+ frame_output.data = maybe_permute_and_convert_dtype(frame_output.data);
761
+ return frame_output;
762
+ }
763
+
764
+ FrameBatchOutput SingleStreamDecoder::get_frames_played_at(
765
+ const torch::stable::Tensor& timestamps) {
766
+ validate_active_stream(AVMEDIA_TYPE_VIDEO);
767
+
768
+ const auto& stream_metadata =
769
+ container_metadata_.all_stream_metadata[active_stream_index_];
770
+
771
+ double min_seconds = stream_metadata.get_begin_stream_seconds(seek_mode_);
772
+ std::optional<double> max_seconds =
773
+ stream_metadata.get_end_stream_seconds(seek_mode_);
774
+
775
+ // The frame played at timestamp t and the one played at timestamp `t +
776
+ // eps` are probably the same frame, with the same index. The easiest way to
777
+ // avoid decoding that unique frame twice is to convert the input timestamps
778
+ // to indices, and leverage the de-duplication logic of getFramesAtIndices.
779
+
780
+ torch::stable::Tensor frame_indices =
781
+ torch::stable::empty({timestamps.numel()}, kStableInt64);
782
+ auto frame_indices_accessor = mutable_accessor<int64_t, 1>(frame_indices);
783
+ auto timestamps_accessor = const_accessor<double, 1>(timestamps);
784
+
785
+ for (int64_t i = 0; i < timestamps.numel(); ++i) {
786
+ auto frame_seconds = timestamps_accessor[i];
787
+ STD_TORCH_CHECK(
788
+ frame_seconds >= min_seconds,
789
+ "frame pts is " + std::to_string(frame_seconds) +
790
+ "; must be greater than or equal to " +
791
+ std::to_string(min_seconds) + ".");
792
+
793
+ // Note that if we can't determine the maximum number of seconds from the
794
+ // metadata, then we assume the frame's pts is valid.
795
+ if (max_seconds.has_value()) {
796
+ STD_TORCH_CHECK(
797
+ frame_seconds < max_seconds.value(),
798
+ "frame pts is " + std::to_string(frame_seconds) +
799
+ "; must be less than " + std::to_string(max_seconds.value()) +
800
+ ".");
801
+ }
802
+
803
+ frame_indices_accessor[i] = seconds_to_index_lower_bound(frame_seconds);
804
+ }
805
+
806
+ return get_frames_at_indices(frame_indices);
807
+ }
808
+
809
+ FrameBatchOutput SingleStreamDecoder::get_frames_played_in_range(
810
+ double start_seconds,
811
+ double stop_seconds,
812
+ std::optional<double> fps) {
813
+ validate_active_stream(AVMEDIA_TYPE_VIDEO);
814
+ const auto& stream_metadata =
815
+ container_metadata_.all_stream_metadata[active_stream_index_];
816
+ STD_TORCH_CHECK(
817
+ start_seconds <= stop_seconds,
818
+ "Start seconds (" + std::to_string(start_seconds) +
819
+ ") must be less than or equal to stop seconds (" +
820
+ std::to_string(stop_seconds) + ".");
821
+
822
+ const auto& stream_info = stream_infos_[active_stream_index_];
823
+ const auto& video_stream_options = stream_info.video_stream_options;
824
+
825
+ // Special case needed to implement a half-open range. At first glance, this
826
+ // may seem unnecessary, as our search for stopFrame can return the end, and
827
+ // we don't include stopFramIndex in our output. However, consider the
828
+ // following scenario:
829
+ //
830
+ // frame=0, pts=0.0
831
+ // frame=1, pts=0.3
832
+ //
833
+ // interval A: [0.2, 0.2)
834
+ // interval B: [0.2, 0.15)
835
+ //
836
+ // Both intervals take place between the pts values for frame 0 and frame 1,
837
+ // which by our abstract player, means that both intervals map to frame 0.
838
+ // By the definition of a half open interval, interval A should return no
839
+ // frames. Interval B should return frame 0. However, for both A and B, the
840
+ // individual values of the intervals will map to the same frame indices
841
+ // below. Hence, we need this special case below.
842
+ if (start_seconds == stop_seconds) {
843
+ FrameBatchOutput frame_batch_output(
844
+ 0,
845
+ get_output_dims(),
846
+ video_stream_options.device,
847
+ device_interface_->get_pre_allocation_dtype(
848
+ video_stream_options.output_dtype));
849
+ frame_batch_output.data =
850
+ maybe_permute_and_convert_dtype(frame_batch_output.data);
851
+ return frame_batch_output;
852
+ }
853
+
854
+ double min_seconds = stream_metadata.get_begin_stream_seconds(seek_mode_);
855
+ STD_TORCH_CHECK(
856
+ start_seconds >= min_seconds,
857
+ "Start seconds is " + std::to_string(start_seconds) +
858
+ "; must be greater than or equal to " + std::to_string(min_seconds) +
859
+ ".");
860
+
861
+ // Note that if we can't determine the maximum seconds from the metadata,
862
+ // then we assume upper range is valid.
863
+ std::optional<double> max_seconds =
864
+ stream_metadata.get_end_stream_seconds(seek_mode_);
865
+ if (max_seconds.has_value()) {
866
+ STD_TORCH_CHECK(
867
+ start_seconds < max_seconds.value(),
868
+ "Start seconds is " + std::to_string(start_seconds) +
869
+ "; must be less than " + std::to_string(max_seconds.value()) + ".");
870
+ STD_TORCH_CHECK(
871
+ stop_seconds <= max_seconds.value(),
872
+ "Stop seconds (" + std::to_string(stop_seconds) +
873
+ "; must be less than or equal to " +
874
+ std::to_string(max_seconds.value()) + ").");
875
+ }
876
+
877
+ // Resample frames to match the target frame rate
878
+ if (fps.has_value()) {
879
+ STD_TORCH_CHECK(
880
+ fps.value() > 0,
881
+ "fps must be positive, got " + std::to_string(fps.value()));
882
+
883
+ // TODO: add an early break if requested fps is the same as the current fps
884
+
885
+ double fps_val = fps.value();
886
+ double frame_duration_seconds = 1.0 / fps_val;
887
+
888
+ double product = (stop_seconds - start_seconds) * fps_val;
889
+ int64_t num_output_frames = static_cast<int64_t>(std::round(product));
890
+
891
+ FrameBatchOutput frame_batch_output(
892
+ num_output_frames,
893
+ get_output_dims(),
894
+ video_stream_options.device,
895
+ device_interface_->get_pre_allocation_dtype(
896
+ video_stream_options.output_dtype));
897
+
898
+ auto frame_batch_output_pts_seconds =
899
+ mutable_accessor<double, 1>(frame_batch_output.pts_seconds);
900
+ auto frame_batch_output_duration_seconds =
901
+ mutable_accessor<double, 1>(frame_batch_output.duration_seconds);
902
+
903
+ // Decode frames, reusing already-decoded frames for duplicates
904
+ int64_t last_decoded_source_index = -1;
905
+
906
+ for (int64_t i = 0; i < num_output_frames; ++i) {
907
+ double target_pts_seconds = start_seconds + i * frame_duration_seconds;
908
+ int64_t source_idx = seconds_to_index_lower_bound(target_pts_seconds);
909
+
910
+ if (source_idx == last_decoded_source_index &&
911
+ last_decoded_source_index >= 0) {
912
+ copy_frame(frame_batch_output.data, i, frame_batch_output.data, i - 1);
913
+ } else {
914
+ get_frame_at_index_internal(
915
+ source_idx, select_row(frame_batch_output.data, i));
916
+ last_decoded_source_index = source_idx;
917
+ }
918
+
919
+ frame_batch_output_pts_seconds[i] = target_pts_seconds;
920
+ frame_batch_output_duration_seconds[i] = frame_duration_seconds;
921
+ }
922
+
923
+ frame_batch_output.data =
924
+ maybe_permute_and_convert_dtype(frame_batch_output.data);
925
+ return frame_batch_output;
926
+ } else {
927
+ // Note that we look at nextPts for a frame, and not its pts or duration.
928
+ // Our abstract player displays frames starting at the pts for that frame
929
+ // until the pts for the next frame. There are two consequences:
930
+ //
931
+ // 1. We ignore the duration for a frame. A frame is played until the
932
+ // next frame replaces it. This model is robust to durations being 0 or
933
+ // incorrect; our source of truth is the pts for frames. If duration is
934
+ // accurate, the nextPts for a frame would be equivalent to pts +
935
+ // duration.
936
+ // 2. In order to establish if the start of an interval maps to a
937
+ // particular frame, we need to figure out if it is ordered after the
938
+ // frame's pts, but before the next frames's pts.
939
+
940
+ int64_t start_frame_index = seconds_to_index_lower_bound(start_seconds);
941
+ int64_t stop_frame_index = seconds_to_index_upper_bound(stop_seconds);
942
+ int64_t num_frames = stop_frame_index - start_frame_index;
943
+
944
+ FrameBatchOutput frame_batch_output(
945
+ num_frames,
946
+ get_output_dims(),
947
+ video_stream_options.device,
948
+ device_interface_->get_pre_allocation_dtype(
949
+ video_stream_options.output_dtype));
950
+ auto frame_batch_output_pts_seconds =
951
+ mutable_accessor<double, 1>(frame_batch_output.pts_seconds);
952
+ auto frame_batch_output_duration_seconds =
953
+ mutable_accessor<double, 1>(frame_batch_output.duration_seconds);
954
+ for (int64_t i = start_frame_index, f = 0; i < stop_frame_index; ++i, ++f) {
955
+ FrameOutput frame_output = get_frame_at_index_internal(
956
+ i, select_row(frame_batch_output.data, f));
957
+ frame_batch_output_pts_seconds[f] = frame_output.pts_seconds;
958
+ frame_batch_output_duration_seconds[f] = frame_output.duration_seconds;
959
+ }
960
+ frame_batch_output.data =
961
+ maybe_permute_and_convert_dtype(frame_batch_output.data);
962
+
963
+ return frame_batch_output;
964
+ }
965
+ }
966
+
967
+ // clang-format off
968
+ //
969
+ // Note [Audio Decoding Design]
970
+ // This note explains why audio decoding is implemented the way it is, and why
971
+ // it inherently differs from video decoding.
972
+ //
973
+ // Like for video, FFmpeg exposes the concept of a frame for audio streams. An
974
+ // audio frame is a contiguous sequence of samples, where a sample consists of
975
+ // `numChannels` values. An audio frame, or a sequence thereof, is always
976
+ // converted into a tensor of shape `(numChannels, numSamplesPerChannel)`.
977
+ //
978
+ // The notion of 'frame' in audio isn't what users want to interact with.
979
+ // Users want to interact with samples. The C++ and core APIs return frames,
980
+ // because we want those to be close to FFmpeg concepts, but the higher-level
981
+ // public APIs expose samples. As a result:
982
+ // - We don't expose index-based APIs for audio, because that would mean
983
+ // exposing the concept of audio frame. For now, we think exposing
984
+ // time-based APIs is more natural.
985
+ // - We never perform a scan for audio streams. We don't need to, since we
986
+ // won't be converting timestamps to indices. That's why we enforce the
987
+ // seek_mode to be "approximate" (which is slightly misleading, because
988
+ // technically the output samples will be at their exact positions. But
989
+ // this incongruence is only exposed at the C++/core private levels).
990
+ //
991
+ // Audio frames are of variable dimensions: in the same stream, a frame can
992
+ // contain 1024 samples and the next one may contain 512 [1]. This makes it
993
+ // impossible to stack audio frames in the same way we can stack video frames.
994
+ // This is one of the main reasons we cannot reuse the same pre-allocation
995
+ // logic we have for videos in getFramesPlayedInRange(): pre-allocating a
996
+ // batch requires constant (and known) frame dimensions. That's also why
997
+ // *concatenated* along the samples dimension, not stacked.
998
+ //
999
+ // Note [Audio pre-roll and post-roll]
1000
+ //
1001
+ // get_samples_played_in_range(a, b) decodes more than [a, b):
1002
+ // target_preroll_seconds before a, and target_postroll_seconds after b, which
1003
+ // the Python layer then trims off. Two independent data dependencies need this
1004
+ // extra margin:
1005
+ //
1006
+ // 1. The codec. Most lossy codecs (AAC, MP3, Vorbis, AC-3...) use MDCT with
1007
+ // overlap-add the output of frame i depends on state accumulated from frame
1008
+ // i-1, sometimes earlier. avcodec_flush_buffers() empties it on a seek, so the
1009
+ // first frames decoded after one come out wrong. Decoding k_num_preroll_frames
1010
+ // frames before the target primes it back - libmpg123 calls these
1011
+ // "ignoreframes" [1][2] and defaults to 4, which is where our 4 comes from. 1
1012
+ // is believed to be enough for aac, vorbis and mp3. If frame_size is unknown we
1013
+ // fall back to k_fallback_preroll_seconds. Lossless codecs don't need such a
1014
+ // pre-roll, so we avoid it for those.
1015
+ //
1016
+ // 2. The resampler, when resampling. It is an interpolation filter: the sample
1017
+ // it emits at a given instant is a weighted sum of the input samples on both
1018
+ // sides of it. That is a data dependency of its own, and it holds whether or
1019
+ // not the codec has one. On top of it, a freshly created resampler skips up to
1020
+ // num_samples_to_skip input samples to land on the grid, see [Audio resampling
1021
+ // and frame alignment]. So it needs:
1022
+ //
1023
+ // before a: num_samples_to_skip + filter_length input samples
1024
+ // after b: filter_length input samples
1025
+ //
1026
+ // where filter_length is computed like in FFmpeg [3]. To be on the safe side,
1027
+ // we actually use 2 * filter_length.
1028
+ //
1029
+ // Typical values look like:
1030
+ //
1031
+ // isr -> osr num_samples_to_skip filter_length target_preroll_seconds
1032
+ // 24000 -> 16000 3 50 102 smp = 4.25 ms
1033
+ // 44100 -> 16000 441 91 622 smp = 14.10 ms
1034
+ // 44100 -> 8000 441 182 804 smp = 18.23 ms
1035
+ // 44100 -> 16001 44100 91 44281 smp = 1004.10 ms
1036
+ //
1037
+ // Note that at worst, we need to preroll ~1s worth of samples: by definition,
1038
+ // the input and output sample rates align every second.
1039
+ //
1040
+ // target_preroll_seconds is the max of the two: the preroll needed by the
1041
+ // codec, and the preroll needed by the resampler.
1042
+ //
1043
+ // [1]
1044
+ // https://github.com/gypified/libmpg123/blob/8cbf2faf994bd999ce2b45869093bd61ecf8416f/src/libmpg123/frame.c#L884-L894
1045
+ // [2]
1046
+ // https://github.com/gypified/libmpg123/blob/8cbf2faf994bd999ce2b45869093bd61ecf8416f/src/libmpg123/libmpg123.c#L586
1047
+ // [3] https://github.com/FFmpeg/FFmpeg/blob/844e10e1a74929c27dfe0aac1c34e92bb6edbf5a/libswresample/resample.c#L188-L193
1048
+ //
1049
+ // clang-format on
1050
+ AudioFramesOutput SingleStreamDecoder::get_frames_played_in_range_audio(
1051
+ double start_seconds,
1052
+ std::optional<double> stop_seconds_optional) {
1053
+ validate_active_stream(AVMEDIA_TYPE_AUDIO);
1054
+
1055
+ if (stop_seconds_optional.has_value()) {
1056
+ STD_TORCH_CHECK(
1057
+ start_seconds <= *stop_seconds_optional,
1058
+ "Start seconds (" + std::to_string(start_seconds) +
1059
+ ") must be less than or equal to stop seconds (" +
1060
+ std::to_string(*stop_seconds_optional) + ").");
1061
+ }
1062
+
1063
+ StreamInfo& stream_info = stream_infos_[active_stream_index_];
1064
+
1065
+ if (stop_seconds_optional.has_value() &&
1066
+ start_seconds == *stop_seconds_optional) {
1067
+ // For consistency with video
1068
+ int num_channels = stream_info.audio_stream_options.num_channels.value_or(
1069
+ get_num_channels(stream_info.codec_context));
1070
+ return AudioFramesOutput{torch::stable::empty({num_channels, 0}), 0.0};
1071
+ }
1072
+
1073
+ // We must figure out if we need to seek, and where to. The following figures
1074
+ // out the value of target_preroll_seconds. See the [Audio pre-roll and
1075
+ // post-roll] note.
1076
+ // Codec pre-roll
1077
+ static constexpr int k_num_preroll_frames = 4;
1078
+ static constexpr double k_fallback_preroll_seconds = 1.0;
1079
+ int src_sample_rate = stream_info.codec_context->sample_rate;
1080
+ int frame_size = stream_info.codec_context->frame_size;
1081
+
1082
+ const AVCodecDescriptor* codec_descriptor =
1083
+ avcodec_descriptor_get(stream_info.codec_context->codec_id);
1084
+ bool is_lossless = codec_descriptor != nullptr &&
1085
+ (codec_descriptor->props & AV_CODEC_PROP_LOSSLESS) != 0;
1086
+
1087
+ double target_preroll_seconds;
1088
+ double target_postroll_seconds = 0.0;
1089
+ if (is_lossless) {
1090
+ target_preroll_seconds = 0.0;
1091
+ } else if (frame_size > 0) {
1092
+ target_preroll_seconds = static_cast<double>(k_num_preroll_frames) *
1093
+ frame_size / src_sample_rate;
1094
+ } else {
1095
+ target_preroll_seconds = k_fallback_preroll_seconds;
1096
+ }
1097
+
1098
+ // Resampler pre-roll
1099
+ int out_sample_rate =
1100
+ stream_info.audio_stream_options.sample_rate.value_or(src_sample_rate);
1101
+ bool is_resampling = out_sample_rate != src_sample_rate;
1102
+ if (is_resampling) {
1103
+ // See
1104
+ // https://github.com/FFmpeg/FFmpeg/blob/844e10e1a74929c27dfe0aac1c34e92bb6edbf5a/libswresample/resample.c#L188-L193
1105
+ // for constants, and the note mentioned above.
1106
+ static constexpr int k_swr_filter_size = 32;
1107
+ static constexpr double k_swr_cutoff = 0.97;
1108
+ double factor =
1109
+ std::min(1.0, out_sample_rate * k_swr_cutoff / src_sample_rate);
1110
+ double filter_length = std::ceil(k_swr_filter_size / factor);
1111
+ // alignment is k in the [Audio resampling and frame alignment] note,
1112
+ // alignment - 1 bounds num_samples_to_skip so it's safe to use in our
1113
+ // preroll calculation.
1114
+ int64_t alignment =
1115
+ src_sample_rate / std::gcd(src_sample_rate, out_sample_rate);
1116
+
1117
+ // double filter length to be safe.
1118
+ target_preroll_seconds = std::max(
1119
+ target_preroll_seconds,
1120
+ (alignment - 1 + 2 * filter_length) / src_sample_rate);
1121
+
1122
+ target_postroll_seconds = 2 * filter_length / src_sample_rate;
1123
+ }
1124
+ // The time base can be much coarser than a sample (1ms in Matroska), so
1125
+ // start_seconds and stop_seconds are never converted to their closest pts:
1126
+ // that could exclude the frames containing them. Frames are selected by
1127
+ // comparing their bounds in seconds instead. The seek target is rounded down:
1128
+ // seeking a bit early only decodes an extra frame.
1129
+ const AVRational& time_base = stream_info.time_base;
1130
+ double seek_seconds = start_seconds - target_preroll_seconds;
1131
+ auto target_seek_pts = static_cast<int64_t>(
1132
+ std::floor(seek_seconds * time_base.den / time_base.num));
1133
+
1134
+ int64_t min_pts = stream_info.stream->start_time != AV_NOPTS_VALUE
1135
+ ? stream_info.stream->start_time
1136
+ : 0;
1137
+
1138
+ bool needs_seek;
1139
+ if (last_decoded_av_frame_pts_ == INT64_MIN) {
1140
+ // Fresh decoder: in theory we'd always seek, but we can't because seeking
1141
+ // to INT64_MIN (the priming-packet path below) fails on some formats like
1142
+ // FLAC, see test_fresh_decoder_seek
1143
+ needs_seek = target_seek_pts > min_pts;
1144
+ } else {
1145
+ auto current_end = last_decoded_av_frame_end_pts();
1146
+ // We seek if we need to go backwards, or if the target is far enough
1147
+ // forward that decoding every intermediate frame would be wasteful.
1148
+ needs_seek = start_seconds < pts_to_seconds(current_end, time_base) ||
1149
+ target_seek_pts > current_end;
1150
+ }
1151
+
1152
+ if (needs_seek) {
1153
+ if (target_seek_pts <= min_pts) {
1154
+ // Edge case: when seeking to the very beginning of the stream, there
1155
+ // are no earlier frames to use as preroll. In that case we seek with
1156
+ // INT64_MIN, which lets the demuxer land on the true first packet
1157
+ // (including any priming packets with negative PTS, such as the AAC
1158
+ // priming frame). Not super clear why this is needed, but we have tests
1159
+ // that fail without this.
1160
+ set_cursor(INT64_MIN);
1161
+ } else {
1162
+ set_cursor(target_seek_pts);
1163
+ }
1164
+ }
1165
+
1166
+ // TODO-AUDIO Pre-allocate a long-enough tensor instead of creating a vec +
1167
+ // cat(). This would save a copy. We know the duration of the output and the
1168
+ // sample rate, so in theory we know the number of output samples.
1169
+ std::vector<torch::stable::Tensor> frames;
1170
+
1171
+ std::optional<double> first_frame_pts_seconds = std::nullopt;
1172
+
1173
+ // When resampling, we must send the prerolled and postrolled frames through
1174
+ // the resampler!
1175
+ double output_start_seconds = is_resampling ? seek_seconds : start_seconds;
1176
+ double output_stop_seconds = stop_seconds_optional.has_value()
1177
+ ? *stop_seconds_optional + target_postroll_seconds
1178
+ : std::numeric_limits<double>::infinity();
1179
+
1180
+ auto finished = false;
1181
+ while (!finished) {
1182
+ try {
1183
+ UniqueAVFrame av_frame = decode_av_frame(
1184
+ [output_start_seconds, output_stop_seconds, &time_base](
1185
+ const AVFrame& av_frame) {
1186
+ int64_t pts = get_pts_or_dts(av_frame);
1187
+ return output_start_seconds <
1188
+ pts_to_seconds(pts + get_duration(av_frame), time_base) &&
1189
+ output_stop_seconds > pts_to_seconds(pts, time_base);
1190
+ });
1191
+ auto frame_output = convert_av_frame_to_frame_output(*av_frame);
1192
+ if (!first_frame_pts_seconds.has_value()) {
1193
+ first_frame_pts_seconds = frame_output.pts_seconds;
1194
+ }
1195
+ frames.push_back(frame_output.data);
1196
+ } catch (const EndOfFileException&) {
1197
+ finished = true;
1198
+ }
1199
+
1200
+ // We're done once output_stop_seconds falls within the last decoded frame,
1201
+ // bounds
1202
+ // included. Excluding the upper bound would look more natural, but when
1203
+ // output_stop_seconds lands exactly on a frame boundary we'd keep going:
1204
+ // the frame starting there is rejected by the pts filter above, as is
1205
+ // every frame after it, so we'd decode to EOF for the same output.
1206
+
1207
+ finished |= pts_to_seconds(last_decoded_av_frame_pts_, time_base) <=
1208
+ output_stop_seconds &&
1209
+ output_stop_seconds <=
1210
+ pts_to_seconds(last_decoded_av_frame_end_pts(), time_base);
1211
+ }
1212
+
1213
+ auto last_samples = device_interface_->maybe_flush_audio_buffers();
1214
+ if (last_samples.has_value()) {
1215
+ frames.push_back(*last_samples);
1216
+ }
1217
+
1218
+ STD_TORCH_CHECK(
1219
+ frames.size() > 0 && first_frame_pts_seconds.has_value(),
1220
+ "No audio frames were decoded. ",
1221
+ "This is probably because start_seconds is too high(",
1222
+ start_seconds,
1223
+ "),",
1224
+ "or because stop_seconds(",
1225
+ stop_seconds_optional.has_value() ? std::to_string(*stop_seconds_optional)
1226
+ : "nullopt",
1227
+ ") is too low.");
1228
+
1229
+ return AudioFramesOutput{stable_cat(frames, 1), *first_frame_pts_seconds};
1230
+ }
1231
+
1232
+ // --------------------------------------------------------------------------
1233
+ // SEEKING APIs
1234
+ // --------------------------------------------------------------------------
1235
+
1236
+ void SingleStreamDecoder::set_cursor_pts_in_seconds(double seconds) {
1237
+ // Audio seeking is handled internally by getFramesPlayedInRangeAudio()
1238
+ // with preroll, see [Audio pre-roll and post-roll].
1239
+ validate_active_stream(AVMEDIA_TYPE_VIDEO);
1240
+ set_cursor(seconds_to_closest_pts(
1241
+ seconds, stream_infos_[active_stream_index_].time_base));
1242
+ }
1243
+
1244
+ void SingleStreamDecoder::set_cursor(int64_t pts) {
1245
+ cursor_was_just_set_ = true;
1246
+ cursor_ = pts;
1247
+ }
1248
+
1249
+ int64_t SingleStreamDecoder::last_decoded_av_frame_end_pts() const {
1250
+ return last_decoded_av_frame_pts_ + last_decoded_av_frame_duration_;
1251
+ }
1252
+
1253
+ bool SingleStreamDecoder::can_we_avoid_seeking() const {
1254
+ // Returns true if we can avoid seeking in the AVFormatContext based on
1255
+ // heuristics that rely on the target cursor_ and the last decoded frame.
1256
+ // Seeking is expensive, so we try to avoid it when possible.
1257
+ const StreamInfo& stream_info = stream_infos_.at(active_stream_index_);
1258
+ if (stream_info.av_media_type == AVMEDIA_TYPE_AUDIO) {
1259
+ // For audio, seeking is handled internally by
1260
+ // getFramesPlayedInRangeAudio(). See [Audio pre-roll and post-roll].
1261
+ return !cursor_was_just_set_;
1262
+ } else if (!cursor_was_just_set_) {
1263
+ // For videos, when decoding consecutive frames, we don't need to seek.
1264
+ return true;
1265
+ }
1266
+
1267
+ if (cursor_ < last_decoded_av_frame_pts_) {
1268
+ // We can never skip a seek if we are seeking backwards.
1269
+ return false;
1270
+ }
1271
+ if (last_decoded_av_frame_pts_ == cursor_) {
1272
+ // We are seeking to the exact same frame as we are currently at. Without
1273
+ // caching we have to rewind back and decode the frame again.
1274
+ return false;
1275
+ }
1276
+ if (cursor_ <= last_decoded_av_frame_end_pts()) {
1277
+ // The target is the frame right after the last decoded one, i.e. the next
1278
+ // frame the decoder will output.
1279
+ return true;
1280
+ }
1281
+ // We are seeking forward, from the current frame x (lastDecodedAvFramePts_)
1282
+ // to a target frame y (cursor_). Seeking means jumping to the last keyframe
1283
+ // before y, which we call j:
1284
+ //
1285
+ // .........x...............j...............y.......
1286
+ // ^ ^ ^
1287
+ // current frame keyframe we'd frame we
1288
+ // (last decoded) seek to want
1289
+ //
1290
+ // Whether seeking is worth it depends on how far j is from x. Seeking flushes
1291
+ // the decoder, which throws away the `has_b_frames` frames already sitting in
1292
+ // the reorder buffer plus the `thread_count - 1` frames in flight in the
1293
+ // threading pipeline -- exactly the frames we'd decode next anyway. So we
1294
+ // only seek if j is beyond them, i.e. if decoding straight through would cost
1295
+ // more than the flush:
1296
+ //
1297
+ // seek iff (j - x) > has_b_frames + thread_count - 1
1298
+ //
1299
+ // (the thread_count term only applies to CPU decoding and to FRAME threading,
1300
+ // see below.)
1301
+ // See https://github.com/meta-pytorch/torchcodec/issues/1488 for details.
1302
+
1303
+ // These "identifiers" only let us tell whether x and y share the same
1304
+ // keyframe. They are not necessarily frame indices (see
1305
+ // getKeyFrameIdentifier()), so we use them for equality only, not for the
1306
+ // (j - x) distance below.
1307
+ int last_key_frame_id = get_key_frame_identifier(last_decoded_av_frame_pts_);
1308
+ int target_key_frame_id = get_key_frame_identifier(cursor_);
1309
+ if (last_key_frame_id < 0 || target_key_frame_id < 0) {
1310
+ return false;
1311
+ }
1312
+ if (last_key_frame_id == target_key_frame_id) {
1313
+ // x and y share the same keyframe (as in `...j...x...y`): seeking would go
1314
+ // backwards to j and re-decode up to x, landing us back where we are.
1315
+ return true;
1316
+ }
1317
+
1318
+ // x
1319
+ int64_t last_decoded_frame_index = seconds_to_index_lower_bound(
1320
+ pts_to_seconds(last_decoded_av_frame_pts_, stream_info.time_base));
1321
+
1322
+ // j
1323
+ int64_t target_key_frame_index;
1324
+ if (!stream_info.key_frames.empty()) {
1325
+ // exact and custom_frame_mappings modes: getKeyFrameIdentifier() returned
1326
+ // getKeyFrameIndexForPtsUsingScannedIndex() for these modes, so
1327
+ // targetKeyFrameId is already the position of j in the scanned keyFrames
1328
+ // vector.
1329
+ target_key_frame_index =
1330
+ stream_info.key_frames[target_key_frame_id].frame_index;
1331
+ } else {
1332
+ // approximate mode: keyFrames is empty, so we can't locate j. We use y
1333
+ // instead. This makes the heuristic more conservative, i.e. err towards
1334
+ // seeking even more, which is safe.
1335
+ target_key_frame_index = seconds_to_index_lower_bound(
1336
+ pts_to_seconds(cursor_, stream_info.time_base));
1337
+ }
1338
+
1339
+ int64_t frame_reorder_buffer_size =
1340
+ std::max(stream_info.codec_context->has_b_frames, 0);
1341
+
1342
+ // The reorder buffer (has_b_frames) is a codec property that applies
1343
+ // in all scenarios, but the `thread_count - 1` in-flight frames only exist
1344
+ // with FFmpeg FRAME threading, in the CPU decoding path. On other devices
1345
+ // (e.g. CUDA) decoding doesn't depend on thread_count, and with SLICE
1346
+ // threading the threads cooperate on a single frame rather than pipelining
1347
+ // several frames. Note that FRAME threading is the default across the vast
1348
+ // majority of codecs, so our check is just to be on the safe side.
1349
+ int64_t in_flight_frames = 0;
1350
+ if (stream_info.video_stream_options.device == kStableCPU &&
1351
+ (stream_info.codec_context->active_thread_type & FF_THREAD_FRAME)) {
1352
+ in_flight_frames = std::max(stream_info.codec_context->thread_count, 1) - 1;
1353
+ }
1354
+ return (target_key_frame_index - last_decoded_frame_index) <=
1355
+ frame_reorder_buffer_size + in_flight_frames;
1356
+ }
1357
+
1358
+ // This method looks at currentPts and desiredPts and seeks in the
1359
+ // AVFormatContext if it is needed. We can skip seeking in certain cases. See
1360
+ // the comment of canWeAvoidSeeking() for details.
1361
+ // Returns true iff we seeked.
1362
+ bool SingleStreamDecoder::maybe_seek_to_before_desired_pts() {
1363
+ validate_active_stream();
1364
+ StreamInfo& stream_info = stream_infos_[active_stream_index_];
1365
+
1366
+ decode_stats_.num_seeks_attempted++;
1367
+ if (can_we_avoid_seeking()) {
1368
+ decode_stats_.num_seeks_skipped++;
1369
+ return false;
1370
+ }
1371
+
1372
+ int64_t desired_pts = cursor_;
1373
+
1374
+ // For some encodings like H265, FFMPEG sometimes seeks past the point we
1375
+ // set as the max_ts. So we use our own index to give it the exact pts of
1376
+ // the key frame that we want to seek to.
1377
+ // See https://github.com/pytorch/torchcodec/issues/179 for more details.
1378
+ // See https://trac.ffmpeg.org/ticket/11137 for the underlying ffmpeg bug.
1379
+ if (!stream_info.key_frames.empty()) {
1380
+ int desired_key_frame_index =
1381
+ get_key_frame_index_for_pts_using_scanned_index(
1382
+ stream_info.key_frames, desired_pts);
1383
+ if (desired_key_frame_index >= 0) {
1384
+ desired_pts = stream_info.key_frames[desired_key_frame_index].pts;
1385
+ }
1386
+ // Otherwise the target precedes the first *scanned* keyframe. This happens
1387
+ // when the keyframe needed to decode the target was discarded / trimmed by
1388
+ // an edit list (AV_PKT_FLAG_DISCARD) and thus not recorded in our index. We
1389
+ // leave desired_pts as the target pts and let FFmpeg seek to the preceding
1390
+ // keyframe itself (same as approximate mode, which has no scanned index).
1391
+ }
1392
+
1393
+ int status = avformat_seek_file(
1394
+ format_context_.get(),
1395
+ stream_info.stream_index,
1396
+ INT64_MIN,
1397
+ desired_pts,
1398
+ desired_pts,
1399
+ 0);
1400
+ STD_TORCH_CHECK(
1401
+ status >= 0,
1402
+ get_seek_error_message(format_context_.get(), desired_pts, status));
1403
+
1404
+ decode_stats_.num_flushes++;
1405
+ device_interface_->flush();
1406
+ audio_pts_extrapolator_.reset();
1407
+ return true;
1408
+ }
1409
+
1410
+ // --------------------------------------------------------------------------
1411
+ // LOW-LEVEL DECODING
1412
+ // --------------------------------------------------------------------------
1413
+
1414
+ UniqueAVFrame SingleStreamDecoder::decode_av_frame(
1415
+ std::function<bool(const AVFrame&)> filter_function) {
1416
+ validate_active_stream();
1417
+
1418
+ reset_decode_stats();
1419
+
1420
+ bool seeked = maybe_seek_to_before_desired_pts();
1421
+ cursor_was_just_set_ = false;
1422
+
1423
+ // See below where it's used
1424
+ bool packet_data_may_be_misaligned = seeked && is_mpeg_ps_;
1425
+
1426
+ UniqueAVFrame av_frame(av_frame_alloc());
1427
+ AutoAVPacket auto_av_packet;
1428
+ int status = AVSUCCESS;
1429
+ bool reached_eof = false;
1430
+
1431
+ // The default implementation uses avcodec_receive_frame and
1432
+ // avcodec_send_packet, while specialized interfaces can override for
1433
+ // hardware-specific optimizations.
1434
+ while (true) {
1435
+ status = device_interface_->receive_frame(av_frame);
1436
+
1437
+ if (status != AVSUCCESS && status != AVERROR(EAGAIN)) {
1438
+ // Non-retriable error
1439
+ break;
1440
+ }
1441
+
1442
+ decode_stats_.num_frames_received_by_decoder++;
1443
+ if (status == AVSUCCESS &&
1444
+ stream_infos_[active_stream_index_].av_media_type ==
1445
+ AVMEDIA_TYPE_AUDIO) {
1446
+ audio_pts_extrapolator_.process(*av_frame);
1447
+ }
1448
+ // Is this the kind of frame we're looking for?
1449
+ if (status == AVSUCCESS && filter_function(*av_frame)) {
1450
+ // Yes, this is the frame we'll return; break out of the decoding loop.
1451
+ break;
1452
+ } else if (status == AVSUCCESS) {
1453
+ // No, but we received a valid frame - just not the kind we're looking
1454
+ // for. The logic below will read packets and send them to the decoder.
1455
+ // But since we did just receive a frame, we should skip reading more
1456
+ // packets and sending them to the decoder and just try to receive more
1457
+ // frames from the decoder.
1458
+ continue;
1459
+ }
1460
+
1461
+ if (reached_eof) {
1462
+ // We don't have any more packets to receive. So keep on pulling frames
1463
+ // from decoder's internal buffers.
1464
+ continue;
1465
+ }
1466
+
1467
+ // We still haven't found the frame we're looking for. So let's read more
1468
+ // packets and send them to the decoder. (read_next_packet is shared with
1469
+ // the Demuxer building block.)
1470
+ ReferenceAVPacket packet(auto_av_packet);
1471
+ status =
1472
+ read_next_packet(format_context_.get(), active_stream_index_, *packet);
1473
+ decode_stats_.num_packets_read++;
1474
+
1475
+ if (status == AVERROR_EOF) {
1476
+ // End of file reached. We must drain the decoder
1477
+ status = device_interface_->send_eof_packet();
1478
+ STD_TORCH_CHECK(
1479
+ status >= AVSUCCESS,
1480
+ "Could not flush decoder: ",
1481
+ get_ffmpeg_error_string_from_error_code(status));
1482
+
1483
+ reached_eof = true;
1484
+ } else {
1485
+ STD_TORCH_CHECK(
1486
+ status >= AVSUCCESS,
1487
+ "Could not read frame from input file: ",
1488
+ get_ffmpeg_error_string_from_error_code(status));
1489
+ }
1490
+
1491
+ if (reached_eof) {
1492
+ // We don't have any more packets to send to the decoder. So keep on
1493
+ // pulling frames from its internal buffers.
1494
+ continue;
1495
+ }
1496
+
1497
+ // We got a valid packet. Send it to the decoder, and we'll receive it in
1498
+ // the next iteration.
1499
+ status = device_interface_->send_packet(*packet);
1500
+
1501
+ if (status == AVERROR_INVALIDDATA && packet_data_may_be_misaligned) {
1502
+ // The MPEG-PS demuxer doesn't return proper packets just after a seek, so
1503
+ // we skip (potentially more than one) packets until we find a valid one.
1504
+ // We *only* do this for MPEG-PS, not for other demuxers. It is
1505
+ // unfortunate that we need a format-specific condition in this generic
1506
+ // decoding loop.
1507
+ continue;
1508
+ }
1509
+ STD_TORCH_CHECK(
1510
+ status >= AVSUCCESS,
1511
+ "Could not push packet to decoder: ",
1512
+ get_ffmpeg_error_string_from_error_code(status));
1513
+ // The decoder accepted a packet, so we're aligned again: from now on
1514
+ // invalid data means the file is corrupt, and we want to report it.
1515
+ packet_data_may_be_misaligned = false;
1516
+
1517
+ decode_stats_.num_packets_sent_to_decoder++;
1518
+ }
1519
+
1520
+ if (status < AVSUCCESS) {
1521
+ if (reached_eof || status == AVERROR_EOF) {
1522
+ throw SingleStreamDecoder::EndOfFileException(
1523
+ "Requested next frame while there are no more frames left to "
1524
+ "decode.");
1525
+ }
1526
+ STD_TORCH_CHECK(
1527
+ false,
1528
+ "Could not receive frame from decoder: ",
1529
+ get_ffmpeg_error_string_from_error_code(status));
1530
+ }
1531
+
1532
+ // Note that we don't flush the decoder when we reach EOF (even though
1533
+ // that's mentioned in
1534
+ // https://ffmpeg.org/doxygen/trunk/group__lavc__encdec.html). This is
1535
+ // because we may have packets internally in the decoder that we haven't
1536
+ // received as frames. Eventually we will either hit AVERROR_EOF from
1537
+ // av_receive_frame() or the user will have seeked to a different location
1538
+ // in the file and that will flush the decoder.
1539
+ last_decoded_av_frame_pts_ = get_pts_or_dts(*av_frame);
1540
+ last_decoded_av_frame_duration_ = get_duration(*av_frame);
1541
+
1542
+ return av_frame;
1543
+ }
1544
+
1545
+ // --------------------------------------------------------------------------
1546
+ // AVFRAME <-> FRAME OUTPUT CONVERSION
1547
+ // --------------------------------------------------------------------------
1548
+
1549
+ FrameOutput SingleStreamDecoder::convert_av_frame_to_frame_output(
1550
+ const AVFrame& av_frame,
1551
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor) {
1552
+ // Convert the frame to tensor.
1553
+ FrameOutput frame_output;
1554
+ frame_output.pts_seconds = pts_to_seconds(
1555
+ get_pts_or_dts(av_frame),
1556
+ format_context_->streams[active_stream_index_]->time_base);
1557
+ frame_output.duration_seconds = pts_to_seconds(
1558
+ get_duration(av_frame),
1559
+ format_context_->streams[active_stream_index_]->time_base);
1560
+ device_interface_->convert_av_frame_to_frame_output(
1561
+ av_frame, frame_output, std::move(pre_allocated_output_tensor));
1562
+ return frame_output;
1563
+ }
1564
+
1565
+ // --------------------------------------------------------------------------
1566
+ // OUTPUT ALLOCATION AND SHAPE CONVERSION
1567
+ // --------------------------------------------------------------------------
1568
+
1569
+ torch::stable::Tensor SingleStreamDecoder::maybe_permute_and_convert_dtype(
1570
+ torch::stable::Tensor& hwc_tensor) {
1571
+ // Permute HWC to CHW if needed. Returns a view of the input tensor, the
1572
+ // leading batch-dimension [N] is optional i.e. the input tensor can be 3D or
1573
+ // 4D.
1574
+ torch::stable::Tensor tensor = hwc_tensor;
1575
+ if (stream_infos_[active_stream_index_]
1576
+ .video_stream_options.dimension_order != "NHWC") {
1577
+ auto num_dimensions = hwc_tensor.dim();
1578
+ auto shape = hwc_tensor.sizes();
1579
+ if (num_dimensions == 3) {
1580
+ STD_TORCH_CHECK(
1581
+ shape[2] == 3, "Not a HWC tensor: ", int_array_ref_to_string(shape));
1582
+ tensor = stable_permute(hwc_tensor, {2, 0, 1});
1583
+ } else if (num_dimensions == 4) {
1584
+ STD_TORCH_CHECK(
1585
+ shape[3] == 3, "Not a NHWC tensor: ", int_array_ref_to_string(shape));
1586
+ tensor = stable_permute(hwc_tensor, {0, 3, 1, 2});
1587
+ } else {
1588
+ STD_TORCH_CHECK(
1589
+ false,
1590
+ "Expected tensor with 3 or 4 dimensions, got ",
1591
+ num_dimensions);
1592
+ }
1593
+ }
1594
+
1595
+ return convert_to_output_dtype(
1596
+ tensor,
1597
+ stream_infos_[active_stream_index_].video_stream_options.output_dtype);
1598
+ }
1599
+
1600
+ // --------------------------------------------------------------------------
1601
+ // PTS <-> INDEX CONVERSIONS
1602
+ // --------------------------------------------------------------------------
1603
+
1604
+ int SingleStreamDecoder::get_key_frame_identifier(int64_t pts) const {
1605
+ // This function "identifies" a key frame for a given pts value.
1606
+ // We use the term "identifier" rather than "index" because the nature of the
1607
+ // index that is returned depends on various factors:
1608
+ // - If seek_mode is exact, we return the index of the key frame in the
1609
+ // scanned key-frame vector (stream_info.keyFrames). So the returned value
1610
+ // is in [0, num_key_frames).
1611
+ // - If seek_mode is approximate, we use av_index_search_timestamp() which
1612
+ // may return a value in [0, num_key_frames) like for mkv, but also a value
1613
+ // in [0, num_frames) like for mp4. It really depends on the container.
1614
+ //
1615
+ // The range of the "identifier" doesn't matter that much, for now we only
1616
+ // use it to uniquely identify a key frame in canWeAvoidSeeking().
1617
+ const StreamInfo& stream_info = stream_infos_.at(active_stream_index_);
1618
+ if (stream_info.key_frames.empty()) {
1619
+ return av_index_search_timestamp(
1620
+ stream_info.stream, pts, AVSEEK_FLAG_BACKWARD);
1621
+ } else {
1622
+ return get_key_frame_index_for_pts_using_scanned_index(
1623
+ stream_info.key_frames, pts);
1624
+ }
1625
+ }
1626
+
1627
+ int SingleStreamDecoder::get_key_frame_index_for_pts_using_scanned_index(
1628
+ const std::vector<SingleStreamDecoder::FrameInfo>& key_frames,
1629
+ int64_t pts) const {
1630
+ auto upper_bound = std::upper_bound(
1631
+ key_frames.begin(),
1632
+ key_frames.end(),
1633
+ pts,
1634
+ [](int64_t pts, const SingleStreamDecoder::FrameInfo& frame_info) {
1635
+ return pts < frame_info.pts;
1636
+ });
1637
+ if (upper_bound == key_frames.begin()) {
1638
+ return -1;
1639
+ }
1640
+ return upper_bound - 1 - key_frames.begin();
1641
+ }
1642
+
1643
+ int64_t SingleStreamDecoder::seconds_to_index_lower_bound(
1644
+ double seconds) const {
1645
+ const auto& stream_info = stream_infos_.at(active_stream_index_);
1646
+ switch (seek_mode_) {
1647
+ case SeekMode::custom_frame_mappings:
1648
+ case SeekMode::exact: {
1649
+ auto frame = std::lower_bound(
1650
+ stream_info.all_frames.begin(),
1651
+ stream_info.all_frames.end(),
1652
+ seconds,
1653
+ [&stream_info](const FrameInfo& info, double start) {
1654
+ return pts_to_seconds(info.next_pts, stream_info.time_base) <=
1655
+ start;
1656
+ });
1657
+
1658
+ return frame - stream_info.all_frames.begin();
1659
+ }
1660
+ case SeekMode::approximate: {
1661
+ auto& stream_metadata =
1662
+ container_metadata_.all_stream_metadata[active_stream_index_];
1663
+ STD_TORCH_CHECK(
1664
+ stream_metadata.average_fps_from_header.has_value(),
1665
+ "Cannot use approximate mode since we couldn't find the average fps from the metadata.");
1666
+ double begin_seconds =
1667
+ stream_metadata.get_begin_stream_seconds(seek_mode_);
1668
+ double relative_seconds = seconds - begin_seconds;
1669
+ return std::floor(
1670
+ relative_seconds * stream_metadata.average_fps_from_header.value());
1671
+ }
1672
+ default:
1673
+ STD_TORCH_CHECK(false, "Unknown SeekMode");
1674
+ }
1675
+ }
1676
+
1677
+ int64_t SingleStreamDecoder::seconds_to_index_upper_bound(double seconds) {
1678
+ auto& stream_info = stream_infos_[active_stream_index_];
1679
+ switch (seek_mode_) {
1680
+ case SeekMode::custom_frame_mappings:
1681
+ case SeekMode::exact: {
1682
+ auto frame = std::upper_bound(
1683
+ stream_info.all_frames.begin(),
1684
+ stream_info.all_frames.end(),
1685
+ seconds,
1686
+ [&stream_info](double stop, const FrameInfo& info) {
1687
+ return stop <= pts_to_seconds(info.pts, stream_info.time_base);
1688
+ });
1689
+
1690
+ return frame - stream_info.all_frames.begin();
1691
+ }
1692
+ case SeekMode::approximate: {
1693
+ auto& stream_metadata =
1694
+ container_metadata_.all_stream_metadata[active_stream_index_];
1695
+ STD_TORCH_CHECK(
1696
+ stream_metadata.average_fps_from_header.has_value(),
1697
+ "Cannot use approximate mode since we couldn't find the average fps from the metadata.");
1698
+ double begin_seconds =
1699
+ stream_metadata.get_begin_stream_seconds(seek_mode_);
1700
+ double relative_seconds = seconds - begin_seconds;
1701
+ return std::ceil(
1702
+ relative_seconds * stream_metadata.average_fps_from_header.value());
1703
+ }
1704
+ default:
1705
+ STD_TORCH_CHECK(false, "Unknown SeekMode");
1706
+ }
1707
+ }
1708
+
1709
+ int64_t SingleStreamDecoder::get_pts(int64_t frame_index) {
1710
+ auto& stream_info = stream_infos_[active_stream_index_];
1711
+ switch (seek_mode_) {
1712
+ case SeekMode::custom_frame_mappings:
1713
+ case SeekMode::exact:
1714
+ return stream_info.all_frames[frame_index].pts;
1715
+ case SeekMode::approximate: {
1716
+ auto& stream_metadata =
1717
+ container_metadata_.all_stream_metadata[active_stream_index_];
1718
+ STD_TORCH_CHECK(
1719
+ stream_metadata.average_fps_from_header.has_value(),
1720
+ "Cannot use approximate mode since we couldn't find the average fps from the metadata.");
1721
+ return seconds_to_closest_pts(
1722
+ stream_metadata.get_begin_stream_seconds(seek_mode_) +
1723
+ (frame_index / stream_metadata.average_fps_from_header.value()),
1724
+ stream_info.time_base);
1725
+ }
1726
+ default:
1727
+ STD_TORCH_CHECK(false, "Unknown SeekMode");
1728
+ }
1729
+ }
1730
+
1731
+ FrameDims SingleStreamDecoder::get_output_dims() const {
1732
+ const auto& stream_metadata =
1733
+ container_metadata_.all_stream_metadata[active_stream_index_];
1734
+ Rotation rotation = rotation_from_degrees(stream_metadata.rotation);
1735
+ // If there is a rotation, then resizedOutputDims_ is necessarily non-null
1736
+ // (the rotation transform would have set it).
1737
+ if (rotation != Rotation::NONE) {
1738
+ STD_TORCH_CHECK(
1739
+ resized_output_dims_.has_value(),
1740
+ "Internal error: rotation is applied but resizedOutputDims_ is not set");
1741
+ }
1742
+ return resized_output_dims_.value_or(pre_rotation_dims_);
1743
+ }
1744
+
1745
+ // --------------------------------------------------------------------------
1746
+ // STREAM AND METADATA APIS
1747
+ // --------------------------------------------------------------------------
1748
+
1749
+ // --------------------------------------------------------------------------
1750
+ // VALIDATION UTILS
1751
+ // --------------------------------------------------------------------------
1752
+
1753
+ void SingleStreamDecoder::validate_active_stream(
1754
+ std::optional<AVMediaType> av_media_type) {
1755
+ auto error_msg =
1756
+ "Provided stream index=" + std::to_string(active_stream_index_) +
1757
+ " was not previously added.";
1758
+ STD_TORCH_CHECK(active_stream_index_ != no_active_stream_, error_msg);
1759
+ STD_TORCH_CHECK(stream_infos_.count(active_stream_index_) > 0, error_msg);
1760
+
1761
+ int all_stream_metadata_size =
1762
+ static_cast<int>(container_metadata_.all_stream_metadata.size());
1763
+ STD_TORCH_CHECK(
1764
+ active_stream_index_ >= 0 &&
1765
+ active_stream_index_ < all_stream_metadata_size,
1766
+ "Invalid stream index=" + std::to_string(active_stream_index_) +
1767
+ "; valid indices are in the range [0, " +
1768
+ std::to_string(all_stream_metadata_size) + ").");
1769
+
1770
+ if (av_media_type.has_value()) {
1771
+ STD_TORCH_CHECK(
1772
+ stream_infos_[active_stream_index_].av_media_type ==
1773
+ av_media_type.value(),
1774
+ "The method you called isn't supported. ",
1775
+ "If you're seeing this error, you are probably trying to call an ",
1776
+ "unsupported method on an audio stream.");
1777
+ }
1778
+ }
1779
+
1780
+ void SingleStreamDecoder::validate_scanned_all_streams(const std::string& msg) {
1781
+ STD_TORCH_CHECK(
1782
+ scanned_all_streams_,
1783
+ "Must scan all streams to update metadata before calling ",
1784
+ msg);
1785
+ }
1786
+
1787
+ void SingleStreamDecoder::validate_frame_index(
1788
+ const StreamMetadata& stream_metadata,
1789
+ int64_t frame_index) {
1790
+ STABLE_CHECK_INDEX(
1791
+ frame_index >= 0,
1792
+ "Invalid frame index=" + std::to_string(frame_index) +
1793
+ " for stream_index=" + std::to_string(stream_metadata.stream_index) +
1794
+ "; negative indices must have an absolute value less than the number of frames, "
1795
+ "and the number of frames must be known.");
1796
+
1797
+ // Note that if we do not have the number of frames available in our
1798
+ // metadata, then we assume that the frameIndex is valid.
1799
+ std::optional<int64_t> num_frames =
1800
+ stream_metadata.get_num_frames(seek_mode_);
1801
+ if (num_frames.has_value()) {
1802
+ STABLE_CHECK_INDEX(
1803
+ frame_index < num_frames.value(),
1804
+ "Invalid frame index=" + std::to_string(frame_index) +
1805
+ " for stream_index=" +
1806
+ std::to_string(stream_metadata.stream_index) +
1807
+ "; must be less than " + std::to_string(num_frames.value()));
1808
+ }
1809
+ }
1810
+
1811
+ // --------------------------------------------------------------------------
1812
+ // MORALLY PRIVATE UTILS
1813
+ // --------------------------------------------------------------------------
1814
+
1815
+ SingleStreamDecoder::DecodeStats SingleStreamDecoder::get_decode_stats() const {
1816
+ return decode_stats_;
1817
+ }
1818
+
1819
+ std::ostream& operator<<(
1820
+ std::ostream& os,
1821
+ const SingleStreamDecoder::DecodeStats& stats) {
1822
+ os << "DecodeStats{"
1823
+ << "numFramesReceivedByDecoder=" << stats.num_frames_received_by_decoder
1824
+ << ", numPacketsRead=" << stats.num_packets_read
1825
+ << ", numPacketsSentToDecoder=" << stats.num_packets_sent_to_decoder
1826
+ << ", numSeeksAttempted=" << stats.num_seeks_attempted
1827
+ << ", numSeeksSkipped=" << stats.num_seeks_skipped
1828
+ << ", numFlushes=" << stats.num_flushes << "}";
1829
+
1830
+ return os;
1831
+ }
1832
+
1833
+ void SingleStreamDecoder::reset_decode_stats() {
1834
+ decode_stats_ = DecodeStats{};
1835
+ }
1836
+
1837
+ double SingleStreamDecoder::get_pts_seconds_for_frame(int64_t frame_index) {
1838
+ validate_active_stream(AVMEDIA_TYPE_VIDEO);
1839
+ validate_scanned_all_streams("getPtsSecondsForFrame");
1840
+
1841
+ const auto& stream_info = stream_infos_[active_stream_index_];
1842
+ const auto& stream_metadata =
1843
+ container_metadata_.all_stream_metadata[active_stream_index_];
1844
+ validate_frame_index(stream_metadata, frame_index);
1845
+
1846
+ return pts_to_seconds(
1847
+ stream_info.all_frames[frame_index].pts, stream_info.time_base);
1848
+ }
1849
+
1850
+ std::string SingleStreamDecoder::get_device_interface_details() const {
1851
+ STD_TORCH_CHECK(
1852
+ device_interface_ != nullptr, "Device interface doesn't exist.");
1853
+ return device_interface_->get_details();
1854
+ }
1855
+
1856
+ } // namespace facebook::torchcodec