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/files/file_path.h"
19 #include "packager/base/logging.h"
20 #include "packager/base/memory/scoped_ptr.h"
21 #include "packager/base/strings/string_number_conversions.h"
22 #include "packager/base/strings/stringprintf.h"
23 #include "packager/base/synchronization/lock.h"
24 #include "packager/base/time/time.h"
25 #include "packager/media/file/file.h"
26 #include "packager/mpd/base/content_protection_element.h"
27 #include "packager/mpd/base/language_utils.h"
28 #include "packager/mpd/base/mpd_utils.h"
29 #include "packager/mpd/base/xml/xml_node.h"
31 namespace edash_packager {
35 using xml::RepresentationXmlNode;
36 using xml::AdaptationSetXmlNode;
40 const int kAdaptationSetGroupNotSet = -1;
42 AdaptationSet::Role MediaInfoTextTypeToRole(MediaInfo::TextInfo::TextType type) {
44 case MediaInfo::TextInfo::UNKNOWN:
45 LOG(WARNING) <<
"Unknown text type, assuming subtitle.";
46 return AdaptationSet::kRoleSubtitle;
47 case MediaInfo::TextInfo::CAPTION:
48 return AdaptationSet::kRoleCaption;
49 case MediaInfo::TextInfo::SUBTITLE:
50 return AdaptationSet::kRoleSubtitle;
52 NOTREACHED() <<
"Unknown MediaInfo TextType: " << type
53 <<
" assuming subtitle.";
54 return AdaptationSet::kRoleSubtitle;
58 std::string GetMimeType(
const std::string& prefix,
59 MediaInfo::ContainerType container_type) {
60 switch (container_type) {
61 case MediaInfo::CONTAINER_MP4:
62 return prefix +
"/mp4";
63 case MediaInfo::CONTAINER_MPEG2_TS:
65 return prefix +
"/MP2T";
66 case MediaInfo::CONTAINER_WEBM:
67 return prefix +
"/webm";
73 LOG(ERROR) <<
"Unrecognized container type: " << container_type;
77 void AddMpdNameSpaceInfo(XmlNode* mpd) {
80 static const char kXmlNamespace[] =
"urn:mpeg:dash:schema:mpd:2011";
81 static const char kXmlNamespaceXsi[] =
82 "http://www.w3.org/2001/XMLSchema-instance";
83 static const char kXmlNamespaceXlink[] =
"http://www.w3.org/1999/xlink";
84 static const char kDashSchemaMpd2011[] =
85 "urn:mpeg:dash:schema:mpd:2011 DASH-MPD.xsd";
86 static const char kCencNamespace[] =
"urn:mpeg:cenc:2013";
88 mpd->SetStringAttribute(
"xmlns", kXmlNamespace);
89 mpd->SetStringAttribute(
"xmlns:xsi", kXmlNamespaceXsi);
90 mpd->SetStringAttribute(
"xmlns:xlink", kXmlNamespaceXlink);
91 mpd->SetStringAttribute(
"xsi:schemaLocation", kDashSchemaMpd2011);
92 mpd->SetStringAttribute(
"xmlns:cenc", kCencNamespace);
95 bool IsPeriodNode(xmlNodePtr node) {
98 return xmlStrcmp(node->name, reinterpret_cast<const xmlChar*>(
"Period")) ==
107 xmlNodePtr FindPeriodNode(XmlNode* xml_node) {
108 for (xmlNodePtr node = xml_node->GetRawPtr()->xmlChildrenNode; node != NULL;
110 if (IsPeriodNode(node))
117 bool Positive(
double d) {
123 std::string XmlDateTimeNowWithOffset(int32_t offset_seconds) {
124 base::Time time = base::Time::Now();
125 time += base::TimeDelta::FromSeconds(offset_seconds);
126 base::Time::Exploded time_exploded;
127 time.UTCExplode(&time_exploded);
129 return base::StringPrintf(
"%4d-%02d-%02dT%02d:%02d:%02dZ", time_exploded.year,
130 time_exploded.month, time_exploded.day_of_month,
131 time_exploded.hour, time_exploded.minute,
132 time_exploded.second);
135 void SetIfPositive(
const char* attr_name,
double value, XmlNode* mpd) {
136 if (Positive(value)) {
137 mpd->SetStringAttribute(attr_name, SecondsToXmlDuration(value));
141 uint32_t GetTimeScale(
const MediaInfo& media_info) {
142 if (media_info.has_reference_time_scale()) {
143 return media_info.reference_time_scale();
146 if (media_info.has_video_info()) {
147 return media_info.video_info().time_scale();
150 if (media_info.has_audio_info()) {
151 return media_info.audio_info().time_scale();
154 LOG(WARNING) <<
"No timescale specified, using 1 as timescale.";
158 uint64_t LastSegmentStartTime(
const SegmentInfo& segment_info) {
159 return segment_info.start_time + segment_info.duration * segment_info.repeat;
163 uint64_t LastSegmentEndTime(
const SegmentInfo& segment_info) {
164 return segment_info.start_time +
165 segment_info.duration * (segment_info.repeat + 1);
168 uint64_t LatestSegmentStartTime(
const std::list<SegmentInfo>& segments) {
169 DCHECK(!segments.empty());
170 const SegmentInfo& latest_segment = segments.back();
171 return LastSegmentStartTime(latest_segment);
176 int SearchTimedOutRepeatIndex(uint64_t timeshift_limit,
177 const SegmentInfo& segment_info) {
178 DCHECK_LE(timeshift_limit, LastSegmentEndTime(segment_info));
179 if (timeshift_limit < segment_info.start_time)
182 return (timeshift_limit - segment_info.start_time) / segment_info.duration;
188 bool WriteXmlCharArrayToOutput(xmlChar* doc,
190 std::string* output) {
193 output->assign(doc, doc + doc_size);
197 bool WriteXmlCharArrayToOutput(xmlChar* doc,
199 media::File* output) {
202 if (output->Write(doc, doc_size) < doc_size)
205 return output->Flush();
208 std::string MakePathRelative(
const std::string& path,
209 const std::string& mpd_dir) {
210 return (path.find(mpd_dir) == 0) ? path.substr(mpd_dir.size()) : path;
216 bool HasRequiredVideoFields(
const MediaInfo_VideoInfo& video_info) {
217 if (!video_info.has_height() || !video_info.has_width()) {
219 <<
"Width and height are required fields for generating a valid MPD.";
224 LOG_IF(WARNING, !video_info.has_time_scale())
225 <<
"Video info does not contain timescale required for "
226 "calculating framerate. @frameRate is required for DASH IOP.";
227 LOG_IF(WARNING, !video_info.has_frame_duration())
228 <<
"Video info does not contain frame duration required "
229 "for calculating framerate. @frameRate is required for DASH IOP.";
230 LOG_IF(WARNING, !video_info.has_pixel_width())
231 <<
"Video info does not contain pixel_width to calculate the sample "
232 "aspect ratio required for DASH IOP.";
233 LOG_IF(WARNING, !video_info.has_pixel_height())
234 <<
"Video info does not contain pixel_height to calculate the sample "
235 "aspect ratio required for DASH IOP.";
246 std::string GetPictureAspectRatio(uint32_t width,
248 uint32_t pixel_width,
249 uint32_t pixel_height) {
250 const uint32_t scaled_width = pixel_width * width;
251 const uint32_t scaled_height = pixel_height * height;
252 const double par =
static_cast<double>(scaled_width) / scaled_height;
256 const uint32_t kLargestPossibleParY = 19;
258 uint32_t par_num = 0;
259 uint32_t par_den = 0;
260 double min_error = 1.0;
261 for (uint32_t den = 1; den <= kLargestPossibleParY; ++den) {
262 uint32_t num = par * den + 0.5;
263 double error = fabs(par - static_cast<double>(num) / den);
264 if (error < min_error) {
268 if (error == 0)
break;
271 VLOG(2) <<
"width*pix_width : height*pixel_height (" << scaled_width <<
":"
272 << scaled_height <<
") reduced to " << par_num <<
":" << par_den
273 <<
" with error " << min_error <<
".";
275 return base::IntToString(par_num) +
":" + base::IntToString(par_den);
280 void AddPictureAspectRatio(
281 const MediaInfo::VideoInfo& video_info,
282 std::set<std::string>* picture_aspect_ratio) {
285 if (picture_aspect_ratio->size() > 1)
288 if (video_info.width() == 0 || video_info.height() == 0 ||
289 video_info.pixel_width() == 0 || video_info.pixel_height() == 0) {
294 picture_aspect_ratio->insert(
"bogus");
295 picture_aspect_ratio->insert(
"entries");
299 const std::string par = GetPictureAspectRatio(
300 video_info.width(), video_info.height(),
301 video_info.pixel_width(), video_info.pixel_height());
302 DVLOG(1) <<
"Setting par as: " << par
303 <<
" for video with width: " << video_info.width()
304 <<
" height: " << video_info.height()
305 <<
" pixel_width: " << video_info.pixel_width() <<
" pixel_height; "
306 << video_info.pixel_height();
307 picture_aspect_ratio->insert(par);
310 std::string RoleToText(AdaptationSet::Role role) {
314 case AdaptationSet::kRoleCaption:
316 case AdaptationSet::kRoleSubtitle:
318 case AdaptationSet::kRoleMain:
320 case AdaptationSet::kRoleAlternate:
322 case AdaptationSet::kRoleSupplementary:
323 return "supplementary";
324 case AdaptationSet::kRoleCommentary:
326 case AdaptationSet::kRoleDub:
338 class LibXmlInitializer {
340 LibXmlInitializer() : initialized_(false) {
341 base::AutoLock lock(lock_);
348 ~LibXmlInitializer() {
349 base::AutoLock lock(lock_);
352 initialized_ =
false;
360 DISALLOW_COPY_AND_ASSIGN(LibXmlInitializer);
363 class RepresentationStateChangeListenerImpl
364 :
public RepresentationStateChangeListener {
367 RepresentationStateChangeListenerImpl(uint32_t representation_id,
368 AdaptationSet* adaptation_set)
369 : representation_id_(representation_id), adaptation_set_(adaptation_set) {
370 DCHECK(adaptation_set_);
372 ~RepresentationStateChangeListenerImpl()
override {}
375 void OnNewSegmentForRepresentation(uint64_t start_time,
376 uint64_t duration)
override {
377 adaptation_set_->OnNewSegmentForRepresentation(representation_id_,
378 start_time, duration);
381 void OnSetFrameRateForRepresentation(uint32_t frame_duration,
382 uint32_t timescale)
override {
383 adaptation_set_->OnSetFrameRateForRepresentation(representation_id_,
384 frame_duration, timescale);
388 const uint32_t representation_id_;
389 AdaptationSet*
const adaptation_set_;
391 DISALLOW_COPY_AND_ASSIGN(RepresentationStateChangeListenerImpl);
398 mpd_options_(mpd_options),
399 adaptation_sets_deleter_(&adaptation_sets_) {}
401 MpdBuilder::~MpdBuilder() {}
404 base_urls_.push_back(base_url);
408 scoped_ptr<AdaptationSet> adaptation_set(
409 new AdaptationSet(adaptation_set_counter_.GetNext(), lang, mpd_options_,
410 type_, &representation_counter_));
412 DCHECK(adaptation_set);
413 adaptation_sets_.push_back(adaptation_set.get());
414 return adaptation_set.release();
419 return WriteMpdToOutput(output_file);
424 return WriteMpdToOutput(output);
426 template <
typename OutputType>
427 bool MpdBuilder::WriteMpdToOutput(OutputType* output) {
428 static LibXmlInitializer lib_xml_initializer;
430 xml::scoped_xml_ptr<xmlDoc> doc(GenerateMpd());
434 static const int kNiceFormat = 1;
435 int doc_str_size = 0;
436 xmlChar* doc_str = NULL;
437 xmlDocDumpFormatMemoryEnc(doc.get(), &doc_str, &doc_str_size,
"UTF-8",
440 bool result = WriteXmlCharArrayToOutput(doc_str, doc_str_size, output);
448 xmlDocPtr MpdBuilder::GenerateMpd() {
450 static const char kXmlVersion[] =
"1.0";
451 xml::scoped_xml_ptr<xmlDoc> doc(xmlNewDoc(BAD_CAST kXmlVersion));
455 XmlNode period(
"Period");
456 std::list<AdaptationSet*>::iterator adaptation_sets_it =
457 adaptation_sets_.begin();
458 for (; adaptation_sets_it != adaptation_sets_.end(); ++adaptation_sets_it) {
459 xml::scoped_xml_ptr<xmlNode> child((*adaptation_sets_it)->GetXml());
460 if (!child.get() || !period.AddChild(child.Pass()))
465 std::list<std::string>::const_iterator base_urls_it = base_urls_.begin();
466 for (; base_urls_it != base_urls_.end(); ++base_urls_it) {
467 XmlNode base_url(
"BaseURL");
468 base_url.SetContent(*base_urls_it);
470 if (!mpd.AddChild(base_url.PassScopedPtr()))
474 if (type_ == kDynamic) {
476 period.SetStringAttribute(
"start",
"PT0S");
479 if (!mpd.AddChild(period.PassScopedPtr()))
482 AddMpdNameSpaceInfo(&mpd);
483 AddCommonMpdInfo(&mpd);
486 AddStaticMpdInfo(&mpd);
489 AddDynamicMpdInfo(&mpd);
492 NOTREACHED() <<
"Unknown MPD type: " << type_;
497 std::string version_string =
498 "Generated with https://github.com/google/edash-packager version " +
499 mpd_options_.packager_version_string;
500 xml::scoped_xml_ptr<xmlNode> comment(
501 xmlNewDocComment(doc.get(), BAD_CAST version_string.c_str()));
502 xmlDocSetRootElement(doc.get(), comment.get());
503 xmlAddSibling(comment.release(), mpd.Release());
504 return doc.release();
507 void MpdBuilder::AddCommonMpdInfo(XmlNode* mpd_node) {
508 if (Positive(mpd_options_.min_buffer_time)) {
509 mpd_node->SetStringAttribute(
510 "minBufferTime", SecondsToXmlDuration(mpd_options_.min_buffer_time));
512 LOG(ERROR) <<
"minBufferTime value not specified.";
517 void MpdBuilder::AddStaticMpdInfo(XmlNode* mpd_node) {
519 DCHECK_EQ(MpdBuilder::kStatic, type_);
521 static const char kStaticMpdType[] =
"static";
522 static const char kStaticMpdProfile[] =
523 "urn:mpeg:dash:profile:isoff-on-demand:2011";
524 mpd_node->SetStringAttribute(
"type", kStaticMpdType);
525 mpd_node->SetStringAttribute(
"profiles", kStaticMpdProfile);
526 mpd_node->SetStringAttribute(
527 "mediaPresentationDuration",
528 SecondsToXmlDuration(GetStaticMpdDuration(mpd_node)));
531 void MpdBuilder::AddDynamicMpdInfo(XmlNode* mpd_node) {
533 DCHECK_EQ(MpdBuilder::kDynamic, type_);
535 static const char kDynamicMpdType[] =
"dynamic";
536 static const char kDynamicMpdProfile[] =
537 "urn:mpeg:dash:profile:isoff-live:2011";
538 mpd_node->SetStringAttribute(
"type", kDynamicMpdType);
539 mpd_node->SetStringAttribute(
"profiles", kDynamicMpdProfile);
543 if (availability_start_time_.empty()) {
544 double earliest_presentation_time;
545 if (GetEarliestTimestamp(&earliest_presentation_time)) {
546 availability_start_time_ =
547 XmlDateTimeNowWithOffset(mpd_options_.availability_time_offset -
548 std::ceil(earliest_presentation_time));
550 LOG(ERROR) <<
"Could not determine the earliest segment presentation "
551 "time for availabilityStartTime calculation.";
555 if (!availability_start_time_.empty())
556 mpd_node->SetStringAttribute(
"availabilityStartTime",
557 availability_start_time_);
559 if (Positive(mpd_options_.minimum_update_period)) {
560 mpd_node->SetStringAttribute(
561 "minimumUpdatePeriod",
562 SecondsToXmlDuration(mpd_options_.minimum_update_period));
564 LOG(WARNING) <<
"The profile is dynamic but no minimumUpdatePeriod "
568 SetIfPositive(
"timeShiftBufferDepth", mpd_options_.time_shift_buffer_depth,
570 SetIfPositive(
"suggestedPresentationDelay",
571 mpd_options_.suggested_presentation_delay, mpd_node);
574 float MpdBuilder::GetStaticMpdDuration(XmlNode* mpd_node) {
576 DCHECK_EQ(MpdBuilder::kStatic, type_);
578 xmlNodePtr period_node = FindPeriodNode(mpd_node);
579 DCHECK(period_node) <<
"Period element must be a child of mpd_node.";
580 DCHECK(IsPeriodNode(period_node));
585 float max_duration = 0.0f;
586 for (xmlNodePtr adaptation_set = xmlFirstElementChild(period_node);
587 adaptation_set; adaptation_set = xmlNextElementSibling(adaptation_set)) {
588 for (xmlNodePtr representation = xmlFirstElementChild(adaptation_set);
590 representation = xmlNextElementSibling(representation)) {
591 float duration = 0.0f;
592 if (GetDurationAttribute(representation, &duration)) {
593 max_duration = max_duration > duration ? max_duration : duration;
597 xmlUnsetProp(representation, BAD_CAST
"duration");
605 bool MpdBuilder::GetEarliestTimestamp(
double* timestamp_seconds) {
606 DCHECK(timestamp_seconds);
608 double earliest_timestamp(-1);
609 for (std::list<AdaptationSet*>::const_iterator iter =
610 adaptation_sets_.begin();
611 iter != adaptation_sets_.end(); ++iter) {
613 if ((*iter)->GetEarliestTimestamp(×tamp) &&
614 ((earliest_timestamp < 0) || (timestamp < earliest_timestamp))) {
615 earliest_timestamp = timestamp;
618 if (earliest_timestamp < 0)
621 *timestamp_seconds = earliest_timestamp;
626 MediaInfo* media_info) {
628 const std::string kFileProtocol(
"file://");
629 std::string mpd_file_path = (mpd_path.find(kFileProtocol) == 0)
630 ? mpd_path.substr(kFileProtocol.size())
633 if (!mpd_file_path.empty()) {
635 FilePath(mpd_file_path).DirName().AsEndingWithSeparator().value());
636 if (!mpd_dir.empty()) {
637 if (media_info->has_media_file_name()) {
638 media_info->set_media_file_name(
639 MakePathRelative(media_info->media_file_name(), mpd_dir));
641 if (media_info->has_init_segment_name()) {
642 media_info->set_init_segment_name(
643 MakePathRelative(media_info->init_segment_name(), mpd_dir));
645 if (media_info->has_segment_template()) {
646 media_info->set_segment_template(
647 MakePathRelative(media_info->segment_template(), mpd_dir));
654 const std::string& lang,
656 MpdBuilder::MpdType mpd_type,
657 base::AtomicSequenceNumber* counter)
658 : representations_deleter_(&representations_),
659 representation_counter_(counter),
660 id_(adaptation_set_id),
662 mpd_options_(mpd_options),
664 group_(kAdaptationSetGroupNotSet),
665 segments_aligned_(kSegmentAlignmentUnknown),
666 force_set_segment_alignment_(false) {
670 AdaptationSet::~AdaptationSet() {}
673 const uint32_t representation_id = representation_counter_->GetNext();
676 scoped_ptr<RepresentationStateChangeListener> listener(
677 new RepresentationStateChangeListenerImpl(representation_id,
this));
679 media_info, mpd_options_, representation_id, listener.Pass()));
681 if (!representation->Init())
686 if (media_info.has_video_info()) {
687 const MediaInfo::VideoInfo& video_info = media_info.video_info();
688 DCHECK(video_info.has_width());
689 DCHECK(video_info.has_height());
690 video_widths_.insert(video_info.width());
691 video_heights_.insert(video_info.height());
693 if (video_info.has_time_scale() && video_info.has_frame_duration())
694 RecordFrameRate(video_info.frame_duration(), video_info.time_scale());
696 AddPictureAspectRatio(video_info, &picture_aspect_ratio_);
699 if (media_info.has_video_info()) {
700 content_type_ =
"video";
701 }
else if (media_info.has_audio_info()) {
702 content_type_ =
"audio";
703 }
else if (media_info.has_text_info()) {
704 content_type_ =
"text";
706 if (media_info.text_info().has_type() &&
707 (media_info.text_info().type() != MediaInfo::TextInfo::UNKNOWN)) {
708 roles_.insert(MediaInfoTextTypeToRole(media_info.text_info().type()));
712 representations_.push_back(representation.get());
713 return representation.release();
718 content_protection_elements_.push_back(content_protection_element);
719 RemoveDuplicateAttributes(&content_protection_elements_.back());
723 const std::string& pssh) {
724 UpdateContentProtectionPsshHelper(drm_uuid, pssh,
725 &content_protection_elements_);
735 AdaptationSetXmlNode adaptation_set;
737 if (!adaptation_set.AddContentProtectionElements(
738 content_protection_elements_)) {
739 return xml::scoped_xml_ptr<xmlNode>();
741 for (std::set<Role>::const_iterator role_it = roles_.begin();
742 role_it != roles_.end(); ++role_it) {
743 adaptation_set.AddRoleElement(
"urn:mpeg:dash:role:2011",
744 RoleToText(*role_it));
747 std::list<Representation*>::iterator representation_it =
748 representations_.begin();
750 for (; representation_it != representations_.end(); ++representation_it) {
751 xml::scoped_xml_ptr<xmlNode> child((*representation_it)->GetXml());
752 if (!child || !adaptation_set.AddChild(child.Pass()))
753 return xml::scoped_xml_ptr<xmlNode>();
756 adaptation_set.SetId(id_);
757 adaptation_set.SetStringAttribute(
"contentType", content_type_);
758 if (!lang_.empty() && lang_ !=
"und") {
763 if (video_widths_.size() == 1) {
764 adaptation_set.SetIntegerAttribute(
"width", *video_widths_.begin());
765 }
else if (video_widths_.size() > 1) {
766 adaptation_set.SetIntegerAttribute(
"maxWidth", *video_widths_.rbegin());
768 if (video_heights_.size() == 1) {
769 adaptation_set.SetIntegerAttribute(
"height", *video_heights_.begin());
770 }
else if (video_heights_.size() > 1) {
771 adaptation_set.SetIntegerAttribute(
"maxHeight", *video_heights_.rbegin());
774 if (video_frame_rates_.size() == 1) {
775 adaptation_set.SetStringAttribute(
"frameRate",
776 video_frame_rates_.begin()->second);
777 }
else if (video_frame_rates_.size() > 1) {
778 adaptation_set.SetStringAttribute(
"maxFrameRate",
779 video_frame_rates_.rbegin()->second);
783 if (mpd_type_ == MpdBuilder::kStatic) {
784 CheckVodSegmentAlignment();
787 if (segments_aligned_ == kSegmentAlignmentTrue) {
788 adaptation_set.SetStringAttribute(mpd_type_ == MpdBuilder::kStatic
789 ?
"subsegmentAlignment"
790 :
"segmentAlignment",
794 if (picture_aspect_ratio_.size() == 1)
795 adaptation_set.SetStringAttribute(
"par", *picture_aspect_ratio_.begin());
798 adaptation_set.SetIntegerAttribute(
"group", group_);
800 return adaptation_set.PassScopedPtr();
805 segment_alignment ? kSegmentAlignmentTrue : kSegmentAlignmentFalse;
806 force_set_segment_alignment_ =
true;
810 group_ = group_number;
827 if (mpd_type_ == MpdBuilder::kDynamic) {
828 CheckLiveSegmentAlignment(representation_id, start_time, duration);
830 representation_segment_start_times_[representation_id].push_back(
836 uint32_t representation_id,
837 uint32_t frame_duration,
838 uint32_t timescale) {
839 RecordFrameRate(frame_duration, timescale);
842 bool AdaptationSet::GetEarliestTimestamp(
double* timestamp_seconds) {
843 DCHECK(timestamp_seconds);
845 double earliest_timestamp(-1);
846 for (std::list<Representation*>::const_iterator iter =
847 representations_.begin();
848 iter != representations_.end(); ++iter) {
850 if ((*iter)->GetEarliestTimestamp(×tamp) &&
851 ((earliest_timestamp < 0) || (timestamp < earliest_timestamp))) {
852 earliest_timestamp = timestamp;
855 if (earliest_timestamp < 0)
858 *timestamp_seconds = earliest_timestamp;
886 void AdaptationSet::CheckLiveSegmentAlignment(uint32_t representation_id,
889 if (segments_aligned_ == kSegmentAlignmentFalse ||
890 force_set_segment_alignment_) {
894 std::list<uint64_t>& representation_start_times =
895 representation_segment_start_times_[representation_id];
896 representation_start_times.push_back(start_time);
899 if (representation_segment_start_times_.size() != representations_.size())
902 DCHECK(!representation_start_times.empty());
903 const uint64_t expected_start_time = representation_start_times.front();
904 for (RepresentationTimeline::const_iterator it =
905 representation_segment_start_times_.begin();
906 it != representation_segment_start_times_.end(); ++it) {
910 if (it->second.empty())
913 if (expected_start_time != it->second.front()) {
916 segments_aligned_ = kSegmentAlignmentFalse;
917 representation_segment_start_times_.clear();
921 segments_aligned_ = kSegmentAlignmentTrue;
923 for (RepresentationTimeline::iterator it =
924 representation_segment_start_times_.begin();
925 it != representation_segment_start_times_.end(); ++it) {
926 it->second.pop_front();
932 void AdaptationSet::CheckVodSegmentAlignment() {
933 if (segments_aligned_ == kSegmentAlignmentFalse ||
934 force_set_segment_alignment_) {
937 if (representation_segment_start_times_.empty())
939 if (representation_segment_start_times_.size() == 1) {
940 segments_aligned_ = kSegmentAlignmentTrue;
947 const std::list<uint64_t>& expected_time_line =
948 representation_segment_start_times_.begin()->second;
950 bool all_segment_time_line_same_length =
true;
952 RepresentationTimeline::const_iterator it =
953 representation_segment_start_times_.begin();
954 for (++it; it != representation_segment_start_times_.end(); ++it) {
955 const std::list<uint64_t>& other_time_line = it->second;
956 if (expected_time_line.size() != other_time_line.size()) {
957 all_segment_time_line_same_length =
false;
960 const std::list<uint64_t>* longer_list = &other_time_line;
961 const std::list<uint64_t>* shorter_list = &expected_time_line;
962 if (expected_time_line.size() > other_time_line.size()) {
963 shorter_list = &other_time_line;
964 longer_list = &expected_time_line;
967 if (!std::equal(shorter_list->begin(), shorter_list->end(),
968 longer_list->begin())) {
970 segments_aligned_ = kSegmentAlignmentFalse;
971 representation_segment_start_times_.clear();
982 if (!all_segment_time_line_same_length) {
983 segments_aligned_ = kSegmentAlignmentUnknown;
987 segments_aligned_ = kSegmentAlignmentTrue;
992 void AdaptationSet::RecordFrameRate(uint32_t frame_duration,
993 uint32_t timescale) {
994 if (frame_duration == 0) {
995 LOG(ERROR) <<
"Frame duration is 0 and cannot be set.";
998 video_frame_rates_[
static_cast<double>(timescale) / frame_duration] =
999 base::IntToString(timescale) +
"/" + base::IntToString(frame_duration);
1003 const MediaInfo& media_info,
1006 scoped_ptr<RepresentationStateChangeListener> state_change_listener)
1007 : media_info_(media_info),
1010 mpd_options_(mpd_options),
1012 state_change_listener_(state_change_listener.Pass()) {}
1014 Representation::~Representation() {}
1017 if (!AtLeastOneTrue(media_info_.has_video_info(),
1018 media_info_.has_audio_info(),
1019 media_info_.has_text_info())) {
1023 LOG(ERROR) <<
"Representation needs one of video, audio, or text.";
1027 if (MoreThanOneTrue(media_info_.has_video_info(),
1028 media_info_.has_audio_info(),
1029 media_info_.has_text_info())) {
1030 LOG(ERROR) <<
"Only one of VideoInfo, AudioInfo, or TextInfo can be set.";
1034 if (media_info_.container_type() == MediaInfo::CONTAINER_UNKNOWN) {
1035 LOG(ERROR) <<
"'container_type' in MediaInfo cannot be CONTAINER_UNKNOWN.";
1039 if (media_info_.has_video_info()) {
1040 mime_type_ = GetVideoMimeType();
1041 if (!HasRequiredVideoFields(media_info_.video_info())) {
1042 LOG(ERROR) <<
"Missing required fields to create a video Representation.";
1045 }
else if (media_info_.has_audio_info()) {
1046 mime_type_ = GetAudioMimeType();
1047 }
else if (media_info_.has_text_info()) {
1048 mime_type_ = GetTextMimeType();
1051 if (mime_type_.empty())
1054 codecs_ = GetCodecs(media_info_);
1060 content_protection_elements_.push_back(content_protection_element);
1061 RemoveDuplicateAttributes(&content_protection_elements_.back());
1065 const std::string& pssh) {
1066 UpdateContentProtectionPsshHelper(drm_uuid, pssh,
1067 &content_protection_elements_);
1073 if (start_time == 0 && duration == 0) {
1074 LOG(WARNING) <<
"Got segment with start_time and duration == 0. Ignoring.";
1078 if (state_change_listener_)
1079 state_change_listener_->OnNewSegmentForRepresentation(start_time, duration);
1080 if (IsContiguous(start_time, duration, size)) {
1081 ++segment_infos_.back().repeat;
1084 segment_infos_.push_back(s);
1087 bandwidth_estimator_.AddBlock(
1088 size, static_cast<double>(duration) / media_info_.reference_time_scale());
1091 DCHECK_GE(segment_infos_.size(), 1u);
1095 if (media_info_.has_video_info()) {
1096 media_info_.mutable_video_info()->set_frame_duration(sample_duration);
1097 if (state_change_listener_) {
1098 state_change_listener_->OnSetFrameRateForRepresentation(
1099 sample_duration, media_info_.video_info().time_scale());
1111 if (!HasRequiredMediaInfoFields()) {
1112 LOG(ERROR) <<
"MediaInfo missing required fields.";
1113 return xml::scoped_xml_ptr<xmlNode>();
1116 const uint64_t bandwidth = media_info_.has_bandwidth()
1117 ? media_info_.bandwidth()
1118 : bandwidth_estimator_.Estimate();
1120 DCHECK(!(HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)));
1122 RepresentationXmlNode representation;
1124 representation.SetId(id_);
1125 representation.SetIntegerAttribute(
"bandwidth", bandwidth);
1126 if (!codecs_.empty())
1127 representation.SetStringAttribute(
"codecs", codecs_);
1128 representation.SetStringAttribute(
"mimeType", mime_type_);
1130 const bool has_video_info = media_info_.has_video_info();
1131 const bool has_audio_info = media_info_.has_audio_info();
1133 if (has_video_info &&
1134 !representation.AddVideoInfo(media_info_.video_info())) {
1135 LOG(ERROR) <<
"Failed to add video info to Representation XML.";
1136 return xml::scoped_xml_ptr<xmlNode>();
1139 if (has_audio_info &&
1140 !representation.AddAudioInfo(media_info_.audio_info())) {
1141 LOG(ERROR) <<
"Failed to add audio info to Representation XML.";
1142 return xml::scoped_xml_ptr<xmlNode>();
1145 if (!representation.AddContentProtectionElements(
1146 content_protection_elements_)) {
1147 return xml::scoped_xml_ptr<xmlNode>();
1150 if (HasVODOnlyFields(media_info_) &&
1151 !representation.AddVODOnlyInfo(media_info_)) {
1152 LOG(ERROR) <<
"Failed to add VOD segment info.";
1153 return xml::scoped_xml_ptr<xmlNode>();
1156 if (HasLiveOnlyFields(media_info_) &&
1157 !representation.AddLiveOnlyInfo(media_info_, segment_infos_,
1159 LOG(ERROR) <<
"Failed to add Live info.";
1160 return xml::scoped_xml_ptr<xmlNode>();
1165 return representation.PassScopedPtr();
1168 bool Representation::HasRequiredMediaInfoFields() {
1169 if (HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)) {
1170 LOG(ERROR) <<
"MediaInfo cannot have both VOD and Live fields.";
1174 if (!media_info_.has_container_type()) {
1175 LOG(ERROR) <<
"MediaInfo missing required field: container_type.";
1179 if (HasVODOnlyFields(media_info_) && !media_info_.has_bandwidth()) {
1180 LOG(ERROR) <<
"Missing 'bandwidth' field. MediaInfo requires bandwidth for "
1181 "static profile for generating a valid MPD.";
1185 VLOG_IF(3, HasLiveOnlyFields(media_info_) && !media_info_.has_bandwidth())
1186 <<
"MediaInfo missing field 'bandwidth'. Using estimated from "
1192 bool Representation::IsContiguous(uint64_t start_time,
1194 uint64_t size)
const {
1195 if (segment_infos_.empty())
1199 const SegmentInfo& previous = segment_infos_.back();
1200 const uint64_t previous_segment_end_time =
1201 previous.start_time + previous.duration * (previous.repeat + 1);
1202 if (previous_segment_end_time == start_time &&
1203 segment_infos_.back().duration == duration) {
1208 const uint64_t previous_segment_start_time =
1209 previous.start_time + previous.duration * previous.repeat;
1210 if (previous_segment_start_time >= start_time) {
1211 LOG(ERROR) <<
"Segments should not be out of order segment. Adding segment "
1212 "with start_time == "
1213 << start_time <<
" but the previous segment starts at "
1214 << previous.start_time <<
".";
1219 const uint64_t kRoundingErrorGrace = 5;
1220 if (previous_segment_end_time + kRoundingErrorGrace < start_time) {
1221 LOG(WARNING) <<
"Found a gap of size "
1222 << (start_time - previous_segment_end_time)
1223 <<
" > kRoundingErrorGrace (" << kRoundingErrorGrace
1224 <<
"). The new segment starts at " << start_time
1225 <<
" but the previous segment ends at "
1226 << previous_segment_end_time <<
".";
1231 if (start_time < previous_segment_end_time - kRoundingErrorGrace) {
1233 <<
"Segments should not be overlapping. The new segment starts at "
1234 << start_time <<
" but the previous segment ends at "
1235 << previous_segment_end_time <<
".";
1243 void Representation::SlideWindow() {
1244 DCHECK(!segment_infos_.empty());
1245 if (mpd_options_.time_shift_buffer_depth <= 0.0)
1248 const uint32_t time_scale = GetTimeScale(media_info_);
1249 DCHECK_GT(time_scale, 0u);
1251 uint64_t time_shift_buffer_depth =
1252 static_cast<uint64_t
>(mpd_options_.time_shift_buffer_depth * time_scale);
1256 const uint64_t current_play_time = LatestSegmentStartTime(segment_infos_);
1257 if (current_play_time <= time_shift_buffer_depth)
1260 const uint64_t timeshift_limit = current_play_time - time_shift_buffer_depth;
1264 std::list<SegmentInfo>::iterator first = segment_infos_.begin();
1265 std::list<SegmentInfo>::iterator last = first;
1266 size_t num_segments_removed = 0;
1267 for (; last != segment_infos_.end(); ++last) {
1268 const uint64_t last_segment_end_time = LastSegmentEndTime(*last);
1269 if (timeshift_limit < last_segment_end_time)
1271 num_segments_removed += last->repeat + 1;
1273 segment_infos_.erase(first, last);
1274 start_number_ += num_segments_removed;
1277 SegmentInfo* first_segment_info = &segment_infos_.front();
1278 DCHECK_LE(timeshift_limit, LastSegmentEndTime(*first_segment_info));
1281 const int repeat_index =
1282 SearchTimedOutRepeatIndex(timeshift_limit, *first_segment_info);
1283 CHECK_GE(repeat_index, 0);
1284 if (repeat_index == 0)
1287 first_segment_info->start_time = first_segment_info->start_time +
1288 first_segment_info->duration * repeat_index;
1290 first_segment_info->repeat = first_segment_info->repeat - repeat_index;
1291 start_number_ += repeat_index;
1294 std::string Representation::GetVideoMimeType()
const {
1295 return GetMimeType(
"video", media_info_.container_type());
1298 std::string Representation::GetAudioMimeType()
const {
1299 return GetMimeType(
"audio", media_info_.container_type());
1302 std::string Representation::GetTextMimeType()
const {
1303 CHECK(media_info_.has_text_info());
1304 if (media_info_.text_info().format() ==
"ttml") {
1305 switch (media_info_.container_type()) {
1306 case MediaInfo::CONTAINER_TEXT:
1307 return "application/ttml+xml";
1308 case MediaInfo::CONTAINER_MP4:
1309 return "application/mp4";
1311 LOG(ERROR) <<
"Failed to determine MIME type for TTML container: "
1312 << media_info_.container_type();
1316 if (media_info_.text_info().format() ==
"vtt") {
1317 if (media_info_.container_type() == MediaInfo::CONTAINER_TEXT) {
1320 LOG(ERROR) <<
"Failed to determine MIME type for VTT container: "
1321 << media_info_.container_type();
1325 LOG(ERROR) <<
"Cannot determine MIME type for format: "
1326 << media_info_.text_info().format()
1327 <<
" container: " << media_info_.container_type();
1331 bool Representation::GetEarliestTimestamp(
double* timestamp_seconds) {
1332 DCHECK(timestamp_seconds);
1334 if (segment_infos_.empty())
1337 *timestamp_seconds =
static_cast<double>(segment_infos_.begin()->start_time) /
1338 GetTimeScale(media_info_);
std::string LanguageToShortestForm(const std::string &language)
virtual void AddNewSegment(uint64_t start_time, uint64_t duration, uint64_t size)
AdaptationSet(uint32_t adaptation_set_id, const std::string &lang, const MpdOptions &mpd_options, MpdBuilder::MpdType mpd_type, base::AtomicSequenceNumber *representation_counter)
virtual int Group() const
virtual AdaptationSet * AddAdaptationSet(const std::string &lang)
xml::scoped_xml_ptr< xmlNode > GetXml()
static void MakePathsRelativeToMpd(const std::string &mpd_path, MediaInfo *media_info)
virtual void ForceSetSegmentAlignment(bool segment_alignment)
virtual void SetSampleDuration(uint32_t sample_duration)
void AddBaseUrl(const std::string &base_url)
virtual void UpdateContentProtectionPssh(const std::string &drm_uuid, const std::string &pssh)
Representation(const MediaInfo &media_info, const MpdOptions &mpd_options, uint32_t representation_id, scoped_ptr< RepresentationStateChangeListener > state_change_listener)
virtual void SetGroup(int group_number)
virtual void AddContentProtectionElement(const ContentProtectionElement &element)
bool WriteMpdToFile(media::File *output_file)
void OnSetFrameRateForRepresentation(uint32_t representation_id, uint32_t frame_duration, uint32_t timescale)
virtual Representation * AddRepresentation(const MediaInfo &media_info)
xml::scoped_xml_ptr< xmlNode > GetXml()
virtual void UpdateContentProtectionPssh(const std::string &drm_uuid, const std::string &pssh)
virtual bool ToString(std::string *output)
virtual void AddRole(Role role)
MpdBuilder(MpdType type, const MpdOptions &mpd_options)
virtual void AddContentProtectionElement(const ContentProtectionElement &element)
void OnNewSegmentForRepresentation(uint32_t representation_id, uint64_t start_time, uint64_t duration)