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