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