-
-
Notifications
You must be signed in to change notification settings - Fork 840
Expand file tree
/
Copy pathLAVFDemuxer.cpp
More file actions
3202 lines (2785 loc) · 107 KB
/
Copy pathLAVFDemuxer.cpp
File metadata and controls
3202 lines (2785 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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 of the License, 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 this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "stdafx.h"
#include "LAVFDemuxer.h"
#include "LAVFUtils.h"
#include "LAVFStreamInfo.h"
#include "ILAVPinInfo.h"
#include "LAVFVideoHelper.h"
#include "ExtradataParser.h"
#include "IMediaSideDataFFmpeg.h"
#include "LAVSplitterSettingsInternal.h"
#include "moreuuids.h"
extern "C"
{
typedef struct CodecMime
{
char str[32];
enum AVCodecID id;
} CodecMime;
#include "libavformat/mpegts.h"
#include "libavformat/matroska.h"
#include "libavutil/avstring.h"
enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags);
#include "libavformat/isom.h"
AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end,
const char *title);
}
#ifdef DEBUG
#include "lavf_log.h"
#endif
#include "BDDemuxer.h"
#include "CueSheet.h"
#define AVFORMAT_OPEN_TIMEOUT 20
extern void lavf_get_iformat_infos(const AVInputFormat *pFormat, const char **pszName, const char **pszDescription);
static const AVRational AV_RATIONAL_TIMEBASE = {1, AV_TIME_BASE};
std::set<FormatInfo> CLAVFDemuxer::GetFormatList()
{
std::set<FormatInfo> formats;
const AVInputFormat *f = nullptr;
void *state = NULL;
while (f = av_demuxer_iterate(&state))
{
FormatInfo format;
lavf_get_iformat_infos(f, &format.strName, &format.strDescription);
if (format.strName)
formats.insert(format);
}
return formats;
}
CLAVFDemuxer::CLAVFDemuxer(CCritSec *pLock, ILAVFSettingsInternal *settings)
: CBaseDemuxer(L"lavf demuxer", pLock)
{
#ifdef DEBUG
DbgSetModuleLevel(LOG_CUSTOM1, DWORD_MAX); // FFMPEG messages use custom1
av_log_set_callback(lavf_log_callback);
#else
av_log_set_callback(nullptr);
#endif
m_bSubStreams = settings->GetSubstreamsEnabled();
m_pSettings = settings;
WCHAR fileName[1024];
GetModuleFileName(nullptr, fileName, 1024);
const WCHAR *file = PathFindFileName(fileName);
if (_wcsicmp(file, L"zplayer.exe") == 0)
{
m_bEnableTrackInfo = FALSE;
// TrackInfo is only properly handled in ZoomPlayer 8.0.0.74 and above
DWORD dwVersionSize = GetFileVersionInfoSize(fileName, nullptr);
if (dwVersionSize > 0)
{
void *versionInfo = CoTaskMemAlloc(dwVersionSize);
if (!versionInfo)
return;
GetFileVersionInfo(fileName, 0, dwVersionSize, versionInfo);
VS_FIXEDFILEINFO *info;
unsigned cbInfo;
BOOL bInfoPresent = VerQueryValue(versionInfo, TEXT("\\"), (LPVOID *)&info, &cbInfo);
if (bInfoPresent)
{
bInfoPresent = bInfoPresent;
uint64_t version = info->dwFileVersionMS;
version <<= 32;
version += info->dwFileVersionLS;
if (version >= 0x000800000000004A)
m_bEnableTrackInfo = TRUE;
}
CoTaskMemFree(versionInfo);
}
}
}
CLAVFDemuxer::~CLAVFDemuxer()
{
CleanupAVFormat();
SAFE_DELETE(m_pFontInstaller);
}
STDMETHODIMP CLAVFDemuxer::NonDelegatingQueryInterface(REFIID riid, void **ppv)
{
CheckPointer(ppv, E_POINTER);
*ppv = nullptr;
return QI(IKeyFrameInfo) m_bEnableTrackInfo &&
QI(ITrackInfo) QI2(IAMExtendedSeeking) QI2(IAMMediaContent) QI(IPropertyBag)
QI(IDSMResourceBag) __super::NonDelegatingQueryInterface(riid, ppv);
}
/////////////////////////////////////////////////////////////////////////////
// Demuxer Functions
STDMETHODIMP CLAVFDemuxer::Open(LPCOLESTR pszFileName)
{
return OpenInputStream(nullptr, pszFileName, nullptr, TRUE);
}
STDMETHODIMP CLAVFDemuxer::Start()
{
if (m_bH264MVCCombine)
{
CMediaType *pmt = m_pSettings->GetOutputMediatype(m_nH264MVCBaseStream);
if (pmt)
{
if (pmt->subtype != MEDIASUBTYPE_AMVC && pmt->subtype != MEDIASUBTYPE_MVC1)
{
DbgLog(
(LOG_TRACE, 10,
L"CLAVFDemuxer::Start(): Disabling MVC demuxing, downstream did not select an appropriate type"));
m_bH264MVCCombine = FALSE;
m_nH264MVCBaseStream = -1;
m_nH264MVCExtensionStream = -1;
}
}
}
if (m_avFormat)
av_read_play(m_avFormat);
return S_OK;
}
STDMETHODIMP CLAVFDemuxer::AbortOpening(int mode, int timeout)
{
m_Abort = mode;
m_timeAbort = timeout ? time(nullptr) + timeout : 0;
return S_OK;
}
int CLAVFDemuxer::avio_interrupt_cb(void *opaque)
{
CLAVFDemuxer *demux = (CLAVFDemuxer *)opaque;
// Check for file opening timeout
time_t now = time(nullptr);
if (demux->m_timeOpening && now > (demux->m_timeOpening + AVFORMAT_OPEN_TIMEOUT))
return 1;
if (demux->m_Abort && now > demux->m_timeAbort)
return 1;
return 0;
}
static LPCWSTR wszImageExtensions[] = {
L".png", L".mng", L".pns", // PNG
L".tif", L".tiff", // TIFF
L".jpeg", L".jpg", L".jps", // JPEG
L".tga", // TGA
L".bmp", // BMP
L".j2c", // JPEG2000
};
static LPCWSTR wszBlockedExtensions[] = {L".ifo", L".bup"};
static std::pair<const char *, const char *> rtmpParametersTranslate[] = {
std::make_pair("app", "rtmp_app"),
std::make_pair("buffer", "rtmp_buffer"),
std::make_pair("conn", "rtmp_conn"),
std::make_pair("flashVer", "rtmp_flashver"),
std::make_pair("rtmp_flush_interval", "rtmp_flush_interval"),
std::make_pair("live", "rtmp_live"),
std::make_pair("pageUrl", "rtmp_pageurl"),
std::make_pair("playpath", "rtmp_playpath"),
std::make_pair("subscribe", "rtmp_subscribe"),
std::make_pair("swfHash", "rtmp_swfhash"),
std::make_pair("swfSize", "rtmp_swfsize"),
std::make_pair("swfUrl", "rtmp_swfurl"),
std::make_pair("swfVfy", "rtmp_swfverify"),
std::make_pair("tcUrl", "rtmp_tcurl")};
STDMETHODIMP CLAVFDemuxer::OpenInputStream(AVIOContext *byteContext, LPCOLESTR pszFileName, const char *format,
BOOL bForce, BOOL bFileSource)
{
CAutoLock lock(m_pLock);
HRESULT hr = S_OK;
int ret; // return code from avformat functions
// Convert the filename from wchar to char for avformat
char *fileName = NULL;
if (pszFileName)
fileName = CoTaskGetMultiByteFromWideChar(CP_UTF8, 0, pszFileName, -1);
if (fileName == NULL)
{
fileName = (char *)CoTaskMemAlloc(1);
*fileName = 0;
}
if (_strnicmp("mms:", fileName, 4) == 0)
{
memmove(fileName + 1, fileName, strlen(fileName));
memcpy(fileName, "mmsh", 4);
}
// replace "icyx" protocol by http
if (_strnicmp("icyx:", fileName, 5) == 0)
{
memcpy(fileName, "http", 4);
}
char *rtmp_prameters = nullptr;
const char *rtsp_transport = nullptr;
// check for rtsp transport protocol options
if (_strnicmp("rtsp", fileName, 4) == 0)
{
if (_strnicmp("rtspu:", fileName, 6) == 0)
{
rtsp_transport = "udp";
}
else if (_strnicmp("rtspm:", fileName, 6) == 0)
{
rtsp_transport = "udp_multicast";
}
else if (_strnicmp("rtspt:", fileName, 6) == 0)
{
rtsp_transport = "tcp";
}
else if (_strnicmp("rtsph:", fileName, 6) == 0)
{
rtsp_transport = "http";
}
// replace "rtsp[u|m|t|h]" protocol by rtsp
if (rtsp_transport != nullptr)
{
memmove(fileName + 4, fileName + 5, strlen(fileName) - 4);
}
}
else if (_strnicmp("rtmp", fileName, 4) == 0)
{
rtmp_prameters = strchr(fileName, ' ');
if (rtmp_prameters)
{
*rtmp_prameters = '\0'; // Trim not supported part form fileName
}
}
AVIOInterruptCB cb = {avio_interrupt_cb, this};
trynoformat:
// Create the avformat_context
m_avFormat = avformat_alloc_context();
m_avFormat->pb = byteContext;
m_avFormat->interrupt_callback = cb;
if (m_avFormat->pb)
m_avFormat->flags |= AVFMT_FLAG_CUSTOM_IO;
LPWSTR extension = pszFileName ? PathFindExtensionW(pszFileName) : nullptr;
const AVInputFormat *inputFormat = nullptr;
if (format)
{
inputFormat = av_find_input_format(format);
}
else if (pszFileName)
{
LPWSTR extension = PathFindExtensionW(pszFileName);
for (int i = 0; i < countof(wszImageExtensions); i++)
{
if (_wcsicmp(extension, wszImageExtensions[i]) == 0)
{
if (byteContext)
{
inputFormat = av_find_input_format("image2pipe");
}
else
{
inputFormat = av_find_input_format("image2");
}
break;
}
}
if (byteContext == nullptr || bFileSource)
{
for (int i = 0; i < countof(wszBlockedExtensions); i++)
{
if (_wcsicmp(extension, wszBlockedExtensions[i]) == 0)
{
goto done;
}
}
}
}
// Disable loading of external mkv segments, if required
if (!m_pSettings->GetLoadMatroskaExternalSegments())
m_avFormat->flags |= AVFMT_FLAG_NOEXTERNAL;
// demuxer/protocol options
AVDictionary *options = nullptr;
av_dict_set(&options, "icy", "1", 0); // request ICY metadata
av_dict_set(&options, "advanced_editlist", "0", 0); // disable broken mov editlist handling
av_dict_set(&options, "reconnect", "1", 0); // for http, reconnect if we get disconnected
av_dict_set(&options, "referer", fileName, 0); // for http, send self as referer
av_dict_set(&options, "skip_clear", "1", 0); // mpegts program handling
// send global side data to the decoder
av_format_inject_global_side_data(m_avFormat);
if (rtsp_transport != nullptr)
{
av_dict_set(&options, "rtsp_transport", rtsp_transport, 0);
}
if (rtmp_prameters != nullptr)
{
char buff[4100];
char *next_token = nullptr;
bool bSwfVerify = false;
strcpy_s(buff, rtmp_prameters + 1);
const char *token = strtok_s(buff, " ", &next_token);
while (token)
{
for (size_t i = 0; i < _countof(rtmpParametersTranslate); i++)
{
const size_t len = strlen(rtmpParametersTranslate[i].first);
if (_strnicmp(token, rtmpParametersTranslate[i].first, len) == 0)
{
if (strlen(token) > len + 1 && token[len] == '=')
{
if (_strnicmp("swfVfy", rtmpParametersTranslate[i].first, len) == 0)
{
bSwfVerify = token[len + 1] == '1';
continue;
}
else if (_strnicmp("live", rtmpParametersTranslate[i].first, len) == 0)
{
if (token[len + 1] == '1')
{
av_dict_set(&options, rtmpParametersTranslate[i].second, "live", 0);
}
else if (token[len + 1] == '0')
{
av_dict_set(&options, rtmpParametersTranslate[i].second, "recorded", 0);
}
continue;
}
av_dict_set(&options, rtmpParametersTranslate[i].second, token + len + 1, 0);
}
}
}
token = strtok_s(nullptr, " ", &next_token);
}
if (bSwfVerify)
{
const AVDictionaryEntry *swfUrlEntry = av_dict_get(options, "rtmp_swfurl", nullptr, 0);
if (swfUrlEntry)
{
av_dict_set(&options, "rtmp_swfverify", swfUrlEntry->value, 0);
}
}
}
m_timeOpening = time(nullptr);
ret = avformat_open_input(&m_avFormat, fileName, inputFormat, &options);
av_dict_free(&options);
if (ret < 0)
{
DbgLog((LOG_ERROR, 0, TEXT("::OpenInputStream(): avformat_open_input failed (%d)"), ret));
if (format)
{
DbgLog((LOG_ERROR, 0, TEXT(" -> trying again without specific format")));
format = nullptr;
avformat_close_input(&m_avFormat);
goto trynoformat;
}
goto done;
}
DbgLog((LOG_TRACE, 10,
TEXT("::OpenInputStream(): avformat_open_input opened file of type '%S' (took %I64d seconds)"),
m_avFormat->iformat->name, time(nullptr) - m_timeOpening));
m_timeOpening = 0;
CHECK_HR(hr = InitAVFormat(pszFileName, bForce));
SAFE_CO_FREE(fileName);
return S_OK;
done:
CleanupAVFormat();
SAFE_CO_FREE(fileName);
return E_FAIL;
}
void CLAVFDemuxer::AddMPEGTSStream(int pid, uint32_t stream_type)
{
if (m_avFormat)
{
int program = -1;
if (m_avFormat->nb_programs > 0)
{
unsigned nb_streams = 0;
for (unsigned i = 0; i < m_avFormat->nb_programs; i++)
{
if (m_avFormat->programs[i]->nb_stream_indexes > nb_streams)
program = i;
}
}
avpriv_mpegts_add_stream(m_avFormat, pid, stream_type, program >= 0 ? m_avFormat->programs[program]->id : -1);
}
}
HRESULT CLAVFDemuxer::CheckBDM2TSCPLI(LPCOLESTR pszFileName)
{
size_t len = wcslen(pszFileName);
if (len <= 23 || (_wcsnicmp(pszFileName + len - 23, L"\\BDMV\\STREAM\\", 13) != 0 &&
(len <= 28 || _wcsnicmp(pszFileName + len - 28, L"\\BDMV\\STREAM\\SSIF\\", 18) != 0)))
return E_FAIL;
// Get the base file name (should be a number, like 00000)
const WCHAR *file = pszFileName + (len - 10);
WCHAR basename[6];
wcsncpy_s(basename, file, 5);
basename[5] = 0;
// Convert to UTF-8 path
size_t a_len = WideCharToMultiByte(CP_UTF8, 0, pszFileName, -1, nullptr, 0, nullptr, nullptr);
a_len += 2; // one extra char because CLIPINF is 7 chars and STREAM is 6, and one for the terminating-zero
char *path = (char *)CoTaskMemAlloc(a_len * sizeof(char));
if (!path)
return E_OUTOFMEMORY;
WideCharToMultiByte(CP_UTF8, 0, pszFileName, -1, path, (int)a_len, nullptr, nullptr);
// Remove file name itself
PathRemoveFileSpecA(path);
// Remove SSIF if appropriate
BOOL bSSIF = FALSE;
if (_strnicmp(path + strlen(path) - 5, "\\SSIF", 5) == 0)
{
bSSIF = TRUE;
PathRemoveFileSpecA(path);
}
// Remove STREAM folder
PathRemoveFileSpecA(path);
// Write new path
sprintf_s(path + strlen(path), a_len - strlen(path), "\\CLIPINF\\%S.clpi", basename);
CLPI_CL *cl = bd_read_clpi(path);
if (!cl)
return E_FAIL;
// Clip Info was found, add the language metadata to the AVStreams
for (unsigned i = 0; i < cl->program.num_prog; ++i)
{
CLPI_PROG *p = &cl->program.progs[i];
for (unsigned k = 0; k < p->num_streams; ++k)
{
CLPI_PROG_STREAM *s = &p->streams[k];
AVStream *avstream = GetAVStreamByPID(s->pid);
if (avstream)
{
if (s->lang[0] != 0)
av_dict_set(&avstream->metadata, "language", (const char *)s->lang, 0);
}
}
}
// Free the clip
bd_free_clpi(cl);
cl = nullptr;
if (bSSIF)
{
uint32_t clip_id = _wtoi(basename);
// Remove filename
PathRemoveFileSpecA(path);
// Remove CLIPINF
PathRemoveFileSpecA(path);
// Remove BDMV
PathRemoveFileSpecA(path);
BLURAY *bd = bd_open(path, nullptr);
if (!bd)
return S_FALSE;
uint32_t nTitles = bd_get_titles(bd, TITLES_RELEVANT, 0);
BOOL found = FALSE;
for (uint32_t n = 0; n < nTitles && !found; n++)
{
BLURAY_TITLE_INFO *TitleInfo = bd_get_title_info(bd, n, 0);
if (TitleInfo)
{
for (uint32_t i = 0; i < TitleInfo->clip_count; i++)
{
BLURAY_CLIP_INFO *Clip = &TitleInfo->clips[i];
if (Clip->idx == clip_id)
{
AVStream *avstream = nullptr;
for (uint8_t c = 0; c < Clip->video_stream_count && !avstream; c++)
{
if (Clip->video_streams[c].coding_type == BLURAY_STREAM_TYPE_VIDEO_H264)
avstream = GetAVStreamByPID(Clip->video_streams[c].pid);
}
if (avstream)
av_dict_set(&avstream->metadata, "stereo_mode",
TitleInfo->mvc_base_view_r_flag ? "mvc_rl" : "mvc_lr", 0);
found = TRUE;
break;
}
}
bd_free_title_info(TitleInfo);
}
}
bd_close(bd);
}
return S_OK;
}
inline static int init_parser(AVFormatContext *s, AVStream *st)
{
if (av_lav_stream_parser_get_needed(st) && !(s->flags & AVFMT_FLAG_NOPARSE))
{
av_lav_stream_parser_init(st);
}
return 0;
}
void CLAVFDemuxer::UpdateParserFlags(AVStream *st)
{
int flags = av_lav_stream_parser_get_flags(st);
if ((st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO || st->codecpar->codec_id == AV_CODEC_ID_MPEG1VIDEO) &&
_stricmp(m_pszInputFormat, "mpegvideo") != 0)
{
flags |= PARSER_FLAG_NO_TIMESTAMP_MANGLING;
}
else if (st->codecpar->codec_id == AV_CODEC_ID_H264)
{
flags |= PARSER_FLAG_NO_TIMESTAMP_MANGLING;
}
else if (st->codecpar->codec_id == AV_CODEC_ID_VC1)
{
if (m_bVC1Correction)
{
flags &= ~PARSER_FLAG_NO_TIMESTAMP_MANGLING;
}
else
{
flags |= PARSER_FLAG_NO_TIMESTAMP_MANGLING;
}
}
av_lav_stream_parser_update_flags(st, flags);
}
static struct sCoverMimeTypes
{
AVCodecID codec;
LPCWSTR mime;
LPCWSTR ext;
} CoverMimeTypes[] = {
{AV_CODEC_ID_MJPEG, L"image/jpeg", L".jpg"}, {AV_CODEC_ID_PNG, L"image/png", L".png"},
{AV_CODEC_ID_GIF, L"image/gif", L".gif"}, {AV_CODEC_ID_BMP, L"image/bmp", L".bmp"},
{AV_CODEC_ID_TIFF, L"image/tiff", L".tiff"},
};
STDMETHODIMP CLAVFDemuxer::InitAVFormat(LPCOLESTR pszFileName, BOOL bForce)
{
HRESULT hr = S_OK;
const char *format = nullptr;
lavf_get_iformat_infos(m_avFormat->iformat, &format, nullptr);
if (!bForce && (!format || !m_pSettings->IsFormatEnabled(format)))
{
DbgLog((LOG_TRACE, 20, L"::InitAVFormat() - format of type '%S' disabled, failing",
format ? format : m_avFormat->iformat->name));
return E_FAIL;
}
m_pszInputFormat = format ? format : m_avFormat->iformat->name;
m_bVC1SeenTimestamp = FALSE;
LPWSTR extension = pszFileName ? PathFindExtensionW(pszFileName) : nullptr;
m_bMatroska = (_strnicmp(m_pszInputFormat, "matroska", 8) == 0);
m_bOgg = (_strnicmp(m_pszInputFormat, "ogg", 3) == 0);
m_bAVI = (_strnicmp(m_pszInputFormat, "avi", 3) == 0);
m_bMPEGTS = (_strnicmp(m_pszInputFormat, "mpegts", 6) == 0);
m_bMPEGPS = (_stricmp(m_pszInputFormat, "mpeg") == 0);
m_bRM = (_stricmp(m_pszInputFormat, "rm") == 0);
m_bPMP = (_stricmp(m_pszInputFormat, "pmp") == 0);
m_bMP4 = (_stricmp(m_pszInputFormat, "mp4") == 0);
m_bTSDiscont = (m_avFormat->iformat->flags & AVFMT_TS_DISCONT) || m_bRM || (_stricmp(m_pszInputFormat, "dash") == 0);
WCHAR szProt[24] = L"file";
if (pszFileName)
{
DWORD dwNumChars = 24;
hr = UrlGetPart(pszFileName, szProt, &dwNumChars, URL_PART_SCHEME, 0);
if (SUCCEEDED(hr) && dwNumChars && (_wcsicmp(szProt, L"file") != 0))
{
m_avFormat->flags |= AVFMT_FLAG_NETWORK;
DbgLog((LOG_TRACE, 10, TEXT("::InitAVFormat(): detected network protocol: %s"), szProt));
}
}
// TODO: make both durations below configurable
// decrease analyze duration for network streams
if (m_avFormat->flags & AVFMT_FLAG_NETWORK ||
(m_avFormat->flags & AVFMT_FLAG_CUSTOM_IO && !m_avFormat->pb->seekable))
{
// require at least 0.2 seconds
av_opt_set_int(m_avFormat, "analyzeduration",
max(m_pSettings->GetNetworkStreamAnalysisDuration() * 1000, 200000), 0);
}
else
{
av_opt_set_int(m_avFormat, "analyzeduration", 7500000, 0);
// And increase it for mpeg-ts/ps files
if (m_bMPEGTS || m_bMPEGPS)
{
av_opt_set_int(m_avFormat, "analyzeduration", 30000000, 0);
av_opt_set_int(m_avFormat, "probesize", 75000000, 0);
}
}
av_opt_set_int(m_avFormat, "correct_ts_overflow", !m_pBluRay, 0);
m_timeOpening = time(nullptr);
int ret = avformat_find_stream_info(m_avFormat, nullptr);
if (ret < 0)
{
DbgLog((LOG_ERROR, 0, TEXT("::InitAVFormat(): av_find_stream_info failed (%d)"), ret));
goto done;
}
DbgLog((LOG_TRACE, 10, TEXT("::InitAVFormat(): avformat_find_stream_info finished, took %I64d seconds"),
time(nullptr) - m_timeOpening));
m_timeOpening = 0;
// Check if this is a m2ts in a BD structure, and if it is, read some extra stream properties out of the CLPI files
if (m_pBluRay)
{
m_pBluRay->ProcessBluRayMetadata();
}
else if (pszFileName && m_bMPEGTS)
{
CheckBDM2TSCPLI(pszFileName);
}
char *icy_headers = nullptr;
if (av_opt_get(m_avFormat, "icy_metadata_headers", AV_OPT_SEARCH_CHILDREN, (uint8_t **)&icy_headers) >= 0 &&
icy_headers && strlen(icy_headers) > 0)
{
std::string icyHeaders(icy_headers);
std::stringstream icyHeaderStream(icyHeaders);
std::string line;
while (std::getline(icyHeaderStream, line))
{
size_t seperatorIdx = line.find_first_of(":");
std::string token = line.substr(0, seperatorIdx);
std::string value = line.substr(seperatorIdx + 1);
if (_stricmp(token.c_str(), "icy-name") == 0)
{
// not entirely correct, but this way it gets exported through IAMMediaContent
av_dict_set(&m_avFormat->metadata, "artist", value.c_str(), 0);
}
else if (_stricmp(token.c_str(), "icy-description") == 0)
{
av_dict_set(&m_avFormat->metadata, "comment", value.c_str(), 0);
}
else if (_stricmp(token.c_str(), "icy-genre") == 0)
{
av_dict_set(&m_avFormat->metadata, "genre", value.c_str(), 0);
}
}
ParseICYMetadataPacket();
}
av_freep(&icy_headers);
SAFE_CO_FREE(m_stOrigParser);
m_stOrigParser = (enum AVStreamParseType *)CoTaskMemAlloc(m_avFormat->nb_streams * sizeof(enum AVStreamParseType));
if (!m_stOrigParser)
return E_OUTOFMEMORY;
for (unsigned int idx = 0; idx < m_avFormat->nb_streams; ++idx)
{
AVStream *st = m_avFormat->streams[idx];
// Disable full stream parsing for these formats
if (av_lav_stream_parser_get_needed(st) == AVSTREAM_PARSE_FULL)
{
if (st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
{
av_lav_stream_parser_set_needed(st, AVSTREAM_PARSE_NONE);
}
}
if (m_bOgg && st->codecpar->codec_id == AV_CODEC_ID_H264)
{
av_lav_stream_parser_set_needed(st, AVSTREAM_PARSE_FULL);
}
// Create the parsers with the appropriate flags
init_parser(m_avFormat, st);
UpdateParserFlags(st);
#ifdef DEBUG
AVProgram *streamProg = av_find_program_from_stream(m_avFormat, nullptr, idx);
DbgLog((LOG_TRACE, 30, L"Stream %d (pid %d) - program: %d, codec: %S; parsing: %S;", idx, st->id,
streamProg ? streamProg->pmt_pid : -1, avcodec_get_name(st->codecpar->codec_id),
lavf_get_parsing_string(av_lav_stream_parser_get_needed(st))));
#endif
m_stOrigParser[idx] = av_lav_stream_parser_get_needed(st);
if ((st->codecpar->codec_id == AV_CODEC_ID_DTS && st->codecpar->codec_tag == 0xA2) ||
(st->codecpar->codec_id == AV_CODEC_ID_EAC3 && st->codecpar->codec_tag == 0xA1))
st->disposition |= LAVF_DISPOSITION_SECONDARY_AUDIO;
UpdateSubStreams();
if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT)
{
const AVDictionaryEntry *attachFilename = av_dict_get(st->metadata, "filename", nullptr, 0);
const AVDictionaryEntry *attachMimeType = av_dict_get(st->metadata, "mimetype", nullptr, 0);
const AVDictionaryEntry *attachDescription = av_dict_get(st->metadata, "comment", nullptr, 0);
if (attachFilename && attachMimeType)
{
LPWSTR chFilename =
CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachFilename->value, -1);
LPWSTR chMimetype =
CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachMimeType->value, -1);
LPWSTR chDescription = nullptr;
if (attachDescription)
chDescription =
CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachDescription->value, -1);
if (chFilename && chMimetype)
ResAppend(chFilename, chDescription, chMimetype, st->codecpar->extradata,
(DWORD)st->codecpar->extradata_size);
SAFE_CO_FREE(chFilename);
SAFE_CO_FREE(chMimetype);
SAFE_CO_FREE(chDescription);
}
else
{
DbgLog((LOG_TRACE, 10, L" -> Unknown attachment, missing filename or mimetype"));
}
// Try to guess the codec id for fonts only listed by name
if (st->codecpar->codec_id == AV_CODEC_ID_NONE && attachFilename)
{
char *dot = strrchr(attachFilename->value, '.');
if (dot && !_stricmp(dot, ".ttf"))
st->codecpar->codec_id = AV_CODEC_ID_TTF;
else if (dot && !_stricmp(dot, ".otf"))
st->codecpar->codec_id = AV_CODEC_ID_OTF;
}
if (st->codecpar->codec_id == AV_CODEC_ID_TTF || st->codecpar->codec_id == AV_CODEC_ID_OTF)
{
if (!m_pFontInstaller)
{
m_pFontInstaller = new CFontInstaller();
}
m_pFontInstaller->InstallFont(st->codecpar->extradata, st->codecpar->extradata_size);
}
}
else if (st->disposition & AV_DISPOSITION_ATTACHED_PIC && st->attached_pic.data && st->attached_pic.size > 0)
{
LPWSTR chFilename = nullptr;
LPWSTR chMimeType = nullptr;
LPWSTR chDescription = nullptr;
// gather a filename
const AVDictionaryEntry *attachFilename = av_dict_get(st->metadata, "filename", nullptr, 0);
if (attachFilename)
chFilename = CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachFilename->value, -1);
// gather a mimetype
const AVDictionaryEntry *attachMimeType = av_dict_get(st->metadata, "mimetype", nullptr, 0);
if (attachMimeType)
chMimeType = CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachMimeType->value, -1);
// gather description
const AVDictionaryEntry *attachDescription = av_dict_get(st->metadata, "comment", nullptr, 0);
if (attachDescription)
chDescription =
CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachDescription->value, -1);
for (int c = 0; c < countof(CoverMimeTypes); c++)
{
if (CoverMimeTypes[c].codec == st->codecpar->codec_id)
{
if (chFilename == nullptr)
{
size_t size = wcslen(CoverMimeTypes[c].ext) + 15;
chFilename = (LPWSTR)CoTaskMemAlloc(size * sizeof(wchar_t));
wcscpy_s(chFilename, size, L"EmbeddedCover");
wcscat_s(chFilename, size, CoverMimeTypes[c].ext);
}
if (chMimeType == nullptr)
{
size_t size = wcslen(CoverMimeTypes[c].mime) + 1;
chMimeType = (LPWSTR)CoTaskMemAlloc(size * sizeof(wchar_t));
wcscpy_s(chMimeType, size, CoverMimeTypes[c].mime);
}
break;
}
}
// Export embedded cover-art through IDSMResourceBag interface
if (chFilename && chMimeType)
{
ResAppend(chFilename, chDescription, chMimeType, st->attached_pic.data, (DWORD)st->attached_pic.size);
}
else
{
DbgLog((LOG_TRACE, 10, L" -> Unknown attachment, missing filename or mimetype"));
}
SAFE_CO_FREE(chFilename);
SAFE_CO_FREE(chMimeType);
SAFE_CO_FREE(chDescription);
}
}
if (AVDictionaryEntry *cue = av_dict_get(m_avFormat->metadata, "CUESHEET", nullptr, 0))
{
CCueSheet cueSheet;
if (SUCCEEDED(cueSheet.Parse(cue->value)))
{
// Metadata
if (!cueSheet.m_Title.empty() && !av_dict_get(m_avFormat->metadata, "title", nullptr, 0))
av_dict_set(&m_avFormat->metadata, "title", cueSheet.m_Title.c_str(), 0);
if (!cueSheet.m_Performer.empty() && !av_dict_get(m_avFormat->metadata, "artist", nullptr, 0))
av_dict_set(&m_avFormat->metadata, "artist", cueSheet.m_Performer.c_str(), 0);
// Free old chapters
while (m_avFormat->nb_chapters--)
{
av_dict_free(&m_avFormat->chapters[m_avFormat->nb_chapters]->metadata);
av_freep(&m_avFormat->chapters[m_avFormat->nb_chapters]);
}
av_freep(&m_avFormat->chapters);
m_avFormat->nb_chapters = 0;
for (CCueSheet::Track track : cueSheet.m_Tracks)
{
avpriv_new_chapter(m_avFormat, track.index, AVRational{1, DSHOW_TIME_BASE}, track.Time, track.Time,
cueSheet.FormatTrack(track).c_str());
}
}
}
CHECK_HR(hr = CreateStreams());
return S_OK;
done:
CleanupAVFormat();
return E_FAIL;
}
void CLAVFDemuxer::CleanupAVFormat()
{
FlushMVCExtensionQueue();
if (m_avFormat)
{
// Override abort timer to ensure the close function in network protocols can actually close the stream
AbortOpening(1, 5);
avformat_close_input(&m_avFormat);
}
SAFE_CO_FREE(m_stOrigParser);
}
AVStream *CLAVFDemuxer::GetAVStreamByPID(int pid)
{
if (!m_avFormat)
return nullptr;
for (unsigned int idx = 0; idx < m_avFormat->nb_streams; ++idx)
{
if (m_avFormat->streams[idx]->id == pid &&
!(m_avFormat->streams[idx]->disposition & LAVF_DISPOSITION_SUB_STREAM))
return m_avFormat->streams[idx];
}
return nullptr;
}
HRESULT CLAVFDemuxer::SetActiveStream(StreamType type, int pid)
{
HRESULT hr = S_OK;
if (type == audio)
UpdateForcedSubtitleStream(pid);
hr = __super::SetActiveStream(type, pid);
// Usually selecting an audio stream would set the forced substream (since it uses the audio stream language)
// but in case there is no audio stream, do a fallback selection of any PGS stream here.
if (type == subpic && pid == FORCED_SUBTITLE_PID && m_ForcedSubStream == -1)
{
std::list<CSubtitleSelector> selectors;
CSubtitleSelector selector;
selector.audioLanguage = "*";
selector.subtitleLanguage = "*";
selector.dwFlagsSet = SUBTITLE_FLAG_PGS;
selector.dwFlagsNot = 0;
selectors.push_back(selector);
const stream *subst = SelectSubtitleStream(selectors, "");
if (subst)
m_ForcedSubStream = subst->pid;
}
for (unsigned int idx = 0; idx < m_avFormat->nb_streams; ++idx)
{
AVStream *st = m_avFormat->streams[idx];
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
{
st->discard = (m_dActiveStreams[video] == idx) ? AVDISCARD_DEFAULT : AVDISCARD_ALL;
// don't discard h264 mvc streams
if (m_bH264MVCCombine && st->codecpar->codec_id == AV_CODEC_ID_H264_MVC)
st->discard = AVDISCARD_DEFAULT;
}
else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
{
st->discard = (m_dActiveStreams[audio] == idx) ? AVDISCARD_DEFAULT : AVDISCARD_ALL;
// If the stream is a sub stream, make sure to activate the main stream as well
if (m_bMPEGTS && (st->disposition & LAVF_DISPOSITION_SUB_STREAM) && st->discard == AVDISCARD_DEFAULT)
{
for (unsigned int idx2 = 0; idx2 < m_avFormat->nb_streams; ++idx2)
{
AVStream *mst = m_avFormat->streams[idx2];
if (mst->id == st->id)
{