forked from xueguoliang/QtAV
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AVDemuxer.cpp
1306 lines (1220 loc) · 40.4 KB
/
AVDemuxer.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
/******************************************************************************
QtAV: Multimedia framework based on Qt and FFmpeg
Copyright (C) 2012-2016 Wang Bin <[email protected]>
* This file is part of QtAV
This library 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 2.1 of the License, or (at your option) any later version.
This library 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 this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
#include "QtAV/AVDemuxer.h"
#include "QtAV/MediaIO.h"
#include "QtAV/private/AVCompat.h"
#include <QtCore/QMutex>
#include <QtCore/QStringList>
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
#include <QtCore/QElapsedTimer>
#else
#include <QtCore/QTime>
typedef QTime QElapsedTimer;
#endif
#include "utils/internal.h"
#include "utils/Logger.h"
namespace QtAV {
static const char kFileScheme[] = "file:";
class AVDemuxer::InterruptHandler : public AVIOInterruptCB
{
public:
enum Action {
Unknown = -1,
Open,
FindStreamInfo,
Read
};
//default network timeout: 30000
InterruptHandler(AVDemuxer* demuxer, int timeout = 30000)
: mStatus(0)
, mTimeout(timeout)
, mTimeoutAbort(true)
, mEmitError(true)
//, mLastTime(0)
, mAction(Unknown)
, mpDemuxer(demuxer)
{
callback = handleTimeout;
opaque = this;
}
~InterruptHandler() {
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
mTimer.invalidate();
#else
mTimer.stop();
#endif
}
void begin(Action act) {
if (mStatus > 0)
mStatus = 0;
mEmitError = true;
mAction = act;
mTimer.start();
}
void end() {
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
mTimer.invalidate();
#else
mTimer.stop();
#endif
switch (mAction) {
case Read:
//mpDemuxer->setMediaStatus(BufferedMedia);
break;
default:
break;
}
mAction = Unknown;
}
qint64 getTimeout() const { return mTimeout; }
void setTimeout(qint64 timeout) { mTimeout = timeout; }
bool setInterruptOnTimeout(bool value) {
if (mTimeoutAbort == value)
return false;
mTimeoutAbort = value;
if (mTimeoutAbort) {
mEmitError = true;
}
return true;
}
bool isInterruptOnTimeout() const {return mTimeoutAbort;}
int getStatus() const { return mStatus; }
void setStatus(int status) { mStatus = status; }
/*
* metodo per interruzione loop ffmpeg
* @param void*obj: classe attuale
* @return
* >0 Interruzione loop di ffmpeg!
*/
static int handleTimeout(void* obj) {
InterruptHandler* handler = static_cast<InterruptHandler*>(obj);
if (!handler) {
qWarning("InterruptHandler is null");
return -1;
}
//check manual interruption
if (handler->getStatus() < 0) {
qDebug("User Interrupt: -> quit!");
// DO NOT call setMediaStatus() here.
/* MUST make sure blocking functions (open, read) return before we change the status
* because demuxer may be closed in another thread at the same time if status is not LoadingMedia
* use handleError() after blocking functions return is good
*/
// 1: blocking operation will be aborted.
return 1;//interrupt
}
// qApp->processEvents(); //FIXME: qml crash
switch (handler->mAction) {
case Unknown: //callback is not called between begin()/end()
//qWarning("Unknown timeout action");
break;
case Open:
case FindStreamInfo:
//qDebug("set loading media for %d from: %d", handler->mAction, handler->mpDemuxer->mediaStatus());
handler->mpDemuxer->setMediaStatus(LoadingMedia);
break;
case Read:
//handler->mpDemuxer->setMediaStatus(BufferingMedia);
default:
break;
}
if (handler->mTimeout < 0)
return 0;
if (!handler->mTimer.isValid()) {
//qDebug("timer is not valid, start it");
handler->mTimer.start();
//handler->mLastTime = handler->mTimer.elapsed();
return 0;
}
//use restart
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
if (!handler->mTimer.hasExpired(handler->mTimeout))
#else
if (handler->mTimer.elapsed() < handler->mTimeout)
#endif
return 0;
qDebug("status: %d, Timeout expired: %lld/%lld -> quit!", (int)handler->mStatus, handler->mTimer.elapsed(), handler->mTimeout);
handler->mTimer.invalidate();
if (handler->mStatus == 0) {
AVError::ErrorCode ec(AVError::ReadTimedout);
if (handler->mAction == Open) {
ec = AVError::OpenTimedout;
} else if (handler->mAction == FindStreamInfo) {
ec = AVError::ParseStreamTimedOut;
} else if (handler->mAction == Read) {
ec = AVError::ReadTimedout;
}
handler->mStatus = (int)ec;
// maybe changed in other threads
//handler->mStatus.testAndSetAcquire(0, ec);
}
if (handler->mTimeoutAbort)
return 1;
// emit demuxer error, handleerror
if (handler->mEmitError) {
handler->mEmitError = false;
AVError::ErrorCode ec = AVError::ErrorCode(handler->mStatus); //FIXME: maybe changed in other threads
QString es;
handler->mpDemuxer->handleError(AVERROR_EXIT, &ec, es);
}
return 0;
}
private:
int mStatus;
qint64 mTimeout;
bool mTimeoutAbort;
bool mEmitError;
//qint64 mLastTime;
Action mAction;
AVDemuxer *mpDemuxer;
QElapsedTimer mTimer;
};
class AVDemuxer::Private
{
public:
Private()
: media_status(NoMedia)
, seekable(false)
, network(false)
, has_attached_pic(false)
, started(false)
, max_pts(0.0)
, eof(false)
, media_changed(true)
, buf_pos(0)
, stream(-1)
, format_ctx(0)
, input_format(0)
, input(0)
, seek_unit(SeekByTime)
, seek_type(AccurateSeek)
, dict(0)
, interrupt_hanlder(0)
{}
~Private() {
delete interrupt_hanlder;
if (dict) {
av_dict_free(&dict);
dict = 0;
}
if (input) {
delete input;
input = 0;
}
}
void applyOptionsForDict();
void applyOptionsForContext();
void resetStreams() {
stream = -1;
if (media_changed)
astream = vstream = sstream = StreamInfo();
else
astream.avctx = vstream.avctx = sstream.avctx = 0;
audio_streams.clear();
video_streams.clear();
subtitle_streams.clear();
}
void checkNetwork() {
// FIXME: is there a good way to check network? now use URLContext.flags == URL_PROTOCOL_FLAG_NETWORK
// not network: concat cache pipe avdevice crypto?
if (!file.isEmpty()
&& file.contains(QLatin1String(":"))
&& (file.startsWith(QLatin1String("http")) //http, https, httpproxy
|| file.startsWith(QLatin1String("rtmp")) //rtmp{,e,s,te,ts}
|| file.startsWith(QLatin1String("mms")) //mms{,h,t}
|| file.startsWith(QLatin1String("ffrtmp")) //ffrtmpcrypt, ffrtmphttp
|| file.startsWith(QLatin1String("rtp:"))
|| file.startsWith(QLatin1String("rtsp:"))
|| file.startsWith(QLatin1String("sctp:"))
|| file.startsWith(QLatin1String("tcp:"))
|| file.startsWith(QLatin1String("tls:"))
|| file.startsWith(QLatin1String("udp:"))
|| file.startsWith(QLatin1String("gopher:"))
)) {
network = true; //iformat.flags: AVFMT_NOFILE
}
}
bool checkSeekable() {
if (!format_ctx)
return false;
if (input)
return input->isSeekable();
if (format_ctx->pb)
return format_ctx->pb->seekable;
// avio context null. not sure the correct way to detect seekable
return format_ctx->iformat->read_seek || format_ctx->iformat->read_seek2;
}
// set wanted_xx_stream. call openCodecs() to read new stream frames
// stream < 0 is choose best
bool setStream(AVDemuxer::StreamType st, int streamValue);
//called by loadFile(). if change to a new stream, call it(e.g. in AVPlayer)
bool prepareStreams();
MediaStatus media_status;
bool seekable;
bool network;
bool has_attached_pic;
bool started;
qreal max_pts; // max pts read
bool eof;
bool media_changed;
mutable qptrdiff buf_pos; // detect eof for dynamic size (growing) stream even if detectDynamicStreamInterval() is not set
Packet pkt;
int stream;
QList<int> audio_streams, video_streams, subtitle_streams;
AVFormatContext *format_ctx;
//copy the info, not parse the file when constructed, then need member vars
QString file;
QString file_orig;
AVInputFormat *input_format;
QString format_forced;
MediaIO *input;
SeekUnit seek_unit;
SeekType seek_type;
AVDictionary *dict;
QVariantHash options;
typedef struct StreamInfo {
StreamInfo()
: stream(-1)
, wanted_stream(-1)
, index(-1)
, wanted_index(-1)
, avctx(0)
{}
// wanted_stream is REQUIRED. e.g. always set -1 to indicate the default stream, -2 to disable
int stream, wanted_stream; // -1 default, selected by ff
int index, wanted_index; // index in a kind of streams
AVCodecContext *avctx;
} StreamInfo;
StreamInfo astream, vstream, sstream;
AVDemuxer::InterruptHandler *interrupt_hanlder;
QMutex mutex; //TODO: remove?
};
AVDemuxer::AVDemuxer(QObject *parent)
: QObject(parent)
, d(new Private())
{
// TODO: xxx_register_all already use static var
class AVInitializer {
public:
AVInitializer() {
avcodec_register_all();
#if QTAV_HAVE(AVDEVICE)
avdevice_register_all();
#endif
av_register_all();
avformat_network_init();
}
~AVInitializer() {
avformat_network_deinit();
}
};
static AVInitializer sAVInit;
Q_UNUSED(sAVInit);
d->interrupt_hanlder = new InterruptHandler(this);
}
AVDemuxer::~AVDemuxer()
{
unload();
}
static void getFFmpegInputFormats(QStringList* formats, QStringList* extensions)
{
static QStringList exts;
static QStringList fmts;
if (exts.isEmpty() && fmts.isEmpty()) {
av_register_all(); // MUST register all input/output formats
AVInputFormat *i = NULL;
QStringList e, f;
while ((i = av_iformat_next(i))) {
if (i->extensions)
e << QString::fromLatin1(i->extensions).split(QLatin1Char(','), QString::SkipEmptyParts);
if (i->name)
f << QString::fromLatin1(i->name).split(QLatin1Char(','), QString::SkipEmptyParts);
}
foreach (const QString& v, e) {
exts.append(v.trimmed());
}
foreach (const QString& v, f) {
fmts.append(v.trimmed());
}
exts.removeDuplicates();
fmts.removeDuplicates();
}
if (formats)
*formats = fmts;
if (extensions)
*extensions = exts;
}
const QStringList& AVDemuxer::supportedFormats()
{
static QStringList fmts;
if (fmts.isEmpty())
getFFmpegInputFormats(&fmts, NULL);
return fmts;
}
const QStringList& AVDemuxer::supportedExtensions()
{
static QStringList exts;
if (exts.isEmpty())
getFFmpegInputFormats(NULL, &exts);
return exts;
}
const QStringList &AVDemuxer::supportedProtocols()
{
static QStringList protocols;
if (!protocols.isEmpty())
return protocols;
#if QTAV_HAVE(AVDEVICE)
protocols << QStringLiteral("avdevice");
#endif
av_register_all(); // MUST register all input/output formats
void* opq = 0;
const char* protocol = avio_enum_protocols(&opq, 0);
while (protocol) {
// static string, no deep copy needed. but QByteArray::fromRawData(data,size) assumes data is not null terminated and we must give a size
protocols.append(QString::fromUtf8(protocol));
protocol = avio_enum_protocols(&opq, 0);
}
return protocols;
}
MediaStatus AVDemuxer::mediaStatus() const
{
return d->media_status;
}
bool AVDemuxer::readFrame()
{
QMutexLocker lock(&d->mutex);
Q_UNUSED(lock);
if (!d->format_ctx)
return false;
d->pkt = Packet();
// no lock required because in AVDemuxThread read and seek are in the same thread
AVPacket packet;
d->interrupt_hanlder->begin(InterruptHandler::Read);
int ret = av_read_frame(d->format_ctx, &packet); //0: ok, <0: error/end
d->interrupt_hanlder->end();
// TODO: why return 0 if interrupted by user?
if (ret < 0) {
//end of file. FIXME: why no d->eof if replaying by seek(0)?
// ffplay also check pb && pb->error and exit read thread
if (ret == AVERROR_EOF
// AVFMT_NOFILE(e.g. network streams) stream has no pb
|| avio_feof(d->format_ctx->pb)) {
if (!d->eof) {
if (getInterruptStatus()) { //eof error if interrupted!
AVError::ErrorCode ec(AVError::ReadError);
QString msg(tr("error reading stream data"));
handleError(ret, &ec, msg);
}
d->eof = true;
#if 0 // EndOfMedia when demux thread finished
d->started = false;
setMediaStatus(EndOfMedia);
emit finished();
#endif
qDebug("End of file. erreof=%d feof=%d", ret == AVERROR_EOF, avio_feof(d->format_ctx->pb));
}
return false;
}
if (ret == AVERROR(EAGAIN)) {
qWarning("demuxer EAGAIN :%s", av_err2str(ret));
return false;
}
AVError::ErrorCode ec(AVError::ReadError);
QString msg(tr("error reading stream data"));
handleError(ret, &ec, msg);
qWarning("[AVDemuxer] error: %s", av_err2str(ret));
return false;
}
d->stream = packet.stream_index;
//check whether the 1st frame is alreay got. emit only once
if (!d->started) {
d->started = true;
emit started();
}
if (d->stream != videoStream() && d->stream != audioStream() && d->stream != subtitleStream()) {
//qWarning("[AVDemuxer] unknown stream index: %d", stream);
return false;
}
// TODO: v4l2 copy
d->pkt = Packet::fromAVPacket(&packet, av_q2d(d->format_ctx->streams[d->stream]->time_base));
av_packet_unref(&packet); //important!
d->eof = false;
if (d->pkt.pts > qreal(duration())/1000.0) {
d->max_pts = d->pkt.pts;
}
return true;
}
Packet AVDemuxer::packet() const
{
return d->pkt;
}
int AVDemuxer::stream() const
{
return d->stream;
}
bool AVDemuxer::atEnd() const
{
if (!d->format_ctx)
return false;
if (d->format_ctx->pb) {
AVIOContext *pb = d->format_ctx->pb;
//qDebug("pb->error: %#x, eof: %d, pos: %lld, bufptr: %p", pb->error, pb->eof_reached, pb->pos, pb->buf_ptr);
if (d->eof && (qptrdiff)pb->buf_ptr == d->buf_pos)
return true;
d->buf_pos = (qptrdiff)pb->buf_ptr;
return false;
}
return d->eof;
}
bool AVDemuxer::isSeekable() const
{
return d->seekable;
}
void AVDemuxer::setSeekUnit(SeekUnit unit)
{
d->seek_unit = unit;
}
SeekUnit AVDemuxer::seekUnit() const
{
return d->seek_unit;
}
void AVDemuxer::setSeekType(SeekType target)
{
d->seek_type = target;
}
SeekType AVDemuxer::seekType() const
{
return d->seek_type;
}
//TODO: seek by byte
bool AVDemuxer::seek(qint64 pos)
{
if (!isLoaded())
return false;
//duration: unit is us (10^-6 s, AV_TIME_BASE)
qint64 upos = pos*1000LL;
if (upos > startTimeUs() + durationUs() || pos < 0LL) {
if (pos >= 0LL && d->input && d->input->isSeekable() && d->input->isVariableSize()) {
qDebug("Seek for variable size hack. %lld %.2f. valid range [%lld, %lld]", upos, double(upos)/double(durationUs()), startTimeUs(), startTimeUs()+durationUs());
} else if (d->max_pts > qreal(duration())/1000.0) { //FIXME
qDebug("Seek (%lld) when video duration is growing %lld=>%lld", pos, duration(), qint64(d->max_pts*1000.0));
} else {
qWarning("Invalid seek position %lld %.2f. valid range [%lld, %lld]", upos, double(upos)/double(durationUs()), startTimeUs(), startTimeUs()+durationUs());
return false;
}
}
d->eof = false;
// no lock required because in AVDemuxThread read and seek are in the same thread
#if 0
//t: unit is s
qreal t = q;// * (double)d->format_ctx->duration; //
int ret = av_seek_frame(d->format_ctx, -1, (int64_t)(t*AV_TIME_BASE), t > d->pkt.pts ? 0 : AVSEEK_FLAG_BACKWARD);
qDebug("[AVDemuxer] seek to %f %f %lld / %lld", q, d->pkt.pts, (int64_t)(t*AV_TIME_BASE), durationUs());
#else
//TODO: d->pkt.pts may be 0, compute manually.
bool backward = d->seek_type == AccurateSeek || upos <= (int64_t)(d->pkt.pts*AV_TIME_BASE);
//qDebug("[AVDemuxer] seek to %f %f %lld / %lld backward=%d", double(upos)/double(durationUs()), d->pkt.pts, upos, durationUs(), backward);
//AVSEEK_FLAG_BACKWARD has no effect? because we know the timestamp
// FIXME: back flag is opposite? otherwise seek is bad and may crash?
/* If stread->inputdex is (-1), a default
* stream is selected, and timestamp is automatically converted
* from AV_TIME_BASE units to the stream specific time_base.
*/
int seek_flag = (backward ? AVSEEK_FLAG_BACKWARD : 0);
if (d->seek_type == AccurateSeek) {
seek_flag = AVSEEK_FLAG_BACKWARD;
}
if (d->seek_type == AnyFrameSeek) {
seek_flag |= AVSEEK_FLAG_ANY;
}
//qDebug("seek flag: %d", seek_flag);
//bool seek_bytes = !!(d->format_ctx->iformat->flags & AVFMT_TS_DISCONT) && strcmp("ogg", d->format_ctx->iformat->name);
int ret = av_seek_frame(d->format_ctx, -1, upos, seek_flag);
//int ret = avformat_seek_file(d->format_ctx, -1, INT64_MIN, upos, upos, seek_flag);
//avformat_seek_file()
if (ret < 0 && (seek_flag & AVSEEK_FLAG_BACKWARD)) {
// seek to 0?
qDebug("av_seek_frame error with flag AVSEEK_FLAG_BACKWARD: %s. try to seek without the flag", av_err2str(ret));
seek_flag &= ~AVSEEK_FLAG_BACKWARD;
ret = av_seek_frame(d->format_ctx, -1, upos, seek_flag);
}
//qDebug("av_seek_frame ret: %d", ret);
#endif
if (ret < 0) {
AVError::ErrorCode ec(AVError::SeekError);
QString msg(tr("seek error"));
handleError(ret, &ec, msg);
return false;
}
// TODO: replay
if (upos <= startTime()) {
qDebug("************seek to beginning. started = false");
d->started = false; //???
if (d->astream.avctx)
d->astream.avctx->frame_number = 0;
if (d->vstream.avctx)
d->vstream.avctx->frame_number = 0; //TODO: why frame_number not changed after seek?
if (d->sstream.avctx)
d->sstream.avctx->frame_number = 0;
}
return true;
}
bool AVDemuxer::seek(qreal q)
{
if (duration() <= 0) {
qWarning("duration() must be valid for percentage seek");
return false;
}
return seek(qint64(q*(double)duration()));
}
QString AVDemuxer::fileName() const
{
return d->file_orig;
}
QIODevice* AVDemuxer::ioDevice() const
{
if (!d->input)
return 0;
if (d->input->name() != QLatin1String("QIODevice"))
return 0;
return d->input->property("device").value<QIODevice*>();
}
MediaIO* AVDemuxer::mediaIO() const
{
return d->input;
}
bool AVDemuxer::setMedia(const QString &fileName)
{
if (d->input) {
delete d->input;
d->input = 0;
}
d->file_orig = fileName;
const QString url_old(d->file);
d->file = fileName.trimmed();
if (d->file.startsWith(QLatin1String("mms:")))
d->file.insert(3, QLatin1Char('h'));
else if (d->file.startsWith(QLatin1String(kFileScheme)))
d->file = Internal::Path::toLocal(d->file);
int colon = d->file.indexOf(QLatin1Char(':'));
if (colon == 1) {
#ifdef Q_OS_WINRT
d->file.prepend(QStringLiteral("qfile:"));
#endif
}
d->media_changed = url_old != d->file;
if (d->media_changed) {
d->format_forced.clear();
}
// a local file. return here to avoid protocol checking. If path contains ":", protocol checking will fail
if (d->file.startsWith(QLatin1Char('/')))
return d->media_changed;
// use MediaIO to support protocols not supported by ffmpeg
colon = d->file.indexOf(QLatin1Char(':'));
if (colon >= 0) {
#ifdef Q_OS_WIN
if (colon == 1 && d->file.at(0).isLetter())
return d->media_changed;
#endif
const QString scheme = colon == 0 ? QStringLiteral("qrc") : d->file.left(colon);
// supportedProtocols() is not complete. so try MediaIO 1st, if not found, fallback to libavformat
d->input = MediaIO::createForProtocol(scheme);
if (d->input) {
d->input->setUrl(d->file);
}
}
return d->media_changed;
}
bool AVDemuxer::setMedia(QIODevice* device)
{
d->file = QString();
d->file_orig = QString();
if (d->input) {
if (d->input->name() != QLatin1String("QIODevice")) {
delete d->input;
d->input = 0;
}
}
if (!d->input)
d->input = MediaIO::create("QIODevice");
QIODevice* old_dev = d->input->property("device").value<QIODevice*>();
d->media_changed = old_dev != device;
if (d->media_changed) {
d->format_forced.clear();
}
d->input->setProperty("device", QVariant::fromValue(device)); //open outside?
return d->media_changed;
}
bool AVDemuxer::setMedia(MediaIO *in)
{
d->media_changed = in != d->input;
if (d->media_changed) {
d->format_forced.clear();
}
d->file = QString();
d->file_orig = QString();
if (!d->input)
d->input = in;
if (d->input != in) {
delete d->input;
d->input = in;
}
return d->media_changed;
}
void AVDemuxer::setFormat(const QString &fmt)
{
d->format_forced = fmt;
}
QString AVDemuxer::formatForced() const
{
return d->format_forced;
}
bool AVDemuxer::load()
{
unload();
qDebug("all closed and reseted");
if (d->file.isEmpty() && !d->input) {
setMediaStatus(NoMedia);
return false;
}
QMutexLocker lock(&d->mutex);
Q_UNUSED(lock);
setMediaStatus(LoadingMedia);
d->checkNetwork();
#if QTAV_HAVE(AVDEVICE)
static const QString avd_scheme(QStringLiteral("avdevice:"));
if (d->file.startsWith(avd_scheme)) {
QStringList parts = d->file.split(QStringLiteral(":"));
if (parts.count() != 3) {
qDebug("invalid avdevice specification");
setMediaStatus(InvalidMedia);
return false;
}
if (d->file.startsWith(avd_scheme + QStringLiteral("//"))) {
// avdevice://avfoundation:device_name
d->input_format = av_find_input_format(parts[1].mid(2).toUtf8().constData());
} else {
// avdevice:video4linux2:file_name
d->input_format = av_find_input_format(parts[1].toUtf8().constData());
}
d->file = parts[2];
}
#endif
//alloc av format context
if (!d->format_ctx)
d->format_ctx = avformat_alloc_context();
d->format_ctx->flags |= AVFMT_FLAG_GENPTS;
//install interrupt callback
d->format_ctx->interrupt_callback = *d->interrupt_hanlder;
d->applyOptionsForDict();
// check special dict keys
// d->format_forced can be set from AVFormatContext.format_whitelist
if (!d->format_forced.isEmpty()) {
d->input_format = av_find_input_format(d->format_forced.toUtf8().constData());
qDebug() << "force format: " << d->format_forced;
}
int ret = 0;
// used dict entries will be removed in avformat_open_input
d->interrupt_hanlder->begin(InterruptHandler::Open);
if (d->input) {
if (d->input->accessMode() == MediaIO::Write) {
qWarning("wrong MediaIO accessMode. MUST be Read");
}
d->format_ctx->pb = (AVIOContext*)d->input->avioContext();
d->format_ctx->flags |= AVFMT_FLAG_CUSTOM_IO;
qDebug("avformat_open_input: d->format_ctx:'%p'..., MediaIO('%s'): %p", d->format_ctx, d->input->name().toUtf8().constData(), d->input);
ret = avformat_open_input(&d->format_ctx, "MediaIO", d->input_format, d->options.isEmpty() ? NULL : &d->dict);
qDebug("avformat_open_input: (with MediaIO) ret:%d", ret);
} else {
qDebug("avformat_open_input: d->format_ctx:'%p', url:'%s'...",d->format_ctx, qPrintable(d->file));
ret = avformat_open_input(&d->format_ctx, d->file.toUtf8().constData(), d->input_format, d->options.isEmpty() ? NULL : &d->dict);
qDebug("avformat_open_input: url:'%s' ret:%d",qPrintable(d->file), ret);
}
d->interrupt_hanlder->end();
if (ret < 0) {
// d->format_ctx is 0
AVError::ErrorCode ec = AVError::OpenError;
QString msg = tr("failed to open media");
handleError(ret, &ec, msg);
qWarning() << "Can't open media: " << msg;
if (mediaStatus() == LoadingMedia) //workaround for timeout but not interrupted
setMediaStatus(InvalidMedia);
Q_EMIT unloaded(); //context not ready. so will not emit in unload()
return false;
}
//deprecated
//if(av_find_stread->inputfo(d->format_ctx)<0) {
//TODO: avformat_find_stread->inputfo is too slow, only useful for some video format
d->interrupt_hanlder->begin(InterruptHandler::FindStreamInfo);
ret = avformat_find_stream_info(d->format_ctx, NULL);
d->interrupt_hanlder->end();
if (ret < 0) {
setMediaStatus(InvalidMedia);
AVError::ErrorCode ec(AVError::ParseStreamError);
QString msg(tr("failed to find stream info"));
handleError(ret, &ec, msg);
qWarning() << "Can't find stream info: " << msg;
// context is ready. unloaded() will be emitted in unload()
if (mediaStatus() == LoadingMedia) //workaround for timeout but not interrupted
setMediaStatus(InvalidMedia);
return false;
}
if (!d->prepareStreams()) {
if (mediaStatus() == LoadingMedia)
setMediaStatus(InvalidMedia);
return false;
}
d->started = false;
setMediaStatus(LoadedMedia);
Q_EMIT loaded();
const bool was_seekable = d->seekable;
d->seekable = d->checkSeekable();
if (was_seekable != d->seekable)
Q_EMIT seekableChanged();
qDebug("avfmtctx.flag: %d", d->format_ctx->flags);
qDebug("AVFMT_NOTIMESTAMPS: %d, AVFMT_TS_DISCONT: %d, AVFMT_NO_BYTE_SEEK:%d, custom io: %d"
, d->format_ctx->flags&AVFMT_NOTIMESTAMPS
, d->format_ctx->flags&AVFMT_TS_DISCONT
, d->format_ctx->flags&AVFMT_NO_BYTE_SEEK
, d->format_ctx->flags&AVFMT_FLAG_CUSTOM_IO
);
if (getInterruptStatus() < 0) {
QString msg;
qDebug("AVERROR_EXIT: %d", AVERROR_EXIT);
handleError(AVERROR_EXIT, 0, msg);
qWarning() << "User interupted: " << msg;
return false;
}
return true;
}
bool AVDemuxer::unload()
{
QMutexLocker lock(&d->mutex);
Q_UNUSED(lock);
/*
if (d->seekable) {
d->seekable = false; //
emit seekableChanged();
}
*/
d->network = false;
d->has_attached_pic = false;
d->eof = false; // true and set false in load()?
d->buf_pos = 0;
d->started = false;
d->max_pts = 0.0;
d->resetStreams();
d->interrupt_hanlder->setStatus(0);
//av_close_input_file(d->format_ctx); //deprecated
if (d->format_ctx) {
qDebug("closing d->format_ctx");
avformat_close_input(&d->format_ctx); //libavf > 53.10.0
d->format_ctx = 0;
d->input_format = 0;
// no delete. may be used in next load
if (d->input)
d->input->release();
Q_EMIT unloaded();
}
return true;
}
bool AVDemuxer::isLoaded() const
{
return d->format_ctx && (d->astream.avctx || d->vstream.avctx || d->sstream.avctx);
}
bool AVDemuxer::hasAttacedPicture() const
{
return d->has_attached_pic;
}
bool AVDemuxer::setStreamIndex(StreamType st, int index)
{
QList<int> *streams = 0;
Private::StreamInfo *si = 0;
if (st == AudioStream) { // TODO: use a struct
si = &d->astream;
streams = &d->audio_streams;
} else if (st == VideoStream) {
si = &d->vstream;
streams = &d->video_streams;
} else if (st == SubtitleStream) {
si = &d->sstream;
streams = &d->subtitle_streams;
}
if (!si) {
qWarning("stream type %d for index %d not found", st, index);
return false;
}
if (index >= streams->size()) {// || index < 0) { //TODO: disable if <0
//si->wanted_stream = -1;
qWarning("invalid index %d (valid is 0~%d) for stream type %d.", index, streams->size(), st);
return false;
}
if (index < 0) {
qDebug("disable %d stream", st);
si->stream = -1;
si->wanted_index = -1;
si->wanted_stream = -1;
return true;
}
if (!d->setStream(st, streams->at(index)))
return false;
si->wanted_index = index;
return true;
}
AVFormatContext* AVDemuxer::formatContext()
{
return d->format_ctx;
}
QString AVDemuxer::formatName() const
{
if (!d->format_ctx)
return QString();
return QLatin1String(d->format_ctx->iformat->name);
}
QString AVDemuxer::formatLongName() const
{
if (!d->format_ctx)
return QString();
return QLatin1String(d->format_ctx->iformat->long_name);
}
// convert to s using AV_TIME_BASE then *1000?
qint64 AVDemuxer::startTime() const
{
return startTimeUs()/1000LL;
}
qint64 AVDemuxer::duration() const
{
return durationUs()/1000LL; //time base: AV_TIME_BASE
}
//AVFrameContext use AV_TIME_BASE as time base. AVStream use their own timebase
qint64 AVDemuxer::startTimeUs() const
{
// start time may be not null for network stream
if (!d->format_ctx || d->format_ctx->start_time == AV_NOPTS_VALUE)
return 0;
return d->format_ctx->start_time;
}
qint64 AVDemuxer::durationUs() const
{
if (!d->format_ctx || d->format_ctx->duration == AV_NOPTS_VALUE)
return 0;
return d->format_ctx->duration; //time base: AV_TIME_BASE
}
int AVDemuxer::bitRate() const
{
return d->format_ctx->bit_rate;
}
qreal AVDemuxer::frameRate() const
{
if (videoStream() < 0)
return 0;
AVStream *stream = d->format_ctx->streams[videoStream()];
return av_q2d(stream->avg_frame_rate);
//codecCtx->time_base.den / codecCtx->time_base.num
}
qint64 AVDemuxer::frames(int stream) const
{
if (stream == -1) {
stream = videoStream();
if (stream < 0)
stream = audioStream();
if (stream < 0)
return 0;
}
return d->format_ctx->streams[stream]->nb_frames;
}
int AVDemuxer::currentStream(StreamType st) const
{
if (st == AudioStream)