forked from rdkcmf/rdk-aamp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fragmentcollector_mpd.cpp
8812 lines (8208 loc) · 295 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 "priv_aamp.h"
#include "AampDRMSessionManager.h"
#include "admanager_mpd.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"
//#define DEBUG_TIMELINE
//#define AAMP_HARVEST_SUPPORT_ENABLED
//#define AAMP_DISABLE_INJECT
//#define HARVEST_MPD
/**
* @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 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 SCHEME_ID_URI_VSS_STREAM "urn:comcast:x1:lin:ck"
#define SCHEME_ID_URI_DAI_STREAM "urn:comcast:dai:2018"
#define EC3_EXT_VALUE_AUDIO_ATMOS "JOC"
/**
* @struct FragmentDescriptor
* @brief Stores information of dash fragment
*/
struct FragmentDescriptor
{
private :
const std::vector<IBaseUrl *>*baseUrls;
std::string matchingBaseURL;
public :
std::string manifestUrl;
uint32_t Bandwidth;
std::string RepresentationID;
uint64_t Number;
double Time;
FragmentDescriptor() : manifestUrl(""), baseUrls (NULL), Bandwidth(0), Number(0), Time(0), RepresentationID(""),matchingBaseURL("")
{
}
FragmentDescriptor(const FragmentDescriptor& p) : manifestUrl(p.manifestUrl), baseUrls(p.baseUrls), Bandwidth(p.Bandwidth), RepresentationID(p.RepresentationID), Number(p.Number), Time(p.Time),matchingBaseURL(p.matchingBaseURL)
{
}
FragmentDescriptor& operator=(const FragmentDescriptor &p)
{
manifestUrl = p.manifestUrl;
baseUrls = p.baseUrls;
RepresentationID.assign(p.RepresentationID);
Bandwidth = p.Bandwidth;
Number = p.Number;
Time = p.Time;
matchingBaseURL = p.matchingBaseURL;
return *this;
}
const std::vector<IBaseUrl *>* GetBaseURLs() const
{
return baseUrls;
}
std::string GetMatchingBaseUrl() const
{
return matchingBaseURL;
}
void SetBaseURLs(const std::vector<IBaseUrl *>* baseurls )
{
if(baseurls)
{
this->baseUrls = baseurls;
if(this->baseUrls->size() > 0 )
{
// use baseurl which matches with host from manifest.
if(gpGlobalConfig->useMatchingBaseUrl == eTrueState)
{
std::string prefHost = aamp_getHostFromURL(manifestUrl);
for (auto & item : *this->baseUrls) {
std::string itemUrl =item->GetUrl();
std::string host = aamp_getHostFromURL(itemUrl);
if(0 == prefHost.compare(host))
{
this->matchingBaseURL = item->GetUrl();
return; // return here, we are done
}
}
}
//we are here means useMatchingBaseUrl not enabled or host did not match
// hence initialize default to first baseurl
this->matchingBaseURL = this->baseUrls->at(0)->GetUrl();
}
else
{
this->matchingBaseURL.clear();
}
}
}
};
/**
* @struct PeriodInfo
* @brief Stores details about available periods in mpd
*/
struct PeriodInfo {
std::string periodId;
uint64_t startTime;
double duration;
PeriodInfo() : periodId(""), startTime(0), duration(0.0)
{
}
};
static double ComputeFragmentDuration( uint32_t duration, uint32_t timeScale )
{
double newduration = 2.0;
if( duration && timeScale )
{
newduration = (double)duration / (double)timeScale;
newduration = ceil(newduration * 1000.0) / 1000.0;
return newduration;
}
AAMPLOG_WARN( "%s:%d bad fragment duration", __FUNCTION__, __LINE__ );
return newduration;
}
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()
{
return segmentTemplate1 || segmentTemplate2;
}
std::string Getmedia()
{
std::string media;
if( segmentTemplate1 ) media = segmentTemplate1->Getmedia();
if( media.empty() && segmentTemplate2 ) media = segmentTemplate2->Getmedia();
return media;
}
const ISegmentTimeline *GetSegmentTimeline()
{
const ISegmentTimeline *segmentTimeline = NULL;
if( segmentTemplate1 ) segmentTimeline = segmentTemplate1->GetSegmentTimeline();
if( !segmentTimeline && segmentTemplate2 ) segmentTimeline = segmentTemplate2->GetSegmentTimeline();
return segmentTimeline;
}
uint32_t GetTimescale()
{
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()
{
uint32_t duration = 0;
if( segmentTemplate1 ) duration = segmentTemplate1->GetDuration();
if( duration==0 && segmentTemplate2 ) duration = segmentTemplate2->GetDuration();
return duration;
}
long GetStartNumber()
{
long startNumber = 0;
if( segmentTemplate1 ) startNumber = segmentTemplate1->GetStartNumber();
if( startNumber==0 && segmentTemplate2 ) startNumber = segmentTemplate2->GetStartNumber();
return startNumber;
}
uint32_t GetPresentationTimeOffset()
{
uint32_t presentationOffset = 0;
if(segmentTemplate1 ) presentationOffset = segmentTemplate1->GetPresentationTimeOffset();
if( presentationOffset==0 && segmentTemplate2) presentationOffset = segmentTemplate2->GetPresentationTimeOffset();
return presentationOffset;
}
std::string Getinitialization()
{
std::string initialization;
if( segmentTemplate1 ) initialization = segmentTemplate1->Getinitialization();
if( initialization.empty() && segmentTemplate2 ) initialization = segmentTemplate2->Getinitialization();
return initialization;
}
}; // SegmentTemplates
static const char *mMediaTypeName[] = { "video", "audio", "text" };
#ifdef AAMP_HARVEST_SUPPORT_ENABLED
#ifdef USE_PLAYERSINKBIN
#define HARVEST_BASE_PATH "/media/tsb/aamp-harvest/" // SD card friendly path
#else
#define HARVEST_BASE_PATH "aamp-harvest/"
#endif
static void GetFilePath(std::string& filePath, const FragmentDescriptor *fragmentDescriptor, std::string media);
static void WriteFile(std::string fileName, const char* data, int len);
#endif // AAMP_HARVEST_SUPPORT_ENABLED
/**
* @brief Check if the given period is empty
*/
static bool IsEmptyPeriod(IPeriod *period);
/**
* @class MediaStreamContext
* @brief MPD media track
*/
class MediaStreamContext : public MediaTrack
{
public:
/**
* @brief MediaStreamContext Constructor
* @param type Type of track
* @param context MPD collector context
* @param aamp Pointer to associated aamp instance
* @param name Name of the track
*/
MediaStreamContext(TrackType type, StreamAbstractionAAMP_MPD* context, PrivateInstanceAAMP* aamp, const char* name) :
MediaTrack(type, aamp, name),
mediaType((MediaType)type), adaptationSet(NULL), representation(NULL),
fragmentIndex(0), timeLineIndex(0), fragmentRepeatCount(0), fragmentOffset(0),
eos(false), fragmentTime(0), periodStartOffset(0), index_ptr(NULL), index_len(0),
lastSegmentTime(0), lastSegmentNumber(0), lastSegmentDuration(0), adaptationSetIdx(0), representationIndex(0), profileChanged(true),
adaptationSetId(0), fragmentDescriptor(), mContext(context), initialization(""),
mDownloadedFragment(), discontinuity(false), mSkipSegmentOnError(true)
{
memset(&mDownloadedFragment, 0, sizeof(GrowableBuffer));
}
/**
* @brief MediaStreamContext Destructor
*/
~MediaStreamContext()
{
if(mDownloadedFragment.ptr)
{
aamp_Free(&mDownloadedFragment.ptr);
mDownloadedFragment.ptr = NULL;
}
}
/**
* @brief MediaStreamContext Copy Constructor
*/
MediaStreamContext(const MediaStreamContext&) = delete;
/**
* @brief MediaStreamContext Assignment operator overloading
*/
MediaStreamContext& operator=(const MediaStreamContext&) = delete;
/**
* @brief Get the context of media track. To be implemented by subclasses
* @retval Context of track.
*/
StreamAbstractionAAMP* GetContext()
{
return mContext;
}
/**
* @brief Receives cached fragment and injects to sink.
*
* @param[in] cachedFragment - contains fragment to be processed and injected
* @param[out] fragmentDiscarded - true if fragment is discarded.
*/
void InjectFragmentInternal(CachedFragment* cachedFragment, bool &fragmentDiscarded)
{
#ifndef AAMP_DISABLE_INJECT
aamp->SendStream((MediaType)type, &cachedFragment->fragment,
cachedFragment->position, cachedFragment->position, cachedFragment->duration);
#endif
fragmentDiscarded = false;
} // InjectFragmentInternal
/**
* @brief Fetch and cache a fragment
* @param fragmentUrl url of fragment
* @param curlInstance curl instance to be used to fetch
* @param position position of fragment in seconds
* @param duration duration of fragment in seconds
* @param range byte range
* @param initSegment true if fragment is init fragment
* @param discontinuity true if fragment is discontinuous
* @retval true on success
*/
bool CacheFragment(std::string fragmentUrl, unsigned int curlInstance, double position, double duration, const char *range = NULL, bool initSegment = false, bool discontinuity = false
#ifdef AAMP_HARVEST_SUPPORT_ENABLED
, std::string media = 0
#endif
, bool playingAd = false
)
{
bool ret = false;
fragmentDurationSeconds = duration;
ProfilerBucketType bucketType = aamp->GetProfilerBucketForMedia(mediaType, initSegment);
CachedFragment* cachedFragment = GetFetchBuffer(true);
long http_code = 0;
long bitrate = 0;
double downloadTime = 0;
MediaType actualType = (MediaType)(initSegment?(eMEDIATYPE_INIT_VIDEO+mediaType):mediaType); //Need to revisit the logic
if(!initSegment && mDownloadedFragment.ptr)
{
ret = true;
cachedFragment->fragment.ptr = mDownloadedFragment.ptr;
cachedFragment->fragment.len = mDownloadedFragment.len;
cachedFragment->fragment.avail = mDownloadedFragment.avail;
memset(&mDownloadedFragment, 0, sizeof(GrowableBuffer));
}
else
{
std::string effectiveUrl;
int iFogError = -1;
int iCurrentRate = aamp->rate; // Store it as back up, As sometimes by the time File is downloaded, rate might have changed due to user initiated Trick-Play
ret = aamp->LoadFragment(bucketType, fragmentUrl,effectiveUrl, &cachedFragment->fragment, curlInstance,
range, actualType, &http_code, &downloadTime, &bitrate, &iFogError, fragmentDurationSeconds );
if (iCurrentRate != AAMP_NORMAL_PLAY_RATE)
{
if(actualType == eMEDIATYPE_VIDEO)
{
actualType = eMEDIATYPE_IFRAME;
}
else if(actualType == eMEDIATYPE_INIT_VIDEO)
{
actualType = eMEDIATYPE_INIT_IFRAME;
}
//CID:101284 - To resolve the deadcode
}
//update videoend info
aamp->UpdateVideoEndMetrics( actualType,
bitrate? bitrate : fragmentDescriptor.Bandwidth,
(iFogError > 0 ? iFogError : http_code),effectiveUrl,duration, downloadTime);
}
mContext->mCheckForRampdown = false;
if(bitrate > 0 && bitrate != fragmentDescriptor.Bandwidth)
{
AAMPLOG_INFO("%s:%d Bitrate changed from %u to %ld", __FUNCTION__, __LINE__, fragmentDescriptor.Bandwidth, bitrate);
fragmentDescriptor.Bandwidth = bitrate;
mContext->SetTsbBandwidth(bitrate);
mDownloadedFragment.ptr = cachedFragment->fragment.ptr;
mDownloadedFragment.avail = cachedFragment->fragment.avail;
mDownloadedFragment.len = cachedFragment->fragment.len;
memset(&cachedFragment->fragment, 0, sizeof(GrowableBuffer));
ret = false;
}
else if (!ret)
{
aamp_Free(&cachedFragment->fragment.ptr);
if( aamp->DownloadsAreEnabled())
{
logprintf("%s:%d LoadFragment failed", __FUNCTION__, __LINE__);
if (initSegment)
{
logprintf("%s:%d Init fragment fetch failed. fragmentUrl %s", __FUNCTION__, __LINE__, fragmentUrl.c_str());
}
if (mSkipSegmentOnError)
{
// Skip segment on error, and increse fail count
segDLFailCount += 1;
}
else
{
// Rampdown already attempted on same segment
// Reset flag for next fetch
mSkipSegmentOnError = true;
}
if (MAX_SEG_DOWNLOAD_FAIL_COUNT <= segDLFailCount)
{
if(!playingAd) //If playingAd, we are invalidating the current Ad in onAdEvent().
{
if (!initSegment)
{
AAMPLOG_ERR("%s:%d Not able to download fragments; reached failure threshold sending tune failed event",__FUNCTION__, __LINE__);
aamp->SendDownloadErrorEvent(AAMP_TUNE_FRAGMENT_DOWNLOAD_FAILURE, http_code);
}
else
{
// When rampdown limit is not specified, init segment will be ramped down, this wil
AAMPLOG_ERR("%s:%d Not able to download init fragments; reached failure threshold sending tune failed event",__FUNCTION__, __LINE__);
aamp->SendDownloadErrorEvent(AAMP_TUNE_INIT_FRAGMENT_DOWNLOAD_FAILURE, http_code);
}
}
}
// DELIA-32287 - Profile RampDown check and rampdown is needed only for Video . If audio fragment download fails
// should continue with next fragment,no retry needed .
else if ((eTRACK_VIDEO == type) && !(mContext->CheckForRampDownLimitReached()))
{
// Attempt rampdown
if (mContext->CheckForRampDownProfile(http_code))
{
mContext->mCheckForRampdown = true;
if (!initSegment)
{
// Rampdown attempt success, download same segment from lower profile.
mSkipSegmentOnError = false;
}
AAMPLOG_WARN( "PrivateStreamAbstractionMPD::%s:%d > Error while fetching fragment:%s, failedCount:%d. decrementing profile",
__FUNCTION__, __LINE__, fragmentUrl.c_str(), segDLFailCount);
}
else
{
if(!playingAd && initSegment)
{
// Already at lowest profile, send error event for init fragment.
AAMPLOG_ERR("%s:%d Not able to download init fragments; reached failure threshold sending tune failed event",__FUNCTION__, __LINE__);
aamp->SendDownloadErrorEvent(AAMP_TUNE_INIT_FRAGMENT_DOWNLOAD_FAILURE, http_code);
}
else
{
AAMPLOG_WARN("PrivateStreamAbstractionMPD::%s:%d Already at the lowest profile, skipping segment", __FUNCTION__,__LINE__);
mContext->mRampDownCount = 0;
}
}
}
else if (AAMP_IS_LOG_WORTHY_ERROR(http_code))
{
AAMPLOG_WARN("PrivateStreamAbstractionMPD::%s:%d > Error on fetching %s fragment. failedCount:%d",
__FUNCTION__, __LINE__, name, segDLFailCount);
// For init fragment, rampdown limit is reached. Send error event.
if(!playingAd && initSegment)
{
aamp->SendDownloadErrorEvent(AAMP_TUNE_INIT_FRAGMENT_DOWNLOAD_FAILURE, http_code);
}
}
}
}
else
{
#ifdef AAMP_HARVEST_SUPPORT_ENABLED
if (aamp->HarvestFragments())
{
std::string fileName;
fileName.assign(fragmentUrl);
GetFilePath(fileName, &fragmentDescriptor, media);
logprintf("%s:%d filePath %s", __FUNCTION__, __LINE__, fileName.c_str());
WriteFile(fileName, cachedFragment->fragment.ptr, cachedFragment->fragment.len);
}
#endif
cachedFragment->position = position;
cachedFragment->duration = duration;
cachedFragment->discontinuity = discontinuity;
#ifdef AAMP_DEBUG_INJECT
if (discontinuity)
{
logprintf("%s:%d Discontinuous fragment", __FUNCTION__, __LINE__);
}
if ((1 << type) & AAMP_DEBUG_INJECT)
{
cachedFragment->uri.assign(fragmentUrl);
}
#endif
segDLFailCount = 0;
if ((eTRACK_VIDEO == type) && (!initSegment))
{
// reset count on video fragment success
mContext->mRampDownCount = 0;
}
UpdateTSAfterFetch();
ret = true;
}
return ret;
}
/**
* @brief Listener to ABR profile change
*/
void ABRProfileChanged(void)
{
if (representationIndex != mContext->currentProfileIndex)
{
IRepresentation *pNewRepresentation = adaptationSet->GetRepresentation().at(mContext->currentProfileIndex);
if(representation != NULL)
{
logprintf("PrivateStreamAbstractionMPD::%s:%d - ABR %dx%d[%d] -> %dx%d[%d]", __FUNCTION__, __LINE__,
representation->GetWidth(), representation->GetHeight(), representation->GetBandwidth(),
pNewRepresentation->GetWidth(), pNewRepresentation->GetHeight(), pNewRepresentation->GetBandwidth());
representationIndex = mContext->currentProfileIndex;
representation = adaptationSet->GetRepresentation().at(mContext->currentProfileIndex);
const std::vector<IBaseUrl *>*baseUrls = &representation->GetBaseURLs();
if (baseUrls->size() != 0)
{
fragmentDescriptor.SetBaseURLs(baseUrls);
}
fragmentDescriptor.Bandwidth = representation->GetBandwidth();
fragmentDescriptor.RepresentationID.assign(representation->GetId());
profileChanged = true;
}
else
{
AAMPLOG_WARN("%s:%d : representation is null", __FUNCTION__, __LINE__); //CID:83962 - Null Returns
}
}
else
{
traceprintf("PrivateStreamAbstractionMPD::%s:%d - Not switching ABR %dx%d[%d] ", __FUNCTION__, __LINE__,
representation->GetWidth(), representation->GetHeight(), representation->GetBandwidth());
}
}
double GetBufferedDuration()
{
return (fragmentTime - (aamp->GetPositionMs() / 1000));
}
/**
* @brief Notify discontinuity during trick-mode as PTS re-stamping is done in sink
*/
void SignalTrickModeDiscontinuity()
{
aamp->SignalTrickModeDiscontinuity();
}
/**
* @brief Returns if the end of track reached.
*/
bool IsAtEndOfTrack()
{
return eosReached;
}
MediaType mediaType;
struct FragmentDescriptor fragmentDescriptor;
IAdaptationSet *adaptationSet;
IRepresentation *representation;
int fragmentIndex;
int timeLineIndex;
int fragmentRepeatCount;
int fragmentOffset;
bool eos;
bool profileChanged;
bool discontinuity;
GrowableBuffer mDownloadedFragment;
double fragmentTime;
double periodStartOffset;
char *index_ptr;
size_t index_len;
uint64_t lastSegmentTime;
uint64_t lastSegmentNumber;
uint64_t lastSegmentDuration;
int adaptationSetIdx;
int representationIndex;
StreamAbstractionAAMP_MPD* mContext;
std::string initialization;
uint32_t adaptationSetId;
bool mSkipSegmentOnError;
};
/**
* @struct HeaderFetchParams
* @brief Holds information regarding initialization fragment
*/
struct HeaderFetchParams
{
HeaderFetchParams() : context(NULL), pMediaStreamContext(NULL), initialization(""), fragmentduration(0),
isinitialization(false), discontinuity(false)
{
}
HeaderFetchParams(const HeaderFetchParams&) = delete;
HeaderFetchParams& operator=(const HeaderFetchParams&) = delete;
class PrivateStreamAbstractionMPD *context;
struct MediaStreamContext *pMediaStreamContext;
string initialization;
double fragmentduration;
bool isinitialization;
bool discontinuity;
};
/**
* @struct FragmentDownloadParams
* @brief Holds data of fragment to be downloaded
*/
struct FragmentDownloadParams
{
class PrivateStreamAbstractionMPD *context;
struct MediaStreamContext *pMediaStreamContext;
bool playingLastPeriod;
long long lastPlaylistUpdateMS;
};
struct EarlyAvailablePeriodInfo
{
EarlyAvailablePeriodInfo() : periodId(), isLicenseProcessed(false), isLicenseFailed(false), helper(nullptr){}
std::string periodId;
std::shared_ptr<AampDrmHelper> helper;
bool isLicenseProcessed;
bool isLicenseFailed;
};
static bool IsIframeTrack(IAdaptationSet *adaptationSet);
/**
* @class PrivateStreamAbstractionMPD
* @brief Private implementation of MPD fragment collector
*/
class PrivateStreamAbstractionMPD
{
public:
PrivateStreamAbstractionMPD( StreamAbstractionAAMP_MPD* context, PrivateInstanceAAMP *aamp,double seekpos, float rate);
~PrivateStreamAbstractionMPD();
PrivateStreamAbstractionMPD(const PrivateStreamAbstractionMPD&) = delete;
PrivateStreamAbstractionMPD& operator=(const PrivateStreamAbstractionMPD&) = delete;
void SetEndPos(double endPosition);
void Start();
void Stop();
AAMPStatusType Init(TuneType tuneType);
void GetStreamFormat(StreamOutputFormat &primaryOutputFormat, StreamOutputFormat &audioOutputFormat);
/**
* @brief Get current stream position.
*
* @retval current position of stream.
*/
double GetStreamPosition() { return seekPosition; }
void FetcherLoop();
bool PushNextFragment( MediaStreamContext *pMediaStreamContext, unsigned int curlInstance = 0);
bool FetchFragment(MediaStreamContext *pMediaStreamContext, std::string media, double fragmentDuration, bool isInitializationSegment, unsigned int curlInstance = 0, bool discontinuity = false );
double GetPeriodEndTime(IMPD *mpd, int periodIndex, uint64_t mpdRefreshTime);
double GetPeriodStartTime(IMPD *mpd, int periodIndex);
double GetPeriodDuration(IMPD *mpd, int periodIndex);
int GetProfileCount();
int GetProfileIndexForBandwidth(long mTsbBandwidth);
StreamInfo* GetStreamInfo(int idx);
MediaTrack* GetMediaTrack(TrackType type);
double GetFirstPTS();
int64_t GetMinUpdateDuration() { return mMinUpdateDurationMs;}
PrivateInstanceAAMP *aamp;
int GetBWIndex(long bitrate);
std::vector<long> GetVideoBitrates(void);
std::vector<long> GetAudioBitrates(void);
void StopInjection();
void StartInjection();
void SetCDAIObject(CDAIObject *cdaiObj);
bool isAdbreakStart(IPeriod *period, uint32_t &duration, uint64_t &startMS, std::string &scte35);
bool onAdEvent(AdEvent evt);
bool onAdEvent(AdEvent evt, double &adOffset);
long GetMaxTSBBandwidth() { return mMaxTSBBandwidth; }
bool IsTSBUsed() { return mIsFogTSB; }
#ifdef AAMP_MPD_DRM
void ProcessEAPLicenseRequest();
void StartDeferredDRMRequestThread(MediaType mediaType);
#endif
private:
AAMPStatusType UpdateMPD(bool init = false);
void FindTimedMetadata(MPD* mpd, Node* root, bool init = false, bool reportBulkMet = false);
void ProcessPeriodSupplementalProperty(Node* node, std::string& AdID, uint64_t startMS, uint64_t durationMS, bool isInit, bool reportBulkMeta=false);
void ProcessPeriodAssetIdentifier(Node* node, uint64_t startMS, uint64_t durationMS, std::string& assetID, std::string& providerID,bool isInit, bool reportBulkMeta=false);
bool ProcessEventStream(uint64_t startMS, IPeriod * period);
void ProcessStreamRestrictionList(Node* node, const std::string& AdID, uint64_t startMS, bool isInit, bool reportBulkMeta);
void ProcessStreamRestriction(Node* node, const std::string& AdID, uint64_t startMS, bool isInit, bool reportBulkMeta);
void ProcessStreamRestrictionExt(Node* node, const std::string& AdID, uint64_t startMS, bool isInit, bool reportBulkMeta);
void ProcessTrickModeRestriction(Node* node, const std::string& AdID, uint64_t startMS, bool isInit, bool reportBulkMeta);
void FetchAndInjectInitialization(bool discontinuity = false);
void StreamSelection(bool newTune = false, bool forceSpeedsChangedEvent = false);
bool CheckForInitalClearPeriod();
void PushEncryptedHeaders();
int GetProfileIdxForBandwidthNotification(uint32_t bandwidth);
AAMPStatusType UpdateTrackInfo(bool modifyDefaultBW, bool periodChanged, bool resetTimeLineIndex=false);
double SkipFragments( MediaStreamContext *pMediaStreamContext, double skipTime, bool updateFirstPTS = false);
void SkipToEnd( MediaStreamContext *pMediaStreamContext); //Added to support rewind in multiperiod assets
void ProcessContentProtection(IAdaptationSet * adaptationSet,MediaType mediaType, std::shared_ptr<AampDrmHelper> drmHelper = nullptr);
#ifdef AAMP_MPD_DRM
void ProcessVssContentProtection(std::shared_ptr<AampDrmHelper> drmHelper, MediaType mediaType);
std::shared_ptr<AampDrmHelper> CreateDrmHelper(IAdaptationSet * adaptationSet,MediaType mediaType);
#endif
void SeekInPeriod( double seekPositionSeconds);
double GetCulledSeconds();
void UpdateLanguageList();
int GetBestAudioTrackByLanguage(int &desiredRepIdx,AudioType &selectedCodecType);
int GetPreferredAudioTrackByLanguage();
std::string GetLanguageForAdaptationSet( IAdaptationSet *adaptationSet );
AAMPStatusType GetMpdFromManfiest(const GrowableBuffer &manifest, MPD * &mpd, std::string manifestUrl, bool init = false);
bool IsEmptyPeriod(IPeriod *period);
int GetDrmPrefs(const std::string& uuid);
void GetAvailableVSSPeriods(std::vector<IPeriod*>& PeriodIds);
bool CheckForVssTags();
std::string GetVssVirtualStreamID();
bool fragmentCollectorThreadStarted;
std::set<std::string> mLangList;
double seekPosition;
float rate;
pthread_t fragmentCollectorThreadID;
pthread_t createDRMSessionThreadID;
std::thread *deferredDRMRequestThread;
bool deferredDRMRequestThreadStarted;
bool mAbortDeferredLicenseLoop;
bool drmSessionThreadStarted;
dash::mpd::IMPD *mpd;
MediaStreamContext *mMediaStreamContext[AAMP_TRACK_COUNT];
int mNumberOfTracks;
int mCurrentPeriodIdx;
double mEndPosition;
bool mIsLiveStream; //Stream is live or not; won't change during runtime.
bool mIsLiveManifest; //Current manifest is dynamic or static; may change during runtime. eg: Hot DVR.
StreamAbstractionAAMP_MPD* mContext;
StreamInfo* mStreamInfo;
bool mUpdateStreamInfo; //Indicates mStreamInfo needs to be updated
double mPrevStartTimeSeconds;
std::string mPrevLastSegurlMedia;
long mPrevLastSegurlOffset; //duration offset from beginning of TSB
double mPeriodEndTime;
double mPeriodStartTime;
double mPeriodDuration;
int64_t mMinUpdateDurationMs;
double mTSBDepth;
double mPresentationOffsetDelay;
uint64_t mLastPlaylistDownloadTimeMs;
double mFirstPTS;
double mVideoPosRemainder;
double mFirstFragPTS[AAMP_TRACK_COUNT];
AudioType mAudioType;
int mPrevAdaptationSetCount;
std::vector<long> mBitrateIndexVector;
bool mIsFogTSB;
vector<PeriodInfo> mMPDPeriodsInfo;
IPeriod *mCurrentPeriod;
std::string mBasePeriodId;
double mBasePeriodOffset;
PrivateCDAIObjectMPD *mCdaiObject;
std::shared_ptr<AampDrmHelper> mLastDrmHelper;
std::vector<std::string> mEarlyAvailablePeriodIds;
std::map<std::string, EarlyAvailablePeriodInfo> mEarlyAvailableKeyIDMap;
std::queue<std::string> mPendingKeyIDs;
int mCommonKeyDuration;
// DASH does not use abr manager to store the supported bandwidth values,
// hence storing max TSB bandwith in this variable which will be used for VideoEnd Metric data via
// StreamAbstractionAAMP::GetMaxBitrate function,
long mMaxTSBBandwidth;
double mLiveEndPosition;
double mCulledSeconds;
bool mAdPlayingFromCDN; /*Note: TRUE: Ad playing currently & from CDN. FALSE: Ad "maybe playing", but not from CDN.*/
double mAvailabilityStartTime;
std::map<std::string, int> mDrmPrefs;
int mMaxTracks; /* Max number of tracks for this session */
};
/**
* @brief PrivateStreamAbstractionMPD Constructor
* @param context MPD fragment collector context
* @param aamp Pointer to associated aamp private object
* @param seekpos Seek positon
* @param rate playback rate
*/
PrivateStreamAbstractionMPD::PrivateStreamAbstractionMPD( StreamAbstractionAAMP_MPD* context, PrivateInstanceAAMP *aamp,double seekpos, float rate) : aamp(aamp),
fragmentCollectorThreadStarted(false), mLangList(), seekPosition(seekpos), rate(rate), fragmentCollectorThreadID(0), createDRMSessionThreadID(0),
drmSessionThreadStarted(false), mpd(NULL), mNumberOfTracks(0), mCurrentPeriodIdx(0), mEndPosition(0), mIsLiveStream(true), mIsLiveManifest(true), mContext(context),
mStreamInfo(NULL), mPrevStartTimeSeconds(0), mPrevLastSegurlMedia(""), mPrevLastSegurlOffset(0),
mPeriodEndTime(0), mPeriodStartTime(0), mPeriodDuration(0), mMinUpdateDurationMs(DEFAULT_INTERVAL_BETWEEN_MPD_UPDATES_MS),
mLastPlaylistDownloadTimeMs(0), mFirstPTS(0), mAudioType(eAUDIO_UNKNOWN),
mPrevAdaptationSetCount(0), mBitrateIndexVector(), mIsFogTSB(false), mMPDPeriodsInfo(),
mCurrentPeriod(NULL), mBasePeriodId(""), mBasePeriodOffset(0), mCdaiObject(NULL), mLiveEndPosition(0), mCulledSeconds(0)
,mAdPlayingFromCDN(false)
,mMaxTSBBandwidth(0), mTSBDepth(0)
,mVideoPosRemainder(0)
,mPresentationOffsetDelay(0)
,mAvailabilityStartTime(0)
,mUpdateStreamInfo(false)
,mDrmPrefs({{CLEARKEY_UUID, 1}, {WIDEVINE_UUID, 2}, {PLAYREADY_UUID, 3}})// Default values, may get changed due to config file
,mLastDrmHelper()
,deferredDRMRequestThread(NULL), deferredDRMRequestThreadStarted(false), mCommonKeyDuration(0)
,mEarlyAvailableKeyIDMap(), mPendingKeyIDs(), mAbortDeferredLicenseLoop(false), mEarlyAvailablePeriodIds()
, mMaxTracks(0)
{
this->aamp = aamp;
memset(&mMediaStreamContext, 0, sizeof(mMediaStreamContext));
for (int i=0; i<AAMP_TRACK_COUNT; i++) mFirstFragPTS[i] = 0.0;
mContext->GetABRManager().clearProfiles();
mLastPlaylistDownloadTimeMs = aamp_GetCurrentTimeMS();
// setup DRM prefs from config
int highestPref = 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;
}
}
}
// 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);
}
};
/**
* @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)
{
bool isCompatible = false;
switch ( mediaType )
{
case eMEDIATYPE_VIDEO:
if (mimeType == "video/mp4")
isCompatible = true;
break;
case eMEDIATYPE_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 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)
{
bool isAtmos = false;
if (!nodePtr){
AAMPLOG_ERR("%s:%d > API Failed due to Invalid Arguments", __FUNCTION__, __LINE__);
}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("%s:%d > Recieved %s tag property value as %s ",
__FUNCTION__, __LINE__, SUPPLEMENTAL_PROPERTY_TAG, value.c_str());
if (value == EC3_EXT_VALUE_AUDIO_ATMOS){
isAtmos = true;
break;
}
}
}
else
{
AAMPLOG_WARN("%s:%d : schemeIdUri is not equals to SCHEME_ID_URI_EC3_EXT_CODEC ", __FUNCTION__, __LINE__); //CID:84346 - Null Returns
}
}
}