7 #include "packager/mpd/base/mpd_builder.h"
9 #include <libxml/tree.h>
10 #include <libxml/xmlstring.h>
18 #include "packager/base/base64.h"
19 #include "packager/base/bind.h"
20 #include "packager/base/files/file_path.h"
21 #include "packager/base/logging.h"
22 #include "packager/base/strings/string_number_conversions.h"
23 #include "packager/base/strings/stringprintf.h"
24 #include "packager/base/synchronization/lock.h"
25 #include "packager/base/time/default_clock.h"
26 #include "packager/base/time/time.h"
27 #include "packager/file/file.h"
28 #include "packager/media/base/language_utils.h"
29 #include "packager/mpd/base/content_protection_element.h"
30 #include "packager/mpd/base/mpd_utils.h"
31 #include "packager/mpd/base/xml/xml_node.h"
32 #include "packager/version/version.h"
38 using xml::RepresentationXmlNode;
39 using xml::AdaptationSetXmlNode;
43 AdaptationSet::Role MediaInfoTextTypeToRole(
44 MediaInfo::TextInfo::TextType type) {
46 case MediaInfo::TextInfo::UNKNOWN:
47 LOG(WARNING) <<
"Unknown text type, assuming subtitle.";
48 return AdaptationSet::kRoleSubtitle;
49 case MediaInfo::TextInfo::CAPTION:
50 return AdaptationSet::kRoleCaption;
51 case MediaInfo::TextInfo::SUBTITLE:
52 return AdaptationSet::kRoleSubtitle;
54 NOTREACHED() <<
"Unknown MediaInfo TextType: " << type
55 <<
" assuming subtitle.";
56 return AdaptationSet::kRoleSubtitle;
60 std::string GetMimeType(
const std::string& prefix,
61 MediaInfo::ContainerType container_type) {
62 switch (container_type) {
63 case MediaInfo::CONTAINER_MP4:
64 return prefix +
"/mp4";
65 case MediaInfo::CONTAINER_MPEG2_TS:
67 return prefix +
"/MP2T";
68 case MediaInfo::CONTAINER_WEBM:
69 return prefix +
"/webm";
75 LOG(ERROR) <<
"Unrecognized container type: " << container_type;
79 void AddMpdNameSpaceInfo(XmlNode* mpd) {
82 static const char kXmlNamespace[] =
"urn:mpeg:dash:schema:mpd:2011";
83 static const char kXmlNamespaceXsi[] =
84 "http://www.w3.org/2001/XMLSchema-instance";
85 static const char kXmlNamespaceXlink[] =
"http://www.w3.org/1999/xlink";
86 static const char kDashSchemaMpd2011[] =
87 "urn:mpeg:dash:schema:mpd:2011 DASH-MPD.xsd";
88 static const char kCencNamespace[] =
"urn:mpeg:cenc:2013";
90 mpd->SetStringAttribute(
"xmlns", kXmlNamespace);
91 mpd->SetStringAttribute(
"xmlns:xsi", kXmlNamespaceXsi);
92 mpd->SetStringAttribute(
"xmlns:xlink", kXmlNamespaceXlink);
93 mpd->SetStringAttribute(
"xsi:schemaLocation", kDashSchemaMpd2011);
94 mpd->SetStringAttribute(
"xmlns:cenc", kCencNamespace);
97 bool IsPeriodNode(xmlNodePtr node) {
100 return xmlStrcmp(node->name, reinterpret_cast<const xmlChar*>(
"Period")) ==
109 xmlNodePtr FindPeriodNode(XmlNode* xml_node) {
110 for (xmlNodePtr node = xml_node->GetRawPtr()->xmlChildrenNode; node != NULL;
112 if (IsPeriodNode(node))
119 bool Positive(
double d) {
125 std::string XmlDateTimeNowWithOffset(
126 int32_t offset_seconds,
127 base::Clock* clock) {
128 base::Time time = clock->Now();
129 time += base::TimeDelta::FromSeconds(offset_seconds);
130 base::Time::Exploded time_exploded;
131 time.UTCExplode(&time_exploded);
133 return base::StringPrintf(
"%4d-%02d-%02dT%02d:%02d:%02dZ", time_exploded.year,
134 time_exploded.month, time_exploded.day_of_month,
135 time_exploded.hour, time_exploded.minute,
136 time_exploded.second);
139 void SetIfPositive(
const char* attr_name,
double value, XmlNode* mpd) {
140 if (Positive(value)) {
141 mpd->SetStringAttribute(attr_name, SecondsToXmlDuration(value));
145 uint32_t GetTimeScale(
const MediaInfo& media_info) {
146 if (media_info.has_reference_time_scale()) {
147 return media_info.reference_time_scale();
150 if (media_info.has_video_info()) {
151 return media_info.video_info().time_scale();
154 if (media_info.has_audio_info()) {
155 return media_info.audio_info().time_scale();
158 LOG(WARNING) <<
"No timescale specified, using 1 as timescale.";
162 uint64_t LastSegmentStartTime(
const SegmentInfo& segment_info) {
163 return segment_info.start_time + segment_info.duration * segment_info.repeat;
167 uint64_t LastSegmentEndTime(
const SegmentInfo& segment_info) {
168 return segment_info.start_time +
169 segment_info.duration * (segment_info.repeat + 1);
172 uint64_t LatestSegmentStartTime(
const std::list<SegmentInfo>& segments) {
173 DCHECK(!segments.empty());
174 const SegmentInfo& latest_segment = segments.back();
175 return LastSegmentStartTime(latest_segment);
180 int SearchTimedOutRepeatIndex(uint64_t timeshift_limit,
181 const SegmentInfo& segment_info) {
182 DCHECK_LE(timeshift_limit, LastSegmentEndTime(segment_info));
183 if (timeshift_limit < segment_info.start_time)
186 return (timeshift_limit - segment_info.start_time) / segment_info.duration;
189 std::string MakePathRelative(
const std::string& path,
190 const std::string& mpd_dir) {
191 return (path.find(mpd_dir) == 0) ? path.substr(mpd_dir.size()) : path;
197 bool HasRequiredVideoFields(
const MediaInfo_VideoInfo& video_info) {
198 if (!video_info.has_height() || !video_info.has_width()) {
200 <<
"Width and height are required fields for generating a valid MPD.";
205 LOG_IF(WARNING, !video_info.has_time_scale())
206 <<
"Video info does not contain timescale required for "
207 "calculating framerate. @frameRate is required for DASH IOP.";
208 LOG_IF(WARNING, !video_info.has_pixel_width())
209 <<
"Video info does not contain pixel_width to calculate the sample "
210 "aspect ratio required for DASH IOP.";
211 LOG_IF(WARNING, !video_info.has_pixel_height())
212 <<
"Video info does not contain pixel_height to calculate the sample "
213 "aspect ratio required for DASH IOP.";
224 std::string GetPictureAspectRatio(uint32_t width,
226 uint32_t pixel_width,
227 uint32_t pixel_height) {
228 const uint32_t scaled_width = pixel_width * width;
229 const uint32_t scaled_height = pixel_height * height;
230 const double par =
static_cast<double>(scaled_width) / scaled_height;
234 const uint32_t kLargestPossibleParY = 19;
236 uint32_t par_num = 0;
237 uint32_t par_den = 0;
238 double min_error = 1.0;
239 for (uint32_t den = 1; den <= kLargestPossibleParY; ++den) {
240 uint32_t num = par * den + 0.5;
241 double error = fabs(par - static_cast<double>(num) / den);
242 if (error < min_error) {
246 if (error == 0)
break;
249 VLOG(2) <<
"width*pix_width : height*pixel_height (" << scaled_width <<
":"
250 << scaled_height <<
") reduced to " << par_num <<
":" << par_den
251 <<
" with error " << min_error <<
".";
253 return base::IntToString(par_num) +
":" + base::IntToString(par_den);
258 void AddPictureAspectRatio(
259 const MediaInfo::VideoInfo& video_info,
260 std::set<std::string>* picture_aspect_ratio) {
263 if (picture_aspect_ratio->size() > 1)
266 if (video_info.width() == 0 || video_info.height() == 0 ||
267 video_info.pixel_width() == 0 || video_info.pixel_height() == 0) {
272 picture_aspect_ratio->insert(
"bogus");
273 picture_aspect_ratio->insert(
"entries");
277 const std::string par = GetPictureAspectRatio(
278 video_info.width(), video_info.height(),
279 video_info.pixel_width(), video_info.pixel_height());
280 DVLOG(1) <<
"Setting par as: " << par
281 <<
" for video with width: " << video_info.width()
282 <<
" height: " << video_info.height()
283 <<
" pixel_width: " << video_info.pixel_width() <<
" pixel_height; "
284 << video_info.pixel_height();
285 picture_aspect_ratio->insert(par);
288 std::string RoleToText(AdaptationSet::Role role) {
292 case AdaptationSet::kRoleCaption:
294 case AdaptationSet::kRoleSubtitle:
296 case AdaptationSet::kRoleMain:
298 case AdaptationSet::kRoleAlternate:
300 case AdaptationSet::kRoleSupplementary:
301 return "supplementary";
302 case AdaptationSet::kRoleCommentary:
304 case AdaptationSet::kRoleDub:
315 class LibXmlInitializer {
317 LibXmlInitializer() : initialized_(false) {
318 base::AutoLock lock(lock_);
325 ~LibXmlInitializer() {
326 base::AutoLock lock(lock_);
329 initialized_ =
false;
337 DISALLOW_COPY_AND_ASSIGN(LibXmlInitializer);
340 class RepresentationStateChangeListenerImpl
341 :
public RepresentationStateChangeListener {
344 RepresentationStateChangeListenerImpl(uint32_t representation_id,
345 AdaptationSet* adaptation_set)
346 : representation_id_(representation_id), adaptation_set_(adaptation_set) {
347 DCHECK(adaptation_set_);
349 ~RepresentationStateChangeListenerImpl()
override {}
352 void OnNewSegmentForRepresentation(uint64_t start_time,
353 uint64_t duration)
override {
354 adaptation_set_->OnNewSegmentForRepresentation(representation_id_,
355 start_time, duration);
358 void OnSetFrameRateForRepresentation(uint32_t frame_duration,
359 uint32_t timescale)
override {
360 adaptation_set_->OnSetFrameRateForRepresentation(representation_id_,
361 frame_duration, timescale);
365 const uint32_t representation_id_;
366 AdaptationSet*
const adaptation_set_;
368 DISALLOW_COPY_AND_ASSIGN(RepresentationStateChangeListenerImpl);
374 : mpd_options_(mpd_options), clock_(new base::DefaultClock()) {}
376 MpdBuilder::~MpdBuilder() {}
379 base_urls_.push_back(base_url);
383 std::unique_ptr<AdaptationSet> adaptation_set(
384 new AdaptationSet(adaptation_set_counter_.GetNext(), lang, mpd_options_,
385 &representation_counter_));
386 DCHECK(adaptation_set);
388 if (!lang.empty() && lang == mpd_options_.mpd_params.default_language) {
389 adaptation_set->AddRole(AdaptationSet::kRoleMain);
392 adaptation_sets_.push_back(std::move(adaptation_set));
393 return adaptation_sets_.back().get();
398 static LibXmlInitializer lib_xml_initializer;
400 xml::scoped_xml_ptr<xmlDoc> doc(GenerateMpd());
404 static const int kNiceFormat = 1;
405 int doc_str_size = 0;
406 xmlChar* doc_str =
nullptr;
407 xmlDocDumpFormatMemoryEnc(doc.get(), &doc_str, &doc_str_size,
"UTF-8",
409 output->assign(doc_str, doc_str + doc_str_size);
417 xmlDocPtr MpdBuilder::GenerateMpd() {
419 static const char kXmlVersion[] =
"1.0";
420 xml::scoped_xml_ptr<xmlDoc> doc(xmlNewDoc(BAD_CAST kXmlVersion));
424 XmlNode period(
"Period");
430 for (
const std::unique_ptr<AdaptationSet>& adaptation_set :
432 xml::scoped_xml_ptr<xmlNode> child(adaptation_set->GetXml());
433 if (!child.get() || !period.AddChild(std::move(child)))
438 std::list<std::string>::const_iterator base_urls_it = base_urls_.begin();
439 for (; base_urls_it != base_urls_.end(); ++base_urls_it) {
440 XmlNode base_url(
"BaseURL");
441 base_url.SetContent(*base_urls_it);
443 if (!mpd.AddChild(base_url.PassScopedPtr()))
448 if (mpd_options_.mpd_type == MpdType::kDynamic) {
450 period.SetStringAttribute(
"start",
"PT0S");
453 if (!mpd.AddChild(period.PassScopedPtr()))
456 AddMpdNameSpaceInfo(&mpd);
458 static const char kOnDemandProfile[] =
459 "urn:mpeg:dash:profile:isoff-on-demand:2011";
460 static const char kLiveProfile[] =
461 "urn:mpeg:dash:profile:isoff-live:2011";
462 switch (mpd_options_.dash_profile) {
463 case DashProfile::kOnDemand:
464 mpd.SetStringAttribute(
"profiles", kOnDemandProfile);
466 case DashProfile::kLive:
467 mpd.SetStringAttribute(
"profiles", kLiveProfile);
470 NOTREACHED() <<
"Unknown DASH profile: "
471 <<
static_cast<int>(mpd_options_.dash_profile);
475 AddCommonMpdInfo(&mpd);
476 switch (mpd_options_.mpd_type) {
477 case MpdType::kStatic:
478 AddStaticMpdInfo(&mpd);
480 case MpdType::kDynamic:
481 AddDynamicMpdInfo(&mpd);
484 NOTREACHED() <<
"Unknown MPD type: "
485 <<
static_cast<int>(mpd_options_.mpd_type);
490 const std::string version = GetPackagerVersion();
491 if (!version.empty()) {
492 std::string version_string =
493 base::StringPrintf(
"Generated with %s version %s",
494 GetPackagerProjectUrl().c_str(), version.c_str());
495 xml::scoped_xml_ptr<xmlNode> comment(
496 xmlNewDocComment(doc.get(), BAD_CAST version_string.c_str()));
497 xmlDocSetRootElement(doc.get(), comment.get());
498 xmlAddSibling(comment.release(), mpd.Release());
500 xmlDocSetRootElement(doc.get(), mpd.Release());
502 return doc.release();
505 void MpdBuilder::AddCommonMpdInfo(XmlNode* mpd_node) {
507 mpd_node->SetStringAttribute(
511 LOG(ERROR) <<
"minBufferTime value not specified.";
516 void MpdBuilder::AddStaticMpdInfo(XmlNode* mpd_node) {
518 DCHECK_EQ(MpdType::kStatic, mpd_options_.mpd_type);
520 static const char kStaticMpdType[] =
"static";
521 mpd_node->SetStringAttribute(
"type", kStaticMpdType);
522 mpd_node->SetStringAttribute(
523 "mediaPresentationDuration",
524 SecondsToXmlDuration(GetStaticMpdDuration(mpd_node)));
527 void MpdBuilder::AddDynamicMpdInfo(XmlNode* mpd_node) {
529 DCHECK_EQ(MpdType::kDynamic, mpd_options_.mpd_type);
531 static const char kDynamicMpdType[] =
"dynamic";
532 mpd_node->SetStringAttribute(
"type", kDynamicMpdType);
535 mpd_node->SetStringAttribute(
"publishTime",
536 XmlDateTimeNowWithOffset(0, clock_.get()));
540 if (availability_start_time_.empty()) {
541 double earliest_presentation_time;
542 if (GetEarliestTimestamp(&earliest_presentation_time)) {
543 availability_start_time_ = XmlDateTimeNowWithOffset(
544 -std::ceil(earliest_presentation_time), clock_.get());
546 LOG(ERROR) <<
"Could not determine the earliest segment presentation "
547 "time for availabilityStartTime calculation.";
551 if (!availability_start_time_.empty())
552 mpd_node->SetStringAttribute(
"availabilityStartTime",
553 availability_start_time_);
556 mpd_node->SetStringAttribute(
557 "minimumUpdatePeriod",
560 LOG(WARNING) <<
"The profile is dynamic but no minimumUpdatePeriod "
564 SetIfPositive(
"timeShiftBufferDepth",
566 SetIfPositive(
"suggestedPresentationDelay",
567 mpd_options_.mpd_params.suggested_presentation_delay, mpd_node);
570 float MpdBuilder::GetStaticMpdDuration(XmlNode* mpd_node) {
572 DCHECK_EQ(MpdType::kStatic, mpd_options_.mpd_type);
574 xmlNodePtr period_node = FindPeriodNode(mpd_node);
575 DCHECK(period_node) <<
"Period element must be a child of mpd_node.";
576 DCHECK(IsPeriodNode(period_node));
582 float max_duration = 0.0f;
583 for (xmlNodePtr adaptation_set = xmlFirstElementChild(period_node);
584 adaptation_set; adaptation_set = xmlNextElementSibling(adaptation_set)) {
585 for (xmlNodePtr representation = xmlFirstElementChild(adaptation_set);
587 representation = xmlNextElementSibling(representation)) {
588 float duration = 0.0f;
589 if (GetDurationAttribute(representation, &duration)) {
590 max_duration = max_duration > duration ? max_duration : duration;
594 xmlUnsetProp(representation, BAD_CAST
"duration");
602 bool MpdBuilder::GetEarliestTimestamp(
double* timestamp_seconds) {
603 DCHECK(timestamp_seconds);
605 double earliest_timestamp(-1);
606 for (
const std::unique_ptr<AdaptationSet>& adaptation_set :
609 if (adaptation_set->GetEarliestTimestamp(×tamp) &&
610 ((earliest_timestamp < 0) || (timestamp < earliest_timestamp))) {
611 earliest_timestamp = timestamp;
614 if (earliest_timestamp < 0)
617 *timestamp_seconds = earliest_timestamp;
622 MediaInfo* media_info) {
624 const std::string kFileProtocol(
"file://");
625 std::string mpd_file_path = (mpd_path.find(kFileProtocol) == 0)
626 ? mpd_path.substr(kFileProtocol.size())
629 if (!mpd_file_path.empty()) {
630 std::string mpd_dir(FilePath::FromUTF8Unsafe(mpd_file_path)
631 .DirName().AsEndingWithSeparator().AsUTF8Unsafe());
632 if (!mpd_dir.empty()) {
633 if (media_info->has_media_file_name()) {
634 media_info->set_media_file_name(
635 MakePathRelative(media_info->media_file_name(), mpd_dir));
637 if (media_info->has_init_segment_name()) {
638 media_info->set_init_segment_name(
639 MakePathRelative(media_info->init_segment_name(), mpd_dir));
641 if (media_info->has_segment_template()) {
642 media_info->set_segment_template(
643 MakePathRelative(media_info->segment_template(), mpd_dir));
650 const std::string& lang,
652 base::AtomicSequenceNumber* counter)
653 : representation_counter_(counter),
654 id_(adaptation_set_id),
656 mpd_options_(mpd_options),
657 segments_aligned_(kSegmentAlignmentUnknown),
658 force_set_segment_alignment_(false) {
662 AdaptationSet::~AdaptationSet() {}
665 const uint32_t representation_id = representation_counter_->GetNext();
668 std::unique_ptr<RepresentationStateChangeListener> listener(
669 new RepresentationStateChangeListenerImpl(representation_id,
this));
670 std::unique_ptr<Representation> representation(
new Representation(
671 media_info, mpd_options_, representation_id, std::move(listener)));
673 if (!representation->Init()) {
674 LOG(ERROR) <<
"Failed to initialize Representation.";
680 if (media_info.has_video_info()) {
681 const MediaInfo::VideoInfo& video_info = media_info.video_info();
682 DCHECK(video_info.has_width());
683 DCHECK(video_info.has_height());
684 video_widths_.insert(video_info.width());
685 video_heights_.insert(video_info.height());
687 if (video_info.has_time_scale() && video_info.has_frame_duration())
688 RecordFrameRate(video_info.frame_duration(), video_info.time_scale());
690 AddPictureAspectRatio(video_info, &picture_aspect_ratio_);
693 if (media_info.has_video_info()) {
694 content_type_ =
"video";
695 }
else if (media_info.has_audio_info()) {
696 content_type_ =
"audio";
697 }
else if (media_info.has_text_info()) {
698 content_type_ =
"text";
700 if (media_info.text_info().has_type() &&
701 (media_info.text_info().type() != MediaInfo::TextInfo::UNKNOWN)) {
702 roles_.insert(MediaInfoTextTypeToRole(media_info.text_info().type()));
706 representations_.push_back(std::move(representation));
707 return representations_.back().get();
712 content_protection_elements_.push_back(content_protection_element);
713 RemoveDuplicateAttributes(&content_protection_elements_.back());
717 const std::string& pssh) {
718 UpdateContentProtectionPsshHelper(drm_uuid, pssh,
719 &content_protection_elements_);
733 AdaptationSetXmlNode adaptation_set;
735 bool suppress_representation_width =
false;
736 bool suppress_representation_height =
false;
737 bool suppress_representation_frame_rate =
false;
739 adaptation_set.SetId(id_);
740 adaptation_set.SetStringAttribute(
"contentType", content_type_);
741 if (!lang_.empty() && lang_ !=
"und") {
746 if (video_widths_.size() == 1) {
747 suppress_representation_width =
true;
748 adaptation_set.SetIntegerAttribute(
"width", *video_widths_.begin());
749 }
else if (video_widths_.size() > 1) {
750 adaptation_set.SetIntegerAttribute(
"maxWidth", *video_widths_.rbegin());
752 if (video_heights_.size() == 1) {
753 suppress_representation_height =
true;
754 adaptation_set.SetIntegerAttribute(
"height", *video_heights_.begin());
755 }
else if (video_heights_.size() > 1) {
756 adaptation_set.SetIntegerAttribute(
"maxHeight", *video_heights_.rbegin());
759 if (video_frame_rates_.size() == 1) {
760 suppress_representation_frame_rate =
true;
761 adaptation_set.SetStringAttribute(
"frameRate",
762 video_frame_rates_.begin()->second);
763 }
else if (video_frame_rates_.size() > 1) {
764 adaptation_set.SetStringAttribute(
"maxFrameRate",
765 video_frame_rates_.rbegin()->second);
770 if (mpd_options_.dash_profile == DashProfile::kOnDemand) {
771 CheckVodSegmentAlignment();
774 if (segments_aligned_ == kSegmentAlignmentTrue) {
775 adaptation_set.SetStringAttribute(
776 mpd_options_.dash_profile == DashProfile::kOnDemand
777 ?
"subsegmentAlignment"
778 :
"segmentAlignment",
782 if (picture_aspect_ratio_.size() == 1)
783 adaptation_set.SetStringAttribute(
"par", *picture_aspect_ratio_.begin());
785 if (!adaptation_set.AddContentProtectionElements(
786 content_protection_elements_)) {
787 return xml::scoped_xml_ptr<xmlNode>();
790 if (!trick_play_reference_ids_.empty()) {
791 std::string id_string;
792 for (uint32_t
id : trick_play_reference_ids_) {
793 id_string += std::to_string(
id) +
",";
795 DCHECK(!id_string.empty());
796 id_string.resize(id_string.size() - 1);
797 adaptation_set.AddEssentialProperty(
798 "http://dashif.org/guidelines/trickmode", id_string);
801 std::string switching_ids;
802 for (uint32_t
id : adaptation_set_switching_ids_) {
803 if (!switching_ids.empty())
804 switching_ids +=
',';
805 switching_ids += base::UintToString(
id);
807 if (!switching_ids.empty()) {
808 adaptation_set.AddSupplementalProperty(
809 "urn:mpeg:dash:adaptation-set-switching:2016", switching_ids);
812 for (AdaptationSet::Role role : roles_)
813 adaptation_set.AddRoleElement(
"urn:mpeg:dash:role:2011", RoleToText(role));
815 for (
const std::unique_ptr<Representation>& representation :
817 if (suppress_representation_width)
818 representation->SuppressOnce(Representation::kSuppressWidth);
819 if (suppress_representation_height)
820 representation->SuppressOnce(Representation::kSuppressHeight);
821 if (suppress_representation_frame_rate)
822 representation->SuppressOnce(Representation::kSuppressFrameRate);
823 xml::scoped_xml_ptr<xmlNode> child(representation->GetXml());
824 if (!child || !adaptation_set.AddChild(std::move(child)))
825 return xml::scoped_xml_ptr<xmlNode>();
828 return adaptation_set.PassScopedPtr();
833 segment_alignment ? kSegmentAlignmentTrue : kSegmentAlignmentFalse;
834 force_set_segment_alignment_ =
true;
838 adaptation_set_switching_ids_.push_back(adaptation_set_id);
851 if (mpd_options_.dash_profile == DashProfile::kLive) {
852 CheckLiveSegmentAlignment(representation_id, start_time, duration);
854 representation_segment_start_times_[representation_id].push_back(
860 uint32_t representation_id,
861 uint32_t frame_duration,
862 uint32_t timescale) {
863 RecordFrameRate(frame_duration, timescale);
867 trick_play_reference_ids_.insert(
id);
870 bool AdaptationSet::GetEarliestTimestamp(
double* timestamp_seconds) {
871 DCHECK(timestamp_seconds);
873 double earliest_timestamp(-1);
874 for (
const std::unique_ptr<Representation>& representation :
877 if (representation->GetEarliestTimestamp(×tamp) &&
878 ((earliest_timestamp < 0) || (timestamp < earliest_timestamp))) {
879 earliest_timestamp = timestamp;
882 if (earliest_timestamp < 0)
885 *timestamp_seconds = earliest_timestamp;
913 void AdaptationSet::CheckLiveSegmentAlignment(uint32_t representation_id,
916 if (segments_aligned_ == kSegmentAlignmentFalse ||
917 force_set_segment_alignment_) {
921 std::list<uint64_t>& representation_start_times =
922 representation_segment_start_times_[representation_id];
923 representation_start_times.push_back(start_time);
926 if (representation_segment_start_times_.size() != representations_.size())
929 DCHECK(!representation_start_times.empty());
930 const uint64_t expected_start_time = representation_start_times.front();
931 for (RepresentationTimeline::const_iterator it =
932 representation_segment_start_times_.begin();
933 it != representation_segment_start_times_.end(); ++it) {
937 if (it->second.empty())
940 if (expected_start_time != it->second.front()) {
943 segments_aligned_ = kSegmentAlignmentFalse;
944 representation_segment_start_times_.clear();
948 segments_aligned_ = kSegmentAlignmentTrue;
950 for (RepresentationTimeline::iterator it =
951 representation_segment_start_times_.begin();
952 it != representation_segment_start_times_.end(); ++it) {
953 it->second.pop_front();
959 void AdaptationSet::CheckVodSegmentAlignment() {
960 if (segments_aligned_ == kSegmentAlignmentFalse ||
961 force_set_segment_alignment_) {
964 if (representation_segment_start_times_.empty())
966 if (representation_segment_start_times_.size() == 1) {
967 segments_aligned_ = kSegmentAlignmentTrue;
974 const std::list<uint64_t>& expected_time_line =
975 representation_segment_start_times_.begin()->second;
977 bool all_segment_time_line_same_length =
true;
979 RepresentationTimeline::const_iterator it =
980 representation_segment_start_times_.begin();
981 for (++it; it != representation_segment_start_times_.end(); ++it) {
982 const std::list<uint64_t>& other_time_line = it->second;
983 if (expected_time_line.size() != other_time_line.size()) {
984 all_segment_time_line_same_length =
false;
987 const std::list<uint64_t>* longer_list = &other_time_line;
988 const std::list<uint64_t>* shorter_list = &expected_time_line;
989 if (expected_time_line.size() > other_time_line.size()) {
990 shorter_list = &other_time_line;
991 longer_list = &expected_time_line;
994 if (!std::equal(shorter_list->begin(), shorter_list->end(),
995 longer_list->begin())) {
997 segments_aligned_ = kSegmentAlignmentFalse;
998 representation_segment_start_times_.clear();
1009 if (!all_segment_time_line_same_length) {
1010 segments_aligned_ = kSegmentAlignmentUnknown;
1014 segments_aligned_ = kSegmentAlignmentTrue;
1019 void AdaptationSet::RecordFrameRate(uint32_t frame_duration,
1020 uint32_t timescale) {
1021 if (frame_duration == 0) {
1022 LOG(ERROR) <<
"Frame duration is 0 and cannot be set.";
1025 video_frame_rates_[
static_cast<double>(timescale) / frame_duration] =
1026 base::IntToString(timescale) +
"/" + base::IntToString(frame_duration);
1030 const MediaInfo& media_info,
1033 std::unique_ptr<RepresentationStateChangeListener> state_change_listener)
1034 : media_info_(media_info),
1037 mpd_options_(mpd_options),
1039 state_change_listener_(std::move(state_change_listener)),
1040 output_suppression_flags_(0) {}
1042 Representation::~Representation() {}
1045 if (!AtLeastOneTrue(media_info_.has_video_info(),
1046 media_info_.has_audio_info(),
1047 media_info_.has_text_info())) {
1051 LOG(ERROR) <<
"Representation needs one of video, audio, or text.";
1055 if (MoreThanOneTrue(media_info_.has_video_info(),
1056 media_info_.has_audio_info(),
1057 media_info_.has_text_info())) {
1058 LOG(ERROR) <<
"Only one of VideoInfo, AudioInfo, or TextInfo can be set.";
1062 if (media_info_.container_type() == MediaInfo::CONTAINER_UNKNOWN) {
1063 LOG(ERROR) <<
"'container_type' in MediaInfo cannot be CONTAINER_UNKNOWN.";
1067 if (media_info_.has_video_info()) {
1068 mime_type_ = GetVideoMimeType();
1069 if (!HasRequiredVideoFields(media_info_.video_info())) {
1070 LOG(ERROR) <<
"Missing required fields to create a video Representation.";
1073 }
else if (media_info_.has_audio_info()) {
1074 mime_type_ = GetAudioMimeType();
1075 }
else if (media_info_.has_text_info()) {
1076 mime_type_ = GetTextMimeType();
1079 if (mime_type_.empty())
1082 codecs_ = GetCodecs(media_info_);
1088 content_protection_elements_.push_back(content_protection_element);
1089 RemoveDuplicateAttributes(&content_protection_elements_.back());
1093 const std::string& pssh) {
1094 UpdateContentProtectionPsshHelper(drm_uuid, pssh,
1095 &content_protection_elements_);
1101 if (start_time == 0 && duration == 0) {
1102 LOG(WARNING) <<
"Got segment with start_time and duration == 0. Ignoring.";
1106 if (state_change_listener_)
1107 state_change_listener_->OnNewSegmentForRepresentation(start_time, duration);
1108 if (IsContiguous(start_time, duration, size)) {
1109 ++segment_infos_.back().repeat;
1112 segment_infos_.push_back(s);
1115 bandwidth_estimator_.AddBlock(
1116 size, static_cast<double>(duration) / media_info_.reference_time_scale());
1119 DCHECK_GE(segment_infos_.size(), 1u);
1123 if (media_info_.has_video_info()) {
1124 media_info_.mutable_video_info()->set_frame_duration(sample_duration);
1125 if (state_change_listener_) {
1126 state_change_listener_->OnSetFrameRateForRepresentation(
1127 sample_duration, media_info_.video_info().time_scale());
1139 if (!HasRequiredMediaInfoFields()) {
1140 LOG(ERROR) <<
"MediaInfo missing required fields.";
1141 return xml::scoped_xml_ptr<xmlNode>();
1144 const uint64_t bandwidth = media_info_.has_bandwidth()
1145 ? media_info_.bandwidth()
1146 : bandwidth_estimator_.Estimate();
1148 DCHECK(!(HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)));
1150 RepresentationXmlNode representation;
1152 representation.SetId(id_);
1153 representation.SetIntegerAttribute(
"bandwidth", bandwidth);
1154 if (!codecs_.empty())
1155 representation.SetStringAttribute(
"codecs", codecs_);
1156 representation.SetStringAttribute(
"mimeType", mime_type_);
1158 const bool has_video_info = media_info_.has_video_info();
1159 const bool has_audio_info = media_info_.has_audio_info();
1161 if (has_video_info &&
1162 !representation.AddVideoInfo(
1163 media_info_.video_info(),
1164 !(output_suppression_flags_ & kSuppressWidth),
1165 !(output_suppression_flags_ & kSuppressHeight),
1166 !(output_suppression_flags_ & kSuppressFrameRate))) {
1167 LOG(ERROR) <<
"Failed to add video info to Representation XML.";
1168 return xml::scoped_xml_ptr<xmlNode>();
1171 if (has_audio_info &&
1172 !representation.AddAudioInfo(media_info_.audio_info())) {
1173 LOG(ERROR) <<
"Failed to add audio info to Representation XML.";
1174 return xml::scoped_xml_ptr<xmlNode>();
1177 if (!representation.AddContentProtectionElements(
1178 content_protection_elements_)) {
1179 return xml::scoped_xml_ptr<xmlNode>();
1183 if (mpd_options_.mpd_type == MpdType::kStatic &&
1184 media_info_.has_media_duration_seconds()) {
1187 representation.SetFloatingPointAttribute(
1188 "duration", media_info_.media_duration_seconds());
1191 if (HasVODOnlyFields(media_info_) &&
1192 !representation.AddVODOnlyInfo(media_info_)) {
1193 LOG(ERROR) <<
"Failed to add VOD segment info.";
1194 return xml::scoped_xml_ptr<xmlNode>();
1197 if (HasLiveOnlyFields(media_info_) &&
1198 !representation.AddLiveOnlyInfo(media_info_, segment_infos_,
1200 LOG(ERROR) <<
"Failed to add Live info.";
1201 return xml::scoped_xml_ptr<xmlNode>();
1206 output_suppression_flags_ = 0;
1207 return representation.PassScopedPtr();
1211 output_suppression_flags_ |= flag;
1214 bool Representation::HasRequiredMediaInfoFields() {
1215 if (HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)) {
1216 LOG(ERROR) <<
"MediaInfo cannot have both VOD and Live fields.";
1220 if (!media_info_.has_container_type()) {
1221 LOG(ERROR) <<
"MediaInfo missing required field: container_type.";
1225 if (HasVODOnlyFields(media_info_) && !media_info_.has_bandwidth()) {
1226 LOG(ERROR) <<
"Missing 'bandwidth' field. MediaInfo requires bandwidth for "
1227 "static profile for generating a valid MPD.";
1231 VLOG_IF(3, HasLiveOnlyFields(media_info_) && !media_info_.has_bandwidth())
1232 <<
"MediaInfo missing field 'bandwidth'. Using estimated from "
1238 bool Representation::IsContiguous(uint64_t start_time,
1240 uint64_t size)
const {
1241 if (segment_infos_.empty())
1245 const SegmentInfo& previous = segment_infos_.back();
1246 const uint64_t previous_segment_end_time =
1247 previous.start_time + previous.duration * (previous.repeat + 1);
1248 if (previous_segment_end_time == start_time &&
1249 segment_infos_.back().duration == duration) {
1254 const uint64_t previous_segment_start_time =
1255 previous.start_time + previous.duration * previous.repeat;
1256 if (previous_segment_start_time >= start_time) {
1257 LOG(ERROR) <<
"Segments should not be out of order segment. Adding segment "
1258 "with start_time == "
1259 << start_time <<
" but the previous segment starts at "
1260 << previous_segment_start_time <<
".";
1265 const uint64_t kRoundingErrorGrace = 5;
1266 if (previous_segment_end_time + kRoundingErrorGrace < start_time) {
1267 LOG(WARNING) <<
"Found a gap of size "
1268 << (start_time - previous_segment_end_time)
1269 <<
" > kRoundingErrorGrace (" << kRoundingErrorGrace
1270 <<
"). The new segment starts at " << start_time
1271 <<
" but the previous segment ends at "
1272 << previous_segment_end_time <<
".";
1277 if (start_time < previous_segment_end_time - kRoundingErrorGrace) {
1279 <<
"Segments should not be overlapping. The new segment starts at "
1280 << start_time <<
" but the previous segment ends at "
1281 << previous_segment_end_time <<
".";
1289 void Representation::SlideWindow() {
1290 DCHECK(!segment_infos_.empty());
1292 mpd_options_.mpd_type == MpdType::kStatic)
1295 const uint32_t time_scale = GetTimeScale(media_info_);
1296 DCHECK_GT(time_scale, 0u);
1298 uint64_t time_shift_buffer_depth =
static_cast<uint64_t
>(
1303 const uint64_t current_play_time = LatestSegmentStartTime(segment_infos_);
1304 if (current_play_time <= time_shift_buffer_depth)
1307 const uint64_t timeshift_limit = current_play_time - time_shift_buffer_depth;
1311 std::list<SegmentInfo>::iterator first = segment_infos_.begin();
1312 std::list<SegmentInfo>::iterator last = first;
1313 size_t num_segments_removed = 0;
1314 for (; last != segment_infos_.end(); ++last) {
1315 const uint64_t last_segment_end_time = LastSegmentEndTime(*last);
1316 if (timeshift_limit < last_segment_end_time)
1318 num_segments_removed += last->repeat + 1;
1320 segment_infos_.erase(first, last);
1321 start_number_ += num_segments_removed;
1324 SegmentInfo* first_segment_info = &segment_infos_.front();
1325 DCHECK_LE(timeshift_limit, LastSegmentEndTime(*first_segment_info));
1328 const int repeat_index =
1329 SearchTimedOutRepeatIndex(timeshift_limit, *first_segment_info);
1330 CHECK_GE(repeat_index, 0);
1331 if (repeat_index == 0)
1334 first_segment_info->start_time = first_segment_info->start_time +
1335 first_segment_info->duration * repeat_index;
1337 first_segment_info->repeat = first_segment_info->repeat - repeat_index;
1338 start_number_ += repeat_index;
1341 std::string Representation::GetVideoMimeType()
const {
1342 return GetMimeType(
"video", media_info_.container_type());
1345 std::string Representation::GetAudioMimeType()
const {
1346 return GetMimeType(
"audio", media_info_.container_type());
1349 std::string Representation::GetTextMimeType()
const {
1350 CHECK(media_info_.has_text_info());
1351 if (media_info_.text_info().format() ==
"ttml") {
1352 switch (media_info_.container_type()) {
1353 case MediaInfo::CONTAINER_TEXT:
1354 return "application/ttml+xml";
1355 case MediaInfo::CONTAINER_MP4:
1356 return "application/mp4";
1358 LOG(ERROR) <<
"Failed to determine MIME type for TTML container: "
1359 << media_info_.container_type();
1363 if (media_info_.text_info().format() ==
"vtt") {
1364 if (media_info_.container_type() == MediaInfo::CONTAINER_TEXT) {
1366 }
else if (media_info_.container_type() == MediaInfo::CONTAINER_MP4) {
1367 return "application/mp4";
1369 LOG(ERROR) <<
"Failed to determine MIME type for VTT container: "
1370 << media_info_.container_type();
1374 LOG(ERROR) <<
"Cannot determine MIME type for format: "
1375 << media_info_.text_info().format()
1376 <<
" container: " << media_info_.container_type();
1380 bool Representation::GetEarliestTimestamp(
double* timestamp_seconds) {
1381 DCHECK(timestamp_seconds);
1383 if (segment_infos_.empty())
1386 *timestamp_seconds =
static_cast<double>(segment_infos_.begin()->start_time) /
1387 GetTimeScale(media_info_);
void OnSetFrameRateForRepresentation(uint32_t representation_id, uint32_t frame_duration, uint32_t timescale)
virtual void AddNewSegment(uint64_t start_time, uint64_t duration, uint64_t size)
Representation(const MediaInfo &media_info, const MpdOptions &mpd_options, uint32_t representation_id, std::unique_ptr< RepresentationStateChangeListener > state_change_listener)
virtual void SetSampleDuration(uint32_t sample_duration)
virtual Representation * AddRepresentation(const MediaInfo &media_info)
std::string LanguageToShortestForm(const std::string &language)
virtual void AddContentProtectionElement(const ContentProtectionElement &element)
virtual void AddTrickPlayReferenceId(uint32_t id)
MpdBuilder(const MpdOptions &mpd_options)
virtual void AddRole(Role role)
void AddBaseUrl(const std::string &base_url)
virtual void UpdateContentProtectionPssh(const std::string &drm_uuid, const std::string &pssh)
AdaptationSet(uint32_t adaptation_set_id, const std::string &lang, const MpdOptions &mpd_options, base::AtomicSequenceNumber *representation_counter)
xml::scoped_xml_ptr< xmlNode > GetXml()
virtual bool ToString(std::string *output)
void AddAdaptationSetSwitching(uint32_t adaptation_set_id)
virtual void ForceSetSegmentAlignment(bool segment_alignment)
static void MakePathsRelativeToMpd(const std::string &mpd_path, MediaInfo *media_info)
double minimum_update_period
xml::scoped_xml_ptr< xmlNode > GetXml()
virtual void AddContentProtectionElement(const ContentProtectionElement &element)
virtual AdaptationSet * AddAdaptationSet(const std::string &lang)
void OnNewSegmentForRepresentation(uint32_t representation_id, uint64_t start_time, uint64_t duration)
virtual void UpdateContentProtectionPssh(const std::string &drm_uuid, const std::string &pssh)
double time_shift_buffer_depth
void SuppressOnce(SuppressFlag flag)