1 /*
2  * Copyright (c) 2022-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #define HST_LOG_TAG "DashMpdDownloader"
16 #include <mutex>
17 #include <unistd.h>
18 #include <cstdlib>
19 #include <limits>
20 #include <sstream>
21 #include <iomanip>
22 #include <algorithm>
23 #include "plugin/plugin_time.h"
24 #include "network/network_typs.h"
25 #include "dash_mpd_downloader.h"
26 #include "dash_mpd_util.h"
27 #include "sidx_box_parser.h"
28 #include "utils/time_utils.h"
29 #include "base64_utils.h"
30 
31 namespace OHOS {
32 namespace Media {
33 namespace Plugins {
34 namespace HttpPlugin {
35 constexpr uint32_t DRM_UUID_OFFSET = 12;
36 constexpr size_t RETRY_TIMES = 15000;
37 constexpr unsigned int SLEEP_TIME = 1;
38 constexpr int32_t MPD_HTTP_TIME_OUT_MS = 5 * 1000;
39 constexpr unsigned int SEGMENT_DURATION_DELTA = 100; // ms
40 
DashMpdDownloader()41 DashMpdDownloader::DashMpdDownloader()
42 {
43     downloader_ = std::make_shared<Downloader>("dashMpd");
44 
45     dataSave_ =  [this] (uint8_t*&& data, uint32_t&& len) {
46         return SaveData(std::forward<decltype(data)>(data), std::forward<decltype(len)>(len));
47     };
48 
49     mpdParser_ = std::make_shared<DashMpdParser>();
50     mpdManager_ = std::make_shared<DashMpdManager>();
51     periodManager_ = std::make_shared<DashPeriodManager>();
52     adptSetManager_ = std::make_shared<DashAdptSetManager>();
53     representationManager_ = std::make_shared<DashRepresentationManager>();
54 }
55 
~DashMpdDownloader()56 DashMpdDownloader::~DashMpdDownloader() noexcept
57 {
58     if (downloader_ != nullptr) {
59         downloader_->Stop(false);
60     }
61     streamDescriptions_.clear();
62 }
63 
ParseStartNumber(const std::string & numberStr)64 static int64_t ParseStartNumber(const std::string &numberStr)
65 {
66     int64_t startNum = 1;
67     if (numberStr.length() > 0) {
68         startNum = atoi(numberStr.c_str());
69     }
70 
71     return startNum;
72 }
73 
GetStartNumber(const DashRepresentationInfo * repInfo)74 static int64_t GetStartNumber(const DashRepresentationInfo* repInfo)
75 {
76     int64_t startNumberSeq = 1;
77     if (repInfo->representationSegTmplt_ != nullptr) {
78         startNumberSeq = ParseStartNumber(repInfo->representationSegTmplt_->multSegBaseInfo_.startNumber_);
79     } else if (repInfo->representationSegList_ != nullptr) {
80         startNumberSeq = ParseStartNumber(repInfo->representationSegList_->multSegBaseInfo_.startNumber_);
81     }
82     return startNumberSeq;
83 }
84 
GetStartNumber(const DashAdptSetInfo * adptSetInfo)85 static int64_t GetStartNumber(const DashAdptSetInfo* adptSetInfo)
86 {
87     int64_t startNumberSeq = 1;
88     if (adptSetInfo->adptSetSegTmplt_ != nullptr) {
89         startNumberSeq = ParseStartNumber(adptSetInfo->adptSetSegTmplt_->multSegBaseInfo_.startNumber_);
90     } else if (adptSetInfo->adptSetSegList_ != nullptr) {
91         startNumberSeq = ParseStartNumber(adptSetInfo->adptSetSegList_->multSegBaseInfo_.startNumber_);
92     }
93     return startNumberSeq;
94 }
95 
GetStartNumber(const DashPeriodInfo * periodInfo)96 static int64_t GetStartNumber(const DashPeriodInfo* periodInfo)
97 {
98     int64_t startNumberSeq = 1;
99     if (periodInfo->periodSegTmplt_ != nullptr) {
100         startNumberSeq = ParseStartNumber(periodInfo->periodSegTmplt_->multSegBaseInfo_.startNumber_);
101     } else if (periodInfo->periodSegList_ != nullptr) {
102         startNumberSeq = ParseStartNumber(periodInfo->periodSegList_->multSegBaseInfo_.startNumber_);
103     }
104     return startNumberSeq;
105 }
106 
MakeAbsoluteWithBaseUrl(const std::vector<std::shared_ptr<DashSegment>> & segmentsVector,const std::string & baseUrl)107 static void MakeAbsoluteWithBaseUrl(const std::vector<std::shared_ptr<DashSegment>> &segmentsVector,
108                                     const std::string &baseUrl)
109 {
110     std::string segUrl;
111     unsigned int size = segmentsVector.size();
112 
113     for (unsigned int index = 0; index < size; index++) {
114         if (segmentsVector[index] != nullptr) {
115             segUrl = baseUrl;
116             DashAppendBaseUrl(segUrl, segmentsVector[index]->url_);
117             segmentsVector[index]->url_ = segUrl;
118         }
119     }
120 }
121 
MakeAbsoluteWithBaseUrl(std::shared_ptr<DashInitSegment> initSegment,const std::string & baseUrl)122 static void MakeAbsoluteWithBaseUrl(std::shared_ptr<DashInitSegment> initSegment, const std::string &baseUrl)
123 {
124     if (initSegment == nullptr) {
125         return;
126     }
127 
128     if (DashUrlIsAbsolute(initSegment->url_)) {
129         return;
130     }
131 
132     std::string segUrl = baseUrl;
133     DashAppendBaseUrl(segUrl, initSegment->url_);
134     initSegment->url_ = segUrl;
135 }
136 
AddOneSegment(unsigned int segRealDur,int64_t segmentSeq,const std::string & tempUrl,std::shared_ptr<DashStreamDescription> streamDesc)137 static DashSegmentInitValue AddOneSegment(unsigned int segRealDur, int64_t segmentSeq, const std::string &tempUrl,
138                                           std::shared_ptr<DashStreamDescription> streamDesc)
139 {
140     std::shared_ptr<DashSegment> segment = std::make_shared<DashSegment>();
141     segment->streamId_ = streamDesc->streamId_;
142     segment->bandwidth_ = streamDesc->bandwidth_;
143     segment->duration_ = segRealDur;
144     segment->startNumberSeq_ = streamDesc->startNumberSeq_;
145     segment->numberSeq_ = segmentSeq;
146     segment->url_ = tempUrl;
147     segment->byteRange_ = "";
148     streamDesc->mediaSegments_.push_back(segment);
149     return DASH_SEGMENT_INIT_SUCCESS;
150 }
151 
AddOneSegment(const DashSegment & srcSegment,std::shared_ptr<DashStreamDescription> streamDesc)152 static DashSegmentInitValue AddOneSegment(const DashSegment &srcSegment,
153                                           std::shared_ptr<DashStreamDescription> streamDesc)
154 {
155     std::shared_ptr<DashSegment> segment = std::make_shared<DashSegment>(srcSegment);
156     streamDesc->mediaSegments_.push_back(segment);
157     return DASH_SEGMENT_INIT_SUCCESS;
158 }
159 
160 /**
161  * @brief    Get Representation From AdaptationSet
162  *
163  * @param    adptSet                chosen AdaptationSet
164  * @param    repreIndex             Representation index in AdaptationSet
165  *
166  * @return   chosen representation
167  */
GetRepresentationFromAdptSet(DashAdptSetInfo * adptSet,unsigned int repreIndex)168 static DashRepresentationInfo* GetRepresentationFromAdptSet(DashAdptSetInfo* adptSet, unsigned int repreIndex)
169 {
170     if (repreIndex >= adptSet->representationList_.size()) {
171         return nullptr;
172     }
173 
174     unsigned int index = 0;
175     for (DashList<DashRepresentationInfo *>::iterator it = adptSet->representationList_.begin();
176          it != adptSet->representationList_.end(); ++it, ++index) {
177         if (index == repreIndex) {
178             return *it;
179         }
180     }
181     return nullptr;
182 }
183 
Open(const std::string & url)184 void DashMpdDownloader::Open(const std::string &url)
185 {
186     url_ = url;
187     DoOpen(url);
188 }
189 
Close(bool isAsync)190 void DashMpdDownloader::Close(bool isAsync)
191 {
192     downloader_->Stop(isAsync);
193 
194     if (downloadRequest_ != nullptr && !downloadRequest_->IsClosed()) {
195         downloadRequest_->Close();
196     }
197 }
198 
SetStatusCallback(StatusCallbackFunc cb)199 void DashMpdDownloader::SetStatusCallback(StatusCallbackFunc cb)
200 {
201     statusCallback_ = cb;
202 }
203 
UpdateDownloadFinished(const std::string & url)204 void DashMpdDownloader::UpdateDownloadFinished(const std::string &url)
205 {
206     MEDIA_LOG_I("UpdateDownloadFinished:ondemandSegBase_=%{public}u", ondemandSegBase_);
207     if (ondemandSegBase_) {
208         ParseSidx();
209     } else {
210         ParseManifest();
211     }
212 }
213 
GetInUseVideoStreamId() const214 int DashMpdDownloader::GetInUseVideoStreamId() const
215 {
216     for (uint32_t index = 0; index < streamDescriptions_.size(); index++) {
217         if (streamDescriptions_[index]->inUse_ && streamDescriptions_[index]->type_ == MediaAVCodec::MEDIA_TYPE_VID) {
218             return streamDescriptions_[index]->streamId_;
219         }
220     }
221     return -1;
222 }
223 
GetNextSegmentByStreamId(int streamId,std::shared_ptr<DashSegment> & seg)224 DashMpdGetRet DashMpdDownloader::GetNextSegmentByStreamId(int streamId, std::shared_ptr<DashSegment> &seg)
225 {
226     MEDIA_LOG_I("GetNextSegmentByStreamId streamId:" PUBLIC_LOG_D32, streamId);
227     seg = nullptr;
228     DashMpdGetRet ret = DASH_MPD_GET_ERROR;
229     for (auto &streamDescription : streamDescriptions_) {
230         if (streamDescription->streamId_ != streamId) {
231             continue;
232         }
233 
234         if (streamDescription->segsState_ == DASH_SEGS_STATE_FINISH) {
235             int64_t segmentIndex = (streamDescription->currentNumberSeq_ == -1) ? 0 :
236                 streamDescription->currentNumberSeq_ - streamDescription->startNumberSeq_ + 1;
237             MEDIA_LOG_D("get segment index :" PUBLIC_LOG_D64 ", id:" PUBLIC_LOG_D32 ", seq:"
238                 PUBLIC_LOG_D64, segmentIndex, streamDescription->streamId_, streamDescription->currentNumberSeq_);
239             if (segmentIndex >= 0 && (unsigned int) segmentIndex < streamDescription->mediaSegments_.size()) {
240                 seg = streamDescription->mediaSegments_[segmentIndex];
241                 streamDescription->currentNumberSeq_ = seg->numberSeq_;
242                 MEDIA_LOG_D("after get segment index :"
243                     PUBLIC_LOG_D64, streamDescription->currentNumberSeq_);
244                 ret = DASH_MPD_GET_DONE;
245             } else {
246                 ret = DASH_MPD_GET_FINISH;
247             }
248         } else {
249             ret = DASH_MPD_GET_UNDONE;
250         }
251         break;
252     }
253 
254     return ret;
255 }
256 
GetBreakPointSegment(int streamId,int64_t breakpoint,std::shared_ptr<DashSegment> & seg)257 DashMpdGetRet DashMpdDownloader::GetBreakPointSegment(int streamId, int64_t breakpoint,
258                                                       std::shared_ptr<DashSegment> &seg)
259 {
260     MEDIA_LOG_I("GetBreakPointSegment streamId:" PUBLIC_LOG_D32 ", breakpoint:" PUBLIC_LOG_D64, streamId, breakpoint);
261     seg = nullptr;
262     DashMpdGetRet ret = DASH_MPD_GET_ERROR;
263     for (auto &streamDescription : streamDescriptions_) {
264         if (streamDescription->streamId_ != streamId) {
265             continue;
266         }
267 
268         if (streamDescription->segsState_ != DASH_SEGS_STATE_FINISH) {
269             MEDIA_LOG_E("GetBreakPointSegment no segment list");
270             ret = DASH_MPD_GET_UNDONE;
271             break;
272         }
273 
274         int64_t segmentDuration = 0;
275         for (unsigned int index = 0; index <  streamDescription->mediaSegments_.size(); index++) {
276             if (segmentDuration + (int64_t)(streamDescription->mediaSegments_[index]->duration_) > breakpoint) {
277                 seg = streamDescription->mediaSegments_[index];
278                 break;
279             }
280         }
281 
282         if (seg != nullptr) {
283             streamDescription->currentNumberSeq_ = seg->numberSeq_;
284             MEDIA_LOG_I("GetBreakPointSegment find segment index :"
285                 PUBLIC_LOG_D64, streamDescription->currentNumberSeq_);
286             ret = DASH_MPD_GET_DONE;
287         } else {
288             MEDIA_LOG_W("GetBreakPointSegment all segment finish");
289             ret = DASH_MPD_GET_FINISH;
290         }
291         break;
292     }
293 
294     return ret;
295 }
296 
GetNextVideoStream(DashMpdBitrateParam & param,int & streamId)297 DashMpdGetRet DashMpdDownloader::GetNextVideoStream(DashMpdBitrateParam &param, int &streamId)
298 {
299     std::shared_ptr<DashStreamDescription> currentStream = nullptr;
300     std::shared_ptr<DashStreamDescription> destStream = nullptr;
301     bool isFirstSelect = true;
302     uint32_t maxGap = 0;
303     for (const auto &stream : streamDescriptions_) {
304         if (stream->type_ != MediaAVCodec::MediaType::MEDIA_TYPE_VID) {
305             continue;
306         }
307 
308         uint32_t tempGap = (stream->bandwidth_ > param.bitrate_) ?
309             (stream->bandwidth_ - param.bitrate_) : (param.bitrate_ - stream->bandwidth_);
310         if (isFirstSelect || (tempGap < maxGap)) {
311             isFirstSelect = false;
312             maxGap = tempGap;
313             destStream = stream;
314         }
315 
316         if (stream->inUse_) {
317             currentStream = stream;
318         }
319     }
320 
321     if (destStream == nullptr || currentStream == nullptr) {
322         MEDIA_LOG_E("switch to bandwidth:" PUBLIC_LOG_U32 ", can not find stream", param.bitrate_);
323         return DASH_MPD_GET_ERROR;
324     }
325 
326     currentStream->inUse_ = false;
327     destStream->inUse_ = true;
328     streamId = destStream->streamId_;
329     if (param.position_ == -1) {
330         destStream->currentNumberSeq_ = currentStream->currentNumberSeq_;
331     } else {
332         destStream->currentNumberSeq_ = param.position_;
333     }
334 
335     param.nextSegTime_ = GetSegTimeBySeq(currentStream->mediaSegments_, destStream->currentNumberSeq_);
336     MEDIA_LOG_I("select bitrate from type:" PUBLIC_LOG_D32 ", to type:" PUBLIC_LOG_D32 ", nextSegTime:"
337         PUBLIC_LOG_U32 ", bandwidth:" PUBLIC_LOG_U32 ", id:" PUBLIC_LOG_D32 ", width:"
338         PUBLIC_LOG_U32, currentStream->videoType_, destStream->videoType_, param.nextSegTime_,
339         destStream->bandwidth_, destStream->streamId_, destStream->width_);
340 
341     DashMpdGetRet ret = GetSegmentsInNewStream(destStream);
342     if (ret == DASH_MPD_GET_DONE && param.nextSegTime_ > 0) {
343         UpdateCurrentNumberSeqByTime(destStream, param.nextSegTime_);
344         param.nextSegTime_ = 0;
345     }
346 
347     return ret;
348 }
349 
GetNextTrackStream(DashMpdTrackParam & param)350 DashMpdGetRet DashMpdDownloader::GetNextTrackStream(DashMpdTrackParam &param)
351 {
352     std::shared_ptr<DashStreamDescription> currentStream = nullptr;
353     std::shared_ptr<DashStreamDescription> destStream = nullptr;
354     for (const auto &stream : streamDescriptions_) {
355         if (stream->type_ != param.type_) {
356             continue;
357         }
358 
359         if (stream->streamId_ == param.streamId_) {
360             destStream = stream;
361             MEDIA_LOG_I("switch to id:" PUBLIC_LOG_D32 ", lang:" PUBLIC_LOG_S,
362                 stream->streamId_, stream->lang_.c_str());
363         }
364 
365         if (stream->inUse_) {
366             currentStream = stream;
367         }
368     }
369 
370     if (destStream == nullptr || currentStream == nullptr) {
371         MEDIA_LOG_E("switch to streamId:" PUBLIC_LOG_D32 ", can not find stream", param.streamId_);
372         return DASH_MPD_GET_ERROR;
373     }
374 
375     currentStream->inUse_ = false;
376     destStream->inUse_ = true;
377 
378     if (destStream->startNumberSeq_ != currentStream->startNumberSeq_) {
379         MEDIA_LOG_E("select track streamId:" PUBLIC_LOG_D32 " but seq:" PUBLIC_LOG_D64 " is not equal bitrate:"
380             PUBLIC_LOG_D32 ", seq:" PUBLIC_LOG_D64, destStream->streamId_, destStream->startNumberSeq_,
381         currentStream->streamId_, currentStream->startNumberSeq_);
382     }
383     if (param.position_ == -1) {
384         destStream->currentNumberSeq_ = currentStream->currentNumberSeq_;
385     } else {
386         destStream->currentNumberSeq_ = param.position_;
387     }
388 
389     if (!param.isEnd_) {
390         destStream->currentNumberSeq_ -= 1;
391         if (destStream->currentNumberSeq_ < destStream->startNumberSeq_) {
392             destStream->currentNumberSeq_ = -1;
393         }
394     }
395 
396     param.nextSegTime_ = GetSegTimeBySeq(currentStream->mediaSegments_, destStream->currentNumberSeq_);
397     MEDIA_LOG_I("select track current lang:" PUBLIC_LOG_S ", change to:" PUBLIC_LOG_S ",nextSegTime:"
398         PUBLIC_LOG_U32, currentStream->lang_.c_str(), destStream->lang_.c_str(), param.nextSegTime_);
399 
400     DashMpdGetRet ret = GetSegmentsInNewStream(destStream);
401     if (ret == DASH_MPD_GET_DONE && param.nextSegTime_ > 0) {
402         UpdateCurrentNumberSeqByTime(destStream, param.nextSegTime_);
403         param.nextSegTime_ = 0;
404     }
405 
406     return ret;
407 }
408 
GetStreamByStreamId(int streamId)409 std::shared_ptr<DashStreamDescription> DashMpdDownloader::GetStreamByStreamId(int streamId)
410 {
411     auto iter = std::find_if(streamDescriptions_.begin(), streamDescriptions_.end(),
412         [&](const std::shared_ptr<DashStreamDescription> &stream) {
413             return stream->streamId_ == streamId;
414         });
415     if (iter == streamDescriptions_.end()) {
416         return nullptr;
417     }
418 
419     return *iter;
420 }
421 
GetUsingStreamByType(MediaAVCodec::MediaType type)422 std::shared_ptr<DashStreamDescription> DashMpdDownloader::GetUsingStreamByType(MediaAVCodec::MediaType type)
423 {
424     auto iter = std::find_if(streamDescriptions_.begin(), streamDescriptions_.end(),
425         [&](const std::shared_ptr<DashStreamDescription> &stream) {
426             return stream->type_ == type && stream->inUse_;
427         });
428     if (iter == streamDescriptions_.end()) {
429         return nullptr;
430     }
431 
432     return *iter;
433 }
434 
GetInitSegmentByStreamId(int streamId)435 std::shared_ptr<DashInitSegment> DashMpdDownloader::GetInitSegmentByStreamId(int streamId)
436 {
437     auto iter = std::find_if(streamDescriptions_.begin(), streamDescriptions_.end(),
438         [&](const std::shared_ptr<DashStreamDescription> &streamDescription) {
439             return streamDescription->streamId_ == streamId;
440         });
441     if (iter == streamDescriptions_.end()) {
442         return nullptr;
443     }
444     return (*iter)->initSegment_;
445 }
446 
SetCurrentNumberSeqByStreamId(int streamId,int64_t numberSeq)447 void DashMpdDownloader::SetCurrentNumberSeqByStreamId(int streamId, int64_t numberSeq)
448 {
449     for (unsigned int index = 0; index < streamDescriptions_.size(); index++) {
450         if (streamDescriptions_[index]->streamId_ == streamId) {
451             streamDescriptions_[index]->currentNumberSeq_ = numberSeq;
452             MEDIA_LOG_I("SetCurrentNumberSeqByStreamId update id:" PUBLIC_LOG_D32 ", seq:"
453                 PUBLIC_LOG_D64, streamId, numberSeq);
454             break;
455         }
456     }
457 }
458 
UpdateCurrentNumberSeqByTime(const std::shared_ptr<DashStreamDescription> & streamDesc,uint32_t nextSegTime)459 void DashMpdDownloader::UpdateCurrentNumberSeqByTime(const std::shared_ptr<DashStreamDescription> &streamDesc,
460     uint32_t nextSegTime)
461 {
462     if (streamDesc == nullptr) {
463         return;
464     }
465 
466     unsigned int previousSegsDuration = 0;
467     int64_t numberSeq = -1;
468     for (unsigned int index = 0; index <  streamDesc->mediaSegments_.size(); index++) {
469         previousSegsDuration += streamDesc->mediaSegments_[index]->duration_;
470         // previousSegsDuration greater than nextSegTime 100ms, get this segment, otherwise find next segment to check
471         if (previousSegsDuration > nextSegTime && (previousSegsDuration - nextSegTime) > SEGMENT_DURATION_DELTA) {
472             MEDIA_LOG_I("UpdateSeqByTime find next seq:" PUBLIC_LOG_D64, streamDesc->mediaSegments_[index]->numberSeq_);
473             break;
474         }
475 
476         numberSeq = streamDesc->mediaSegments_[index]->numberSeq_;
477     }
478 
479     MEDIA_LOG_I("UpdateSeqByTime change current seq from:" PUBLIC_LOG_D64 " to:" PUBLIC_LOG_D64 ", nextSegTime:"
480         PUBLIC_LOG_U32, streamDesc->currentNumberSeq_, numberSeq, nextSegTime);
481     streamDesc->currentNumberSeq_ = numberSeq;
482 }
483 
SetHdrStart(bool isHdrStart)484 void DashMpdDownloader::SetHdrStart(bool isHdrStart)
485 {
486     MEDIA_LOG_I("SetHdrStart:" PUBLIC_LOG_D32, isHdrStart);
487     isHdrStart_ = isHdrStart;
488 }
489 
SetInitResolution(unsigned int width,unsigned int height)490 void DashMpdDownloader::SetInitResolution(unsigned int width, unsigned int height)
491 {
492     MEDIA_LOG_I("SetInitResolution, width:" PUBLIC_LOG_U32 ", height:" PUBLIC_LOG_U32, width, height);
493     if (width > 0 && height > 0) {
494         initResolution_ = width * height;
495     }
496 }
497 
SetDefaultLang(const std::string & lang,MediaAVCodec::MediaType type)498 void DashMpdDownloader::SetDefaultLang(const std::string &lang, MediaAVCodec::MediaType type)
499 {
500     MEDIA_LOG_I("SetDefaultLang, lang:" PUBLIC_LOG_S ", type:" PUBLIC_LOG_D32, lang.c_str(), (int)type);
501     if (type == MediaAVCodec::MediaType::MEDIA_TYPE_AUD) {
502         defaultAudioLang_ = lang;
503     } else if (type == MediaAVCodec::MediaType::MEDIA_TYPE_SUBTITLE) {
504         defaultSubtitleLang_ = lang;
505     }
506 }
507 
SetInterruptState(bool isInterruptNeeded)508 void DashMpdDownloader::SetInterruptState(bool isInterruptNeeded)
509 {
510     isInterruptNeeded_ = isInterruptNeeded;
511     if (downloader_ != nullptr) {
512         downloader_->SetInterruptState(isInterruptNeeded);
513     }
514 }
515 
GetUrl() const516 std::string DashMpdDownloader::GetUrl() const
517 {
518     return url_;
519 }
520 
ParseManifest()521 void DashMpdDownloader::ParseManifest()
522 {
523     if (downloadContent_.length() == 0) {
524         MEDIA_LOG_I("ParseManifest content length is 0");
525         return;
526     }
527 
528     mpdParser_->ParseMPD(downloadContent_.c_str(), downloadContent_.length());
529     mpdParser_->GetMPD(mpdInfo_);
530     if (mpdInfo_ != nullptr) {
531         mpdManager_->SetMpdInfo(mpdInfo_, url_);
532         mpdManager_->GetDuration(&duration_);
533         SetOndemandSegBase();
534         GetStreamsInfoInMpd();
535         ChooseStreamToPlay(MediaAVCodec::MediaType::MEDIA_TYPE_VID);
536         ChooseStreamToPlay(MediaAVCodec::MediaType::MEDIA_TYPE_AUD);
537         ChooseStreamToPlay(MediaAVCodec::MediaType::MEDIA_TYPE_SUBTITLE);
538         if (ondemandSegBase_) {
539             PutStreamToDownload();
540             ProcessDrmInfos();
541             return;
542         }
543 
544         if (callback_ != nullptr) {
545             callback_->OnMpdInfoUpdate(DASH_MPD_EVENT_STREAM_INIT);
546         }
547 
548         ProcessDrmInfos();
549         notifyOpenOk_ = true;
550     }
551 }
552 
GetDrmInfos(std::vector<DashDrmInfo> & drmInfos)553 void DashMpdDownloader::GetDrmInfos(std::vector<DashDrmInfo>& drmInfos)
554 {
555     std::list<DashPeriodInfo*> periods = mpdInfo_->periodInfoList_;
556     for (auto &periodInfo : periods) {
557         if (periodInfo == nullptr) {
558             continue;
559         }
560         std::string periodDrmId{"PeriodId:"};
561         periodDrmId.append(periodInfo->id_);
562         GetAdpDrmInfos(drmInfos, periodInfo, periodDrmId);
563     }
564 }
565 
GetAdpDrmInfos(std::vector<DashDrmInfo> & drmInfos,DashPeriodInfo * const & periodInfo,const std::string & periodDrmId)566 void DashMpdDownloader::GetAdpDrmInfos(std::vector<DashDrmInfo> &drmInfos, DashPeriodInfo *const &periodInfo,
567                                        const std::string &periodDrmId)
568 {
569     DashList<DashAdptSetInfo*> adptSetList = periodInfo->adptSetList_;
570     for (const auto &adptSetInfo : adptSetList) {
571         if (adptSetInfo == nullptr) {
572             continue;
573         }
574 
575         std::string adptSetDrmId = periodDrmId;
576         adptSetDrmId.append(":AdptSetId:");
577         adptSetDrmId.append(std::to_string(adptSetInfo->id_));
578         GetDrmInfos(adptSetDrmId, adptSetInfo->commonAttrsAndElements_.contentProtectionList_, drmInfos);
579         DashList<DashRepresentationInfo*> representationList = adptSetInfo->representationList_;
580         for (auto &representationInfo : representationList) {
581             if (representationInfo == nullptr) {
582                 continue;
583             }
584             std::string representationDrmId = adptSetDrmId;
585             representationDrmId.append(":RepresentationId:");
586             representationDrmId.append(representationInfo->id_);
587             GetDrmInfos(representationDrmId, representationInfo->commonAttrsAndElements_.contentProtectionList_,
588                         drmInfos);
589         }
590     }
591 }
592 
ProcessDrmInfos()593 void DashMpdDownloader::ProcessDrmInfos()
594 {
595     std::vector<DashDrmInfo> drmInfos;
596     GetDrmInfos(drmInfos);
597 
598     std::multimap<std::string, std::vector<uint8_t>> drmInfoMap;
599     for (const auto &drmInfo: drmInfos) {
600         bool isReported = std::any_of(localDrmInfos_.begin(), localDrmInfos_.end(),
601             [&](const DashDrmInfo &localDrmInfo) {
602                 return drmInfo.uuid_ == localDrmInfo.uuid_ && drmInfo.pssh_ == localDrmInfo.pssh_;
603             });
604         if (isReported) {
605             continue;
606         }
607 
608         std::string psshString = drmInfo.pssh_;
609         uint8_t pssh[2048]; // 2048: pssh len
610         uint32_t psshSize = 2048; // 2048: pssh len
611         if (Base64Utils::Base64Decode(reinterpret_cast<const uint8_t *>(psshString.c_str()),
612                                       static_cast<uint32_t>(psshString.length()), pssh, &psshSize)) {
613             uint32_t uuidSize = 16; // 16: uuid len
614             if (psshSize < DRM_UUID_OFFSET + uuidSize) {
615                 continue;
616             }
617 
618             uint8_t uuid[16]; // 16: uuid len
619             errno_t ret = memcpy_s(uuid, sizeof(uuid), pssh + DRM_UUID_OFFSET, uuidSize);
620             if (ret != EOK) {
621                 MEDIA_LOG_W("fetch uuid from pssh error, drmId " PUBLIC_LOG_S, drmInfo.drmId_.c_str());
622                 continue;
623             }
624             std::stringstream ssConverter;
625             std::string uuidString;
626             for (uint32_t i = 0; i < uuidSize; i++) {
627                 ssConverter << std::hex << std::setfill('0') << std::setw(2) << static_cast<int32_t>(uuid[i]); // 2:w
628                 uuidString = ssConverter.str();
629             }
630             drmInfoMap.insert({uuidString, std::vector<uint8_t>(pssh, pssh + psshSize)});
631             localDrmInfos_.emplace_back(drmInfo);
632         } else {
633             MEDIA_LOG_W("Base64Decode pssh error, drmId " PUBLIC_LOG_S, drmInfo.drmId_.c_str());
634         }
635     }
636 
637     if (callback_ != nullptr) {
638         callback_->OnDrmInfoChanged(drmInfoMap);
639     }
640 }
641 
GetDrmInfos(const std::string & drmId,const DashList<DashDescriptor * > & contentProtections,std::vector<DashDrmInfo> & drmInfoList)642 void DashMpdDownloader::GetDrmInfos(const std::string &drmId, const DashList<DashDescriptor *> &contentProtections,
643                                     std::vector<DashDrmInfo> &drmInfoList)
644 {
645     for (const auto &contentProtection : contentProtections) {
646         if (contentProtection == nullptr) {
647             continue;
648         }
649 
650         std::string schemeIdUrl = contentProtection->schemeIdUrl_;
651         size_t uuidPos = schemeIdUrl.find(DRM_URN_UUID_PREFIX);
652         if (uuidPos != std::string::npos) {
653             std::string urnUuid = DRM_URN_UUID_PREFIX;
654             std::string systemId = schemeIdUrl.substr(uuidPos + urnUuid.length());
655             auto elementIt = contentProtection->elementMap_.find(MPD_LABEL_PSSH);
656             if (elementIt != contentProtection->elementMap_.end()) {
657                 DashDrmInfo drmInfo = {drmId, systemId, elementIt->second};
658                 drmInfoList.emplace_back(drmInfo);
659             }
660         }
661     }
662 }
663 
ParseSidx()664 void DashMpdDownloader::ParseSidx()
665 {
666     if (downloadContent_.length() == 0 || currentDownloadStream_ == nullptr ||
667         currentDownloadStream_->indexSegment_ == nullptr) {
668         MEDIA_LOG_I("ParseSidx content length is 0 or stream is nullptr");
669         return;
670     }
671 
672     std::string sidxContent = downloadContent_;
673     if (CheckToDownloadSidxWithInitSeg(currentDownloadStream_)) {
674         currentDownloadStream_->initSegment_->content_ = downloadContent_;
675         currentDownloadStream_->initSegment_->isDownloadFinish_ = true;
676         MEDIA_LOG_I("ParseSidx update init segment content size is "
677             PUBLIC_LOG_ZU, currentDownloadStream_->initSegment_->content_.size());
678         int64_t initLen = currentDownloadStream_->indexSegment_->indexRangeBegin_ -
679                           currentDownloadStream_->initSegment_->rangeBegin_;
680         if (initLen >= 0 && (unsigned int)initLen < downloadContent_.size()) {
681             sidxContent = downloadContent_.substr((unsigned int)initLen);
682             MEDIA_LOG_I("ParseSidx update sidx segment content size is " PUBLIC_LOG_ZU, sidxContent.size());
683         }
684     }
685 
686     std::list<std::shared_ptr<SubSegmentIndex>> subSegIndexList;
687     int32_t parseRet = SidxBoxParser::ParseSidxBox(const_cast<char *>(sidxContent.c_str()), sidxContent.length(),
688                                                    currentDownloadStream_->indexSegment_->indexRangeEnd_,
689                                                    subSegIndexList);
690     if (parseRet != 0) {
691         MEDIA_LOG_E("sidx box parse error");
692         return;
693     }
694 
695     BuildDashSegment(subSegIndexList);
696     currentDownloadStream_->segsState_ = DASH_SEGS_STATE_FINISH;
697     if (!notifyOpenOk_) {
698         if (!PutStreamToDownload()) {
699             if (callback_ != nullptr) {
700                 callback_->OnMpdInfoUpdate(DASH_MPD_EVENT_STREAM_INIT);
701             }
702 
703             notifyOpenOk_ = true;
704         }
705     } else {
706         if (callback_ != nullptr) {
707             callback_->OnMpdInfoUpdate(DASH_MPD_EVENT_PARSE_OK);
708         }
709     }
710 }
711 
BuildDashSegment(std::list<std::shared_ptr<SubSegmentIndex>> & subSegIndexList) const712 void DashMpdDownloader::BuildDashSegment(std::list<std::shared_ptr<SubSegmentIndex>> &subSegIndexList) const
713 {
714     uint64_t segDurSum = 0; // the sum of segment duration, not devide timescale
715     uint64_t segAddDuration = 0; // add all segments duration(ms) before current segment
716     uint32_t timeScale = 1;
717     int64_t segSeq = currentDownloadStream_->startNumberSeq_;
718     for (const auto &subSegIndex : subSegIndexList) {
719         timeScale = (subSegIndex->timeScale_ > 0) ? subSegIndex->timeScale_ : 1;
720         uint64_t durationMS = (static_cast<uint64_t>(subSegIndex->duration_) * S_2_MS) / timeScale;
721         segDurSum += subSegIndex->duration_;
722         uint64_t segDurMsSum = (segDurSum * S_2_MS) / timeScale;
723         if (segDurMsSum >= UINT_MAX) {
724             MEDIA_LOG_W("segDurMsSum is too large: " PUBLIC_LOG_U64 ", timeScale: "
725                 PUBLIC_LOG_U32, segDurMsSum, timeScale);
726             break;
727         }
728 
729         if (segDurMsSum > segAddDuration) {
730             durationMS = segDurMsSum - segAddDuration;
731         }
732 
733         segAddDuration += durationMS;
734 
735         DashSegment srcSegment;
736         srcSegment.streamId_ = currentDownloadStream_->streamId_;
737         srcSegment.bandwidth_ = currentDownloadStream_->bandwidth_;
738         srcSegment.duration_ = (uint32_t)durationMS;
739         srcSegment.startNumberSeq_ = currentDownloadStream_->startNumberSeq_;
740         srcSegment.numberSeq_ = segSeq++;
741         srcSegment.startRangeValue_ = subSegIndex->startPos_;
742         srcSegment.endRangeValue_ = subSegIndex->endPos_;
743         srcSegment.url_ = currentDownloadStream_->indexSegment_->url_; // only store url in stream in Dash On-Demand
744         srcSegment.byteRange_ = "";
745         if (DASH_SEGMENT_INIT_FAILED == AddOneSegment(srcSegment, currentDownloadStream_)) {
746             MEDIA_LOG_E("ParseSidx AddOneSegment is failed");
747         }
748     }
749 
750     if (currentDownloadStream_->mediaSegments_.size() > 0) {
751         std::shared_ptr<DashSegment> lastSegment = currentDownloadStream_->mediaSegments_[
752             currentDownloadStream_->mediaSegments_.size() - 1];
753         if (lastSegment != nullptr && mpdInfo_ != nullptr && mpdInfo_->type_ == DashType::DASH_TYPE_STATIC) {
754             lastSegment->isLast_ = true;
755         }
756     }
757 }
758 
OpenStream(std::shared_ptr<DashStreamDescription> stream)759 void DashMpdDownloader::OpenStream(std::shared_ptr<DashStreamDescription> stream)
760 {
761     stream->segsState_ = DASH_SEGS_STATE_PARSING;
762     currentDownloadStream_ = stream;
763     int64_t startRange = stream->indexSegment_->indexRangeBegin_;
764     int64_t endRange = stream->indexSegment_->indexRangeEnd_;
765     // exist init segment, download together
766     if (CheckToDownloadSidxWithInitSeg(stream)) {
767         MEDIA_LOG_I("update range begin from " PUBLIC_LOG_D64 " to "
768             PUBLIC_LOG_D64, startRange, stream->initSegment_->rangeBegin_);
769         startRange = stream->initSegment_->rangeBegin_;
770     }
771     DoOpen(stream->indexSegment_->url_, startRange, endRange);
772 }
773 
DoOpen(const std::string & url,int64_t startRange,int64_t endRange)774 void DashMpdDownloader::DoOpen(const std::string& url, int64_t startRange, int64_t endRange)
775 {
776     downloadContent_.clear();
777     auto realStatusCallback = [this](DownloadStatus &&status, std::shared_ptr<Downloader> &downloader,
778         std::shared_ptr<DownloadRequest> &request) {
779         if (statusCallback_ != nullptr) {
780             statusCallback_(status, downloader_, std::forward<decltype(request)>(request));
781         }
782     };
783 
784     bool requestWholeFile = true;
785     if (startRange > 0 || endRange > 0) {
786         requestWholeFile = false;
787     }
788 
789     MEDIA_LOG_I("DoOpen:start=%{public}lld end=%{public}lld", (long long) startRange, (long long) endRange);
790     RequestInfo mediaSource;
791     mediaSource.url = url;
792     mediaSource.timeoutMs = MPD_HTTP_TIME_OUT_MS;
793     downloadRequest_ = std::make_shared<DownloadRequest>(dataSave_, realStatusCallback, mediaSource, requestWholeFile);
794     auto downloadDoneCallback = [this](const std::string &url, const std::string &location) {
795         UpdateDownloadFinished(url);
796     };
797     downloadRequest_->SetDownloadDoneCb(downloadDoneCallback);
798 
799     if (!requestWholeFile) {
800         downloadRequest_->SetRangePos(startRange, endRange);
801     }
802     downloader_->Download(downloadRequest_, -1); // -1
803     downloader_->Start();
804 }
805 
SaveData(uint8_t * data,uint32_t len)806 bool DashMpdDownloader::SaveData(uint8_t* data, uint32_t len)
807 {
808     MEDIA_LOG_D("SaveData:size=%{public}u len=%{public}u", (unsigned int)downloadContent_.size(), len);
809     downloadContent_.append(reinterpret_cast<const char*>(data), len);
810     return true;
811 }
812 
SetMpdCallback(DashMpdCallback * callback)813 void DashMpdDownloader::SetMpdCallback(DashMpdCallback *callback)
814 {
815     callback_ = callback;
816 }
817 
GetDuration() const818 int64_t DashMpdDownloader::GetDuration() const
819 {
820     MEDIA_LOG_I("GetDuration " PUBLIC_LOG_U32, duration_);
821     return (duration_ > 0) ? ((int64_t)duration_ * MS_2_NS) : 0;
822 }
823 
GetSeekable() const824 Seekable DashMpdDownloader::GetSeekable() const
825 {
826     // need wait mpdInfo_ not null
827     size_t times = 0;
828     while (times < RETRY_TIMES && !isInterruptNeeded_) {
829         if (mpdInfo_ != nullptr && notifyOpenOk_) {
830             break;
831         }
832         OSAL::SleepFor(SLEEP_TIME);
833         times++;
834     }
835 
836     if (times >= RETRY_TIMES || isInterruptNeeded_) {
837         MEDIA_LOG_I("GetSeekable INVALID");
838         return Seekable::INVALID;
839     }
840 
841     MEDIA_LOG_I("GetSeekable end");
842     return mpdInfo_->type_ == DashType::DASH_TYPE_STATIC ? Seekable::SEEKABLE : Seekable::UNSEEKABLE;
843 }
844 
GetBitRates() const845 std::vector<uint32_t> DashMpdDownloader::GetBitRates() const
846 {
847     std::vector<uint32_t> bitRates;
848     for (const auto &item : streamDescriptions_) {
849         if (item->type_ == MediaAVCodec::MediaType::MEDIA_TYPE_VID && item->bandwidth_ > 0) {
850             bitRates.push_back(item->bandwidth_);
851         }
852     }
853     return bitRates;
854 }
855 
GetBitRatesByHdr(bool isHdr) const856 std::vector<uint32_t> DashMpdDownloader::GetBitRatesByHdr(bool isHdr) const
857 {
858     std::vector<uint32_t> bitRates;
859     for (const auto &item : streamDescriptions_) {
860         if (item->type_ == MediaAVCodec::MediaType::MEDIA_TYPE_VID &&
861             item->bandwidth_ > 0 &&
862             (isHdr == (item->videoType_ != DASH_VIDEO_TYPE_SDR))) {
863             bitRates.push_back(item->bandwidth_);
864         }
865     }
866     return bitRates;
867 }
868 
SeekToTs(int streamId,int64_t seekTime,std::shared_ptr<DashSegment> & seg) const869 void DashMpdDownloader::SeekToTs(int streamId, int64_t seekTime, std::shared_ptr<DashSegment> &seg) const
870 {
871     seg = nullptr;
872     std::vector<std::shared_ptr<DashSegment>> mediaSegments;
873     std::shared_ptr<DashStreamDescription> streamDescription;
874     for (const auto &index : streamDescriptions_) {
875         streamDescription = index;
876         if (streamDescription != nullptr && streamDescription->streamId_ == streamId &&
877             streamDescription->segsState_ == DASH_SEGS_STATE_FINISH) {
878             mediaSegments = streamDescription->mediaSegments_;
879             break;
880         }
881     }
882 
883     if (!mediaSegments.empty()) {
884         int64_t totalDuration = 0;
885         for (const auto &mediaSegment : mediaSegments) {
886             if (mediaSegment == nullptr) {
887                 continue;
888             }
889 
890             totalDuration += static_cast<int64_t>(mediaSegment->duration_);
891             if (totalDuration > seekTime) {
892                 seg = mediaSegment;
893                 MEDIA_LOG_I("Dash SeekToTs segment totalDuration:" PUBLIC_LOG_D64 ", segNum:"
894                     PUBLIC_LOG_D64 ", duration:" PUBLIC_LOG_U32,
895                     totalDuration, mediaSegment->numberSeq_, mediaSegment->duration_);
896                 return;
897             }
898         }
899     }
900 }
901 
902 /**
903  * @brief    get segments in Period with SegmentTemplate or SegmentList or BaseUrl
904  *
905  * @param    periodInfo             current Period
906  * @param    adptSetInfo            current AdptSet
907  * @param    periodBaseUrl          Mpd.BaseUrl
908  * @param    streamDesc             stream description
909  *
910  * @return   failed success undo
911  */
GetSegmentsByPeriodInfo(DashPeriodInfo * periodInfo,DashAdptSetInfo * adptSetInfo,std::string & periodBaseUrl,std::shared_ptr<DashStreamDescription> streamDesc)912 DashSegmentInitValue DashMpdDownloader::GetSegmentsByPeriodInfo(DashPeriodInfo *periodInfo,
913                                                                 DashAdptSetInfo *adptSetInfo,
914                                                                 std::string &periodBaseUrl,
915                                                                 std::shared_ptr<DashStreamDescription> streamDesc)
916 {
917     DashSegmentInitValue initVal;
918     // get segments from Period.SegmentTemplate
919     if (periodInfo->periodSegTmplt_ != nullptr && periodInfo->periodSegTmplt_->segTmpltMedia_.length() > 0) {
920         DashAppendBaseUrl(periodBaseUrl, periodInfo->baseUrl_);
921 
922         std::string representationId;
923         // get Representation@id in the chosen AdaptationSet
924         if (adptSetInfo != nullptr && streamDesc->bandwidth_ > 0) {
925             DashRepresentationInfo *repInfo = GetRepresentationFromAdptSet(adptSetInfo,
926                                                                            streamDesc->representationIndex_);
927             if (repInfo != nullptr) {
928                 representationId = repInfo->id_;
929             }
930         }
931 
932         initVal = GetSegmentsWithSegTemplate(periodInfo->periodSegTmplt_, representationId, streamDesc);
933     } else if (periodInfo->periodSegList_ != nullptr && periodInfo->periodSegList_->segmentUrl_.size() > 0) {
934         // get segments from Period.SegmentList
935         DashAppendBaseUrl(periodBaseUrl, periodInfo->baseUrl_);
936         initVal = GetSegmentsWithSegList(periodInfo->periodSegList_, periodBaseUrl, streamDesc);
937     } else if (periodInfo->baseUrl_.size() > 0) {
938         // get segments fromn Period.BaseUrl
939         initVal = GetSegmentsWithBaseUrl(periodInfo->baseUrl_, streamDesc);
940     } else {
941         initVal = DASH_SEGMENT_INIT_UNDO;
942     }
943 
944     return initVal;
945 }
946 
SetOndemandSegBase()947 void DashMpdDownloader::SetOndemandSegBase()
948 {
949     for (const auto &periodInfo : mpdInfo_->periodInfoList_) {
950         if (SetOndemandSegBase(periodInfo->adptSetList_)) {
951             break;
952         }
953     }
954 
955     MEDIA_LOG_I("dash onDemandSegBase is " PUBLIC_LOG_D32, ondemandSegBase_);
956 }
957 
SetOndemandSegBase(std::list<DashAdptSetInfo * > adptSetList)958 bool DashMpdDownloader::SetOndemandSegBase(std::list<DashAdptSetInfo*> adptSetList)
959 {
960     for (const auto &adptSetInfo : adptSetList) {
961         if (adptSetInfo->representationList_.size() == 0) {
962             if (adptSetInfo->adptSetSegBase_ != nullptr && adptSetInfo->adptSetSegBase_->indexRange_.size() > 0) {
963                 ondemandSegBase_ = true;
964                 return true;
965             }
966         } else {
967             if (SetOndemandSegBase(adptSetInfo->representationList_)) {
968                 return true;
969             }
970         }
971     }
972 
973     return false;
974 }
975 
SetOndemandSegBase(std::list<DashRepresentationInfo * > repList)976 bool DashMpdDownloader::SetOndemandSegBase(std::list<DashRepresentationInfo*> repList)
977 {
978     for (const auto &rep : repList) {
979         if (rep->representationSegList_ != nullptr || rep->representationSegTmplt_ != nullptr) {
980             MEDIA_LOG_I("dash representation contain segmentlist or template");
981             ondemandSegBase_ = false;
982             return true;
983         }
984 
985         if (rep->representationSegBase_ != nullptr && rep->representationSegBase_->indexRange_.size() > 0) {
986             MEDIA_LOG_I("dash representation contain indexRange");
987             ondemandSegBase_ = true;
988             return true;
989         }
990     }
991 
992     return false;
993 }
994 
CheckToDownloadSidxWithInitSeg(std::shared_ptr<DashStreamDescription> streamDesc)995 bool DashMpdDownloader::CheckToDownloadSidxWithInitSeg(std::shared_ptr<DashStreamDescription> streamDesc)
996 {
997     if (streamDesc->initSegment_ != nullptr &&
998         streamDesc->initSegment_->url_.compare(streamDesc->indexSegment_->url_) == 0 &&
999         streamDesc->indexSegment_->indexRangeBegin_ > streamDesc->initSegment_->rangeEnd_) {
1000         return true;
1001     }
1002 
1003     return false;
1004 }
1005 
GetStreamsInfoInMpd()1006 bool DashMpdDownloader::GetStreamsInfoInMpd()
1007 {
1008     if (mpdInfo_ == nullptr) {
1009         return false;
1010     }
1011 
1012     mpdManager_->SetMpdInfo(mpdInfo_, url_);
1013     std::string mpdBaseUrl = mpdManager_->GetBaseUrl();
1014     std::list<DashPeriodInfo*> periods = mpdInfo_->periodInfoList_;
1015     unsigned int periodIndex = 0;
1016     for (std::list<DashPeriodInfo*>::iterator it = periods.begin(); it != periods.end(); ++it, ++periodIndex) {
1017         DashPeriodInfo *period = *it;
1018         if (period == nullptr) {
1019             continue;
1020         }
1021 
1022         GetStreamsInfoInPeriod(period, periodIndex, mpdBaseUrl);
1023     }
1024 
1025     int size = static_cast<int>(streamDescriptions_.size());
1026     for (int index = 0; index < size; index++) {
1027         streamDescriptions_[index]->streamId_ = index;
1028         std::shared_ptr<DashInitSegment> initSegment = streamDescriptions_[index]->initSegment_;
1029         if (initSegment != nullptr) {
1030             initSegment->streamId_ = index;
1031         }
1032     }
1033 
1034     return true;
1035 }
1036 
GetStreamsInfoInPeriod(DashPeriodInfo * periodInfo,unsigned int periodIndex,const std::string & mpdBaseUrl)1037 void DashMpdDownloader::GetStreamsInfoInPeriod(DashPeriodInfo *periodInfo, unsigned int periodIndex,
1038                                                const std::string &mpdBaseUrl)
1039 {
1040     periodManager_->SetPeriodInfo(periodInfo);
1041     DashStreamDescription streamDesc;
1042     streamDesc.duration_ = (periodInfo->duration_ > 0) ? periodInfo->duration_ : duration_;
1043     streamDesc.periodIndex_ = periodIndex;
1044     std::string periodBaseUrl = mpdBaseUrl;
1045     DashAppendBaseUrl(periodBaseUrl, periodInfo->baseUrl_);
1046 
1047     if (periodInfo->adptSetList_.size() == 0) {
1048         streamDesc.startNumberSeq_ = GetStartNumber(periodInfo);
1049         // no adaptationset in period, store as video stream
1050         std::shared_ptr<DashStreamDescription> desc = std::make_shared<DashStreamDescription>(streamDesc);
1051 
1052         GetInitSegFromPeriod(periodBaseUrl, "", desc);
1053         if (ondemandSegBase_ && periodInfo->periodSegBase_ != nullptr &&
1054             periodInfo->periodSegBase_->indexRange_.size() > 0) {
1055             desc->indexSegment_ = std::make_shared<DashIndexSegment>();
1056             desc->indexSegment_->url_ = periodBaseUrl;
1057             DashParseRange(periodInfo->periodSegBase_->indexRange_, desc->indexSegment_->indexRangeBegin_,
1058                            desc->indexSegment_->indexRangeEnd_);
1059         }
1060         streamDescriptions_.push_back(desc);
1061         return;
1062     }
1063 
1064     std::vector<DashAdptSetInfo*> adptSetVector;
1065     DashAdptSetInfo *adptSetInfo = nullptr;
1066     for (int32_t type = MediaAVCodec::MediaType::MEDIA_TYPE_AUD;
1067         type <= MediaAVCodec::MediaType::MEDIA_TYPE_SUBTITLE; type++) {
1068         streamDesc.type_ = (MediaAVCodec::MediaType)type;
1069         periodManager_->GetAdptSetsByStreamType(adptSetVector, streamDesc.type_);
1070         if (adptSetVector.size() == 0) {
1071             MEDIA_LOG_I("Get streamType " PUBLIC_LOG_D32 " in period " PUBLIC_LOG_U32 " size is 0", type, periodIndex);
1072             continue;
1073         }
1074 
1075         for (unsigned int adptSetIndex = 0; adptSetIndex < adptSetVector.size(); adptSetIndex++) {
1076             streamDesc.adptSetIndex_ = adptSetIndex;
1077             adptSetInfo = adptSetVector[adptSetIndex];
1078             GetStreamsInfoInAdptSet(adptSetInfo, periodBaseUrl, streamDesc);
1079         }
1080     }
1081 }
1082 
GetStreamsInfoInAdptSet(DashAdptSetInfo * adptSetInfo,const std::string & periodBaseUrl,DashStreamDescription & streamDesc)1083 void DashMpdDownloader::GetStreamsInfoInAdptSet(DashAdptSetInfo *adptSetInfo, const std::string &periodBaseUrl,
1084                                                 DashStreamDescription &streamDesc)
1085 {
1086     streamDesc.width_ = adptSetInfo->commonAttrsAndElements_.width_;
1087     streamDesc.height_ = adptSetInfo->commonAttrsAndElements_.height_;
1088     streamDesc.lang_ = adptSetInfo->lang_;
1089     std::string adptSetBaseUrl = periodBaseUrl;
1090     DashAppendBaseUrl(adptSetBaseUrl, adptSetInfo->baseUrl_);
1091     adptSetManager_->SetAdptSetInfo(adptSetInfo);
1092     if (adptSetManager_->IsHdr()) {
1093         streamDesc.videoType_ = DASH_VIDEO_TYPE_HDR_10;
1094     } else {
1095         streamDesc.videoType_ = DASH_VIDEO_TYPE_SDR;
1096     }
1097     MEDIA_LOG_D("GetStreamsInfoInAdptSet hdrType " PUBLIC_LOG_U32, streamDesc.videoType_);
1098 
1099     std::list<DashRepresentationInfo*> repList = adptSetInfo->representationList_;
1100     if (repList.size() == 0) {
1101         MEDIA_LOG_I("representation count is 0 in adptset index " PUBLIC_LOG_U32, streamDesc.adptSetIndex_);
1102         streamDesc.startNumberSeq_ = GetStartNumber(adptSetInfo);
1103         std::shared_ptr<DashStreamDescription> desc = std::make_shared<DashStreamDescription>(streamDesc);
1104         if (!GetInitSegFromAdptSet(adptSetBaseUrl, "", desc)) {
1105             GetInitSegFromPeriod(periodBaseUrl, "", desc);
1106         }
1107 
1108         if (ondemandSegBase_ && adptSetInfo->adptSetSegBase_ != nullptr &&
1109             adptSetInfo->adptSetSegBase_->indexRange_.size() > 0) {
1110             desc->indexSegment_ = std::make_shared<DashIndexSegment>();
1111             desc->indexSegment_->url_ = adptSetBaseUrl;
1112             DashParseRange(adptSetInfo->adptSetSegBase_->indexRange_, desc->indexSegment_->indexRangeBegin_,
1113                            desc->indexSegment_->indexRangeEnd_);
1114         }
1115         streamDescriptions_.push_back(desc);
1116         return;
1117     }
1118 
1119     GetStreamDescriptions(periodBaseUrl, streamDesc, adptSetBaseUrl, repList);
1120 }
1121 
GetStreamDescriptions(const std::string & periodBaseUrl,DashStreamDescription & streamDesc,const std::string & adptSetBaseUrl,std::list<DashRepresentationInfo * > & repList)1122 void DashMpdDownloader::GetStreamDescriptions(const std::string &periodBaseUrl, DashStreamDescription &streamDesc,
1123                                               const std::string &adptSetBaseUrl,
1124                                               std::list<DashRepresentationInfo *> &repList)
1125 {
1126     std::string repBaseUrl;
1127     unsigned int repIndex = 0;
1128     DashVideoType defaultVideoType = streamDesc.videoType_;
1129     for (std::list<DashRepresentationInfo*>::iterator it = repList.begin(); it != repList.end(); ++it, ++repIndex) {
1130         if (*it == nullptr) {
1131             continue;
1132         }
1133 
1134         repBaseUrl = adptSetBaseUrl;
1135         streamDesc.representationIndex_ = repIndex;
1136         streamDesc.startNumberSeq_ = GetStartNumber(*it);
1137         streamDesc.bandwidth_ = (*it)->bandwidth_;
1138         if ((*it)->commonAttrsAndElements_.width_ > 0) {
1139             streamDesc.width_ = (*it)->commonAttrsAndElements_.width_;
1140         }
1141 
1142         if ((*it)->commonAttrsAndElements_.height_ > 0) {
1143             streamDesc.height_ = (*it)->commonAttrsAndElements_.height_;
1144         }
1145 
1146         if (defaultVideoType != DASH_VIDEO_TYPE_SDR &&
1147             (*it)->commonAttrsAndElements_.cuvvVersion_.find("cuvv.") != std::string::npos) {
1148             streamDesc.videoType_ = DASH_VIDEO_TYPE_HDR_VIVID;
1149             MEDIA_LOG_I("current stream is hdr vivid, band:" PUBLIC_LOG_U32, streamDesc.bandwidth_);
1150         } else {
1151             streamDesc.videoType_ = defaultVideoType;
1152         }
1153 
1154         std::shared_ptr<DashStreamDescription> desc = std::make_shared<DashStreamDescription>(streamDesc);
1155         representationManager_->SetRepresentationInfo(*it);
1156         DashAppendBaseUrl(repBaseUrl, (*it)->baseUrl_);
1157 
1158         if (!GetInitSegFromRepresentation(repBaseUrl, (*it)->id_, desc)) {
1159             if (!GetInitSegFromAdptSet(adptSetBaseUrl, (*it)->id_, desc)) {
1160                 GetInitSegFromPeriod(periodBaseUrl, (*it)->id_, desc);
1161             }
1162         }
1163 
1164         if (ondemandSegBase_ &&
1165             (*it)->representationSegBase_ != nullptr &&
1166             (*it)->representationSegBase_->indexRange_.size() > 0) {
1167             desc->indexSegment_ = std::make_shared<DashIndexSegment>();
1168             desc->indexSegment_->url_ = repBaseUrl;
1169             DashParseRange((*it)->representationSegBase_->indexRange_, desc->indexSegment_->indexRangeBegin_,
1170                            desc->indexSegment_->indexRangeEnd_);
1171         }
1172         MEDIA_LOG_I("add stream band:" PUBLIC_LOG_U32 ", hdr: " PUBLIC_LOG_D32,
1173             streamDesc.bandwidth_, streamDesc.videoType_);
1174         streamDescriptions_.push_back(desc);
1175     }
1176 }
1177 
GetResolutionDelta(unsigned int width,unsigned int height)1178 unsigned int DashMpdDownloader::GetResolutionDelta(unsigned int width, unsigned int height)
1179 {
1180     unsigned int resolution = width * height;
1181     if (resolution > initResolution_) {
1182         return resolution - initResolution_;
1183     } else {
1184         return initResolution_ - resolution;
1185     }
1186 }
1187 
IsChoosedVideoStream(const std::shared_ptr<DashStreamDescription> & choosedStream,const std::shared_ptr<DashStreamDescription> & currentStream)1188 bool DashMpdDownloader::IsChoosedVideoStream(const std::shared_ptr<DashStreamDescription> &choosedStream,
1189     const std::shared_ptr<DashStreamDescription> &currentStream)
1190 {
1191     if (choosedStream == nullptr ||
1192         (initResolution_ == 0 && choosedStream->bandwidth_ > currentStream->bandwidth_) ||
1193         IsNearToInitResolution(choosedStream, currentStream)) {
1194         return true;
1195     }
1196     return false;
1197 }
1198 
IsNearToInitResolution(const std::shared_ptr<DashStreamDescription> & choosedStream,const std::shared_ptr<DashStreamDescription> & currentStream)1199 bool DashMpdDownloader::IsNearToInitResolution(const std::shared_ptr<DashStreamDescription> &choosedStream,
1200     const std::shared_ptr<DashStreamDescription> &currentStream)
1201 {
1202     if (choosedStream == nullptr || currentStream == nullptr || initResolution_ == 0) {
1203         return false;
1204     }
1205 
1206     unsigned int choosedDelta = GetResolutionDelta(choosedStream->width_, choosedStream->height_);
1207     unsigned int currentDelta = GetResolutionDelta(currentStream->width_, currentStream->height_);
1208     return (currentDelta < choosedDelta)
1209            || (currentDelta == choosedDelta && currentStream->bandwidth_ < choosedStream->bandwidth_);
1210 }
1211 
IsLangMatch(const std::string & lang,MediaAVCodec::MediaType type)1212 bool DashMpdDownloader::IsLangMatch(const std::string &lang, MediaAVCodec::MediaType type)
1213 {
1214     if (type == MediaAVCodec::MediaType::MEDIA_TYPE_AUD &&
1215         defaultAudioLang_.length() > 0) {
1216         if (defaultAudioLang_.compare(lang) == 0) {
1217             return true;
1218         } else {
1219             return false;
1220         }
1221     } else if (type == MediaAVCodec::MediaType::MEDIA_TYPE_SUBTITLE &&
1222         defaultSubtitleLang_.length() > 0) {
1223         if (defaultSubtitleLang_.compare(lang) == 0) {
1224             return true;
1225         } else {
1226             return false;
1227         }
1228     }
1229     return true;
1230 }
1231 
ChooseStreamToPlay(MediaAVCodec::MediaType type)1232 bool DashMpdDownloader::ChooseStreamToPlay(MediaAVCodec::MediaType type)
1233 {
1234     if (mpdInfo_ == nullptr || streamDescriptions_.size() == 0) {
1235         return false;
1236     }
1237 
1238     std::shared_ptr<DashStreamDescription> choosedStream = nullptr;
1239     std::shared_ptr<DashStreamDescription> backupStream = nullptr;
1240     for (const auto &stream : streamDescriptions_) {
1241         if (stream->type_ != type || stream->inUse_) {
1242             continue;
1243         }
1244 
1245         if (type != MediaAVCodec::MediaType::MEDIA_TYPE_VID) {
1246             // audio and subtitle choose first stream to play or get default lang
1247             if (choosedStream == nullptr) {
1248                 choosedStream = stream;
1249             }
1250             if (!IsLangMatch(stream->lang_, type)) {
1251                 continue;
1252             }
1253 
1254             choosedStream = stream;
1255             break;
1256         }
1257 
1258         if (backupStream == nullptr || IsNearToInitResolution(backupStream, stream) ||
1259             (initResolution_ == 0 && backupStream->bandwidth_ > stream->bandwidth_)) {
1260             backupStream = stream;
1261         }
1262 
1263         if ((stream->videoType_ != DASH_VIDEO_TYPE_SDR) != isHdrStart_) {
1264             continue;
1265         }
1266 
1267         if (IsChoosedVideoStream(choosedStream, stream)) {
1268             choosedStream = stream;
1269         }
1270     }
1271 
1272     if (choosedStream == nullptr && type == MediaAVCodec::MediaType::MEDIA_TYPE_VID) {
1273         MEDIA_LOG_I("ChooseStreamToPlay video can not find hdrstart:" PUBLIC_LOG_D32, isHdrStart_);
1274         choosedStream = backupStream;
1275     }
1276 
1277     if (choosedStream != nullptr) {
1278         choosedStream->inUse_ = true;
1279         MEDIA_LOG_I("ChooseStreamToPlay type:" PUBLIC_LOG_D32 ", streamId:"
1280             PUBLIC_LOG_D32, (int) type, choosedStream->streamId_);
1281         if (!ondemandSegBase_) {
1282             GetSegmentsInMpd(choosedStream);
1283         }
1284         return true;
1285     }
1286 
1287     return false;
1288 }
1289 
GetSegTimeBySeq(const std::vector<std::shared_ptr<DashSegment>> & segments,int64_t segSeq)1290 unsigned int DashMpdDownloader::GetSegTimeBySeq(const std::vector<std::shared_ptr<DashSegment>> &segments,
1291                                                 int64_t segSeq)
1292 {
1293     if (segments.size() == 0) {
1294         return 0;
1295     }
1296 
1297     unsigned int nextSegTime = 0;
1298     for (unsigned int index = 0; index <  segments.size(); index++) {
1299         if (segments[index]->numberSeq_ > segSeq) {
1300             break;
1301         }
1302 
1303         nextSegTime += segments[index]->duration_;
1304     }
1305 
1306     return nextSegTime;
1307 }
1308 
GetSegmentsInMpd(std::shared_ptr<DashStreamDescription> streamDesc)1309 DashSegmentInitValue DashMpdDownloader::GetSegmentsInMpd(std::shared_ptr<DashStreamDescription> streamDesc)
1310 {
1311     if (mpdInfo_ == nullptr || streamDesc == nullptr) {
1312         MEDIA_LOG_E("GetSegments but mpdInfo_ or streamDesc is nullptr");
1313         return DASH_SEGMENT_INIT_FAILED;
1314     }
1315 
1316     streamDesc->segsState_ = DASH_SEGS_STATE_FINISH;
1317     std::string mpdBaseUrl;
1318     mpdManager_->SetMpdInfo(mpdInfo_, url_);
1319     mpdBaseUrl = mpdManager_->GetBaseUrl();
1320 
1321     unsigned int currentPeriodIndex = 0;
1322     for (std::list<DashPeriodInfo *>::iterator it = mpdInfo_->periodInfoList_.begin();
1323          it != mpdInfo_->periodInfoList_.end(); ++it, ++currentPeriodIndex) {
1324         if (*it != nullptr && currentPeriodIndex == streamDesc->periodIndex_) {
1325             if (GetSegmentsInPeriod(*it, mpdBaseUrl, streamDesc) == DASH_SEGMENT_INIT_FAILED) {
1326                 MEDIA_LOG_I("GetSegmentsInPeriod" PUBLIC_LOG_U32 " failed, type "
1327                     PUBLIC_LOG_D32, currentPeriodIndex, streamDesc->type_);
1328                 return DASH_SEGMENT_INIT_FAILED;
1329             }
1330 
1331             break;
1332         }
1333     }
1334 
1335     if (streamDesc->mediaSegments_.size() == 0) {
1336         MEDIA_LOG_E("GetSegmentsInMpd failed, type " PUBLIC_LOG_D32, streamDesc->type_);
1337         return DASH_SEGMENT_INIT_FAILED;
1338     }
1339 
1340     std::shared_ptr<DashSegment> lastSegment = streamDesc->mediaSegments_[streamDesc->mediaSegments_.size() - 1];
1341     if (lastSegment != nullptr && mpdInfo_ != nullptr && mpdInfo_->type_ == DashType::DASH_TYPE_STATIC) {
1342         lastSegment->isLast_ = true;
1343     }
1344     return DASH_SEGMENT_INIT_SUCCESS;
1345 }
1346 
GetSegmentsInPeriod(DashPeriodInfo * periodInfo,const std::string & mpdBaseUrl,std::shared_ptr<DashStreamDescription> streamDesc)1347 DashSegmentInitValue DashMpdDownloader::GetSegmentsInPeriod(DashPeriodInfo *periodInfo, const std::string &mpdBaseUrl,
1348                                                             std::shared_ptr<DashStreamDescription> streamDesc)
1349 {
1350     std::vector<DashAdptSetInfo*> adptSetVector;
1351     DashSegmentInitValue initValue = DASH_SEGMENT_INIT_UNDO;
1352     std::string periodBaseUrl = mpdBaseUrl;
1353     periodManager_->SetPeriodInfo(periodInfo);
1354     periodManager_->GetAdptSetsByStreamType(adptSetVector, streamDesc->type_);
1355     DashAdptSetInfo *adptSetInfo = nullptr;
1356 
1357     if (streamDesc->adptSetIndex_ < adptSetVector.size()) {
1358         adptSetInfo = adptSetVector[streamDesc->adptSetIndex_];
1359         DashAppendBaseUrl(periodBaseUrl, periodInfo->baseUrl_);
1360         initValue = GetSegmentsInAdptSet(adptSetInfo, periodBaseUrl, streamDesc);
1361         if (initValue != DASH_SEGMENT_INIT_UNDO) {
1362             return initValue;
1363         }
1364     }
1365 
1366     // segments in period.segmentList/segmentTemplate/baseurl, should store in video stream manager
1367     if (streamDesc->type_ != MediaAVCodec::MediaType::MEDIA_TYPE_VID) {
1368         return initValue;
1369     }
1370 
1371     // UST182 base to relative segment url
1372     periodBaseUrl = mpdBaseUrl;
1373     initValue = GetSegmentsByPeriodInfo(periodInfo, adptSetInfo, periodBaseUrl, streamDesc);
1374     if (initValue == DASH_SEGMENT_INIT_SUCCESS) {
1375         MakeAbsoluteWithBaseUrl(streamDesc->mediaSegments_, periodBaseUrl);
1376     }
1377 
1378     return initValue;
1379 }
1380 
GetSegmentsInAdptSet(DashAdptSetInfo * adptSetInfo,const std::string & periodBaseUrl,std::shared_ptr<DashStreamDescription> streamDesc)1381 DashSegmentInitValue DashMpdDownloader::GetSegmentsInAdptSet(DashAdptSetInfo *adptSetInfo,
1382                                                              const std::string &periodBaseUrl,
1383                                                              std::shared_ptr<DashStreamDescription> streamDesc)
1384 {
1385     if (adptSetInfo == nullptr) {
1386         return DASH_SEGMENT_INIT_UNDO;
1387     }
1388 
1389     DashSegmentInitValue initValue = DASH_SEGMENT_INIT_UNDO;
1390     DashRepresentationInfo* repInfo = nullptr;
1391     std::string adptSetBaseUrl = periodBaseUrl;
1392 
1393     if (streamDesc->representationIndex_ < adptSetInfo->representationList_.size()) {
1394         repInfo = GetRepresemtationFromAdptSet(adptSetInfo, streamDesc->representationIndex_);
1395         if (repInfo != nullptr) {
1396             DashAppendBaseUrl(adptSetBaseUrl, adptSetInfo->baseUrl_);
1397             initValue = GetSegmentsInRepresentation(repInfo, adptSetBaseUrl, streamDesc);
1398         }
1399 
1400         if (initValue != DASH_SEGMENT_INIT_UNDO) {
1401             return initValue;
1402         }
1403     }
1404 
1405     adptSetBaseUrl = periodBaseUrl;
1406     initValue = GetSegmentsByAdptSetInfo(adptSetInfo, repInfo, adptSetBaseUrl, streamDesc);
1407     if (initValue == DASH_SEGMENT_INIT_SUCCESS) {
1408         MakeAbsoluteWithBaseUrl(streamDesc->mediaSegments_, adptSetBaseUrl);
1409     }
1410 
1411     return initValue;
1412 }
1413 
GetSegmentsInRepresentation(DashRepresentationInfo * repInfo,const std::string & adptSetBaseUrl,std::shared_ptr<DashStreamDescription> streamDesc)1414 DashSegmentInitValue DashMpdDownloader::GetSegmentsInRepresentation(DashRepresentationInfo *repInfo,
1415                                                                     const std::string &adptSetBaseUrl,
1416                                                                     std::shared_ptr<DashStreamDescription> streamDesc)
1417 {
1418     std::string repBaseUrl = adptSetBaseUrl;
1419     DashSegmentInitValue initValue = DASH_SEGMENT_INIT_UNDO;
1420     if (repInfo->representationSegTmplt_ != nullptr && repInfo->representationSegTmplt_->segTmpltMedia_.length() > 0) {
1421         DashAppendBaseUrl(repBaseUrl, repInfo->baseUrl_);
1422         initValue = GetSegmentsWithSegTemplate(repInfo->representationSegTmplt_, repInfo->id_, streamDesc);
1423     } else if (repInfo->representationSegList_ != nullptr && repInfo->representationSegList_->segmentUrl_.size() > 0) {
1424         // get segments from Representation.SegmentList
1425         DashAppendBaseUrl(repBaseUrl, repInfo->baseUrl_);
1426         initValue = GetSegmentsWithSegList(repInfo->representationSegList_, repBaseUrl, streamDesc);
1427     } else if (repInfo->baseUrl_.size() > 0) {
1428         // get one segment from Representation.BaseUrl
1429         initValue = GetSegmentsWithBaseUrl(repInfo->baseUrl_, streamDesc);
1430     }
1431 
1432     if (initValue == DASH_SEGMENT_INIT_SUCCESS) {
1433         MakeAbsoluteWithBaseUrl(streamDesc->mediaSegments_, repBaseUrl);
1434     }
1435 
1436     return initValue;
1437 }
1438 
GetSegmentsWithSegTemplate(const DashSegTmpltInfo * segTmpltInfo,std::string id,std::shared_ptr<DashStreamDescription> streamDesc)1439 DashSegmentInitValue DashMpdDownloader::GetSegmentsWithSegTemplate(const DashSegTmpltInfo *segTmpltInfo, std::string id,
1440                                                                    std::shared_ptr<DashStreamDescription> streamDesc)
1441 {
1442     std::string media = segTmpltInfo->segTmpltMedia_;
1443     std::string::size_type posIden = media.find("$$");
1444     if (posIden != std::string::npos) {
1445         size_t strLength = strlen("$$");
1446         media.replace(posIden, strLength, "$");
1447     }
1448 
1449     if (DashSubstituteTmpltStr(media, "$RepresentationID", id) == -1) {
1450         MEDIA_LOG_E("media " PUBLIC_LOG_S " substitute $RepresentationID error "
1451             PUBLIC_LOG_S, media.c_str(), id.c_str());
1452         return DASH_SEGMENT_INIT_FAILED;
1453     }
1454 
1455     if (DashSubstituteTmpltStr(media, "$Bandwidth", std::to_string(streamDesc->bandwidth_)) == -1) {
1456         MEDIA_LOG_E("media " PUBLIC_LOG_S " substitute $Bandwidth error " PUBLIC_LOG_D32, media.c_str(),
1457             streamDesc->bandwidth_);
1458         return DASH_SEGMENT_INIT_FAILED;
1459     }
1460 
1461     streamDesc->startNumberSeq_ = ParseStartNumber(segTmpltInfo->multSegBaseInfo_.startNumber_);
1462     if (mpdInfo_->type_ == DashType::DASH_TYPE_STATIC) {
1463         return GetSegmentsWithTmpltStatic(segTmpltInfo, media, streamDesc);
1464     }
1465 
1466     return DASH_SEGMENT_INIT_FAILED;
1467 }
1468 
GetSegmentsWithTmpltStatic(const DashSegTmpltInfo * segTmpltInfo,const std::string & mediaUrl,std::shared_ptr<DashStreamDescription> streamDesc)1469 DashSegmentInitValue DashMpdDownloader::GetSegmentsWithTmpltStatic(const DashSegTmpltInfo *segTmpltInfo,
1470                                                                    const std::string &mediaUrl,
1471                                                                    std::shared_ptr<DashStreamDescription> streamDesc)
1472 {
1473     unsigned int timeScale = 1;
1474     if (segTmpltInfo->multSegBaseInfo_.segBaseInfo_.timeScale_ > 0) {
1475         timeScale = segTmpltInfo->multSegBaseInfo_.segBaseInfo_.timeScale_;
1476     }
1477 
1478     if (segTmpltInfo->multSegBaseInfo_.duration_ > 0) {
1479         return GetSegmentsWithTmpltDurationStatic(segTmpltInfo, mediaUrl, timeScale, streamDesc);
1480     } else if (segTmpltInfo->multSegBaseInfo_.segTimeline_.size() > 0) {
1481         return GetSegmentsWithTmpltTimelineStatic(segTmpltInfo, mediaUrl, timeScale, streamDesc);
1482     } else {
1483         MEDIA_LOG_E("static SegmentTemplate do not have segment duration");
1484         return DASH_SEGMENT_INIT_FAILED;
1485     }
1486 }
1487 
1488 /**
1489  * @brief    Get segments with SegmentTemplate in static as contain SegmentBase.duration
1490  *
1491  * @param    segTmpltInfo           SegmentTemplate infomation
1492  * @param    mediaUrl               SegmentTemplate mediaSegment Url
1493  * @param    timeScale              the timeScale of this period, duration / timescale = seconds
1494  * @param    desc             stream description
1495  *
1496  * @return   DashSegmentInitValue
1497  */
GetSegmentsWithTmpltDurationStatic(const DashSegTmpltInfo * segTmpltInfo,const std::string & mediaUrl,unsigned int timeScale,std::shared_ptr<DashStreamDescription> desc)1498 DashSegmentInitValue DashMpdDownloader::GetSegmentsWithTmpltDurationStatic(const DashSegTmpltInfo *segTmpltInfo,
1499                                                                            const std::string &mediaUrl,
1500                                                                            unsigned int timeScale,
1501                                                                            std::shared_ptr<DashStreamDescription> desc)
1502 {
1503     unsigned int timeScaleTmp = timeScale > 0 ? timeScale : 1;
1504     // the segment duration in millisecond
1505     unsigned int segmentDuration =
1506         (static_cast<uint64_t>(segTmpltInfo->multSegBaseInfo_.duration_) * S_2_MS) / timeScaleTmp;
1507     if (segmentDuration == 0) {
1508         return DASH_SEGMENT_INIT_FAILED;
1509     }
1510 
1511     uint64_t segmentBaseDurationSum = 0; // the sum of segment duration(ms), not devide timescale
1512     unsigned int accumulateDuration = 0; // add all segments dutation(ms) before current segment
1513     int64_t segmentSeq = -1;
1514 
1515     while (accumulateDuration < desc->duration_) {
1516         segmentBaseDurationSum += segTmpltInfo->multSegBaseInfo_.duration_;
1517         // the sum of segment duration(ms), devide timescale
1518         unsigned int durationSumWithScale = static_cast<unsigned int>(segmentBaseDurationSum * S_2_MS / timeScaleTmp);
1519         unsigned int segRealDur = (durationSumWithScale > accumulateDuration) ?
1520             (durationSumWithScale - accumulateDuration) : segmentDuration;
1521 
1522         if (desc->duration_ - accumulateDuration < segRealDur) {
1523             segRealDur = desc->duration_ - accumulateDuration;
1524         }
1525 
1526         accumulateDuration += segRealDur;
1527         segmentSeq = (segmentSeq == -1) ? desc->startNumberSeq_ : (segmentSeq + 1);
1528 
1529         // if the @duration attribute is present
1530         // then the time address is determined by replacing the $Time$ identifier with ((k-1) + (kStart-1))* @duration
1531         // with kStart the value of the @startNumber attribute, if present, or 1 otherwise.
1532         int64_t startTime = (segmentSeq - 1) * segTmpltInfo->multSegBaseInfo_.duration_;
1533         std::string tempUrl = mediaUrl;
1534 
1535         if (DashSubstituteTmpltStr(tempUrl, "$Time", std::to_string(startTime)) == -1) {
1536             MEDIA_LOG_I("GetSegmentsWithTmpltDuration substitute $Time " PUBLIC_LOG_S " error in static duration",
1537                 std::to_string(startTime).c_str());
1538             return DASH_SEGMENT_INIT_FAILED;
1539         }
1540 
1541         if (DashSubstituteTmpltStr(tempUrl, "$Number", std::to_string(segmentSeq)) == -1) {
1542             MEDIA_LOG_I("GetSegmentsWithTmpltDuration substitute $Number " PUBLIC_LOG_S " error in static duration",
1543                 std::to_string(segmentSeq).c_str());
1544             return DASH_SEGMENT_INIT_FAILED;
1545         }
1546 
1547         if (DASH_SEGMENT_INIT_FAILED == AddOneSegment(segRealDur, segmentSeq, tempUrl, desc)) {
1548             return DASH_SEGMENT_INIT_FAILED;
1549         }
1550     }
1551     return DASH_SEGMENT_INIT_SUCCESS;
1552 }
1553 
GetSegmentsWithTmpltTimelineStatic(const DashSegTmpltInfo * segTmpltInfo,const std::string & mediaUrl,unsigned int timeScale,std::shared_ptr<DashStreamDescription> desc)1554 DashSegmentInitValue DashMpdDownloader::GetSegmentsWithTmpltTimelineStatic(const DashSegTmpltInfo *segTmpltInfo,
1555                                                                            const std::string &mediaUrl,
1556                                                                            unsigned int timeScale,
1557                                                                            std::shared_ptr<DashStreamDescription> desc)
1558 {
1559     if (timeScale == 0) {
1560         return DASH_SEGMENT_INIT_FAILED;
1561     }
1562 
1563     int64_t segmentSeq = -1;
1564     uint64_t startTime = 0;
1565     std::list<DashSegTimeline*> timelineList = segTmpltInfo->multSegBaseInfo_.segTimeline_;
1566     for (std::list<DashSegTimeline*>::iterator it = timelineList.begin(); it != timelineList.end(); ++it) {
1567         if (*it != nullptr) {
1568             int segCount = GetSegCountFromTimeline(it, timelineList.end(), desc->duration_, timeScale, startTime);
1569             if (segCount < 0) {
1570                 MEDIA_LOG_W("get segment count error in SegmentTemplate.SegmentTimeline");
1571                 continue;
1572             }
1573 
1574             unsigned int segDuration = ((*it)->d_ * S_2_MS) / timeScale;
1575             MediaSegSampleInfo sampleInfo;
1576             sampleInfo.mediaUrl_ = mediaUrl;
1577             sampleInfo.segCount_ = segCount;
1578             sampleInfo.segDuration_ = segDuration;
1579             if (GetSegmentsInOneTimeline(*it, sampleInfo, segmentSeq, startTime, desc) ==
1580                 DASH_SEGMENT_INIT_FAILED) {
1581                 return DASH_SEGMENT_INIT_FAILED;
1582             }
1583         }
1584     }
1585 
1586     return DASH_SEGMENT_INIT_SUCCESS;
1587 }
1588 
1589 /**
1590  * @brief    Get segments in ome timeline
1591  *
1592  * @param    timeline               Segment Timeline infomation
1593  * @param    sampleInfo               segment count duration Url in timeline
1594  * @param    segmentSeq[out]        segment segquence in timeline
1595  * @param    startTime[out]         segment start time in timeline
1596  * @param    streamDesc[out]        stream description, segments store in it
1597  *
1598  * @return   0 indicates success, -1 indicates failed
1599  */
GetSegmentsInOneTimeline(const DashSegTimeline * timeline,const MediaSegSampleInfo & sampleInfo,int64_t & segmentSeq,uint64_t & startTime,std::shared_ptr<DashStreamDescription> streamDesc)1600 DashSegmentInitValue DashMpdDownloader::GetSegmentsInOneTimeline(const DashSegTimeline *timeline,
1601                                                                  const MediaSegSampleInfo &sampleInfo,
1602                                                                  int64_t &segmentSeq, uint64_t &startTime,
1603                                                                  std::shared_ptr<DashStreamDescription> streamDesc)
1604 {
1605     int repeat = 0;
1606 
1607     while (repeat <= sampleInfo.segCount_) {
1608         repeat++;
1609         if (segmentSeq == -1) {
1610             segmentSeq = streamDesc->startNumberSeq_;
1611         } else {
1612             segmentSeq++;
1613         }
1614 
1615         std::string tempUrl = sampleInfo.mediaUrl_;
1616         if (DashSubstituteTmpltStr(tempUrl, "$Time", std::to_string(startTime)) == -1) {
1617             MEDIA_LOG_E("GetSegmentsInOneTimeline substitute $Time " PUBLIC_LOG_S " error in static timeline",
1618                 std::to_string(startTime).c_str());
1619             return DASH_SEGMENT_INIT_FAILED;
1620         }
1621 
1622         if (DashSubstituteTmpltStr(tempUrl, "$Number", std::to_string(segmentSeq)) == -1) {
1623             MEDIA_LOG_E("GetSegmentsInOneTimeline substitute $Number " PUBLIC_LOG_S " error in static timeline",
1624                 std::to_string(segmentSeq).c_str());
1625             return DASH_SEGMENT_INIT_FAILED;
1626         }
1627 
1628         if (DASH_SEGMENT_INIT_FAILED == AddOneSegment(sampleInfo.segDuration_, segmentSeq, tempUrl, streamDesc)) {
1629             MEDIA_LOG_E("AddOneSegment with SegmentTimeline in static is failed");
1630             return DASH_SEGMENT_INIT_FAILED;
1631         }
1632 
1633         startTime += timeline->d_;
1634     }
1635 
1636     return DASH_SEGMENT_INIT_SUCCESS;
1637 }
1638 
1639 /**
1640  * @brief    Get Segment Repeat Count In SegmentTimeline.S
1641  *
1642  * @param    it                     the current S element infomation iterator of list
1643  * @param    end                    the end iterator of list
1644  * @param    periodDuration         the duration of this period
1645  * @param    timeScale              the timeScale of this period, duration / timescale = seconds
1646  * @param    startTime              segment start time in timeline
1647  *
1648  * @return   segment repeat count, 0 means only one segment, negative means no segment
1649  */
GetSegCountFromTimeline(DashList<DashSegTimeline * >::iterator & it,const DashList<DashSegTimeline * >::iterator & end,unsigned int periodDuration,unsigned int timeScale,uint64_t startTime)1650 int DashMpdDownloader::GetSegCountFromTimeline(DashList<DashSegTimeline *>::iterator &it,
1651                                                const DashList<DashSegTimeline *>::iterator &end,
1652                                                unsigned int periodDuration, unsigned int timeScale, uint64_t startTime)
1653 {
1654     int segCount = (*it)->r_;
1655 
1656     /* A negative value of the @r attribute of the S element indicates that
1657      * the duration indicated in @d attribute repeats until the start of
1658      * the next S element, the end of the Period or until the next MPD update.
1659      */
1660     if (segCount < 0 && (*it)->d_) {
1661         ++it;
1662         // the start of next S
1663         if (it != end && *it != nullptr) {
1664             uint64_t nextStartTime = (*it)->t_;
1665             it--;
1666 
1667             if (nextStartTime <= startTime) {
1668                 MEDIA_LOG_W("r is negative and next S@t " PUBLIC_LOG_U64 " is not larger than startTime "
1669                     PUBLIC_LOG_U64, nextStartTime, startTime);
1670                 return segCount;
1671             }
1672 
1673             segCount = (int)((nextStartTime - startTime) / (*it)->d_);
1674         } else {
1675             // the end of period
1676             it--;
1677             uint64_t scaleDuration = (uint64_t)periodDuration * timeScale / S_2_MS;
1678             if (scaleDuration <= startTime) {
1679                 MEDIA_LOG_W("r is negative, duration " PUBLIC_LOG_U32 " is not larger than startTime "
1680                     PUBLIC_LOG_U64 ", timeScale " PUBLIC_LOG_U32, periodDuration, startTime, timeScale);
1681                 return segCount;
1682             }
1683 
1684             segCount = (int)((scaleDuration - startTime) / (*it)->d_);
1685         }
1686 
1687         // 0 means only one segment
1688         segCount -= 1;
1689     }
1690 
1691     return segCount;
1692 }
1693 
1694 /**
1695  * @brief    get segments with SegmentList
1696  *
1697  * @param    segListInfo            SegmentList infomation
1698  * @param    baseUrl                BaseUrl that map to media attribute if media missed and range present
1699  * @param    streamDesc             stream description, store segments
1700  *
1701  * @return   failed success undo
1702  */
GetSegmentsWithSegList(const DashSegListInfo * segListInfo,const std::string & baseUrl,std::shared_ptr<DashStreamDescription> streamDesc)1703 DashSegmentInitValue DashMpdDownloader::GetSegmentsWithSegList(const DashSegListInfo *segListInfo,
1704                                                                const std::string &baseUrl,
1705                                                                std::shared_ptr<DashStreamDescription> streamDesc)
1706 {
1707     int64_t segmentSeq = -1;
1708     int segmentCount = 0;
1709     std::list<unsigned int> durationList;
1710 
1711     unsigned int timescale = 1;
1712     if (segListInfo->multSegBaseInfo_.segBaseInfo_.timeScale_ != 0) {
1713         timescale = segListInfo->multSegBaseInfo_.segBaseInfo_.timeScale_;
1714     }
1715 
1716     unsigned int segDuration = (static_cast<uint64_t>(segListInfo->multSegBaseInfo_.duration_) * S_2_MS) / timescale;
1717     GetSegDurationFromTimeline(streamDesc->duration_, timescale, &segListInfo->multSegBaseInfo_, durationList);
1718 
1719     std::list<DashSegUrl*> segUrlList = segListInfo->segmentUrl_;
1720     for (std::list<DashSegUrl*>::iterator it = segUrlList.begin(); it != segUrlList.end(); ++it) {
1721         if (*it == nullptr) {
1722             continue;
1723         }
1724 
1725         std::string mediaUrl;
1726         if ((*it)->media_.length() > 0) {
1727             mediaUrl = (*it)->media_;
1728         } else if (baseUrl.length() > 0) {
1729             mediaUrl = ""; // append baseurl as the media url in MakeAbsoluteWithBaseUrl
1730         } else {
1731             continue;
1732         }
1733         segmentSeq = streamDesc->startNumberSeq_ + segmentCount;
1734         DashSegment srcSegment;
1735         srcSegment.streamId_ = streamDesc->streamId_;
1736         srcSegment.bandwidth_ = streamDesc->bandwidth_;
1737         if (durationList.size() > 0) {
1738             // by SegmentTimeline
1739             srcSegment.duration_ = durationList.front();
1740             // if size of SegmentTimeline smaller than size of SegmentURL,
1741             // keep the last segment duration in SegmentTimeline
1742             if (durationList.size() > 1) {
1743                 durationList.pop_front();
1744             }
1745         } else {
1746             // by duration
1747             srcSegment.duration_ = segDuration;
1748         }
1749 
1750         srcSegment.startNumberSeq_ = streamDesc->startNumberSeq_;
1751         srcSegment.numberSeq_ = segmentSeq;
1752         srcSegment.url_ = mediaUrl;
1753         srcSegment.byteRange_ = (*it)->mediaRange_;
1754         if (DASH_SEGMENT_INIT_FAILED == AddOneSegment(srcSegment, streamDesc)) {
1755             return DASH_SEGMENT_INIT_FAILED;
1756         }
1757         segmentCount++;
1758     }
1759 
1760     return DASH_SEGMENT_INIT_SUCCESS;
1761 }
1762 
1763 /**
1764  * @brief    Get Segment Duration From SegmentTimeline
1765  *
1766  * @param    periodDuration         the duration of this period
1767  * @param    timeScale              the timeScale of this period, duration / timescale = seconds
1768  * @param    multSegBaseInfo        multipleSegmentBaseInfomation in segmentlist
1769  * @param    durationList[out]      the list to store segment duration
1770  *
1771  * @return   none
1772  */
GetSegDurationFromTimeline(unsigned int periodDuration,unsigned int timeScale,const DashMultSegBaseInfo * multSegBaseInfo,DashList<unsigned int> & durationList)1773 void DashMpdDownloader::GetSegDurationFromTimeline(unsigned int periodDuration, unsigned int timeScale,
1774                                                    const DashMultSegBaseInfo *multSegBaseInfo,
1775                                                    DashList<unsigned int> &durationList)
1776 {
1777     if (timeScale == 0 || mpdInfo_ == nullptr) {
1778         return;
1779     }
1780 
1781     // support SegmentList.SegmentTimeline in static type
1782     if (multSegBaseInfo->duration_ == 0 && multSegBaseInfo->segTimeline_.size() > 0 &&
1783         mpdInfo_->type_ == DashType::DASH_TYPE_STATIC) {
1784         uint64_t startTime = 0;
1785         std::list<DashSegTimeline*> timelineList = multSegBaseInfo->segTimeline_;
1786         for (std::list<DashSegTimeline*>::iterator it = timelineList.begin(); it != timelineList.end(); ++it) {
1787             if (*it == nullptr) {
1788                 continue;
1789             }
1790             int segCount = GetSegCountFromTimeline(it, timelineList.end(), periodDuration, timeScale, startTime);
1791             if (segCount < 0) {
1792                 MEDIA_LOG_W("get segment count error in SegmentList.SegmentTimeline");
1793                 continue;
1794             }
1795             // calculate segment duration by SegmentTimeline
1796             unsigned int segDuration = ((*it)->d_ * 1000) / timeScale;
1797             for (int repeat = 0; repeat <= segCount; repeat++) {
1798                 durationList.push_back(segDuration);
1799                 startTime += (*it)->d_;
1800             }
1801         }
1802     }
1803 }
1804 
1805 /**
1806  * @brief    init segments with BaseUrl
1807  *
1808  * @param    baseUrlList            BaseUrl List
1809  * @param    streamDesc             stream description, store segments
1810  * @return   failed success undo
1811  */
GetSegmentsWithBaseUrl(std::list<std::string> baseUrlList,std::shared_ptr<DashStreamDescription> streamDesc)1812 DashSegmentInitValue DashMpdDownloader::GetSegmentsWithBaseUrl(std::list<std::string> baseUrlList,
1813                                                                std::shared_ptr<DashStreamDescription> streamDesc)
1814 {
1815     DashSegment srcSegment;
1816     srcSegment.streamId_ = streamDesc->streamId_;
1817     srcSegment.bandwidth_ = streamDesc->bandwidth_;
1818     srcSegment.duration_ = streamDesc->duration_;
1819     srcSegment.startNumberSeq_ = streamDesc->startNumberSeq_;
1820     srcSegment.numberSeq_ = streamDesc->startNumberSeq_;
1821     if (baseUrlList.size() > 0) {
1822         srcSegment.url_ = baseUrlList.front();
1823     }
1824 
1825     if (DASH_SEGMENT_INIT_FAILED == AddOneSegment(srcSegment, streamDesc)) {
1826         MEDIA_LOG_E("GetSegmentsWithBaseUrl AddOneSegment is failed");
1827         return DASH_SEGMENT_INIT_FAILED;
1828     }
1829 
1830     return DASH_SEGMENT_INIT_SUCCESS;
1831 }
1832 
GetRepresemtationFromAdptSet(DashAdptSetInfo * adptSetInfo,unsigned int repIndex)1833 DashRepresentationInfo *DashMpdDownloader::GetRepresemtationFromAdptSet(DashAdptSetInfo *adptSetInfo,
1834                                                                         unsigned int repIndex)
1835 {
1836     unsigned int index = 0;
1837     for (std::list<DashRepresentationInfo *>::iterator it = adptSetInfo->representationList_.begin();
1838          it != adptSetInfo->representationList_.end(); ++it, ++index) {
1839         if (repIndex == index) {
1840             return *it;
1841         }
1842     }
1843 
1844     return nullptr;
1845 }
1846 
1847 /**
1848  * @brief    get segments in AdaptationSet with SegmentTemplate or SegmentList or BaseUrl
1849  *
1850  * @param    adptSetInfo            chosen AdaptationSet
1851  * @param    repInfo                use its id as get segments with SegmentTemplate
1852  * @param    baseUrl                Mpd.BaseUrl + Period.BaseUrl
1853  * @param    streamDesc             stream description, store segments
1854  *
1855  * @return   failed success undo
1856  */
GetSegmentsByAdptSetInfo(const DashAdptSetInfo * adptSetInfo,const DashRepresentationInfo * repInfo,std::string & baseUrl,std::shared_ptr<DashStreamDescription> streamDesc)1857 DashSegmentInitValue DashMpdDownloader::GetSegmentsByAdptSetInfo(const DashAdptSetInfo* adptSetInfo,
1858     const DashRepresentationInfo* repInfo, std::string& baseUrl, std::shared_ptr<DashStreamDescription> streamDesc)
1859 {
1860     DashSegmentInitValue initValue = DASH_SEGMENT_INIT_UNDO;
1861 
1862     // get segments from AdaptationSet.SegmentTemplate
1863     if (adptSetInfo->adptSetSegTmplt_ != nullptr && adptSetInfo->adptSetSegTmplt_->segTmpltMedia_.length() > 0) {
1864         DashAppendBaseUrl(baseUrl, adptSetInfo->baseUrl_);
1865 
1866         std::string representationId;
1867         if (repInfo != nullptr) {
1868             representationId = repInfo->id_;
1869         }
1870 
1871         initValue = GetSegmentsWithSegTemplate(adptSetInfo->adptSetSegTmplt_, representationId, streamDesc);
1872     } else if (adptSetInfo->adptSetSegList_ != nullptr && adptSetInfo->adptSetSegList_->segmentUrl_.size() > 0) {
1873         // get segments from AdaptationSet.SegmentList
1874         DashAppendBaseUrl(baseUrl, adptSetInfo->baseUrl_);
1875         initValue = GetSegmentsWithSegList(adptSetInfo->adptSetSegList_, baseUrl, streamDesc);
1876     } else if (adptSetInfo->baseUrl_.size() > 0) {
1877         initValue = GetSegmentsWithBaseUrl(adptSetInfo->baseUrl_, streamDesc);
1878     }
1879 
1880     return initValue;
1881 }
1882 
GetInitSegFromPeriod(const std::string & periodBaseUrl,const std::string & repId,std::shared_ptr<DashStreamDescription> streamDesc)1883 bool DashMpdDownloader::GetInitSegFromPeriod(const std::string &periodBaseUrl, const std::string &repId,
1884                                              std::shared_ptr<DashStreamDescription> streamDesc)
1885 {
1886     int segTmpltFlag = 0;
1887     // should SetPeriodInfo before GetInitSegment
1888     DashUrlType *initSegment = periodManager_->GetInitSegment(segTmpltFlag);
1889     if (initSegment != nullptr) {
1890         streamDesc->initSegment_ = std::make_shared<DashInitSegment>();
1891         UpdateInitSegUrl(streamDesc, initSegment, segTmpltFlag, repId);
1892         MakeAbsoluteWithBaseUrl(streamDesc->initSegment_, periodBaseUrl);
1893         MEDIA_LOG_D("GetInitSegFromPeriod:streamId:" PUBLIC_LOG_D32, streamDesc->streamId_);
1894         return true;
1895     }
1896 
1897     return false;
1898 }
1899 
GetInitSegFromAdptSet(const std::string & adptSetBaseUrl,const std::string & repId,std::shared_ptr<DashStreamDescription> streamDesc)1900 bool DashMpdDownloader::GetInitSegFromAdptSet(const std::string &adptSetBaseUrl, const std::string &repId,
1901                                               std::shared_ptr<DashStreamDescription> streamDesc)
1902 {
1903     int segTmpltFlag = 0;
1904     // should SetAdptSetInfo before GetInitSegment
1905     DashUrlType *initSegment = adptSetManager_->GetInitSegment(segTmpltFlag);
1906     if (initSegment != nullptr) {
1907         streamDesc->initSegment_ = std::make_shared<DashInitSegment>();
1908         UpdateInitSegUrl(streamDesc, initSegment, segTmpltFlag, repId);
1909         MakeAbsoluteWithBaseUrl(streamDesc->initSegment_, adptSetBaseUrl);
1910         MEDIA_LOG_D("GetInitSegFromAdptSet:streamId:" PUBLIC_LOG_D32, streamDesc->streamId_);
1911         return true;
1912     }
1913 
1914     return false;
1915 }
1916 
GetInitSegFromRepresentation(const std::string & repBaseUrl,const std::string & repId,std::shared_ptr<DashStreamDescription> streamDesc)1917 bool DashMpdDownloader::GetInitSegFromRepresentation(const std::string &repBaseUrl, const std::string &repId,
1918                                                      std::shared_ptr<DashStreamDescription> streamDesc)
1919 {
1920     int segTmpltFlag = 0;
1921     DashUrlType *initSegment = representationManager_->GetInitSegment(segTmpltFlag);
1922     // should SetRepresentationInfo before GetInitSegment
1923     if (initSegment != nullptr) {
1924         streamDesc->initSegment_ = std::make_shared<DashInitSegment>();
1925         UpdateInitSegUrl(streamDesc, initSegment, segTmpltFlag, repId);
1926         MakeAbsoluteWithBaseUrl(streamDesc->initSegment_, repBaseUrl);
1927         MEDIA_LOG_D("GetInitSegFromRepresentation:streamId:" PUBLIC_LOG_D32, streamDesc->streamId_);
1928         return true;
1929     }
1930 
1931     return false;
1932 }
1933 
GetSegmentsInNewStream(std::shared_ptr<DashStreamDescription> destStream)1934 DashMpdGetRet DashMpdDownloader::GetSegmentsInNewStream(std::shared_ptr<DashStreamDescription> destStream)
1935 {
1936     MEDIA_LOG_I("GetSegmentsInNewStream update id:" PUBLIC_LOG_D32 ", seq:"
1937         PUBLIC_LOG_D64, destStream->streamId_, destStream->currentNumberSeq_);
1938     DashMpdGetRet ret = DASH_MPD_GET_ERROR;
1939     if (destStream->segsState_ == DASH_SEGS_STATE_FINISH) {
1940         // segment list is ok
1941         MEDIA_LOG_I("GetNextVideoStream id:" PUBLIC_LOG_D32 ", segment list is ok", destStream->streamId_);
1942         ret = DASH_MPD_GET_DONE;
1943     } else {
1944         // get segment list
1945         if (ondemandSegBase_) {
1946             // request sidx segment
1947             if (destStream->indexSegment_ != nullptr) {
1948                 ret = DASH_MPD_GET_UNDONE;
1949                 OpenStream(destStream);
1950             } else {
1951                 MEDIA_LOG_E("GetNextSegmentByBitrate id:"
1952                     PUBLIC_LOG_D32 " ondemandSegBase_ but indexSegment is null", destStream->streamId_);
1953             }
1954         } else {
1955             // get segment list
1956             if (GetSegmentsInMpd(destStream) == DASH_SEGMENT_INIT_FAILED) {
1957                 MEDIA_LOG_E("GetNextSegmentByBitrate id:"
1958                     PUBLIC_LOG_D32 " GetSegmentsInMpd failed", destStream->streamId_);
1959             }
1960             // get segment by position
1961             ret = DASH_MPD_GET_DONE;
1962         }
1963     }
1964     return ret;
1965 }
1966 
UpdateInitSegUrl(std::shared_ptr<DashStreamDescription> streamDesc,const DashUrlType * urlType,int segTmpltFlag,std::string representationID)1967 void DashMpdDownloader::UpdateInitSegUrl(std::shared_ptr<DashStreamDescription> streamDesc, const DashUrlType *urlType,
1968                                          int segTmpltFlag, std::string representationID)
1969 {
1970     if (streamDesc != nullptr && streamDesc->initSegment_ != nullptr) {
1971         streamDesc->initSegment_->url_ = urlType->sourceUrl_;
1972         if (urlType->range_.length() > 0) {
1973             DashParseRange(urlType->range_, streamDesc->initSegment_->rangeBegin_, streamDesc->initSegment_->rangeEnd_);
1974         }
1975 
1976         if (segTmpltFlag) {
1977             std::string::size_type posIden = streamDesc->initSegment_->url_.find("$$");
1978             if (posIden != std::string::npos) {
1979                 size_t strLength = strlen("$$");
1980                 streamDesc->initSegment_->url_.replace(posIden, strLength, "$");
1981             }
1982 
1983             if (DashSubstituteTmpltStr(streamDesc->initSegment_->url_, "$RepresentationID", representationID) == -1) {
1984                 MEDIA_LOG_E("UpdateInitSegUrl subtitute $RepresentationID error "
1985                     PUBLIC_LOG_S, representationID.c_str());
1986             }
1987 
1988             if (DashSubstituteTmpltStr(streamDesc->initSegment_->url_, "$Bandwidth",
1989                                        std::to_string(streamDesc->bandwidth_)) == -1) {
1990                 MEDIA_LOG_E("UpdateInitSegUrl subtitute $Bandwidth error "
1991                     PUBLIC_LOG_U32, streamDesc->bandwidth_);
1992             }
1993         }
1994     }
1995 }
1996 
GetVideoType(DashVideoType videoType)1997 static VideoType GetVideoType(DashVideoType videoType)
1998 {
1999     if (videoType == DASH_VIDEO_TYPE_HDR_VIVID) {
2000         return VIDEO_TYPE_HDR_VIVID;
2001     } else if (videoType == DASH_VIDEO_TYPE_HDR_10) {
2002         return VIDEO_TYPE_HDR_10;
2003     } else {
2004         return VIDEO_TYPE_SDR;
2005     }
2006 }
2007 
GetStreamInfo(std::vector<StreamInfo> & streams)2008 Status DashMpdDownloader::GetStreamInfo(std::vector<StreamInfo> &streams)
2009 {
2010     MEDIA_LOG_I("GetStreamInfo");
2011     // only support one audio/subtitle Representation in one AdaptationSet
2012     unsigned int audioAdptSetIndex = streamDescriptions_.size();
2013     unsigned int subtitleAdptSetIndex = audioAdptSetIndex;
2014     for (unsigned int index = 0; index < streamDescriptions_.size(); index++) {
2015         if (streamDescriptions_[index]->type_ == MediaAVCodec::MediaType::MEDIA_TYPE_AUD) {
2016             if (streamDescriptions_[index]->adptSetIndex_ == audioAdptSetIndex) {
2017                 MEDIA_LOG_D("GetStreamInfo skip audio stream:" PUBLIC_LOG_D32 ",lang:" PUBLIC_LOG_S,
2018                     streamDescriptions_[index]->streamId_, streamDescriptions_[index]->lang_.c_str());
2019                 continue;
2020             }
2021 
2022             audioAdptSetIndex = streamDescriptions_[index]->adptSetIndex_;
2023         } else if (streamDescriptions_[index]->type_ == MediaAVCodec::MediaType::MEDIA_TYPE_SUBTITLE) {
2024             if (streamDescriptions_[index]->adptSetIndex_ == subtitleAdptSetIndex) {
2025                 MEDIA_LOG_D("GetStreamInfo skip subtitle stream:" PUBLIC_LOG_D32 ",lang:" PUBLIC_LOG_S,
2026                     streamDescriptions_[index]->streamId_, streamDescriptions_[index]->lang_.c_str());
2027                 continue;
2028             }
2029             subtitleAdptSetIndex = streamDescriptions_[index]->adptSetIndex_;
2030         }
2031 
2032         StreamInfo info;
2033         info.streamId = streamDescriptions_[index]->streamId_;
2034         info.bitRate = streamDescriptions_[index]->bandwidth_;
2035         info.videoWidth = static_cast<int32_t>(streamDescriptions_[index]->width_);
2036         info.videoHeight = static_cast<int32_t>(streamDescriptions_[index]->height_);
2037         info.lang = streamDescriptions_[index]->lang_;
2038         info.videoType = GetVideoType(streamDescriptions_[index]->videoType_);
2039         if (streamDescriptions_[index]->type_ == MediaAVCodec::MediaType::MEDIA_TYPE_SUBTITLE) {
2040             info.type = SUBTITLE;
2041         } else if (streamDescriptions_[index]->type_ == MediaAVCodec::MediaType::MEDIA_TYPE_AUD) {
2042             info.type = AUDIO;
2043         } else {
2044             info.type = VIDEO;
2045         }
2046 
2047         MEDIA_LOG_D("GetStreamInfo streamId:" PUBLIC_LOG_D32 ", type:" PUBLIC_LOG_D32 ", bitRate:"
2048             PUBLIC_LOG_U32, info.streamId, info.type, info.bitRate);
2049         if (streamDescriptions_[index]->inUse_ && streams.size() > 0) {
2050             // play stream insert begin
2051             streams.insert(streams.begin(), info);
2052         } else {
2053             streams.push_back(info);
2054         }
2055     }
2056     return Status::OK;
2057 }
2058 
PutStreamToDownload()2059 bool DashMpdDownloader::PutStreamToDownload()
2060 {
2061     auto iter = std::find_if(streamDescriptions_.begin(), streamDescriptions_.end(),
2062         [&](const std::shared_ptr<DashStreamDescription> &stream) {
2063             return stream->inUse_ &&
2064                 stream->indexSegment_ != nullptr &&
2065                 stream->segsState_ != DASH_SEGS_STATE_FINISH;
2066         });
2067     if (iter == streamDescriptions_.end()) {
2068         return false;
2069     }
2070 
2071     OpenStream(*iter);
2072     return true;
2073 }
2074 
2075 }
2076 }
2077 }
2078 }