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