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