-
Notifications
You must be signed in to change notification settings - Fork 261
/
FFmpegReader.cpp
2477 lines (2079 loc) · 88.2 KB
/
FFmpegReader.cpp
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
/**
* @file
* @brief Source file for FFmpegReader class
* @author Jonathan Thomas <jonathan@openshot.org>, Fabrice Bellard
*
* @ref License
*/
/* LICENSE
*
* Copyright (c) 2008-2019 OpenShot Studios, LLC, Fabrice Bellard
* (http://www.openshotstudios.com). This file is part of
* OpenShot Library (http://www.openshot.org), an open-source project
* dedicated to delivering high quality video editing and animation solutions
* to the world.
*
* This file is originally based on the Libavformat API example, and then modified
* by the libopenshot project.
*
* OpenShot Library (libopenshot) is free software: you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* OpenShot Library (libopenshot) is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "FFmpegReader.h"
#include "Exceptions.h"
#include "Timeline.h"
#include <thread> // for std::this_thread::sleep_for
#include <chrono> // for std::chrono::milliseconds
#define ENABLE_VAAPI 0
#if USE_HW_ACCEL
#define MAX_SUPPORTED_WIDTH 1950
#define MAX_SUPPORTED_HEIGHT 1100
#if ENABLE_VAAPI
#include "libavutil/hwcontext_vaapi.h"
typedef struct VAAPIDecodeContext {
VAProfile va_profile;
VAEntrypoint va_entrypoint;
VAConfigID va_config;
VAContextID va_context;
#if FF_API_STRUCT_VAAPI_CONTEXT
// FF_DISABLE_DEPRECATION_WARNINGS
int have_old_context;
struct vaapi_context *old_context;
AVBufferRef *device_ref;
// FF_ENABLE_DEPRECATION_WARNINGS
#endif
AVHWDeviceContext *device;
AVVAAPIDeviceContext *hwctx;
AVHWFramesContext *frames;
AVVAAPIFramesContext *hwfc;
enum AVPixelFormat surface_format;
int surface_count;
} VAAPIDecodeContext;
#endif // ENABLE_VAAPI
#endif // USE_HW_ACCEL
using namespace openshot;
int hw_de_on = 0;
#if USE_HW_ACCEL
AVPixelFormat hw_de_av_pix_fmt_global = AV_PIX_FMT_NONE;
AVHWDeviceType hw_de_av_device_type_global = AV_HWDEVICE_TYPE_NONE;
#endif
FFmpegReader::FFmpegReader(const std::string& path, bool inspect_reader)
: last_frame(0), is_seeking(0), seeking_pts(0), seeking_frame(0), seek_count(0),
audio_pts_offset(99999), video_pts_offset(99999), path(path), is_video_seek(true), check_interlace(false),
check_fps(false), enable_seek(true), is_open(false), seek_audio_frame_found(0), seek_video_frame_found(0),
prev_samples(0), prev_pts(0), pts_total(0), pts_counter(0), is_duration_known(false), largest_frame_processed(0),
current_video_frame(0), has_missing_frames(false), num_packets_since_video_frame(0), num_checks_since_final(0),
packet(NULL), max_concurrent_frames(OPEN_MP_NUM_PROCESSORS) {
// Initialize FFMpeg, and register all formats and codecs
AV_REGISTER_ALL
AVCODEC_REGISTER_ALL
// Init cache
working_cache.SetMaxBytesFromInfo(max_concurrent_frames * info.fps.ToDouble() * 2, info.width, info.height, info.sample_rate, info.channels);
missing_frames.SetMaxBytesFromInfo(max_concurrent_frames * 2, info.width, info.height, info.sample_rate, info.channels);
final_cache.SetMaxBytesFromInfo(max_concurrent_frames * 2, info.width, info.height, info.sample_rate, info.channels);
// Open and Close the reader, to populate its attributes (such as height, width, etc...)
if (inspect_reader) {
Open();
Close();
}
}
FFmpegReader::~FFmpegReader() {
if (is_open)
// Auto close reader if not already done
Close();
}
// This struct holds the associated video frame and starting sample # for an audio packet.
bool AudioLocation::is_near(AudioLocation location, int samples_per_frame, int64_t amount) {
// Is frame even close to this one?
if (abs(location.frame - frame) >= 2)
// This is too far away to be considered
return false;
// Note that samples_per_frame can vary slightly frame to frame when the
// audio sampling rate is not an integer multiple of the video fps.
int64_t diff = samples_per_frame * (location.frame - frame) + location.sample_start - sample_start;
if (abs(diff) <= amount)
// close
return true;
// not close
return false;
}
#if USE_HW_ACCEL
// Get hardware pix format
static enum AVPixelFormat get_hw_dec_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts)
{
const enum AVPixelFormat *p;
for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
switch (*p) {
#if defined(__linux__)
// Linux pix formats
case AV_PIX_FMT_VAAPI:
hw_de_av_pix_fmt_global = AV_PIX_FMT_VAAPI;
hw_de_av_device_type_global = AV_HWDEVICE_TYPE_VAAPI;
return *p;
break;
case AV_PIX_FMT_VDPAU:
hw_de_av_pix_fmt_global = AV_PIX_FMT_VDPAU;
hw_de_av_device_type_global = AV_HWDEVICE_TYPE_VDPAU;
return *p;
break;
#endif
#if defined(_WIN32)
// Windows pix formats
case AV_PIX_FMT_DXVA2_VLD:
hw_de_av_pix_fmt_global = AV_PIX_FMT_DXVA2_VLD;
hw_de_av_device_type_global = AV_HWDEVICE_TYPE_DXVA2;
return *p;
break;
case AV_PIX_FMT_D3D11:
hw_de_av_pix_fmt_global = AV_PIX_FMT_D3D11;
hw_de_av_device_type_global = AV_HWDEVICE_TYPE_D3D11VA;
return *p;
break;
#endif
#if defined(__APPLE__)
// Apple pix formats
case AV_PIX_FMT_VIDEOTOOLBOX:
hw_de_av_pix_fmt_global = AV_PIX_FMT_VIDEOTOOLBOX;
hw_de_av_device_type_global = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
return *p;
break;
#endif
// Cross-platform pix formats
case AV_PIX_FMT_CUDA:
hw_de_av_pix_fmt_global = AV_PIX_FMT_CUDA;
hw_de_av_device_type_global = AV_HWDEVICE_TYPE_CUDA;
return *p;
break;
case AV_PIX_FMT_QSV:
hw_de_av_pix_fmt_global = AV_PIX_FMT_QSV;
hw_de_av_device_type_global = AV_HWDEVICE_TYPE_QSV;
return *p;
break;
default:
// This is only here to silence unused-enum warnings
break;
}
}
ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::get_hw_dec_format (Unable to decode this file using hardware decode)");
return AV_PIX_FMT_NONE;
}
int FFmpegReader::IsHardwareDecodeSupported(int codecid)
{
int ret;
switch (codecid) {
case AV_CODEC_ID_H264:
case AV_CODEC_ID_MPEG2VIDEO:
case AV_CODEC_ID_VC1:
case AV_CODEC_ID_WMV1:
case AV_CODEC_ID_WMV2:
case AV_CODEC_ID_WMV3:
ret = 1;
break;
default :
ret = 0;
break;
}
return ret;
}
#endif // USE_HW_ACCEL
void FFmpegReader::Open() {
// Open reader if not already open
if (!is_open) {
// Initialize format context
pFormatCtx = NULL;
{
hw_de_on = (openshot::Settings::Instance()->HARDWARE_DECODER == 0 ? 0 : 1);
}
// Open video file
if (avformat_open_input(&pFormatCtx, path.c_str(), NULL, NULL) != 0)
throw InvalidFile("File could not be opened.", path);
// Retrieve stream information
if (avformat_find_stream_info(pFormatCtx, NULL) < 0)
throw NoStreamsFound("No streams found in file.", path);
videoStream = -1;
audioStream = -1;
// Loop through each stream, and identify the video and audio stream index
for (unsigned int i = 0; i < pFormatCtx->nb_streams; i++) {
// Is this a video stream?
if (AV_GET_CODEC_TYPE(pFormatCtx->streams[i]) == AVMEDIA_TYPE_VIDEO && videoStream < 0) {
videoStream = i;
}
// Is this an audio stream?
if (AV_GET_CODEC_TYPE(pFormatCtx->streams[i]) == AVMEDIA_TYPE_AUDIO && audioStream < 0) {
audioStream = i;
}
}
if (videoStream == -1 && audioStream == -1)
throw NoStreamsFound("No video or audio streams found in this file.", path);
// Is there a video stream?
if (videoStream != -1) {
// Set the stream index
info.video_stream_index = videoStream;
// Set the codec and codec context pointers
pStream = pFormatCtx->streams[videoStream];
// Find the codec ID from stream
AVCodecID codecId = AV_FIND_DECODER_CODEC_ID(pStream);
// Get codec and codec context from stream
AVCodec *pCodec = avcodec_find_decoder(codecId);
AVDictionary *opts = NULL;
int retry_decode_open = 2;
// If hw accel is selected but hardware cannot handle repeat with software decoding
do {
pCodecCtx = AV_GET_CODEC_CONTEXT(pStream, pCodec);
#if USE_HW_ACCEL
if (hw_de_on && (retry_decode_open==2)) {
// Up to here no decision is made if hardware or software decode
hw_de_supported = IsHardwareDecodeSupported(pCodecCtx->codec_id);
}
#endif
retry_decode_open = 0;
// Set number of threads equal to number of processors (not to exceed 16)
pCodecCtx->thread_count = std::min(FF_NUM_PROCESSORS, 16);
if (pCodec == NULL) {
throw InvalidCodec("A valid video codec could not be found for this file.", path);
}
// Init options
av_dict_set(&opts, "strict", "experimental", 0);
#if USE_HW_ACCEL
if (hw_de_on && hw_de_supported) {
// Open Hardware Acceleration
int i_decoder_hw = 0;
char adapter[256];
char *adapter_ptr = NULL;
int adapter_num;
adapter_num = openshot::Settings::Instance()->HW_DE_DEVICE_SET;
fprintf(stderr, "Hardware decoding device number: %d\n", adapter_num);
// Set hardware pix format (callback)
pCodecCtx->get_format = get_hw_dec_format;
if (adapter_num < 3 && adapter_num >=0) {
#if defined(__linux__)
snprintf(adapter,sizeof(adapter),"/dev/dri/renderD%d", adapter_num+128);
adapter_ptr = adapter;
i_decoder_hw = openshot::Settings::Instance()->HARDWARE_DECODER;
switch (i_decoder_hw) {
case 1:
hw_de_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
break;
case 2:
hw_de_av_device_type = AV_HWDEVICE_TYPE_CUDA;
break;
case 6:
hw_de_av_device_type = AV_HWDEVICE_TYPE_VDPAU;
break;
case 7:
hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
break;
default:
hw_de_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
break;
}
#elif defined(_WIN32)
adapter_ptr = NULL;
i_decoder_hw = openshot::Settings::Instance()->HARDWARE_DECODER;
switch (i_decoder_hw) {
case 2:
hw_de_av_device_type = AV_HWDEVICE_TYPE_CUDA;
break;
case 3:
hw_de_av_device_type = AV_HWDEVICE_TYPE_DXVA2;
break;
case 4:
hw_de_av_device_type = AV_HWDEVICE_TYPE_D3D11VA;
break;
case 7:
hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
break;
default:
hw_de_av_device_type = AV_HWDEVICE_TYPE_DXVA2;
break;
}
#elif defined(__APPLE__)
adapter_ptr = NULL;
i_decoder_hw = openshot::Settings::Instance()->HARDWARE_DECODER;
switch (i_decoder_hw) {
case 5:
hw_de_av_device_type = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
break;
case 7:
hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
break;
default:
hw_de_av_device_type = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
break;
}
#endif
} else {
adapter_ptr = NULL; // Just to be sure
}
// Check if it is there and writable
#if defined(__linux__)
if( adapter_ptr != NULL && access( adapter_ptr, W_OK ) == 0 ) {
#elif defined(_WIN32)
if( adapter_ptr != NULL ) {
#elif defined(__APPLE__)
if( adapter_ptr != NULL ) {
#endif
ZmqLogger::Instance()->AppendDebugMethod("Decode Device present using device");
}
else {
adapter_ptr = NULL; // use default
ZmqLogger::Instance()->AppendDebugMethod("Decode Device not present using default");
}
hw_device_ctx = NULL;
// Here the first hardware initialisations are made
if (av_hwdevice_ctx_create(&hw_device_ctx, hw_de_av_device_type, adapter_ptr, NULL, 0) >= 0) {
if (!(pCodecCtx->hw_device_ctx = av_buffer_ref(hw_device_ctx))) {
throw InvalidCodec("Hardware device reference create failed.", path);
}
/*
av_buffer_unref(&ist->hw_frames_ctx);
ist->hw_frames_ctx = av_hwframe_ctx_alloc(hw_device_ctx);
if (!ist->hw_frames_ctx) {
av_log(avctx, AV_LOG_ERROR, "Error creating a CUDA frames context\n");
return AVERROR(ENOMEM);
}
frames_ctx = (AVHWFramesContext*)ist->hw_frames_ctx->data;
frames_ctx->format = AV_PIX_FMT_CUDA;
frames_ctx->sw_format = avctx->sw_pix_fmt;
frames_ctx->width = avctx->width;
frames_ctx->height = avctx->height;
av_log(avctx, AV_LOG_DEBUG, "Initializing CUDA frames context: sw_format = %s, width = %d, height = %d\n",
av_get_pix_fmt_name(frames_ctx->sw_format), frames_ctx->width, frames_ctx->height);
ret = av_hwframe_ctx_init(pCodecCtx->hw_device_ctx);
ret = av_hwframe_ctx_init(ist->hw_frames_ctx);
if (ret < 0) {
av_log(avctx, AV_LOG_ERROR, "Error initializing a CUDA frame pool\n");
return ret;
}
*/
}
else {
throw InvalidCodec("Hardware device create failed.", path);
}
}
#endif // USE_HW_ACCEL
// Disable per-frame threading for album arts
// Using FF_THREAD_FRAME adds one frame decoding delay per thread,
// but there's only one frame in this case.
if (HasAlbumArt())
{
pCodecCtx->thread_type &= ~FF_THREAD_FRAME;
}
// Open video codec
if (avcodec_open2(pCodecCtx, pCodec, &opts) < 0)
throw InvalidCodec("A video codec was found, but could not be opened.", path);
#if USE_HW_ACCEL
if (hw_de_on && hw_de_supported) {
AVHWFramesConstraints *constraints = NULL;
void *hwconfig = NULL;
hwconfig = av_hwdevice_hwconfig_alloc(hw_device_ctx);
// TODO: needs va_config!
#if ENABLE_VAAPI
((AVVAAPIHWConfig *)hwconfig)->config_id = ((VAAPIDecodeContext *)(pCodecCtx->priv_data))->va_config;
constraints = av_hwdevice_get_hwframe_constraints(hw_device_ctx,hwconfig);
#endif // ENABLE_VAAPI
if (constraints) {
if (pCodecCtx->coded_width < constraints->min_width ||
pCodecCtx->coded_height < constraints->min_height ||
pCodecCtx->coded_width > constraints->max_width ||
pCodecCtx->coded_height > constraints->max_height) {
ZmqLogger::Instance()->AppendDebugMethod("DIMENSIONS ARE TOO LARGE for hardware acceleration\n");
hw_de_supported = 0;
retry_decode_open = 1;
AV_FREE_CONTEXT(pCodecCtx);
if (hw_device_ctx) {
av_buffer_unref(&hw_device_ctx);
hw_device_ctx = NULL;
}
}
else {
// All is just peachy
ZmqLogger::Instance()->AppendDebugMethod("\nDecode hardware acceleration is used\n", "Min width :", constraints->min_width, "Min Height :", constraints->min_height, "MaxWidth :", constraints->max_width, "MaxHeight :", constraints->max_height, "Frame width :", pCodecCtx->coded_width, "Frame height :", pCodecCtx->coded_height);
retry_decode_open = 0;
}
av_hwframe_constraints_free(&constraints);
if (hwconfig) {
av_freep(&hwconfig);
}
}
else {
int max_h, max_w;
//max_h = ((getenv( "LIMIT_HEIGHT_MAX" )==NULL) ? MAX_SUPPORTED_HEIGHT : atoi(getenv( "LIMIT_HEIGHT_MAX" )));
max_h = openshot::Settings::Instance()->DE_LIMIT_HEIGHT_MAX;
//max_w = ((getenv( "LIMIT_WIDTH_MAX" )==NULL) ? MAX_SUPPORTED_WIDTH : atoi(getenv( "LIMIT_WIDTH_MAX" )));
max_w = openshot::Settings::Instance()->DE_LIMIT_WIDTH_MAX;
ZmqLogger::Instance()->AppendDebugMethod("Constraints could not be found using default limit\n");
//cerr << "Constraints could not be found using default limit\n";
if (pCodecCtx->coded_width < 0 ||
pCodecCtx->coded_height < 0 ||
pCodecCtx->coded_width > max_w ||
pCodecCtx->coded_height > max_h ) {
ZmqLogger::Instance()->AppendDebugMethod("DIMENSIONS ARE TOO LARGE for hardware acceleration\n", "Max Width :", max_w, "Max Height :", max_h, "Frame width :", pCodecCtx->coded_width, "Frame height :", pCodecCtx->coded_height);
hw_de_supported = 0;
retry_decode_open = 1;
AV_FREE_CONTEXT(pCodecCtx);
if (hw_device_ctx) {
av_buffer_unref(&hw_device_ctx);
hw_device_ctx = NULL;
}
}
else {
ZmqLogger::Instance()->AppendDebugMethod("\nDecode hardware acceleration is used\n", "Max Width :", max_w, "Max Height :", max_h, "Frame width :", pCodecCtx->coded_width, "Frame height :", pCodecCtx->coded_height);
retry_decode_open = 0;
}
}
} // if hw_de_on && hw_de_supported
else {
ZmqLogger::Instance()->AppendDebugMethod("\nDecode in software is used\n");
}
#else
retry_decode_open = 0;
#endif // USE_HW_ACCEL
} while (retry_decode_open); // retry_decode_open
// Free options
av_dict_free(&opts);
// Update the File Info struct with video details (if a video stream is found)
UpdateVideoInfo();
}
// Is there an audio stream?
if (audioStream != -1) {
// Set the stream index
info.audio_stream_index = audioStream;
// Get a pointer to the codec context for the audio stream
aStream = pFormatCtx->streams[audioStream];
// Find the codec ID from stream
AVCodecID codecId = AV_FIND_DECODER_CODEC_ID(aStream);
// Get codec and codec context from stream
AVCodec *aCodec = avcodec_find_decoder(codecId);
aCodecCtx = AV_GET_CODEC_CONTEXT(aStream, aCodec);
// Set number of threads equal to number of processors (not to exceed 16)
aCodecCtx->thread_count = std::min(FF_NUM_PROCESSORS, 16);
if (aCodec == NULL) {
throw InvalidCodec("A valid audio codec could not be found for this file.", path);
}
// Init options
AVDictionary *opts = NULL;
av_dict_set(&opts, "strict", "experimental", 0);
// Open audio codec
if (avcodec_open2(aCodecCtx, aCodec, &opts) < 0)
throw InvalidCodec("An audio codec was found, but could not be opened.", path);
// Free options
av_dict_free(&opts);
// Update the File Info struct with audio details (if an audio stream is found)
UpdateAudioInfo();
}
// Add format metadata (if any)
AVDictionaryEntry *tag = NULL;
while ((tag = av_dict_get(pFormatCtx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
QString str_key = tag->key;
QString str_value = tag->value;
info.metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
}
// Init previous audio location to zero
previous_packet_location.frame = -1;
previous_packet_location.sample_start = 0;
// Adjust cache size based on size of frame and audio
working_cache.SetMaxBytesFromInfo(max_concurrent_frames * info.fps.ToDouble() * 2, info.width, info.height, info.sample_rate, info.channels);
missing_frames.SetMaxBytesFromInfo(max_concurrent_frames * 2, info.width, info.height, info.sample_rate, info.channels);
final_cache.SetMaxBytesFromInfo(max_concurrent_frames * 2, info.width, info.height, info.sample_rate, info.channels);
// Mark as "open"
is_open = true;
}
}
void FFmpegReader::Close() {
// Close all objects, if reader is 'open'
if (is_open) {
// Mark as "closed"
is_open = false;
ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::Close");
if (packet) {
// Remove previous packet before getting next one
RemoveAVPacket(packet);
packet = NULL;
}
// Close the codec
if (info.has_video) {
avcodec_flush_buffers(pCodecCtx);
AV_FREE_CONTEXT(pCodecCtx);
#if USE_HW_ACCEL
if (hw_de_on) {
if (hw_device_ctx) {
av_buffer_unref(&hw_device_ctx);
hw_device_ctx = NULL;
}
}
#endif // USE_HW_ACCEL
}
if (info.has_audio) {
avcodec_flush_buffers(aCodecCtx);
AV_FREE_CONTEXT(aCodecCtx);
}
// Clear final cache
final_cache.Clear();
working_cache.Clear();
missing_frames.Clear();
// Clear processed lists
{
const GenericScopedLock <CriticalSection> lock(processingCriticalSection);
processed_video_frames.clear();
processed_audio_frames.clear();
processing_video_frames.clear();
processing_audio_frames.clear();
missing_audio_frames.clear();
missing_video_frames.clear();
missing_audio_frames_source.clear();
missing_video_frames_source.clear();
checked_frames.clear();
}
// Close the video file
avformat_close_input(&pFormatCtx);
av_freep(&pFormatCtx);
// Reset some variables
last_frame = 0;
largest_frame_processed = 0;
seek_audio_frame_found = 0;
seek_video_frame_found = 0;
current_video_frame = 0;
has_missing_frames = false;
last_video_frame.reset();
}
}
bool FFmpegReader::HasAlbumArt() {
// Check if the video stream we use is an attached picture
// This won't return true if the file has a cover image as a secondary stream
// like an MKV file with an attached image file
return pFormatCtx && videoStream >= 0 && pFormatCtx->streams[videoStream]
&& (pFormatCtx->streams[videoStream]->disposition & AV_DISPOSITION_ATTACHED_PIC);
}
void FFmpegReader::UpdateAudioInfo() {
// Set values of FileInfo struct
info.has_audio = true;
info.file_size = pFormatCtx->pb ? avio_size(pFormatCtx->pb) : -1;
info.acodec = aCodecCtx->codec->name;
info.channels = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channels;
if (AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout == 0)
AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout = av_get_default_channel_layout(AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channels);
info.channel_layout = (ChannelLayout) AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout;
info.sample_rate = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->sample_rate;
info.audio_bit_rate = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->bit_rate;
// Set audio timebase
info.audio_timebase.num = aStream->time_base.num;
info.audio_timebase.den = aStream->time_base.den;
// Get timebase of audio stream (if valid) and greater than the current duration
if (aStream->duration > 0.0f && aStream->duration > info.duration)
info.duration = aStream->duration * info.audio_timebase.ToDouble();
// Check for an invalid video length
if (info.has_video && info.video_length <= 0) {
// Calculate the video length from the audio duration
info.video_length = info.duration * info.fps.ToDouble();
}
// Set video timebase (if no video stream was found)
if (!info.has_video) {
// Set a few important default video settings (so audio can be divided into frames)
info.fps.num = 24;
info.fps.den = 1;
info.video_timebase.num = 1;
info.video_timebase.den = 24;
info.video_length = info.duration * info.fps.ToDouble();
info.width = 720;
info.height = 480;
}
// Fix invalid video lengths for certain types of files (MP3 for example)
if (info.has_video && ((info.duration * info.fps.ToDouble()) - info.video_length > 60)) {
info.video_length = info.duration * info.fps.ToDouble();
}
// Add audio metadata (if any found)
AVDictionaryEntry *tag = NULL;
while ((tag = av_dict_get(aStream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
QString str_key = tag->key;
QString str_value = tag->value;
info.metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
}
}
void FFmpegReader::UpdateVideoInfo() {
if (check_fps)
// Already initialized all the video metadata, no reason to do it again
return;
// Set values of FileInfo struct
info.has_video = true;
info.file_size = pFormatCtx->pb ? avio_size(pFormatCtx->pb) : -1;
info.height = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->height;
info.width = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->width;
info.vcodec = pCodecCtx->codec->name;
info.video_bit_rate = (pFormatCtx->bit_rate / 8);
// Frame rate from the container and codec
AVRational framerate = av_guess_frame_rate(pFormatCtx, pStream, NULL);
info.fps.num = framerate.num;
info.fps.den = framerate.den;
ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::UpdateVideoInfo", "info.fps.num", info.fps.num, "info.fps.den", info.fps.den);
// TODO: remove excessive debug info in the next releases
// The debug info below is just for comparison and troubleshooting on users side during the transition period
ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::UpdateVideoInfo (pStream->avg_frame_rate)", "num", pStream->avg_frame_rate.num, "den", pStream->avg_frame_rate.den);
if (pStream->sample_aspect_ratio.num != 0) {
info.pixel_ratio.num = pStream->sample_aspect_ratio.num;
info.pixel_ratio.den = pStream->sample_aspect_ratio.den;
} else if (AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->sample_aspect_ratio.num != 0) {
info.pixel_ratio.num = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->sample_aspect_ratio.num;
info.pixel_ratio.den = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->sample_aspect_ratio.den;
} else {
info.pixel_ratio.num = 1;
info.pixel_ratio.den = 1;
}
info.pixel_format = AV_GET_CODEC_PIXEL_FORMAT(pStream, pCodecCtx);
// Calculate the DAR (display aspect ratio)
Fraction size(info.width * info.pixel_ratio.num, info.height * info.pixel_ratio.den);
// Reduce size fraction
size.Reduce();
// Set the ratio based on the reduced fraction
info.display_ratio.num = size.num;
info.display_ratio.den = size.den;
// Get scan type and order from codec context/params
if (!check_interlace) {
check_interlace = true;
AVFieldOrder field_order = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->field_order;
switch(field_order) {
case AV_FIELD_PROGRESSIVE:
info.interlaced_frame = false;
break;
case AV_FIELD_TT:
case AV_FIELD_TB:
info.interlaced_frame = true;
info.top_field_first = true;
break;
case AV_FIELD_BT:
case AV_FIELD_BB:
info.interlaced_frame = true;
info.top_field_first = false;
break;
case AV_FIELD_UNKNOWN:
// Check again later?
check_interlace = false;
break;
}
// check_interlace will prevent these checks being repeated,
// unless it was cleared because we got an AV_FIELD_UNKNOWN response.
}
// Set the video timebase
info.video_timebase.num = pStream->time_base.num;
info.video_timebase.den = pStream->time_base.den;
// Set the duration in seconds, and video length (# of frames)
info.duration = pStream->duration * info.video_timebase.ToDouble();
// Check for valid duration (if found)
if (info.duration <= 0.0f && pFormatCtx->duration >= 0)
// Use the format's duration
info.duration = float(pFormatCtx->duration) / AV_TIME_BASE;
// Calculate duration from filesize and bitrate (if any)
if (info.duration <= 0.0f && info.video_bit_rate > 0 && info.file_size > 0)
// Estimate from bitrate, total bytes, and framerate
info.duration = float(info.file_size) / info.video_bit_rate;
// No duration found in stream of file
if (info.duration <= 0.0f) {
// No duration is found in the video stream
info.duration = -1;
info.video_length = -1;
is_duration_known = false;
} else {
// Yes, a duration was found
is_duration_known = true;
// Calculate number of frames
info.video_length = round(info.duration * info.fps.ToDouble());
}
// Override an invalid framerate
if (info.fps.ToFloat() > 240.0f || (info.fps.num <= 0 || info.fps.den <= 0) || info.video_length <= 0) {
// Calculate FPS, duration, video bit rate, and video length manually
// by scanning through all the video stream packets
CheckFPS();
}
// Add video metadata (if any)
AVDictionaryEntry *tag = NULL;
while ((tag = av_dict_get(pStream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
QString str_key = tag->key;
QString str_value = tag->value;
info.metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
}
}
bool FFmpegReader::GetIsDurationKnown() {
return this->is_duration_known;
}
std::shared_ptr<Frame> FFmpegReader::GetFrame(int64_t requested_frame) {
// Check for open reader (or throw exception)
if (!is_open)
throw ReaderClosed("The FFmpegReader is closed. Call Open() before calling this method.", path);
// Adjust for a requested frame that is too small or too large
if (requested_frame < 1)
requested_frame = 1;
if (requested_frame > info.video_length && is_duration_known)
requested_frame = info.video_length;
if (info.has_video && info.video_length == 0)
// Invalid duration of video file
throw InvalidFile("Could not detect the duration of the video or audio stream.", path);
// Debug output
ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetFrame", "requested_frame", requested_frame, "last_frame", last_frame);
// Check the cache for this frame
std::shared_ptr<Frame> frame = final_cache.GetFrame(requested_frame);
if (frame) {
// Debug output
ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetFrame", "returned cached frame", requested_frame);
// Return the cached frame
return frame;
} else {
// Check the cache a 2nd time (due to a potential previous lock)
frame = final_cache.GetFrame(requested_frame);
if (frame) {
// Debug output
ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetFrame", "returned cached frame on 2nd look", requested_frame);
// Return the cached frame
} else {
// Frame is not in cache
// Reset seek count
seek_count = 0;
// Check for first frame (always need to get frame 1 before other frames, to correctly calculate offsets)
if (last_frame == 0 && requested_frame != 1)
// Get first frame
ReadStream(1);
// Are we within X frames of the requested frame?
int64_t diff = requested_frame - last_frame;
if (diff >= 1 && diff <= 20) {
// Continue walking the stream
frame = ReadStream(requested_frame);
} else {
// Greater than 30 frames away, or backwards, we need to seek to the nearest key frame
if (enable_seek)
// Only seek if enabled
Seek(requested_frame);
else if (!enable_seek && diff < 0) {
// Start over, since we can't seek, and the requested frame is smaller than our position
Close();
Open();
}
// Then continue walking the stream
frame = ReadStream(requested_frame);
}
}
return frame;
}
}
// Read the stream until we find the requested Frame
std::shared_ptr<Frame> FFmpegReader::ReadStream(int64_t requested_frame) {
// Allocate video frame
bool end_of_stream = false;
bool check_seek = false;
bool frame_finished = false;
int packet_error = -1;
// Minimum number of packets to process (for performance reasons)
int packets_processed = 0;
int minimum_packets = 1;
int max_packets = 4096;
// Debug output
ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ReadStream", "requested_frame", requested_frame, "max_concurrent_frames", max_concurrent_frames);
// Loop through the stream until the correct frame is found
while (true) {
// Get the next packet into a local variable called packet
packet_error = GetNextPacket();
int processing_video_frames_size = 0;
int processing_audio_frames_size = 0;
{
const GenericScopedLock <CriticalSection> lock(processingCriticalSection);
processing_video_frames_size = processing_video_frames.size();
processing_audio_frames_size = processing_audio_frames.size();
}
// Wait if too many frames are being processed
while (processing_video_frames_size + processing_audio_frames_size >= minimum_packets) {
std::this_thread::sleep_for(std::chrono::milliseconds(3));
const GenericScopedLock <CriticalSection> lock(processingCriticalSection);
processing_video_frames_size = processing_video_frames.size();
processing_audio_frames_size = processing_audio_frames.size();
}
// Get the next packet (if any)
if (packet_error < 0) {
// Break loop when no more packets found
end_of_stream = true;
break;
}
// Debug output
ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ReadStream (GetNextPacket)", "requested_frame", requested_frame, "processing_video_frames_size", processing_video_frames_size, "processing_audio_frames_size", processing_audio_frames_size, "minimum_packets", minimum_packets, "packets_processed", packets_processed, "is_seeking", is_seeking);
// Video packet
if (info.has_video && packet->stream_index == videoStream) {
// Reset this counter, since we have a video packet
num_packets_since_video_frame = 0;
// Check the status of a seek (if any)
if (is_seeking) {
check_seek = CheckSeek(true);
} else {
check_seek = false;
}
if (check_seek) {
// Jump to the next iteration of this loop
continue;
}
// Packet may become NULL on Close inside Seek if CheckSeek returns false
if (!packet) {
// Jump to the next iteration of this loop
continue;
}
// Get the AVFrame from the current packet
frame_finished = GetAVFrame();
// Check if the AVFrame is finished and set it
if (frame_finished) {
// Update PTS / Frame Offset (if any)
UpdatePTSOffset(true);
// Process Video Packet
ProcessVideoPacket(requested_frame);
}
}
// Audio packet
else if (info.has_audio && packet->stream_index == audioStream) {
// Increment this (to track # of packets since the last video packet)
num_packets_since_video_frame++;
// Check the status of a seek (if any)
if (is_seeking) {
check_seek = CheckSeek(false);
} else {
check_seek = false;
}
if (check_seek) {
// Jump to the next iteration of this loop
continue;
}
// Packet may become NULL on Close inside Seek if CheckSeek returns false
if (!packet) {
// Jump to the next iteration of this loop
continue;
}
// Update PTS / Frame Offset (if any)
UpdatePTSOffset(false);
// Determine related video frame and starting sample # from audio PTS
AudioLocation location = GetAudioPTSLocation(packet->pts);
// Process Audio Packet
ProcessAudioPacket(requested_frame, location.frame, location.sample_start);
}
// Check if working frames are 'finished'
if (!is_seeking) {
// Check for final frames
CheckWorkingFrames(false, requested_frame);