torchcodec 0.8.0__cp313-cp313-macosx_12_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

Files changed (82) hide show
  1. torchcodec/.dylibs/libc++.1.0.dylib +0 -0
  2. torchcodec/.dylibs/libpython3.13.dylib +0 -0
  3. torchcodec/__init__.py +16 -0
  4. torchcodec/_core/AVIOContextHolder.cpp +60 -0
  5. torchcodec/_core/AVIOContextHolder.h +64 -0
  6. torchcodec/_core/AVIOFileLikeContext.cpp +98 -0
  7. torchcodec/_core/AVIOFileLikeContext.h +55 -0
  8. torchcodec/_core/AVIOTensorContext.cpp +123 -0
  9. torchcodec/_core/AVIOTensorContext.h +43 -0
  10. torchcodec/_core/BetaCudaDeviceInterface.cpp +636 -0
  11. torchcodec/_core/BetaCudaDeviceInterface.h +191 -0
  12. torchcodec/_core/CMakeLists.txt +325 -0
  13. torchcodec/_core/CUDACommon.cpp +315 -0
  14. torchcodec/_core/CUDACommon.h +46 -0
  15. torchcodec/_core/Cache.h +138 -0
  16. torchcodec/_core/CpuDeviceInterface.cpp +347 -0
  17. torchcodec/_core/CpuDeviceInterface.h +132 -0
  18. torchcodec/_core/CudaDeviceInterface.cpp +357 -0
  19. torchcodec/_core/CudaDeviceInterface.h +64 -0
  20. torchcodec/_core/DeviceInterface.cpp +117 -0
  21. torchcodec/_core/DeviceInterface.h +148 -0
  22. torchcodec/_core/Encoder.cpp +807 -0
  23. torchcodec/_core/Encoder.h +173 -0
  24. torchcodec/_core/FFMPEGCommon.cpp +608 -0
  25. torchcodec/_core/FFMPEGCommon.h +245 -0
  26. torchcodec/_core/FilterGraph.cpp +149 -0
  27. torchcodec/_core/FilterGraph.h +59 -0
  28. torchcodec/_core/Frame.cpp +42 -0
  29. torchcodec/_core/Frame.h +72 -0
  30. torchcodec/_core/Metadata.h +72 -0
  31. torchcodec/_core/NVDECCache.cpp +70 -0
  32. torchcodec/_core/NVDECCache.h +104 -0
  33. torchcodec/_core/SingleStreamDecoder.cpp +1719 -0
  34. torchcodec/_core/SingleStreamDecoder.h +405 -0
  35. torchcodec/_core/StreamOptions.h +63 -0
  36. torchcodec/_core/Transform.cpp +60 -0
  37. torchcodec/_core/Transform.h +59 -0
  38. torchcodec/_core/ValidationUtils.cpp +35 -0
  39. torchcodec/_core/ValidationUtils.h +21 -0
  40. torchcodec/_core/__init__.py +41 -0
  41. torchcodec/_core/_metadata.py +317 -0
  42. torchcodec/_core/custom_ops.cpp +875 -0
  43. torchcodec/_core/fetch_and_expose_non_gpl_ffmpeg_libs.cmake +360 -0
  44. torchcodec/_core/nvcuvid_include/cuviddec.h +1374 -0
  45. torchcodec/_core/nvcuvid_include/nvcuvid.h +610 -0
  46. torchcodec/_core/ops.py +498 -0
  47. torchcodec/_core/pybind_ops.cpp +50 -0
  48. torchcodec/_frame.py +145 -0
  49. torchcodec/_internally_replaced_utils.py +67 -0
  50. torchcodec/_samplers/__init__.py +7 -0
  51. torchcodec/_samplers/video_clip_sampler.py +418 -0
  52. torchcodec/decoders/__init__.py +12 -0
  53. torchcodec/decoders/_audio_decoder.py +177 -0
  54. torchcodec/decoders/_decoder_utils.py +112 -0
  55. torchcodec/decoders/_video_decoder.py +500 -0
  56. torchcodec/encoders/__init__.py +1 -0
  57. torchcodec/encoders/_audio_encoder.py +150 -0
  58. torchcodec/libtorchcodec_core4.dylib +0 -0
  59. torchcodec/libtorchcodec_core5.dylib +0 -0
  60. torchcodec/libtorchcodec_core6.dylib +0 -0
  61. torchcodec/libtorchcodec_core7.dylib +0 -0
  62. torchcodec/libtorchcodec_core8.dylib +0 -0
  63. torchcodec/libtorchcodec_custom_ops4.dylib +0 -0
  64. torchcodec/libtorchcodec_custom_ops5.dylib +0 -0
  65. torchcodec/libtorchcodec_custom_ops6.dylib +0 -0
  66. torchcodec/libtorchcodec_custom_ops7.dylib +0 -0
  67. torchcodec/libtorchcodec_custom_ops8.dylib +0 -0
  68. torchcodec/libtorchcodec_pybind_ops4.so +0 -0
  69. torchcodec/libtorchcodec_pybind_ops5.so +0 -0
  70. torchcodec/libtorchcodec_pybind_ops6.so +0 -0
  71. torchcodec/libtorchcodec_pybind_ops7.so +0 -0
  72. torchcodec/libtorchcodec_pybind_ops8.so +0 -0
  73. torchcodec/samplers/__init__.py +2 -0
  74. torchcodec/samplers/_common.py +84 -0
  75. torchcodec/samplers/_index_based.py +287 -0
  76. torchcodec/samplers/_time_based.py +358 -0
  77. torchcodec/version.py +2 -0
  78. torchcodec-0.8.0.dist-info/METADATA +253 -0
  79. torchcodec-0.8.0.dist-info/RECORD +82 -0
  80. torchcodec-0.8.0.dist-info/WHEEL +5 -0
  81. torchcodec-0.8.0.dist-info/licenses/LICENSE +28 -0
  82. torchcodec-0.8.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,1719 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #include "src/torchcodec/_core/SingleStreamDecoder.h"
