forked from xbmc/xbmc
/
DVDDemuxFFmpeg.cpp
1650 lines (1430 loc) · 49.5 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-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "system.h"
#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
#include "DVDDemuxFFmpeg.h"
#include "DVDInputStreams/DVDInputStream.h"
#include "DVDInputStreams/DVDInputStreamNavigator.h"
#ifdef HAVE_LIBBLURAY
#include "DVDInputStreams/DVDInputStreamBluray.h"
#endif
#include "DVDInputStreams/DVDInputStreamPVRManager.h"
#include "DVDInputStreams/DVDInputStreamFFmpeg.h"
#include "DVDDemuxUtils.h"
#include "DVDClock.h" // for DVD_TIME_BASE
#include "commons/Exception.h"
#include "settings/AdvancedSettings.h"
#include "settings/Settings.h"
#include "filesystem/File.h"
#include "filesystem/CurlFile.h"
#include "filesystem/Directory.h"
#include "utils/log.h"
#include "threads/Thread.h"
#include "threads/SystemClock.h"
#include "utils/TimeUtils.h"
#include "utils/StringUtils.h"
#include "URL.h"
#include "cores/FFmpeg.h"
extern "C" {
#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) - FF_INPUT_BUFFER_PADDING_SIZE)
void CDemuxStreamAudioFFmpeg::GetStreamInfo(std::string& strInfo)
{
if(!m_stream) return;
char temp[128];
avcodec_string(temp, 128, m_stream->codec, 0);
strInfo = temp;
}
void CDemuxStreamAudioFFmpeg::GetStreamName(std::string& strInfo)
{
if(!m_stream) return;
if(!m_description.empty())
strInfo = m_description;
else
CDemuxStream::GetStreamName(strInfo);
}
void CDemuxStreamSubtitleFFmpeg::GetStreamName(std::string& strInfo)
{
if(!m_stream) return;
if(!m_description.empty())
strInfo = m_description;
else
CDemuxStream::GetStreamName(strInfo);
}
void CDemuxStreamVideoFFmpeg::GetStreamInfo(std::string& strInfo)
{
if(!m_stream) return;
char temp[128];
avcodec_string(temp, 128, m_stream->codec, 0);
strInfo = temp;
}
void CDemuxStreamSubtitleFFmpeg::GetStreamInfo(std::string& strInfo)
{
if(!m_stream) return;
char temp[128];
avcodec_string(temp, 128, m_stream->codec, 0);
strInfo = temp;
}
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;
CDVDInputStream* pInputStream = static_cast<CDVDDemuxFFmpeg*>(h)->m_pInput;
return pInputStream->Read(buf, size);
}
/*
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;
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_iCurrentPts = DVD_NOPTS_VALUE;
m_bMatroska = false;
m_bAVI = 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;
}
CDVDDemuxFFmpeg::~CDVDDemuxFFmpeg()
{
Dispose();
ff_flush_avutil_log_buffers();
}
bool CDVDDemuxFFmpeg::Aborted()
{
if(m_timeout.IsTimePast())
return true;
CDVDInputStreamFFmpeg * input = dynamic_cast<CDVDInputStreamFFmpeg*>(m_pInput);
if(input && input->Aborted())
return true;
return false;
}
bool CDVDDemuxFFmpeg::Open(CDVDInputStream* pInput, bool streaminfo)
{
AVInputFormat* iformat = NULL;
std::string strFile;
m_streaminfo = streaminfo;
m_iCurrentPts = DVD_NOPTS_VALUE;
m_speed = DVD_PLAYSPEED_NORMAL;
m_program = UINT_MAX;
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();
/* 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/x-mpegts") == 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
CURL url = m_pInput->GetURL();
AVDictionary *options = GetFFMpegOptionsFromURL(url);
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
{
unsigned char* buffer = (unsigned char*)av_malloc(FFMPEG_FILE_BUFFER_SIZE);
m_ioContext = avio_alloc_context(buffer, FFMPEG_FILE_BUFFER_SIZE, 0, this, dvd_file_read, NULL, dvd_file_seek);
m_ioContext->max_packet_size = m_pInput->GetBlockSize();
if(m_ioContext->max_packet_size)
m_ioContext->max_packet_size *= FFMPEG_FILE_BUFFER_SIZE / m_ioContext->max_packet_size;
if(m_pInput->Seek(0, SEEK_POSSIBLE) == 0)
m_ioContext->seekable = 0;
if( iformat == NULL )
{
// 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;
uint8_t probe_buffer[FFMPEG_FILE_BUFFER_SIZE + AVPROBE_PADDING_SIZE];
// init probe data
pd.buf = probe_buffer;
pd.filename = strFile.c_str();
// read data using avformat's buffers
pd.buf_size = avio_read(m_ioContext, pd.buf, m_ioContext->max_packet_size ? m_ioContext->max_packet_size : m_ioContext->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_dvdplayerIgnoreDTSinWAV))
{
// 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 explicitely
// requested to only check for S/PDIF padded compressed audio
CLog::Log(LOGDEBUG, "%s - not spdif or dts file, fallbacking", __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(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 (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);
if (iformat && (strcmp(iformat->name, "mpegts") == 0))
{
av_opt_set_int(m_pFormatContext, "analyzeduration", 500000, 0);
m_checkvideo = true;
}
// we need to know if this is matroska or avi later
m_bMatroska = strncmp(m_pFormatContext->iformat->name, "matroska", 8) == 0; // for "matroska.webm"
m_bAVI = strcmp(m_pFormatContext->iformat->name, "avi") == 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]->codec->codec_id == AV_CODEC_ID_AC3))
{
// 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;
}
// 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, strFile.c_str(), 0);
UpdateCurrentPTS();
// in case of mpegts and we have not seen pat/pmt, defer creation of streams
if (!m_checkvideo || m_pFormatContext->nb_programs > 0)
CreateStreams();
// allow IsProgramChange to return true
if (m_checkvideo && GetNrOfStreams() == 0)
m_program = 0;
return true;
}
void CDVDDemuxFFmpeg::Dispose()
{
m_pkt.result = -1;
av_free_packet(&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;
}
void CDVDDemuxFFmpeg::Reset()
{
CDVDInputStream* pInputStream = m_pInput;
Dispose();
Open(pInputStream, m_streaminfo);
}
void CDVDDemuxFFmpeg::Flush()
{
// naughty usage of an internal ffmpeg function
if (m_pFormatContext)
av_read_frame_flush(m_pFormatContext);
m_iCurrentPts = DVD_NOPTS_VALUE;
m_pkt.result = -1;
av_free_packet(&m_pkt.pkt);
}
void CDVDDemuxFFmpeg::Abort()
{
m_timeout.SetExpired();
}
void CDVDDemuxFFmpeg::SetSpeed(int iSpeed)
{
if(!m_pFormatContext)
return;
if(m_speed != DVD_PLAYSPEED_PAUSE && iSpeed == DVD_PLAYSPEED_PAUSE)
{
m_pInput->Pause((double)m_iCurrentPts);
av_read_pause(m_pFormatContext);
}
else if(m_speed == DVD_PLAYSPEED_PAUSE && iSpeed != DVD_PLAYSPEED_PAUSE)
{
m_pInput->Pause((double)m_iCurrentPts);
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::GetFFMpegOptionsFromURL(const CURL &url)
{
AVDictionary *options = NULL;
if (url.IsProtocol("http") || url.IsProtocol("https"))
{
std::map<std::string, std::string> protocolOptions;
url.GetProtocolOptions(protocolOptions);
std::string headers;
bool hasUserAgent = 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);
else if (name == "user-agent")
{
av_dict_set(&options, "user-agent", value.c_str(), 0);
hasUserAgent = true;
}
else if (name != "auth" && name != "encoding")
// all other protocol options can be added as http header.
headers.append(it->first).append(": ").append(value).append("\r\n");
}
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);
std::string cookies;
if (XFILE::CCurlFile::GetCookies(url, cookies))
av_dict_set(&options, "cookies", cookies.c_str(), 0);
}
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 completly exact timestamp anyway
double timestamp = (double)pts * num / den;
double starttime = 0.0f;
// for dvd's we need the original time
if(dynamic_cast<CDVDInputStream::IMenus*>(m_pInput))
starttime = dynamic_cast<CDVDInputStream::IMenus*>(m_pInput)->GetTimeStampCorrection() / DVD_TIME_BASE;
else if (m_pFormatContext->start_time != (int64_t)AV_NOPTS_VALUE)
starttime = (double)m_pFormatContext->start_time / AV_TIME_BASE;
if(timestamp > starttime)
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 CDVDPlayer)
// 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 < 0)
{
Flush();
}
else if (IsProgramChange())
{
// update streams
CreateStreams(m_program);
pPacket = CDVDDemuxUtils::AllocateDemuxPacket(0);
pPacket->iStreamId = DMX_SPECIALID_STREAMCHANGE;
return pPacket;
}
// 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_free_packet(&m_pkt.pkt);
}
else
{
ParsePacket(&m_pkt.pkt);
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)
{
// lavf sometimes bugs out and gives 0 dts/pts instead of no dts/pts
// since this could only happens on initial frame under normal
// circomstances, let's assume it is wrong all the time
if(m_pkt.pkt.dts == 0)
m_pkt.pkt.dts = AV_NOPTS_VALUE;
if(m_pkt.pkt.pts == 0)
m_pkt.pkt.pts = AV_NOPTS_VALUE;
if(m_bMatroska && stream->codec && stream->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{ // matroska can store different timestamps
// for different formats, for native stored
// stuff it is pts, but for ms compatibility
// tracks, it is really dts. sadly ffmpeg
// sets these two timestamps equal all the
// time, so we select it here instead
if(stream->codec->codec_tag == 0)
m_pkt.pkt.dts = AV_NOPTS_VALUE;
else
m_pkt.pkt.pts = AV_NOPTS_VALUE;
}
// we need to get duration slightly different for matroska embedded text subtitels
if(m_bMatroska && stream->codec && stream->codec->codec_id == AV_CODEC_ID_TEXT && m_pkt.pkt.convergence_duration != 0)
m_pkt.pkt.duration = m_pkt.pkt.convergence_duration;
if(m_bAVI && stream->codec && stream->codec->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);
// used to guess streamlength
if (pPacket->dts != DVD_NOPTS_VALUE && (pPacket->dts > m_iCurrentPts || m_iCurrentPts == DVD_NOPTS_VALUE))
m_iCurrentPts = pPacket->dts;
// check if stream has passed full duration, needed for live streams
bool bAllowDurationExt = (stream->codec && (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO || stream->codec->codec_type == AVMEDIA_TYPE_AUDIO));
if(bAllowDurationExt && m_pkt.pkt.dts != (int64_t)AV_NOPTS_VALUE)
{
int64_t duration;
duration = m_pkt.pkt.dts;
if(stream->start_time != (int64_t)AV_NOPTS_VALUE)
duration -= stream->start_time;
if(duration > stream->duration)
{
stream->duration = duration;
duration = av_rescale_rnd(stream->duration, (int64_t)stream->time_base.num * AV_TIME_BASE, stream->time_base.den, AV_ROUND_NEAR_INF);
if ((m_pFormatContext->duration == (int64_t)AV_NOPTS_VALUE)
|| (m_pFormatContext->duration != (int64_t)AV_NOPTS_VALUE && duration > m_pFormatContext->duration))
m_pFormatContext->duration = duration;
}
}
// store internal id until we know the continuous id presented to player
// the stream might not have been created yet
pPacket->iStreamId = m_pkt.pkt.stream_index;
}
m_pkt.result = -1;
av_free_packet(&m_pkt.pkt);
}
}
} // end of lock scope
if (bReturnEmpty && !pPacket)
pPacket = CDVDDemuxUtils::AllocateDemuxPacket(0);
if (!pPacket) return NULL;
// check streams, can we make this a bit more simple?
if (pPacket && pPacket->iStreamId >= 0)
{
CDemuxStream *stream = GetStreamInternal(pPacket->iStreamId);
if (!stream ||
stream->pPrivate != m_pFormatContext->streams[pPacket->iStreamId] ||
stream->codec != m_pFormatContext->streams[pPacket->iStreamId]->codec->codec_id)
{
// content has changed, or stream did not yet exist
stream = AddStream(pPacket->iStreamId);
}
// we already check for a valid m_streams[pPacket->iStreamId] above
else if (stream->type == STREAM_AUDIO)
{
if (((CDemuxStreamAudio*)stream)->iChannels != m_pFormatContext->streams[pPacket->iStreamId]->codec->channels ||
((CDemuxStreamAudio*)stream)->iSampleRate != m_pFormatContext->streams[pPacket->iStreamId]->codec->sample_rate)
{
// content has changed
stream = AddStream(pPacket->iStreamId);
}
}
else if (stream->type == STREAM_VIDEO)
{
if (((CDemuxStreamVideo*)stream)->iWidth != m_pFormatContext->streams[pPacket->iStreamId]->codec->width ||
((CDemuxStreamVideo*)stream)->iHeight != m_pFormatContext->streams[pPacket->iStreamId]->codec->height)
{
// content has changed
stream = AddStream(pPacket->iStreamId);
}
}
if (!stream)
{
CLog::Log(LOGERROR, "CDVDDemuxFFmpeg::AddStream - internal error, stream is null");
CDVDDemuxUtils::FreeDemuxPacket(pPacket);
return NULL;
}
// set continuous stream id for player
pPacket->iStreamId = stream->iId;
}
return pPacket;
}
bool CDVDDemuxFFmpeg::SeekTime(int time, bool backwords, double *startpts)
{
if(time < 0)
time = 0;
m_pkt.result = -1;
av_free_packet(&m_pkt.pkt);
CDVDInputStream::ISeekTime* ist = dynamic_cast<CDVDInputStream::ISeekTime*>(m_pInput);
if (ist)
{
if (!ist->SeekTime(time))
return false;
if(startpts)
*startpts = DVD_NOPTS_VALUE;
Flush();
// also empty the internal ffmpeg buffer
m_ioContext->buf_ptr = m_ioContext->buf_end;
return true;
}
if(!m_pInput->Seek(0, SEEK_POSSIBLE)
&& !m_pInput->IsStreamType(DVDSTREAM_TYPE_FFMPEG))
{
CLog::Log(LOGDEBUG, "%s - input stream reports it is not seekable", __FUNCTION__);
return false;
}
int64_t seek_pts = (int64_t)time * (AV_TIME_BASE / 1000);
if (m_pFormatContext->start_time != (int64_t)AV_NOPTS_VALUE)
seek_pts += m_pFormatContext->start_time;
int ret;
{
CSingleLock lock(m_critSection);
ret = av_seek_frame(m_pFormatContext, -1, seek_pts, backwords ? AVSEEK_FLAG_BACKWARD : 0);
if(ret >= 0)
UpdateCurrentPTS();
}
if(m_iCurrentPts == DVD_NOPTS_VALUE)
CLog::Log(LOGDEBUG, "%s - unknown position after seek", __FUNCTION__);
else
CLog::Log(LOGDEBUG, "%s - seek ended up on time %d", __FUNCTION__, (int)(m_iCurrentPts / DVD_TIME_BASE * 1000));
// in this case the start time is requested time
if(startpts)
*startpts = DVD_MSEC_TO_TIME(time);
// demuxer will return failure, if you seek to eof
if (m_pInput->IsEOF() && ret <= 0)
return true;
return (ret >= 0);
}
bool CDVDDemuxFFmpeg::SeekByte(int64_t pos)
{
CSingleLock lock(m_critSection);
int ret = av_seek_frame(m_pFormatContext, -1, pos, AVSEEK_FLAG_BYTE);
if(ret >= 0)
UpdateCurrentPTS();
m_pkt.result = -1;
av_free_packet(&m_pkt.pkt);
return (ret >= 0);
}
void CDVDDemuxFFmpeg::UpdateCurrentPTS()
{
m_iCurrentPts = DVD_NOPTS_VALUE;
for(unsigned int i = 0; i < m_pFormatContext->nb_streams; i++)
{
AVStream *stream = m_pFormatContext->streams[i];
if(stream && stream->cur_dts != (int64_t)AV_NOPTS_VALUE)
{
double ts = ConvertTimestamp(stream->cur_dts, stream->time_base.den, stream->time_base.num);
if(m_iCurrentPts == DVD_NOPTS_VALUE || m_iCurrentPts > ts )
m_iCurrentPts = ts;
}
}
}
int CDVDDemuxFFmpeg::GetStreamLength()
{
if (!m_pFormatContext)
return 0;
if (m_pFormatContext->duration < 0)
return 0;
return (int)(m_pFormatContext->duration / (AV_TIME_BASE / 1000));
}
/**
* @brief Finds stream based on demuxer index
*/
CDemuxStream* CDVDDemuxFFmpeg::GetStream(int iStreamId)
{
if(iStreamId >= 0 && (size_t)iStreamId < m_stream_index.size())
return m_stream_index[iStreamId]->second;
else
return NULL;
}
/**
* @brief Finds stream based on ffmpeg index
*/
CDemuxStream* CDVDDemuxFFmpeg::GetStreamInternal(int iId)
{
std::map<int, CDemuxStream*>::iterator it = m_streams.find(iId);
if (it == m_streams.end())
return NULL;
else
return it->second;
}
int CDVDDemuxFFmpeg::GetNrOfStreams()
{
return m_stream_index.size();
}
static double SelectAspect(AVStream* st, bool* forced)
{
*forced = false;
/* if stream aspect is 1:1 or 0:0 use codec aspect */
if((st->sample_aspect_ratio.den == 1 || st->sample_aspect_ratio.den == 0)
&& (st->sample_aspect_ratio.num == 1 || st->sample_aspect_ratio.num == 0)
&& st->codec->sample_aspect_ratio.num != 0)
return av_q2d(st->codec->sample_aspect_ratio);
*forced = true;
if(st->sample_aspect_ratio.num != 0)
return av_q2d(st->sample_aspect_ratio);
return 0.0;
}
void CDVDDemuxFFmpeg::CreateStreams(unsigned int program)
{