7 #include "packager/mpd/base/mpd_builder.h"
9 #include <libxml/tree.h>
10 #include <libxml/xmlstring.h>
17 #include "packager/base/base64.h"
18 #include "packager/base/bind.h"
19 #include "packager/base/files/file_path.h"
20 #include "packager/base/logging.h"
21 #include "packager/base/memory/scoped_ptr.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/file/file.h"
28 #include "packager/mpd/base/content_protection_element.h"
29 #include "packager/mpd/base/language_utils.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 const int kAdaptationSetGroupNotSet = -1;
45 AdaptationSet::Role MediaInfoTextTypeToRole(
46 MediaInfo::TextInfo::TextType type) {
48 case MediaInfo::TextInfo::UNKNOWN:
49 LOG(WARNING) <<
"Unknown text type, assuming subtitle.";
50 return AdaptationSet::kRoleSubtitle;
51 case MediaInfo::TextInfo::CAPTION:
52 return AdaptationSet::kRoleCaption;
53 case MediaInfo::TextInfo::SUBTITLE:
54 return AdaptationSet::kRoleSubtitle;
56 NOTREACHED() <<
"Unknown MediaInfo TextType: " << type
57 <<
" assuming subtitle.";
58 return AdaptationSet::kRoleSubtitle;
62 std::string GetMimeType(
const std::string& prefix,
63 MediaInfo::ContainerType container_type) {
64 switch (container_type) {
65 case MediaInfo::CONTAINER_MP4:
66 return prefix +
"/mp4";
67 case MediaInfo::CONTAINER_MPEG2_TS:
69 return prefix +
"/MP2T";
70 case MediaInfo::CONTAINER_WEBM:
71 return prefix +
"/webm";
77 LOG(ERROR) <<
"Unrecognized container type: " << container_type;
81 void AddMpdNameSpaceInfo(XmlNode* mpd) {
84 static const char kXmlNamespace[] =
"urn:mpeg:dash:schema:mpd:2011";
85 static const char kXmlNamespaceXsi[] =
86 "http://www.w3.org/2001/XMLSchema-instance";
87 static const char kXmlNamespaceXlink[] =
"http://www.w3.org/1999/xlink";
88 static const char kDashSchemaMpd2011[] =
89 "urn:mpeg:dash:schema:mpd:2011 DASH-MPD.xsd";
90 static const char kCencNamespace[] =
"urn:mpeg:cenc:2013";
92 mpd->SetStringAttribute(
"xmlns", kXmlNamespace);
93 mpd->SetStringAttribute(
"xmlns:xsi", kXmlNamespaceXsi);
94 mpd->SetStringAttribute(
"xmlns:xlink", kXmlNamespaceXlink);
95 mpd->SetStringAttribute(
"xsi:schemaLocation", kDashSchemaMpd2011);
96 mpd->SetStringAttribute(
"xmlns:cenc", kCencNamespace);
99 bool IsPeriodNode(xmlNodePtr node) {
102 return xmlStrcmp(node->name, reinterpret_cast<const xmlChar*>(
"Period")) ==
111 xmlNodePtr FindPeriodNode(XmlNode* xml_node) {
112 for (xmlNodePtr node = xml_node->GetRawPtr()->xmlChildrenNode; node != NULL;
114 if (IsPeriodNode(node))
121 bool Positive(
double d) {
127 std::string XmlDateTimeNowWithOffset(
128 int32_t offset_seconds,
129 base::Clock* clock) {
130 base::Time time = clock->Now();
131 time += base::TimeDelta::FromSeconds(offset_seconds);
132 base::Time::Exploded time_exploded;
133 time.UTCExplode(&time_exploded);
135 return base::StringPrintf(
"%4d-%02d-%02dT%02d:%02d:%02dZ", time_exploded.year,
136 time_exploded.month, time_exploded.day_of_month,
137 time_exploded.hour, time_exploded.minute,
138 time_exploded.second);
141 void SetIfPositive(
const char* attr_name,
double value, XmlNode* mpd) {
142 if (Positive(value)) {
143 mpd->SetStringAttribute(attr_name, SecondsToXmlDuration(value));
147 uint32_t GetTimeScale(
const MediaInfo& media_info) {
148 if (media_info.has_reference_time_scale()) {
149 return media_info.reference_time_scale();
152 if (media_info.has_video_info()) {
153 return media_info.video_info().time_scale();
156 if (media_info.has_audio_info()) {
157 return media_info.audio_info().time_scale();
160 LOG(WARNING) <<
"No timescale specified, using 1 as timescale.";
164 uint64_t LastSegmentStartTime(
const SegmentInfo& segment_info) {
165 return segment_info.start_time + segment_info.duration * segment_info.repeat;
169 uint64_t LastSegmentEndTime(
const SegmentInfo& segment_info) {
170 return segment_info.start_time +
171 segment_info.duration * (segment_info.repeat + 1);
174 uint64_t LatestSegmentStartTime(
const std::list<SegmentInfo>& segments) {
175 DCHECK(!segments.empty());
176 const SegmentInfo& latest_segment = segments.back();
177 return LastSegmentStartTime(latest_segment);
182 int SearchTimedOutRepeatIndex(uint64_t timeshift_limit,
183 const SegmentInfo& segment_info) {
184 DCHECK_LE(timeshift_limit, LastSegmentEndTime(segment_info));
185 if (timeshift_limit < segment_info.start_time)
188 return (timeshift_limit - segment_info.start_time) / segment_info.duration;
194 bool WriteXmlCharArrayToOutput(xmlChar* doc,
196 std::string* output) {
199 output->assign(doc, doc + doc_size);
203 bool WriteXmlCharArrayToOutput(xmlChar* doc,
205 media::File* output) {
208 if (output->Write(doc, doc_size) < doc_size)
211 return output->Flush();
214 std::string MakePathRelative(
const std::string& path,
215 const std::string& mpd_dir) {
216 return (path.find(mpd_dir) == 0) ? path.substr(mpd_dir.size()) : path;
222 bool HasRequiredVideoFields(
const MediaInfo_VideoInfo& video_info) {
223 if (!video_info.has_height() || !video_info.has_width()) {
225 <<
"Width and height are required fields for generating a valid MPD.";
230 LOG_IF(WARNING, !video_info.has_time_scale())
231 <<
"Video info does not contain timescale required for "
232 "calculating framerate. @frameRate is required for DASH IOP.";
233 LOG_IF(WARNING, !video_info.has_frame_duration())
234 <<
"Video info does not contain frame duration required "
235 "for calculating framerate. @frameRate is required for DASH IOP.";
236 LOG_IF(WARNING, !video_info.has_pixel_width())
237 <<
"Video info does not contain pixel_width to calculate the sample "
238 "aspect ratio required for DASH IOP.";
239 LOG_IF(WARNING, !video_info.has_pixel_height())
240 <<
"Video info does not contain pixel_height to calculate the sample "
241 "aspect ratio required for DASH IOP.";
252 std::string GetPictureAspectRatio(uint32_t width,
254 uint32_t pixel_width,
255 uint32_t pixel_height) {
256 const uint32_t scaled_width = pixel_width * width;
257 const uint32_t scaled_height = pixel_height * height;
258 const double par =
static_cast<double>(scaled_width) / scaled_height;
262 const uint32_t kLargestPossibleParY = 19;
264 uint32_t par_num = 0;
265 uint32_t par_den = 0;
266 double min_error = 1.0;
267 for (uint32_t den = 1; den <= kLargestPossibleParY; ++den) {
268 uint32_t num = par * den + 0.5;
269 double error = fabs(par - static_cast<double>(num) / den);
270 if (error < min_error) {
274 if (error == 0)
break;
277 VLOG(2) <<
"width*pix_width : height*pixel_height (" << scaled_width <<
":"
278 << scaled_height <<
") reduced to " << par_num <<
":" << par_den
279 <<
" with error " << min_error <<
".";
281 return base::IntToString(par_num) +
":" + base::IntToString(par_den);
286 void AddPictureAspectRatio(
287 const MediaInfo::VideoInfo& video_info,
288 std::set<std::string>* picture_aspect_ratio) {
291 if (picture_aspect_ratio->size() > 1)
294 if (video_info.width() == 0 || video_info.height() == 0 ||
295 video_info.pixel_width() == 0 || video_info.pixel_height() == 0) {
300 picture_aspect_ratio->insert(
"bogus");
301 picture_aspect_ratio->insert(
"entries");
305 const std::string par = GetPictureAspectRatio(
306 video_info.width(), video_info.height(),
307 video_info.pixel_width(), video_info.pixel_height());
308 DVLOG(1) <<
"Setting par as: " << par
309 <<
" for video with width: " << video_info.width()
310 <<
" height: " << video_info.height()
311 <<
" pixel_width: " << video_info.pixel_width() <<
" pixel_height; "
312 << video_info.pixel_height();
313 picture_aspect_ratio->insert(par);
316 std::string RoleToText(AdaptationSet::Role role) {
320 case AdaptationSet::kRoleCaption:
322 case AdaptationSet::kRoleSubtitle:
324 case AdaptationSet::kRoleMain:
326 case AdaptationSet::kRoleAlternate:
328 case AdaptationSet::kRoleSupplementary:
329 return "supplementary";
330 case AdaptationSet::kRoleCommentary:
332 case AdaptationSet::kRoleDub:
344 class LibXmlInitializer {
346 LibXmlInitializer() : initialized_(false) {
347 base::AutoLock lock(lock_);
354 ~LibXmlInitializer() {
355 base::AutoLock lock(lock_);
358 initialized_ =
false;
366 DISALLOW_COPY_AND_ASSIGN(LibXmlInitializer);
369 class RepresentationStateChangeListenerImpl
370 :
public RepresentationStateChangeListener {
373 RepresentationStateChangeListenerImpl(uint32_t representation_id,
374 AdaptationSet* adaptation_set)
375 : representation_id_(representation_id), adaptation_set_(adaptation_set) {
376 DCHECK(adaptation_set_);
378 ~RepresentationStateChangeListenerImpl()
override {}
381 void OnNewSegmentForRepresentation(uint64_t start_time,
382 uint64_t duration)
override {
383 adaptation_set_->OnNewSegmentForRepresentation(representation_id_,
384 start_time, duration);
387 void OnSetFrameRateForRepresentation(uint32_t frame_duration,
388 uint32_t timescale)
override {
389 adaptation_set_->OnSetFrameRateForRepresentation(representation_id_,
390 frame_duration, timescale);
394 const uint32_t representation_id_;
395 AdaptationSet*
const adaptation_set_;
397 DISALLOW_COPY_AND_ASSIGN(RepresentationStateChangeListenerImpl);
404 mpd_options_(mpd_options),
405 adaptation_sets_deleter_(&adaptation_sets_),
406 clock_(new base::DefaultClock()) {}
408 MpdBuilder::~MpdBuilder() {}
411 base_urls_.push_back(base_url);
415 scoped_ptr<AdaptationSet> adaptation_set(
416 new AdaptationSet(adaptation_set_counter_.GetNext(), lang, mpd_options_,
417 type_, &representation_counter_));
419 DCHECK(adaptation_set);
420 adaptation_sets_.push_back(adaptation_set.get());
421 return adaptation_set.release();
426 return WriteMpdToOutput(output_file);
431 return WriteMpdToOutput(output);
433 template <
typename OutputType>
434 bool MpdBuilder::WriteMpdToOutput(OutputType* output) {
435 static LibXmlInitializer lib_xml_initializer;
437 xml::scoped_xml_ptr<xmlDoc> doc(GenerateMpd());
441 static const int kNiceFormat = 1;
442 int doc_str_size = 0;
443 xmlChar* doc_str = NULL;
444 xmlDocDumpFormatMemoryEnc(doc.get(), &doc_str, &doc_str_size,
"UTF-8",
447 bool result = WriteXmlCharArrayToOutput(doc_str, doc_str_size, output);
455 xmlDocPtr MpdBuilder::GenerateMpd() {
457 static const char kXmlVersion[] =
"1.0";
458 xml::scoped_xml_ptr<xmlDoc> doc(xmlNewDoc(BAD_CAST kXmlVersion));
462 XmlNode period(
"Period");
468 std::list<AdaptationSet*>::iterator adaptation_sets_it =
469 adaptation_sets_.begin();
470 for (; adaptation_sets_it != adaptation_sets_.end(); ++adaptation_sets_it) {
471 xml::scoped_xml_ptr<xmlNode> child((*adaptation_sets_it)->GetXml());
472 if (!child.get() || !period.AddChild(child.Pass()))
477 std::list<std::string>::const_iterator base_urls_it = base_urls_.begin();
478 for (; base_urls_it != base_urls_.end(); ++base_urls_it) {
479 XmlNode base_url(
"BaseURL");
480 base_url.SetContent(*base_urls_it);
482 if (!mpd.AddChild(base_url.PassScopedPtr()))
486 if (type_ == kDynamic) {
488 period.SetStringAttribute(
"start",
"PT0S");
491 if (!mpd.AddChild(period.PassScopedPtr()))
494 AddMpdNameSpaceInfo(&mpd);
495 AddCommonMpdInfo(&mpd);
498 AddStaticMpdInfo(&mpd);
501 AddDynamicMpdInfo(&mpd);
504 NOTREACHED() <<
"Unknown MPD type: " << type_;
509 const std::string version = GetPackagerVersion();
510 if (!version.empty()) {
511 std::string version_string =
512 base::StringPrintf(
"Generated with %s version %s",
513 GetPackagerProjectUrl().c_str(), version.c_str());
514 xml::scoped_xml_ptr<xmlNode> comment(
515 xmlNewDocComment(doc.get(), BAD_CAST version_string.c_str()));
516 xmlDocSetRootElement(doc.get(), comment.get());
517 xmlAddSibling(comment.release(), mpd.Release());
519 xmlDocSetRootElement(doc.get(), mpd.Release());
521 return doc.release();
524 void MpdBuilder::AddCommonMpdInfo(XmlNode* mpd_node) {
525 if (Positive(mpd_options_.min_buffer_time)) {
526 mpd_node->SetStringAttribute(
527 "minBufferTime", SecondsToXmlDuration(mpd_options_.min_buffer_time));
529 LOG(ERROR) <<
"minBufferTime value not specified.";
534 void MpdBuilder::AddStaticMpdInfo(XmlNode* mpd_node) {
536 DCHECK_EQ(MpdBuilder::kStatic, type_);
538 static const char kStaticMpdType[] =
"static";
539 static const char kStaticMpdProfile[] =
540 "urn:mpeg:dash:profile:isoff-on-demand:2011";
541 mpd_node->SetStringAttribute(
"type", kStaticMpdType);
542 mpd_node->SetStringAttribute(
"profiles", kStaticMpdProfile);
543 mpd_node->SetStringAttribute(
544 "mediaPresentationDuration",
545 SecondsToXmlDuration(GetStaticMpdDuration(mpd_node)));
548 void MpdBuilder::AddDynamicMpdInfo(XmlNode* mpd_node) {
550 DCHECK_EQ(MpdBuilder::kDynamic, type_);
552 static const char kDynamicMpdType[] =
"dynamic";
553 static const char kDynamicMpdProfile[] =
554 "urn:mpeg:dash:profile:isoff-live:2011";
555 mpd_node->SetStringAttribute(
"type", kDynamicMpdType);
556 mpd_node->SetStringAttribute(
"profiles", kDynamicMpdProfile);
559 mpd_node->SetStringAttribute(
"publishTime",
560 XmlDateTimeNowWithOffset(0, clock_.get()));
564 if (availability_start_time_.empty()) {
565 double earliest_presentation_time;
566 if (GetEarliestTimestamp(&earliest_presentation_time)) {
567 availability_start_time_ =
568 XmlDateTimeNowWithOffset(mpd_options_.availability_time_offset -
569 std::ceil(earliest_presentation_time),
572 LOG(ERROR) <<
"Could not determine the earliest segment presentation "
573 "time for availabilityStartTime calculation.";
577 if (!availability_start_time_.empty())
578 mpd_node->SetStringAttribute(
"availabilityStartTime",
579 availability_start_time_);
581 if (Positive(mpd_options_.minimum_update_period)) {
582 mpd_node->SetStringAttribute(
583 "minimumUpdatePeriod",
584 SecondsToXmlDuration(mpd_options_.minimum_update_period));
586 LOG(WARNING) <<
"The profile is dynamic but no minimumUpdatePeriod "
590 SetIfPositive(
"timeShiftBufferDepth", mpd_options_.time_shift_buffer_depth,
592 SetIfPositive(
"suggestedPresentationDelay",
593 mpd_options_.suggested_presentation_delay, mpd_node);
596 float MpdBuilder::GetStaticMpdDuration(XmlNode* mpd_node) {
598 DCHECK_EQ(MpdBuilder::kStatic, type_);
600 xmlNodePtr period_node = FindPeriodNode(mpd_node);
601 DCHECK(period_node) <<
"Period element must be a child of mpd_node.";
602 DCHECK(IsPeriodNode(period_node));
607 float max_duration = 0.0f;
608 for (xmlNodePtr adaptation_set = xmlFirstElementChild(period_node);
609 adaptation_set; adaptation_set = xmlNextElementSibling(adaptation_set)) {
610 for (xmlNodePtr representation = xmlFirstElementChild(adaptation_set);
612 representation = xmlNextElementSibling(representation)) {
613 float duration = 0.0f;
614 if (GetDurationAttribute(representation, &duration)) {
615 max_duration = max_duration > duration ? max_duration : duration;
619 xmlUnsetProp(representation, BAD_CAST
"duration");
627 bool MpdBuilder::GetEarliestTimestamp(
double* timestamp_seconds) {
628 DCHECK(timestamp_seconds);
630 double earliest_timestamp(-1);
631 for (std::list<AdaptationSet*>::const_iterator iter =
632 adaptation_sets_.begin();
633 iter != adaptation_sets_.end(); ++iter) {
635 if ((*iter)->GetEarliestTimestamp(×tamp) &&
636 ((earliest_timestamp < 0) || (timestamp < earliest_timestamp))) {
637 earliest_timestamp = timestamp;
640 if (earliest_timestamp < 0)
643 *timestamp_seconds = earliest_timestamp;
648 MediaInfo* media_info) {
650 const std::string kFileProtocol(
"file://");
651 std::string mpd_file_path = (mpd_path.find(kFileProtocol) == 0)
652 ? mpd_path.substr(kFileProtocol.size())
655 if (!mpd_file_path.empty()) {
657 FilePath(mpd_file_path).DirName().AsEndingWithSeparator().value());
658 if (!mpd_dir.empty()) {
659 if (media_info->has_media_file_name()) {
660 media_info->set_media_file_name(
661 MakePathRelative(media_info->media_file_name(), mpd_dir));
663 if (media_info->has_init_segment_name()) {
664 media_info->set_init_segment_name(
665 MakePathRelative(media_info->init_segment_name(), mpd_dir));
667 if (media_info->has_segment_template()) {
668 media_info->set_segment_template(
669 MakePathRelative(media_info->segment_template(), mpd_dir));
676 const std::string& lang,
678 MpdBuilder::MpdType mpd_type,
679 base::AtomicSequenceNumber* counter)
680 : representations_deleter_(&representations_),
681 representation_counter_(counter),
682 id_(adaptation_set_id),
684 mpd_options_(mpd_options),
686 group_(kAdaptationSetGroupNotSet),
687 segments_aligned_(kSegmentAlignmentUnknown),
688 force_set_segment_alignment_(false) {
692 AdaptationSet::~AdaptationSet() {}
695 const uint32_t representation_id = representation_counter_->GetNext();
698 scoped_ptr<RepresentationStateChangeListener> listener(
699 new RepresentationStateChangeListenerImpl(representation_id,
this));
701 media_info, mpd_options_, representation_id, listener.Pass()));
703 if (!representation->Init())
708 if (media_info.has_video_info()) {
709 const MediaInfo::VideoInfo& video_info = media_info.video_info();
710 DCHECK(video_info.has_width());
711 DCHECK(video_info.has_height());
712 video_widths_.insert(video_info.width());
713 video_heights_.insert(video_info.height());
715 if (video_info.has_time_scale() && video_info.has_frame_duration())
716 RecordFrameRate(video_info.frame_duration(), video_info.time_scale());
718 AddPictureAspectRatio(video_info, &picture_aspect_ratio_);
721 if (media_info.has_video_info()) {
722 content_type_ =
"video";
723 }
else if (media_info.has_audio_info()) {
724 content_type_ =
"audio";
725 }
else if (media_info.has_text_info()) {
726 content_type_ =
"text";
728 if (media_info.text_info().has_type() &&
729 (media_info.text_info().type() != MediaInfo::TextInfo::UNKNOWN)) {
730 roles_.insert(MediaInfoTextTypeToRole(media_info.text_info().type()));
734 representations_.push_back(representation.get());
735 return representation.release();
740 content_protection_elements_.push_back(content_protection_element);
741 RemoveDuplicateAttributes(&content_protection_elements_.back());
745 const std::string& pssh) {
746 UpdateContentProtectionPsshHelper(drm_uuid, pssh,
747 &content_protection_elements_);
761 AdaptationSetXmlNode adaptation_set;
763 bool suppress_representation_width =
false;
764 bool suppress_representation_height =
false;
765 bool suppress_representation_frame_rate =
false;
767 adaptation_set.SetId(id_);
768 adaptation_set.SetStringAttribute(
"contentType", content_type_);
769 if (!lang_.empty() && lang_ !=
"und") {
774 if (video_widths_.size() == 1) {
775 suppress_representation_width =
true;
776 adaptation_set.SetIntegerAttribute(
"width", *video_widths_.begin());
777 }
else if (video_widths_.size() > 1) {
778 adaptation_set.SetIntegerAttribute(
"maxWidth", *video_widths_.rbegin());
780 if (video_heights_.size() == 1) {
781 suppress_representation_height =
true;
782 adaptation_set.SetIntegerAttribute(
"height", *video_heights_.begin());
783 }
else if (video_heights_.size() > 1) {
784 adaptation_set.SetIntegerAttribute(
"maxHeight", *video_heights_.rbegin());
787 if (video_frame_rates_.size() == 1) {
788 suppress_representation_frame_rate =
true;
789 adaptation_set.SetStringAttribute(
"frameRate",
790 video_frame_rates_.begin()->second);
791 }
else if (video_frame_rates_.size() > 1) {
792 adaptation_set.SetStringAttribute(
"maxFrameRate",
793 video_frame_rates_.rbegin()->second);
798 if (mpd_type_ == MpdBuilder::kStatic) {
799 CheckVodSegmentAlignment();
802 if (segments_aligned_ == kSegmentAlignmentTrue) {
803 adaptation_set.SetStringAttribute(mpd_type_ == MpdBuilder::kStatic
804 ?
"subsegmentAlignment"
805 :
"segmentAlignment",
809 if (picture_aspect_ratio_.size() == 1)
810 adaptation_set.SetStringAttribute(
"par", *picture_aspect_ratio_.begin());
813 adaptation_set.SetIntegerAttribute(
"group", group_);
815 if (!adaptation_set.AddContentProtectionElements(
816 content_protection_elements_)) {
817 return xml::scoped_xml_ptr<xmlNode>();
819 for (AdaptationSet::Role role : roles_)
820 adaptation_set.AddRoleElement(
"urn:mpeg:dash:role:2011", RoleToText(role));
823 if (suppress_representation_width)
824 representation->SuppressOnce(Representation::kSuppressWidth);
825 if (suppress_representation_height)
826 representation->SuppressOnce(Representation::kSuppressHeight);
827 if (suppress_representation_frame_rate)
828 representation->SuppressOnce(Representation::kSuppressFrameRate);
829 xml::scoped_xml_ptr<xmlNode> child(representation->GetXml());
830 if (!child || !adaptation_set.AddChild(child.Pass()))
831 return xml::scoped_xml_ptr<xmlNode>();
834 return adaptation_set.PassScopedPtr();
839 segment_alignment ? kSegmentAlignmentTrue : kSegmentAlignmentFalse;
840 force_set_segment_alignment_ =
true;
844 group_ = group_number;
861 if (mpd_type_ == MpdBuilder::kDynamic) {
862 CheckLiveSegmentAlignment(representation_id, start_time, duration);
864 representation_segment_start_times_[representation_id].push_back(
870 uint32_t representation_id,
871 uint32_t frame_duration,
872 uint32_t timescale) {
873 RecordFrameRate(frame_duration, timescale);
876 bool AdaptationSet::GetEarliestTimestamp(
double* timestamp_seconds) {
877 DCHECK(timestamp_seconds);
879 double earliest_timestamp(-1);
880 for (std::list<Representation*>::const_iterator iter =
881 representations_.begin();
882 iter != representations_.end(); ++iter) {
884 if ((*iter)->GetEarliestTimestamp(×tamp) &&
885 ((earliest_timestamp < 0) || (timestamp < earliest_timestamp))) {
886 earliest_timestamp = timestamp;
889 if (earliest_timestamp < 0)
892 *timestamp_seconds = earliest_timestamp;
920 void AdaptationSet::CheckLiveSegmentAlignment(uint32_t representation_id,
923 if (segments_aligned_ == kSegmentAlignmentFalse ||
924 force_set_segment_alignment_) {
928 std::list<uint64_t>& representation_start_times =
929 representation_segment_start_times_[representation_id];
930 representation_start_times.push_back(start_time);
933 if (representation_segment_start_times_.size() != representations_.size())
936 DCHECK(!representation_start_times.empty());
937 const uint64_t expected_start_time = representation_start_times.front();
938 for (RepresentationTimeline::const_iterator it =
939 representation_segment_start_times_.begin();
940 it != representation_segment_start_times_.end(); ++it) {
944 if (it->second.empty())
947 if (expected_start_time != it->second.front()) {
950 segments_aligned_ = kSegmentAlignmentFalse;
951 representation_segment_start_times_.clear();
955 segments_aligned_ = kSegmentAlignmentTrue;
957 for (RepresentationTimeline::iterator it =
958 representation_segment_start_times_.begin();
959 it != representation_segment_start_times_.end(); ++it) {
960 it->second.pop_front();
966 void AdaptationSet::CheckVodSegmentAlignment() {
967 if (segments_aligned_ == kSegmentAlignmentFalse ||
968 force_set_segment_alignment_) {
971 if (representation_segment_start_times_.empty())
973 if (representation_segment_start_times_.size() == 1) {
974 segments_aligned_ = kSegmentAlignmentTrue;
981 const std::list<uint64_t>& expected_time_line =
982 representation_segment_start_times_.begin()->second;
984 bool all_segment_time_line_same_length =
true;
986 RepresentationTimeline::const_iterator it =
987 representation_segment_start_times_.begin();
988 for (++it; it != representation_segment_start_times_.end(); ++it) {
989 const std::list<uint64_t>& other_time_line = it->second;
990 if (expected_time_line.size() != other_time_line.size()) {
991 all_segment_time_line_same_length =
false;
994 const std::list<uint64_t>* longer_list = &other_time_line;
995 const std::list<uint64_t>* shorter_list = &expected_time_line;
996 if (expected_time_line.size() > other_time_line.size()) {
997 shorter_list = &other_time_line;
998 longer_list = &expected_time_line;
1001 if (!std::equal(shorter_list->begin(), shorter_list->end(),
1002 longer_list->begin())) {
1004 segments_aligned_ = kSegmentAlignmentFalse;
1005 representation_segment_start_times_.clear();
1016 if (!all_segment_time_line_same_length) {
1017 segments_aligned_ = kSegmentAlignmentUnknown;
1021 segments_aligned_ = kSegmentAlignmentTrue;
1026 void AdaptationSet::RecordFrameRate(uint32_t frame_duration,
1027 uint32_t timescale) {
1028 if (frame_duration == 0) {
1029 LOG(ERROR) <<
"Frame duration is 0 and cannot be set.";
1032 video_frame_rates_[
static_cast<double>(timescale) / frame_duration] =
1033 base::IntToString(timescale) +
"/" + base::IntToString(frame_duration);
1037 const MediaInfo& media_info,
1040 scoped_ptr<RepresentationStateChangeListener> state_change_listener)
1041 : media_info_(media_info),
1044 mpd_options_(mpd_options),
1046 state_change_listener_(state_change_listener.Pass()),
1047 output_suppression_flags_(0) {}
1049 Representation::~Representation() {}
1052 if (!AtLeastOneTrue(media_info_.has_video_info(),
1053 media_info_.has_audio_info(),
1054 media_info_.has_text_info())) {
1058 LOG(ERROR) <<
"Representation needs one of video, audio, or text.";
1062 if (MoreThanOneTrue(media_info_.has_video_info(),
1063 media_info_.has_audio_info(),
1064 media_info_.has_text_info())) {
1065 LOG(ERROR) <<
"Only one of VideoInfo, AudioInfo, or TextInfo can be set.";
1069 if (media_info_.container_type() == MediaInfo::CONTAINER_UNKNOWN) {
1070 LOG(ERROR) <<
"'container_type' in MediaInfo cannot be CONTAINER_UNKNOWN.";
1074 if (media_info_.has_video_info()) {
1075 mime_type_ = GetVideoMimeType();
1076 if (!HasRequiredVideoFields(media_info_.video_info())) {
1077 LOG(ERROR) <<
"Missing required fields to create a video Representation.";
1080 }
else if (media_info_.has_audio_info()) {
1081 mime_type_ = GetAudioMimeType();
1082 }
else if (media_info_.has_text_info()) {
1083 mime_type_ = GetTextMimeType();
1086 if (mime_type_.empty())
1089 codecs_ = GetCodecs(media_info_);
1095 content_protection_elements_.push_back(content_protection_element);
1096 RemoveDuplicateAttributes(&content_protection_elements_.back());
1100 const std::string& pssh) {
1101 UpdateContentProtectionPsshHelper(drm_uuid, pssh,
1102 &content_protection_elements_);
1108 if (start_time == 0 && duration == 0) {
1109 LOG(WARNING) <<
"Got segment with start_time and duration == 0. Ignoring.";
1113 if (state_change_listener_)
1114 state_change_listener_->OnNewSegmentForRepresentation(start_time, duration);
1115 if (IsContiguous(start_time, duration, size)) {
1116 ++segment_infos_.back().repeat;
1119 segment_infos_.push_back(s);
1122 bandwidth_estimator_.AddBlock(
1123 size, static_cast<double>(duration) / media_info_.reference_time_scale());
1126 DCHECK_GE(segment_infos_.size(), 1u);
1130 if (media_info_.has_video_info()) {
1131 media_info_.mutable_video_info()->set_frame_duration(sample_duration);
1132 if (state_change_listener_) {
1133 state_change_listener_->OnSetFrameRateForRepresentation(
1134 sample_duration, media_info_.video_info().time_scale());
1146 if (!HasRequiredMediaInfoFields()) {
1147 LOG(ERROR) <<
"MediaInfo missing required fields.";
1148 return xml::scoped_xml_ptr<xmlNode>();
1151 const uint64_t bandwidth = media_info_.has_bandwidth()
1152 ? media_info_.bandwidth()
1153 : bandwidth_estimator_.Estimate();
1155 DCHECK(!(HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)));
1157 RepresentationXmlNode representation;
1159 representation.SetId(id_);
1160 representation.SetIntegerAttribute(
"bandwidth", bandwidth);
1161 if (!codecs_.empty())
1162 representation.SetStringAttribute(
"codecs", codecs_);
1163 representation.SetStringAttribute(
"mimeType", mime_type_);
1165 const bool has_video_info = media_info_.has_video_info();
1166 const bool has_audio_info = media_info_.has_audio_info();
1168 if (has_video_info &&
1169 !representation.AddVideoInfo(
1170 media_info_.video_info(),
1171 !(output_suppression_flags_ & kSuppressWidth),
1172 !(output_suppression_flags_ & kSuppressHeight),
1173 !(output_suppression_flags_ & kSuppressFrameRate))) {
1174 LOG(ERROR) <<
"Failed to add video info to Representation XML.";
1175 return xml::scoped_xml_ptr<xmlNode>();
1178 if (has_audio_info &&
1179 !representation.AddAudioInfo(media_info_.audio_info())) {
1180 LOG(ERROR) <<
"Failed to add audio info to Representation XML.";
1181 return xml::scoped_xml_ptr<xmlNode>();
1184 if (!representation.AddContentProtectionElements(
1185 content_protection_elements_)) {
1186 return xml::scoped_xml_ptr<xmlNode>();
1189 if (HasVODOnlyFields(media_info_) &&
1190 !representation.AddVODOnlyInfo(media_info_)) {
1191 LOG(ERROR) <<
"Failed to add VOD segment info.";
1192 return xml::scoped_xml_ptr<xmlNode>();
1195 if (HasLiveOnlyFields(media_info_) &&
1196 !representation.AddLiveOnlyInfo(media_info_, segment_infos_,
1198 LOG(ERROR) <<
"Failed to add Live info.";
1199 return xml::scoped_xml_ptr<xmlNode>();
1204 output_suppression_flags_ = 0;
1205 return representation.PassScopedPtr();
1209 output_suppression_flags_ |= flag;
1212 bool Representation::HasRequiredMediaInfoFields() {
1213 if (HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)) {
1214 LOG(ERROR) <<
"MediaInfo cannot have both VOD and Live fields.";
1218 if (!media_info_.has_container_type()) {
1219 LOG(ERROR) <<
"MediaInfo missing required field: container_type.";
1223 if (HasVODOnlyFields(media_info_) && !media_info_.has_bandwidth()) {
1224 LOG(ERROR) <<
"Missing 'bandwidth' field. MediaInfo requires bandwidth for "
1225 "static profile for generating a valid MPD.";
1229 VLOG_IF(3, HasLiveOnlyFields(media_info_) && !media_info_.has_bandwidth())
1230 <<
"MediaInfo missing field 'bandwidth'. Using estimated from "
1236 bool Representation::IsContiguous(uint64_t start_time,
1238 uint64_t size)
const {
1239 if (segment_infos_.empty())
1243 const SegmentInfo& previous = segment_infos_.back();
1244 const uint64_t previous_segment_end_time =
1245 previous.start_time + previous.duration * (previous.repeat + 1);
1246 if (previous_segment_end_time == start_time &&
1247 segment_infos_.back().duration == duration) {
1252 const uint64_t previous_segment_start_time =
1253 previous.start_time + previous.duration * previous.repeat;
1254 if (previous_segment_start_time >= start_time) {
1255 LOG(ERROR) <<
"Segments should not be out of order segment. Adding segment "
1256 "with start_time == "
1257 << start_time <<
" but the previous segment starts at "
1258 << previous.start_time <<
".";
1263 const uint64_t kRoundingErrorGrace = 5;
1264 if (previous_segment_end_time + kRoundingErrorGrace < start_time) {
1265 LOG(WARNING) <<
"Found a gap of size "
1266 << (start_time - previous_segment_end_time)
1267 <<
" > kRoundingErrorGrace (" << kRoundingErrorGrace
1268 <<
"). The new segment starts at " << start_time
1269 <<
" but the previous segment ends at "
1270 << previous_segment_end_time <<
".";
1275 if (start_time < previous_segment_end_time - kRoundingErrorGrace) {
1277 <<
"Segments should not be overlapping. The new segment starts at "
1278 << start_time <<
" but the previous segment ends at "
1279 << previous_segment_end_time <<
".";
1287 void Representation::SlideWindow() {
1288 DCHECK(!segment_infos_.empty());
1289 if (mpd_options_.time_shift_buffer_depth <= 0.0)
1292 const uint32_t time_scale = GetTimeScale(media_info_);
1293 DCHECK_GT(time_scale, 0u);
1295 uint64_t time_shift_buffer_depth =
1296 static_cast<uint64_t
>(mpd_options_.time_shift_buffer_depth * time_scale);
1300 const uint64_t current_play_time = LatestSegmentStartTime(segment_infos_);
1301 if (current_play_time <= time_shift_buffer_depth)
1304 const uint64_t timeshift_limit = current_play_time - time_shift_buffer_depth;
1308 std::list<SegmentInfo>::iterator first = segment_infos_.begin();
1309 std::list<SegmentInfo>::iterator last = first;
1310 size_t num_segments_removed = 0;
1311 for (; last != segment_infos_.end(); ++last) {
1312 const uint64_t last_segment_end_time = LastSegmentEndTime(*last);
1313 if (timeshift_limit < last_segment_end_time)
1315 num_segments_removed += last->repeat + 1;
1317 segment_infos_.erase(first, last);
1318 start_number_ += num_segments_removed;
1321 SegmentInfo* first_segment_info = &segment_infos_.front();
1322 DCHECK_LE(timeshift_limit, LastSegmentEndTime(*first_segment_info));
1325 const int repeat_index =
1326 SearchTimedOutRepeatIndex(timeshift_limit, *first_segment_info);
1327 CHECK_GE(repeat_index, 0);
1328 if (repeat_index == 0)
1331 first_segment_info->start_time = first_segment_info->start_time +
1332 first_segment_info->duration * repeat_index;
1334 first_segment_info->repeat = first_segment_info->repeat - repeat_index;
1335 start_number_ += repeat_index;
1338 std::string Representation::GetVideoMimeType()
const {
1339 return GetMimeType(
"video", media_info_.container_type());
1342 std::string Representation::GetAudioMimeType()
const {
1343 return GetMimeType(
"audio", media_info_.container_type());
1346 std::string Representation::GetTextMimeType()
const {
1347 CHECK(media_info_.has_text_info());
1348 if (media_info_.text_info().format() ==
"ttml") {
1349 switch (media_info_.container_type()) {
1350 case MediaInfo::CONTAINER_TEXT:
1351 return "application/ttml+xml";
1352 case MediaInfo::CONTAINER_MP4:
1353 return "application/mp4";
1355 LOG(ERROR) <<
"Failed to determine MIME type for TTML container: "
1356 << media_info_.container_type();
1360 if (media_info_.text_info().format() ==
"vtt") {
1361 if (media_info_.container_type() == MediaInfo::CONTAINER_TEXT) {
1364 LOG(ERROR) <<
"Failed to determine MIME type for VTT container: "
1365 << media_info_.container_type();
1369 LOG(ERROR) <<
"Cannot determine MIME type for format: "
1370 << media_info_.text_info().format()
1371 <<
" container: " << media_info_.container_type();
1375 bool Representation::GetEarliestTimestamp(
double* timestamp_seconds) {
1376 DCHECK(timestamp_seconds);
1378 if (segment_infos_.empty())
1381 *timestamp_seconds =
static_cast<double>(segment_infos_.begin()->start_time) /
1382 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)
AdaptationSet(uint32_t adaptation_set_id, const std::string &lang, const MpdOptions &mpd_options, MpdBuilder::MpdType mpd_type, base::AtomicSequenceNumber *representation_counter)
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)
Representation(const MediaInfo &media_info, const MpdOptions &mpd_options, uint32_t representation_id, scoped_ptr< RepresentationStateChangeListener > state_change_listener)
virtual void AddRole(Role role)
void AddBaseUrl(const std::string &base_url)
virtual void UpdateContentProtectionPssh(const std::string &drm_uuid, const std::string &pssh)
virtual void SetGroup(int group_number)
xml::scoped_xml_ptr< xmlNode > GetXml()
virtual bool ToString(std::string *output)
virtual void ForceSetSegmentAlignment(bool segment_alignment)
static void MakePathsRelativeToMpd(const std::string &mpd_path, MediaInfo *media_info)
MpdBuilder(MpdType type, const MpdOptions &mpd_options)
xml::scoped_xml_ptr< xmlNode > GetXml()
virtual void AddContentProtectionElement(const ContentProtectionElement &element)
virtual AdaptationSet * AddAdaptationSet(const std::string &lang)
virtual int Group() const
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)