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