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/media/base/language_utils.h"
28 #include "packager/media/file/file.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;
192 bool WriteXmlCharArrayToOutput(xmlChar* doc,
194 std::string* output) {
197 output->assign(doc, doc + doc_size);
201 bool WriteXmlCharArrayToOutput(xmlChar* doc,
203 media::File* output) {
206 if (output->Write(doc, doc_size) < doc_size)
209 return output->Flush();
212 std::string MakePathRelative(
const std::string& path,
213 const std::string& mpd_dir) {
214 return (path.find(mpd_dir) == 0) ? path.substr(mpd_dir.size()) : path;
220 bool HasRequiredVideoFields(
const MediaInfo_VideoInfo& video_info) {
221 if (!video_info.has_height() || !video_info.has_width()) {
223 <<
"Width and height are required fields for generating a valid MPD.";
228 LOG_IF(WARNING, !video_info.has_time_scale())
229 <<
"Video info does not contain timescale required for "
230 "calculating framerate. @frameRate is required for DASH IOP.";
231 LOG_IF(WARNING, !video_info.has_frame_duration())
232 <<
"Video info does not contain frame duration required "
233 "for calculating framerate. @frameRate is required for DASH IOP.";
234 LOG_IF(WARNING, !video_info.has_pixel_width())
235 <<
"Video info does not contain pixel_width to calculate the sample "
236 "aspect ratio required for DASH IOP.";
237 LOG_IF(WARNING, !video_info.has_pixel_height())
238 <<
"Video info does not contain pixel_height to calculate the sample "
239 "aspect ratio required for DASH IOP.";
250 std::string GetPictureAspectRatio(uint32_t width,
252 uint32_t pixel_width,
253 uint32_t pixel_height) {
254 const uint32_t scaled_width = pixel_width * width;
255 const uint32_t scaled_height = pixel_height * height;
256 const double par =
static_cast<double>(scaled_width) / scaled_height;
260 const uint32_t kLargestPossibleParY = 19;
262 uint32_t par_num = 0;
263 uint32_t par_den = 0;
264 double min_error = 1.0;
265 for (uint32_t den = 1; den <= kLargestPossibleParY; ++den) {
266 uint32_t num = par * den + 0.5;
267 double error = fabs(par - static_cast<double>(num) / den);
268 if (error < min_error) {
272 if (error == 0)
break;
275 VLOG(2) <<
"width*pix_width : height*pixel_height (" << scaled_width <<
":"
276 << scaled_height <<
") reduced to " << par_num <<
":" << par_den
277 <<
" with error " << min_error <<
".";
279 return base::IntToString(par_num) +
":" + base::IntToString(par_den);
284 void AddPictureAspectRatio(
285 const MediaInfo::VideoInfo& video_info,
286 std::set<std::string>* picture_aspect_ratio) {
289 if (picture_aspect_ratio->size() > 1)
292 if (video_info.width() == 0 || video_info.height() == 0 ||
293 video_info.pixel_width() == 0 || video_info.pixel_height() == 0) {
298 picture_aspect_ratio->insert(
"bogus");
299 picture_aspect_ratio->insert(
"entries");
303 const std::string par = GetPictureAspectRatio(
304 video_info.width(), video_info.height(),
305 video_info.pixel_width(), video_info.pixel_height());
306 DVLOG(1) <<
"Setting par as: " << par
307 <<
" for video with width: " << video_info.width()
308 <<
" height: " << video_info.height()
309 <<
" pixel_width: " << video_info.pixel_width() <<
" pixel_height; "
310 << video_info.pixel_height();
311 picture_aspect_ratio->insert(par);
314 std::string RoleToText(AdaptationSet::Role role) {
318 case AdaptationSet::kRoleCaption:
320 case AdaptationSet::kRoleSubtitle:
322 case AdaptationSet::kRoleMain:
324 case AdaptationSet::kRoleAlternate:
326 case AdaptationSet::kRoleSupplementary:
327 return "supplementary";
328 case AdaptationSet::kRoleCommentary:
330 case AdaptationSet::kRoleDub:
341 class LibXmlInitializer {
343 LibXmlInitializer() : initialized_(false) {
344 base::AutoLock lock(lock_);
351 ~LibXmlInitializer() {
352 base::AutoLock lock(lock_);
355 initialized_ =
false;
363 DISALLOW_COPY_AND_ASSIGN(LibXmlInitializer);
366 class RepresentationStateChangeListenerImpl
367 :
public RepresentationStateChangeListener {
370 RepresentationStateChangeListenerImpl(uint32_t representation_id,
371 AdaptationSet* adaptation_set)
372 : representation_id_(representation_id), adaptation_set_(adaptation_set) {
373 DCHECK(adaptation_set_);
375 ~RepresentationStateChangeListenerImpl()
override {}
378 void OnNewSegmentForRepresentation(uint64_t start_time,
379 uint64_t duration)
override {
380 adaptation_set_->OnNewSegmentForRepresentation(representation_id_,
381 start_time, duration);
384 void OnSetFrameRateForRepresentation(uint32_t frame_duration,
385 uint32_t timescale)
override {
386 adaptation_set_->OnSetFrameRateForRepresentation(representation_id_,
387 frame_duration, timescale);
391 const uint32_t representation_id_;
392 AdaptationSet*
const adaptation_set_;
394 DISALLOW_COPY_AND_ASSIGN(RepresentationStateChangeListenerImpl);
400 : mpd_options_(mpd_options), clock_(new base::DefaultClock()) {}
402 MpdBuilder::~MpdBuilder() {}
405 base_urls_.push_back(base_url);
409 std::unique_ptr<AdaptationSet> adaptation_set(
410 new AdaptationSet(adaptation_set_counter_.GetNext(), lang, mpd_options_,
411 &representation_counter_));
412 DCHECK(adaptation_set);
414 if (!lang.empty() && lang == mpd_options_.default_language) {
415 adaptation_set->AddRole(AdaptationSet::kRoleMain);
418 adaptation_sets_.push_back(std::move(adaptation_set));
419 return adaptation_sets_.back().get();
424 return WriteMpdToOutput(output_file);
429 return WriteMpdToOutput(output);
431 template <
typename OutputType>
432 bool MpdBuilder::WriteMpdToOutput(OutputType* output) {
433 static LibXmlInitializer lib_xml_initializer;
435 xml::scoped_xml_ptr<xmlDoc> doc(GenerateMpd());
439 static const int kNiceFormat = 1;
440 int doc_str_size = 0;
441 xmlChar* doc_str = NULL;
442 xmlDocDumpFormatMemoryEnc(doc.get(), &doc_str, &doc_str_size,
"UTF-8",
445 bool result = WriteXmlCharArrayToOutput(doc_str, doc_str_size, output);
453 xmlDocPtr MpdBuilder::GenerateMpd() {
455 static const char kXmlVersion[] =
"1.0";
456 xml::scoped_xml_ptr<xmlDoc> doc(xmlNewDoc(BAD_CAST kXmlVersion));
460 XmlNode period(
"Period");
466 for (
const std::unique_ptr<AdaptationSet>& adaptation_set :
468 xml::scoped_xml_ptr<xmlNode> child(adaptation_set->GetXml());
469 if (!child.get() || !period.AddChild(std::move(child)))
474 std::list<std::string>::const_iterator base_urls_it = base_urls_.begin();
475 for (; base_urls_it != base_urls_.end(); ++base_urls_it) {
476 XmlNode base_url(
"BaseURL");
477 base_url.SetContent(*base_urls_it);
479 if (!mpd.AddChild(base_url.PassScopedPtr()))
484 if (mpd_options_.mpd_type == MpdType::kDynamic) {
486 period.SetStringAttribute(
"start",
"PT0S");
489 if (!mpd.AddChild(period.PassScopedPtr()))
492 AddMpdNameSpaceInfo(&mpd);
494 static const char kOnDemandProfile[] =
495 "urn:mpeg:dash:profile:isoff-on-demand:2011";
496 static const char kLiveProfile[] =
497 "urn:mpeg:dash:profile:isoff-live:2011";
498 switch (mpd_options_.dash_profile) {
499 case DashProfile::kOnDemand:
500 mpd.SetStringAttribute(
"profiles", kOnDemandProfile);
502 case DashProfile::kLive:
503 mpd.SetStringAttribute(
"profiles", kLiveProfile);
506 NOTREACHED() <<
"Unknown DASH profile: "
507 <<
static_cast<int>(mpd_options_.dash_profile);
511 AddCommonMpdInfo(&mpd);
512 switch (mpd_options_.mpd_type) {
513 case MpdType::kStatic:
514 AddStaticMpdInfo(&mpd);
516 case MpdType::kDynamic:
517 AddDynamicMpdInfo(&mpd);
520 NOTREACHED() <<
"Unknown MPD type: "
521 <<
static_cast<int>(mpd_options_.mpd_type);
526 const std::string version = GetPackagerVersion();
527 if (!version.empty()) {
528 std::string version_string =
529 base::StringPrintf(
"Generated with %s version %s",
530 GetPackagerProjectUrl().c_str(), version.c_str());
531 xml::scoped_xml_ptr<xmlNode> comment(
532 xmlNewDocComment(doc.get(), BAD_CAST version_string.c_str()));
533 xmlDocSetRootElement(doc.get(), comment.get());
534 xmlAddSibling(comment.release(), mpd.Release());
536 xmlDocSetRootElement(doc.get(), mpd.Release());
538 return doc.release();
541 void MpdBuilder::AddCommonMpdInfo(XmlNode* mpd_node) {
542 if (Positive(mpd_options_.min_buffer_time)) {
543 mpd_node->SetStringAttribute(
544 "minBufferTime", SecondsToXmlDuration(mpd_options_.min_buffer_time));
546 LOG(ERROR) <<
"minBufferTime value not specified.";
551 void MpdBuilder::AddStaticMpdInfo(XmlNode* mpd_node) {
553 DCHECK_EQ(MpdType::kStatic, mpd_options_.mpd_type);
555 static const char kStaticMpdType[] =
"static";
556 mpd_node->SetStringAttribute(
"type", kStaticMpdType);
557 mpd_node->SetStringAttribute(
558 "mediaPresentationDuration",
559 SecondsToXmlDuration(GetStaticMpdDuration(mpd_node)));
562 void MpdBuilder::AddDynamicMpdInfo(XmlNode* mpd_node) {
564 DCHECK_EQ(MpdType::kDynamic, mpd_options_.mpd_type);
566 static const char kDynamicMpdType[] =
"dynamic";
567 mpd_node->SetStringAttribute(
"type", kDynamicMpdType);
570 mpd_node->SetStringAttribute(
"publishTime",
571 XmlDateTimeNowWithOffset(0, clock_.get()));
575 if (availability_start_time_.empty()) {
576 double earliest_presentation_time;
577 if (GetEarliestTimestamp(&earliest_presentation_time)) {
578 availability_start_time_ = XmlDateTimeNowWithOffset(
579 -std::ceil(earliest_presentation_time), clock_.get());
581 LOG(ERROR) <<
"Could not determine the earliest segment presentation "
582 "time for availabilityStartTime calculation.";
586 if (!availability_start_time_.empty())
587 mpd_node->SetStringAttribute(
"availabilityStartTime",
588 availability_start_time_);
590 if (Positive(mpd_options_.minimum_update_period)) {
591 mpd_node->SetStringAttribute(
592 "minimumUpdatePeriod",
593 SecondsToXmlDuration(mpd_options_.minimum_update_period));
595 LOG(WARNING) <<
"The profile is dynamic but no minimumUpdatePeriod "
599 SetIfPositive(
"timeShiftBufferDepth", mpd_options_.time_shift_buffer_depth,
601 SetIfPositive(
"suggestedPresentationDelay",
602 mpd_options_.suggested_presentation_delay, mpd_node);
605 float MpdBuilder::GetStaticMpdDuration(XmlNode* mpd_node) {
607 DCHECK_EQ(MpdType::kStatic, mpd_options_.mpd_type);
609 xmlNodePtr period_node = FindPeriodNode(mpd_node);
610 DCHECK(period_node) <<
"Period element must be a child of mpd_node.";
611 DCHECK(IsPeriodNode(period_node));
617 float max_duration = 0.0f;
618 for (xmlNodePtr adaptation_set = xmlFirstElementChild(period_node);
619 adaptation_set; adaptation_set = xmlNextElementSibling(adaptation_set)) {
620 for (xmlNodePtr representation = xmlFirstElementChild(adaptation_set);
622 representation = xmlNextElementSibling(representation)) {
623 float duration = 0.0f;
624 if (GetDurationAttribute(representation, &duration)) {
625 max_duration = max_duration > duration ? max_duration : duration;
629 xmlUnsetProp(representation, BAD_CAST
"duration");
637 bool MpdBuilder::GetEarliestTimestamp(
double* timestamp_seconds) {
638 DCHECK(timestamp_seconds);
640 double earliest_timestamp(-1);
641 for (
const std::unique_ptr<AdaptationSet>& adaptation_set :
644 if (adaptation_set->GetEarliestTimestamp(×tamp) &&
645 ((earliest_timestamp < 0) || (timestamp < earliest_timestamp))) {
646 earliest_timestamp = timestamp;
649 if (earliest_timestamp < 0)
652 *timestamp_seconds = earliest_timestamp;
657 MediaInfo* media_info) {
659 const std::string kFileProtocol(
"file://");
660 std::string mpd_file_path = (mpd_path.find(kFileProtocol) == 0)
661 ? mpd_path.substr(kFileProtocol.size())
664 if (!mpd_file_path.empty()) {
665 std::string mpd_dir(FilePath::FromUTF8Unsafe(mpd_file_path)
666 .DirName().AsEndingWithSeparator().AsUTF8Unsafe());
667 if (!mpd_dir.empty()) {
668 if (media_info->has_media_file_name()) {
669 media_info->set_media_file_name(
670 MakePathRelative(media_info->media_file_name(), mpd_dir));
672 if (media_info->has_init_segment_name()) {
673 media_info->set_init_segment_name(
674 MakePathRelative(media_info->init_segment_name(), mpd_dir));
676 if (media_info->has_segment_template()) {
677 media_info->set_segment_template(
678 MakePathRelative(media_info->segment_template(), mpd_dir));
685 const std::string& lang,
687 base::AtomicSequenceNumber* counter)
688 : representation_counter_(counter),
689 id_(adaptation_set_id),
691 mpd_options_(mpd_options),
692 segments_aligned_(kSegmentAlignmentUnknown),
693 force_set_segment_alignment_(false) {
697 AdaptationSet::~AdaptationSet() {}
700 const uint32_t representation_id = representation_counter_->GetNext();
703 std::unique_ptr<RepresentationStateChangeListener> listener(
704 new RepresentationStateChangeListenerImpl(representation_id,
this));
705 std::unique_ptr<Representation> representation(
new Representation(
706 media_info, mpd_options_, representation_id, std::move(listener)));
708 if (!representation->Init()) {
709 LOG(ERROR) <<
"Failed to initialize Representation.";
715 if (media_info.has_video_info()) {
716 const MediaInfo::VideoInfo& video_info = media_info.video_info();
717 DCHECK(video_info.has_width());
718 DCHECK(video_info.has_height());
719 video_widths_.insert(video_info.width());
720 video_heights_.insert(video_info.height());
722 if (video_info.has_time_scale() && video_info.has_frame_duration())
723 RecordFrameRate(video_info.frame_duration(), video_info.time_scale());
725 AddPictureAspectRatio(video_info, &picture_aspect_ratio_);
728 if (media_info.has_video_info()) {
729 content_type_ =
"video";
730 }
else if (media_info.has_audio_info()) {
731 content_type_ =
"audio";
732 }
else if (media_info.has_text_info()) {
733 content_type_ =
"text";
735 if (media_info.text_info().has_type() &&
736 (media_info.text_info().type() != MediaInfo::TextInfo::UNKNOWN)) {
737 roles_.insert(MediaInfoTextTypeToRole(media_info.text_info().type()));
741 representations_.push_back(std::move(representation));
742 return representations_.back().get();
747 content_protection_elements_.push_back(content_protection_element);
748 RemoveDuplicateAttributes(&content_protection_elements_.back());
752 const std::string& pssh) {
753 UpdateContentProtectionPsshHelper(drm_uuid, pssh,
754 &content_protection_elements_);
768 AdaptationSetXmlNode adaptation_set;
770 bool suppress_representation_width =
false;
771 bool suppress_representation_height =
false;
772 bool suppress_representation_frame_rate =
false;
774 adaptation_set.SetId(id_);
775 adaptation_set.SetStringAttribute(
"contentType", content_type_);
776 if (!lang_.empty() && lang_ !=
"und") {
781 if (video_widths_.size() == 1) {
782 suppress_representation_width =
true;
783 adaptation_set.SetIntegerAttribute(
"width", *video_widths_.begin());
784 }
else if (video_widths_.size() > 1) {
785 adaptation_set.SetIntegerAttribute(
"maxWidth", *video_widths_.rbegin());
787 if (video_heights_.size() == 1) {
788 suppress_representation_height =
true;
789 adaptation_set.SetIntegerAttribute(
"height", *video_heights_.begin());
790 }
else if (video_heights_.size() > 1) {
791 adaptation_set.SetIntegerAttribute(
"maxHeight", *video_heights_.rbegin());
794 if (video_frame_rates_.size() == 1) {
795 suppress_representation_frame_rate =
true;
796 adaptation_set.SetStringAttribute(
"frameRate",
797 video_frame_rates_.begin()->second);
798 }
else if (video_frame_rates_.size() > 1) {
799 adaptation_set.SetStringAttribute(
"maxFrameRate",
800 video_frame_rates_.rbegin()->second);
805 if (mpd_options_.dash_profile == DashProfile::kOnDemand) {
806 CheckVodSegmentAlignment();
809 if (segments_aligned_ == kSegmentAlignmentTrue) {
810 adaptation_set.SetStringAttribute(
811 mpd_options_.dash_profile == DashProfile::kOnDemand
812 ?
"subsegmentAlignment"
813 :
"segmentAlignment",
817 if (picture_aspect_ratio_.size() == 1)
818 adaptation_set.SetStringAttribute(
"par", *picture_aspect_ratio_.begin());
820 if (!adaptation_set.AddContentProtectionElements(
821 content_protection_elements_)) {
822 return xml::scoped_xml_ptr<xmlNode>();
825 if (!trick_play_reference_ids_.empty()) {
826 std::string id_string;
827 for (uint32_t
id : trick_play_reference_ids_) {
828 id_string += std::to_string(
id) +
",";
830 DCHECK(!id_string.empty());
831 id_string.resize(id_string.size() - 1);
832 adaptation_set.AddEssentialProperty(
833 "http://dashif.org/guidelines/trickmode", id_string);
836 std::string switching_ids;
837 for (uint32_t
id : adaptation_set_switching_ids_) {
838 if (!switching_ids.empty())
839 switching_ids +=
',';
840 switching_ids += base::UintToString(
id);
842 if (!switching_ids.empty()) {
843 adaptation_set.AddSupplementalProperty(
844 "urn:mpeg:dash:adaptation-set-switching:2016", switching_ids);
847 for (AdaptationSet::Role role : roles_)
848 adaptation_set.AddRoleElement(
"urn:mpeg:dash:role:2011", RoleToText(role));
850 for (
const std::unique_ptr<Representation>& representation :
852 if (suppress_representation_width)
853 representation->SuppressOnce(Representation::kSuppressWidth);
854 if (suppress_representation_height)
855 representation->SuppressOnce(Representation::kSuppressHeight);
856 if (suppress_representation_frame_rate)
857 representation->SuppressOnce(Representation::kSuppressFrameRate);
858 xml::scoped_xml_ptr<xmlNode> child(representation->GetXml());
859 if (!child || !adaptation_set.AddChild(std::move(child)))
860 return xml::scoped_xml_ptr<xmlNode>();
863 return adaptation_set.PassScopedPtr();
868 segment_alignment ? kSegmentAlignmentTrue : kSegmentAlignmentFalse;
869 force_set_segment_alignment_ =
true;
873 adaptation_set_switching_ids_.push_back(adaptation_set_id);
886 if (mpd_options_.dash_profile == DashProfile::kLive) {
887 CheckLiveSegmentAlignment(representation_id, start_time, duration);
889 representation_segment_start_times_[representation_id].push_back(
895 uint32_t representation_id,
896 uint32_t frame_duration,
897 uint32_t timescale) {
898 RecordFrameRate(frame_duration, timescale);
902 trick_play_reference_ids_.insert(
id);
905 bool AdaptationSet::GetEarliestTimestamp(
double* timestamp_seconds) {
906 DCHECK(timestamp_seconds);
908 double earliest_timestamp(-1);
909 for (
const std::unique_ptr<Representation>& representation :
912 if (representation->GetEarliestTimestamp(×tamp) &&
913 ((earliest_timestamp < 0) || (timestamp < earliest_timestamp))) {
914 earliest_timestamp = timestamp;
917 if (earliest_timestamp < 0)
920 *timestamp_seconds = earliest_timestamp;
948 void AdaptationSet::CheckLiveSegmentAlignment(uint32_t representation_id,
951 if (segments_aligned_ == kSegmentAlignmentFalse ||
952 force_set_segment_alignment_) {
956 std::list<uint64_t>& representation_start_times =
957 representation_segment_start_times_[representation_id];
958 representation_start_times.push_back(start_time);
961 if (representation_segment_start_times_.size() != representations_.size())
964 DCHECK(!representation_start_times.empty());
965 const uint64_t expected_start_time = representation_start_times.front();
966 for (RepresentationTimeline::const_iterator it =
967 representation_segment_start_times_.begin();
968 it != representation_segment_start_times_.end(); ++it) {
972 if (it->second.empty())
975 if (expected_start_time != it->second.front()) {
978 segments_aligned_ = kSegmentAlignmentFalse;
979 representation_segment_start_times_.clear();
983 segments_aligned_ = kSegmentAlignmentTrue;
985 for (RepresentationTimeline::iterator it =
986 representation_segment_start_times_.begin();
987 it != representation_segment_start_times_.end(); ++it) {
988 it->second.pop_front();
994 void AdaptationSet::CheckVodSegmentAlignment() {
995 if (segments_aligned_ == kSegmentAlignmentFalse ||
996 force_set_segment_alignment_) {
999 if (representation_segment_start_times_.empty())
1001 if (representation_segment_start_times_.size() == 1) {
1002 segments_aligned_ = kSegmentAlignmentTrue;
1009 const std::list<uint64_t>& expected_time_line =
1010 representation_segment_start_times_.begin()->second;
1012 bool all_segment_time_line_same_length =
true;
1014 RepresentationTimeline::const_iterator it =
1015 representation_segment_start_times_.begin();
1016 for (++it; it != representation_segment_start_times_.end(); ++it) {
1017 const std::list<uint64_t>& other_time_line = it->second;
1018 if (expected_time_line.size() != other_time_line.size()) {
1019 all_segment_time_line_same_length =
false;
1022 const std::list<uint64_t>* longer_list = &other_time_line;
1023 const std::list<uint64_t>* shorter_list = &expected_time_line;
1024 if (expected_time_line.size() > other_time_line.size()) {
1025 shorter_list = &other_time_line;
1026 longer_list = &expected_time_line;
1029 if (!std::equal(shorter_list->begin(), shorter_list->end(),
1030 longer_list->begin())) {
1032 segments_aligned_ = kSegmentAlignmentFalse;
1033 representation_segment_start_times_.clear();
1044 if (!all_segment_time_line_same_length) {
1045 segments_aligned_ = kSegmentAlignmentUnknown;
1049 segments_aligned_ = kSegmentAlignmentTrue;
1054 void AdaptationSet::RecordFrameRate(uint32_t frame_duration,
1055 uint32_t timescale) {
1056 if (frame_duration == 0) {
1057 LOG(ERROR) <<
"Frame duration is 0 and cannot be set.";
1060 video_frame_rates_[
static_cast<double>(timescale) / frame_duration] =
1061 base::IntToString(timescale) +
"/" + base::IntToString(frame_duration);
1065 const MediaInfo& media_info,
1068 std::unique_ptr<RepresentationStateChangeListener> state_change_listener)
1069 : media_info_(media_info),
1072 mpd_options_(mpd_options),
1074 state_change_listener_(std::move(state_change_listener)),
1075 output_suppression_flags_(0) {}
1077 Representation::~Representation() {}
1080 if (!AtLeastOneTrue(media_info_.has_video_info(),
1081 media_info_.has_audio_info(),
1082 media_info_.has_text_info())) {
1086 LOG(ERROR) <<
"Representation needs one of video, audio, or text.";
1090 if (MoreThanOneTrue(media_info_.has_video_info(),
1091 media_info_.has_audio_info(),
1092 media_info_.has_text_info())) {
1093 LOG(ERROR) <<
"Only one of VideoInfo, AudioInfo, or TextInfo can be set.";
1097 if (media_info_.container_type() == MediaInfo::CONTAINER_UNKNOWN) {
1098 LOG(ERROR) <<
"'container_type' in MediaInfo cannot be CONTAINER_UNKNOWN.";
1102 if (media_info_.has_video_info()) {
1103 mime_type_ = GetVideoMimeType();
1104 if (!HasRequiredVideoFields(media_info_.video_info())) {
1105 LOG(ERROR) <<
"Missing required fields to create a video Representation.";
1108 }
else if (media_info_.has_audio_info()) {
1109 mime_type_ = GetAudioMimeType();
1110 }
else if (media_info_.has_text_info()) {
1111 mime_type_ = GetTextMimeType();
1114 if (mime_type_.empty())
1117 codecs_ = GetCodecs(media_info_);
1123 content_protection_elements_.push_back(content_protection_element);
1124 RemoveDuplicateAttributes(&content_protection_elements_.back());
1128 const std::string& pssh) {
1129 UpdateContentProtectionPsshHelper(drm_uuid, pssh,
1130 &content_protection_elements_);
1136 if (start_time == 0 && duration == 0) {
1137 LOG(WARNING) <<
"Got segment with start_time and duration == 0. Ignoring.";
1141 if (state_change_listener_)
1142 state_change_listener_->OnNewSegmentForRepresentation(start_time, duration);
1143 if (IsContiguous(start_time, duration, size)) {
1144 ++segment_infos_.back().repeat;
1147 segment_infos_.push_back(s);
1150 bandwidth_estimator_.AddBlock(
1151 size, static_cast<double>(duration) / media_info_.reference_time_scale());
1154 DCHECK_GE(segment_infos_.size(), 1u);
1158 if (media_info_.has_video_info()) {
1159 media_info_.mutable_video_info()->set_frame_duration(sample_duration);
1160 if (state_change_listener_) {
1161 state_change_listener_->OnSetFrameRateForRepresentation(
1162 sample_duration, media_info_.video_info().time_scale());
1174 if (!HasRequiredMediaInfoFields()) {
1175 LOG(ERROR) <<
"MediaInfo missing required fields.";
1176 return xml::scoped_xml_ptr<xmlNode>();
1179 const uint64_t bandwidth = media_info_.has_bandwidth()
1180 ? media_info_.bandwidth()
1181 : bandwidth_estimator_.Estimate();
1183 DCHECK(!(HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)));
1185 RepresentationXmlNode representation;
1187 representation.SetId(id_);
1188 representation.SetIntegerAttribute(
"bandwidth", bandwidth);
1189 if (!codecs_.empty())
1190 representation.SetStringAttribute(
"codecs", codecs_);
1191 representation.SetStringAttribute(
"mimeType", mime_type_);
1193 const bool has_video_info = media_info_.has_video_info();
1194 const bool has_audio_info = media_info_.has_audio_info();
1196 if (has_video_info &&
1197 !representation.AddVideoInfo(
1198 media_info_.video_info(),
1199 !(output_suppression_flags_ & kSuppressWidth),
1200 !(output_suppression_flags_ & kSuppressHeight),
1201 !(output_suppression_flags_ & kSuppressFrameRate))) {
1202 LOG(ERROR) <<
"Failed to add video info to Representation XML.";
1203 return xml::scoped_xml_ptr<xmlNode>();
1206 if (has_audio_info &&
1207 !representation.AddAudioInfo(media_info_.audio_info())) {
1208 LOG(ERROR) <<
"Failed to add audio info to Representation XML.";
1209 return xml::scoped_xml_ptr<xmlNode>();
1212 if (!representation.AddContentProtectionElements(
1213 content_protection_elements_)) {
1214 return xml::scoped_xml_ptr<xmlNode>();
1218 if (mpd_options_.mpd_type == MpdType::kStatic &&
1219 media_info_.has_media_duration_seconds()) {
1222 representation.SetFloatingPointAttribute(
1223 "duration", media_info_.media_duration_seconds());
1226 if (HasVODOnlyFields(media_info_) &&
1227 !representation.AddVODOnlyInfo(media_info_)) {
1228 LOG(ERROR) <<
"Failed to add VOD segment info.";
1229 return xml::scoped_xml_ptr<xmlNode>();
1232 if (HasLiveOnlyFields(media_info_) &&
1233 !representation.AddLiveOnlyInfo(media_info_, segment_infos_,
1235 LOG(ERROR) <<
"Failed to add Live info.";
1236 return xml::scoped_xml_ptr<xmlNode>();
1241 output_suppression_flags_ = 0;
1242 return representation.PassScopedPtr();
1246 output_suppression_flags_ |= flag;
1249 bool Representation::HasRequiredMediaInfoFields() {
1250 if (HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)) {
1251 LOG(ERROR) <<
"MediaInfo cannot have both VOD and Live fields.";
1255 if (!media_info_.has_container_type()) {
1256 LOG(ERROR) <<
"MediaInfo missing required field: container_type.";
1260 if (HasVODOnlyFields(media_info_) && !media_info_.has_bandwidth()) {
1261 LOG(ERROR) <<
"Missing 'bandwidth' field. MediaInfo requires bandwidth for "
1262 "static profile for generating a valid MPD.";
1266 VLOG_IF(3, HasLiveOnlyFields(media_info_) && !media_info_.has_bandwidth())
1267 <<
"MediaInfo missing field 'bandwidth'. Using estimated from "
1273 bool Representation::IsContiguous(uint64_t start_time,
1275 uint64_t size)
const {
1276 if (segment_infos_.empty())
1280 const SegmentInfo& previous = segment_infos_.back();
1281 const uint64_t previous_segment_end_time =
1282 previous.start_time + previous.duration * (previous.repeat + 1);
1283 if (previous_segment_end_time == start_time &&
1284 segment_infos_.back().duration == duration) {
1289 const uint64_t previous_segment_start_time =
1290 previous.start_time + previous.duration * previous.repeat;
1291 if (previous_segment_start_time >= start_time) {
1292 LOG(ERROR) <<
"Segments should not be out of order segment. Adding segment "
1293 "with start_time == "
1294 << start_time <<
" but the previous segment starts at "
1295 << previous_segment_start_time <<
".";
1300 const uint64_t kRoundingErrorGrace = 5;
1301 if (previous_segment_end_time + kRoundingErrorGrace < start_time) {
1302 LOG(WARNING) <<
"Found a gap of size "
1303 << (start_time - previous_segment_end_time)
1304 <<
" > kRoundingErrorGrace (" << kRoundingErrorGrace
1305 <<
"). The new segment starts at " << start_time
1306 <<
" but the previous segment ends at "
1307 << previous_segment_end_time <<
".";
1312 if (start_time < previous_segment_end_time - kRoundingErrorGrace) {
1314 <<
"Segments should not be overlapping. The new segment starts at "
1315 << start_time <<
" but the previous segment ends at "
1316 << previous_segment_end_time <<
".";
1324 void Representation::SlideWindow() {
1325 DCHECK(!segment_infos_.empty());
1326 if (mpd_options_.time_shift_buffer_depth <= 0.0 ||
1327 mpd_options_.mpd_type == MpdType::kStatic)
1330 const uint32_t time_scale = GetTimeScale(media_info_);
1331 DCHECK_GT(time_scale, 0u);
1333 uint64_t time_shift_buffer_depth =
1334 static_cast<uint64_t
>(mpd_options_.time_shift_buffer_depth * time_scale);
1338 const uint64_t current_play_time = LatestSegmentStartTime(segment_infos_);
1339 if (current_play_time <= time_shift_buffer_depth)
1342 const uint64_t timeshift_limit = current_play_time - time_shift_buffer_depth;
1346 std::list<SegmentInfo>::iterator first = segment_infos_.begin();
1347 std::list<SegmentInfo>::iterator last = first;
1348 size_t num_segments_removed = 0;
1349 for (; last != segment_infos_.end(); ++last) {
1350 const uint64_t last_segment_end_time = LastSegmentEndTime(*last);
1351 if (timeshift_limit < last_segment_end_time)
1353 num_segments_removed += last->repeat + 1;
1355 segment_infos_.erase(first, last);
1356 start_number_ += num_segments_removed;
1359 SegmentInfo* first_segment_info = &segment_infos_.front();
1360 DCHECK_LE(timeshift_limit, LastSegmentEndTime(*first_segment_info));
1363 const int repeat_index =
1364 SearchTimedOutRepeatIndex(timeshift_limit, *first_segment_info);
1365 CHECK_GE(repeat_index, 0);
1366 if (repeat_index == 0)
1369 first_segment_info->start_time = first_segment_info->start_time +
1370 first_segment_info->duration * repeat_index;
1372 first_segment_info->repeat = first_segment_info->repeat - repeat_index;
1373 start_number_ += repeat_index;
1376 std::string Representation::GetVideoMimeType()
const {
1377 return GetMimeType(
"video", media_info_.container_type());
1380 std::string Representation::GetAudioMimeType()
const {
1381 return GetMimeType(
"audio", media_info_.container_type());
1384 std::string Representation::GetTextMimeType()
const {
1385 CHECK(media_info_.has_text_info());
1386 if (media_info_.text_info().format() ==
"ttml") {
1387 switch (media_info_.container_type()) {
1388 case MediaInfo::CONTAINER_TEXT:
1389 return "application/ttml+xml";
1390 case MediaInfo::CONTAINER_MP4:
1391 return "application/mp4";
1393 LOG(ERROR) <<
"Failed to determine MIME type for TTML container: "
1394 << media_info_.container_type();
1398 if (media_info_.text_info().format() ==
"vtt") {
1399 if (media_info_.container_type() == MediaInfo::CONTAINER_TEXT) {
1401 }
else if (media_info_.container_type() == MediaInfo::CONTAINER_MP4) {
1402 return "application/mp4";
1404 LOG(ERROR) <<
"Failed to determine MIME type for VTT container: "
1405 << media_info_.container_type();
1409 LOG(ERROR) <<
"Cannot determine MIME type for format: "
1410 << media_info_.text_info().format()
1411 <<
" container: " << media_info_.container_type();
1415 bool Representation::GetEarliestTimestamp(
double* timestamp_seconds) {
1416 DCHECK(timestamp_seconds);
1418 if (segment_infos_.empty())
1421 *timestamp_seconds =
static_cast<double>(segment_infos_.begin()->start_time) /
1422 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)
bool WriteMpdToFile(media::File *output_file)
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)
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)
void SuppressOnce(SuppressFlag flag)