-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathSession.cpp
1542 lines (1331 loc) · 49.7 KB
/
Session.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) 2022 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 "Session.h"
#include "CompKodiProps.h"
#include "CompSettings.h"
#include "SrvBroker.h"
#include "aes_decrypter.h"
#include "common/AdaptiveDecrypter.h"
#include "common/AdaptiveTreeFactory.h"
#include "common/Chooser.h"
#include "decrypters/DrmFactory.h"
#include "decrypters/Helpers.h"
#include "utils/Base64Utils.h"
#include "utils/CurlUtils.h"
#include "utils/StringUtils.h"
#include "utils/UrlUtils.h"
#include "utils/Utils.h"
#include "utils/log.h"
using namespace adaptive;
using namespace PLAYLIST;
using namespace SESSION;
using namespace UTILS;
SESSION::CSession::~CSession()
{
LOG::Log(LOGDEBUG, "CSession::~CSession()");
DeleteStreams();
DisposeDecrypter();
if (m_adaptiveTree)
{
m_adaptiveTree->Uninitialize();
delete m_adaptiveTree;
m_adaptiveTree = nullptr;
}
delete m_reprChooser;
m_reprChooser = nullptr;
}
void SESSION::CSession::DeleteStreams()
{
LOG::Log(LOGDEBUG, "CSession::DeleteStreams()");
m_streams.clear();
}
void SESSION::CSession::SetSupportedDecrypterURN(std::vector<std::string_view>& keySystems)
{
std::string decrypterPath = CSrvBroker::GetSettings().GetDecrypterPath();
if (decrypterPath.empty())
{
LOG::Log(LOGWARNING, "Decrypter path not set in the add-on settings");
return;
}
const std::string keySystem = CSrvBroker::GetKodiProps().GetDrmKeySystem();
m_decrypter = DRM::FACTORY::GetDecrypter(GetCryptoKeySystem(keySystem));
if (!m_decrypter)
return;
if (!m_decrypter->Initialize())
{
LOG::Log(LOGERROR, "The decrypter library cannot be initialized.");
return;
}
keySystems = m_decrypter->SelectKeySystems(keySystem);
m_decrypter->SetLibraryPath(decrypterPath);
}
void SESSION::CSession::DisposeSampleDecrypter()
{
if (m_decrypter)
{
for (auto& cdmSession : m_cdmSessions)
{
cdmSession.m_sessionId.clear();
cdmSession.m_cencSingleSampleDecrypter = nullptr;
}
}
}
void SESSION::CSession::DisposeDecrypter()
{
DisposeSampleDecrypter();
m_decrypter = nullptr;
}
/*----------------------------------------------------------------------
| initialize
+---------------------------------------------------------------------*/
bool SESSION::CSession::Initialize(std::string manifestUrl)
{
m_reprChooser = CHOOSER::CreateRepresentationChooser();
switch (CSrvBroker::GetSettings().GetMediaType())
{
case 1:
m_mediaTypeMask = static_cast<uint8_t>(1U) << static_cast<int>(StreamType::AUDIO);
break;
case 2:
m_mediaTypeMask = static_cast<uint8_t>(1U) << static_cast<int>(StreamType::VIDEO);
break;
case 3:
m_mediaTypeMask = (static_cast<uint8_t>(1U) << static_cast<int>(StreamType::VIDEO)) |
(static_cast<uint8_t>(1U) << static_cast<int>(StreamType::SUBTITLE));
break;
default:
m_mediaTypeMask = static_cast<uint8_t>(~0);
}
auto& kodiProps = CSrvBroker::GetKodiProps();
// Get URN's wich are supported by this addon
std::vector<std::string_view> supportedKeySystems;
if (!kodiProps.GetDrmKeySystem().empty())
{
SetSupportedDecrypterURN(supportedKeySystems);
for (std::string_view keySystem : supportedKeySystems)
{
LOG::Log(LOGDEBUG, "Supported URN: %s", keySystem.data());
}
}
std::map<std::string, std::string> manifestHeaders = kodiProps.GetManifestHeaders();
bool isSessionOpened{false};
// Preinitialize the DRM, if pre-initialisation data are provided
if (!kodiProps.GetDrmConfig().preInitData.empty())
{
std::string challengeB64;
std::string sessionId;
// Pre-initialize the DRM allow to generate the challenge and session ID data
// used to make licensed manifest requests (via proxy callback)
if (PreInitializeDRM(challengeB64, sessionId, isSessionOpened))
{
manifestHeaders["challengeB64"] = STRING::URLEncode(challengeB64);
manifestHeaders["sessionId"] = sessionId;
}
else
{
return false;
}
}
URL::RemovePipePart(manifestUrl); // No pipe char uses, must be used Kodi properties only
URL::AppendParameters(manifestUrl, kodiProps.GetManifestParams());
CURL::HTTPResponse manifestResp;
if (!CURL::DownloadFile(manifestUrl, manifestHeaders, {"etag", "last-modified"}, manifestResp))
return false;
// The download speed with small file sizes is not accurate, we should download at least 512Kb
// to have a sufficient acceptable value to calculate the bandwidth,
// then to have a better speed value we apply following proportion hack.
// This does not happen when you play with webbrowser because can obtain the connection speed.
static const size_t minSize{512 * 1024};
if (manifestResp.dataSize < minSize)
manifestResp.downloadSpeed = (manifestResp.downloadSpeed / manifestResp.dataSize) * minSize;
// We set the download speed to calculate the initial network bandwidth
m_reprChooser->SetDownloadSpeed(manifestResp.downloadSpeed);
m_adaptiveTree = PLAYLIST_FACTORY::CreateAdaptiveTree(manifestResp);
if (!m_adaptiveTree)
return false;
m_adaptiveTree->Configure(m_reprChooser, supportedKeySystems, kodiProps.GetManifestUpdParams());
if (!m_adaptiveTree->Open(manifestResp.effectiveUrl, manifestResp.headers, manifestResp.data))
{
LOG::Log(LOGERROR, "Cannot parse the manifest (%s)", manifestUrl.c_str());
return false;
}
m_adaptiveTree->PostOpen();
m_reprChooser->PostInit();
CSrvBroker::GetInstance()->InitStage2(m_adaptiveTree);
return InitializePeriod(isSessionOpened);
}
void SESSION::CSession::CheckHDCP()
{
//! @todo: is needed to implement an appropriate CP check to
//! remove HDCPOVERRIDE setting workaround
if (m_cdmSessions.empty())
return;
std::vector<DRM::DecrypterCapabilites> decrypterCaps;
for (const auto& cdmsession : m_cdmSessions)
{
decrypterCaps.emplace_back(cdmsession.m_decrypterCaps);
}
uint32_t adpIndex{0};
CAdaptationSet* adp{nullptr};
while ((adp = m_adaptiveTree->GetAdaptationSet(adpIndex++)))
{
if (adp->GetStreamType() != StreamType::VIDEO)
continue;
for (auto itRepr = adp->GetRepresentations().begin();
itRepr != adp->GetRepresentations().end();)
{
CRepresentation* repr = (*itRepr).get();
const DRM::DecrypterCapabilites& ssd_caps = decrypterCaps[repr->m_psshSetPos];
if (repr->GetHdcpVersion() > ssd_caps.hdcpVersion ||
(ssd_caps.hdcpLimit > 0 && repr->GetWidth() * repr->GetHeight() > ssd_caps.hdcpLimit))
{
LOG::Log(LOGDEBUG, "Representation ID \"%s\" removed as not HDCP compliant",
repr->GetId().data());
itRepr = adp->GetRepresentations().erase(itRepr);
}
else
itRepr++;
}
}
}
bool SESSION::CSession::PreInitializeDRM(std::string& challengeB64,
std::string& sessionId,
bool& isSessionOpened)
{
auto& drmPropCfg = CSrvBroker::GetKodiProps().GetDrmConfig();
std::string psshData;
std::string kidData;
// Parse the PSSH/KID data
size_t posSplitter = drmPropCfg.preInitData.find("|");
if (posSplitter != std::string::npos)
{
psshData = drmPropCfg.preInitData.substr(0, posSplitter);
kidData = drmPropCfg.preInitData.substr(posSplitter + 1);
}
if (psshData.empty() || kidData.empty())
{
LOG::LogF(LOGERROR, "Invalid DRM pre-init data, must be as: {PSSH as base64}|{KID as base64}");
return false;
}
m_cdmSessions.resize(2);
// Try to initialize an SingleSampleDecryptor
LOG::LogF(LOGDEBUG, "Entering encryption section");
if (!m_decrypter)
{
LOG::LogF(LOGERROR, "No decrypter found for encrypted stream");
return false;
}
if (!m_decrypter->IsInitialised())
{
DRM::Config drmCfg = DRM::CreateDRMConfig(DRM::KS_WIDEVINE, drmPropCfg);
if (!m_decrypter->OpenDRMSystem(drmCfg))
{
LOG::LogF(LOGERROR, "OpenDRMSystem failed");
return false;
}
}
std::vector<uint8_t> initData;
// Set the provided PSSH
initData = BASE64::Decode(psshData);
// Decode the provided KID
const std::vector<uint8_t> decKid = BASE64::Decode(kidData);
CCdmSession& session(m_cdmSessions[1]);
std::string hexKid{STRING::ToHexadecimal(decKid)};
LOG::LogF(LOGDEBUG, "Initializing session with KID: %s", hexKid.c_str());
if (m_decrypter && (session.m_cencSingleSampleDecrypter =
m_decrypter->CreateSingleSampleDecrypter(initData, decKid, "", true,
CryptoMode::AES_CTR)) != nullptr)
{
session.m_sessionId = session.m_cencSingleSampleDecrypter->GetSessionId();
sessionId = session.m_sessionId;
challengeB64 = m_decrypter->GetChallengeB64Data(session.m_cencSingleSampleDecrypter);
}
else
{
LOG::LogF(LOGERROR, "Initialize failed (SingleSampleDecrypter)");
session.m_cencSingleSampleDecrypter = nullptr;
return false;
}
#if defined(ANDROID)
// On android is not possible add the default KID key
// then we cannot re-use same session
DisposeSampleDecrypter();
#else
isSessionOpened = true;
#endif
return true;
}
bool SESSION::CSession::InitializeDRM(bool addDefaultKID /* = false */)
{
bool isSecureVideoSession{false};
m_cdmSessions.resize(m_adaptiveTree->m_currentPeriod->GetPSSHSets().size());
// Try to initialize an SingleSampleDecryptor
if (m_adaptiveTree->m_currentPeriod->GetEncryptionState() == EncryptionState::ENCRYPTED_DRM)
{
const std::string keySystem = CSrvBroker::GetKodiProps().GetDrmKeySystem();
auto& drmPropCfg = CSrvBroker::GetKodiProps().GetDrmConfig();
DRM::Config drmCfg = DRM::CreateDRMConfig(keySystem, drmPropCfg);
if (drmCfg.license.serverUrl.empty())
drmCfg.license.serverUrl = m_adaptiveTree->GetLicenseUrl();
LOG::Log(LOGDEBUG, "Entering encryption section");
if (!m_decrypter)
{
LOG::Log(LOGERROR, "No decrypter found for encrypted stream");
return false;
}
if (!m_decrypter->IsInitialised())
{
if (!m_decrypter->OpenDRMSystem(drmCfg))
{
LOG::Log(LOGERROR, "OpenDRMSystem failed");
return false;
}
}
// cdmSession 0 is reserved for unencrypted streams
for (size_t ses{1}; ses < m_cdmSessions.size(); ++ses)
{
CCdmSession& session{m_cdmSessions[ses]};
// Check if the decrypter has been previously initialized, if so skip it,
// sessions are collected and never removed and InitializeDRM can be called more times
// depending on how it is used:
// 1) CSession::Initialize->InitializePeriod->InitializeDRM - Used by DASH/SS (single call)
// 2) CInputStreamAdaptive::DemuxRead->m_session->InitializePeriod()->InitializeDRM - On chapter change (single call)
// 3) CInputStreamAdaptive::OpenStream->m_session->PrepareStream->InitializeDRM - Used by HLS (a call for each stream)
if (session.m_cencSingleSampleDecrypter)
continue;
const CPeriod::PSSHSet& sessionPsshset = m_adaptiveTree->m_currentPeriod->GetPSSHSets()[ses];
if (sessionPsshset.adaptation_set_->GetStreamType() == StreamType::NOTYPE)
continue;
std::vector<uint8_t> initData = sessionPsshset.pssh_;
std::string defaultKidStr = sessionPsshset.defaultKID_;
std::vector<uint8_t> customInitData = BASE64::Decode(drmPropCfg.initData);
if (m_adaptiveTree->GetTreeType() == adaptive::TreeType::SMOOTH_STREAMING &&
keySystem == DRM::KS_WIDEVINE)
{
if (DRM::IsValidPsshHeader(customInitData))
{
initData = customInitData;
}
else
{
LOG::Log(LOGDEBUG, "License data: Create Widevine PSSH for SmoothStreaming %s",
customInitData.empty() ? "" : "(with custom data)");
initData =
DRM::PSSH::MakeWidevine({DRM::ConvertKidStrToBytes(defaultKidStr)}, customInitData);
}
}
else if (!customInitData.empty())
{
// Custom license PSSH data provided from property
// This can allow to initialize a DRM that could be also not specified
// as supported in the manifest (e.g. missing DASH ContentProtection tags)
LOG::Log(LOGDEBUG, "License data: Use PSSH data provided by the license data property");
initData = customInitData;
}
// If no KID, but init data, extract the KID from init data
if (!initData.empty() && defaultKidStr.empty())
{
DRM::PSSH parser;
if (parser.Parse(initData) && !parser.GetKeyIds().empty())
{
LOG::Log(LOGDEBUG, "Default KID parsed from init data");
defaultKidStr = STRING::ToHexadecimal(parser.GetKeyIds()[0]);
}
}
//! @todo: as is implemented InitializeDRM will initialize all PSSHSet's also when are not used,
//! therefore ExtractStreamProtectionData can perform many (not needed) downloads of mp4 init files
if ((initData.empty() && keySystem != DRM::KS_CLEARKEY) || defaultKidStr.empty())
{
// Try extract the PSSH/KID from the stream
ExtractStreamProtectionData(sessionPsshset, defaultKidStr, initData,
m_adaptiveTree->m_supportedKeySystems);
}
const std::vector<uint8_t> defaultKid = DRM::ConvertKidStrToBytes(defaultKidStr);
if (addDefaultKID && ses == 1 && session.m_cencSingleSampleDecrypter)
{
// If the CDM has been pre-initialized, on non-android systems
// we use the same session opened then we have to add the current KID
// because the session has been opened with a different PSSH/KID
session.m_cencSingleSampleDecrypter->AddKeyId(defaultKid);
session.m_cencSingleSampleDecrypter->SetDefaultKeyId(defaultKid);
}
if (!defaultKid.empty())
{
LOG::Log(LOGDEBUG, "Initializing stream with KID: %s", defaultKidStr.c_str());
// If a decrypter has the default KID, re-use the same decrypter for also this session
for (size_t i{1}; i < ses; ++i)
{
if (m_decrypter->HasLicenseKey(m_cdmSessions[i].m_cencSingleSampleDecrypter, defaultKid))
{
session.m_cencSingleSampleDecrypter = m_cdmSessions[i].m_cencSingleSampleDecrypter;
break;
}
}
}
else if (defaultKid.empty())
{
for (size_t i{1}; i < ses; ++i)
{
if (sessionPsshset.pssh_ == m_adaptiveTree->m_currentPeriod->GetPSSHSets()[i].pssh_)
{
session.m_cencSingleSampleDecrypter = m_cdmSessions[i].m_cencSingleSampleDecrypter;
break;
}
}
if (!session.m_cencSingleSampleDecrypter)
{
LOG::Log(LOGWARNING, "Initializing stream with unknown KID!");
}
}
if (session.m_cencSingleSampleDecrypter ||
(session.m_cencSingleSampleDecrypter = m_decrypter->CreateSingleSampleDecrypter(
initData, defaultKid, sessionPsshset.m_licenseUrl, false,
sessionPsshset.m_cryptoMode == CryptoMode::NONE ? CryptoMode::AES_CTR
: sessionPsshset.m_cryptoMode)) !=
nullptr)
{
m_decrypter->GetCapabilities(session.m_cencSingleSampleDecrypter, defaultKid,
sessionPsshset.media_, session.m_decrypterCaps);
session.m_sessionId = session.m_cencSingleSampleDecrypter->GetSessionId();
if (session.m_decrypterCaps.flags & DRM::DecrypterCapabilites::SSD_INVALID)
{
m_adaptiveTree->m_currentPeriod->RemovePSSHSet(static_cast<std::uint16_t>(ses));
}
else if (session.m_decrypterCaps.flags & DRM::DecrypterCapabilites::SSD_SECURE_PATH)
{
isSecureVideoSession = true;
// Allow to disable the secure decoder
bool disableSecureDecoder = CSrvBroker::GetSettings().IsDisableSecureDecoder();
// but, DRM config can override it
if (drmPropCfg.isSecureDecoderEnabled.has_value())
disableSecureDecoder = !*drmPropCfg.isSecureDecoderEnabled;
// but, manifest config can override all others
if (m_adaptiveTree->m_currentPeriod->IsSecureDecodeNeeded().has_value())
disableSecureDecoder = !*m_adaptiveTree->m_currentPeriod->IsSecureDecodeNeeded();
if (disableSecureDecoder)
{
LOG::Log(LOGDEBUG, "Initialize DRM: Configured with secure decoder disabled");
session.m_decrypterCaps.flags &= ~DRM::DecrypterCapabilites::SSD_SECURE_DECODER;
}
}
}
else
{
LOG::Log(LOGERROR, "Initialize failed (SingleSampleDecrypter)");
for (size_t i(ses); i < m_cdmSessions.size(); ++i)
m_cdmSessions[i].m_cencSingleSampleDecrypter = nullptr;
return false;
}
}
}
bool isHdcpOverride = CSrvBroker::GetSettings().IsHdcpOverride();
if (isHdcpOverride)
LOG::Log(LOGDEBUG, "Ignore HDCP status is enabled");
if (!isHdcpOverride)
CheckHDCP();
m_reprChooser->SetSecureSession(isSecureVideoSession);
return true;
}
bool SESSION::CSession::InitializePeriod(bool isSessionOpened /* = false */)
{
bool isPsshChanged{true};
bool isReusePssh{true};
if (m_adaptiveTree->IsChangingPeriod())
{
isPsshChanged =
!(m_adaptiveTree->m_currentPeriod->GetPSSHSets() == m_adaptiveTree->m_nextPeriod->GetPSSHSets());
isReusePssh = !isPsshChanged && m_adaptiveTree->m_nextPeriod->GetEncryptionState() ==
EncryptionState::ENCRYPTED_DRM;
m_adaptiveTree->m_currentPeriod = m_adaptiveTree->m_nextPeriod;
}
m_chapterStartTime = GetChapterStartTime();
if (m_adaptiveTree->m_currentPeriod->GetEncryptionState() == EncryptionState::NOT_SUPPORTED)
{
LOG::LogF(LOGERROR, "Unhandled encrypted stream.");
return false;
}
// create SESSION::STREAM objects. One for each AdaptationSet
m_streams.clear();
if (!isPsshChanged)
{
if (isReusePssh)
LOG::Log(LOGDEBUG, "Reusing DRM psshSets for new period!");
}
else
{
if (isSessionOpened)
{
LOG::Log(LOGDEBUG, "New period, reinitialize by using same session");
}
else
{
LOG::Log(LOGDEBUG, "New period, dispose sample decrypter and reinitialize");
DisposeSampleDecrypter();
}
if (!InitializeDRM(isSessionOpened))
return false;
}
uint32_t adpIndex{0};
CAdaptationSet* adp{nullptr};
CHOOSER::StreamSelection streamSelectionMode = m_reprChooser->GetStreamSelectionMode();
//! @todo: GetAudioLangOrig property should be reworked to allow override or set
//! manifest a/v and subtitles streams attributes such as default/original etc..
//! since Kodi stream flags dont have always the same meaning of manifest attributes
//! and some video services dont follow exactly the specs so can lead to wrong Kodi flags sets.
//! An idea is add/move these override of attributes on post manifest parsing.
std::string audioLanguageOrig = CSrvBroker::GetKodiProps().GetAudioLangOrig();
while ((adp = m_adaptiveTree->GetAdaptationSet(adpIndex++)))
{
if (adp->GetRepresentations().empty())
continue;
if (adp->GetStreamType() == StreamType::NOTYPE)
{
LOG::LogF(LOGDEBUG, "Skipped streams on adaptation set id \"%s\" due to unsupported/unknown type",
adp->GetId().data());
continue;
}
bool isManualStreamSelection;
if (adp->GetStreamType() == StreamType::VIDEO)
isManualStreamSelection = streamSelectionMode != CHOOSER::StreamSelection::AUTO;
else
isManualStreamSelection = streamSelectionMode == CHOOSER::StreamSelection::MANUAL;
// Get the default initial stream repr. based on "adaptive repr. chooser"
auto defaultRepr{m_reprChooser->GetRepresentation(adp)};
if (isManualStreamSelection)
{
// Add all stream representations
for (size_t i{0}; i < adp->GetRepresentations().size(); i++)
{
size_t reprIndex{adp->GetRepresentations().size() - i};
uint32_t uniqueId{adpIndex};
uniqueId |= reprIndex << 16;
CRepresentation* currentRepr = adp->GetRepresentations()[i].get();
bool isDefaultRepr{currentRepr == defaultRepr};
AddStream(adp, currentRepr, isDefaultRepr, uniqueId, audioLanguageOrig);
}
}
else
{
// Add the default stream representation only
size_t reprIndex{adp->GetRepresentations().size()};
uint32_t uniqueId{adpIndex};
uniqueId |= reprIndex << 16;
AddStream(adp, defaultRepr, true, uniqueId, audioLanguageOrig);
}
}
return true;
}
void SESSION::CSession::AddStream(PLAYLIST::CAdaptationSet* adp,
PLAYLIST::CRepresentation* initialRepr,
bool isDefaultRepr,
uint32_t uniqueId,
std::string_view audioLanguageOrig)
{
m_streams.push_back(std::make_unique<CStream>(m_adaptiveTree, adp, initialRepr));
CStream& stream{*m_streams.back()};
uint32_t flags{INPUTSTREAM_FLAG_NONE};
stream.m_info.SetName(adp->GetName());
switch (adp->GetStreamType())
{
case StreamType::VIDEO:
{
stream.m_info.SetStreamType(INPUTSTREAM_TYPE_VIDEO);
if (isDefaultRepr)
flags |= INPUTSTREAM_FLAG_DEFAULT;
break;
}
case StreamType::AUDIO:
{
stream.m_info.SetStreamType(INPUTSTREAM_TYPE_AUDIO);
if (adp->IsImpaired())
flags |= INPUTSTREAM_FLAG_VISUAL_IMPAIRED;
if (adp->IsDefault())
flags |= INPUTSTREAM_FLAG_DEFAULT;
if (adp->IsOriginal() || (!audioLanguageOrig.empty() &&
adp->GetLanguage() == audioLanguageOrig))
{
flags |= INPUTSTREAM_FLAG_ORIGINAL;
}
break;
}
case StreamType::SUBTITLE:
{
stream.m_info.SetStreamType(INPUTSTREAM_TYPE_SUBTITLE);
if (adp->IsImpaired())
flags |= INPUTSTREAM_FLAG_HEARING_IMPAIRED;
if (adp->IsForced())
flags |= INPUTSTREAM_FLAG_FORCED;
if (adp->IsDefault())
flags |= INPUTSTREAM_FLAG_DEFAULT;
break;
}
default:
break;
}
stream.m_info.SetFlags(flags);
stream.m_info.SetPhysicalIndex(uniqueId);
std::string langCode = adp->GetLanguage();
if (langCode.empty() && stream.m_info.GetStreamType() != INPUTSTREAM_TYPE_VIDEO)
langCode = LANG_CODE::UNDETERMINED;
stream.m_info.SetLanguage(langCode);
stream.m_info.ClearExtraData();
stream.m_info.SetFeatures(0);
stream.m_adStream.set_observer(dynamic_cast<adaptive::AdaptiveStreamObserver*>(this));
UpdateStream(stream);
}
void SESSION::CSession::UpdateStream(CStream& stream)
{
// On this method we set stream info provided by manifest parsing, but these info could be
// changed by sample readers just before the start of playback by using GetInformation() methods
const StreamType streamType = stream.m_adStream.getAdaptationSet()->GetStreamType();
CRepresentation* rep{stream.m_adStream.getRepresentation()};
if (rep->GetContainerType() == ContainerType::INVALID)
{
LOG::LogF(LOGERROR, "Container type not valid on stream representation ID: %s",
rep->GetId().data());
stream.m_isValid = false;
return;
}
stream.m_isEncrypted = rep->GetPsshSetPos() != PSSHSET_POS_DEFAULT;
stream.m_info.SetExtraData(nullptr, 0);
if (!rep->GetCodecPrivateData().empty())
stream.m_info.SetExtraData(rep->GetCodecPrivateData());
stream.m_info.SetCodecFourCC(0);
stream.m_info.SetBitRate(rep->GetBandwidth());
const std::set<std::string>& codecs = rep->GetCodecs();
// Original codec string
std::string codecStr;
if (streamType == StreamType::VIDEO)
{
stream.m_info.SetWidth(static_cast<uint32_t>(rep->GetWidth()));
stream.m_info.SetHeight(static_cast<uint32_t>(rep->GetHeight()));
stream.m_info.SetAspect(rep->GetAspectRatio());
if (stream.m_info.GetAspect() == 0.0f && stream.m_info.GetHeight())
stream.m_info.SetAspect(static_cast<float>(stream.m_info.GetWidth()) /
stream.m_info.GetHeight());
stream.m_info.SetFpsRate(rep->GetFrameRate());
stream.m_info.SetFpsScale(rep->GetFrameRateScale());
stream.m_info.SetColorSpace(INPUTSTREAM_COLORSPACE_UNSPECIFIED);
stream.m_info.SetColorRange(INPUTSTREAM_COLORRANGE_UNKNOWN);
stream.m_info.SetColorPrimaries(INPUTSTREAM_COLORPRIMARY_UNSPECIFIED);
stream.m_info.SetColorTransferCharacteristic(INPUTSTREAM_COLORTRC_UNSPECIFIED);
if (CODEC::Contains(codecs, CODEC::FOURCC_AVC_, codecStr) ||
CODEC::Contains(codecs, CODEC::FOURCC_H264, codecStr))
{
stream.m_info.SetCodecName(CODEC::NAME_H264);
if (STRING::Contains(codecStr, CODEC::FOURCC_AVC1))
stream.m_info.SetCodecFourCC(CODEC::MakeFourCC(CODEC::FOURCC_AVC1));
else if (STRING::Contains(codecStr, CODEC::FOURCC_AVC2))
stream.m_info.SetCodecFourCC(CODEC::MakeFourCC(CODEC::FOURCC_AVC2));
else if (STRING::Contains(codecStr, CODEC::FOURCC_AVC3))
stream.m_info.SetCodecFourCC(CODEC::MakeFourCC(CODEC::FOURCC_AVC3));
else if (STRING::Contains(codecStr, CODEC::FOURCC_AVC4))
stream.m_info.SetCodecFourCC(CODEC::MakeFourCC(CODEC::FOURCC_AVC4));
}
else if (CODEC::Contains(codecs, CODEC::FOURCC_HEVC, codecStr))
stream.m_info.SetCodecName(CODEC::NAME_HEVC);
else if (CODEC::Contains(codecs, CODEC::FOURCC_HVC1, codecStr))
{
stream.m_info.SetCodecName(CODEC::NAME_HEVC);
stream.m_info.SetCodecFourCC(CODEC::MakeFourCC(CODEC::FOURCC_HVC1));
}
else if (CODEC::Contains(codecs, CODEC::FOURCC_DVH1, codecStr))
{
stream.m_info.SetCodecName(CODEC::NAME_HEVC);
stream.m_info.SetCodecFourCC(CODEC::MakeFourCC(CODEC::FOURCC_DVH1));
}
else if (CODEC::Contains(codecs, CODEC::FOURCC_HEV1, codecStr))
{
stream.m_info.SetCodecName(CODEC::NAME_HEVC);
stream.m_info.SetCodecFourCC(CODEC::MakeFourCC(CODEC::FOURCC_HEV1));
}
else if (CODEC::Contains(codecs, CODEC::FOURCC_DVHE, codecStr))
{
stream.m_info.SetCodecName(CODEC::NAME_HEVC);
stream.m_info.SetCodecFourCC(CODEC::MakeFourCC(CODEC::FOURCC_DVHE));
}
else if (CODEC::Contains(codecs, CODEC::FOURCC_VP09, codecStr) ||
CODEC::Contains(codecs, CODEC::NAME_VP9, codecStr)) // Some streams incorrectly use the name
{
stream.m_info.SetCodecName(CODEC::NAME_VP9);
if (STRING::Contains(codecStr, "."))
{
int codecProfileNum = STRING::ToInt32(codecStr.substr(codecStr.find('.') + 1));
switch (codecProfileNum)
{
case 0:
stream.m_info.SetCodecProfile(STREAMCODEC_PROFILE::VP9CodecProfile0);
break;
case 1:
stream.m_info.SetCodecProfile(STREAMCODEC_PROFILE::VP9CodecProfile1);
break;
case 2:
stream.m_info.SetCodecProfile(STREAMCODEC_PROFILE::VP9CodecProfile2);
break;
case 3:
stream.m_info.SetCodecProfile(STREAMCODEC_PROFILE::VP9CodecProfile3);
break;
default:
LOG::LogF(LOGWARNING, "Unhandled video codec profile \"%i\" for codec string: %s",
codecProfileNum, codecStr.c_str());
break;
}
}
}
else if (CODEC::Contains(codecs, CODEC::FOURCC_AV01, codecStr) ||
CODEC::Contains(codecs, CODEC::NAME_AV1, codecStr)) // Some streams incorrectly use the name
stream.m_info.SetCodecName(CODEC::NAME_AV1);
else
{
stream.m_isValid = false;
LOG::LogF(LOGERROR, "Unhandled video codec");
}
}
else if (streamType == StreamType::AUDIO)
{
stream.m_info.SetSampleRate(rep->GetSampleRate());
stream.m_info.SetChannels(rep->GetAudioChannels());
if (CODEC::Contains(codecs, CODEC::FOURCC_MP4A, codecStr) ||
CODEC::Contains(codecs, CODEC::FOURCC_AAC_, codecStr))
stream.m_info.SetCodecName(CODEC::NAME_AAC);
else if (CODEC::Contains(codecs, CODEC::FOURCC_DTS_, codecStr))
stream.m_info.SetCodecName(CODEC::NAME_DTS);
else if (CODEC::Contains(codecs, CODEC::FOURCC_AC_3, codecStr))
stream.m_info.SetCodecName(CODEC::NAME_AC3);
else if (CODEC::Contains(codecs, CODEC::FOURCC_EC_3, codecStr))
{
stream.m_info.SetCodecName(CODEC::NAME_EAC3);
if (CODEC::Contains(codecs, CODEC::NAME_EAC3_JOC))
stream.m_info.SetCodecProfile(STREAMCODEC_PROFILE::DDPlusCodecProfileAtmos);
}
else if (CODEC::Contains(codecs, CODEC::FOURCC_OPUS, codecStr))
stream.m_info.SetCodecName(CODEC::NAME_OPUS);
else if (CODEC::Contains(codecs, CODEC::FOURCC_VORB, codecStr) || // Find "vorb" and "vorbis" case
CODEC::Contains(codecs, CODEC::FOURCC_VORB1, codecStr) ||
CODEC::Contains(codecs, CODEC::FOURCC_VORB1P, codecStr) ||
CODEC::Contains(codecs, CODEC::FOURCC_VORB2, codecStr) ||
CODEC::Contains(codecs, CODEC::FOURCC_VORB2P, codecStr) ||
CODEC::Contains(codecs, CODEC::FOURCC_VORB3, codecStr) ||
CODEC::Contains(codecs, CODEC::FOURCC_VORB3P, codecStr))
stream.m_info.SetCodecName(CODEC::NAME_VORBIS);
else
{
stream.m_isValid = false;
LOG::LogF(LOGERROR, "Unhandled audio codec");
}
}
else if (streamType == StreamType::SUBTITLE)
{
if (CODEC::Contains(codecs, CODEC::FOURCC_TTML, codecStr) ||
CODEC::Contains(codecs, CODEC::FOURCC_DFXP, codecStr) ||
CODEC::Contains(codecs, CODEC::FOURCC_STPP, codecStr))
stream.m_info.SetCodecName(CODEC::NAME_SRT); // We convert it to SRT, Kodi dont support TTML yet
else if (CODEC::Contains(codecs, CODEC::FOURCC_WVTT, codecStr))
stream.m_info.SetCodecName(CODEC::NAME_WEBVTT);
else
{
stream.m_isValid = false;
LOG::LogF(LOGERROR, "Unhandled subtitle codec");
}
}
// Internal codec name can be used by Kodi to detect the codec name to be shown in the GUI track list
stream.m_info.SetCodecInternalName(codecStr);
}
void SESSION::CSession::PrepareStream(CStream* stream)
{
if (!m_adaptiveTree->IsReqPrepareStream())
return;
CRepresentation* repr = stream->m_adStream.getRepresentation();
const EVENT_TYPE startEvent = stream->m_adStream.GetStartEvent();
// Prepare the representation when the period change usually its not needed,
// because the timeline is always already updated
if ((!m_adaptiveTree->IsChangingPeriod() || repr->Timeline().IsEmpty()) &&
(startEvent == EVENT_TYPE::STREAM_START || startEvent == EVENT_TYPE::STREAM_ENABLE))
{
m_adaptiveTree->PrepareRepresentation(stream->m_adStream.getPeriod(),
stream->m_adStream.getAdaptationSet(), repr);
}
if (stream->m_adStream.getPeriod()->GetEncryptionState() == EncryptionState::ENCRYPTED_DRM)
{
InitializeDRM();
}
stream->m_isEncrypted = repr->GetPsshSetPos() != PSSHSET_POS_DEFAULT;
}
void CSession::EnableStream(CStream* stream, bool enable)
{
if (enable)
{
if (!m_timingStream)
m_timingStream = stream;
stream->m_isEnabled = true;
}
else
{
if (stream == m_timingStream)
m_timingStream = nullptr;
stream->Disable();
}
}
bool SESSION::CSession::IsCDMSessionSecurePath(size_t index)
{
if (index >= m_cdmSessions.size())
{
LOG::LogF(LOGERROR, "No CDM session at index %u", index);
return false;
}
return (m_cdmSessions[index].m_decrypterCaps.flags &
DRM::DecrypterCapabilites::SSD_SECURE_PATH) != 0;
}
std::string SESSION::CSession::GetCDMSession(unsigned int index)
{
if (index >= m_cdmSessions.size())
{
LOG::LogF(LOGERROR, "No CDM session at index %u", index);
return {};
}
return m_cdmSessions[index].m_sessionId;
}
std::shared_ptr<Adaptive_CencSingleSampleDecrypter> SESSION::CSession::GetSingleSampleDecryptor(
unsigned int index) const
{
if (index >= m_cdmSessions.size())
{
LOG::LogF(LOGERROR, "Index %u out of range, cannot get single sample decrypter", index);
return nullptr;
}
return m_cdmSessions[index].m_cencSingleSampleDecrypter;
}
uint64_t SESSION::CSession::PTSToElapsed(uint64_t pts)
{
if (m_timingStream)
{
ISampleReader* timingReader{m_timingStream->GetReader()};
if (!timingReader)
{
LOG::LogF(LOGERROR, "Cannot get the stream sample reader");
return 0;
}
// adjusted pts value taking the difference between segment's pts and reader pts
int64_t manifest_time{static_cast<int64_t>(pts) - timingReader->GetPTSDiff()};
if (manifest_time < 0)
manifest_time = 0;
if (static_cast<uint64_t>(manifest_time) > m_timingStream->m_adStream.GetAbsolutePTSOffset())
return static_cast<uint64_t>(manifest_time) -
m_timingStream->m_adStream.GetAbsolutePTSOffset();
return 0ULL;
}
else
return pts;
}
uint64_t SESSION::CSession::GetTimeshiftBufferStart()
{
if (m_timingStream)
{
ISampleReader* timingReader{m_timingStream->GetReader()};
if (!timingReader)
{
LOG::LogF(LOGERROR, "Cannot get the stream sample reader");
return 0ULL;
}
return m_timingStream->m_adStream.GetAbsolutePTSOffset() + timingReader->GetPTSDiff();
}
else
return 0ULL;
}
// TODO: clean this up along with seektime
void SESSION::CSession::StartReader(
CStream* stream, uint64_t seekTime, int64_t ptsDiff, bool preceeding, bool timing)
{
ISampleReader* streamReader = stream->GetReader();
if (!streamReader)
{
LOG::LogF(LOGERROR, "Cannot get the stream reader");
return;
}
bool bReset = true;
if (timing)
seekTime += stream->m_adStream.GetAbsolutePTSOffset();
else
seekTime -= ptsDiff;
stream->m_adStream.seek_time(static_cast<double>(seekTime / STREAM_TIME_BASE), preceeding,
bReset);