/
DVDDemuxFFmpeg.cpp
2168 lines (1892 loc) · 65.9 KB
/
DVDDemuxFFmpeg.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
/*
* Copyright (C) 2005-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#include "DVDDemuxFFmpeg.h"
#include <sstream>
#include <utility>
#include "commons/Exception.h"
#include "cores/FFmpeg.h"
#include "cores/VideoPlayer/Interface/Addon/TimingConstants.h" // for DVD_TIME_BASE
#include "DVDDemuxUtils.h"
#include "DVDInputStreams/DVDInputStream.h"
#include "DVDInputStreams/DVDInputStreamFFmpeg.h"
#include "ServiceBroker.h"
#include "filesystem/CurlFile.h"
#include "filesystem/Directory.h"
#include "filesystem/File.h"
#include "settings/AdvancedSettings.h"
#include "settings/Settings.h"
#include "threads/SystemClock.h"
#include "threads/SingleLock.h"
#include "URL.h"
#include "utils/log.h"
#include "utils/StringUtils.h"
#include "utils/URIUtils.h"
#ifdef HAVE_LIBBLURAY
#include "DVDInputStreams/DVDInputStreamBluray.h"
#endif
#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#ifdef TARGET_POSIX
#include "stdint.h"
#endif
extern "C" {
#include "libavutil/dict.h"
#include "libavutil/opt.h"
}
struct StereoModeConversionMap
{
const char* name;
const char* mode;
};
// we internally use the matroska string representation of stereoscopic modes.
// This struct is a conversion map to convert stereoscopic mode values
// from asf/wmv to the internally used matroska ones
static const struct StereoModeConversionMap WmvToInternalStereoModeMap[] =
{
{ "SideBySideRF", "right_left" },
{ "SideBySideLF", "left_right" },
{ "OverUnderRT", "bottom_top" },
{ "OverUnderLT", "top_bottom" },
{}
};
#define FF_MAX_EXTRADATA_SIZE ((1 << 28) - AV_INPUT_BUFFER_PADDING_SIZE)
std::string CDemuxStreamAudioFFmpeg::GetStreamName()
{
if(!m_stream)
return "";
if(!m_description.empty())
return m_description;
else
return CDemuxStream::GetStreamName();
}
std::string CDemuxStreamSubtitleFFmpeg::GetStreamName()
{
if(!m_stream)
return "";
if(!m_description.empty())
return m_description;
else
return CDemuxStream::GetStreamName();
}
std::string CDemuxStreamVideoFFmpeg::GetStreamName()
{
if (!m_stream)
return "";
if (!m_description.empty())
return m_description;
else
return CDemuxStream::GetStreamName();
}
CDemuxParserFFmpeg::~CDemuxParserFFmpeg()
{
if (m_codecCtx)
avcodec_free_context(&m_codecCtx);
if (m_parserCtx)
{
av_parser_close(m_parserCtx);
m_parserCtx = nullptr;
}
}
static int interrupt_cb(void* ctx)
{
CDVDDemuxFFmpeg* demuxer = static_cast<CDVDDemuxFFmpeg*>(ctx);
if(demuxer && demuxer->Aborted())
return 1;
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
/*
static int dvd_file_open(URLContext *h, const char *filename, int flags)
{
return -1;
}
*/
static int dvd_file_read(void *h, uint8_t* buf, int size)
{
if(interrupt_cb(h))
return AVERROR_EXIT;
std::shared_ptr<CDVDInputStream> pInputStream = static_cast<CDVDDemuxFFmpeg*>(h)->m_pInput;
int len = pInputStream->Read(buf, size);
if (len == 0)
return AVERROR_EOF;
else
return len;
}
/*
static int dvd_file_write(URLContext *h, uint8_t* buf, int size)
{
return -1;
}
*/
static int64_t dvd_file_seek(void *h, int64_t pos, int whence)
{
if(interrupt_cb(h))
return AVERROR_EXIT;
std::shared_ptr<CDVDInputStream> pInputStream = static_cast<CDVDDemuxFFmpeg*>(h)->m_pInput;
if(whence == AVSEEK_SIZE)
return pInputStream->GetLength();
else
return pInputStream->Seek(pos, whence & ~AVSEEK_FORCE);
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
CDVDDemuxFFmpeg::CDVDDemuxFFmpeg() : CDVDDemux()
{
m_pFormatContext = NULL;
m_pInput = NULL;
m_ioContext = NULL;
m_currentPts = DVD_NOPTS_VALUE;
m_bMatroska = false;
m_bAVI = false;
m_bSup = false;
m_speed = DVD_PLAYSPEED_NORMAL;
m_program = UINT_MAX;
m_pkt.result = -1;
memset(&m_pkt.pkt, 0, sizeof(AVPacket));
m_streaminfo = true; /* set to true if we want to look for streams before playback */
m_checkvideo = false;
m_dtsAtDisplayTime = DVD_NOPTS_VALUE;
}
CDVDDemuxFFmpeg::~CDVDDemuxFFmpeg()
{
Dispose();
ff_flush_avutil_log_buffers();
}
bool CDVDDemuxFFmpeg::Aborted()
{
if(m_timeout.IsTimePast())
return true;
std::shared_ptr<CDVDInputStreamFFmpeg> input = std::dynamic_pointer_cast<CDVDInputStreamFFmpeg>(m_pInput);
if(input && input->Aborted())
return true;
return false;
}
bool CDVDDemuxFFmpeg::Open(std::shared_ptr<CDVDInputStream> pInput, bool streaminfo, bool fileinfo)
{
AVInputFormat* iformat = NULL;
std::string strFile;
m_streaminfo = streaminfo;
m_currentPts = DVD_NOPTS_VALUE;
m_speed = DVD_PLAYSPEED_NORMAL;
m_program = UINT_MAX;
m_seekToKeyFrame = false;
const AVIOInterruptCB int_cb = { interrupt_cb, this };
if (!pInput) return false;
m_pInput = pInput;
strFile = m_pInput->GetFileName();
if( m_pInput->GetContent().length() > 0 )
{
std::string content = m_pInput->GetContent();
StringUtils::ToLower(content);
/* check if we can get a hint from content */
if ( content.compare("video/x-vobsub") == 0 )
iformat = av_find_input_format("mpeg");
else if( content.compare("video/x-dvd-mpeg") == 0 )
iformat = av_find_input_format("mpeg");
else if( content.compare("video/mp2t") == 0 )
iformat = av_find_input_format("mpegts");
else if( content.compare("multipart/x-mixed-replace") == 0 )
iformat = av_find_input_format("mjpeg");
}
// open the demuxer
m_pFormatContext = avformat_alloc_context();
m_pFormatContext->interrupt_callback = int_cb;
// try to abort after 30 seconds
m_timeout.Set(30000);
if (m_pInput->IsStreamType(DVDSTREAM_TYPE_FFMPEG))
{
// special stream type that makes avformat handle file opening
// allows internal ffmpeg protocols to be used
AVDictionary *options = GetFFMpegOptionsFromInput();
CURL url = m_pInput->GetURL();
int result=-1;
if (url.IsProtocol("mms"))
{
// try mmsh, then mmst
url.SetProtocol("mmsh");
url.SetProtocolOptions("");
result = avformat_open_input(&m_pFormatContext, url.Get().c_str(), iformat, &options);
if (result < 0)
{
url.SetProtocol("mmst");
strFile = url.Get();
}
}
if (result < 0 && avformat_open_input(&m_pFormatContext, strFile.c_str(), iformat, &options) < 0 )
{
CLog::Log(LOGDEBUG, "Error, could not open file %s", CURL::GetRedacted(strFile).c_str());
Dispose();
av_dict_free(&options);
return false;
}
av_dict_free(&options);
}
else
{
int bufferSize = 4096;
int blockSize = m_pInput->GetBlockSize();
if (blockSize > 1)
bufferSize = blockSize;
unsigned char* buffer = (unsigned char*)av_malloc(bufferSize);
m_ioContext = avio_alloc_context(buffer, bufferSize, 0, this, dvd_file_read, NULL, dvd_file_seek);
m_ioContext->max_packet_size = bufferSize;
if (m_pInput->Seek(0, SEEK_POSSIBLE) == 0)
{
m_ioContext->seekable = 0;
m_ioContext->max_packet_size = 0;
}
std::string content = m_pInput->GetContent();
StringUtils::ToLower(content);
if (StringUtils::StartsWith(content, "audio/l16"))
iformat = av_find_input_format("s16be");
if (iformat == nullptr)
{
// let ffmpeg decide which demuxer we have to open
bool trySPDIFonly = (m_pInput->GetContent() == "audio/x-spdif-compressed");
if (!trySPDIFonly)
av_probe_input_buffer(m_ioContext, &iformat, strFile.c_str(), NULL, 0, 0);
// Use the more low-level code in case we have been built against an old
// FFmpeg without the above av_probe_input_buffer(), or in case we only
// want to probe for spdif (DTS or IEC 61937) compressed audio
// specifically, or in case the file is a wav which may contain DTS or
// IEC 61937 (e.g. ac3-in-wav) and we want to check for those formats.
if (trySPDIFonly || (iformat && strcmp(iformat->name, "wav") == 0))
{
AVProbeData pd;
int probeBufferSize = 32768;
std::unique_ptr<uint8_t[]> probe_buffer (new uint8_t[probeBufferSize + AVPROBE_PADDING_SIZE]);
// init probe data
pd.buf = probe_buffer.get();
pd.filename = strFile.c_str();
// av_probe_input_buffer might have changed the buffer_size beyond our allocated amount
int buffer_size = std::min(probeBufferSize, m_ioContext->buffer_size);
buffer_size = m_ioContext->max_packet_size ? m_ioContext->max_packet_size : buffer_size;
// read data using avformat's buffers
pd.buf_size = avio_read(m_ioContext, pd.buf, buffer_size);
if (pd.buf_size <= 0)
{
CLog::Log(LOGERROR, "%s - error reading from input stream, %s", __FUNCTION__, CURL::GetRedacted(strFile).c_str());
return false;
}
memset(pd.buf+pd.buf_size, 0, AVPROBE_PADDING_SIZE);
// restore position again
avio_seek(m_ioContext , 0, SEEK_SET);
// the advancedsetting is for allowing the user to force outputting the
// 44.1 kHz DTS wav file as PCM, so that an A/V receiver can decode
// it (this is temporary until we handle 44.1 kHz passthrough properly)
if (trySPDIFonly || (iformat && strcmp(iformat->name, "wav") == 0 && !g_advancedSettings.m_VideoPlayerIgnoreDTSinWAV))
{
// check for spdif and dts
// This is used with wav files and audio CDs that may contain
// a DTS or AC3 track padded for S/PDIF playback. If neither of those
// is present, we assume it is PCM audio.
// AC3 is always wrapped in iec61937 (ffmpeg "spdif"), while DTS
// may be just padded.
AVInputFormat *iformat2;
iformat2 = av_find_input_format("spdif");
if (iformat2 && iformat2->read_probe(&pd) > AVPROBE_SCORE_MAX / 4)
{
iformat = iformat2;
}
else
{
// not spdif or no spdif demuxer, try dts
iformat2 = av_find_input_format("dts");
if (iformat2 && iformat2->read_probe(&pd) > AVPROBE_SCORE_MAX / 4)
{
iformat = iformat2;
}
else if (trySPDIFonly)
{
// not dts either, return false in case we were explicitly
// requested to only check for S/PDIF padded compressed audio
CLog::Log(LOGDEBUG, "%s - not spdif or dts file, falling back", __FUNCTION__);
return false;
}
}
}
}
if(!iformat)
{
std::string content = m_pInput->GetContent();
/* check if we can get a hint from content */
if( content.compare("audio/aacp") == 0 )
iformat = av_find_input_format("aac");
else if( content.compare("audio/aac") == 0 )
iformat = av_find_input_format("aac");
else if( content.compare("video/flv") == 0 )
iformat = av_find_input_format("flv");
else if( content.compare("video/x-flv") == 0 )
iformat = av_find_input_format("flv");
}
if (!iformat)
{
CLog::Log(LOGERROR, "%s - error probing input format, %s", __FUNCTION__, CURL::GetRedacted(strFile).c_str());
return false;
}
else
{
if (iformat->name)
CLog::Log(LOGDEBUG, "%s - probing detected format [%s]", __FUNCTION__, iformat->name);
else
CLog::Log(LOGDEBUG, "%s - probing detected unnamed format", __FUNCTION__);
}
}
m_pFormatContext->pb = m_ioContext;
AVDictionary *options = NULL;
if (iformat->name && (strcmp(iformat->name, "mp3") == 0 || strcmp(iformat->name, "mp2") == 0))
{
CLog::Log(LOGDEBUG, "%s - setting usetoc to 0 for accurate VBR MP3 seek", __FUNCTION__);
av_dict_set(&options, "usetoc", "0", 0);
}
if (StringUtils::StartsWith(content, "audio/l16"))
{
int channels = 2;
int samplerate = 44100;
GetL16Parameters(channels, samplerate);
av_dict_set_int(&options, "channels", channels, 0);
av_dict_set_int(&options, "sample_rate", samplerate, 0);
}
if (avformat_open_input(&m_pFormatContext, strFile.c_str(), iformat, &options) < 0)
{
CLog::Log(LOGERROR, "%s - Error, could not open file %s", __FUNCTION__, CURL::GetRedacted(strFile).c_str());
Dispose();
av_dict_free(&options);
return false;
}
av_dict_free(&options);
}
// Avoid detecting framerate if advancedsettings.xml says so
if (g_advancedSettings.m_videoFpsDetect == 0)
m_pFormatContext->fps_probe_size = 0;
// analyse very short to speed up mjpeg playback start
if (iformat && (strcmp(iformat->name, "mjpeg") == 0) && m_ioContext->seekable == 0)
av_opt_set_int(m_pFormatContext, "analyzeduration", 500000, 0);
bool skipCreateStreams = false;
bool isBluray = pInput->IsStreamType(DVDSTREAM_TYPE_BLURAY);
if (iformat && (strcmp(iformat->name, "mpegts") == 0) && !fileinfo && !isBluray)
{
av_opt_set_int(m_pFormatContext, "analyzeduration", 500000, 0);
m_checkvideo = true;
skipCreateStreams = true;
}
else if (!iformat || (strcmp(iformat->name, "mpegts") != 0))
{
m_streaminfo = true;
}
if (iformat && (strcmp(iformat->name, "mov,mp4,m4a,3gp,3g2,mj2") == 0))
{
if (URIUtils::IsRemote(strFile))
m_pFormatContext->iformat->flags |= AVFMT_NOGENSEARCH;
}
// we need to know if this is matroska, avi or sup later
m_bMatroska = strncmp(m_pFormatContext->iformat->name, "matroska", 8) == 0; // for "matroska.webm"
m_bAVI = strcmp(m_pFormatContext->iformat->name, "avi") == 0;
m_bSup = strcmp(m_pFormatContext->iformat->name, "sup") == 0;
if (m_streaminfo)
{
/* to speed up dvd switches, only analyse very short */
if(m_pInput->IsStreamType(DVDSTREAM_TYPE_DVD))
av_opt_set_int(m_pFormatContext, "analyzeduration", 500000, 0);
CLog::Log(LOGDEBUG, "%s - avformat_find_stream_info starting", __FUNCTION__);
int iErr = avformat_find_stream_info(m_pFormatContext, NULL);
if (iErr < 0)
{
CLog::Log(LOGWARNING,"could not find codec parameters for %s", CURL::GetRedacted(strFile).c_str());
if (m_pInput->IsStreamType(DVDSTREAM_TYPE_DVD) ||
m_pInput->IsStreamType(DVDSTREAM_TYPE_BLURAY) ||
(m_pFormatContext->nb_streams == 1 &&
m_pFormatContext->streams[0]->codecpar->codec_id == AV_CODEC_ID_AC3) ||
m_checkvideo)
{
// special case, our codecs can still handle it.
}
else
{
Dispose();
return false;
}
}
CLog::Log(LOGDEBUG, "%s - av_find_stream_info finished", __FUNCTION__);
if (m_checkvideo)
{
// make sure we start video with an i-frame
ResetVideoStreams();
}
}
else
{
m_program = 0;
m_checkvideo = true;
skipCreateStreams = true;
}
// reset any timeout
m_timeout.SetInfinite();
// if format can be nonblocking, let's use that
m_pFormatContext->flags |= AVFMT_FLAG_NONBLOCK;
// print some extra information
av_dump_format(m_pFormatContext, 0, CURL::GetRedacted(strFile).c_str(), 0);
// deprecated, will be always set in future versions
m_pFormatContext->flags |= AVFMT_FLAG_KEEP_SIDE_DATA;
UpdateCurrentPTS();
// in case of mpegts and we have not seen pat/pmt, defer creation of streams
if (!skipCreateStreams || m_pFormatContext->nb_programs > 0)
{
unsigned int nProgram = UINT_MAX;
if (m_pFormatContext->nb_programs > 0)
{
// select the correct program if requested
CVariant programProp(pInput->GetProperty("program"));
if (!programProp.isNull())
{
int programNumber = static_cast<int>(programProp.asInteger());
for (unsigned int i = 0; i < m_pFormatContext->nb_programs; ++i)
{
if (m_pFormatContext->programs[i]->program_num == programNumber)
{
nProgram = i;
break;
}
}
}
else if (m_pFormatContext->iformat && strcmp(m_pFormatContext->iformat->name, "hls,applehttp") == 0)
{
nProgram = HLSSelectProgram();
}
else
{
// skip programs without or empty audio/video streams
for (unsigned int i = 0; nProgram == UINT_MAX && i < m_pFormatContext->nb_programs; i++)
{
for (unsigned int j = 0; j < m_pFormatContext->programs[i]->nb_stream_indexes; j++)
{
int idx = m_pFormatContext->programs[i]->stream_index[j];
AVStream *st = m_pFormatContext->streams[idx];
if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->codec_info_nb_frames > 0) ||
(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate > 0))
{
nProgram = i;
break;
}
}
}
}
}
CreateStreams(nProgram);
}
// allow IsProgramChange to return true
if (skipCreateStreams && GetNrOfStreams() == 0)
m_program = 0;
m_newProgram = m_program;
m_displayTime = 0;
m_dtsAtDisplayTime = DVD_NOPTS_VALUE;
m_startTime = 0;
// seems to be a bug in ffmpeg, hls jumps back to start after a couple of seconds
// this cures the issue
if (m_pFormatContext->iformat && strcmp(m_pFormatContext->iformat->name, "hls,applehttp") == 0)
{
SeekTime(0);
}
return true;
}
void CDVDDemuxFFmpeg::Dispose()
{
m_pkt.result = -1;
av_packet_unref(&m_pkt.pkt);
if (m_pFormatContext)
{
if (m_ioContext && m_pFormatContext->pb && m_pFormatContext->pb != m_ioContext)
{
CLog::Log(LOGWARNING, "CDVDDemuxFFmpeg::Dispose - demuxer changed our byte context behind our back, possible memleak");
m_ioContext = m_pFormatContext->pb;
}
avformat_close_input(&m_pFormatContext);
}
if(m_ioContext)
{
av_free(m_ioContext->buffer);
av_free(m_ioContext);
}
m_ioContext = NULL;
m_pFormatContext = NULL;
m_speed = DVD_PLAYSPEED_NORMAL;
DisposeStreams();
m_pInput = NULL;
}
bool CDVDDemuxFFmpeg::Reset()
{
std::shared_ptr<CDVDInputStream> pInputStream = m_pInput;
Dispose();
return Open(pInputStream, m_streaminfo);
}
void CDVDDemuxFFmpeg::Flush()
{
if (m_pFormatContext)
{
if (m_pFormatContext->pb)
avio_flush(m_pFormatContext->pb);
avformat_flush(m_pFormatContext);
}
m_currentPts = DVD_NOPTS_VALUE;
m_pkt.result = -1;
av_packet_unref(&m_pkt.pkt);
m_displayTime = 0;
m_dtsAtDisplayTime = DVD_NOPTS_VALUE;
m_seekToKeyFrame = false;
}
void CDVDDemuxFFmpeg::Abort()
{
m_timeout.SetExpired();
}
void CDVDDemuxFFmpeg::SetSpeed(int iSpeed)
{
if(!m_pFormatContext)
return;
if (m_speed == iSpeed)
return;
if(m_speed != DVD_PLAYSPEED_PAUSE && iSpeed == DVD_PLAYSPEED_PAUSE)
{
m_pInput->Pause(m_currentPts);
av_read_pause(m_pFormatContext);
}
else if(m_speed == DVD_PLAYSPEED_PAUSE && iSpeed != DVD_PLAYSPEED_PAUSE)
{
m_pInput->Pause(m_currentPts);
av_read_play(m_pFormatContext);
}
m_speed = iSpeed;
AVDiscard discard = AVDISCARD_NONE;
if(m_speed > 4*DVD_PLAYSPEED_NORMAL)
discard = AVDISCARD_NONKEY;
else if(m_speed > 2*DVD_PLAYSPEED_NORMAL)
discard = AVDISCARD_BIDIR;
else if(m_speed < DVD_PLAYSPEED_PAUSE)
discard = AVDISCARD_NONKEY;
for(unsigned int i = 0; i < m_pFormatContext->nb_streams; i++)
{
if(m_pFormatContext->streams[i])
{
if(m_pFormatContext->streams[i]->discard != AVDISCARD_ALL)
m_pFormatContext->streams[i]->discard = discard;
}
}
}
AVDictionary *CDVDDemuxFFmpeg::GetFFMpegOptionsFromInput()
{
const std::shared_ptr<CDVDInputStreamFFmpeg> input =
std::dynamic_pointer_cast<CDVDInputStreamFFmpeg>(m_pInput);
CURL url = m_pInput->GetURL();
AVDictionary *options = nullptr;
if (url.IsProtocol("http") || url.IsProtocol("https"))
{
std::map<std::string, std::string> protocolOptions;
url.GetProtocolOptions(protocolOptions);
std::string headers;
bool hasUserAgent = false;
bool hasCookies = false;
for(std::map<std::string, std::string>::const_iterator it = protocolOptions.begin(); it != protocolOptions.end(); ++it)
{
std::string name = it->first;
StringUtils::ToLower(name);
const std::string &value = it->second;
if (name == "seekable")
av_dict_set(&options, "seekable", value.c_str(), 0);
// map some standard http headers to the ffmpeg related options
else if (name == "user-agent")
{
av_dict_set(&options, "user_agent", value.c_str(), 0);
CLog::Log(LOGDEBUG, "CDVDDemuxFFmpeg::GetFFMpegOptionsFromInput() adding ffmpeg option 'user_agent: %s'", value.c_str());
hasUserAgent = true;
}
else if (name == "cookies")
{
// in the plural option expect multiple Set-Cookie values. They are passed \n delimited to FFMPEG
av_dict_set(&options, "cookies", value.c_str(), 0);
CLog::Log(LOGDEBUG, "CDVDDemuxFFmpeg::GetFFMpegOptionsFromInput() adding ffmpeg option 'cookies: %s'", value.c_str());
hasCookies = true;
}
else if (name == "cookie")
{
CLog::Log(LOGDEBUG, "CDVDDemuxFFmpeg::GetFFMpegOptionsFromInput() adding ffmpeg header value 'cookie: %s'", value.c_str());
headers.append(it->first).append(": ").append(value).append("\r\n");
hasCookies = true;
}
// other standard headers (see https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) are appended as actual headers
else if (name == "accept" || name == "accept-language" || name == "accept-datetime" ||
name == "authorization" || name == "cache-control" || name == "connection" || name == "content-md5" ||
name == "date" || name == "expect" || name == "forwarded" || name == "from" || name == "if-match" ||
name == "if-modified-since" || name == "if-none-match" || name == "if-range" || name == "if-unmodified-since" ||
name == "max-forwards" || name == "origin" || name == "pragma" || name == "range" || name == "referer" ||
name == "te" || name == "upgrade" || name == "via" || name == "warning" || name == "x-requested-with" ||
name == "dnt" || name == "x-forwarded-for" || name == "x-forwarded-host" || name == "x-forwarded-proto" ||
name == "front-end-https" || name == "x-http-method-override" || name == "x-att-deviceid" ||
name == "x-wap-profile" || name == "x-uidh" || name == "x-csrf-token" || name == "x-request-id" ||
name == "x-correlation-id")
{
if (name == "authorization")
{
CLog::Log(LOGDEBUG, "CDVDDemuxFFmpeg::GetFFMpegOptionsFromInput() adding custom header option '%s: ***********'", it->first.c_str());
}
else
{
CLog::Log(LOGDEBUG, "CDVDDemuxFFmpeg::GetFFMpegOptionsFromInput() adding custom header option '%s: %s'", it->first.c_str(), value.c_str());
}
headers.append(it->first).append(": ").append(value).append("\r\n");
}
// we don't add blindly all options to headers anymore
// if anybody wants to pass options to ffmpeg, explicitly prefix those
// to be identified here
else
{
CLog::Log(LOGDEBUG, "CDVDDemuxFFmpeg::GetFFMpegOptionsFromInput() ignoring header option '%s: %s'", it->first.c_str(), value.c_str());
}
}
if (!hasUserAgent)
{
// set default xbmc user-agent.
av_dict_set(&options, "user_agent", g_advancedSettings.m_userAgent.c_str(), 0);
}
if (!headers.empty())
av_dict_set(&options, "headers", headers.c_str(), 0);
if (!hasCookies)
{
std::string cookies;
if (XFILE::CCurlFile::GetCookies(url, cookies))
av_dict_set(&options, "cookies", cookies.c_str(), 0);
}
}
if (input)
{
const std::string host = input->GetProxyHost();
if (!host.empty() && input->GetProxyType() == "http")
{
std::ostringstream urlStream;
const uint16_t port = input->GetProxyPort();
const std::string user = input->GetProxyUser();
const std::string password = input->GetProxyPassword();
urlStream << "http://";
if (!user.empty()) {
urlStream << user;
if (!password.empty())
urlStream << ":" << password;
urlStream << "@";
}
urlStream << host << ':' << port;
av_dict_set(&options, "http_proxy", urlStream.str().c_str(), 0);
}
// rtmp options
if (url.IsProtocol("rtmp") || url.IsProtocol("rtmpt") ||
url.IsProtocol("rtmpe") || url.IsProtocol("rtmpte") ||
url.IsProtocol("rtmps"))
{
static const std::map<std::string,std::string> optionmap =
{{{"SWFPlayer", "rtmp_swfurl"},
{"swfplayer", "rtmp_swfurl"},
{"PageURL", "rtmp_pageurl"},
{"pageurl", "rtmp_pageurl"},
{"PlayPath", "rtmp_playpath"},
{"playpath", "rtmp_playpath"},
{"TcUrl", "rtmp_tcurl"},
{"tcurl", "rtmp_tcurl"},
{"IsLive", "rtmp_live"},
{"islive", "rtmp_live"},
{"swfurl", "rtmp_swfurl"},
{"swfvfy", "rtmp_swfverify"},
}};
for (const auto& it : optionmap)
{
if (input->GetItem().HasProperty(it.first))
{
av_dict_set(&options, it.second.c_str(),
input->GetItem().GetProperty(it.first).asString().c_str(),0);
}
}
CURL tmpUrl = url;
std::vector<std::string> opts = StringUtils::Split(tmpUrl.Get(), " ");
if (opts.size() > 1) // inline rtmp options
{
std::string swfurl;
bool swfvfy=false;
for (size_t i = 1; i < opts.size(); ++i)
{
std::vector<std::string> value = StringUtils::Split(opts[i], "=", 2);
StringUtils::ToLower(value[0]);
auto it = optionmap.find(value[0]);
if (it != optionmap.end())
{
if (value[0] == "swfurl" || value[0] == "SWFPlayer")
swfurl = value[1];
if (value[0] == "swfvfy" && (value[1] == "true" || value[1] == "1"))
swfvfy = true;
else
av_dict_set(&options, it->second.c_str(), value[1].c_str(), 0);
}
if (swfvfy)
av_dict_set(&options, "rtmp_swfverify", swfurl.c_str(), 0);
}
tmpUrl = CURL(opts.front());
}
}
}
return options;
}
double CDVDDemuxFFmpeg::ConvertTimestamp(int64_t pts, int den, int num)
{
if (pts == (int64_t)AV_NOPTS_VALUE)
return DVD_NOPTS_VALUE;
// do calculations in floats as they can easily overflow otherwise
// we don't care for having a completely exact timestamp anyway
double timestamp = (double)pts * num / den;
double starttime = 0.0f;
std::shared_ptr<CDVDInputStream::IMenus> menu = std::dynamic_pointer_cast<CDVDInputStream::IMenus>(m_pInput);
if (!menu && m_pFormatContext->start_time != (int64_t)AV_NOPTS_VALUE)
starttime = (double)m_pFormatContext->start_time / AV_TIME_BASE;
if (!m_streaminfo)
starttime = m_startTime;
if (!m_bSup)
{
if (timestamp > starttime || !m_streaminfo)
timestamp -= starttime;
// allow for largest possible difference in pts and dts for a single packet
else if (timestamp + 0.5f > starttime)
timestamp = 0;
}
return timestamp*DVD_TIME_BASE;
}
DemuxPacket* CDVDDemuxFFmpeg::Read()
{
DemuxPacket* pPacket = NULL;
// on some cases where the received packet is invalid we will need to return an empty packet (0 length) otherwise the main loop (in CVideoPlayer)
// would consider this the end of stream and stop.
bool bReturnEmpty = false;
{ CSingleLock lock(m_critSection); // open lock scope
if (m_pFormatContext)
{
// assume we are not eof
if(m_pFormatContext->pb)
m_pFormatContext->pb->eof_reached = 0;
// check for saved packet after a program change
if (m_pkt.result < 0)
{
// keep track if ffmpeg doesn't always set these
m_pkt.pkt.size = 0;
m_pkt.pkt.data = NULL;
// timeout reads after 100ms
m_timeout.Set(20000);
m_pkt.result = av_read_frame(m_pFormatContext, &m_pkt.pkt);
m_timeout.SetInfinite();
}
if (m_pkt.result == AVERROR(EINTR) || m_pkt.result == AVERROR(EAGAIN))
{
// timeout, probably no real error, return empty packet
bReturnEmpty = true;
}
else if (m_pkt.result == AVERROR_EOF)
{
}
else if (m_pkt.result < 0)
{
Flush();
}
// check size and stream index for being in a valid range
else if (m_pkt.pkt.size < 0 ||
m_pkt.pkt.stream_index < 0 ||
m_pkt.pkt.stream_index >= (int)m_pFormatContext->nb_streams)
{
// XXX, in some cases ffmpeg returns a negative packet size
if(m_pFormatContext->pb && !m_pFormatContext->pb->eof_reached)
{
CLog::Log(LOGERROR, "CDVDDemuxFFmpeg::Read() no valid packet");
bReturnEmpty = true;
Flush();
}
else
CLog::Log(LOGERROR, "CDVDDemuxFFmpeg::Read() returned invalid packet and eof reached");
m_pkt.result = -1;
av_packet_unref(&m_pkt.pkt);
}
else
{
ParsePacket(&m_pkt.pkt);
if (IsProgramChange())
{
// update streams
CreateStreams(m_program);
pPacket = CDVDDemuxUtils::AllocateDemuxPacket(0);
pPacket->iStreamId = DMX_SPECIALID_STREAMCHANGE;
pPacket->demuxerId = m_demuxerId;
return pPacket;
}
AVStream *stream = m_pFormatContext->streams[m_pkt.pkt.stream_index];
if (IsVideoReady())
{
if (m_program != UINT_MAX)
{
/* check so packet belongs to selected program */
for (unsigned int i = 0; i < m_pFormatContext->programs[m_program]->nb_stream_indexes; i++)
{
if(m_pkt.pkt.stream_index == (int)m_pFormatContext->programs[m_program]->stream_index[i])
{
pPacket = CDVDDemuxUtils::AllocateDemuxPacket(m_pkt.pkt.size);
break;
}
}
if (!pPacket)
bReturnEmpty = true;
}
else
pPacket = CDVDDemuxUtils::AllocateDemuxPacket(m_pkt.pkt.size);
}
else
bReturnEmpty = true;
if (pPacket)
{
if (m_bAVI && stream->codecpar && stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
{
// AVI's always have borked pts, specially if m_pFormatContext->flags includes
// AVFMT_FLAG_GENPTS so always use dts
m_pkt.pkt.pts = AV_NOPTS_VALUE;
}
// copy contents into our own packet
pPacket->iSize = m_pkt.pkt.size;
// maybe we can avoid a memcpy here by detecting where pkt.destruct is pointing too?
if (m_pkt.pkt.data)
memcpy(pPacket->pData, m_pkt.pkt.data, pPacket->iSize);
pPacket->pts = ConvertTimestamp(m_pkt.pkt.pts, stream->time_base.den, stream->time_base.num);
pPacket->dts = ConvertTimestamp(m_pkt.pkt.dts, stream->time_base.den, stream->time_base.num);
pPacket->duration = DVD_SEC_TO_TIME((double)m_pkt.pkt.duration * stream->time_base.num / stream->time_base.den);
CDVDDemuxUtils::StoreSideData(pPacket, &m_pkt.pkt);