DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerator
mpd_builder.cc
1 // Copyright 2014 Google Inc. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file or at
5 // https://developers.google.com/open-source/licenses/bsd
6 
7 #include "packager/mpd/base/mpd_builder.h"
8 
9 #include <libxml/tree.h>
10 #include <libxml/xmlstring.h>
11 
12 #include <cmath>
13 #include <iterator>
14 #include <list>
15 #include <string>
16 
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"
30 
31 namespace edash_packager {
32 
33 using base::FilePath;
34 using xml::XmlNode;
35 using xml::RepresentationXmlNode;
36 using xml::AdaptationSetXmlNode;
37 
38 namespace {
39 
40 const int kAdaptationSetGroupNotSet = -1;
41 
42 AdaptationSet::Role MediaInfoTextTypeToRole(
43  MediaInfo::TextInfo::TextType type) {
44  switch (type) {
45  case MediaInfo::TextInfo::UNKNOWN:
46  LOG(WARNING) << "Unknown text type, assuming subtitle.";
47  return AdaptationSet::kRoleSubtitle;
48  case MediaInfo::TextInfo::CAPTION:
49  return AdaptationSet::kRoleCaption;
50  case MediaInfo::TextInfo::SUBTITLE:
51  return AdaptationSet::kRoleSubtitle;
52  default:
53  NOTREACHED() << "Unknown MediaInfo TextType: " << type
54  << " assuming subtitle.";
55  return AdaptationSet::kRoleSubtitle;
56  }
57 }
58 
59 std::string GetMimeType(const std::string& prefix,
60  MediaInfo::ContainerType container_type) {
61  switch (container_type) {
62  case MediaInfo::CONTAINER_MP4:
63  return prefix + "/mp4";
64  case MediaInfo::CONTAINER_MPEG2_TS:
65  // NOTE: DASH MPD spec uses lowercase but RFC3555 says uppercase.
66  return prefix + "/MP2T";
67  case MediaInfo::CONTAINER_WEBM:
68  return prefix + "/webm";
69  default:
70  break;
71  }
72 
73  // Unsupported container types should be rejected/handled by the caller.
74  LOG(ERROR) << "Unrecognized container type: " << container_type;
75  return std::string();
76 }
77 
78 void AddMpdNameSpaceInfo(XmlNode* mpd) {
79  DCHECK(mpd);
80 
81  static const char kXmlNamespace[] = "urn:mpeg:dash:schema:mpd:2011";
82  static const char kXmlNamespaceXsi[] =
83  "http://www.w3.org/2001/XMLSchema-instance";
84  static const char kXmlNamespaceXlink[] = "http://www.w3.org/1999/xlink";
85  static const char kDashSchemaMpd2011[] =
86  "urn:mpeg:dash:schema:mpd:2011 DASH-MPD.xsd";
87  static const char kCencNamespace[] = "urn:mpeg:cenc:2013";
88 
89  mpd->SetStringAttribute("xmlns", kXmlNamespace);
90  mpd->SetStringAttribute("xmlns:xsi", kXmlNamespaceXsi);
91  mpd->SetStringAttribute("xmlns:xlink", kXmlNamespaceXlink);
92  mpd->SetStringAttribute("xsi:schemaLocation", kDashSchemaMpd2011);
93  mpd->SetStringAttribute("xmlns:cenc", kCencNamespace);
94 }
95 
96 bool IsPeriodNode(xmlNodePtr node) {
97  DCHECK(node);
98  int kEqual = 0;
99  return xmlStrcmp(node->name, reinterpret_cast<const xmlChar*>("Period")) ==
100  kEqual;
101 }
102 
103 // Find the first <Period> element. This does not recurse down the tree,
104 // only checks direct children. Returns the pointer to Period element on
105 // success, otherwise returns false.
106 // As noted here, we must traverse.
107 // http://www.xmlsoft.org/tutorial/ar01s04.html
108 xmlNodePtr FindPeriodNode(XmlNode* xml_node) {
109  for (xmlNodePtr node = xml_node->GetRawPtr()->xmlChildrenNode; node != NULL;
110  node = node->next) {
111  if (IsPeriodNode(node))
112  return node;
113  }
114 
115  return NULL;
116 }
117 
118 bool Positive(double d) {
119  return d > 0.0;
120 }
121 
122 // Return current time in XML DateTime format. The value is in UTC, so the
123 // string ends with a 'Z'.
124 std::string XmlDateTimeNowWithOffset(int32_t offset_seconds) {
125  base::Time time = base::Time::Now();
126  time += base::TimeDelta::FromSeconds(offset_seconds);
127  base::Time::Exploded time_exploded;
128  time.UTCExplode(&time_exploded);
129 
130  return base::StringPrintf("%4d-%02d-%02dT%02d:%02d:%02dZ", time_exploded.year,
131  time_exploded.month, time_exploded.day_of_month,
132  time_exploded.hour, time_exploded.minute,
133  time_exploded.second);
134 }
135 
136 void SetIfPositive(const char* attr_name, double value, XmlNode* mpd) {
137  if (Positive(value)) {
138  mpd->SetStringAttribute(attr_name, SecondsToXmlDuration(value));
139  }
140 }
141 
142 uint32_t GetTimeScale(const MediaInfo& media_info) {
143  if (media_info.has_reference_time_scale()) {
144  return media_info.reference_time_scale();
145  }
146 
147  if (media_info.has_video_info()) {
148  return media_info.video_info().time_scale();
149  }
150 
151  if (media_info.has_audio_info()) {
152  return media_info.audio_info().time_scale();
153  }
154 
155  LOG(WARNING) << "No timescale specified, using 1 as timescale.";
156  return 1;
157 }
158 
159 uint64_t LastSegmentStartTime(const SegmentInfo& segment_info) {
160  return segment_info.start_time + segment_info.duration * segment_info.repeat;
161 }
162 
163 // This is equal to |segment_info| end time
164 uint64_t LastSegmentEndTime(const SegmentInfo& segment_info) {
165  return segment_info.start_time +
166  segment_info.duration * (segment_info.repeat + 1);
167 }
168 
169 uint64_t LatestSegmentStartTime(const std::list<SegmentInfo>& segments) {
170  DCHECK(!segments.empty());
171  const SegmentInfo& latest_segment = segments.back();
172  return LastSegmentStartTime(latest_segment);
173 }
174 
175 // Given |timeshift_limit|, finds out the number of segments that are no longer
176 // valid and should be removed from |segment_info|.
177 int SearchTimedOutRepeatIndex(uint64_t timeshift_limit,
178  const SegmentInfo& segment_info) {
179  DCHECK_LE(timeshift_limit, LastSegmentEndTime(segment_info));
180  if (timeshift_limit < segment_info.start_time)
181  return 0;
182 
183  return (timeshift_limit - segment_info.start_time) / segment_info.duration;
184 }
185 
186 // Overload this function to support different types of |output|.
187 // Note that this could be done by call MpdBuilder::ToString() and use the
188 // result to write to a file, it requires an extra copy.
189 bool WriteXmlCharArrayToOutput(xmlChar* doc,
190  int doc_size,
191  std::string* output) {
192  DCHECK(doc);
193  DCHECK(output);
194  output->assign(doc, doc + doc_size);
195  return true;
196 }
197 
198 bool WriteXmlCharArrayToOutput(xmlChar* doc,
199  int doc_size,
200  media::File* output) {
201  DCHECK(doc);
202  DCHECK(output);
203  if (output->Write(doc, doc_size) < doc_size)
204  return false;
205 
206  return output->Flush();
207 }
208 
209 std::string MakePathRelative(const std::string& path,
210  const std::string& mpd_dir) {
211  return (path.find(mpd_dir) == 0) ? path.substr(mpd_dir.size()) : path;
212 }
213 
214 // Check whether the video info has width and height.
215 // DASH IOP also requires several other fields for video representations, namely
216 // width, height, framerate, and sar.
217 bool HasRequiredVideoFields(const MediaInfo_VideoInfo& video_info) {
218  if (!video_info.has_height() || !video_info.has_width()) {
219  LOG(ERROR)
220  << "Width and height are required fields for generating a valid MPD.";
221  return false;
222  }
223  // These fields are not required for a valid MPD, but required for DASH IOP
224  // compliant MPD. MpdBuilder can keep generating MPDs without these fields.
225  LOG_IF(WARNING, !video_info.has_time_scale())
226  << "Video info does not contain timescale required for "
227  "calculating framerate. @frameRate is required for DASH IOP.";
228  LOG_IF(WARNING, !video_info.has_frame_duration())
229  << "Video info does not contain frame duration required "
230  "for calculating framerate. @frameRate is required for DASH IOP.";
231  LOG_IF(WARNING, !video_info.has_pixel_width())
232  << "Video info does not contain pixel_width to calculate the sample "
233  "aspect ratio required for DASH IOP.";
234  LOG_IF(WARNING, !video_info.has_pixel_height())
235  << "Video info does not contain pixel_height to calculate the sample "
236  "aspect ratio required for DASH IOP.";
237  return true;
238 }
239 
240 // Returns the picture aspect ratio string e.g. "16:9", "4:3".
241 // "Reducing the quotient to minimal form" does not work well in practice as
242 // there may be some rounding performed in the input, e.g. the resolution of
243 // 480p is 854:480 for 16:9 aspect ratio, can only be reduced to 427:240.
244 // The algorithm finds out the pair of integers, num and den, where num / den is
245 // the closest ratio to scaled_width / scaled_height, by looping den through
246 // common values.
247 std::string GetPictureAspectRatio(uint32_t width,
248  uint32_t height,
249  uint32_t pixel_width,
250  uint32_t pixel_height) {
251  const uint32_t scaled_width = pixel_width * width;
252  const uint32_t scaled_height = pixel_height * height;
253  const double par = static_cast<double>(scaled_width) / scaled_height;
254 
255  // Typical aspect ratios have par_y less than or equal to 19:
256  // https://en.wikipedia.org/wiki/List_of_common_resolutions
257  const uint32_t kLargestPossibleParY = 19;
258 
259  uint32_t par_num = 0;
260  uint32_t par_den = 0;
261  double min_error = 1.0;
262  for (uint32_t den = 1; den <= kLargestPossibleParY; ++den) {
263  uint32_t num = par * den + 0.5;
264  double error = fabs(par - static_cast<double>(num) / den);
265  if (error < min_error) {
266  min_error = error;
267  par_num = num;
268  par_den = den;
269  if (error == 0) break;
270  }
271  }
272  VLOG(2) << "width*pix_width : height*pixel_height (" << scaled_width << ":"
273  << scaled_height << ") reduced to " << par_num << ":" << par_den
274  << " with error " << min_error << ".";
275 
276  return base::IntToString(par_num) + ":" + base::IntToString(par_den);
277 }
278 
279 // Adds an entry to picture_aspect_ratio if the size of picture_aspect_ratio is
280 // less than 2 and video_info has both pixel width and pixel height.
281 void AddPictureAspectRatio(
282  const MediaInfo::VideoInfo& video_info,
283  std::set<std::string>* picture_aspect_ratio) {
284  // If there are more than one entries in picture_aspect_ratio, the @par
285  // attribute cannot be set, so skip.
286  if (picture_aspect_ratio->size() > 1)
287  return;
288 
289  if (video_info.width() == 0 || video_info.height() == 0 ||
290  video_info.pixel_width() == 0 || video_info.pixel_height() == 0) {
291  // If there is even one Representation without a @sar attribute, @par cannot
292  // be calculated.
293  // Just populate the set with at least 2 bogus strings so that further call
294  // to this function will bail out immediately.
295  picture_aspect_ratio->insert("bogus");
296  picture_aspect_ratio->insert("entries");
297  return;
298  }
299 
300  const std::string par = GetPictureAspectRatio(
301  video_info.width(), video_info.height(),
302  video_info.pixel_width(), video_info.pixel_height());
303  DVLOG(1) << "Setting par as: " << par
304  << " for video with width: " << video_info.width()
305  << " height: " << video_info.height()
306  << " pixel_width: " << video_info.pixel_width() << " pixel_height; "
307  << video_info.pixel_height();
308  picture_aspect_ratio->insert(par);
309 }
310 
311 std::string RoleToText(AdaptationSet::Role role) {
312  // Using switch so that the compiler can detect whether there is a case that's
313  // not being handled.
314  switch (role) {
315  case AdaptationSet::kRoleCaption:
316  return "caption";
317  case AdaptationSet::kRoleSubtitle:
318  return "subtitle";
319  case AdaptationSet::kRoleMain:
320  return "main";
321  case AdaptationSet::kRoleAlternate:
322  return "alternate";
323  case AdaptationSet::kRoleSupplementary:
324  return "supplementary";
325  case AdaptationSet::kRoleCommentary:
326  return "commentary";
327  case AdaptationSet::kRoleDub:
328  return "dub";
329  default:
330  NOTREACHED();
331  return "";
332  }
333 
334  NOTREACHED();
335  return "";
336 }
337 
338 // Spooky static initialization/cleanup of libxml.
339 class LibXmlInitializer {
340  public:
341  LibXmlInitializer() : initialized_(false) {
342  base::AutoLock lock(lock_);
343  if (!initialized_) {
344  xmlInitParser();
345  initialized_ = true;
346  }
347  }
348 
349  ~LibXmlInitializer() {
350  base::AutoLock lock(lock_);
351  if (initialized_) {
352  xmlCleanupParser();
353  initialized_ = false;
354  }
355  }
356 
357  private:
358  base::Lock lock_;
359  bool initialized_;
360 
361  DISALLOW_COPY_AND_ASSIGN(LibXmlInitializer);
362 };
363 
364 class RepresentationStateChangeListenerImpl
365  : public RepresentationStateChangeListener {
366  public:
367  // |adaptation_set| is not owned by this class.
368  RepresentationStateChangeListenerImpl(uint32_t representation_id,
369  AdaptationSet* adaptation_set)
370  : representation_id_(representation_id), adaptation_set_(adaptation_set) {
371  DCHECK(adaptation_set_);
372  }
373  ~RepresentationStateChangeListenerImpl() override {}
374 
375  // RepresentationStateChangeListener implementation.
376  void OnNewSegmentForRepresentation(uint64_t start_time,
377  uint64_t duration) override {
378  adaptation_set_->OnNewSegmentForRepresentation(representation_id_,
379  start_time, duration);
380  }
381 
382  void OnSetFrameRateForRepresentation(uint32_t frame_duration,
383  uint32_t timescale) override {
384  adaptation_set_->OnSetFrameRateForRepresentation(representation_id_,
385  frame_duration, timescale);
386  }
387 
388  private:
389  const uint32_t representation_id_;
390  AdaptationSet* const adaptation_set_;
391 
392  DISALLOW_COPY_AND_ASSIGN(RepresentationStateChangeListenerImpl);
393 };
394 
395 } // namespace
396 
397 MpdBuilder::MpdBuilder(MpdType type, const MpdOptions& mpd_options)
398  : type_(type),
399  mpd_options_(mpd_options),
400  adaptation_sets_deleter_(&adaptation_sets_) {}
401 
402 MpdBuilder::~MpdBuilder() {}
403 
404 void MpdBuilder::AddBaseUrl(const std::string& base_url) {
405  base_urls_.push_back(base_url);
406 }
407 
408 AdaptationSet* MpdBuilder::AddAdaptationSet(const std::string& lang) {
409  scoped_ptr<AdaptationSet> adaptation_set(
410  new AdaptationSet(adaptation_set_counter_.GetNext(), lang, mpd_options_,
411  type_, &representation_counter_));
412 
413  DCHECK(adaptation_set);
414  adaptation_sets_.push_back(adaptation_set.get());
415  return adaptation_set.release();
416 }
417 
419  DCHECK(output_file);
420  return WriteMpdToOutput(output_file);
421 }
422 
423 bool MpdBuilder::ToString(std::string* output) {
424  DCHECK(output);
425  return WriteMpdToOutput(output);
426 }
427 template <typename OutputType>
428 bool MpdBuilder::WriteMpdToOutput(OutputType* output) {
429  static LibXmlInitializer lib_xml_initializer;
430 
431  xml::scoped_xml_ptr<xmlDoc> doc(GenerateMpd());
432  if (!doc.get())
433  return false;
434 
435  static const int kNiceFormat = 1;
436  int doc_str_size = 0;
437  xmlChar* doc_str = NULL;
438  xmlDocDumpFormatMemoryEnc(doc.get(), &doc_str, &doc_str_size, "UTF-8",
439  kNiceFormat);
440 
441  bool result = WriteXmlCharArrayToOutput(doc_str, doc_str_size, output);
442  xmlFree(doc_str);
443 
444  // Cleanup, free the doc.
445  doc.reset();
446  return result;
447 }
448 
449 xmlDocPtr MpdBuilder::GenerateMpd() {
450  // Setup nodes.
451  static const char kXmlVersion[] = "1.0";
452  xml::scoped_xml_ptr<xmlDoc> doc(xmlNewDoc(BAD_CAST kXmlVersion));
453  XmlNode mpd("MPD");
454 
455  // Iterate thru AdaptationSets and add them to one big Period element.
456  XmlNode period("Period");
457  std::list<AdaptationSet*>::iterator adaptation_sets_it =
458  adaptation_sets_.begin();
459  for (; adaptation_sets_it != adaptation_sets_.end(); ++adaptation_sets_it) {
460  xml::scoped_xml_ptr<xmlNode> child((*adaptation_sets_it)->GetXml());
461  if (!child.get() || !period.AddChild(child.Pass()))
462  return NULL;
463  }
464 
465  // Add baseurls to MPD.
466  std::list<std::string>::const_iterator base_urls_it = base_urls_.begin();
467  for (; base_urls_it != base_urls_.end(); ++base_urls_it) {
468  XmlNode base_url("BaseURL");
469  base_url.SetContent(*base_urls_it);
470 
471  if (!mpd.AddChild(base_url.PassScopedPtr()))
472  return NULL;
473  }
474 
475  if (type_ == kDynamic) {
476  // This is the only Period and it is a regular period.
477  period.SetStringAttribute("start", "PT0S");
478  }
479 
480  if (!mpd.AddChild(period.PassScopedPtr()))
481  return NULL;
482 
483  AddMpdNameSpaceInfo(&mpd);
484  AddCommonMpdInfo(&mpd);
485  switch (type_) {
486  case kStatic:
487  AddStaticMpdInfo(&mpd);
488  break;
489  case kDynamic:
490  AddDynamicMpdInfo(&mpd);
491  break;
492  default:
493  NOTREACHED() << "Unknown MPD type: " << type_;
494  break;
495  }
496 
497  DCHECK(doc);
498  std::string version_string =
499  "Generated with https://github.com/google/edash-packager version " +
500  mpd_options_.packager_version_string;
501  xml::scoped_xml_ptr<xmlNode> comment(
502  xmlNewDocComment(doc.get(), BAD_CAST version_string.c_str()));
503  xmlDocSetRootElement(doc.get(), comment.get());
504  xmlAddSibling(comment.release(), mpd.Release());
505  return doc.release();
506 }
507 
508 void MpdBuilder::AddCommonMpdInfo(XmlNode* mpd_node) {
509  if (Positive(mpd_options_.min_buffer_time)) {
510  mpd_node->SetStringAttribute(
511  "minBufferTime", SecondsToXmlDuration(mpd_options_.min_buffer_time));
512  } else {
513  LOG(ERROR) << "minBufferTime value not specified.";
514  // TODO(tinskip): Propagate error.
515  }
516 }
517 
518 void MpdBuilder::AddStaticMpdInfo(XmlNode* mpd_node) {
519  DCHECK(mpd_node);
520  DCHECK_EQ(MpdBuilder::kStatic, type_);
521 
522  static const char kStaticMpdType[] = "static";
523  static const char kStaticMpdProfile[] =
524  "urn:mpeg:dash:profile:isoff-on-demand:2011";
525  mpd_node->SetStringAttribute("type", kStaticMpdType);
526  mpd_node->SetStringAttribute("profiles", kStaticMpdProfile);
527  mpd_node->SetStringAttribute(
528  "mediaPresentationDuration",
529  SecondsToXmlDuration(GetStaticMpdDuration(mpd_node)));
530 }
531 
532 void MpdBuilder::AddDynamicMpdInfo(XmlNode* mpd_node) {
533  DCHECK(mpd_node);
534  DCHECK_EQ(MpdBuilder::kDynamic, type_);
535 
536  static const char kDynamicMpdType[] = "dynamic";
537  static const char kDynamicMpdProfile[] =
538  "urn:mpeg:dash:profile:isoff-live:2011";
539  mpd_node->SetStringAttribute("type", kDynamicMpdType);
540  mpd_node->SetStringAttribute("profiles", kDynamicMpdProfile);
541 
542  // 'availabilityStartTime' is required for dynamic profile. Calculate if
543  // not already calculated.
544  if (availability_start_time_.empty()) {
545  double earliest_presentation_time;
546  if (GetEarliestTimestamp(&earliest_presentation_time)) {
547  availability_start_time_ =
548  XmlDateTimeNowWithOffset(mpd_options_.availability_time_offset -
549  std::ceil(earliest_presentation_time));
550  } else {
551  LOG(ERROR) << "Could not determine the earliest segment presentation "
552  "time for availabilityStartTime calculation.";
553  // TODO(tinskip). Propagate an error.
554  }
555  }
556  if (!availability_start_time_.empty())
557  mpd_node->SetStringAttribute("availabilityStartTime",
558  availability_start_time_);
559 
560  if (Positive(mpd_options_.minimum_update_period)) {
561  mpd_node->SetStringAttribute(
562  "minimumUpdatePeriod",
563  SecondsToXmlDuration(mpd_options_.minimum_update_period));
564  } else {
565  LOG(WARNING) << "The profile is dynamic but no minimumUpdatePeriod "
566  "specified.";
567  }
568 
569  SetIfPositive("timeShiftBufferDepth", mpd_options_.time_shift_buffer_depth,
570  mpd_node);
571  SetIfPositive("suggestedPresentationDelay",
572  mpd_options_.suggested_presentation_delay, mpd_node);
573 }
574 
575 float MpdBuilder::GetStaticMpdDuration(XmlNode* mpd_node) {
576  DCHECK(mpd_node);
577  DCHECK_EQ(MpdBuilder::kStatic, type_);
578 
579  xmlNodePtr period_node = FindPeriodNode(mpd_node);
580  DCHECK(period_node) << "Period element must be a child of mpd_node.";
581  DCHECK(IsPeriodNode(period_node));
582 
583  // Attribute mediaPresentationDuration must be present for 'static' MPD. So
584  // setting "PT0S" is required even if none of the representaions have duration
585  // attribute.
586  float max_duration = 0.0f;
587  for (xmlNodePtr adaptation_set = xmlFirstElementChild(period_node);
588  adaptation_set; adaptation_set = xmlNextElementSibling(adaptation_set)) {
589  for (xmlNodePtr representation = xmlFirstElementChild(adaptation_set);
590  representation;
591  representation = xmlNextElementSibling(representation)) {
592  float duration = 0.0f;
593  if (GetDurationAttribute(representation, &duration)) {
594  max_duration = max_duration > duration ? max_duration : duration;
595 
596  // 'duration' attribute is there only to help generate MPD, not
597  // necessary for MPD, remove the attribute.
598  xmlUnsetProp(representation, BAD_CAST "duration");
599  }
600  }
601  }
602 
603  return max_duration;
604 }
605 
606 bool MpdBuilder::GetEarliestTimestamp(double* timestamp_seconds) {
607  DCHECK(timestamp_seconds);
608 
609  double earliest_timestamp(-1);
610  for (std::list<AdaptationSet*>::const_iterator iter =
611  adaptation_sets_.begin();
612  iter != adaptation_sets_.end(); ++iter) {
613  double timestamp;
614  if ((*iter)->GetEarliestTimestamp(&timestamp) &&
615  ((earliest_timestamp < 0) || (timestamp < earliest_timestamp))) {
616  earliest_timestamp = timestamp;
617  }
618  }
619  if (earliest_timestamp < 0)
620  return false;
621 
622  *timestamp_seconds = earliest_timestamp;
623  return true;
624 }
625 
626 void MpdBuilder::MakePathsRelativeToMpd(const std::string& mpd_path,
627  MediaInfo* media_info) {
628  DCHECK(media_info);
629  const std::string kFileProtocol("file://");
630  std::string mpd_file_path = (mpd_path.find(kFileProtocol) == 0)
631  ? mpd_path.substr(kFileProtocol.size())
632  : mpd_path;
633 
634  if (!mpd_file_path.empty()) {
635  std::string mpd_dir(
636  FilePath(mpd_file_path).DirName().AsEndingWithSeparator().value());
637  if (!mpd_dir.empty()) {
638  if (media_info->has_media_file_name()) {
639  media_info->set_media_file_name(
640  MakePathRelative(media_info->media_file_name(), mpd_dir));
641  }
642  if (media_info->has_init_segment_name()) {
643  media_info->set_init_segment_name(
644  MakePathRelative(media_info->init_segment_name(), mpd_dir));
645  }
646  if (media_info->has_segment_template()) {
647  media_info->set_segment_template(
648  MakePathRelative(media_info->segment_template(), mpd_dir));
649  }
650  }
651  }
652 }
653 
654 AdaptationSet::AdaptationSet(uint32_t adaptation_set_id,
655  const std::string& lang,
656  const MpdOptions& mpd_options,
657  MpdBuilder::MpdType mpd_type,
658  base::AtomicSequenceNumber* counter)
659  : representations_deleter_(&representations_),
660  representation_counter_(counter),
661  id_(adaptation_set_id),
662  lang_(lang),
663  mpd_options_(mpd_options),
664  mpd_type_(mpd_type),
665  group_(kAdaptationSetGroupNotSet),
666  segments_aligned_(kSegmentAlignmentUnknown),
667  force_set_segment_alignment_(false) {
668  DCHECK(counter);
669 }
670 
671 AdaptationSet::~AdaptationSet() {}
672 
673 Representation* AdaptationSet::AddRepresentation(const MediaInfo& media_info) {
674  const uint32_t representation_id = representation_counter_->GetNext();
675  // Note that AdaptationSet outlive Representation, so this object
676  // will die before AdaptationSet.
677  scoped_ptr<RepresentationStateChangeListener> listener(
678  new RepresentationStateChangeListenerImpl(representation_id, this));
679  scoped_ptr<Representation> representation(new Representation(
680  media_info, mpd_options_, representation_id, listener.Pass()));
681 
682  if (!representation->Init())
683  return NULL;
684 
685  // For videos, record the width, height, and the frame rate to calculate the
686  // max {width,height,framerate} required for DASH IOP.
687  if (media_info.has_video_info()) {
688  const MediaInfo::VideoInfo& video_info = media_info.video_info();
689  DCHECK(video_info.has_width());
690  DCHECK(video_info.has_height());
691  video_widths_.insert(video_info.width());
692  video_heights_.insert(video_info.height());
693 
694  if (video_info.has_time_scale() && video_info.has_frame_duration())
695  RecordFrameRate(video_info.frame_duration(), video_info.time_scale());
696 
697  AddPictureAspectRatio(video_info, &picture_aspect_ratio_);
698  }
699 
700  if (media_info.has_video_info()) {
701  content_type_ = "video";
702  } else if (media_info.has_audio_info()) {
703  content_type_ = "audio";
704  } else if (media_info.has_text_info()) {
705  content_type_ = "text";
706 
707  if (media_info.text_info().has_type() &&
708  (media_info.text_info().type() != MediaInfo::TextInfo::UNKNOWN)) {
709  roles_.insert(MediaInfoTextTypeToRole(media_info.text_info().type()));
710  }
711  }
712 
713  representations_.push_back(representation.get());
714  return representation.release();
715 }
716 
718  const ContentProtectionElement& content_protection_element) {
719  content_protection_elements_.push_back(content_protection_element);
720  RemoveDuplicateAttributes(&content_protection_elements_.back());
721 }
722 
723 void AdaptationSet::UpdateContentProtectionPssh(const std::string& drm_uuid,
724  const std::string& pssh) {
725  UpdateContentProtectionPsshHelper(drm_uuid, pssh,
726  &content_protection_elements_);
727 }
728 
729 void AdaptationSet::AddRole(Role role) {
730  roles_.insert(role);
731 }
732 
733 // Creates a copy of <AdaptationSet> xml element, iterate thru all the
734 // <Representation> (child) elements and add them to the copy.
735 // Set all the attributes first and then add the children elements so that flags
736 // can be passed to Representation to avoid setting redundant attributes. For
737 // example, if AdaptationSet@width is set, then Representation@width is
738 // redundant and should not be set.
739 xml::scoped_xml_ptr<xmlNode> AdaptationSet::GetXml() {
740  AdaptationSetXmlNode adaptation_set;
741 
742  bool suppress_representation_width = false;
743  bool suppress_representation_height = false;
744  bool suppress_representation_frame_rate = false;
745 
746  adaptation_set.SetId(id_);
747  adaptation_set.SetStringAttribute("contentType", content_type_);
748  if (!lang_.empty() && lang_ != "und") {
749  adaptation_set.SetStringAttribute("lang", LanguageToShortestForm(lang_));
750  }
751 
752  // Note that std::{set,map} are ordered, so the last element is the max value.
753  if (video_widths_.size() == 1) {
754  suppress_representation_width = true;
755  adaptation_set.SetIntegerAttribute("width", *video_widths_.begin());
756  } else if (video_widths_.size() > 1) {
757  adaptation_set.SetIntegerAttribute("maxWidth", *video_widths_.rbegin());
758  }
759  if (video_heights_.size() == 1) {
760  suppress_representation_height = true;
761  adaptation_set.SetIntegerAttribute("height", *video_heights_.begin());
762  } else if (video_heights_.size() > 1) {
763  adaptation_set.SetIntegerAttribute("maxHeight", *video_heights_.rbegin());
764  }
765 
766  if (video_frame_rates_.size() == 1) {
767  suppress_representation_frame_rate = true;
768  adaptation_set.SetStringAttribute("frameRate",
769  video_frame_rates_.begin()->second);
770  } else if (video_frame_rates_.size() > 1) {
771  adaptation_set.SetStringAttribute("maxFrameRate",
772  video_frame_rates_.rbegin()->second);
773  }
774 
775  // Note: must be checked before checking segments_aligned_ (below). So that
776  // segments_aligned_ is set before checking below.
777  if (mpd_type_ == MpdBuilder::kStatic) {
778  CheckVodSegmentAlignment();
779  }
780 
781  if (segments_aligned_ == kSegmentAlignmentTrue) {
782  adaptation_set.SetStringAttribute(mpd_type_ == MpdBuilder::kStatic
783  ? "subsegmentAlignment"
784  : "segmentAlignment",
785  "true");
786  }
787 
788  if (picture_aspect_ratio_.size() == 1)
789  adaptation_set.SetStringAttribute("par", *picture_aspect_ratio_.begin());
790 
791  if (group_ >= 0)
792  adaptation_set.SetIntegerAttribute("group", group_);
793 
794  if (!adaptation_set.AddContentProtectionElements(
795  content_protection_elements_)) {
796  return xml::scoped_xml_ptr<xmlNode>();
797  }
798  for (AdaptationSet::Role role : roles_)
799  adaptation_set.AddRoleElement("urn:mpeg:dash:role:2011", RoleToText(role));
800 
801  for (Representation* representation : representations_) {
802  if (suppress_representation_width)
803  representation->SuppressOnce(Representation::kSuppressWidth);
804  if (suppress_representation_height)
805  representation->SuppressOnce(Representation::kSuppressHeight);
806  if (suppress_representation_frame_rate)
807  representation->SuppressOnce(Representation::kSuppressFrameRate);
808  xml::scoped_xml_ptr<xmlNode> child(representation->GetXml());
809  if (!child || !adaptation_set.AddChild(child.Pass()))
810  return xml::scoped_xml_ptr<xmlNode>();
811  }
812 
813  return adaptation_set.PassScopedPtr();
814 }
815 
816 void AdaptationSet::ForceSetSegmentAlignment(bool segment_alignment) {
817  segments_aligned_ =
818  segment_alignment ? kSegmentAlignmentTrue : kSegmentAlignmentFalse;
819  force_set_segment_alignment_ = true;
820 }
821 
822 void AdaptationSet::SetGroup(int group_number) {
823  group_ = group_number;
824 }
825 
826 int AdaptationSet::Group() const {
827  return group_;
828 }
829 
830 // Check segmentAlignment for Live here. Storing all start_time and duration
831 // will out-of-memory because there's no way of knowing when it will end.
832 // VOD subsegmentAlignment check is *not* done here because it is possible
833 // that some Representations might not have been added yet (e.g. a thread is
834 // assigned per muxer so one might run faster than others).
835 // To be clear, for Live, all Representations should be added before a
836 // segment is added.
837 void AdaptationSet::OnNewSegmentForRepresentation(uint32_t representation_id,
838  uint64_t start_time,
839  uint64_t duration) {
840  if (mpd_type_ == MpdBuilder::kDynamic) {
841  CheckLiveSegmentAlignment(representation_id, start_time, duration);
842  } else {
843  representation_segment_start_times_[representation_id].push_back(
844  start_time);
845  }
846 }
847 
849  uint32_t representation_id,
850  uint32_t frame_duration,
851  uint32_t timescale) {
852  RecordFrameRate(frame_duration, timescale);
853 }
854 
855 bool AdaptationSet::GetEarliestTimestamp(double* timestamp_seconds) {
856  DCHECK(timestamp_seconds);
857 
858  double earliest_timestamp(-1);
859  for (std::list<Representation*>::const_iterator iter =
860  representations_.begin();
861  iter != representations_.end(); ++iter) {
862  double timestamp;
863  if ((*iter)->GetEarliestTimestamp(&timestamp) &&
864  ((earliest_timestamp < 0) || (timestamp < earliest_timestamp))) {
865  earliest_timestamp = timestamp;
866  }
867  }
868  if (earliest_timestamp < 0)
869  return false;
870 
871  *timestamp_seconds = earliest_timestamp;
872  return true;
873 }
874 
875 // This implementation assumes that each representations' segments' are
876 // contiguous.
877 // Also assumes that all Representations are added before this is called.
878 // This checks whether the first elements of the lists in
879 // representation_segment_start_times_ are aligned.
880 // For example, suppose this method was just called with args rep_id=2
881 // start_time=1.
882 // 1 -> [1, 100, 200]
883 // 2 -> [1]
884 // The timestamps of the first elements match, so this flags
885 // segments_aligned_=true.
886 // Also since the first segment start times match, the first element of all the
887 // lists are removed, so the map of lists becomes:
888 // 1 -> [100, 200]
889 // 2 -> []
890 // Note that there could be false positives.
891 // e.g. just got rep_id=3 start_time=1 duration=300, and the duration of the
892 // whole AdaptationSet is 300.
893 // 1 -> [1, 100, 200]
894 // 2 -> [1, 90, 100]
895 // 3 -> [1]
896 // They are not aligned but this will be marked as aligned.
897 // But since this is unlikely to happen in the packager (and to save
898 // computation), this isn't handled at the moment.
899 void AdaptationSet::CheckLiveSegmentAlignment(uint32_t representation_id,
900  uint64_t start_time,
901  uint64_t /* duration */) {
902  if (segments_aligned_ == kSegmentAlignmentFalse ||
903  force_set_segment_alignment_) {
904  return;
905  }
906 
907  std::list<uint64_t>& representation_start_times =
908  representation_segment_start_times_[representation_id];
909  representation_start_times.push_back(start_time);
910  // There's no way to detemine whether the segments are aligned if some
911  // representations do not have any segments.
912  if (representation_segment_start_times_.size() != representations_.size())
913  return;
914 
915  DCHECK(!representation_start_times.empty());
916  const uint64_t expected_start_time = representation_start_times.front();
917  for (RepresentationTimeline::const_iterator it =
918  representation_segment_start_times_.begin();
919  it != representation_segment_start_times_.end(); ++it) {
920  // If there are no entries in a list, then there is no way for the
921  // segment alignment status to change.
922  // Note that it can be empty because entries get deleted below.
923  if (it->second.empty())
924  return;
925 
926  if (expected_start_time != it->second.front()) {
927  // Flag as false and clear the start times data, no need to keep it
928  // around.
929  segments_aligned_ = kSegmentAlignmentFalse;
930  representation_segment_start_times_.clear();
931  return;
932  }
933  }
934  segments_aligned_ = kSegmentAlignmentTrue;
935 
936  for (RepresentationTimeline::iterator it =
937  representation_segment_start_times_.begin();
938  it != representation_segment_start_times_.end(); ++it) {
939  it->second.pop_front();
940  }
941 }
942 
943 // Make sure all segements start times match for all Representations.
944 // This assumes that the segments are contiguous.
945 void AdaptationSet::CheckVodSegmentAlignment() {
946  if (segments_aligned_ == kSegmentAlignmentFalse ||
947  force_set_segment_alignment_) {
948  return;
949  }
950  if (representation_segment_start_times_.empty())
951  return;
952  if (representation_segment_start_times_.size() == 1) {
953  segments_aligned_ = kSegmentAlignmentTrue;
954  return;
955  }
956 
957  // This is not the most efficient implementation to compare the values
958  // because expected_time_line is compared against all other time lines, but
959  // probably the most readable.
960  const std::list<uint64_t>& expected_time_line =
961  representation_segment_start_times_.begin()->second;
962 
963  bool all_segment_time_line_same_length = true;
964  // Note that the first entry is skipped because it is expected_time_line.
965  RepresentationTimeline::const_iterator it =
966  representation_segment_start_times_.begin();
967  for (++it; it != representation_segment_start_times_.end(); ++it) {
968  const std::list<uint64_t>& other_time_line = it->second;
969  if (expected_time_line.size() != other_time_line.size()) {
970  all_segment_time_line_same_length = false;
971  }
972 
973  const std::list<uint64_t>* longer_list = &other_time_line;
974  const std::list<uint64_t>* shorter_list = &expected_time_line;
975  if (expected_time_line.size() > other_time_line.size()) {
976  shorter_list = &other_time_line;
977  longer_list = &expected_time_line;
978  }
979 
980  if (!std::equal(shorter_list->begin(), shorter_list->end(),
981  longer_list->begin())) {
982  // Some segments are definitely unaligned.
983  segments_aligned_ = kSegmentAlignmentFalse;
984  representation_segment_start_times_.clear();
985  return;
986  }
987  }
988 
989  // TODO(rkuroiwa): The right way to do this is to also check the durations.
990  // For example:
991  // (a) 3 4 5
992  // (b) 3 4 5 6
993  // could be true or false depending on the length of the third segment of (a).
994  // i.e. if length of the third segment is 2, then this is not aligned.
995  if (!all_segment_time_line_same_length) {
996  segments_aligned_ = kSegmentAlignmentUnknown;
997  return;
998  }
999 
1000  segments_aligned_ = kSegmentAlignmentTrue;
1001 }
1002 
1003 // Since all AdaptationSet cares about is the maxFrameRate, representation_id
1004 // is not passed to this method.
1005 void AdaptationSet::RecordFrameRate(uint32_t frame_duration,
1006  uint32_t timescale) {
1007  if (frame_duration == 0) {
1008  LOG(ERROR) << "Frame duration is 0 and cannot be set.";
1009  return;
1010  }
1011  video_frame_rates_[static_cast<double>(timescale) / frame_duration] =
1012  base::IntToString(timescale) + "/" + base::IntToString(frame_duration);
1013 }
1014 
1016  const MediaInfo& media_info,
1017  const MpdOptions& mpd_options,
1018  uint32_t id,
1019  scoped_ptr<RepresentationStateChangeListener> state_change_listener)
1020  : media_info_(media_info),
1021  id_(id),
1022  bandwidth_estimator_(BandwidthEstimator::kUseAllBlocks),
1023  mpd_options_(mpd_options),
1024  start_number_(1),
1025  state_change_listener_(state_change_listener.Pass()),
1026  output_suppression_flags_(0) {}
1027 
1028 Representation::~Representation() {}
1029 
1031  if (!AtLeastOneTrue(media_info_.has_video_info(),
1032  media_info_.has_audio_info(),
1033  media_info_.has_text_info())) {
1034  // This is an error. Segment information can be in AdaptationSet, Period, or
1035  // MPD but the interface does not provide a way to set them.
1036  // See 5.3.9.1 ISO 23009-1:2012 for segment info.
1037  LOG(ERROR) << "Representation needs one of video, audio, or text.";
1038  return false;
1039  }
1040 
1041  if (MoreThanOneTrue(media_info_.has_video_info(),
1042  media_info_.has_audio_info(),
1043  media_info_.has_text_info())) {
1044  LOG(ERROR) << "Only one of VideoInfo, AudioInfo, or TextInfo can be set.";
1045  return false;
1046  }
1047 
1048  if (media_info_.container_type() == MediaInfo::CONTAINER_UNKNOWN) {
1049  LOG(ERROR) << "'container_type' in MediaInfo cannot be CONTAINER_UNKNOWN.";
1050  return false;
1051  }
1052 
1053  if (media_info_.has_video_info()) {
1054  mime_type_ = GetVideoMimeType();
1055  if (!HasRequiredVideoFields(media_info_.video_info())) {
1056  LOG(ERROR) << "Missing required fields to create a video Representation.";
1057  return false;
1058  }
1059  } else if (media_info_.has_audio_info()) {
1060  mime_type_ = GetAudioMimeType();
1061  } else if (media_info_.has_text_info()) {
1062  mime_type_ = GetTextMimeType();
1063  }
1064 
1065  if (mime_type_.empty())
1066  return false;
1067 
1068  codecs_ = GetCodecs(media_info_);
1069  return true;
1070 }
1071 
1073  const ContentProtectionElement& content_protection_element) {
1074  content_protection_elements_.push_back(content_protection_element);
1075  RemoveDuplicateAttributes(&content_protection_elements_.back());
1076 }
1077 
1078 void Representation::UpdateContentProtectionPssh(const std::string& drm_uuid,
1079  const std::string& pssh) {
1080  UpdateContentProtectionPsshHelper(drm_uuid, pssh,
1081  &content_protection_elements_);
1082 }
1083 
1084 void Representation::AddNewSegment(uint64_t start_time,
1085  uint64_t duration,
1086  uint64_t size) {
1087  if (start_time == 0 && duration == 0) {
1088  LOG(WARNING) << "Got segment with start_time and duration == 0. Ignoring.";
1089  return;
1090  }
1091 
1092  if (state_change_listener_)
1093  state_change_listener_->OnNewSegmentForRepresentation(start_time, duration);
1094  if (IsContiguous(start_time, duration, size)) {
1095  ++segment_infos_.back().repeat;
1096  } else {
1097  SegmentInfo s = {start_time, duration, /* Not repeat. */ 0};
1098  segment_infos_.push_back(s);
1099  }
1100 
1101  bandwidth_estimator_.AddBlock(
1102  size, static_cast<double>(duration) / media_info_.reference_time_scale());
1103 
1104  SlideWindow();
1105  DCHECK_GE(segment_infos_.size(), 1u);
1106 }
1107 
1108 void Representation::SetSampleDuration(uint32_t sample_duration) {
1109  if (media_info_.has_video_info()) {
1110  media_info_.mutable_video_info()->set_frame_duration(sample_duration);
1111  if (state_change_listener_) {
1112  state_change_listener_->OnSetFrameRateForRepresentation(
1113  sample_duration, media_info_.video_info().time_scale());
1114  }
1115  }
1116 }
1117 
1118 // Uses info in |media_info_| and |content_protection_elements_| to create a
1119 // "Representation" node.
1120 // MPD schema has strict ordering. The following must be done in order.
1121 // AddVideoInfo() (possibly adds FramePacking elements), AddAudioInfo() (Adds
1122 // AudioChannelConfig elements), AddContentProtectionElements*(), and
1123 // AddVODOnlyInfo() (Adds segment info).
1124 xml::scoped_xml_ptr<xmlNode> Representation::GetXml() {
1125  if (!HasRequiredMediaInfoFields()) {
1126  LOG(ERROR) << "MediaInfo missing required fields.";
1127  return xml::scoped_xml_ptr<xmlNode>();
1128  }
1129 
1130  const uint64_t bandwidth = media_info_.has_bandwidth()
1131  ? media_info_.bandwidth()
1132  : bandwidth_estimator_.Estimate();
1133 
1134  DCHECK(!(HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)));
1135 
1136  RepresentationXmlNode representation;
1137  // Mandatory fields for Representation.
1138  representation.SetId(id_);
1139  representation.SetIntegerAttribute("bandwidth", bandwidth);
1140  if (!codecs_.empty())
1141  representation.SetStringAttribute("codecs", codecs_);
1142  representation.SetStringAttribute("mimeType", mime_type_);
1143 
1144  const bool has_video_info = media_info_.has_video_info();
1145  const bool has_audio_info = media_info_.has_audio_info();
1146 
1147  if (has_video_info &&
1148  !representation.AddVideoInfo(
1149  media_info_.video_info(),
1150  !(output_suppression_flags_ & kSuppressWidth),
1151  !(output_suppression_flags_ & kSuppressHeight),
1152  !(output_suppression_flags_ & kSuppressFrameRate))) {
1153  LOG(ERROR) << "Failed to add video info to Representation XML.";
1154  return xml::scoped_xml_ptr<xmlNode>();
1155  }
1156 
1157  if (has_audio_info &&
1158  !representation.AddAudioInfo(media_info_.audio_info())) {
1159  LOG(ERROR) << "Failed to add audio info to Representation XML.";
1160  return xml::scoped_xml_ptr<xmlNode>();
1161  }
1162 
1163  if (!representation.AddContentProtectionElements(
1164  content_protection_elements_)) {
1165  return xml::scoped_xml_ptr<xmlNode>();
1166  }
1167 
1168  if (HasVODOnlyFields(media_info_) &&
1169  !representation.AddVODOnlyInfo(media_info_)) {
1170  LOG(ERROR) << "Failed to add VOD segment info.";
1171  return xml::scoped_xml_ptr<xmlNode>();
1172  }
1173 
1174  if (HasLiveOnlyFields(media_info_) &&
1175  !representation.AddLiveOnlyInfo(media_info_, segment_infos_,
1176  start_number_)) {
1177  LOG(ERROR) << "Failed to add Live info.";
1178  return xml::scoped_xml_ptr<xmlNode>();
1179  }
1180  // TODO(rkuroiwa): It is likely that all representations have the exact same
1181  // SegmentTemplate. Optimize and propagate the tag up to AdaptationSet level.
1182 
1183  output_suppression_flags_ = 0;
1184  return representation.PassScopedPtr();
1185 }
1186 
1187 void Representation::SuppressOnce(SuppressFlag flag) {
1188  output_suppression_flags_ |= flag;
1189 }
1190 
1191 bool Representation::HasRequiredMediaInfoFields() {
1192  if (HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)) {
1193  LOG(ERROR) << "MediaInfo cannot have both VOD and Live fields.";
1194  return false;
1195  }
1196 
1197  if (!media_info_.has_container_type()) {
1198  LOG(ERROR) << "MediaInfo missing required field: container_type.";
1199  return false;
1200  }
1201 
1202  if (HasVODOnlyFields(media_info_) && !media_info_.has_bandwidth()) {
1203  LOG(ERROR) << "Missing 'bandwidth' field. MediaInfo requires bandwidth for "
1204  "static profile for generating a valid MPD.";
1205  return false;
1206  }
1207 
1208  VLOG_IF(3, HasLiveOnlyFields(media_info_) && !media_info_.has_bandwidth())
1209  << "MediaInfo missing field 'bandwidth'. Using estimated from "
1210  "segment size.";
1211 
1212  return true;
1213 }
1214 
1215 bool Representation::IsContiguous(uint64_t start_time,
1216  uint64_t duration,
1217  uint64_t size) const {
1218  if (segment_infos_.empty())
1219  return false;
1220 
1221  // Contiguous segment.
1222  const SegmentInfo& previous = segment_infos_.back();
1223  const uint64_t previous_segment_end_time =
1224  previous.start_time + previous.duration * (previous.repeat + 1);
1225  if (previous_segment_end_time == start_time &&
1226  segment_infos_.back().duration == duration) {
1227  return true;
1228  }
1229 
1230  // No out of order segments.
1231  const uint64_t previous_segment_start_time =
1232  previous.start_time + previous.duration * previous.repeat;
1233  if (previous_segment_start_time >= start_time) {
1234  LOG(ERROR) << "Segments should not be out of order segment. Adding segment "
1235  "with start_time == "
1236  << start_time << " but the previous segment starts at "
1237  << previous.start_time << ".";
1238  return false;
1239  }
1240 
1241  // A gap since previous.
1242  const uint64_t kRoundingErrorGrace = 5;
1243  if (previous_segment_end_time + kRoundingErrorGrace < start_time) {
1244  LOG(WARNING) << "Found a gap of size "
1245  << (start_time - previous_segment_end_time)
1246  << " > kRoundingErrorGrace (" << kRoundingErrorGrace
1247  << "). The new segment starts at " << start_time
1248  << " but the previous segment ends at "
1249  << previous_segment_end_time << ".";
1250  return false;
1251  }
1252 
1253  // No overlapping segments.
1254  if (start_time < previous_segment_end_time - kRoundingErrorGrace) {
1255  LOG(WARNING)
1256  << "Segments should not be overlapping. The new segment starts at "
1257  << start_time << " but the previous segment ends at "
1258  << previous_segment_end_time << ".";
1259  return false;
1260  }
1261 
1262  // Within rounding error grace but technically not contiguous in terms of MPD.
1263  return false;
1264 }
1265 
1266 void Representation::SlideWindow() {
1267  DCHECK(!segment_infos_.empty());
1268  if (mpd_options_.time_shift_buffer_depth <= 0.0)
1269  return;
1270 
1271  const uint32_t time_scale = GetTimeScale(media_info_);
1272  DCHECK_GT(time_scale, 0u);
1273 
1274  uint64_t time_shift_buffer_depth =
1275  static_cast<uint64_t>(mpd_options_.time_shift_buffer_depth * time_scale);
1276 
1277  // The start time of the latest segment is considered the current_play_time,
1278  // and this should guarantee that the latest segment will stay in the list.
1279  const uint64_t current_play_time = LatestSegmentStartTime(segment_infos_);
1280  if (current_play_time <= time_shift_buffer_depth)
1281  return;
1282 
1283  const uint64_t timeshift_limit = current_play_time - time_shift_buffer_depth;
1284 
1285  // First remove all the SegmentInfos that are completely out of range, by
1286  // looking at the very last segment's end time.
1287  std::list<SegmentInfo>::iterator first = segment_infos_.begin();
1288  std::list<SegmentInfo>::iterator last = first;
1289  size_t num_segments_removed = 0;
1290  for (; last != segment_infos_.end(); ++last) {
1291  const uint64_t last_segment_end_time = LastSegmentEndTime(*last);
1292  if (timeshift_limit < last_segment_end_time)
1293  break;
1294  num_segments_removed += last->repeat + 1;
1295  }
1296  segment_infos_.erase(first, last);
1297  start_number_ += num_segments_removed;
1298 
1299  // Now some segment in the first SegmentInfo should be left in the list.
1300  SegmentInfo* first_segment_info = &segment_infos_.front();
1301  DCHECK_LE(timeshift_limit, LastSegmentEndTime(*first_segment_info));
1302 
1303  // Identify which segments should still be in the SegmentInfo.
1304  const int repeat_index =
1305  SearchTimedOutRepeatIndex(timeshift_limit, *first_segment_info);
1306  CHECK_GE(repeat_index, 0);
1307  if (repeat_index == 0)
1308  return;
1309 
1310  first_segment_info->start_time = first_segment_info->start_time +
1311  first_segment_info->duration * repeat_index;
1312 
1313  first_segment_info->repeat = first_segment_info->repeat - repeat_index;
1314  start_number_ += repeat_index;
1315 }
1316 
1317 std::string Representation::GetVideoMimeType() const {
1318  return GetMimeType("video", media_info_.container_type());
1319 }
1320 
1321 std::string Representation::GetAudioMimeType() const {
1322  return GetMimeType("audio", media_info_.container_type());
1323 }
1324 
1325 std::string Representation::GetTextMimeType() const {
1326  CHECK(media_info_.has_text_info());
1327  if (media_info_.text_info().format() == "ttml") {
1328  switch (media_info_.container_type()) {
1329  case MediaInfo::CONTAINER_TEXT:
1330  return "application/ttml+xml";
1331  case MediaInfo::CONTAINER_MP4:
1332  return "application/mp4";
1333  default:
1334  LOG(ERROR) << "Failed to determine MIME type for TTML container: "
1335  << media_info_.container_type();
1336  return "";
1337  }
1338  }
1339  if (media_info_.text_info().format() == "vtt") {
1340  if (media_info_.container_type() == MediaInfo::CONTAINER_TEXT) {
1341  return "text/vtt";
1342  }
1343  LOG(ERROR) << "Failed to determine MIME type for VTT container: "
1344  << media_info_.container_type();
1345  return "";
1346  }
1347 
1348  LOG(ERROR) << "Cannot determine MIME type for format: "
1349  << media_info_.text_info().format()
1350  << " container: " << media_info_.container_type();
1351  return "";
1352 }
1353 
1354 bool Representation::GetEarliestTimestamp(double* timestamp_seconds) {
1355  DCHECK(timestamp_seconds);
1356 
1357  if (segment_infos_.empty())
1358  return false;
1359 
1360  *timestamp_seconds = static_cast<double>(segment_infos_.begin()->start_time) /
1361  GetTimeScale(media_info_);
1362  return true;
1363 }
1364 
1365 } // namespace edash_packager
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)
Definition: mpd_builder.cc:654
Defines Mpd Options.
Definition: mpd_options.h:17
virtual int Group() const
Definition: mpd_builder.cc:826
virtual AdaptationSet * AddAdaptationSet(const std::string &lang)
Definition: mpd_builder.cc:408
xml::scoped_xml_ptr< xmlNode > GetXml()
Define an abstract file interface.
Definition: file.h:23
static void MakePathsRelativeToMpd(const std::string &mpd_path, MediaInfo *media_info)
Definition: mpd_builder.cc:626
virtual void ForceSetSegmentAlignment(bool segment_alignment)
Definition: mpd_builder.cc:816
virtual void SetSampleDuration(uint32_t sample_duration)
void AddBaseUrl(const std::string &base_url)
Definition: mpd_builder.cc:404
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)
Definition: mpd_builder.cc:822
virtual void AddContentProtectionElement(const ContentProtectionElement &element)
bool WriteMpdToFile(media::File *output_file)
Definition: mpd_builder.cc:418
void OnSetFrameRateForRepresentation(uint32_t representation_id, uint32_t frame_duration, uint32_t timescale)
Definition: mpd_builder.cc:848
virtual Representation * AddRepresentation(const MediaInfo &media_info)
Definition: mpd_builder.cc:673
xml::scoped_xml_ptr< xmlNode > GetXml()
Definition: mpd_builder.cc:739
void SuppressOnce(SuppressFlag flag)
virtual void UpdateContentProtectionPssh(const std::string &drm_uuid, const std::string &pssh)
Definition: mpd_builder.cc:723
virtual bool ToString(std::string *output)
Definition: mpd_builder.cc:423
virtual void AddRole(Role role)
Definition: mpd_builder.cc:729
MpdBuilder(MpdType type, const MpdOptions &mpd_options)
Definition: mpd_builder.cc:397
virtual void AddContentProtectionElement(const ContentProtectionElement &element)
Definition: mpd_builder.cc:717
void OnNewSegmentForRepresentation(uint32_t representation_id, uint64_t start_time, uint64_t duration)
Definition: mpd_builder.cc:837