8
+ #include <cstdint>
9
+ #include <cstdio>
10
+ #include <iostream>
11
+ #include <limits>
12
+ #include <sstream>
13
+ #include <stdexcept>
14
+ #include <string_view>
15
+ #include "torch/types.h"
16
+
17
+ namespace facebook::torchcodec {
18
+ namespace {
19
+
20
+ // Some videos aren't properly encoded and do not specify pts values for
21
+ // packets, and thus for frames. Unset values correspond to INT64_MIN. When that
22
+ // happens, we fallback to the dts value which hopefully exists and is correct.
23
+ // Accessing AVFrames and AVPackets's pts values should **always** go through
24
+ // the helpers below. Then, the "pts" fields in our structs like FrameInfo.pts
25
+ // should be interpreted as "pts if it exists, dts otherwise".
26
+ int64_t getPtsOrDts(ReferenceAVPacket& packet) {
27
+ return packet->pts == INT64_MIN ? packet->dts : packet->pts;
28
+ }
29
+
30
+ int64_t getPtsOrDts(const UniqueAVFrame& avFrame) {
31
+ return avFrame->pts == INT64_MIN ? avFrame->pkt_dts : avFrame->pts;
32
+ }
33
+
34
+ } // namespace
35
+
36
+ // --------------------------------------------------------------------------
37
+ // CONSTRUCTORS, INITIALIZATION, DESTRUCTORS
38
+ // --------------------------------------------------------------------------
39
+
40
+ SingleStreamDecoder::SingleStreamDecoder(
41
+ const std::string& videoFilePath,
42
+ SeekMode seekMode)
43
+ : seekMode_(seekMode) {
44
+ setFFmpegLogLevel();
45
+
46
+ AVFormatContext* rawContext = nullptr;
47
+ int status =
48
+ avformat_open_input(&rawContext, videoFilePath.c_str(), nullptr, nullptr);
49
+ TORCH_CHECK(
50
+ status == 0,
51
+ "Could not open input file: " + videoFilePath + " " +
52
+ getFFMPEGErrorStringFromErrorCode(status));
53
+ TORCH_CHECK(rawContext != nullptr);
54
+ formatContext_.reset(rawContext);
55
+
56
+ initializeDecoder();
57
+ }
58
+
59
+ SingleStreamDecoder::SingleStreamDecoder(
60
+ std::unique_ptr<AVIOContextHolder> context,
61
+ SeekMode seekMode)
62
+ : seekMode_(seekMode), avioContextHolder_(std::move(context)) {
63
+ setFFmpegLogLevel();
64
+
65
+ TORCH_CHECK(avioContextHolder_, "Context holder cannot be null");
66
+
67
+ // Because FFmpeg requires a reference to a pointer in the call to open, we
68
+ // can't use a unique pointer here. Note that means we must call free if open
69
+ // fails.
70
+ AVFormatContext* rawContext = avformat_alloc_context();
71
+ TORCH_CHECK(rawContext != nullptr, "Unable to alloc avformat context");
72
+
73
+ rawContext->pb = avioContextHolder_->getAVIOContext();
74
+ int status = avformat_open_input(&rawContext, nullptr, nullptr, nullptr);
75
+ if (status != 0) {
76
+ avformat_free_context(rawContext);
77
+ TORCH_CHECK(
78
+ false,
79
+ "Failed to open input buffer: " +
80
+ getFFMPEGErrorStringFromErrorCode(status));
81
+ }
82
+
83
+ formatContext_.reset(rawContext);
84
+
85
+ initializeDecoder();
86
+ }
87
+
88
+ void SingleStreamDecoder::initializeDecoder() {
89
+ TORCH_CHECK(!initialized_, "Attempted double initialization.");
90
+
91
+ // In principle, the AVFormatContext should be filled in by the call to
92
+ // avformat_open_input() which reads the header. However, some formats do not
93
+ // store enough info in the header, so we call avformat_find_stream_info()
94
+ // which decodes a few frames to get missing info. For more, see:
95
+ // https://ffmpeg.org/doxygen/7.0/group__lavf__decoding.html
96
+ int status = avformat_find_stream_info(formatContext_.get(), nullptr);
97
+ TORCH_CHECK(
98
+ status >= 0,
99
+ "Failed to find stream info: ",
100
+ getFFMPEGErrorStringFromErrorCode(status));
101
+
102
+ for (unsigned int i = 0; i < formatContext_->nb_streams; i++) {
103
+ AVStream* avStream = formatContext_->streams[i];
104
+ StreamMetadata streamMetadata;
105
+
106
+ TORCH_CHECK(
107
+ static_cast<int>(i) == avStream->index,
108
+ "Our stream index, " + std::to_string(i) +
109
+ ", does not match AVStream's index, " +
110
+ std::to_string(avStream->index) + ".");
111
+ streamMetadata.streamIndex = i;
112
+ streamMetadata.mediaType = avStream->codecpar->codec_type;
113
+ streamMetadata.codecName = avcodec_get_name(avStream->codecpar->codec_id);
114
+ streamMetadata.bitRate = avStream->codecpar->bit_rate;
115
+
116
+ int64_t frameCount = avStream->nb_frames;
117
+ if (frameCount > 0) {
118
+ streamMetadata.numFramesFromHeader = frameCount;
119
+ }
120
+
121
+ if (avStream->duration > 0 && avStream->time_base.den > 0) {
122
+ streamMetadata.durationSecondsFromHeader =
123
+ ptsToSeconds(avStream->duration, avStream->time_base);
124
+ }
125
+ if (avStream->start_time != AV_NOPTS_VALUE) {
126
+ streamMetadata.beginStreamSecondsFromHeader =
127
+ ptsToSeconds(avStream->start_time, avStream->time_base);
128
+ }
129
+
130
+ if (avStream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
131
+ double fps = av_q2d(avStream->r_frame_rate);
132
+ if (fps > 0) {
133
+ streamMetadata.averageFpsFromHeader = fps;
134
+ }
135
+ containerMetadata_.numVideoStreams++;
136
+ } else if (avStream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
137
+ AVSampleFormat format =
138
+ static_cast<AVSampleFormat>(avStream->codecpar->format);
139
+
140
+ // If the AVSampleFormat is not recognized, we get back nullptr. We have
141
+ // to make sure we don't initialize a std::string with nullptr. There's
142
+ // nothing to do on the else branch because we're already using an
143
+ // optional; it'll just remain empty.
144
+ const char* rawSampleFormat = av_get_sample_fmt_name(format);
145
+ if (rawSampleFormat != nullptr) {
146
+ streamMetadata.sampleFormat = std::string(rawSampleFormat);
147
+ }
148
+ containerMetadata_.numAudioStreams++;
149
+ }
150
+
151
+ containerMetadata_.allStreamMetadata.push_back(streamMetadata);
152
+ }
153
+
154
+ if (formatContext_->duration > 0) {
155
+ AVRational defaultTimeBase{1, AV_TIME_BASE};
156
+ containerMetadata_.durationSecondsFromHeader =
157
+ ptsToSeconds(formatContext_->duration, defaultTimeBase);
158
+ }
159
+
160
+ if (formatContext_->bit_rate > 0) {
161
+ containerMetadata_.bitRate = formatContext_->bit_rate;
162
+ }
163
+
164
+ int bestVideoStream = getBestStreamIndex(AVMEDIA_TYPE_VIDEO);
165
+ if (bestVideoStream >= 0) {
166
+ containerMetadata_.bestVideoStreamIndex = bestVideoStream;
167
+ }
168
+
169
+ int bestAudioStream = getBestStreamIndex(AVMEDIA_TYPE_AUDIO);
170
+ if (bestAudioStream >= 0) {
171
+ containerMetadata_.bestAudioStreamIndex = bestAudioStream;
172
+ }
173
+
174
+ if (seekMode_ == SeekMode::exact) {
175
+ scanFileAndUpdateMetadataAndIndex();
176
+ }
177
+
178
+ initialized_ = true;
179
+ }
180
+
181
+ int SingleStreamDecoder::getBestStreamIndex(AVMediaType mediaType) {
182
+ AVCodecOnlyUseForCallingAVFindBestStream avCodec = nullptr;
183
+ int streamIndex =
184
+ av_find_best_stream(formatContext_.get(), mediaType, -1, -1, &avCodec, 0);
185
+ return streamIndex;
186
+ }
187
+
188
+ // --------------------------------------------------------------------------
189
+ // VIDEO METADATA QUERY API
190
+ // --------------------------------------------------------------------------
191
+
192
+ void SingleStreamDecoder::sortAllFrames() {
193
+ // Sort the allFrames and keyFrames vecs in each stream, and also sets
194
+ // additional fields of the FrameInfo entries like nextPts and frameIndex
195
+ // This is called at the end of a scan, or when setting a user-defined frame
196
+ // mapping.
197
+ for (auto& [streamIndex, streamInfo] : streamInfos_) {
198
+ std::sort(
199
+ streamInfo.keyFrames.begin(),
200
+ streamInfo.keyFrames.end(),
201
+ [](const FrameInfo& frameInfo1, const FrameInfo& frameInfo2) {
202
+ return frameInfo1.pts < frameInfo2.pts;
203
+ });
204
+ std::sort(
205
+ streamInfo.allFrames.begin(),
206
+ streamInfo.allFrames.end(),
207
+ [](const FrameInfo& frameInfo1, const FrameInfo& frameInfo2) {
208
+ return frameInfo1.pts < frameInfo2.pts;
209
+ });
210
+
211
+ size_t keyFrameIndex = 0;
212
+ for (size_t i = 0; i < streamInfo.allFrames.size(); ++i) {
213
+ streamInfo.allFrames[i].frameIndex = i;
214
+ if (streamInfo.allFrames[i].isKeyFrame) {
215
+ TORCH_CHECK(
216
+ keyFrameIndex < streamInfo.keyFrames.size(),
217
+ "The allFrames vec claims it has MORE keyFrames than the keyFrames vec. There's a bug in torchcodec.");
218
+ streamInfo.keyFrames[keyFrameIndex].frameIndex = i;
219
+ ++keyFrameIndex;
220
+ }
221
+ if (i + 1 < streamInfo.allFrames.size()) {
222
+ streamInfo.allFrames[i].nextPts = streamInfo.allFrames[i + 1].pts;
223
+ }
224
+ }
225
+ TORCH_CHECK(
226
+ keyFrameIndex == streamInfo.keyFrames.size(),
227
+ "The allFrames vec claims it has LESS keyFrames than the keyFrames vec. There's a bug in torchcodec.");
228
+ }
229
+ }
230
+
231
+ void SingleStreamDecoder::scanFileAndUpdateMetadataAndIndex() {
232
+ if (scannedAllStreams_) {
233
+ return;
234
+ }
235
+
236
+ AutoAVPacket autoAVPacket;
237
+ while (true) {
238
+ ReferenceAVPacket packet(autoAVPacket);
239
+
240
+ // av_read_frame is a misleading name: it gets the next **packet**.
241
+ int status = av_read_frame(formatContext_.get(), packet.get());
242
+
243
+ if (status == AVERROR_EOF) {
244
+ break;
245
+ }
246
+
247
+ TORCH_CHECK(
248
+ status == AVSUCCESS,
249
+ "Failed to read frame from input file: ",
250
+ getFFMPEGErrorStringFromErrorCode(status));
251
+
252
+ if (packet->flags & AV_PKT_FLAG_DISCARD) {
253
+ continue;
254
+ }
255
+
256
+ // We got a valid packet. Let's figure out what stream it belongs to and
257
+ // record its relevant metadata.
258
+ int streamIndex = packet->stream_index;
259
+ auto& streamMetadata = containerMetadata_.allStreamMetadata[streamIndex];
260
+ streamMetadata.beginStreamPtsFromContent = std::min(
261
+ streamMetadata.beginStreamPtsFromContent.value_or(INT64_MAX),
262
+ getPtsOrDts(packet));
263
+ streamMetadata.endStreamPtsFromContent = std::max(
264
+ streamMetadata.endStreamPtsFromContent.value_or(INT64_MIN),
265
+ getPtsOrDts(packet) + packet->duration);
266
+ streamMetadata.numFramesFromContent =
267
+ streamMetadata.numFramesFromContent.value_or(0) + 1;
268
+
269
+ // Note that we set the other value in this struct, nextPts, only after
270
+ // we have scanned all packets and sorted by pts.
271
+ FrameInfo frameInfo = {getPtsOrDts(packet)};
272
+ if (packet->flags & AV_PKT_FLAG_KEY) {
273
+ frameInfo.isKeyFrame = true;
274
+ streamInfos_[streamIndex].keyFrames.push_back(frameInfo);
275
+ }
276
+ streamInfos_[streamIndex].allFrames.push_back(frameInfo);
277
+ }
278
+
279
+ // Set all per-stream metadata that requires knowing the content of all
280
+ // packets.
281
+ for (size_t streamIndex = 0;
282
+ streamIndex < containerMetadata_.allStreamMetadata.size();
283
+ ++streamIndex) {
284
+ auto& streamMetadata = containerMetadata_.allStreamMetadata[streamIndex];
285
+ auto avStream = formatContext_->streams[streamIndex];
286
+
287
+ streamMetadata.numFramesFromContent =
288
+ streamInfos_[streamIndex].allFrames.size();
289
+
290
+ if (streamMetadata.beginStreamPtsFromContent.has_value()) {
291
+ streamMetadata.beginStreamPtsSecondsFromContent = ptsToSeconds(
292
+ *streamMetadata.beginStreamPtsFromContent, avStream->time_base);
293
+ }
294
+ if (streamMetadata.endStreamPtsFromContent.has_value()) {
295
+ streamMetadata.endStreamPtsSecondsFromContent = ptsToSeconds(
296
+ *streamMetadata.endStreamPtsFromContent, avStream->time_base);
297
+ }
298
+ }
299
+
300
+ // Reset the seek-cursor back to the beginning.
301
+ int status = avformat_seek_file(formatContext_.get(), 0, INT64_MIN, 0, 0, 0);
302
+ TORCH_CHECK(
303
+ status >= 0,
304
+ "Could not seek file to pts=0: ",
305
+ getFFMPEGErrorStringFromErrorCode(status));
306
+
307
+ // Sort all frames by their pts.
308
+ sortAllFrames();
309
+ scannedAllStreams_ = true;
310
+ }
311
+
312
+ void SingleStreamDecoder::readCustomFrameMappingsUpdateMetadataAndIndex(
313
+ int streamIndex,
314
+ FrameMappings customFrameMappings) {
315
+ TORCH_CHECK(
316
+ customFrameMappings.all_frames.dtype() == torch::kLong &&
317
+ customFrameMappings.is_key_frame.dtype() == torch::kBool &&
318
+ customFrameMappings.duration.dtype() == torch::kLong,
319
+ "all_frames and duration tensors must be int64 dtype, and is_key_frame tensor must be a bool dtype.");
320
+ const torch::Tensor& all_frames =
321
+ customFrameMappings.all_frames.to(torch::kLong);
322
+ const torch::Tensor& is_key_frame =
323
+ customFrameMappings.is_key_frame.to(torch::kBool);
324
+ const torch::Tensor& duration = customFrameMappings.duration.to(torch::kLong);
325
+ TORCH_CHECK(
326
+ all_frames.size(0) == is_key_frame.size(0) &&
327
+ is_key_frame.size(0) == duration.size(0),
328
+ "all_frames, is_key_frame, and duration from custom_frame_mappings were not same size.");
329
+
330
+ // Allocate vectors using num frames to reduce reallocations
331
+ int64_t numFrames = all_frames.size(0);
332
+ streamInfos_[streamIndex].allFrames.reserve(numFrames);
333
+ streamInfos_[streamIndex].keyFrames.reserve(numFrames);
334
+ // Use accessor to efficiently access tensor elements
335
+ auto pts_data = all_frames.accessor<int64_t, 1>();
336
+ auto is_key_frame_data = is_key_frame.accessor<bool, 1>();
337
+ auto duration_data = duration.accessor<int64_t, 1>();
338
+
339
+ auto& streamMetadata = containerMetadata_.allStreamMetadata[streamIndex];
340
+
341
+ streamMetadata.beginStreamPtsFromContent = pts_data[0];
342
+ streamMetadata.endStreamPtsFromContent =
343
+ pts_data[numFrames - 1] + duration_data[numFrames - 1];
344
+
345
+ auto avStream = formatContext_->streams[streamIndex];
346
+ streamMetadata.beginStreamPtsSecondsFromContent = ptsToSeconds(
347
+ *streamMetadata.beginStreamPtsFromContent, avStream->time_base);
348
+
349
+ streamMetadata.endStreamPtsSecondsFromContent = ptsToSeconds(
350
+ *streamMetadata.endStreamPtsFromContent, avStream->time_base);
351
+
352
+ streamMetadata.numFramesFromContent = numFrames;
353
+ for (int64_t i = 0; i < numFrames; ++i) {
354
+ FrameInfo frameInfo;
355
+ frameInfo.pts = pts_data[i];
356
+ frameInfo.isKeyFrame = is_key_frame_data[i];
357
+ streamInfos_[streamIndex].allFrames.push_back(frameInfo);
358
+ if (frameInfo.isKeyFrame) {
359
+ streamInfos_[streamIndex].keyFrames.push_back(frameInfo);
360
+ }
361
+ }
362
+ sortAllFrames();
363
+ }
364
+
365
+ ContainerMetadata SingleStreamDecoder::getContainerMetadata() const {
366
+ return containerMetadata_;
367
+ }
368
+
369
+ torch::Tensor SingleStreamDecoder::getKeyFrameIndices() {
370
+ validateActiveStream(AVMEDIA_TYPE_VIDEO);
371
+ validateScannedAllStreams("getKeyFrameIndices");
372
+
373
+ const std::vector<FrameInfo>& keyFrames =
374
+ streamInfos_[activeStreamIndex_].keyFrames;
375
+ torch::Tensor keyFrameIndices =
376
+ torch::empty({static_cast<int64_t>(keyFrames.size())}, {torch::kInt64});
377
+ for (size_t i = 0; i < keyFrames.size(); ++i) {
378
+ keyFrameIndices[i] = keyFrames[i].frameIndex;
379
+ }
380
+
381
+ return keyFrameIndices;
382
+ }
383
+
384
+ // --------------------------------------------------------------------------
385
+ // ADDING STREAMS API
386
+ // --------------------------------------------------------------------------
387
+
388
+ void SingleStreamDecoder::addStream(
389
+ int streamIndex,
390
+ AVMediaType mediaType,
391
+ const torch::Device& device,
392
+ const std::string_view deviceVariant,
393
+ std::optional<int> ffmpegThreadCount) {
394
+ TORCH_CHECK(
395
+ activeStreamIndex_ == NO_ACTIVE_STREAM,
396
+ "Can only add one single stream.");
397
+ TORCH_CHECK(
398
+ mediaType == AVMEDIA_TYPE_VIDEO || mediaType == AVMEDIA_TYPE_AUDIO,
399
+ "Can only add video or audio streams.");
400
+ TORCH_CHECK(formatContext_.get() != nullptr);
401
+
402
+ AVCodecOnlyUseForCallingAVFindBestStream avCodec = nullptr;
403
+
404
+ activeStreamIndex_ = av_find_best_stream(
405
+ formatContext_.get(), mediaType, streamIndex, -1, &avCodec, 0);
406
+
407
+ if (activeStreamIndex_ < 0) {
408
+ throw std::invalid_argument(
409
+ "No valid stream found in input file. Is " +
410
+ std::to_string(streamIndex) + " of the desired media type?");
411
+ }
412
+
413
+ TORCH_CHECK(avCodec != nullptr);
414
+
415
+ StreamInfo& streamInfo = streamInfos_[activeStreamIndex_];
416
+ streamInfo.streamIndex = activeStreamIndex_;
417
+ streamInfo.timeBase = formatContext_->streams[activeStreamIndex_]->time_base;
418
+ streamInfo.stream = formatContext_->streams[activeStreamIndex_];
419
+ streamInfo.avMediaType = mediaType;
420
+
421
+ // This should never happen, checking just to be safe.
422
+ TORCH_CHECK(
423
+ streamInfo.stream->codecpar->codec_type == mediaType,
424
+ "FFmpeg found stream with index ",
425
+ activeStreamIndex_,
426
+ " which is of the wrong media type.");
427
+
428
+ deviceInterface_ = createDeviceInterface(device, deviceVariant);
429
+ TORCH_CHECK(
430
+ deviceInterface_ != nullptr,
431
+ "Failed to create device interface. This should never happen, please report.");
432
+ deviceInterface_->initialize(streamInfo.stream, formatContext_);
433
+
434
+ // TODO_CODE_QUALITY it's pretty meh to have a video-specific logic within
435
+ // addStream() which is supposed to be generic
436
+ if (mediaType == AVMEDIA_TYPE_VIDEO) {
437
+ avCodec = makeAVCodecOnlyUseForCallingAVFindBestStream(
438
+ deviceInterface_->findCodec(streamInfo.stream->codecpar->codec_id)
439
+ .value_or(avCodec));
440
+ }
441
+
442
+ AVCodecContext* codecContext = avcodec_alloc_context3(avCodec);
443
+ TORCH_CHECK(codecContext != nullptr);
444
+ streamInfo.codecContext.reset(codecContext);
445
+
446
+ int retVal = avcodec_parameters_to_context(
447
+ streamInfo.codecContext.get(), streamInfo.stream->codecpar);
448
+ TORCH_CHECK_EQ(retVal, AVSUCCESS);
449
+
450
+ streamInfo.codecContext->thread_count = ffmpegThreadCount.value_or(0);
451
+ streamInfo.codecContext->pkt_timebase = streamInfo.stream->time_base;
452
+
453
+ // Note that we must make sure to register the harware device context
454
+ // with the codec context before calling avcodec_open2(). Otherwise, decoding
455
+ // will happen on the CPU and not the hardware device.
456
+ deviceInterface_->registerHardwareDeviceWithCodec(codecContext);
457
+ retVal = avcodec_open2(streamInfo.codecContext.get(), avCodec, nullptr);
458
+ TORCH_CHECK(retVal >= AVSUCCESS, getFFMPEGErrorStringFromErrorCode(retVal));
459
+
460
+ codecContext->time_base = streamInfo.stream->time_base;
461
+
462
+ containerMetadata_.allStreamMetadata[activeStreamIndex_].codecName =
463
+ std::string(avcodec_get_name(codecContext->codec_id));
464
+
465
+ // We will only need packets from the active stream, so we tell FFmpeg to
466
+ // discard packets from the other streams. Note that av_read_frame() may still
467
+ // return some of those un-desired packet under some conditions, so it's still
468
+ // important to discard/demux correctly in the inner decoding loop.
469
+ for (unsigned int i = 0; i < formatContext_->nb_streams; ++i) {
470
+ if (i != static_cast<unsigned int>(activeStreamIndex_)) {
471
+ formatContext_->streams[i]->discard = AVDISCARD_ALL;
472
+ }
473
+ }
474
+ }
475
+
476
+ void SingleStreamDecoder::addVideoStream(
477
+ int streamIndex,
478
+ std::vector<Transform*>& transforms,
479
+ const VideoStreamOptions& videoStreamOptions,
480
+ std::optional<FrameMappings> customFrameMappings) {
481
+ TORCH_CHECK(
482
+ transforms.empty() || videoStreamOptions.device == torch::kCPU,
483
+ " Transforms are only supported for CPU devices.");
484
+
485
+ addStream(
486
+ streamIndex,
487
+ AVMEDIA_TYPE_VIDEO,
488
+ videoStreamOptions.device,
489
+ videoStreamOptions.deviceVariant,
490
+ videoStreamOptions.ffmpegThreadCount);
491
+
492
+ auto& streamMetadata =
493
+ containerMetadata_.allStreamMetadata[activeStreamIndex_];
494
+
495
+ if (seekMode_ == SeekMode::approximate) {
496
+ TORCH_CHECK(
497
+ streamMetadata.averageFpsFromHeader.has_value(),
498
+ "Seek mode is approximate, but stream ",
499
+ std::to_string(activeStreamIndex_),
500
+ " does not have an average fps in its metadata.");
501
+ }
502
+
503
+ auto& streamInfo = streamInfos_[activeStreamIndex_];
504
+ streamInfo.videoStreamOptions = videoStreamOptions;
505
+
506
+ streamMetadata.width = streamInfo.codecContext->width;
507
+ streamMetadata.height = streamInfo.codecContext->height;
508
+ streamMetadata.sampleAspectRatio =
509
+ streamInfo.codecContext->sample_aspect_ratio;
510
+
511
+ if (seekMode_ == SeekMode::custom_frame_mappings) {
512
+ TORCH_CHECK(
513
+ customFrameMappings.has_value(),
514
+ "Missing frame mappings when custom_frame_mappings seek mode is set.");
515
+ readCustomFrameMappingsUpdateMetadataAndIndex(
516
+ activeStreamIndex_, customFrameMappings.value());
517
+ }
518
+
519
+ metadataDims_ =
520
+ FrameDims(streamMetadata.height.value(), streamMetadata.width.value());
521
+ for (auto& transform : transforms) {
522
+ TORCH_CHECK(transform != nullptr, "Transforms should never be nullptr!");
523
+ if (transform->getOutputFrameDims().has_value()) {
524
+ resizedOutputDims_ = transform->getOutputFrameDims().value();
525
+ }
526
+
527
+ // Note that we are claiming ownership of the transform objects passed in to
528
+ // us.
529
+ transforms_.push_back(std::unique_ptr<Transform>(transform));
530
+ }
531
+
532
+ deviceInterface_->initializeVideo(
533
+ videoStreamOptions, transforms_, resizedOutputDims_);
534
+ }
535
+
536
+ void SingleStreamDecoder::addAudioStream(
537
+ int streamIndex,
538
+ const AudioStreamOptions& audioStreamOptions) {
539
+ TORCH_CHECK(
540
+ seekMode_ == SeekMode::approximate,
541
+ "seek_mode must be 'approximate' for audio streams.");
542
+ if (audioStreamOptions.numChannels.has_value()) {
543
+ TORCH_CHECK(
544
+ *audioStreamOptions.numChannels > 0 &&
545
+ *audioStreamOptions.numChannels <= AV_NUM_DATA_POINTERS,
546
+ "num_channels must be > 0 and <= AV_NUM_DATA_POINTERS (usually 8). Got: ",
547
+ *audioStreamOptions.numChannels);
548
+ }
549
+
550
+ addStream(streamIndex, AVMEDIA_TYPE_AUDIO);
551
+
552
+ auto& streamInfo = streamInfos_[activeStreamIndex_];
553
+ streamInfo.audioStreamOptions = audioStreamOptions;
554
+
555
+ auto& streamMetadata =
556
+ containerMetadata_.allStreamMetadata[activeStreamIndex_];
557
+ streamMetadata.sampleRate =
558
+ static_cast<int64_t>(streamInfo.codecContext->sample_rate);
559
+ streamMetadata.numChannels =
560
+ static_cast<int64_t>(getNumChannels(streamInfo.codecContext));
561
+
562
+ // FFmpeg docs say that the decoder will try to decode natively in this
563
+ // format, if it can. Docs don't say what the decoder does when it doesn't
564
+ // support that format, but it looks like it does nothing, so this probably
565
+ // doesn't hurt.
566
+ streamInfo.codecContext->request_sample_fmt = AV_SAMPLE_FMT_FLTP;
567
+ }
568
+
569
+ // --------------------------------------------------------------------------
570
+ // HIGH-LEVEL DECODING ENTRY-POINTS
571
+ // --------------------------------------------------------------------------
572
+
573
+ FrameOutput SingleStreamDecoder::getNextFrame() {
574
+ auto output = getNextFrameInternal();
575
+ if (streamInfos_[activeStreamIndex_].avMediaType == AVMEDIA_TYPE_VIDEO) {
576
+ output.data = maybePermuteHWC2CHW(output.data);
577
+ }
578
+ return output;
579
+ }
580
+
581
+ FrameOutput SingleStreamDecoder::getNextFrameInternal(
582
+ std::optional<torch::Tensor> preAllocatedOutputTensor) {
583
+ validateActiveStream();
584
+ UniqueAVFrame avFrame = decodeAVFrame([this](const UniqueAVFrame& avFrame) {
585
+ return getPtsOrDts(avFrame) >= cursor_;
586
+ });
587
+ return convertAVFrameToFrameOutput(avFrame, preAllocatedOutputTensor);
588
+ }
589
+
590
+ FrameOutput SingleStreamDecoder::getFrameAtIndex(int64_t frameIndex) {
591
+ auto frameOutput = getFrameAtIndexInternal(frameIndex);
592
+ frameOutput.data = maybePermuteHWC2CHW(frameOutput.data);
593
+ return frameOutput;
594
+ }
595
+
596
+ FrameOutput SingleStreamDecoder::getFrameAtIndexInternal(
597
+ int64_t frameIndex,
598
+ std::optional<torch::Tensor> preAllocatedOutputTensor) {
599
+ validateActiveStream(AVMEDIA_TYPE_VIDEO);
600
+
601
+ const auto& streamInfo = streamInfos_[activeStreamIndex_];
602
+ const auto& streamMetadata =
603
+ containerMetadata_.allStreamMetadata[activeStreamIndex_];
604
+
605
+ std::optional<int64_t> numFrames = getNumFrames(streamMetadata);
606
+ if (numFrames.has_value()) {
607
+ // If the frameIndex is negative, we convert it to a positive index
608
+ frameIndex = frameIndex >= 0 ? frameIndex : frameIndex + numFrames.value();
609
+ }
610
+ validateFrameIndex(streamMetadata, frameIndex);
611
+
612
+ int64_t pts = getPts(frameIndex);
613
+ setCursorPtsInSeconds(ptsToSeconds(pts, streamInfo.timeBase));
614
+ return getNextFrameInternal(preAllocatedOutputTensor);
615
+ }
616
+
617
+ FrameBatchOutput SingleStreamDecoder::getFramesAtIndices(
618
+ const torch::Tensor& frameIndices) {
619
+ validateActiveStream(AVMEDIA_TYPE_VIDEO);
620
+
621
+ auto frameIndicesAccessor = frameIndices.accessor<int64_t, 1>();
622
+
623
+ bool indicesAreSorted = true;
624
+ for (int64_t i = 1; i < frameIndices.numel(); ++i) {
625
+ if (frameIndicesAccessor[i] < frameIndicesAccessor[i - 1]) {
626
+ indicesAreSorted = false;
627
+ break;
628
+ }
629
+ }
630
+
631
+ std::vector<size_t> argsort;
632
+ if (!indicesAreSorted) {
633
+ // if frameIndices is [13, 10, 12, 11]
634
+ // when sorted, it's [10, 11, 12, 13] <-- this is the sorted order we want
635
+ // to use to decode the frames
636
+ // and argsort is [ 1, 3, 2, 0]
637
+ argsort.resize(frameIndices.numel());
638
+ for (size_t i = 0; i < argsort.size(); ++i) {
639
+ argsort[i] = i;
640
+ }
641
+ std::sort(
642
+ argsort.begin(),
643
+ argsort.end(),
644
+ [&frameIndicesAccessor](size_t a, size_t b) {
645
+ return frameIndicesAccessor[a] < frameIndicesAccessor[b];
646
+ });
647
+ }
648
+
649
+ const auto& streamInfo = streamInfos_[activeStreamIndex_];
650
+ const auto& videoStreamOptions = streamInfo.videoStreamOptions;
651
+ FrameBatchOutput frameBatchOutput(
652
+ frameIndices.numel(),
653
+ resizedOutputDims_.value_or(metadataDims_),
654
+ videoStreamOptions.device);
655
+
656
+ auto previousIndexInVideo = -1;
657
+ for (int64_t f = 0; f < frameIndices.numel(); ++f) {
658
+ auto indexInOutput = indicesAreSorted ? f : argsort[f];
659
+ auto indexInVideo = frameIndicesAccessor[indexInOutput];
660
+
661
+ if ((f > 0) && (indexInVideo == previousIndexInVideo)) {
662
+ // Avoid decoding the same frame twice
663
+ auto previousIndexInOutput = indicesAreSorted ? f - 1 : argsort[f - 1];
664
+ frameBatchOutput.data[indexInOutput].copy_(
665
+ frameBatchOutput.data[previousIndexInOutput]);
666
+ frameBatchOutput.ptsSeconds[indexInOutput] =
667
+ frameBatchOutput.ptsSeconds[previousIndexInOutput];
668
+ frameBatchOutput.durationSeconds[indexInOutput] =
669
+ frameBatchOutput.durationSeconds[previousIndexInOutput];
670
+ } else {
671
+ FrameOutput frameOutput = getFrameAtIndexInternal(
672
+ indexInVideo, frameBatchOutput.data[indexInOutput]);
673
+ frameBatchOutput.ptsSeconds[indexInOutput] = frameOutput.ptsSeconds;
674
+ frameBatchOutput.durationSeconds[indexInOutput] =
675
+ frameOutput.durationSeconds;
676
+ }
677
+ previousIndexInVideo = indexInVideo;
678
+ }
679
+ frameBatchOutput.data = maybePermuteHWC2CHW(frameBatchOutput.data);
680
+ return frameBatchOutput;
681
+ }
682
+
683
+ FrameBatchOutput SingleStreamDecoder::getFramesInRange(
684
+ int64_t start,
685
+ int64_t stop,
686
+ int64_t step) {
687
+ validateActiveStream(AVMEDIA_TYPE_VIDEO);
688
+
689
+ const auto& streamMetadata =
690
+ containerMetadata_.allStreamMetadata[activeStreamIndex_];
691
+ const auto& streamInfo = streamInfos_[activeStreamIndex_];
692
+ TORCH_CHECK(
693
+ start >= 0, "Range start, " + std::to_string(start) + " is less than 0.");
694
+ TORCH_CHECK(
695
+ step > 0, "Step must be greater than 0; is " + std::to_string(step));
696
+
697
+ // Note that if we do not have the number of frames available in our
698
+ // metadata, then we assume that the upper part of the range is valid.
699
+ std::optional<int64_t> numFrames = getNumFrames(streamMetadata);
700
+ if (numFrames.has_value()) {
701
+ TORCH_CHECK(
702
+ stop <= numFrames.value(),
703
+ "Range stop, " + std::to_string(stop) +
704
+ ", is more than the number of frames, " +
705
+ std::to_string(numFrames.value()));
706
+ }
707
+
708
+ int64_t numOutputFrames = std::ceil((stop - start) / double(step));
709
+ const auto& videoStreamOptions = streamInfo.videoStreamOptions;
710
+ FrameBatchOutput frameBatchOutput(
711
+ numOutputFrames,
712
+ resizedOutputDims_.value_or(metadataDims_),
713
+ videoStreamOptions.device);
714
+
715
+ for (int64_t i = start, f = 0; i < stop; i += step, ++f) {
716
+ FrameOutput frameOutput =
717
+ getFrameAtIndexInternal(i, frameBatchOutput.data[f]);
718
+ frameBatchOutput.ptsSeconds[f] = frameOutput.ptsSeconds;
719
+ frameBatchOutput.durationSeconds[f] = frameOutput.durationSeconds;
720
+ }
721
+ frameBatchOutput.data = maybePermuteHWC2CHW(frameBatchOutput.data);
722
+ return frameBatchOutput;
723
+ }
724
+
725
+ FrameOutput SingleStreamDecoder::getFramePlayedAt(double seconds) {
726
+ validateActiveStream(AVMEDIA_TYPE_VIDEO);
727
+ StreamInfo& streamInfo = streamInfos_[activeStreamIndex_];
728
+ double lastDecodedStartTime =
729
+ ptsToSeconds(lastDecodedAvFramePts_, streamInfo.timeBase);
730
+ double lastDecodedEndTime = ptsToSeconds(
731
+ lastDecodedAvFramePts_ + lastDecodedAvFrameDuration_,
732
+ streamInfo.timeBase);
733
+ if (seconds >= lastDecodedStartTime && seconds < lastDecodedEndTime) {
734
+ // We are in the same frame as the one we just returned. However, since we
735
+ // don't cache it locally, we have to rewind back.
736
+ seconds = lastDecodedStartTime;
737
+ }
738
+
739
+ setCursorPtsInSeconds(seconds);
740
+ UniqueAVFrame avFrame =
741
+ decodeAVFrame([seconds, this](const UniqueAVFrame& avFrame) {
742
+ StreamInfo& streamInfo = streamInfos_[activeStreamIndex_];
743
+ double frameStartTime =
744
+ ptsToSeconds(getPtsOrDts(avFrame), streamInfo.timeBase);
745
+ double frameEndTime = ptsToSeconds(
746
+ getPtsOrDts(avFrame) + getDuration(avFrame), streamInfo.timeBase);
747
+ if (frameStartTime > seconds) {
748
+ // FFMPEG seeked past the frame we are looking for even though we
749
+ // set max_ts to be our needed timestamp in avformat_seek_file()
750
+ // in maybeSeekToBeforeDesiredPts().
751
+ // This could be a bug in FFMPEG:
752
+ // https://trac.ffmpeg.org/ticket/11137 In this case we return the
753
+ // very next frame instead of throwing an exception.
754
+ // TODO: Maybe log to stderr for Debug builds?
755
+ return true;
756
+ }
757
+ return seconds >= frameStartTime && seconds < frameEndTime;
758
+ });
759
+
760
+ // Convert the frame to tensor.
761
+ FrameOutput frameOutput = convertAVFrameToFrameOutput(avFrame);
762
+ frameOutput.data = maybePermuteHWC2CHW(frameOutput.data);
763
+ return frameOutput;
764
+ }
765
+
766
+ FrameBatchOutput SingleStreamDecoder::getFramesPlayedAt(
767
+ const torch::Tensor& timestamps) {
768
+ validateActiveStream(AVMEDIA_TYPE_VIDEO);
769
+
770
+ const auto& streamMetadata =
771
+ containerMetadata_.allStreamMetadata[activeStreamIndex_];
772
+
773
+ double minSeconds = getMinSeconds(streamMetadata);
774
+ std::optional<double> maxSeconds = getMaxSeconds(streamMetadata);
775
+
776
+ // The frame played at timestamp t and the one played at timestamp `t +
777
+ // eps` are probably the same frame, with the same index. The easiest way to
778
+ // avoid decoding that unique frame twice is to convert the input timestamps
779
+ // to indices, and leverage the de-duplication logic of getFramesAtIndices.
780
+
781
+ torch::Tensor frameIndices =
782
+ torch::empty({timestamps.numel()}, torch::kInt64);
783
+ auto frameIndicesAccessor = frameIndices.accessor<int64_t, 1>();
784
+ auto timestampsAccessor = timestamps.accessor<double, 1>();
785
+
786
+ for (int64_t i = 0; i < timestamps.numel(); ++i) {
787
+ auto frameSeconds = timestampsAccessor[i];
788
+ TORCH_CHECK(
789
+ frameSeconds >= minSeconds,
790
+ "frame pts is " + std::to_string(frameSeconds) +
791
+ "; must be greater than or equal to " + std::to_string(minSeconds) +
792
+ ".");
793
+
794
+ // Note that if we can't determine the maximum number of seconds from the
795
+ // metadata, then we assume the frame's pts is valid.
796
+ if (maxSeconds.has_value()) {
797
+ TORCH_CHECK(
798
+ frameSeconds < maxSeconds.value(),
799
+ "frame pts is " + std::to_string(frameSeconds) +
800
+ "; must be less than " + std::to_string(maxSeconds.value()) +
801
+ ".");
802
+ }
803
+
804
+ frameIndicesAccessor[i] = secondsToIndexLowerBound(frameSeconds);
805
+ }
806
+
807
+ return getFramesAtIndices(frameIndices);
808
+ }
809
+
810
+ FrameBatchOutput SingleStreamDecoder::getFramesPlayedInRange(
811
+ double startSeconds,
812
+ double stopSeconds) {
813
+ validateActiveStream(AVMEDIA_TYPE_VIDEO);
814
+ const auto& streamMetadata =
815
+ containerMetadata_.allStreamMetadata[activeStreamIndex_];
816
+ TORCH_CHECK(
817
+ startSeconds <= stopSeconds,
818
+ "Start seconds (" + std::to_string(startSeconds) +
819
+ ") must be less than or equal to stop seconds (" +
820
+ std::to_string(stopSeconds) + ".");
821
+
822
+ const auto& streamInfo = streamInfos_[activeStreamIndex_];
823
+ const auto& videoStreamOptions = streamInfo.videoStreamOptions;
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 (startSeconds == stopSeconds) {
843
+ FrameBatchOutput frameBatchOutput(
844
+ 0,
845
+ resizedOutputDims_.value_or(metadataDims_),
846
+ videoStreamOptions.device);
847
+ frameBatchOutput.data = maybePermuteHWC2CHW(frameBatchOutput.data);
848
+ return frameBatchOutput;
849
+ }
850
+
851
+ double minSeconds = getMinSeconds(streamMetadata);
852
+ TORCH_CHECK(
853
+ startSeconds >= minSeconds,
854
+ "Start seconds is " + std::to_string(startSeconds) +
855
+ "; must be greater than or equal to " + std::to_string(minSeconds) +
856
+ ".");
857
+
858
+ // Note that if we can't determine the maximum seconds from the metadata,
859
+ // then we assume upper range is valid.
860
+ std::optional<double> maxSeconds = getMaxSeconds(streamMetadata);
861
+ if (maxSeconds.has_value()) {
862
+ TORCH_CHECK(
863
+ startSeconds < maxSeconds.value(),
864
+ "Start seconds is " + std::to_string(startSeconds) +
865
+ "; must be less than " + std::to_string(maxSeconds.value()) + ".");
866
+ TORCH_CHECK(
867
+ stopSeconds <= maxSeconds.value(),
868
+ "Stop seconds (" + std::to_string(stopSeconds) +
869
+ "; must be less than or equal to " +
870
+ std::to_string(maxSeconds.value()) + ").");
871
+ }
872
+
873
+ // Note that we look at nextPts for a frame, and not its pts or duration.
874
+ // Our abstract player displays frames starting at the pts for that frame
875
+ // until the pts for the next frame. There are two consequences:
876
+ //
877
+ // 1. We ignore the duration for a frame. A frame is played until the
878
+ // next frame replaces it. This model is robust to durations being 0 or
879
+ // incorrect; our source of truth is the pts for frames. If duration is
880
+ // accurate, the nextPts for a frame would be equivalent to pts +
881
+ // duration.
882
+ // 2. In order to establish if the start of an interval maps to a
883
+ // particular frame, we need to figure out if it is ordered after the
884
+ // frame's pts, but before the next frames's pts.
885
+
886
+ int64_t startFrameIndex = secondsToIndexLowerBound(startSeconds);
887
+ int64_t stopFrameIndex = secondsToIndexUpperBound(stopSeconds);
888
+ int64_t numFrames = stopFrameIndex - startFrameIndex;
889
+
890
+ FrameBatchOutput frameBatchOutput(
891
+ numFrames,
892
+ resizedOutputDims_.value_or(metadataDims_),
893
+ videoStreamOptions.device);
894
+ for (int64_t i = startFrameIndex, f = 0; i < stopFrameIndex; ++i, ++f) {
895
+ FrameOutput frameOutput =
896
+ getFrameAtIndexInternal(i, frameBatchOutput.data[f]);
897
+ frameBatchOutput.ptsSeconds[f] = frameOutput.ptsSeconds;
898
+ frameBatchOutput.durationSeconds[f] = frameOutput.durationSeconds;
899
+ }
900
+ frameBatchOutput.data = maybePermuteHWC2CHW(frameBatchOutput.data);
901
+
902
+ return frameBatchOutput;
903
+ }
904
+
905
+ // Note [Audio Decoding Design]
906
+ // This note explains why audio decoding is implemented the way it is, and why
907
+ // it inherently differs from video decoding.
908
+ //
909
+ // Like for video, FFmpeg exposes the concept of a frame for audio streams. An
910
+ // audio frame is a contiguous sequence of samples, where a sample consists of
911
+ // `numChannels` values. An audio frame, or a sequence thereof, is always
912
+ // converted into a tensor of shape `(numChannels, numSamplesPerChannel)`.
913
+ //
914
+ // The notion of 'frame' in audio isn't what users want to interact with.
915
+ // Users want to interact with samples. The C++ and core APIs return frames,
916
+ // because we want those to be close to FFmpeg concepts, but the higher-level
917
+ // public APIs expose samples. As a result:
918
+ // - We don't expose index-based APIs for audio, because that would mean
919
+ // exposing the concept of audio frame. For now, we think exposing
920
+ // time-based APIs is more natural.
921
+ // - We never perform a scan for audio streams. We don't need to, since we
922
+ // won't
923
+ // be converting timestamps to indices. That's why we enforce the seek_mode
924
+ // to be "approximate" (which is slightly misleading, because technically
925
+ // the output samples will be at their exact positions. But this
926
+ // incongruence is only exposed at the C++/core private levels).
927
+ //
928
+ // Audio frames are of variable dimensions: in the same stream, a frame can
929
+ // contain 1024 samples and the next one may contain 512 [1]. This makes it
930
+ // impossible to stack audio frames in the same way we can stack video frames.
931
+ // This is one of the main reasons we cannot reuse the same pre-allocation
932
+ // logic we have for videos in getFramesPlayedInRange(): pre-allocating a
933
+ // batch requires constant (and known) frame dimensions. That's also why
934
+ // *concatenated* along the samples dimension, not stacked.
935
+ //
936
+ // [IMPORTANT!] There is one key invariant that we must respect when decoding
937
+ // audio frames:
938
+ //
939
+ // BEFORE DECODING FRAME i, WE MUST DECODE ALL FRAMES j < i.
940
+ //
941
+ // Always. Why? We don't know. What we know is that if we don't, we get
942
+ // clipped, incorrect audio as output [2]. All other (correct) libraries like
943
+ // TorchAudio or Decord do something similar, whether it was intended or not.
944
+ // This has a few implications:
945
+ // - The **only** place we're allowed to seek to in an audio stream is the
946
+ // stream's beginning. This ensures that if we need a frame, we'll have
947
+ // decoded all previous frames.
948
+ // - Because of that, we don't allow the public APIs to seek. Public APIs can
949
+ // call next() and `getFramesPlayedInRangeAudio()`, but they cannot manually
950
+ // seek.
951
+ // - We try not to seek, when we can avoid it. Typically if the next frame we
952
+ // need is in the future, we don't seek back to the beginning, we just
953
+ // decode all the frames in-between.
954
+ //
955
+ // [2] If you're brave and curious, you can read the long "Seek offset for
956
+ // audio" note in https://github.com/pytorch/torchcodec/pull/507/files, which
957
+ // sums up past (and failed) attemps at working around this issue.
958
+ AudioFramesOutput SingleStreamDecoder::getFramesPlayedInRangeAudio(
959
+ double startSeconds,
960
+ std::optional<double> stopSecondsOptional) {
961
+ validateActiveStream(AVMEDIA_TYPE_AUDIO);
962
+
963
+ if (stopSecondsOptional.has_value()) {
964
+ TORCH_CHECK(
965
+ startSeconds <= *stopSecondsOptional,
966
+ "Start seconds (" + std::to_string(startSeconds) +
967
+ ") must be less than or equal to stop seconds (" +
968
+ std::to_string(*stopSecondsOptional) + ").");
969
+ }
970
+
971
+ StreamInfo& streamInfo = streamInfos_[activeStreamIndex_];
972
+
973
+ if (stopSecondsOptional.has_value() && startSeconds == *stopSecondsOptional) {
974
+ // For consistency with video
975
+ int numChannels = getNumChannels(streamInfo.codecContext);
976
+ return AudioFramesOutput{torch::empty({numChannels, 0}), 0.0};
977
+ }
978
+
979
+ auto startPts = secondsToClosestPts(startSeconds, streamInfo.timeBase);
980
+ if (startPts < lastDecodedAvFramePts_ + lastDecodedAvFrameDuration_) {
981
+ // If we need to seek backwards, then we have to seek back to the
982
+ // beginning of the stream. See [Audio Decoding Design].
983
+ setCursor(INT64_MIN);
984
+ }
985
+
986
+ // TODO-AUDIO Pre-allocate a long-enough tensor instead of creating a vec +
987
+ // cat(). This would save a copy. We know the duration of the output and the
988
+ // sample rate, so in theory we know the number of output samples.
989
+ std::vector<torch::Tensor> frames;
990
+
991
+ std::optional<double> firstFramePtsSeconds = std::nullopt;
992
+ auto stopPts = stopSecondsOptional.has_value()
993
+ ? secondsToClosestPts(*stopSecondsOptional, streamInfo.timeBase)
994
+ : INT64_MAX;
995
+ auto finished = false;
996
+ while (!finished) {
997
+ try {
998
+ UniqueAVFrame avFrame =
999
+ decodeAVFrame([startPts, stopPts](const UniqueAVFrame& avFrame) {
1000
+ return startPts < getPtsOrDts(avFrame) + getDuration(avFrame) &&
1001
+ stopPts > getPtsOrDts(avFrame);
1002
+ });
1003
+ auto frameOutput = convertAVFrameToFrameOutput(avFrame);
1004
+ if (!firstFramePtsSeconds.has_value()) {
1005
+ firstFramePtsSeconds = frameOutput.ptsSeconds;
1006
+ }
1007
+ frames.push_back(frameOutput.data);
1008
+ } catch (const EndOfFileException& e) {
1009
+ finished = true;
1010
+ }
1011
+
1012
+ // If stopSeconds is in [begin, end] of the last decoded frame, we should
1013
+ // stop decoding more frames. Note that if we were to use [begin, end),
1014
+ // which may seem more natural, then we would decode the frame starting at
1015
+ // stopSeconds, which isn't what we want!
1016
+ auto lastDecodedAvFrameEnd =
1017
+ lastDecodedAvFramePts_ + lastDecodedAvFrameDuration_;
1018
+ finished |= (lastDecodedAvFramePts_) <= stopPts &&
1019
+ (stopPts <= lastDecodedAvFrameEnd);
1020
+ }
1021
+
1022
+ auto lastSamples = maybeFlushSwrBuffers();
1023
+ if (lastSamples.has_value()) {
1024
+ frames.push_back(*lastSamples);
1025
+ }
1026
+
1027
+ TORCH_CHECK(
1028
+ frames.size() > 0 && firstFramePtsSeconds.has_value(),
1029
+ "No audio frames were decoded. ",
1030
+ "This is probably because start_seconds is too high(",
1031
+ startSeconds,
1032
+ "),",
1033
+ "or because stop_seconds(",
1034
+ stopSecondsOptional,
1035
+ ") is too low.");
1036
+
1037
+ return AudioFramesOutput{torch::cat(frames, 1), *firstFramePtsSeconds};
1038
+ }
1039
+
1040
+ // --------------------------------------------------------------------------
1041
+ // SEEKING APIs
1042
+ // --------------------------------------------------------------------------
1043
+
1044
+ void SingleStreamDecoder::setCursorPtsInSeconds(double seconds) {
1045
+ // We don't allow public audio decoding APIs to seek, see [Audio Decoding
1046
+ // Design]
1047
+ validateActiveStream(AVMEDIA_TYPE_VIDEO);
1048
+ setCursor(
1049
+ secondsToClosestPts(seconds, streamInfos_[activeStreamIndex_].timeBase));
1050
+ }
1051
+
1052
+ void SingleStreamDecoder::setCursor(int64_t pts) {
1053
+ cursorWasJustSet_ = true;
1054
+ cursor_ = pts;
1055
+ }
1056
+
1057
+ /*
1058
+ Videos have I frames and non-I frames (P and B frames). Non-I frames need data
1059
+ from the previous I frame to be decoded.
1060
+
1061
+ Imagine the cursor is at a random frame with PTS=lastDecodedAvFramePts (x for
1062
+ brevity) and we wish to seek to a user-specified PTS=y.
1063
+
1064
+ If y < x, we don't have a choice but to seek backwards to the highest I frame
1065
+ before y.
1066
+
1067
+ If y > x, we have two choices:
1068
+
1069
+ 1. We could keep decoding forward until we hit y. Illustrated below:
1070
+
1071
+ I P P P I P P P I P P I P P I P
1072
+ x y
1073
+
1074
+ 2. We could try to jump to an I frame between x and y (indicated by j below).
1075
+ And then start decoding until we encounter y. Illustrated below:
1076
+
1077
+ I P P P I P P P I P P I P P I P
1078
+ x j y
1079
+
1080
+ (2) is more efficient than (1) if there is an I frame between x and y.
1081
+ */
1082
+ bool SingleStreamDecoder::canWeAvoidSeeking() const {
1083
+ const StreamInfo& streamInfo = streamInfos_.at(activeStreamIndex_);
1084
+ if (streamInfo.avMediaType == AVMEDIA_TYPE_AUDIO) {
1085
+ // For audio, we only need to seek if a backwards seek was requested
1086
+ // within getFramesPlayedInRangeAudio(), when setCursorPtsInSeconds() was
1087
+ // called. For more context, see [Audio Decoding Design]
1088
+ return !cursorWasJustSet_;
1089
+ }
1090
+ if (cursor_ < lastDecodedAvFramePts_) {
1091
+ // We can never skip a seek if we are seeking backwards.
1092
+ return false;
1093
+ }
1094
+ if (lastDecodedAvFramePts_ == cursor_) {
1095
+ // We are seeking to the exact same frame as we are currently at. Without
1096
+ // caching we have to rewind back and decode the frame again.
1097
+ // TODO: https://github.com/pytorch/torchcodec/issues/84 we could
1098
+ // implement caching.
1099
+ return false;
1100
+ }
1101
+ // We are seeking forwards.
1102
+ // We can only skip a seek if both lastDecodedAvFramePts and
1103
+ // cursor_ share the same keyframe.
1104
+ int lastDecodedAvFrameIndex = getKeyFrameIndexForPts(lastDecodedAvFramePts_);
1105
+ int targetKeyFrameIndex = getKeyFrameIndexForPts(cursor_);
1106
+ return lastDecodedAvFrameIndex >= 0 && targetKeyFrameIndex >= 0 &&
1107
+ lastDecodedAvFrameIndex == targetKeyFrameIndex;
1108
+ }
1109
+
1110
+ // This method looks at currentPts and desiredPts and seeks in the
1111
+ // AVFormatContext if it is needed. We can skip seeking in certain cases. See
1112
+ // the comment of canWeAvoidSeeking() for details.
1113
+ void SingleStreamDecoder::maybeSeekToBeforeDesiredPts() {
1114
+ validateActiveStream();
1115
+ StreamInfo& streamInfo = streamInfos_[activeStreamIndex_];
1116
+
1117
+ decodeStats_.numSeeksAttempted++;
1118
+ if (canWeAvoidSeeking()) {
1119
+ decodeStats_.numSeeksSkipped++;
1120
+ return;
1121
+ }
1122
+
1123
+ int64_t desiredPts = cursor_;
1124
+
1125
+ // For some encodings like H265, FFMPEG sometimes seeks past the point we
1126
+ // set as the max_ts. So we use our own index to give it the exact pts of
1127
+ // the key frame that we want to seek to.
1128
+ // See https://github.com/pytorch/torchcodec/issues/179 for more details.
1129
+ // See https://trac.ffmpeg.org/ticket/11137 for the underlying ffmpeg bug.
1130
+ if (!streamInfo.keyFrames.empty()) {
1131
+ int desiredKeyFrameIndex = getKeyFrameIndexForPtsUsingScannedIndex(
1132
+ streamInfo.keyFrames, desiredPts);
1133
+ desiredKeyFrameIndex = std::max(desiredKeyFrameIndex, 0);
1134
+ desiredPts = streamInfo.keyFrames[desiredKeyFrameIndex].pts;
1135
+ }
1136
+
1137
+ int status = avformat_seek_file(
1138
+ formatContext_.get(),
1139
+ streamInfo.streamIndex,
1140
+ INT64_MIN,
1141
+ desiredPts,
1142
+ desiredPts,
1143
+ 0);
1144
+ TORCH_CHECK(
1145
+ status >= 0,
1146
+ "Could not seek file to pts=",
1147
+ std::to_string(desiredPts),
1148
+ ": ",
1149
+ getFFMPEGErrorStringFromErrorCode(status));
1150
+
1151
+ decodeStats_.numFlushes++;
1152
+ avcodec_flush_buffers(streamInfo.codecContext.get());
1153
+
1154
+ deviceInterface_->flush();
1155
+ }
1156
+
1157
+ // --------------------------------------------------------------------------
1158
+ // LOW-LEVEL DECODING
1159
+ // --------------------------------------------------------------------------
1160
+
1161
+ UniqueAVFrame SingleStreamDecoder::decodeAVFrame(
1162
+ std::function<bool(const UniqueAVFrame&)> filterFunction) {
1163
+ validateActiveStream();
1164
+
1165
+ resetDecodeStats();
1166
+
1167
+ if (cursorWasJustSet_) {
1168
+ maybeSeekToBeforeDesiredPts();
1169
+ cursorWasJustSet_ = false;
1170
+ }
1171
+
1172
+ StreamInfo& streamInfo = streamInfos_[activeStreamIndex_];
1173
+ UniqueAVFrame avFrame(av_frame_alloc());
1174
+ AutoAVPacket autoAVPacket;
1175
+ int status = AVSUCCESS;
1176
+ bool reachedEOF = false;
1177
+
1178
+ // TODONVDEC P2: Instead of calling canDecodePacketDirectly() and rely on
1179
+ // if/else blocks to dispatch to the interface or to FFmpeg, consider *always*
1180
+ // dispatching to the interface. The default implementation of the interface's
1181
+ // receiveFrame and sendPacket could just be calling avcodec_receive_frame and
1182
+ // avcodec_send_packet. This would make the decoding loop even more generic.
1183
+ while (true) {
1184
+ if (deviceInterface_->canDecodePacketDirectly()) {
1185
+ status = deviceInterface_->receiveFrame(avFrame);
1186
+ } else {
1187
+ status =
1188
+ avcodec_receive_frame(streamInfo.codecContext.get(), avFrame.get());
1189
+ }
1190
+
1191
+ if (status != AVSUCCESS && status != AVERROR(EAGAIN)) {
1192
+ // Non-retriable error
1193
+ break;
1194
+ }
1195
+
1196
+ decodeStats_.numFramesReceivedByDecoder++;
1197
+ // Is this the kind of frame we're looking for?
1198
+ if (status == AVSUCCESS && filterFunction(avFrame)) {
1199
+ // Yes, this is the frame we'll return; break out of the decoding loop.
1200
+ break;
1201
+ } else if (status == AVSUCCESS) {
1202
+ // No, but we received a valid frame - just not the kind we're looking
1203
+ // for. The logic below will read packets and send them to the decoder.
1204
+ // But since we did just receive a frame, we should skip reading more
1205
+ // packets and sending them to the decoder and just try to receive more
1206
+ // frames from the decoder.
1207
+ continue;
1208
+ }
1209
+
1210
+ if (reachedEOF) {
1211
+ // We don't have any more packets to receive. So keep on pulling frames
1212
+ // from decoder's internal buffers.
1213
+ continue;
1214
+ }
1215
+
1216
+ // We still haven't found the frame we're looking for. So let's read more
1217
+ // packets and send them to the decoder.
1218
+ ReferenceAVPacket packet(autoAVPacket);
1219
+ do {
1220
+ status = av_read_frame(formatContext_.get(), packet.get());
1221
+ decodeStats_.numPacketsRead++;
1222
+
1223
+ if (status == AVERROR_EOF) {
1224
+ // End of file reached. We must drain the decoder
1225
+ if (deviceInterface_->canDecodePacketDirectly()) {
1226
+ status = deviceInterface_->sendEOFPacket();
1227
+ } else {
1228
+ status = avcodec_send_packet(
1229
+ streamInfo.codecContext.get(),
1230
+ /*avpkt=*/nullptr);
1231
+ }
1232
+ TORCH_CHECK(
1233
+ status >= AVSUCCESS,
1234
+ "Could not flush decoder: ",
1235
+ getFFMPEGErrorStringFromErrorCode(status));
1236
+
1237
+ reachedEOF = true;
1238
+ break;
1239
+ }
1240
+
1241
+ TORCH_CHECK(
1242
+ status >= AVSUCCESS,
1243
+ "Could not read frame from input file: ",
1244
+ getFFMPEGErrorStringFromErrorCode(status));
1245
+
1246
+ } while (packet->stream_index != activeStreamIndex_);
1247
+
1248
+ if (reachedEOF) {
1249
+ // We don't have any more packets to send to the decoder. So keep on
1250
+ // pulling frames from its internal buffers.
1251
+ continue;
1252
+ }
1253
+
1254
+ // We got a valid packet. Send it to the decoder, and we'll receive it in
1255
+ // the next iteration.
1256
+ if (deviceInterface_->canDecodePacketDirectly()) {
1257
+ status = deviceInterface_->sendPacket(packet);
1258
+ } else {
1259
+ status = avcodec_send_packet(streamInfo.codecContext.get(), packet.get());
1260
+ }
1261
+ TORCH_CHECK(
1262
+ status >= AVSUCCESS,
1263
+ "Could not push packet to decoder: ",
1264
+ getFFMPEGErrorStringFromErrorCode(status));
1265
+
1266
+ decodeStats_.numPacketsSentToDecoder++;
1267
+ }
1268
+
1269
+ if (status < AVSUCCESS) {
1270
+ if (reachedEOF || status == AVERROR_EOF) {
1271
+ throw SingleStreamDecoder::EndOfFileException(
1272
+ "Requested next frame while there are no more frames left to "
1273
+ "decode.");
1274
+ }
1275
+ TORCH_CHECK(
1276
+ false,
1277
+ "Could not receive frame from decoder: ",
1278
+ getFFMPEGErrorStringFromErrorCode(status));
1279
+ }
1280
+
1281
+ // Note that we don't flush the decoder when we reach EOF (even though
1282
+ // that's mentioned in
1283
+ // https://ffmpeg.org/doxygen/trunk/group__lavc__encdec.html). This is
1284
+ // because we may have packets internally in the decoder that we haven't
1285
+ // received as frames. Eventually we will either hit AVERROR_EOF from
1286
+ // av_receive_frame() or the user will have seeked to a different location
1287
+ // in the file and that will flush the decoder.
1288
+ lastDecodedAvFramePts_ = getPtsOrDts(avFrame);
1289
+ lastDecodedAvFrameDuration_ = getDuration(avFrame);
1290
+
1291
+ return avFrame;
1292
+ }
1293
+
1294
+ // --------------------------------------------------------------------------
1295
+ // AVFRAME <-> FRAME OUTPUT CONVERSION
1296
+ // --------------------------------------------------------------------------
1297
+
1298
+ FrameOutput SingleStreamDecoder::convertAVFrameToFrameOutput(
1299
+ UniqueAVFrame& avFrame,
1300
+ std::optional<torch::Tensor> preAllocatedOutputTensor) {
1301
+ // Convert the frame to tensor.
1302
+ FrameOutput frameOutput;
1303
+ auto& streamInfo = streamInfos_[activeStreamIndex_];
1304
+ frameOutput.ptsSeconds = ptsToSeconds(
1305
+ getPtsOrDts(avFrame),
1306
+ formatContext_->streams[activeStreamIndex_]->time_base);
1307
+ frameOutput.durationSeconds = ptsToSeconds(
1308
+ getDuration(avFrame),
1309
+ formatContext_->streams[activeStreamIndex_]->time_base);
1310
+ if (streamInfo.avMediaType == AVMEDIA_TYPE_AUDIO) {
1311
+ convertAudioAVFrameToFrameOutputOnCPU(avFrame, frameOutput);
1312
+ } else {
1313
+ deviceInterface_->convertAVFrameToFrameOutput(
1314
+ avFrame, frameOutput, preAllocatedOutputTensor);
1315
+ }
1316
+ return frameOutput;
1317
+ }
1318
+
1319
+ void SingleStreamDecoder::convertAudioAVFrameToFrameOutputOnCPU(
1320
+ UniqueAVFrame& srcAVFrame,
1321
+ FrameOutput& frameOutput) {
1322
+ AVSampleFormat srcSampleFormat =
1323
+ static_cast<AVSampleFormat>(srcAVFrame->format);
1324
+ AVSampleFormat outSampleFormat = AV_SAMPLE_FMT_FLTP;
1325
+
1326
+ StreamInfo& streamInfo = streamInfos_[activeStreamIndex_];
1327
+ int srcSampleRate = srcAVFrame->sample_rate;
1328
+ int outSampleRate =
1329
+ streamInfo.audioStreamOptions.sampleRate.value_or(srcSampleRate);
1330
+
1331
+ int srcNumChannels = getNumChannels(streamInfo.codecContext);
1332
+ TORCH_CHECK(
1333
+ srcNumChannels == getNumChannels(srcAVFrame),
1334
+ "The frame has ",
1335
+ getNumChannels(srcAVFrame),
1336
+ " channels, expected ",
1337
+ srcNumChannels,
1338
+ ". If you are hitting this, it may be because you are using "
1339
+ "a buggy FFmpeg version. FFmpeg4 is known to fail here in some "
1340
+ "valid scenarios. Try to upgrade FFmpeg?");
1341
+ int outNumChannels =
1342
+ streamInfo.audioStreamOptions.numChannels.value_or(srcNumChannels);
1343
+
1344
+ bool mustConvert =
1345
+ (srcSampleFormat != outSampleFormat || srcSampleRate != outSampleRate ||
1346
+ srcNumChannels != outNumChannels);
1347
+
1348
+ UniqueAVFrame convertedAVFrame;
1349
+ if (mustConvert) {
1350
+ if (!swrContext_) {
1351
+ swrContext_.reset(createSwrContext(
1352
+ srcSampleFormat,
1353
+ outSampleFormat,
1354
+ srcSampleRate,
1355
+ outSampleRate,
1356
+ srcAVFrame,
1357
+ outNumChannels));
1358
+ }
1359
+
1360
+ convertedAVFrame = convertAudioAVFrameSamples(
1361
+ swrContext_,
1362
+ srcAVFrame,
1363
+ outSampleFormat,
1364
+ outSampleRate,
1365
+ outNumChannels);
1366
+ }
1367
+ const UniqueAVFrame& avFrame = mustConvert ? convertedAVFrame : srcAVFrame;
1368
+
1369
+ AVSampleFormat format = static_cast<AVSampleFormat>(avFrame->format);
1370
+ TORCH_CHECK(
1371
+ format == outSampleFormat,
1372
+ "Something went wrong, the frame didn't get converted to the desired format. ",
1373
+ "Desired format = ",
1374
+ av_get_sample_fmt_name(outSampleFormat),
1375
+ "source format = ",
1376
+ av_get_sample_fmt_name(format));
1377
+
1378
+ int numChannels = getNumChannels(avFrame);
1379
+ TORCH_CHECK(
1380
+ numChannels == outNumChannels,
1381
+ "Something went wrong, the frame didn't get converted to the desired ",
1382
+ "number of channels = ",
1383
+ outNumChannels,
1384
+ ". Got ",
1385
+ numChannels,
1386
+ " instead.");
1387
+
1388
+ auto numSamples = avFrame->nb_samples; // per channel
1389
+
1390
+ frameOutput.data = torch::empty({numChannels, numSamples}, torch::kFloat32);
1391
+
1392
+ if (numSamples > 0) {
1393
+ uint8_t* outputChannelData =
1394
+ static_cast<uint8_t*>(frameOutput.data.data_ptr());
1395
+ auto numBytesPerChannel = numSamples * av_get_bytes_per_sample(format);
1396
+ for (auto channel = 0; channel < numChannels;
1397
+ ++channel, outputChannelData += numBytesPerChannel) {
1398
+ std::memcpy(
1399
+ outputChannelData,
1400
+ avFrame->extended_data[channel],
1401
+ numBytesPerChannel);
1402
+ }
1403
+ }
1404
+ }
1405
+
1406
+ std::optional<torch::Tensor> SingleStreamDecoder::maybeFlushSwrBuffers() {
1407
+ // When sample rate conversion is involved, swresample buffers some of the
1408
+ // samples in-between calls to swr_convert (see the libswresample docs).
1409
+ // That's because the last few samples in a given frame require future
1410
+ // samples from the next frame to be properly converted. This function
1411
+ // flushes out the samples that are stored in swresample's buffers.
1412
+ auto& streamInfo = streamInfos_[activeStreamIndex_];
1413
+ if (!swrContext_) {
1414
+ return std::nullopt;
1415
+ }
1416
+ auto numRemainingSamples = // this is an upper bound
1417
+ swr_get_out_samples(swrContext_.get(), 0);
1418
+
1419
+ if (numRemainingSamples == 0) {
1420
+ return std::nullopt;
1421
+ }
1422
+
1423
+ int numChannels = streamInfo.audioStreamOptions.numChannels.value_or(
1424
+ getNumChannels(streamInfo.codecContext));
1425
+ torch::Tensor lastSamples =
1426
+ torch::empty({numChannels, numRemainingSamples}, torch::kFloat32);
1427
+
1428
+ std::vector<uint8_t*> outputBuffers(numChannels);
1429
+ for (auto i = 0; i < numChannels; i++) {
1430
+ outputBuffers[i] = static_cast<uint8_t*>(lastSamples[i].data_ptr());
1431
+ }
1432
+
1433
+ auto actualNumRemainingSamples = swr_convert(
1434
+ swrContext_.get(), outputBuffers.data(), numRemainingSamples, nullptr, 0);
1435
+
1436
+ return lastSamples.narrow(
1437
+ /*dim=*/1, /*start=*/0, /*length=*/actualNumRemainingSamples);
1438
+ }
1439
+
1440
+ // --------------------------------------------------------------------------
1441
+ // OUTPUT ALLOCATION AND SHAPE CONVERSION
1442
+ // --------------------------------------------------------------------------
1443
+
1444
+ // Returns a [N]CHW *view* of a [N]HWC input tensor, if the options require
1445
+ // so. The [N] leading batch-dimension is optional i.e. the input tensor can
1446
+ // be 3D or 4D. Calling permute() is guaranteed to return a view as per the
1447
+ // docs: https://pytorch.org/docs/stable/generated/torch.permute.html
1448
+ torch::Tensor SingleStreamDecoder::maybePermuteHWC2CHW(
1449
+ torch::Tensor& hwcTensor) {
1450
+ if (streamInfos_[activeStreamIndex_].videoStreamOptions.dimensionOrder ==
1451
+ "NHWC") {
1452
+ return hwcTensor;
1453
+ }
1454
+ auto numDimensions = hwcTensor.dim();
1455
+ auto shape = hwcTensor.sizes();
1456
+ if (numDimensions == 3) {
1457
+ TORCH_CHECK(shape[2] == 3, "Not a HWC tensor: ", shape);
1458
+ return hwcTensor.permute({2, 0, 1});
1459
+ } else if (numDimensions == 4) {
1460
+ TORCH_CHECK(shape[3] == 3, "Not a NHWC tensor: ", shape);
1461
+ return hwcTensor.permute({0, 3, 1, 2});
1462
+ } else {
1463
+ TORCH_CHECK(
1464
+ false, "Expected tensor with 3 or 4 dimensions, got ", numDimensions);
1465
+ }
1466
+ }
1467
+
1468
+ // --------------------------------------------------------------------------
1469
+ // PTS <-> INDEX CONVERSIONS
1470
+ // --------------------------------------------------------------------------
1471
+
1472
+ int SingleStreamDecoder::getKeyFrameIndexForPts(int64_t pts) const {
1473
+ const StreamInfo& streamInfo = streamInfos_.at(activeStreamIndex_);
1474
+ if (streamInfo.keyFrames.empty()) {
1475
+ return av_index_search_timestamp(
1476
+ streamInfo.stream, pts, AVSEEK_FLAG_BACKWARD);
1477
+ } else {
1478
+ return getKeyFrameIndexForPtsUsingScannedIndex(streamInfo.keyFrames, pts);
1479
+ }
1480
+ }
1481
+
1482
+ int SingleStreamDecoder::getKeyFrameIndexForPtsUsingScannedIndex(
1483
+ const std::vector<SingleStreamDecoder::FrameInfo>& keyFrames,
1484
+ int64_t pts) const {
1485
+ auto upperBound = std::upper_bound(
1486
+ keyFrames.begin(),
1487
+ keyFrames.end(),
1488
+ pts,
1489
+ [](int64_t pts, const SingleStreamDecoder::FrameInfo& frameInfo) {
1490
+ return pts < frameInfo.pts;
1491
+ });
1492
+ if (upperBound == keyFrames.begin()) {
1493
+ return -1;
1494
+ }
1495
+ return upperBound - 1 - keyFrames.begin();
1496
+ }
1497
+
1498
+ int64_t SingleStreamDecoder::secondsToIndexLowerBound(double seconds) {
1499
+ auto& streamInfo = streamInfos_[activeStreamIndex_];
1500
+ switch (seekMode_) {
1501
+ case SeekMode::custom_frame_mappings:
1502
+ case SeekMode::exact: {
1503
+ auto frame = std::lower_bound(
1504
+ streamInfo.allFrames.begin(),
1505
+ streamInfo.allFrames.end(),
1506
+ seconds,
1507
+ [&streamInfo](const FrameInfo& info, double start) {
1508
+ return ptsToSeconds(info.nextPts, streamInfo.timeBase) <= start;
1509
+ });
1510
+
1511
+ return frame - streamInfo.allFrames.begin();
1512
+ }
1513
+ case SeekMode::approximate: {
1514
+ auto& streamMetadata =
1515
+ containerMetadata_.allStreamMetadata[activeStreamIndex_];
1516
+ TORCH_CHECK(
1517
+ streamMetadata.averageFpsFromHeader.has_value(),
1518
+ "Cannot use approximate mode since we couldn't find the average fps from the metadata.");
1519
+ return std::floor(seconds * streamMetadata.averageFpsFromHeader.value());
1520
+ }
1521
+ default:
1522
+ TORCH_CHECK(false, "Unknown SeekMode");
1523
+ }
1524
+ }
1525
+
1526
+ int64_t SingleStreamDecoder::secondsToIndexUpperBound(double seconds) {
1527
+ auto& streamInfo = streamInfos_[activeStreamIndex_];
1528
+ switch (seekMode_) {
1529
+ case SeekMode::custom_frame_mappings:
1530
+ case SeekMode::exact: {
1531
+ auto frame = std::upper_bound(
1532
+ streamInfo.allFrames.begin(),
1533
+ streamInfo.allFrames.end(),
1534
+ seconds,
1535
+ [&streamInfo](double stop, const FrameInfo& info) {
1536
+ return stop <= ptsToSeconds(info.pts, streamInfo.timeBase);
1537
+ });
1538
+
1539
+ return frame - streamInfo.allFrames.begin();
1540
+ }
1541
+ case SeekMode::approximate: {
1542
+ auto& streamMetadata =
1543
+ containerMetadata_.allStreamMetadata[activeStreamIndex_];
1544
+ TORCH_CHECK(
1545
+ streamMetadata.averageFpsFromHeader.has_value(),
1546
+ "Cannot use approximate mode since we couldn't find the average fps from the metadata.");
1547
+ return std::ceil(seconds * streamMetadata.averageFpsFromHeader.value());
1548
+ }
1549
+ default:
1550
+ TORCH_CHECK(false, "Unknown SeekMode");
1551
+ }
1552
+ }
1553
+
1554
+ int64_t SingleStreamDecoder::getPts(int64_t frameIndex) {
1555
+ auto& streamInfo = streamInfos_[activeStreamIndex_];
1556
+ switch (seekMode_) {
1557
+ case SeekMode::custom_frame_mappings:
1558
+ case SeekMode::exact:
1559
+ return streamInfo.allFrames[frameIndex].pts;
1560
+ case SeekMode::approximate: {
1561
+ auto& streamMetadata =
1562
+ containerMetadata_.allStreamMetadata[activeStreamIndex_];
1563
+ TORCH_CHECK(
1564
+ streamMetadata.averageFpsFromHeader.has_value(),
1565
+ "Cannot use approximate mode since we couldn't find the average fps from the metadata.");
1566
+ return secondsToClosestPts(
1567
+ frameIndex / streamMetadata.averageFpsFromHeader.value(),
1568
+ streamInfo.timeBase);
1569
+ }
1570
+ default:
1571
+ TORCH_CHECK(false, "Unknown SeekMode");
1572
+ }
1573
+ }
1574
+
1575
+ // --------------------------------------------------------------------------
1576
+ // STREAM AND METADATA APIS
1577
+ // --------------------------------------------------------------------------
1578
+
1579
+ std::optional<int64_t> SingleStreamDecoder::getNumFrames(
1580
+ const StreamMetadata& streamMetadata) {
1581
+ switch (seekMode_) {
1582
+ case SeekMode::custom_frame_mappings:
1583
+ case SeekMode::exact:
1584
+ return streamMetadata.numFramesFromContent.value();
1585
+ case SeekMode::approximate: {
1586
+ return streamMetadata.numFramesFromHeader;
1587
+ }
1588
+ default:
1589
+ TORCH_CHECK(false, "Unknown SeekMode");
1590
+ }
1591
+ }
1592
+
1593
+ double SingleStreamDecoder::getMinSeconds(
1594
+ const StreamMetadata& streamMetadata) {
1595
+ switch (seekMode_) {
1596
+ case SeekMode::custom_frame_mappings:
1597
+ case SeekMode::exact:
1598
+ return streamMetadata.beginStreamPtsSecondsFromContent.value();
1599
+ case SeekMode::approximate:
1600
+ return 0;
1601
+ default:
1602
+ TORCH_CHECK(false, "Unknown SeekMode");
1603
+ }
1604
+ }
1605
+
1606
+ std::optional<double> SingleStreamDecoder::getMaxSeconds(
1607
+ const StreamMetadata& streamMetadata) {
1608
+ switch (seekMode_) {
1609
+ case SeekMode::custom_frame_mappings:
1610
+ case SeekMode::exact:
1611
+ return streamMetadata.endStreamPtsSecondsFromContent.value();
1612
+ case SeekMode::approximate: {
1613
+ return streamMetadata.durationSecondsFromHeader;
1614
+ }
1615
+ default:
1616
+ TORCH_CHECK(false, "Unknown SeekMode");
1617
+ }
1618
+ }
1619
+
1620
+ // --------------------------------------------------------------------------
1621
+ // VALIDATION UTILS
1622
+ // --------------------------------------------------------------------------
1623
+
1624
+ void SingleStreamDecoder::validateActiveStream(
1625
+ std::optional<AVMediaType> avMediaType) {
1626
+ auto errorMsg =
1627
+ "Provided stream index=" + std::to_string(activeStreamIndex_) +
1628
+ " was not previously added.";
1629
+ TORCH_CHECK(activeStreamIndex_ != NO_ACTIVE_STREAM, errorMsg);
1630
+ TORCH_CHECK(streamInfos_.count(activeStreamIndex_) > 0, errorMsg);
1631
+
1632
+ int allStreamMetadataSize =
1633
+ static_cast<int>(containerMetadata_.allStreamMetadata.size());
1634
+ TORCH_CHECK(
1635
+ activeStreamIndex_ >= 0 && activeStreamIndex_ < allStreamMetadataSize,
1636
+ "Invalid stream index=" + std::to_string(activeStreamIndex_) +
1637
+ "; valid indices are in the range [0, " +
1638
+ std::to_string(allStreamMetadataSize) + ").");
1639
+
1640
+ if (avMediaType.has_value()) {
1641
+ TORCH_CHECK(
1642
+ streamInfos_[activeStreamIndex_].avMediaType == avMediaType.value(),
1643
+ "The method you called isn't supported. ",
1644
+ "If you're seeing this error, you are probably trying to call an ",
1645
+ "unsupported method on an audio stream.");
1646
+ }
1647
+ }
1648
+
1649
+ void SingleStreamDecoder::validateScannedAllStreams(const std::string& msg) {
1650
+ TORCH_CHECK(
1651
+ scannedAllStreams_,
1652
+ "Must scan all streams to update metadata before calling ",
1653
+ msg);
1654
+ }
1655
+
1656
+ void SingleStreamDecoder::validateFrameIndex(
1657
+ const StreamMetadata& streamMetadata,
1658
+ int64_t frameIndex) {
1659
+ if (frameIndex < 0) {
1660
+ throw std::out_of_range(
1661
+ "Invalid frame index=" + std::to_string(frameIndex) +
1662
+ " for streamIndex=" + std::to_string(streamMetadata.streamIndex) +
1663
+ "; negative indices must have an absolute value less than the number of frames, "
1664
+ "and the number of frames must be known.");
1665
+ }
1666
+
1667
+ // Note that if we do not have the number of frames available in our
1668
+ // metadata, then we assume that the frameIndex is valid.
1669
+ std::optional<int64_t> numFrames = getNumFrames(streamMetadata);
1670
+ if (numFrames.has_value()) {
1671
+ if (frameIndex >= numFrames.value()) {
1672
+ throw std::out_of_range(
1673
+ "Invalid frame index=" + std::to_string(frameIndex) +
1674
+ " for streamIndex=" + std::to_string(streamMetadata.streamIndex) +
1675
+ "; must be less than " + std::to_string(numFrames.value()));
1676
+ }
1677
+ }
1678
+ }
1679
+
1680
+ // --------------------------------------------------------------------------
1681
+ // MORALLY PRIVATE UTILS
1682
+ // --------------------------------------------------------------------------
1683
+
1684
+ SingleStreamDecoder::DecodeStats SingleStreamDecoder::getDecodeStats() const {
1685
+ return decodeStats_;
1686
+ }
1687
+
1688
+ std::ostream& operator<<(
1689
+ std::ostream& os,
1690
+ const SingleStreamDecoder::DecodeStats& stats) {
1691
+ os << "DecodeStats{"
1692
+ << "numFramesReceivedByDecoder=" << stats.numFramesReceivedByDecoder
1693
+ << ", numPacketsRead=" << stats.numPacketsRead
1694
+ << ", numPacketsSentToDecoder=" << stats.numPacketsSentToDecoder
1695
+ << ", numSeeksAttempted=" << stats.numSeeksAttempted
1696
+ << ", numSeeksSkipped=" << stats.numSeeksSkipped
1697
+ << ", numFlushes=" << stats.numFlushes << "}";
1698
+
1699
+ return os;
1700
+ }
1701
+
1702
+ void SingleStreamDecoder::resetDecodeStats() {
1703
+ decodeStats_ = DecodeStats{};
1704
+ }
1705
+
1706
+ double SingleStreamDecoder::getPtsSecondsForFrame(int64_t frameIndex) {
1707
+ validateActiveStream(AVMEDIA_TYPE_VIDEO);
1708
+ validateScannedAllStreams("getPtsSecondsForFrame");
1709
+
1710
+ const auto& streamInfo = streamInfos_[activeStreamIndex_];
1711
+ const auto& streamMetadata =
1712
+ containerMetadata_.allStreamMetadata[activeStreamIndex_];
1713
+ validateFrameIndex(streamMetadata, frameIndex);
1714
+
1715
+ return ptsToSeconds(
1716
+ streamInfo.allFrames[frameIndex].pts, streamInfo.timeBase);
1717
+ }
1718
+
1719
+ } // namespace facebook::torchcodec