-
Notifications
You must be signed in to change notification settings - Fork 0
/
fragmentcollector_mpd.cpp
12906 lines (12121 loc) · 435 KB
/
fragmentcollector_mpd.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
/*
* If not stated otherwise in this file or this component's license file the
* following copyright and licenses apply:
*
* Copyright 2018 RDK Management
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file fragmentcollector_mpd.cpp
* @brief Fragment collector implementation of MPEG DASH
*/
#include "iso639map.h"
#include "fragmentcollector_mpd.h"
#include "MediaStreamContext.h"
#include "AampFnLogger.h"
#include "priv_aamp.h"
#include "AampDRMSessionManager.h"
#include "AampConstants.h"
#include "SubtecFactory.hpp"
#include <stdlib.h>
#include <string.h>
#include "_base64.h"
#include <pthread.h>
#include <signal.h>
#include <assert.h>
#include <unistd.h>
#include <set>
#include <iomanip>
#include <ctime>
#include <inttypes.h>
#include <libxml/xmlreader.h>
#include <math.h>
#include <cmath> // For double abs(double)
#include <algorithm>
#include <cctype>
#include <regex>
#include "AampCacheHandler.h"
#include "AampUtils.h"
#include "AampRfc.h"
#include <chrono>
//#define DEBUG_TIMELINE
#ifdef AAMP_CC_ENABLED
#include "AampCCManager.h"
#endif
/**
* @addtogroup AAMP_COMMON_TYPES
*/
#define SEGMENT_COUNT_FOR_ABR_CHECK 5
#define DEFAULT_INTERVAL_BETWEEN_MPD_UPDATES_MS 3000
#define TIMELINE_START_RESET_DIFF 4000000000
#define MAX_DELAY_BETWEEN_MPD_UPDATE_MS (6000)
#define MIN_DELAY_BETWEEN_MPD_UPDATE_MS (500) // 500mSec
#define MIN_TSB_BUFFER_DEPTH 6 //6 seconds from 4.3.3.2.2 in https://dashif.org/docs/DASH-IF-IOP-v4.2-clean.htm
#define VSS_DASH_EARLY_AVAILABLE_PERIOD_PREFIX "vss-"
#define FOG_INSERTED_PERIOD_ID_PREFIX "FogPeriod"
#define INVALID_VOD_DURATION (0)
/**
* Macros for extended audio codec check as per ETSI-TS-103-420-V1.2.1
*/
#define SUPPLEMENTAL_PROPERTY_TAG "SupplementalProperty"
#define SCHEME_ID_URI_EC3_EXT_CODEC "tag:dolby.com,2018:dash:EC3_ExtensionType:2018"
#define EC3_EXT_VALUE_AUDIO_ATMOS "JOC"
#define MEDIATYPE_VIDEO "video"
#define MEDIATYPE_AUDIO "audio"
#define MEDIATYPE_TEXT "text"
#define MEDIATYPE_AUX_AUDIO "aux-audio"
#define MEDIATYPE_IMAGE "image"
// weights used for autio/subtitle track-selection heuristic
#define AAMP_LANGUAGE_SCORE 1000000000ULL /**< Top priority: matching language **/
#define AAMP_SCHEME_ID_SCORE 100000000ULL /**< 2nd priority to scheme id matching **/
#define AAMP_LABEL_SCORE 10000000ULL /**< 3rd priority to label matching **/
#define AAMP_ROLE_SCORE 1000000ULL /**< 4th priority to role/rendition matching **/
#define AAMP_TYPE_SCORE 100000ULL /**< 5th priority to type matching **/
#define AAMP_CODEC_SCORE 1000ULL /**< Lowest priority: matchng codec **/
static double ParseISO8601Duration(const char *ptr);
static double ComputeFragmentDuration( uint32_t duration, uint32_t timeScale )
{
FN_TRACE_F_MPD( __FUNCTION__ );
double newduration = 2.0;
if( duration && timeScale )
{
newduration = (double)duration / (double)timeScale;
return newduration;
}
AAMPLOG_WARN( "bad fragment duration");
return newduration;
}
/**
* @class PeriodElement
* @brief Consists Adaptation Set and representation-specific parts
*/
class PeriodElement
{ // Common (Adaptation Set) and representation-specific parts
private:
const IRepresentation *pRepresentation; // primary (representation)
const IAdaptationSet *pAdaptationSet; // secondary (adaptation set)
public:
PeriodElement(const PeriodElement &other) = delete;
PeriodElement& operator=(const PeriodElement& other) = delete;
PeriodElement(const IAdaptationSet *adaptationSet, const IRepresentation *representation ):
pAdaptationSet(NULL),pRepresentation(NULL)
{
pRepresentation = representation;
pAdaptationSet = adaptationSet;
}
~PeriodElement()
{
}
std::string GetMimeType()
{
FN_TRACE_F_MPD( __FUNCTION__ );
std::string mimeType;
if( pAdaptationSet ) mimeType = pAdaptationSet->GetMimeType();
if( mimeType.empty() && pRepresentation ) mimeType = pRepresentation->GetMimeType();
return mimeType;
}
};//PerioidElement
/**
* @class SegmentTemplates
* @brief Handles operation and information on segment template from manifest
*/
class SegmentTemplates
{ // SegmentTemplate can be split info common (Adaptation Set) and representation-specific parts
private:
const ISegmentTemplate *segmentTemplate1; // primary (representation)
const ISegmentTemplate *segmentTemplate2; // secondary (adaptation set)
public:
SegmentTemplates(const SegmentTemplates &other) = delete;
SegmentTemplates& operator=(const SegmentTemplates& other) = delete;
SegmentTemplates( const ISegmentTemplate *representation, const ISegmentTemplate *adaptationSet ) : segmentTemplate1(0),segmentTemplate2(0)
{
segmentTemplate1 = representation;
segmentTemplate2 = adaptationSet;
}
~SegmentTemplates()
{
}
bool HasSegmentTemplate()
{
FN_TRACE_F_MPD( __FUNCTION__ );
return segmentTemplate1 || segmentTemplate2;
}
std::string Getmedia()
{
FN_TRACE_F_MPD( __FUNCTION__ );
std::string media;
if( segmentTemplate1 ) media = segmentTemplate1->Getmedia();
if( media.empty() && segmentTemplate2 ) media = segmentTemplate2->Getmedia();
return media;
}
const ISegmentTimeline *GetSegmentTimeline()
{
FN_TRACE_F_MPD( __FUNCTION__ );
const ISegmentTimeline *segmentTimeline = NULL;
if( segmentTemplate1 ) segmentTimeline = segmentTemplate1->GetSegmentTimeline();
if( !segmentTimeline && segmentTemplate2 ) segmentTimeline = segmentTemplate2->GetSegmentTimeline();
return segmentTimeline;
}
uint32_t GetTimescale()
{
//FN_TRACE_F_MPD( __FUNCTION__ );
uint32_t timeScale = 0;
if( segmentTemplate1 ) timeScale = segmentTemplate1->GetTimescale();
// if timescale missing in template ,GetTimeScale returns 1
if((timeScale==1 || timeScale==0) && segmentTemplate2 ) timeScale = segmentTemplate2->GetTimescale();
return timeScale;
}
uint32_t GetDuration()
{
//FN_TRACE_F_MPD( __FUNCTION__ );
uint32_t duration = 0;
if( segmentTemplate1 ) duration = segmentTemplate1->GetDuration();
if( duration==0 && segmentTemplate2 ) duration = segmentTemplate2->GetDuration();
return duration;
}
long GetStartNumber()
{
FN_TRACE_F_MPD( __FUNCTION__ );
long startNumber = 0;
if( segmentTemplate1 ) startNumber = segmentTemplate1->GetStartNumber();
if( startNumber==0 && segmentTemplate2 ) startNumber = segmentTemplate2->GetStartNumber();
return startNumber;
}
uint64_t GetPresentationTimeOffset()
{
FN_TRACE_F_MPD( __FUNCTION__ );
uint64_t presentationOffset = 0;
if(segmentTemplate1 ) presentationOffset = segmentTemplate1->GetPresentationTimeOffset();
if( presentationOffset==0 && segmentTemplate2) presentationOffset = segmentTemplate2->GetPresentationTimeOffset();
return presentationOffset;
}
std::string Getinitialization()
{
FN_TRACE_F_MPD( __FUNCTION__ );
std::string initialization;
if( segmentTemplate1 ) initialization = segmentTemplate1->Getinitialization();
if( initialization.empty() && segmentTemplate2 ) initialization = segmentTemplate2->Getinitialization();
return initialization;
}
}; // SegmentTemplates
/**
* @class HeaderFetchParams
* @brief Holds information regarding initialization fragment
*/
class HeaderFetchParams
{
public:
HeaderFetchParams() : context(NULL), pMediaStreamContext(NULL), initialization(""), fragmentduration(0),
isinitialization(false), discontinuity(false)
{
}
HeaderFetchParams(const HeaderFetchParams&) = delete;
HeaderFetchParams& operator=(const HeaderFetchParams&) = delete;
class StreamAbstractionAAMP_MPD *context;
class MediaStreamContext *pMediaStreamContext;
string initialization;
double fragmentduration;
bool isinitialization;
bool discontinuity;
};
/**
* @class FragmentDownloadParams
* @brief Holds data of fragment to be downloaded
*/
class FragmentDownloadParams
{
public:
class StreamAbstractionAAMP_MPD *context;
class MediaStreamContext *pMediaStreamContext;
bool playingLastPeriod;
long long lastPlaylistUpdateMS;
};
static bool IsIframeTrack(IAdaptationSet *adaptationSet);
/**
* @brief StreamAbstractionAAMP_MPD Constructor
*/
StreamAbstractionAAMP_MPD::StreamAbstractionAAMP_MPD(AampLogManager *logObj, class PrivateInstanceAAMP *aamp,double seek_pos, float rate): StreamAbstractionAAMP(logObj, aamp),
fragmentCollectorThreadStarted(false), mLangList(), seekPosition(seek_pos), rate(rate), fragmentCollectorThreadID(),
mpd(NULL), mNumberOfTracks(0), mCurrentPeriodIdx(0), mEndPosition(0), mIsLiveStream(true), mIsLiveManifest(true),
mStreamInfo(NULL), mPrevStartTimeSeconds(0), mPrevLastSegurlMedia(""), mPrevLastSegurlOffset(0),
mPeriodEndTime(0), mPeriodStartTime(0), mPeriodDuration(0), mMinUpdateDurationMs(DEFAULT_INTERVAL_BETWEEN_MPD_UPDATES_MS),
mLastPlaylistDownloadTimeMs(0), mFirstPTS(0), mStartTimeOfFirstPTS(0), mAudioType(eAUDIO_UNKNOWN),
mPrevAdaptationSetCount(0), mBitrateIndexVector(), mProfileMaps(), mIsFogTSB(false),
mCurrentPeriod(NULL), mBasePeriodId(""), mBasePeriodOffset(0), mCdaiObject(NULL), mLiveEndPosition(0), mCulledSeconds(0)
,mAdPlayingFromCDN(false)
,mMaxTSBBandwidth(0), mTSBDepth(0)
,mVideoPosRemainder(0)
,mPresentationOffsetDelay(0)
,mUpdateStreamInfo(false)
,mAvailabilityStartTime(0)
,mFirstPeriodStartTime(0)
,mDrmPrefs({{CLEARKEY_UUID, 1}, {WIDEVINE_UUID, 2}, {PLAYREADY_UUID, 3}})// Default values, may get changed due to config file
,mCommonKeyDuration(0), mEarlyAvailablePeriodIds(), thumbnailtrack(), indexedTileInfo()
,mMaxTracks(0)
,mServerUtcTime(0)
,mDeltaTime(0)
,mHasServerUtcTime(false)
,latencyMonitorThreadStarted(false),prevLatencyStatus(LATENCY_STATUS_UNKNOWN),latencyStatus(LATENCY_STATUS_UNKNOWN),latencyMonitorThreadID()
,mStreamLock()
,mProfileCount(0)
,playlistMutex(), mIterPeriodIndex(0), mNumberOfPeriods(0)
,mUpperBoundaryPeriod(0), mLowerBoundaryPeriod(0), playlistDownloaderThreadStarted(false)
,mLiveTimeFragmentSync(false)
,mSubtitleParser()
,mLicensePrefetcher(logObj, aamp, this)
,mMultiVideoAdaptationPresent(false)
{
FN_TRACE_F_MPD( __FUNCTION__ );
this->aamp = aamp;
memset(&mMediaStreamContext, 0, sizeof(mMediaStreamContext));
for (int i=0; i<AAMP_TRACK_COUNT; i++)
{
mFirstFragPTS[i] = 0.0;
}
GetABRManager().clearProfiles();
mLastPlaylistDownloadTimeMs = aamp_GetCurrentTimeMS();
// setup DRM prefs from config
int highestPref = 0;
#if 0
std::vector<std::string> values;
if (gpGlobalConfig->getMatchingUnknownKeys("drm-preference.", values))
{
for(auto&& item : values)
{
int i = atoi(item.substr(item.find(".") + 1).c_str());
mDrmPrefs[gpGlobalConfig->getUnknownValue(item)] = i;
if (i > highestPref)
{
highestPref = i;
}
}
}
#endif
// Get the highest number
for (auto const& pair: mDrmPrefs)
{
if(pair.second > highestPref)
{
highestPref = pair.second;
}
}
// Give preference based on GetPreferredDRM.
switch (aamp->GetPreferredDRM())
{
case eDRM_WideVine:
{
AAMPLOG_INFO("DRM Selected: WideVine");
mDrmPrefs[WIDEVINE_UUID] = highestPref+1;
}
break;
case eDRM_ClearKey:
{
AAMPLOG_INFO("DRM Selected: ClearKey");
mDrmPrefs[CLEARKEY_UUID] = highestPref+1;
}
break;
case eDRM_PlayReady:
default:
{
AAMPLOG_INFO("DRM Selected: PlayReady");
mDrmPrefs[PLAYREADY_UUID] = highestPref+1;
}
break;
}
AAMPLOG_INFO("DRM prefs");
for (auto const& pair: mDrmPrefs) {
AAMPLOG_INFO("{ %s, %d }", pair.first.c_str(), pair.second);
}
trickplayMode = (rate != AAMP_NORMAL_PLAY_RATE);
}
static void GetBitrateInfoFromCustomMpd( const IAdaptationSet *adaptationSet, std::vector<Representation *>& representations );
/**
* @brief Check if mime type is compatible with media type
* @param mimeType mime type
* @param mediaType media type
* @retval true if compatible
*/
static bool IsCompatibleMimeType(const std::string& mimeType, MediaType mediaType)
{
//FN_TRACE_F_MPD( __FUNCTION__ );
bool isCompatible = false;
switch ( mediaType )
{
case eMEDIATYPE_VIDEO:
if (mimeType == "video/mp4")
isCompatible = true;
break;
case eMEDIATYPE_AUDIO:
case eMEDIATYPE_AUX_AUDIO:
if ((mimeType == "audio/webm") ||
(mimeType == "audio/mp4"))
isCompatible = true;
break;
case eMEDIATYPE_SUBTITLE:
if ((mimeType == "application/ttml+xml") ||
(mimeType == "text/vtt") ||
(mimeType == "application/mp4"))
isCompatible = true;
break;
default:
break;
}
return isCompatible;
}
/**
* @brief Get Additional tag property value from any child node of MPD
* @param nodePtr Pointer to MPD child node, Tage Name , Property Name,
* SchemeIdUri (if the propery mapped against scheme Id , default value is empty)
* @retval return the property name if found, if not found return empty string
*/
static bool IsAtmosAudio(const IMPDElement *nodePtr)
{
FN_TRACE_F_MPD( __FUNCTION__ );
bool isAtmos = false;
if (!nodePtr){
AAMPLOG_ERR("API Failed due to Invalid Arguments");
}else{
std::vector<INode*> childNodeList = nodePtr->GetAdditionalSubNodes();
for (size_t j=0; j < childNodeList.size(); j++) {
INode* childNode = childNodeList.at(j);
const std::string& name = childNode->GetName();
if (name == SUPPLEMENTAL_PROPERTY_TAG ) {
if (childNode->HasAttribute("schemeIdUri")){
const std::string& schemeIdUri = childNode->GetAttributeValue("schemeIdUri");
if (schemeIdUri == SCHEME_ID_URI_EC3_EXT_CODEC ){
if (childNode->HasAttribute("value")) {
std::string value = childNode->GetAttributeValue("value");
AAMPLOG_INFO("Recieved %s tag property value as %s ",
SUPPLEMENTAL_PROPERTY_TAG, value.c_str());
if (value == EC3_EXT_VALUE_AUDIO_ATMOS){
isAtmos = true;
break;
}
}
}
else
{
AAMPLOG_WARN("schemeIdUri is not equals to SCHEME_ID_URI_EC3_EXT_CODEC "); //CID:84346 - Null Returns
}
}
}
}
}
return isAtmos;
}
/**
* @brief Get codec value from representation level
* @param[out] codecValue - string value of codec as per manifest
* @param[in] rep - representation node for atmos audio check
* @retval audio type as per aamp code from string value
*/
static AudioType getCodecType(string & codecValue, const IMPDElement *rep)
{
AudioType audioType = eAUDIO_UNSUPPORTED;
std::string ac4 = "ac-4";
if (codecValue == "ec+3")
{
#ifndef __APPLE__
audioType = eAUDIO_ATMOS;
#endif
}
else if (!codecValue.compare(0, ac4.size(), ac4))
{
audioType = eAUDIO_DOLBYAC4;
}
else if ((codecValue == "ac-3"))
{
audioType = eAUDIO_DOLBYAC3;
}
else if ((codecValue == "ec-3"))
{
audioType = eAUDIO_DDPLUS;
/*
* check whether ATMOS Flag is set as per ETSI TS 103 420
*/
if (IsAtmosAudio(rep))
{
AAMPLOG_INFO("Setting audio codec as eAUDIO_ATMOS as per ETSI TS 103 420");
audioType = eAUDIO_ATMOS;
}
}
else if( codecValue == "opus" || codecValue.find("vorbis") != std::string::npos )
{
audioType = eAUDIO_UNSUPPORTED;
}
else if( codecValue == "aac" || codecValue.find("mp4") != std::string::npos )
{
audioType = eAUDIO_AAC;
}
return audioType;
}
/**
* @brief Get representation index from preferred codec list
* @retval whether track selected or not
*/
bool StreamAbstractionAAMP_MPD::GetPreferredCodecIndex(IAdaptationSet *adaptationSet, int &selectedRepIdx, AudioType &selectedCodecType,
uint32_t &selectedRepBandwidth, uint32_t &bestScore, bool disableEC3, bool disableATMOS, bool disableAC4, bool disableAC3, bool& disabled)
{
FN_TRACE_F_MPD( __FUNCTION__ );
bool isTrackSelected = false;
if( aamp->preferredCodecList.size() > 0 )
{
selectedRepIdx = -1;
if(adaptationSet != NULL)
{
uint32_t score = 0;
const std::vector<IRepresentation *> representation = adaptationSet->GetRepresentation();
/* check for codec defined in Adaptation Set */
const std::vector<string> adapCodecs = adaptationSet->GetCodecs();
for (int representationIndex = 0; representationIndex < representation.size(); representationIndex++)
{
score = 0;
const dash::mpd::IRepresentation *rep = representation.at(representationIndex);
uint32_t bandwidth = rep->GetBandwidth();
const std::vector<string> codecs = rep->GetCodecs();
AudioType audioType = eAUDIO_UNKNOWN;
string codecValue="";
/* check if Representation includec codec */
if(codecs.size())
{
codecValue=codecs.at(0);
}
else if(adapCodecs.size()) /* else check if Adaptation has codec defined */
{
codecValue = adapCodecs.at(0);
}
auto iter = std::find(aamp->preferredCodecList.begin(), aamp->preferredCodecList.end(), codecValue);
if(iter != aamp->preferredCodecList.end())
{ /* track is in preferred codec list */
int distance = std::distance(aamp->preferredCodecList.begin(),iter);
score = ((aamp->preferredCodecList.size()-distance)) * AAMP_CODEC_SCORE; /* bonus for codec match */
}
AudioType codecType = getCodecType(codecValue, rep);
score += (uint32_t)codecType;
if (((codecType == eAUDIO_ATMOS) && (disableATMOS || disableEC3)) || /*ATMOS audio desable by config */
((codecType == eAUDIO_DDPLUS) && disableEC3) || /* EC3 disable neglact it that case */
((codecType == eAUDIO_DOLBYAC4) && disableAC4) || /** Disable AC4 **/
((codecType == eAUDIO_DOLBYAC3) && disableAC3) ) /**< Disable AC3 **/
{
//Reduce score to 0 since ATMOS and/or DDPLUS is disabled;
score = 0;
}
if(( score > bestScore ) || /* better matching codec */
((score == bestScore ) && (bandwidth > selectedRepBandwidth) && isTrackSelected )) /* Same codec as selected track but better quality */
{
bestScore = score;
selectedRepIdx = representationIndex;
selectedRepBandwidth = bandwidth;
selectedCodecType = codecType;
isTrackSelected = true;
}
} //representation Loop
if (score == 0)
{
/**< No valid representation found here */
disabled = true;
}
} //If valid adaptation
} // If preferred Codec Set
return isTrackSelected;
}
/**
* @brief Get representation index from preferred codec list
* @retval whether track selected or not
*/
void StreamAbstractionAAMP_MPD::GetPreferredTextRepresentation(IAdaptationSet *adaptationSet, int &selectedRepIdx, uint32_t &selectedRepBandwidth, unsigned long long &score, std::string &name, std::string &codec)
{
if(adaptationSet != NULL)
{
selectedRepBandwidth = 0;
selectedRepIdx = 0;
/* check for codec defined in Adaptation Set */
const std::vector<string> adapCodecs = adaptationSet->GetCodecs();
const std::vector<IRepresentation *> representation = adaptationSet->GetRepresentation();
for (int representationIndex = 0; representationIndex < representation.size(); representationIndex++)
{
const dash::mpd::IRepresentation *rep = representation.at(representationIndex);
uint32_t bandwidth = rep->GetBandwidth();
if (bandwidth > selectedRepBandwidth) /**< Get Best Rep based on bandwidth **/
{
selectedRepIdx = representationIndex;
selectedRepBandwidth = bandwidth;
score += 2; /**< Increase score by 2 if multiple track present*/
}
name = rep->GetId();
const std::vector<std::string> repCodecs = rep->GetCodecs();
// check if Representation includes codec
if (repCodecs.size())
{
codec = repCodecs.at(0);
}
else if (adapCodecs.size()) // else check if Adaptation has codec
{
codec = adapCodecs.at(0);
}
else
{
// For subtitle, it might be vtt/ttml format
PeriodElement periodElement(adaptationSet, rep);
codec = periodElement.GetMimeType();
}
}
}
AAMPLOG_INFO("StreamAbstractionAAMP_MPD: SelectedRepIndex : %d selectedRepBandwidth: %d", selectedRepIdx, selectedRepBandwidth);
}
static int GetDesiredCodecIndex(IAdaptationSet *adaptationSet, AudioType &selectedCodecType, uint32_t &selectedRepBandwidth,
bool disableEC3,bool disableATMOS, bool disableAC4,bool disableAC3, bool &disabled)
{
FN_TRACE_F_MPD( __FUNCTION__ );
int selectedRepIdx = -1;
if(adaptationSet != NULL)
{
const std::vector<IRepresentation *> representation = adaptationSet->GetRepresentation();
// check for codec defined in Adaptation Set
const std::vector<string> adapCodecs = adaptationSet->GetCodecs();
for (int representationIndex = 0; representationIndex < representation.size(); representationIndex++)
{
const dash::mpd::IRepresentation *rep = representation.at(representationIndex);
uint32_t bandwidth = rep->GetBandwidth();
const std::vector<string> codecs = rep->GetCodecs();
AudioType audioType = eAUDIO_UNKNOWN;
string codecValue="";
// check if Representation includec codec
if(codecs.size())
codecValue=codecs.at(0);
else if(adapCodecs.size()) // else check if Adaptation has codec defn
codecValue = adapCodecs.at(0);
// else no codec defined , go with unknown
#if defined(RPI)
if((codecValue == "ec+3") || (codecValue == "ec-3"))
continue;
#endif
audioType = getCodecType(codecValue, rep);
/*
* By default the audio profile selection priority is set as ATMOS then DD+ then AAC
* Note that this check comes after the check of selected language.
* disableATMOS: avoid use of ATMOS track
* disableEC3: avoid use of DDPLUS and ATMOS tracks
* disableAC4: avoid use if ATMOS AC4 tracks
*/
if ((selectedCodecType == eAUDIO_UNKNOWN && (audioType != eAUDIO_UNSUPPORTED || selectedRepBandwidth == 0)) || // Select any profile for the first time, reject unsupported streams then
(selectedCodecType == audioType && bandwidth>selectedRepBandwidth) || // same type but better quality
(selectedCodecType < eAUDIO_DOLBYAC4 && audioType == eAUDIO_DOLBYAC4 && !disableAC4 ) || // promote to AC4
(selectedCodecType < eAUDIO_ATMOS && audioType == eAUDIO_ATMOS && !disableATMOS && !disableEC3) || // promote to atmos
(selectedCodecType < eAUDIO_DDPLUS && audioType == eAUDIO_DDPLUS && !disableEC3) || // promote to ddplus
(selectedCodecType != eAUDIO_AAC && audioType == eAUDIO_AAC && disableEC3) || // force AAC
(selectedCodecType == eAUDIO_UNSUPPORTED) // anything better than nothing
)
{
selectedRepIdx = representationIndex;
selectedCodecType = audioType;
selectedRepBandwidth = bandwidth;
AAMPLOG_INFO("StreamAbstractionAAMP_MPD: SelectedRepIndex : %d ,selectedCodecType : %d, selectedRepBandwidth: %d", selectedRepIdx, selectedCodecType, selectedRepBandwidth);
}
}
}
else
{
AAMPLOG_WARN("adaptationSet is null"); //CID:85233 - Null Returns
}
return selectedRepIdx;
}
/**
* @brief Get representation index of desired video codec
* @param adaptationSet Adaptation set object
* @param[out] selectedRepIdx index of desired representation
* @retval index of desired representation
*/
static int GetDesiredVideoCodecIndex(IAdaptationSet *adaptationSet)
{
FN_TRACE_F_MPD( __FUNCTION__ );
const std::vector<IRepresentation *> representation = adaptationSet->GetRepresentation();
int selectedRepIdx = -1;
for (int representationIndex = 0; representationIndex < representation.size(); representationIndex++)
{
const dash::mpd::IRepresentation *rep = representation.at(representationIndex);
const std::vector<string> adapCodecs = adaptationSet->GetCodecs();
const std::vector<string> codecs = rep->GetCodecs();
string codecValue="";
if(codecs.size())
codecValue=codecs.at(0);
else if(adapCodecs.size())
codecValue = adapCodecs.at(0);
//Ignore vp8 and vp9 codec video profiles(webm)
if(codecValue.find("vp") == std::string::npos)
{
selectedRepIdx = representationIndex;
}
}
return selectedRepIdx;
}
/**
* @brief Return the name corresponding to the Media Type
* @param mediaType media type
* @retval the name of the mediaType
*/
static const char* getMediaTypeName( MediaType mediaType )
{
//FN_TRACE_F_MPD( __FUNCTION__ );
switch(mediaType)
{
case eMEDIATYPE_VIDEO:
return MEDIATYPE_VIDEO;
case eMEDIATYPE_AUDIO:
return MEDIATYPE_AUDIO;
case eMEDIATYPE_SUBTITLE:
return MEDIATYPE_TEXT;
case eMEDIATYPE_IMAGE:
return MEDIATYPE_IMAGE;
case eMEDIATYPE_AUX_AUDIO:
return MEDIATYPE_AUX_AUDIO;
default:
return NULL;
}
}
/**
* @brief Check if adaptation set is of a given media type
* @param adaptationSet adaptation set
* @param mediaType media type
* @retval true if adaptation set is of the given media type
*/
static bool IsContentType(const IAdaptationSet *adaptationSet, MediaType mediaType )
{
//FN_TRACE_F_MPD( __FUNCTION__ );
const char *name = getMediaTypeName(mediaType);
if(name != NULL)
{
if (adaptationSet->GetContentType() == name)
{
return true;
}
else if (adaptationSet->GetContentType() == "muxed")
{
AAMPLOG_WARN("excluding muxed content");
}
else
{
PeriodElement periodElement(adaptationSet, NULL);
if (IsCompatibleMimeType(periodElement.GetMimeType(), mediaType) )
{
return true;
}
const std::vector<IRepresentation *> &representation = adaptationSet->GetRepresentation();
for (int i = 0; i < representation.size(); i++)
{
const IRepresentation * rep = representation.at(i);
PeriodElement periodElement(adaptationSet, rep);
if (IsCompatibleMimeType(periodElement.GetMimeType(), mediaType) )
{
return true;
}
}
const std::vector<IContentComponent *>contentComponent = adaptationSet->GetContentComponent();
for( int i = 0; i < contentComponent.size(); i++)
{
if (contentComponent.at(i)->GetContentType() == name)
{
return true;
}
}
}
}
else
{
AAMPLOG_WARN("name is null"); //CID:86093 - Null Returns
}
return false;
}
/**
* @brief read unsigned 32 bit value and update buffer pointer
* @param[in] pptr buffer
* @retval 32 bit value
*/
static unsigned int Read32( const char **pptr)
{
const char *ptr = *pptr;
unsigned int rc = 0;
for (int i = 0; i < 4; i++)
{
rc <<= 8;
rc |= (unsigned char)*ptr++;
}
*pptr = ptr;
return rc;
}
/**
* @brief Parse segment index box
* @note The SegmentBase indexRange attribute points to Segment Index Box location with segments and random access points.
* @param start start of box
* @param size size of box
* @param segmentIndex segment index
* @param[out] referenced_size referenced size
* @param[out] referenced_duration referenced duration
* @retval true on success
*/
static bool ParseSegmentIndexBox( const char *start, size_t size, int segmentIndex, unsigned int *referenced_size, float *referenced_duration, unsigned int *firstOffset)
{
FN_TRACE_F_MPD( __FUNCTION__ );
if (!start)
{
// If the fragment pointer is NULL then return from here, no need to process it further.
return false;
}
const char **f = &start;
unsigned int len = Read32(f);
if (len != size)
{
AAMPLOG_WARN("Wrong size in ParseSegmentIndexBox %d found, %zu expected", len, size);
if (firstOffset) *firstOffset = 0;
return false;
}
unsigned int type = Read32(f);
if (type != 'sidx')
{
AAMPLOG_WARN("Wrong type in ParseSegmentIndexBox %c%c%c%c found, %zu expected",
(type >> 24) % 0xff, (type >> 16) & 0xff, (type >> 8) & 0xff, type & 0xff, size);
if (firstOffset) *firstOffset = 0;
return false;
}
unsigned int version = Read32(f);
unsigned int reference_ID = Read32(f);
unsigned int timescale = Read32(f);
unsigned int earliest_presentation_time = Read32(f);
unsigned int first_offset = Read32(f);
unsigned int count = Read32(f);
/* Avoid set but not used warnings. */
(void)version;
(void)reference_ID;
(void)timescale;
(void)earliest_presentation_time;
(void)first_offset;
(void)count;
if (firstOffset)
{
*firstOffset = first_offset;
return true;
}
if( segmentIndex<count )
{
start += 12*segmentIndex;
*referenced_size = Read32(f);
*referenced_duration = Read32(f)/(float)timescale;
unsigned int flags = Read32(f);
(void)flags; // Avoid a warning.
return true;
}
return false;
}
/**
* @brief Replace matching token with given number
* @param str String in which operation to be performed
* @param from token
* @param toNumber number to replace token
* @retval position
*/
static int replace(std::string& str, const std::string& from, uint64_t toNumber )
{
//FN_TRACE_F_MPD( __FUNCTION__ );
int rc = 0;
size_t tokenLength = from.length();
for (;;)
{
bool done = true;
size_t pos = 0;
for (;;)
{
pos = str.find('$', pos);
if (pos == std::string::npos)
{
break;
}
size_t next = str.find('$', pos + 1);
if(next != 0)
{
if (str.substr(pos + 1, tokenLength) == from)
{
size_t formatLen = next - pos - tokenLength - 1;
char buf[256];
if (formatLen > 0)
{
std::string format = str.substr(pos + tokenLength + 1, formatLen-1);
char type = str[pos+tokenLength+formatLen];
switch( type )
{ // don't use the number-formatting string from dash manifest as-is; map to uint64_t equivalent
case 'd':
format += PRIu64;
break;
case 'x':
format += PRIx64;
break;
case 'X':
format += PRIX64;
break;
default:
AAMPLOG_WARN( "unsupported template format: %s%c", format.c_str(), type );
format += type;
break;
}
snprintf(buf, sizeof(buf), format.c_str(), toNumber);
tokenLength += formatLen;
}
else
{
snprintf(buf, sizeof(buf), "%" PRIu64 "", toNumber);
}
str.replace(pos, tokenLength + 2, buf);
done = false;
rc++;
break;
}
pos = next + 1;
}
else
{
AAMPLOG_WARN("next is not found "); //CID:81252 - checked return
break;
}
}
if (done) break;
}
return rc;
}
/**
* @brief Replace matching token with given string
* @param str String in which operation to be performed
* @param from token
* @param toString string to replace token
* @retval position
*/
static int replace(std::string& str, const std::string& from, const std::string& toString )
{
FN_TRACE_F_MPD( __FUNCTION__ );
int rc = 0;
size_t tokenLength = from.length();
for (;;)
{
bool done = true;
size_t pos = 0;
for (;;)
{
pos = str.find('$', pos);
if (pos == std::string::npos)
{
break;
}
size_t next = str.find('$', pos + 1);
if(next != 0)
{
if (str.substr(pos + 1, tokenLength) == from)