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