-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathsoundsourceffmpeg.cpp
More file actions
1542 lines (1427 loc) · 62.6 KB
/
Copy pathsoundsourceffmpeg.cpp
File metadata and controls
1542 lines (1427 loc) · 62.6 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
#include "sources/soundsourceffmpeg.h"
#include <QFileInfo>
extern "C" {
#include <libavutil/avutil.h>
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
#include <libavutil/channel_layout.h>
#endif
} // extern "C"
#include "util/logger.h"
#include "util/sample.h"
#if !defined(VERBOSE_DEBUG_LOG)
#define VERBOSE_DEBUG_LOG false
#endif
namespace mixxx {
namespace {
// FFmpeg constants
#if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
constexpr uint64_t kavChannelLayoutUndefined = 0;
#endif
constexpr int64_t kavStreamDefaultStartTime = 0;
// https://ffmpeg.org/doxygen/trunk/structAVPacket.html#details
// "For audio it may contain several compressed frames."
// A stream packet may produce multiple stream frames when decoded.
// Buffering more than a few codec frames with samples in advance
// should be unlikely.
// This is just a best guess that needs to be increased once
// warnings about reallocation of the internal sample buffer
// appear in the logs!
constexpr uint64_t kavMaxDecodedFramesPerPacket = 16;
// 0.5 sec @ 96 kHz / 1 sec @ 48 kHz / 1.09 sec @ 44.1 kHz
constexpr FrameCount kDefaultFrameBufferCapacity = 48000;
constexpr FrameCount kMinFrameBufferCapacity = kDefaultFrameBufferCapacity;
// "AAC Audio - Encoder Delay and Synchronization: The 2112 Sample Assumption"
// https://developer.apple.com/library/ios/technotes/tn2258/_index.html
// "It must also be assumed that without an explicit value, the playback
// system will trim 2112 samples from the AAC decoder output when starting
// playback from any point in the bitsream."
// See also: https://developer.apple.com/library/archive/documentation/QuickTime/QTFF/QTFFAppenG/QTFFAppenG.html
constexpr int64_t kavStreamDecoderFrameDelayAAC = 2112;
constexpr SINT kMaxSamplesPerMP3Frame = 1152;
// Note: The fist audio stream can be at any stream index after other stream types
constexpr int kFirstAudioStream = -1;
const Logger kLogger("SoundSourceFFmpeg");
int64_t getStreamStartTime(const AVStream& avStream) {
int64_t start_time = avStream.start_time;
if (start_time == AV_NOPTS_VALUE) {
// This case is not unlikely, e.g. happens when decoding WAV files.
switch (avStream.codecpar->codec_id) {
case AV_CODEC_ID_AAC:
case AV_CODEC_ID_AAC_LATM: {
// Account for the expected decoder delay instead of simply
// using the default start time.
// Not all M4A files encode the start_time correctly, e.g.
// the test file cover-test-itunes-12.7.0-aac.m4a has a valid
// start_time of 0. Unfortunately, this special case cannot be
// detected and compensated.
start_time = kavStreamDecoderFrameDelayAAC;
break;
}
default:
start_time = kavStreamDefaultStartTime;
}
#if VERBOSE_DEBUG_LOG
kLogger.debug()
<< "Unknown start time -> using default value"
<< start_time;
#endif
}
return start_time;
}
inline int64_t getStreamEndTime(const AVStream& avStream) {
// The "duration" contains actually the end time of the
// stream.
VERIFY_OR_DEBUG_ASSERT(getStreamStartTime(avStream) <= avStream.duration) {
// assume that the stream is empty
return getStreamStartTime(avStream);
}
return avStream.duration;
}
inline SINT convertStreamTimeToFrameIndex(const AVStream& avStream, int64_t pts) {
DEBUG_ASSERT(pts != AV_NOPTS_VALUE);
// getStreamStartTime(avStream) -> 1st audible frame at FrameIndex 0
return av_rescale_q(
pts - getStreamStartTime(avStream),
avStream.time_base,
av_make_q(1, avStream.codecpar->sample_rate));
}
inline int64_t convertFrameIndexToStreamTime(const AVStream& avStream, SINT frameIndex) {
// Inverse mapping of convertStreamTimeToFrameIndex()
return getStreamStartTime(avStream) +
av_rescale_q(
frameIndex,
av_make_q(1, avStream.codecpar->sample_rate),
avStream.time_base);
}
#if VERBOSE_DEBUG_LOG
inline void avTrace(const QString& preamble, const AVPacket& avPacket) {
kLogger.debug()
<< preamble
<< "{ stream_index" << avPacket.stream_index
<< "| pos" << avPacket.pos
<< "| size" << avPacket.size
<< "| dst" << avPacket.dts
<< "| pts" << avPacket.pts
<< "| duration" << avPacket.duration
<< '}';
}
inline void avTrace(const QString& preamble, const AVFrame& avFrame) {
kLogger.debug()
<< preamble
<< "{ channels" << avFrame.channels
<< "| channel_layout" << avFrame.channel_layout
<< "| format" << avFrame.format
<< "| sample_rate" << avFrame.sample_rate
<< "| pkt_dts" << avFrame.pkt_dts
<< "| pkt_duration" << avFrame.pkt_duration
<< "| pts" << avFrame.pts
<< "| nb_samples" << avFrame.nb_samples
<< '}';
}
#endif // VERBOSE_DEBUG_LOG
} // anonymous namespace
// FFmpeg API Changes:
// https://github.com/FFmpeg/FFmpeg/blob/master/doc/APIchanges
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
// Static
void SoundSourceFFmpeg::initChannelLayoutFromStream(
AVChannelLayout* pUninitializedChannelLayout,
const AVStream& avStream) {
if (avStream.codecpar->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC) {
// Workaround: FFmpeg sometimes fails to determine the channel
// layout, e.g. for a mono WAV files with a single channel!
av_channel_layout_default(pUninitializedChannelLayout,
avStream.codecpar->ch_layout.nb_channels);
if (avStream.codecpar->ch_layout.nb_channels > 1) {
kLogger.warning()
<< "Unknown channel layout -> using default layout"
<< pUninitializedChannelLayout->order
<< "for"
<< avStream.codecpar->ch_layout.nb_channels
<< "channels";
}
} else {
av_channel_layout_default(pUninitializedChannelLayout, 0);
av_channel_layout_copy(pUninitializedChannelLayout, &avStream.codecpar->ch_layout);
}
}
#else
// Static
int64_t SoundSourceFFmpeg::getStreamChannelLayout(const AVStream& avStream) {
auto channel_layout = avStream.codecpar->channel_layout;
if (channel_layout == kavChannelLayoutUndefined) {
// Workaround: FFmpeg sometimes fails to determine the channel
// layout, e.g. for a mono WAV files with a single channel!
channel_layout = av_get_default_channel_layout(avStream.codecpar->channels);
if (avStream.codecpar->channels > 1) {
kLogger.warning()
<< "Unknown channel layout -> using default layout"
<< channel_layout
<< "for"
<< avStream.codecpar->channels
<< "channels";
}
}
return channel_layout;
}
#endif
// Static
FrameCount SoundSourceFFmpeg::frameBufferCapacityForStream(
const AVStream& avStream) {
DEBUG_ASSERT(kMinFrameBufferCapacity <= kDefaultFrameBufferCapacity);
if (avStream.codecpar->frame_size > 0) {
return math_max(
static_cast<FrameCount>(
avStream.codecpar->frame_size *
kavMaxDecodedFramesPerPacket),
kMinFrameBufferCapacity);
}
return kDefaultFrameBufferCapacity;
}
// Static
SINT SoundSourceFFmpeg::getStreamSeekPrerollFrameCount(const AVStream& avStream) {
// Stream might not provide an appropriate value that is
// sufficient for sample accurate decoding
const SINT defaultSeekPrerollFrameCount =
avStream.codecpar->seek_preroll;
DEBUG_ASSERT(defaultSeekPrerollFrameCount >= 0);
switch (avStream.codecpar->codec_id) {
case AV_CODEC_ID_MP3:
case AV_CODEC_ID_MP3ON4: {
// In the worst case up to 29 MP3 frames need to be prerolled
// for accurate seeking:
// http://www.mars.org/mailman/public/mad-dev/2002-May/000634.html
// But that would require to (re-)decode many frames after each seek
// operation, which increases the chance that dropouts may occur.
// As a compromise we will preroll only 9 instead of 29 frames.
// Those 9 frames should at least drain the bit reservoir.
//
// NOTE(2019-09-08): Executing the decoding test with various VBR/CBR
// MP3 files always produced exact results with only 9 preroll frames.
// Thus increasing this number is not required and would increase
// the risk for drop outs when jumping to a new position within
// the file. Audible drop outs are considered more harmful than
// slight deviations from the exact signal!
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
auto numChannels = avStream.codecpar->ch_layout.nb_channels;
#else
auto numChannels = avStream.codecpar->channels;
#endif
DEBUG_ASSERT(numChannels <= 2);
const SINT mp3SeekPrerollFrameCount =
9 * (kMaxSamplesPerMP3Frame / numChannels);
return math_max(mp3SeekPrerollFrameCount, defaultSeekPrerollFrameCount);
}
case AV_CODEC_ID_AAC:
case AV_CODEC_ID_AAC_LATM: {
const SINT aacSeekPrerollFrameCount = kavStreamDecoderFrameDelayAAC;
return math_max(aacSeekPrerollFrameCount, defaultSeekPrerollFrameCount);
}
default:
return defaultSeekPrerollFrameCount;
}
}
// Static
IndexRange SoundSourceFFmpeg::getStreamFrameIndexRange(const AVStream& avStream) {
const auto frameIndexRange = IndexRange::between(
convertStreamTimeToFrameIndex(avStream, getStreamStartTime(avStream)),
convertStreamTimeToFrameIndex(avStream, getStreamEndTime(avStream)));
DEBUG_ASSERT(frameIndexRange.orientation() != IndexRange::Orientation::Backward);
return frameIndexRange;
}
// Static
bool SoundSourceFFmpeg::openDecodingContext(
AVCodecContext* pavCodecContext) {
DEBUG_ASSERT(pavCodecContext != nullptr);
const int avcodec_open2_result =
avcodec_open2(pavCodecContext, pavCodecContext->codec, nullptr);
if (avcodec_open2_result != 0) {
DEBUG_ASSERT(avcodec_open2_result < 0);
kLogger.warning().noquote()
<< "avcodec_open2() failed:"
<< SoundSourceFFmpeg::formatErrorString(avcodec_open2_result);
return false;
}
return true;
}
// Static
QString SoundSourceFFmpeg::formatErrorString(int errnum) {
// Allocate a static buffer on the stack and initialize it
// with a `\0` terminator for extra safety if av_strerror()
// unexpectedly fails and does nothing.
char errbuf[AV_ERROR_MAX_STRING_SIZE]{0};
// The result value if av_strerror() does not need to be handled:
// "Even in case of failure av_strerror() will print a generic error
// message indicating the errnum provided to errbuf."
av_strerror(errnum, errbuf, sizeof(errbuf) / sizeof(errbuf[0]));
return QString::fromLocal8Bit(errbuf);
}
// Static
AVFormatContext* SoundSourceFFmpeg::openInputFile(
const QString& fileName) {
// Will be allocated implicitly when opening the input file
AVFormatContext* pavInputFormatContext = nullptr;
// Open input file and allocate/initialize AVFormatContext
const int avformat_open_input_result =
avformat_open_input(
&pavInputFormatContext, fileName.toUtf8().constData(), nullptr, nullptr);
if (avformat_open_input_result != 0) {
DEBUG_ASSERT(avformat_open_input_result < 0);
kLogger.warning().noquote()
<< "avformat_open_input() failed:"
<< formatErrorString(avformat_open_input_result);
DEBUG_ASSERT(pavInputFormatContext == nullptr);
}
return pavInputFormatContext;
}
void SoundSourceFFmpeg::InputAVFormatContextPtr::take(
AVFormatContext** ppavInputFormatContext) {
DEBUG_ASSERT(ppavInputFormatContext != nullptr);
if (m_pavInputFormatContext != *ppavInputFormatContext) {
close();
m_pavInputFormatContext = *ppavInputFormatContext;
*ppavInputFormatContext = nullptr;
}
}
void SoundSourceFFmpeg::InputAVFormatContextPtr::close() {
if (m_pavInputFormatContext != nullptr) {
avformat_close_input(&m_pavInputFormatContext);
DEBUG_ASSERT(m_pavInputFormatContext == nullptr);
}
}
//static
SoundSourceFFmpeg::AVCodecContextPtr
SoundSourceFFmpeg::AVCodecContextPtr::alloc(
const AVCodec* codec) {
AVCodecContextPtr context(avcodec_alloc_context3(codec));
if (!context) {
kLogger.warning()
<< "avcodec_alloc_context3() failed for codec"
<< codec->name;
}
return context;
}
void SoundSourceFFmpeg::AVCodecContextPtr::close() {
if (m_pavCodecContext != nullptr) {
avcodec_free_context(&m_pavCodecContext);
m_pavCodecContext = nullptr;
}
}
void SoundSourceFFmpeg::SwrContextPtr::take(
SwrContext** ppSwrContext) {
DEBUG_ASSERT(m_pSwrContext != nullptr);
if (m_pSwrContext != *ppSwrContext) {
close();
m_pSwrContext = *ppSwrContext;
*ppSwrContext = nullptr;
}
}
void SoundSourceFFmpeg::SwrContextPtr::close() {
if (m_pSwrContext != nullptr) {
swr_free(&m_pSwrContext);
DEBUG_ASSERT(m_pSwrContext == nullptr);
}
}
const QString SoundSourceProviderFFmpeg::kDisplayName = QStringLiteral("FFmpeg");
QStringList SoundSourceProviderFFmpeg::getSupportedFileTypes() const {
QStringList list;
QStringList disabledInputFormats;
// Collect all supported formats (whitelist)
const AVInputFormat* pavInputFormat = nullptr;
void* pOpaqueInputFormatIterator = nullptr;
while ((pavInputFormat = av_demuxer_iterate(&pOpaqueInputFormatIterator))) {
if (pavInputFormat->flags | AVFMT_SEEK_TO_PTS) {
///////////////////////////////////////////////////////////
// Whitelist of tested codecs (including variants)
///////////////////////////////////////////////////////////
if (!strcmp(pavInputFormat->name, "aac")) {
list.append("aac");
continue;
} else if (!strcmp(pavInputFormat->name, "aiff")) {
list.append("aiff");
continue;
} else if (!strcmp(pavInputFormat->name, "mp3")) {
list.append("mp3");
continue;
} else if (!strcmp(pavInputFormat->name, "mp4") ||
!strcmp(pavInputFormat->name, "m4v")) {
list.append("mp4");
continue;
} else if (!strcmp(pavInputFormat->name, "mov,mp4,m4a,3gp,3g2,mj2")) {
list.append("mov"); // QuickTime File Format video/quicktime
list.append("mp4");
list.append("m4a");
list.append("3gp"); // 3GPP file format audio/3gpp
list.append("3g2"); // 3GPP2 file format audio/3gpp2
list.append("mj2"); // Motion JPEG 2000 video/mj2
continue;
} else if (!strcmp(pavInputFormat->name, "opus") ||
!strcmp(pavInputFormat->name, "libopus")) {
list.append("opus");
continue;
} else if (!strcmp(pavInputFormat->name, "wav")) {
list.append("wav");
continue;
} else if (!strcmp(pavInputFormat->name, "wv")) {
list.append("wv");
continue;
} else if (!strcmp(pavInputFormat->name, "matroska,webm")) {
list.append("mkv");
list.append("webm");
continue;
///////////////////////////////////////////////////////////
// Codecs with failing tests
///////////////////////////////////////////////////////////
/*
} else if (!strcmp(pavInputFormat->name, "flac")) {
// FFmpeg failure causes test failure:
// [flac @ 0x2ef2060] read_timestamp() failed in the middle
// SoundSourceFFmpeg - av_seek_frame() failed: Operation not permitted
list.append("flac");
continue;
} else if (!strcmp(pavInputFormat->name, "ogg")) {
// Test failures that might be caused by FFmpeg bug:
// https://trac.ffmpeg.org/ticket/3825
list.append("ogg");
continue;
} else if (!strcmp(pavInputFormat->name, "wma") ||
!strcmp(pavInputFormat->name, "xwma")) {
list.append("wma"); // Windows Media Audio audio/x-ms-wma
continue;
*/
///////////////////////////////////////////////////////////
// Untested codecs
///////////////////////////////////////////////////////////
/*
} else if (!strcmp(pavInputFormat->name, "ac3")) {
list.append("ac3"); // AC-3 Compressed Audio (Dolby Digital), Revision A audio/ac3
continue;
} else if (!strcmp(pavInputFormat->name, "caf")) {
list.append("caf"); // Apple Lossless
continue;
} else if (!strcmp(pavInputFormat->name, "mpc")) {
list.append("mpc"); // Musepack encoded audio audio/musepack
continue;
} else if (!strcmp(pavInputFormat->name, "mpeg")) {
list.append("mpeg");
continue;
} else if (!strcmp(pavInputFormat->name, "tak")) {
list.append("tak"); // Tom's lossless Audio Kompressor audio/x-tak
continue;
} else if (!strcmp(pavInputFormat->name, "tta")) {
list.append("tta"); // True Audio, version 2
continue;
*/
}
}
disabledInputFormats.append(pavInputFormat->name);
continue;
}
if (!disabledInputFormats.isEmpty()) {
kLogger.debug().noquote()
<< "Disabling untested input formats:"
<< disabledInputFormats.join(QStringLiteral(", "));
}
return list;
}
SoundSourceProviderPriority SoundSourceProviderFFmpeg::getPriorityHint(
const QString& supportedFileType) const {
Q_UNUSED(supportedFileType)
// TODO: Increase priority to Default or even Higher for all
// supported and tested file types?
// Currently it is only used as a fallback after all other
// SoundSources failed to open a file or are otherwise unavailable.
return SoundSourceProviderPriority::Lowest;
}
QString SoundSourceProviderFFmpeg::getVersionString() const {
return QString::fromUtf8(av_version_info());
}
SoundSourceFFmpeg::SoundSourceFFmpeg(const QUrl& url, int wantedStreamIndex)
: SoundSource(url),
m_pavStream(nullptr),
m_pavDecodedFrame(nullptr),
m_seekPrerollFrameCount(0),
m_pavPacket(av_packet_alloc()),
m_pavResampledFrame(nullptr),
m_avutilVersion(avutil_version()),
m_wantedStreamIndex(wantedStreamIndex),
m_isLibfdk_aac(false) {
DEBUG_ASSERT(m_pavPacket);
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
av_channel_layout_default(&m_avStreamChannelLayout, 0);
av_channel_layout_default(&m_avResampledChannelLayout, 0);
#endif
}
SoundSourceFFmpeg::SoundSourceFFmpeg(const QUrl& url)
: SoundSourceFFmpeg(url, kFirstAudioStream) {
}
SoundSourceFFmpeg::~SoundSourceFFmpeg() {
close();
av_packet_free(&m_pavPacket);
DEBUG_ASSERT(!m_pavPacket);
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
av_channel_layout_uninit(&m_avStreamChannelLayout);
av_channel_layout_uninit(&m_avResampledChannelLayout);
#endif
}
SoundSource::OpenResult SoundSourceFFmpeg::tryOpen(
OpenMode /*mode*/,
const OpenParams& params) {
// Open input
{
AVFormatContext* pavInputFormatContext =
openInputFile(getLocalFileName());
if (pavInputFormatContext == nullptr) {
kLogger.warning()
<< "Failed to open input file"
<< getLocalFileName();
return OpenResult::Failed;
}
m_pavInputFormatContext.take(&pavInputFormatContext);
}
#if VERBOSE_DEBUG_LOG
kLogger.debug()
<< "AVFormatContext"
<< "{ nb_streams" << m_pavInputFormatContext->nb_streams
<< "| start_time"
<< (m_pavInputFormatContext->start_time == AV_NOPTS_VALUE
? "AV_NOPTS_VALUE"
: QString::number(
m_pavInputFormatContext->start_time))
<< "| duration" << m_pavInputFormatContext->duration
<< "| bit_rate" << m_pavInputFormatContext->bit_rate
<< "| packet_size" << m_pavInputFormatContext->packet_size
<< "| audio_codec_id" << m_pavInputFormatContext->audio_codec_id
<< "| output_ts_offset" << m_pavInputFormatContext->output_ts_offset
<< '}';
#endif
// Retrieve stream information
const int avformat_find_stream_info_result =
avformat_find_stream_info(m_pavInputFormatContext, nullptr);
if (avformat_find_stream_info_result != 0) {
DEBUG_ASSERT(avformat_find_stream_info_result < 0);
kLogger.warning().noquote()
<< "avformat_find_stream_info() failed:"
<< formatErrorString(avformat_find_stream_info_result);
return OpenResult::Failed;
}
// Find the best stream
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59, 0, 100) // FFmpeg 5.0
const AVCodec* pDecoder = nullptr;
const AVCodec* pFdkAacDecoder = nullptr;
#else
// https://github.com/FFmpeg/FFmpeg/blob/dd17c86aa11feae2b86de054dd0679cc5f88ebab/doc/APIchanges#L175
AVCodec* pDecoder = nullptr;
AVCodec* pFdkAacDecoder = nullptr;
#endif
const int av_find_best_stream_result = av_find_best_stream(
m_pavInputFormatContext,
AVMEDIA_TYPE_AUDIO,
m_wantedStreamIndex,
/*related_stream*/ -1,
&pDecoder,
/*flags*/ 0);
if (av_find_best_stream_result < 0) {
switch (av_find_best_stream_result) {
case AVERROR_STREAM_NOT_FOUND:
if (m_wantedStreamIndex >= 0) {
// This happens if m_wantedStreamIndex is not an audio stream
if (m_pavInputFormatContext->nb_streams <=
static_cast<unsigned int>(m_wantedStreamIndex)) {
kLogger.warning().noquote()
<< "cannot find stream" << m_wantedStreamIndex;
} else {
kLogger.warning().noquote()
<< "stream" << m_wantedStreamIndex << "isn't an audio stream";
}
return OpenResult::Failed;
}
// called with kFirstAudioStream
kLogger.warning()
<< "av_find_best_stream() failed to find an audio stream";
break;
case AVERROR_DECODER_NOT_FOUND:
kLogger.warning()
<< "av_find_best_stream() failed to find a decoder for any audio stream";
break;
default:
kLogger.warning().noquote()
<< "av_find_best_stream() failed:"
<< formatErrorString(av_find_best_stream_result);
}
return SoundSource::OpenResult::Aborted;
}
DEBUG_ASSERT(pDecoder);
if (pDecoder->id == AV_CODEC_ID_AAC ||
pDecoder->id == AV_CODEC_ID_AAC_LATM) {
// Prefer Fraunhofer FDK AAC over internal AAC
// https://trac.ffmpeg.org/wiki/Encode/AAC
if (std::strcmp(pDecoder->name, "aac") == 0) {
pFdkAacDecoder = avcodec_find_decoder_by_name("libfdk_aac");
if (pFdkAacDecoder) {
pDecoder = pFdkAacDecoder;
}
}
if (std::strcmp(pDecoder->name, "libfdk_aac") == 0) {
// Fraunhofer FDK AAC has an issue with flushing memory in the lead-in
m_isLibfdk_aac = true;
}
}
kLogger.debug() << "using decoder:" << pDecoder->long_name;
// Select audio stream for decoding
AVStream* pavStream = m_pavInputFormatContext->streams[av_find_best_stream_result];
DEBUG_ASSERT(pavStream != nullptr);
DEBUG_ASSERT(pavStream->index == av_find_best_stream_result);
// Allocate decoding context
AVCodecContextPtr pavCodecContext = AVCodecContextPtr::alloc(pDecoder);
if (!pavCodecContext) {
return SoundSource::OpenResult::Aborted;
}
// Configure decoding context
const int avcodec_parameters_to_context_result =
avcodec_parameters_to_context(pavCodecContext, pavStream->codecpar);
if (avcodec_parameters_to_context_result != 0) {
DEBUG_ASSERT(avcodec_parameters_to_context_result < 0);
kLogger.warning().noquote()
<< "avcodec_parameters_to_context() failed:"
<< formatErrorString(avcodec_parameters_to_context_result);
return SoundSource::OpenResult::Aborted;
}
// Copy time base for random seeks:
pavCodecContext->pkt_timebase = pavStream->time_base;
// Request output format
pavCodecContext->request_sample_fmt = s_avSampleFormat;
if (params.getSignalInfo().getChannelCount().isValid()) {
// A dedicated number of channels for the output signal
// has been requested. Forward this to FFmpeg to avoid
// manual resampling or post-processing after decoding.
const int requestChannels = std::min(
static_cast<int>(params.getSignalInfo().getChannelCount()),
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
pavStream->codecpar->ch_layout.nb_channels
#else
av_get_channel_layout_nb_channels(pavStream->codecpar->channel_layout)
#endif
);
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
av_channel_layout_default(&pavCodecContext->ch_layout,
requestChannels);
#else
pavCodecContext->request_channel_layout =
av_get_default_channel_layout(requestChannels);
#endif
}
// Open decoding context
if (!openDecodingContext(pavCodecContext)) {
// early exit on any error
return SoundSource::OpenResult::Failed;
}
// Initialize members
m_pavCodecContext = std::move(pavCodecContext);
m_pavStream = pavStream;
if (kLogger.debugEnabled()) {
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
AVChannelLayout fixedChannelLayout;
initChannelLayoutFromStream(&fixedChannelLayout, *m_pavStream);
#endif
kLogger.debug()
<< "AVStream"
<< "{ index" << m_pavStream->index
<< "| id" << m_pavStream->id
<< "| time_base" << m_pavStream->time_base.num << '/' << m_pavStream->time_base.den
<< "| start_time" << m_pavStream->start_time
<< "| duration" << m_pavStream->duration
<< "| nb_frames" << m_pavStream->nb_frames
<< "| codec_type" << m_pavStream->codecpar->codec_type
<< "| codec_id" << m_pavStream->codecpar->codec_id
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
<< "| ch_layout.nb_channels" << m_pavStream->codecpar->ch_layout.nb_channels
<< "| ch_layout.order" << m_pavStream->codecpar->ch_layout.order
<< "| ch_layout.order (fixed)" << fixedChannelLayout.order
#else
<< "| channels" << m_pavStream->codecpar->channels
<< "| channel_layout" << m_pavStream->codecpar->channel_layout
<< "| channel_layout (fixed)" << getStreamChannelLayout(*m_pavStream)
#endif
<< "| format" << m_pavStream->codecpar->format
<< "| sample_rate" << m_pavStream->codecpar->sample_rate
<< "| bit_rate" << m_pavStream->codecpar->bit_rate
<< "| frame_size" << m_pavStream->codecpar->frame_size
<< "| seek_preroll" << m_pavStream->codecpar->seek_preroll
<< "| initial_padding" << m_pavStream->codecpar->initial_padding
<< "| trailing_padding" << m_pavStream->codecpar->trailing_padding
<< '}';
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
av_channel_layout_uninit(&fixedChannelLayout);
#endif
}
audio::ChannelCount channelCount;
audio::SampleRate sampleRate;
if (!initResampling(&channelCount, &sampleRate)) {
return OpenResult::Failed;
}
if (!initChannelCountOnce(channelCount)) {
kLogger.warning()
<< "Failed to initialize number of channels"
<< channelCount;
return OpenResult::Aborted;
}
if (!initSampleRateOnce(sampleRate)) {
kLogger.warning()
<< "Failed to initialize sample rate"
<< sampleRate;
return OpenResult::Aborted;
}
const auto streamBitrate =
audio::Bitrate(m_pavStream->codecpar->bit_rate / 1000); // kbps
if (streamBitrate.isValid() && !initBitrateOnce(streamBitrate)) {
kLogger.warning()
<< "Failed to initialize bitrate"
<< streamBitrate;
return OpenResult::Failed;
}
if (m_pavStream->duration == AV_NOPTS_VALUE) {
if (m_pavInputFormatContext->duration != AV_NOPTS_VALUE) {
// AVFormatContext::duration is measured in AV_TIME_BASE units
// (1/1e6 s), whereas AVStream::duration is measured in
// stream->time_base units. Rescale accordingly, otherwise the
// frame index range is inflated (e.g. ~1000x for webm/mkv
// streams with a 1/1000 s time base) which breaks seeking and
// the waveform/spectrogram.
m_pavStream->duration = av_rescale_q(
m_pavInputFormatContext->duration,
AV_TIME_BASE_Q,
m_pavStream->time_base);
kLogger.debug()
<< "using format context duration instead of stream duration";
} else {
// Streams with unknown or unlimited duration are
// not (yet) supported.
kLogger.warning()
<< "Unknown or unlimited stream duration";
return OpenResult::Failed;
}
}
const auto streamFrameIndexRange =
getStreamFrameIndexRange(*m_pavStream);
VERIFY_OR_DEBUG_ASSERT(streamFrameIndexRange.start() <= streamFrameIndexRange.end()) {
kLogger.warning()
<< "Stream with unsupported or invalid frame index range"
<< streamFrameIndexRange;
return OpenResult::Failed;
}
// Decoding MP3/AAC files manually into WAV using the ffmpeg CLI and
// comparing the audio data revealed that we need to map the nominal
// range of the stream onto our internal range starting at FrameIndex 0.
// See also the discussion regarding cue point shift/offset:
// https://mixxx.zulipchat.com/#narrow/stream/109171-development/topic/Cue.20shift.2Foffset
const auto frameIndexRange = IndexRange::forward(
0,
streamFrameIndexRange.length());
if (!initFrameIndexRangeOnce(frameIndexRange)) {
kLogger.warning()
<< "Failed to initialize frame index range"
<< frameIndexRange;
return OpenResult::Failed;
}
DEBUG_ASSERT(!m_pavDecodedFrame);
m_pavDecodedFrame = av_frame_alloc();
// FFmpeg does not provide sample-accurate decoding after random seeks
// in the stream out of the box. Depending on the actual codec we need
// to account for this and start decoding before the target position.
m_seekPrerollFrameCount = getStreamSeekPrerollFrameCount(*m_pavStream);
#if VERBOSE_DEBUG_LOG
kLogger.debug() << "Seek preroll frame count:" << m_seekPrerollFrameCount;
#endif
m_frameBuffer = ReadAheadFrameBuffer(
getSignalInfo(),
frameBufferCapacityForStream(*m_pavStream));
#if VERBOSE_DEBUG_LOG
kLogger.debug() << "Frame buffer capacity:" << m_frameBuffer.capacity();
#endif
return OpenResult::Succeeded;
}
// @anchor: ffmpeg:import-metadata-override
// TagLib does not support Matroska/WebM containers and its default
// implementation in MetadataSourceTagLib returns Unavailable for these
// file types. This override provides the stream info (especially the
// duration) from the FFmpeg container, so the Mixxx library does not
// show an empty duration column for such files.
std::pair<MetadataSource::ImportResult, QDateTime>
SoundSourceFFmpeg::importTrackMetadataAndCoverImage(
TrackMetadata* pTrackMetadata,
QImage* pCoverArt,
bool resetMissingTagMetadata) const {
// Delegate all file types supported by TagLib to the default
// implementation, which also imports tags like title and artist.
const QString fileSuffix =
QFileInfo(getLocalFileName()).suffix().toLower();
if (fileSuffix != QLatin1String("mkv") &&
fileSuffix != QLatin1String("webm")) {
return MetadataSourceTagLib::importTrackMetadataAndCoverImage(
pTrackMetadata,
pCoverArt,
resetMissingTagMetadata);
}
const auto sourceSynchronizedAt = getFileSynchronizedAt(
QFile(getLocalFileName()));
if (pTrackMetadata == nullptr) {
// Cover art cannot be imported from Matroska/WebM files.
return std::make_pair(ImportResult::Unavailable, sourceSynchronizedAt);
}
// Open the container for metadata inspection. No decoder is required.
AVFormatContext* pavInputFormatContext =
openInputFile(getLocalFileName());
if (pavInputFormatContext == nullptr) {
return std::make_pair(ImportResult::Failed, sourceSynchronizedAt);
}
const int findStreamInfoResult =
avformat_find_stream_info(pavInputFormatContext, nullptr);
if (findStreamInfoResult != 0) {
kLogger.warning()
<< "Failed to read stream info for metadata import"
<< getLocalFileName();
avformat_close_input(&pavInputFormatContext);
return std::make_pair(ImportResult::Failed, sourceSynchronizedAt);
}
// Select the same audio stream as tryOpen() without opening a decoder.
const int streamIndex = av_find_best_stream(
pavInputFormatContext,
AVMEDIA_TYPE_AUDIO,
m_wantedStreamIndex,
/*related_stream=*/ -1,
/*decoder_ret=*/ nullptr,
/*flags=*/ 0);
if (streamIndex < 0) {
kLogger.warning()
<< "Failed to find audio stream for metadata import"
<< getLocalFileName();
avformat_close_input(&pavInputFormatContext);
return std::make_pair(ImportResult::Failed, sourceSynchronizedAt);
}
AVStream* pavStream = pavInputFormatContext->streams[streamIndex];
VERIFY_OR_DEBUG_ASSERT(pavStream != nullptr) {
avformat_close_input(&pavInputFormatContext);
return std::make_pair(ImportResult::Failed, sourceSynchronizedAt);
}
// Mirror the duration fallback of tryOpen(): the stream duration of
// Matroska/WebM files is often unknown, in which case the format
// context duration is rescaled from AV_TIME_BASE to the stream time base.
if (pavStream->duration == AV_NOPTS_VALUE) {
if (pavInputFormatContext->duration == AV_NOPTS_VALUE) {
kLogger.warning()
<< "Unknown or unlimited stream duration"
<< getLocalFileName();
avformat_close_input(&pavInputFormatContext);
return std::make_pair(ImportResult::Failed, sourceSynchronizedAt);
}
pavStream->duration = av_rescale_q(
pavInputFormatContext->duration,
AV_TIME_BASE_Q,
pavStream->time_base);
}
const auto streamFrameIndexRange =
getStreamFrameIndexRange(*pavStream);
VERIFY_OR_DEBUG_ASSERT(
streamFrameIndexRange.start() <= streamFrameIndexRange.end()) {
kLogger.warning()
<< "Stream with unsupported or invalid frame index range"
<< streamFrameIndexRange;
avformat_close_input(&pavInputFormatContext);
return std::make_pair(ImportResult::Failed, sourceSynchronizedAt);
}
// Report the same stream properties as initResampling() to avoid a
// mismatch between the imported and the decoded stream info.
const auto channelCount = audio::ChannelCount(
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
pavStream->codecpar->ch_layout.nb_channels
#else
pavStream->codecpar->channels
#endif
);
const auto sampleRate =
audio::SampleRate(pavStream->codecpar->sample_rate);
if (channelCount.isValid() && sampleRate.isValid()) {
pTrackMetadata->setStreamInfo(audio::StreamInfo{
audio::SignalInfo{channelCount, sampleRate},
audio::Bitrate(pavStream->codecpar->bit_rate / 1000), // kbit/s
Duration::fromSeconds(
static_cast<double>(streamFrameIndexRange.length()) /
sampleRate),
});
}
avformat_close_input(&pavInputFormatContext);
return std::make_pair(ImportResult::Succeeded, sourceSynchronizedAt);
}
bool SoundSourceFFmpeg::initResampling(
audio::ChannelCount* pResampledChannelCount,
audio::SampleRate* pResampledSampleRate) {
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
AVChannelLayout avStreamChannelLayout;
initChannelLayoutFromStream(&avStreamChannelLayout, *m_pavStream);
const auto streamChannelCount =
audio::ChannelCount(m_pavStream->codecpar->ch_layout.nb_channels);
#else
const auto avStreamChannelLayout =
getStreamChannelLayout(*m_pavStream);
const auto streamChannelCount =
audio::ChannelCount(m_pavStream->codecpar->channels);
#endif
// NOTE(uklotzde, 2017-09-26): Resampling to a different number of
// channels like upsampling a mono to stereo signal breaks various
// tests in the EngineBufferE2ETest suite!! SoundSource decoding tests
// are unaffected, because there we always compare two signals produced
// by the same decoder instead of a decoded with a reference signal. As
// a workaround we decode the stream's channels as is and let Mixxx decide
// how to handle this later.
const auto resampledChannelCount =
/*config.getSignalInfo().getChannelCount().isValid() ? config.getSignalInfo().getChannelCount() :*/ streamChannelCount;
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
AVChannelLayout avResampledChannelLayout;
av_channel_layout_default(&avResampledChannelLayout, resampledChannelCount);
#else
const auto avResampledChannelLayout =
av_get_default_channel_layout(resampledChannelCount);
#endif
const auto avStreamSampleFormat =
m_pavCodecContext->sample_fmt;
const auto avResampledSampleFormat =
s_avSampleFormat;
// NOTE(uklotzde): We prefer not to change adjust sample rate here, because
// all the frame calculations while decoding use the frame information
// from the underlying stream! We only need resampling for up-/downsampling
// the channels and to transform the decoded audio data into the sample
// format that is used by Mixxx.
const auto streamSampleRate =
audio::SampleRate(m_pavStream->codecpar->sample_rate);
const auto resampledSampleRate = streamSampleRate;
if (
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
av_channel_layout_compare(&avResampledChannelLayout, &avStreamChannelLayout) != 0 ||
#else
(resampledChannelCount != streamChannelCount) ||
(avResampledChannelLayout != avStreamChannelLayout) ||
#endif
(avResampledSampleFormat != avStreamSampleFormat)) {
#if VERBOSE_DEBUG_LOG
kLogger.debug()
<< "Decoded stream needs to be resampled"
<< ": channel count =" << resampledChannelCount
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1
<< "| channel layout order =" << avResampledChannelLayout.order
#else
<< "| channel layout =" << avResampledChannelLayout
#endif
<< "| sample format =" << av_get_sample_fmt_name(avResampledSampleFormat);
#endif
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1