forked from meta-pytorch/torchcodec
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSingleStreamDecoder.cpp
More file actions
1710 lines (1479 loc) · 63.8 KB
/
SingleStreamDecoder.cpp
File metadata and controls
1710 lines (1479 loc) · 63.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Meta Platforms, Inc. and affiliates.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include "src/torchcodec/_core/SingleStreamDecoder.h"
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string_view>
#include "Metadata.h"
#include "torch/types.h"
namespace facebook::torchcodec {
namespace {
// Some videos aren't properly encoded and do not specify pts values for
// packets, and thus for frames. Unset values correspond to INT64_MIN. When that
// happens, we fallback to the dts value which hopefully exists and is correct.
// Accessing AVFrames and AVPackets's pts values should **always** go through
// the helpers below. Then, the "pts" fields in our structs like FrameInfo.pts
// should be interpreted as "pts if it exists, dts otherwise".
int64_t getPtsOrDts(ReferenceAVPacket& packet) {
return packet->pts == INT64_MIN ? packet->dts : packet->pts;
}
int64_t getPtsOrDts(const UniqueAVFrame& avFrame) {
return avFrame->pts == INT64_MIN ? avFrame->pkt_dts : avFrame->pts;
}
} // namespace
// --------------------------------------------------------------------------
// CONSTRUCTORS, INITIALIZATION, DESTRUCTORS
// --------------------------------------------------------------------------
SingleStreamDecoder::SingleStreamDecoder(
const std::string& videoFilePath,
SeekMode seekMode)
: seekMode_(seekMode) {
setFFmpegLogLevel();
AVFormatContext* rawContext = nullptr;
int status =
avformat_open_input(&rawContext, videoFilePath.c_str(), nullptr, nullptr);
TORCH_CHECK(
status == 0,
"Could not open input file: " + videoFilePath + " " +
getFFMPEGErrorStringFromErrorCode(status));
TORCH_CHECK(rawContext != nullptr);
formatContext_.reset(rawContext);
initializeDecoder();
}
SingleStreamDecoder::SingleStreamDecoder(
std::unique_ptr<AVIOContextHolder> context,
SeekMode seekMode)
: seekMode_(seekMode), avioContextHolder_(std::move(context)) {
setFFmpegLogLevel();
TORCH_CHECK(avioContextHolder_, "Context holder cannot be null");
// Because FFmpeg requires a reference to a pointer in the call to open, we
// can't use a unique pointer here. Note that means we must call free if open
// fails.
AVFormatContext* rawContext = avformat_alloc_context();
TORCH_CHECK(rawContext != nullptr, "Unable to alloc avformat context");
rawContext->pb = avioContextHolder_->getAVIOContext();
int status = avformat_open_input(&rawContext, nullptr, nullptr, nullptr);
if (status != 0) {
avformat_free_context(rawContext);
TORCH_CHECK(
false,
"Failed to open input buffer: " +
getFFMPEGErrorStringFromErrorCode(status));
}
formatContext_.reset(rawContext);
initializeDecoder();
}
void SingleStreamDecoder::initializeDecoder() {
TORCH_CHECK(!initialized_, "Attempted double initialization.");
// In principle, the AVFormatContext should be filled in by the call to
// avformat_open_input() which reads the header. However, some formats do not
// store enough info in the header, so we call avformat_find_stream_info()
// which decodes a few frames to get missing info. For more, see:
// https://ffmpeg.org/doxygen/7.0/group__lavf__decoding.html
int status = avformat_find_stream_info(formatContext_.get(), nullptr);
TORCH_CHECK(
status >= 0,
"Failed to find stream info: ",
getFFMPEGErrorStringFromErrorCode(status));
for (unsigned int i = 0; i < formatContext_->nb_streams; i++) {
AVStream* avStream = formatContext_->streams[i];
StreamMetadata streamMetadata;
TORCH_CHECK(
static_cast<int>(i) == avStream->index,
"Our stream index, " + std::to_string(i) +
", does not match AVStream's index, " +
std::to_string(avStream->index) + ".");
streamMetadata.streamIndex = i;
streamMetadata.mediaType = avStream->codecpar->codec_type;
streamMetadata.codecName = avcodec_get_name(avStream->codecpar->codec_id);
streamMetadata.bitRate = avStream->codecpar->bit_rate;
int64_t frameCount = avStream->nb_frames;
if (frameCount > 0) {
streamMetadata.numFramesFromHeader = frameCount;
}
if (avStream->duration > 0 && avStream->time_base.den > 0) {
streamMetadata.durationSecondsFromHeader =
ptsToSeconds(avStream->duration, avStream->time_base);
}
if (avStream->start_time != AV_NOPTS_VALUE) {
streamMetadata.beginStreamSecondsFromHeader =
ptsToSeconds(avStream->start_time, avStream->time_base);
}
if (avStream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
double fps = av_q2d(avStream->r_frame_rate);
if (fps > 0) {
streamMetadata.averageFpsFromHeader = fps;
}
containerMetadata_.numVideoStreams++;
} else if (avStream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
AVSampleFormat format =
static_cast<AVSampleFormat>(avStream->codecpar->format);
// If the AVSampleFormat is not recognized, we get back nullptr. We have
// to make sure we don't initialize a std::string with nullptr. There's
// nothing to do on the else branch because we're already using an
// optional; it'll just remain empty.
const char* rawSampleFormat = av_get_sample_fmt_name(format);
if (rawSampleFormat != nullptr) {
streamMetadata.sampleFormat = std::string(rawSampleFormat);
}
containerMetadata_.numAudioStreams++;
}
containerMetadata_.allStreamMetadata.push_back(streamMetadata);
}
if (formatContext_->duration > 0) {
AVRational defaultTimeBase{1, AV_TIME_BASE};
containerMetadata_.durationSecondsFromHeader =
ptsToSeconds(formatContext_->duration, defaultTimeBase);
}
if (formatContext_->bit_rate > 0) {
containerMetadata_.bitRate = formatContext_->bit_rate;
}
int bestVideoStream = getBestStreamIndex(AVMEDIA_TYPE_VIDEO);
if (bestVideoStream >= 0) {
containerMetadata_.bestVideoStreamIndex = bestVideoStream;
}
int bestAudioStream = getBestStreamIndex(AVMEDIA_TYPE_AUDIO);
if (bestAudioStream >= 0) {
containerMetadata_.bestAudioStreamIndex = bestAudioStream;
}
if (seekMode_ == SeekMode::exact) {
scanFileAndUpdateMetadataAndIndex();
}
initialized_ = true;
}
int SingleStreamDecoder::getBestStreamIndex(AVMediaType mediaType) {
AVCodecOnlyUseForCallingAVFindBestStream avCodec = nullptr;
int streamIndex =
av_find_best_stream(formatContext_.get(), mediaType, -1, -1, &avCodec, 0);
return streamIndex;
}
// --------------------------------------------------------------------------
// VIDEO METADATA QUERY API
// --------------------------------------------------------------------------
void SingleStreamDecoder::sortAllFrames() {
// Sort the allFrames and keyFrames vecs in each stream, and also sets
// additional fields of the FrameInfo entries like nextPts and frameIndex
// This is called at the end of a scan, or when setting a user-defined frame
// mapping.
for (auto& [streamIndex, streamInfo] : streamInfos_) {
std::sort(
streamInfo.keyFrames.begin(),
streamInfo.keyFrames.end(),
[](const FrameInfo& frameInfo1, const FrameInfo& frameInfo2) {
return frameInfo1.pts < frameInfo2.pts;
});
std::sort(
streamInfo.allFrames.begin(),
streamInfo.allFrames.end(),
[](const FrameInfo& frameInfo1, const FrameInfo& frameInfo2) {
return frameInfo1.pts < frameInfo2.pts;
});
size_t keyFrameIndex = 0;
for (size_t i = 0; i < streamInfo.allFrames.size(); ++i) {
streamInfo.allFrames[i].frameIndex = i;
if (streamInfo.allFrames[i].isKeyFrame) {
TORCH_CHECK(
keyFrameIndex < streamInfo.keyFrames.size(),
"The allFrames vec claims it has MORE keyFrames than the keyFrames vec. There's a bug in torchcodec.");
streamInfo.keyFrames[keyFrameIndex].frameIndex = i;
++keyFrameIndex;
}
if (i + 1 < streamInfo.allFrames.size()) {
streamInfo.allFrames[i].nextPts = streamInfo.allFrames[i + 1].pts;
}
}
TORCH_CHECK(
keyFrameIndex == streamInfo.keyFrames.size(),
"The allFrames vec claims it has LESS keyFrames than the keyFrames vec. There's a bug in torchcodec.");
}
}
void SingleStreamDecoder::scanFileAndUpdateMetadataAndIndex() {
if (scannedAllStreams_) {
return;
}
AutoAVPacket autoAVPacket;
while (true) {
ReferenceAVPacket packet(autoAVPacket);
// av_read_frame is a misleading name: it gets the next **packet**.
int status = av_read_frame(formatContext_.get(), packet.get());
if (status == AVERROR_EOF) {
break;
}
TORCH_CHECK(
status == AVSUCCESS,
"Failed to read frame from input file: ",
getFFMPEGErrorStringFromErrorCode(status));
if (packet->flags & AV_PKT_FLAG_DISCARD) {
continue;
}
// We got a valid packet. Let's figure out what stream it belongs to and
// record its relevant metadata.
int streamIndex = packet->stream_index;
auto& streamMetadata = containerMetadata_.allStreamMetadata[streamIndex];
streamMetadata.beginStreamPtsFromContent = std::min(
streamMetadata.beginStreamPtsFromContent.value_or(INT64_MAX),
getPtsOrDts(packet));
streamMetadata.endStreamPtsFromContent = std::max(
streamMetadata.endStreamPtsFromContent.value_or(INT64_MIN),
getPtsOrDts(packet) + packet->duration);
streamMetadata.numFramesFromContent =
streamMetadata.numFramesFromContent.value_or(0) + 1;
// Note that we set the other value in this struct, nextPts, only after
// we have scanned all packets and sorted by pts.
FrameInfo frameInfo = {getPtsOrDts(packet)};
if (packet->flags & AV_PKT_FLAG_KEY) {
frameInfo.isKeyFrame = true;
streamInfos_[streamIndex].keyFrames.push_back(frameInfo);
}
streamInfos_[streamIndex].allFrames.push_back(frameInfo);
}
// Set all per-stream metadata that requires knowing the content of all
// packets.
for (size_t streamIndex = 0;
streamIndex < containerMetadata_.allStreamMetadata.size();
++streamIndex) {
auto& streamMetadata = containerMetadata_.allStreamMetadata[streamIndex];
auto avStream = formatContext_->streams[streamIndex];
streamMetadata.numFramesFromContent =
streamInfos_[streamIndex].allFrames.size();
if (streamMetadata.beginStreamPtsFromContent.has_value()) {
streamMetadata.beginStreamPtsSecondsFromContent = ptsToSeconds(
*streamMetadata.beginStreamPtsFromContent, avStream->time_base);
}
if (streamMetadata.endStreamPtsFromContent.has_value()) {
streamMetadata.endStreamPtsSecondsFromContent = ptsToSeconds(
*streamMetadata.endStreamPtsFromContent, avStream->time_base);
}
}
// Reset the seek-cursor back to the beginning.
int status = avformat_seek_file(formatContext_.get(), 0, INT64_MIN, 0, 0, 0);
TORCH_CHECK(
status >= 0,
"Could not seek file to pts=0: ",
getFFMPEGErrorStringFromErrorCode(status));
// Sort all frames by their pts.
sortAllFrames();
scannedAllStreams_ = true;
}
void SingleStreamDecoder::readCustomFrameMappingsUpdateMetadataAndIndex(
int streamIndex,
FrameMappings customFrameMappings) {
TORCH_CHECK(
customFrameMappings.all_frames.dtype() == torch::kLong &&
customFrameMappings.is_key_frame.dtype() == torch::kBool &&
customFrameMappings.duration.dtype() == torch::kLong,
"all_frames and duration tensors must be int64 dtype, and is_key_frame tensor must be a bool dtype.");
const torch::Tensor& all_frames =
customFrameMappings.all_frames.to(torch::kLong);
const torch::Tensor& is_key_frame =
customFrameMappings.is_key_frame.to(torch::kBool);
const torch::Tensor& duration = customFrameMappings.duration.to(torch::kLong);
TORCH_CHECK(
all_frames.size(0) == is_key_frame.size(0) &&
is_key_frame.size(0) == duration.size(0),
"all_frames, is_key_frame, and duration from custom_frame_mappings were not same size.");
// Allocate vectors using num frames to reduce reallocations
int64_t numFrames = all_frames.size(0);
streamInfos_[streamIndex].allFrames.reserve(numFrames);
streamInfos_[streamIndex].keyFrames.reserve(numFrames);
// Use accessor to efficiently access tensor elements
auto pts_data = all_frames.accessor<int64_t, 1>();
auto is_key_frame_data = is_key_frame.accessor<bool, 1>();
auto duration_data = duration.accessor<int64_t, 1>();
auto& streamMetadata = containerMetadata_.allStreamMetadata[streamIndex];
streamMetadata.beginStreamPtsFromContent = pts_data[0];
streamMetadata.endStreamPtsFromContent =
pts_data[numFrames - 1] + duration_data[numFrames - 1];
auto avStream = formatContext_->streams[streamIndex];
streamMetadata.beginStreamPtsSecondsFromContent = ptsToSeconds(
*streamMetadata.beginStreamPtsFromContent, avStream->time_base);
streamMetadata.endStreamPtsSecondsFromContent = ptsToSeconds(
*streamMetadata.endStreamPtsFromContent, avStream->time_base);
streamMetadata.numFramesFromContent = numFrames;
for (int64_t i = 0; i < numFrames; ++i) {
FrameInfo frameInfo;
frameInfo.pts = pts_data[i];
frameInfo.isKeyFrame = is_key_frame_data[i];
streamInfos_[streamIndex].allFrames.push_back(frameInfo);
if (frameInfo.isKeyFrame) {
streamInfos_[streamIndex].keyFrames.push_back(frameInfo);
}
}
sortAllFrames();
}
ContainerMetadata SingleStreamDecoder::getContainerMetadata() const {
return containerMetadata_;
}
torch::Tensor SingleStreamDecoder::getKeyFrameIndices() {
validateActiveStream(AVMEDIA_TYPE_VIDEO);
validateScannedAllStreams("getKeyFrameIndices");
const std::vector<FrameInfo>& keyFrames =
streamInfos_[activeStreamIndex_].keyFrames;
torch::Tensor keyFrameIndices =
torch::empty({static_cast<int64_t>(keyFrames.size())}, {torch::kInt64});
for (size_t i = 0; i < keyFrames.size(); ++i) {
keyFrameIndices[i] = keyFrames[i].frameIndex;
}
return keyFrameIndices;
}
// --------------------------------------------------------------------------
// ADDING STREAMS API
// --------------------------------------------------------------------------
void SingleStreamDecoder::addStream(
int streamIndex,
AVMediaType mediaType,
const torch::Device& device,
const std::string_view deviceVariant,
std::optional<int> ffmpegThreadCount) {
TORCH_CHECK(
activeStreamIndex_ == NO_ACTIVE_STREAM,
"Can only add one single stream.");
TORCH_CHECK(
mediaType == AVMEDIA_TYPE_VIDEO || mediaType == AVMEDIA_TYPE_AUDIO,
"Can only add video or audio streams.");
TORCH_CHECK(formatContext_.get() != nullptr);
AVCodecOnlyUseForCallingAVFindBestStream avCodec = nullptr;
activeStreamIndex_ = av_find_best_stream(
formatContext_.get(), mediaType, streamIndex, -1, &avCodec, 0);
if (activeStreamIndex_ < 0) {
throw std::invalid_argument(
"No valid stream found in input file. Is " +
std::to_string(streamIndex) + " of the desired media type?");
}
TORCH_CHECK(avCodec != nullptr);
StreamInfo& streamInfo = streamInfos_[activeStreamIndex_];
streamInfo.streamIndex = activeStreamIndex_;
streamInfo.timeBase = formatContext_->streams[activeStreamIndex_]->time_base;
streamInfo.stream = formatContext_->streams[activeStreamIndex_];
streamInfo.avMediaType = mediaType;
// This should never happen, checking just to be safe.
TORCH_CHECK(
streamInfo.stream->codecpar->codec_type == mediaType,
"FFmpeg found stream with index ",
activeStreamIndex_,
" which is of the wrong media type.");
deviceInterface_ = createDeviceInterface(device, deviceVariant);
TORCH_CHECK(
deviceInterface_ != nullptr,
"Failed to create device interface. This should never happen, please report.");
// TODO_CODE_QUALITY it's pretty meh to have a video-specific logic within
// addStream() which is supposed to be generic
if (mediaType == AVMEDIA_TYPE_VIDEO) {
avCodec = makeAVCodecOnlyUseForCallingAVFindBestStream(
deviceInterface_->findCodec(streamInfo.stream->codecpar->codec_id)
.value_or(avCodec));
}
AVCodecContext* codecContext = avcodec_alloc_context3(avCodec);
TORCH_CHECK(codecContext != nullptr);
streamInfo.codecContext = makeSharedAVCodecContext(codecContext);
int retVal = avcodec_parameters_to_context(
streamInfo.codecContext.get(), streamInfo.stream->codecpar);
TORCH_CHECK_EQ(retVal, AVSUCCESS);
streamInfo.codecContext->thread_count = ffmpegThreadCount.value_or(0);
streamInfo.codecContext->pkt_timebase = streamInfo.stream->time_base;
// Note that we must make sure to register the harware device context
// with the codec context before calling avcodec_open2(). Otherwise, decoding
// will happen on the CPU and not the hardware device.
deviceInterface_->registerHardwareDeviceWithCodec(
streamInfo.codecContext.get());
retVal = avcodec_open2(streamInfo.codecContext.get(), avCodec, nullptr);
TORCH_CHECK(retVal >= AVSUCCESS, getFFMPEGErrorStringFromErrorCode(retVal));
streamInfo.codecContext->time_base = streamInfo.stream->time_base;
// Initialize the device interface with the codec context
deviceInterface_->initialize(
streamInfo.stream, formatContext_, streamInfo.codecContext);
containerMetadata_.allStreamMetadata[activeStreamIndex_].codecName =
std::string(avcodec_get_name(streamInfo.codecContext->codec_id));
// We will only need packets from the active stream, so we tell FFmpeg to
// discard packets from the other streams. Note that av_read_frame() may still
// return some of those un-desired packet under some conditions, so it's still
// important to discard/demux correctly in the inner decoding loop.
for (unsigned int i = 0; i < formatContext_->nb_streams; ++i) {
if (i != static_cast<unsigned int>(activeStreamIndex_)) {
formatContext_->streams[i]->discard = AVDISCARD_ALL;
}
}
}
void SingleStreamDecoder::addVideoStream(
int streamIndex,
std::vector<Transform*>& transforms,
const VideoStreamOptions& videoStreamOptions,
std::optional<FrameMappings> customFrameMappings) {
TORCH_CHECK(
transforms.empty() || videoStreamOptions.device == torch::kCPU,
" Transforms are only supported for CPU devices.");
addStream(
streamIndex,
AVMEDIA_TYPE_VIDEO,
videoStreamOptions.device,
videoStreamOptions.deviceVariant,
videoStreamOptions.ffmpegThreadCount);
auto& streamMetadata =
containerMetadata_.allStreamMetadata[activeStreamIndex_];
if (seekMode_ == SeekMode::approximate) {
TORCH_CHECK(
streamMetadata.averageFpsFromHeader.has_value(),
"Seek mode is approximate, but stream ",
std::to_string(activeStreamIndex_),
" does not have an average fps in its metadata.");
}
auto& streamInfo = streamInfos_[activeStreamIndex_];
streamInfo.videoStreamOptions = videoStreamOptions;
streamMetadata.width = streamInfo.codecContext->width;
streamMetadata.height = streamInfo.codecContext->height;
streamMetadata.sampleAspectRatio =
streamInfo.codecContext->sample_aspect_ratio;
if (seekMode_ == SeekMode::custom_frame_mappings) {
TORCH_CHECK(
customFrameMappings.has_value(),
"Missing frame mappings when custom_frame_mappings seek mode is set.");
readCustomFrameMappingsUpdateMetadataAndIndex(
activeStreamIndex_, customFrameMappings.value());
}
metadataDims_ =
FrameDims(streamMetadata.height.value(), streamMetadata.width.value());
for (auto& transform : transforms) {
TORCH_CHECK(transform != nullptr, "Transforms should never be nullptr!");
if (transform->getOutputFrameDims().has_value()) {
resizedOutputDims_ = transform->getOutputFrameDims().value();
}
transform->validate(streamMetadata);
// Note that we are claiming ownership of the transform objects passed in to
// us.
transforms_.push_back(std::unique_ptr<Transform>(transform));
}
deviceInterface_->initializeVideo(
videoStreamOptions, transforms_, resizedOutputDims_);
}
void SingleStreamDecoder::addAudioStream(
int streamIndex,
const AudioStreamOptions& audioStreamOptions) {
TORCH_CHECK(
seekMode_ == SeekMode::approximate,
"seek_mode must be 'approximate' for audio streams.");
if (audioStreamOptions.numChannels.has_value()) {
TORCH_CHECK(
*audioStreamOptions.numChannels > 0 &&
*audioStreamOptions.numChannels <= AV_NUM_DATA_POINTERS,
"num_channels must be > 0 and <= AV_NUM_DATA_POINTERS (usually 8). Got: ",
*audioStreamOptions.numChannels);
}
addStream(streamIndex, AVMEDIA_TYPE_AUDIO);
auto& streamInfo = streamInfos_[activeStreamIndex_];
streamInfo.audioStreamOptions = audioStreamOptions;
auto& streamMetadata =
containerMetadata_.allStreamMetadata[activeStreamIndex_];
streamMetadata.sampleRate =
static_cast<int64_t>(streamInfo.codecContext->sample_rate);
streamMetadata.numChannels =
static_cast<int64_t>(getNumChannels(streamInfo.codecContext));
// FFmpeg docs say that the decoder will try to decode natively in this
// format, if it can. Docs don't say what the decoder does when it doesn't
// support that format, but it looks like it does nothing, so this probably
// doesn't hurt.
streamInfo.codecContext->request_sample_fmt = AV_SAMPLE_FMT_FLTP;
}
// --------------------------------------------------------------------------
// HIGH-LEVEL DECODING ENTRY-POINTS
// --------------------------------------------------------------------------
FrameOutput SingleStreamDecoder::getNextFrame() {
auto output = getNextFrameInternal();
if (streamInfos_[activeStreamIndex_].avMediaType == AVMEDIA_TYPE_VIDEO) {
output.data = maybePermuteHWC2CHW(output.data);
}
return output;
}
FrameOutput SingleStreamDecoder::getNextFrameInternal(
std::optional<torch::Tensor> preAllocatedOutputTensor) {
validateActiveStream();
UniqueAVFrame avFrame = decodeAVFrame([this](const UniqueAVFrame& avFrame) {
return getPtsOrDts(avFrame) >= cursor_;
});
return convertAVFrameToFrameOutput(avFrame, preAllocatedOutputTensor);
}
FrameOutput SingleStreamDecoder::getFrameAtIndex(int64_t frameIndex) {
auto frameOutput = getFrameAtIndexInternal(frameIndex);
frameOutput.data = maybePermuteHWC2CHW(frameOutput.data);
return frameOutput;
}
FrameOutput SingleStreamDecoder::getFrameAtIndexInternal(
int64_t frameIndex,
std::optional<torch::Tensor> preAllocatedOutputTensor) {
validateActiveStream(AVMEDIA_TYPE_VIDEO);
const auto& streamInfo = streamInfos_[activeStreamIndex_];
const auto& streamMetadata =
containerMetadata_.allStreamMetadata[activeStreamIndex_];
std::optional<int64_t> numFrames = getNumFrames(streamMetadata);
if (numFrames.has_value()) {
// If the frameIndex is negative, we convert it to a positive index
frameIndex = frameIndex >= 0 ? frameIndex : frameIndex + numFrames.value();
}
validateFrameIndex(streamMetadata, frameIndex);
int64_t pts = getPts(frameIndex);
setCursorPtsInSeconds(ptsToSeconds(pts, streamInfo.timeBase));
return getNextFrameInternal(preAllocatedOutputTensor);
}
FrameBatchOutput SingleStreamDecoder::getFramesAtIndices(
const torch::Tensor& frameIndices) {
validateActiveStream(AVMEDIA_TYPE_VIDEO);
auto frameIndicesAccessor = frameIndices.accessor<int64_t, 1>();
bool indicesAreSorted = true;
for (int64_t i = 1; i < frameIndices.numel(); ++i) {
if (frameIndicesAccessor[i] < frameIndicesAccessor[i - 1]) {
indicesAreSorted = false;
break;
}
}
std::vector<size_t> argsort;
if (!indicesAreSorted) {
// if frameIndices is [13, 10, 12, 11]
// when sorted, it's [10, 11, 12, 13] <-- this is the sorted order we want
// to use to decode the frames
// and argsort is [ 1, 3, 2, 0]
argsort.resize(frameIndices.numel());
for (size_t i = 0; i < argsort.size(); ++i) {
argsort[i] = i;
}
std::sort(
argsort.begin(),
argsort.end(),
[&frameIndicesAccessor](size_t a, size_t b) {
return frameIndicesAccessor[a] < frameIndicesAccessor[b];
});
}
const auto& streamInfo = streamInfos_[activeStreamIndex_];
const auto& videoStreamOptions = streamInfo.videoStreamOptions;
FrameBatchOutput frameBatchOutput(
frameIndices.numel(),
resizedOutputDims_.value_or(metadataDims_),
videoStreamOptions.device);
auto previousIndexInVideo = -1;
for (int64_t f = 0; f < frameIndices.numel(); ++f) {
auto indexInOutput = indicesAreSorted ? f : argsort[f];
auto indexInVideo = frameIndicesAccessor[indexInOutput];
if ((f > 0) && (indexInVideo == previousIndexInVideo)) {
// Avoid decoding the same frame twice
auto previousIndexInOutput = indicesAreSorted ? f - 1 : argsort[f - 1];
frameBatchOutput.data[indexInOutput].copy_(
frameBatchOutput.data[previousIndexInOutput]);
frameBatchOutput.ptsSeconds[indexInOutput] =
frameBatchOutput.ptsSeconds[previousIndexInOutput];
frameBatchOutput.durationSeconds[indexInOutput] =
frameBatchOutput.durationSeconds[previousIndexInOutput];
} else {
FrameOutput frameOutput = getFrameAtIndexInternal(
indexInVideo, frameBatchOutput.data[indexInOutput]);
frameBatchOutput.ptsSeconds[indexInOutput] = frameOutput.ptsSeconds;
frameBatchOutput.durationSeconds[indexInOutput] =
frameOutput.durationSeconds;
}
previousIndexInVideo = indexInVideo;
}
frameBatchOutput.data = maybePermuteHWC2CHW(frameBatchOutput.data);
return frameBatchOutput;
}
FrameBatchOutput SingleStreamDecoder::getFramesInRange(
int64_t start,
int64_t stop,
int64_t step) {
validateActiveStream(AVMEDIA_TYPE_VIDEO);
const auto& streamMetadata =
containerMetadata_.allStreamMetadata[activeStreamIndex_];
const auto& streamInfo = streamInfos_[activeStreamIndex_];
TORCH_CHECK(
start >= 0, "Range start, " + std::to_string(start) + " is less than 0.");
TORCH_CHECK(
step > 0, "Step must be greater than 0; is " + std::to_string(step));
// Note that if we do not have the number of frames available in our
// metadata, then we assume that the upper part of the range is valid.
std::optional<int64_t> numFrames = getNumFrames(streamMetadata);
if (numFrames.has_value()) {
TORCH_CHECK(
stop <= numFrames.value(),
"Range stop, " + std::to_string(stop) +
", is more than the number of frames, " +
std::to_string(numFrames.value()));
}
int64_t numOutputFrames = std::ceil((stop - start) / double(step));
const auto& videoStreamOptions = streamInfo.videoStreamOptions;
FrameBatchOutput frameBatchOutput(
numOutputFrames,
resizedOutputDims_.value_or(metadataDims_),
videoStreamOptions.device);
for (int64_t i = start, f = 0; i < stop; i += step, ++f) {
FrameOutput frameOutput =
getFrameAtIndexInternal(i, frameBatchOutput.data[f]);
frameBatchOutput.ptsSeconds[f] = frameOutput.ptsSeconds;
frameBatchOutput.durationSeconds[f] = frameOutput.durationSeconds;
}
frameBatchOutput.data = maybePermuteHWC2CHW(frameBatchOutput.data);
return frameBatchOutput;
}
FrameOutput SingleStreamDecoder::getFramePlayedAt(double seconds) {
validateActiveStream(AVMEDIA_TYPE_VIDEO);
StreamInfo& streamInfo = streamInfos_[activeStreamIndex_];
double lastDecodedStartTime =
ptsToSeconds(lastDecodedAvFramePts_, streamInfo.timeBase);
double lastDecodedEndTime = ptsToSeconds(
lastDecodedAvFramePts_ + lastDecodedAvFrameDuration_,
streamInfo.timeBase);
if (seconds >= lastDecodedStartTime && seconds < lastDecodedEndTime) {
// We are in the same frame as the one we just returned. However, since we
// don't cache it locally, we have to rewind back.
seconds = lastDecodedStartTime;
}
setCursorPtsInSeconds(seconds);
UniqueAVFrame avFrame =
decodeAVFrame([seconds, this](const UniqueAVFrame& avFrame) {
StreamInfo& streamInfo = streamInfos_[activeStreamIndex_];
double frameStartTime =
ptsToSeconds(getPtsOrDts(avFrame), streamInfo.timeBase);
double frameEndTime = ptsToSeconds(
getPtsOrDts(avFrame) + getDuration(avFrame), streamInfo.timeBase);
if (frameStartTime > seconds) {
// FFMPEG seeked past the frame we are looking for even though we
// set max_ts to be our needed timestamp in avformat_seek_file()
// in maybeSeekToBeforeDesiredPts().
// This could be a bug in FFMPEG:
// https://trac.ffmpeg.org/ticket/11137 In this case we return the
// very next frame instead of throwing an exception.
// TODO: Maybe log to stderr for Debug builds?
return true;
}
return seconds >= frameStartTime && seconds < frameEndTime;
});
// Convert the frame to tensor.
FrameOutput frameOutput = convertAVFrameToFrameOutput(avFrame);
frameOutput.data = maybePermuteHWC2CHW(frameOutput.data);
return frameOutput;
}
FrameBatchOutput SingleStreamDecoder::getFramesPlayedAt(
const torch::Tensor& timestamps) {
validateActiveStream(AVMEDIA_TYPE_VIDEO);
const auto& streamMetadata =
containerMetadata_.allStreamMetadata[activeStreamIndex_];
double minSeconds = getMinSeconds(streamMetadata);
std::optional<double> maxSeconds = getMaxSeconds(streamMetadata);
// The frame played at timestamp t and the one played at timestamp `t +
// eps` are probably the same frame, with the same index. The easiest way to
// avoid decoding that unique frame twice is to convert the input timestamps
// to indices, and leverage the de-duplication logic of getFramesAtIndices.
torch::Tensor frameIndices =
torch::empty({timestamps.numel()}, torch::kInt64);
auto frameIndicesAccessor = frameIndices.accessor<int64_t, 1>();
auto timestampsAccessor = timestamps.accessor<double, 1>();
for (int64_t i = 0; i < timestamps.numel(); ++i) {
auto frameSeconds = timestampsAccessor[i];
TORCH_CHECK(
frameSeconds >= minSeconds,
"frame pts is " + std::to_string(frameSeconds) +
"; must be greater than or equal to " + std::to_string(minSeconds) +
".");
// Note that if we can't determine the maximum number of seconds from the
// metadata, then we assume the frame's pts is valid.
if (maxSeconds.has_value()) {
TORCH_CHECK(
frameSeconds < maxSeconds.value(),
"frame pts is " + std::to_string(frameSeconds) +
"; must be less than " + std::to_string(maxSeconds.value()) +
".");
}
frameIndicesAccessor[i] = secondsToIndexLowerBound(frameSeconds);
}
return getFramesAtIndices(frameIndices);
}
FrameBatchOutput SingleStreamDecoder::getFramesPlayedInRange(
double startSeconds,
double stopSeconds) {
validateActiveStream(AVMEDIA_TYPE_VIDEO);
const auto& streamMetadata =
containerMetadata_.allStreamMetadata[activeStreamIndex_];
TORCH_CHECK(
startSeconds <= stopSeconds,
"Start seconds (" + std::to_string(startSeconds) +
") must be less than or equal to stop seconds (" +
std::to_string(stopSeconds) + ".");
const auto& streamInfo = streamInfos_[activeStreamIndex_];
const auto& videoStreamOptions = streamInfo.videoStreamOptions;
// Special case needed to implement a half-open range. At first glance, this
// may seem unnecessary, as our search for stopFrame can return the end, and
// we don't include stopFramIndex in our output. However, consider the
// following scenario:
//
// frame=0, pts=0.0
// frame=1, pts=0.3
//
// interval A: [0.2, 0.2)
// interval B: [0.2, 0.15)
//
// Both intervals take place between the pts values for frame 0 and frame 1,
// which by our abstract player, means that both intervals map to frame 0.
// By the definition of a half open interval, interval A should return no
// frames. Interval B should return frame 0. However, for both A and B, the
// individual values of the intervals will map to the same frame indices
// below. Hence, we need this special case below.
if (startSeconds == stopSeconds) {
FrameBatchOutput frameBatchOutput(
0,
resizedOutputDims_.value_or(metadataDims_),
videoStreamOptions.device);
frameBatchOutput.data = maybePermuteHWC2CHW(frameBatchOutput.data);
return frameBatchOutput;
}
double minSeconds = getMinSeconds(streamMetadata);
TORCH_CHECK(
startSeconds >= minSeconds,
"Start seconds is " + std::to_string(startSeconds) +
"; must be greater than or equal to " + std::to_string(minSeconds) +
".");
// Note that if we can't determine the maximum seconds from the metadata,
// then we assume upper range is valid.
std::optional<double> maxSeconds = getMaxSeconds(streamMetadata);
if (maxSeconds.has_value()) {
TORCH_CHECK(
startSeconds < maxSeconds.value(),
"Start seconds is " + std::to_string(startSeconds) +
"; must be less than " + std::to_string(maxSeconds.value()) + ".");
TORCH_CHECK(
stopSeconds <= maxSeconds.value(),
"Stop seconds (" + std::to_string(stopSeconds) +
"; must be less than or equal to " +
std::to_string(maxSeconds.value()) + ").");
}
// Note that we look at nextPts for a frame, and not its pts or duration.
// Our abstract player displays frames starting at the pts for that frame
// until the pts for the next frame. There are two consequences:
//
// 1. We ignore the duration for a frame. A frame is played until the
// next frame replaces it. This model is robust to durations being 0 or
// incorrect; our source of truth is the pts for frames. If duration is
// accurate, the nextPts for a frame would be equivalent to pts +
// duration.
// 2. In order to establish if the start of an interval maps to a
// particular frame, we need to figure out if it is ordered after the
// frame's pts, but before the next frames's pts.
int64_t startFrameIndex = secondsToIndexLowerBound(startSeconds);
int64_t stopFrameIndex = secondsToIndexUpperBound(stopSeconds);
int64_t numFrames = stopFrameIndex - startFrameIndex;
FrameBatchOutput frameBatchOutput(
numFrames,
resizedOutputDims_.value_or(metadataDims_),
videoStreamOptions.device);
for (int64_t i = startFrameIndex, f = 0; i < stopFrameIndex; ++i, ++f) {
FrameOutput frameOutput =
getFrameAtIndexInternal(i, frameBatchOutput.data[f]);
frameBatchOutput.ptsSeconds[f] = frameOutput.ptsSeconds;
frameBatchOutput.durationSeconds[f] = frameOutput.durationSeconds;
}
frameBatchOutput.data = maybePermuteHWC2CHW(frameBatchOutput.data);
return frameBatchOutput;
}
// Note [Audio Decoding Design]
// This note explains why audio decoding is implemented the way it is, and why
// it inherently differs from video decoding.
//
// Like for video, FFmpeg exposes the concept of a frame for audio streams. An
// audio frame is a contiguous sequence of samples, where a sample consists of
// `numChannels` values. An audio frame, or a sequence thereof, is always
// converted into a tensor of shape `(numChannels, numSamplesPerChannel)`.
//
// The notion of 'frame' in audio isn't what users want to interact with.
// Users want to interact with samples. The C++ and core APIs return frames,
// because we want those to be close to FFmpeg concepts, but the higher-level
// public APIs expose samples. As a result:
// - We don't expose index-based APIs for audio, because that would mean
// exposing the concept of audio frame. For now, we think exposing
// time-based APIs is more natural.
// - We never perform a scan for audio streams. We don't need to, since we
// won't
// be converting timestamps to indices. That's why we enforce the seek_mode
// to be "approximate" (which is slightly misleading, because technically
// the output samples will be at their exact positions. But this
// incongruence is only exposed at the C++/core private levels).
//
// Audio frames are of variable dimensions: in the same stream, a frame can
// contain 1024 samples and the next one may contain 512 [1]. This makes it
// impossible to stack audio frames in the same way we can stack video frames.
// This is one of the main reasons we cannot reuse the same pre-allocation
// logic we have for videos in getFramesPlayedInRange(): pre-allocating a
// batch requires constant (and known) frame dimensions. That's also why
// *concatenated* along the samples dimension, not stacked.
//
// [IMPORTANT!] There is one key invariant that we must respect when decoding
// audio frames:
//
// BEFORE DECODING FRAME i, WE MUST DECODE ALL FRAMES j < i.
//
// Always. Why? We don't know. What we know is that if we don't, we get
// clipped, incorrect audio as output [2]. All other (correct) libraries like
// TorchAudio or Decord do something similar, whether it was intended or not.
// This has a few implications:
// - The **only** place we're allowed to seek to in an audio stream is the
// stream's beginning. This ensures that if we need a frame, we'll have
// decoded all previous frames.
// - Because of that, we don't allow the public APIs to seek. Public APIs can
// call next() and `getFramesPlayedInRangeAudio()`, but they cannot manually
// seek.
// - We try not to seek, when we can avoid it. Typically if the next frame we
// need is in the future, we don't seek back to the beginning, we just
// decode all the frames in-between.
//
// [2] If you're brave and curious, you can read the long "Seek offset for
// audio" note in https://github.com/pytorch/torchcodec/pull/507/files, which
// sums up past (and failed) attemps at working around this issue.
AudioFramesOutput SingleStreamDecoder::getFramesPlayedInRangeAudio(
double startSeconds,
std::optional<double> stopSecondsOptional) {
validateActiveStream(AVMEDIA_TYPE_AUDIO);
if (stopSecondsOptional.has_value()) {
TORCH_CHECK(
startSeconds <= *stopSecondsOptional,
"Start seconds (" + std::to_string(startSeconds) +
") must be less than or equal to stop seconds (" +
std::to_string(*stopSecondsOptional) + ").");
}
StreamInfo& streamInfo = streamInfos_[activeStreamIndex_];
if (stopSecondsOptional.has_value() && startSeconds == *stopSecondsOptional) {
// For consistency with video
int numChannels = getNumChannels(streamInfo.codecContext);
return AudioFramesOutput{torch::empty({numChannels, 0}), 0.0};
}
auto startPts = secondsToClosestPts(startSeconds, streamInfo.timeBase);
if (startPts < lastDecodedAvFramePts_ + lastDecodedAvFrameDuration_) {
// If we need to seek backwards, then we have to seek back to the
// beginning of the stream. See [Audio Decoding Design].
setCursor(INT64_MIN);
}
// TODO-AUDIO Pre-allocate a long-enough tensor instead of creating a vec +
// cat(). This would save a copy. We know the duration of the output and the
// sample rate, so in theory we know the number of output samples.
std::vector<torch::Tensor> frames;
std::optional<double> firstFramePtsSeconds = std::nullopt;
auto stopPts = stopSecondsOptional.has_value()
? secondsToClosestPts(*stopSecondsOptional, streamInfo.timeBase)
: INT64_MAX;