Shaka Packager SDK
xml_node.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/xml/xml_node.h"
8 
9 #include <gflags/gflags.h>
10 
11 #include <limits>
12 #include <set>
13 
14 #include "packager/base/logging.h"
15 #include "packager/base/macros.h"
16 #include "packager/base/strings/string_number_conversions.h"
17 #include "packager/base/sys_byteorder.h"
18 #include "packager/mpd/base/media_info.pb.h"
19 #include "packager/mpd/base/mpd_utils.h"
20 #include "packager/mpd/base/segment_info.h"
21 
22 DEFINE_bool(segment_template_constant_duration,
23  false,
24  "Generates SegmentTemplate@duration if all segments except the "
25  "last one has the same duration if this flag is set to true.");
26 
27 namespace shaka {
28 
29 using xml::XmlNode;
30 typedef MediaInfo::AudioInfo AudioInfo;
31 typedef MediaInfo::VideoInfo VideoInfo;
32 
33 namespace {
34 const char kEC3Codec[] = "ec-3";
35 
36 std::string RangeToString(const Range& range) {
37  return base::Uint64ToString(range.begin()) + "-" +
38  base::Uint64ToString(range.end());
39 }
40 
41 // Check if segments are continuous and all segments except the last one are of
42 // the same duration.
43 bool IsTimelineConstantDuration(const std::list<SegmentInfo>& segment_infos,
44  uint32_t start_number) {
45  if (!FLAGS_segment_template_constant_duration)
46  return false;
47 
48  DCHECK(!segment_infos.empty());
49  if (segment_infos.size() > 2)
50  return false;
51 
52  const SegmentInfo& first_segment = segment_infos.front();
53  if (first_segment.start_time != first_segment.duration * (start_number - 1))
54  return false;
55 
56  if (segment_infos.size() == 1)
57  return true;
58 
59  const SegmentInfo& last_segment = segment_infos.back();
60  if (last_segment.repeat != 0)
61  return false;
62 
63  const int64_t expected_last_segment_start_time =
64  first_segment.start_time +
65  first_segment.duration * (first_segment.repeat + 1);
66  return expected_last_segment_start_time == last_segment.start_time;
67 }
68 
69 bool PopulateSegmentTimeline(const std::list<SegmentInfo>& segment_infos,
70  XmlNode* segment_timeline) {
71  for (const SegmentInfo& segment_info : segment_infos) {
72  XmlNode s_element("S");
73  s_element.SetIntegerAttribute("t", segment_info.start_time);
74  s_element.SetIntegerAttribute("d", segment_info.duration);
75  if (segment_info.repeat > 0)
76  s_element.SetIntegerAttribute("r", segment_info.repeat);
77 
78  CHECK(segment_timeline->AddChild(s_element.PassScopedPtr()));
79  }
80 
81  return true;
82 }
83 
84 void CollectNamespaceFromName(const std::string& name,
85  std::set<std::string>* namespaces) {
86  const size_t pos = name.find(':');
87  if (pos != std::string::npos)
88  namespaces->insert(name.substr(0, pos));
89 }
90 
91 void TraverseAttrsAndCollectNamespaces(const xmlAttr* attr,
92  std::set<std::string>* namespaces) {
93  for (const xmlAttr* cur_attr = attr; cur_attr; cur_attr = cur_attr->next) {
94  CollectNamespaceFromName(reinterpret_cast<const char*>(cur_attr->name),
95  namespaces);
96  }
97 }
98 
99 void TraverseNodesAndCollectNamespaces(const xmlNode* node,
100  std::set<std::string>* namespaces) {
101  for (const xmlNode* cur_node = node; cur_node; cur_node = cur_node->next) {
102  CollectNamespaceFromName(reinterpret_cast<const char*>(cur_node->name),
103  namespaces);
104 
105  TraverseNodesAndCollectNamespaces(cur_node->children, namespaces);
106  TraverseAttrsAndCollectNamespaces(cur_node->properties, namespaces);
107  }
108 }
109 
110 } // namespace
111 
112 namespace xml {
113 
114 XmlNode::XmlNode(const char* name) : node_(xmlNewNode(NULL, BAD_CAST name)) {
115  DCHECK(name);
116  DCHECK(node_);
117 }
118 
119 XmlNode::~XmlNode() {}
120 
121 bool XmlNode::AddChild(scoped_xml_ptr<xmlNode> child) {
122  DCHECK(node_);
123  DCHECK(child);
124  if (!xmlAddChild(node_.get(), child.get()))
125  return false;
126 
127  // Reaching here means the ownership of |child| transfered to |node_|.
128  // Release the pointer so that it doesn't get destructed in this scope.
129  ignore_result(child.release());
130  return true;
131 }
132 
133 bool XmlNode::AddElements(const std::vector<Element>& elements) {
134  for (size_t element_index = 0; element_index < elements.size();
135  ++element_index) {
136  const Element& child_element = elements[element_index];
137  XmlNode child_node(child_element.name.c_str());
138  for (std::map<std::string, std::string>::const_iterator attribute_it =
139  child_element.attributes.begin();
140  attribute_it != child_element.attributes.end(); ++attribute_it) {
141  child_node.SetStringAttribute(attribute_it->first.c_str(),
142  attribute_it->second);
143  }
144 
145  // Note that somehow |SetContent| needs to be called before |AddElements|
146  // otherwise the added children will be overwritten by the content.
147  child_node.SetContent(child_element.content);
148 
149  // Recursively set children for the child.
150  if (!child_node.AddElements(child_element.subelements))
151  return false;
152 
153  if (!xmlAddChild(node_.get(), child_node.GetRawPtr())) {
154  LOG(ERROR) << "Failed to set child " << child_element.name
155  << " to parent element "
156  << reinterpret_cast<const char*>(node_->name);
157  return false;
158  }
159  // Reaching here means the ownership of |child_node| transfered to |node_|.
160  // Release the pointer so that it doesn't get destructed in this scope.
161  ignore_result(child_node.Release());
162  }
163  return true;
164 }
165 
166 void XmlNode::SetStringAttribute(const char* attribute_name,
167  const std::string& attribute) {
168  DCHECK(node_);
169  DCHECK(attribute_name);
170  xmlSetProp(node_.get(), BAD_CAST attribute_name, BAD_CAST attribute.c_str());
171 }
172 
173 void XmlNode::SetIntegerAttribute(const char* attribute_name, uint64_t number) {
174  DCHECK(node_);
175  DCHECK(attribute_name);
176  xmlSetProp(node_.get(),
177  BAD_CAST attribute_name,
178  BAD_CAST (base::Uint64ToString(number).c_str()));
179 }
180 
181 void XmlNode::SetFloatingPointAttribute(const char* attribute_name,
182  double number) {
183  DCHECK(node_);
184  DCHECK(attribute_name);
185  xmlSetProp(node_.get(), BAD_CAST attribute_name,
186  BAD_CAST(base::DoubleToString(number).c_str()));
187 }
188 
189 void XmlNode::SetId(uint32_t id) {
190  SetIntegerAttribute("id", id);
191 }
192 
193 void XmlNode::SetContent(const std::string& content) {
194  DCHECK(node_);
195  xmlNodeSetContent(node_.get(), BAD_CAST content.c_str());
196 }
197 
198 std::set<std::string> XmlNode::ExtractReferencedNamespaces() {
199  std::set<std::string> namespaces;
200  TraverseNodesAndCollectNamespaces(node_.get(), &namespaces);
201  return namespaces;
202 }
203 
204 scoped_xml_ptr<xmlNode> XmlNode::PassScopedPtr() {
205  DVLOG(2) << "Passing node_.";
206  DCHECK(node_);
207  return std::move(node_);
208 }
209 
210 xmlNodePtr XmlNode::Release() {
211  DVLOG(2) << "Releasing node_.";
212  DCHECK(node_);
213  return node_.release();
214 }
215 
216 xmlNodePtr XmlNode::GetRawPtr() {
217  return node_.get();
218 }
219 
220 RepresentationBaseXmlNode::RepresentationBaseXmlNode(const char* name)
221  : XmlNode(name) {}
222 RepresentationBaseXmlNode::~RepresentationBaseXmlNode() {}
223 
224 bool RepresentationBaseXmlNode::AddContentProtectionElements(
225  const std::list<ContentProtectionElement>& content_protection_elements) {
226  std::list<ContentProtectionElement>::const_iterator content_protection_it =
227  content_protection_elements.begin();
228  for (; content_protection_it != content_protection_elements.end();
229  ++content_protection_it) {
230  if (!AddContentProtectionElement(*content_protection_it))
231  return false;
232  }
233 
234  return true;
235 }
236 
238  const std::string& scheme_id_uri,
239  const std::string& value) {
240  XmlNode supplemental_property("SupplementalProperty");
241  supplemental_property.SetStringAttribute("schemeIdUri", scheme_id_uri);
242  supplemental_property.SetStringAttribute("value", value);
243  AddChild(supplemental_property.PassScopedPtr());
244 }
245 
247  const std::string& scheme_id_uri,
248  const std::string& value) {
249  XmlNode essential_property("EssentialProperty");
250  essential_property.SetStringAttribute("schemeIdUri", scheme_id_uri);
251  essential_property.SetStringAttribute("value", value);
252  AddChild(essential_property.PassScopedPtr());
253 }
254 
255 bool RepresentationBaseXmlNode::AddContentProtectionElement(
256  const ContentProtectionElement& content_protection_element) {
257  XmlNode content_protection_node("ContentProtection");
258 
259  // @value is an optional attribute.
260  if (!content_protection_element.value.empty()) {
261  content_protection_node.SetStringAttribute(
262  "value", content_protection_element.value);
263  }
264  content_protection_node.SetStringAttribute(
265  "schemeIdUri", content_protection_element.scheme_id_uri);
266 
267  typedef std::map<std::string, std::string> AttributesMapType;
268  const AttributesMapType& additional_attributes =
269  content_protection_element.additional_attributes;
270 
271  AttributesMapType::const_iterator attributes_it =
272  additional_attributes.begin();
273  for (; attributes_it != additional_attributes.end(); ++attributes_it) {
274  content_protection_node.SetStringAttribute(attributes_it->first.c_str(),
275  attributes_it->second);
276  }
277 
278  if (!content_protection_node.AddElements(
279  content_protection_element.subelements)) {
280  return false;
281  }
282  return AddChild(content_protection_node.PassScopedPtr());
283 }
284 
285 AdaptationSetXmlNode::AdaptationSetXmlNode()
286  : RepresentationBaseXmlNode("AdaptationSet") {}
287 AdaptationSetXmlNode::~AdaptationSetXmlNode() {}
288 
289 void AdaptationSetXmlNode::AddRoleElement(const std::string& scheme_id_uri,
290  const std::string& value) {
291  XmlNode role("Role");
292  role.SetStringAttribute("schemeIdUri", scheme_id_uri);
293  role.SetStringAttribute("value", value);
294  AddChild(role.PassScopedPtr());
295 }
296 
297 RepresentationXmlNode::RepresentationXmlNode()
298  : RepresentationBaseXmlNode("Representation") {}
299 RepresentationXmlNode::~RepresentationXmlNode() {}
300 
301 bool RepresentationXmlNode::AddVideoInfo(const VideoInfo& video_info,
302  bool set_width,
303  bool set_height,
304  bool set_frame_rate) {
305  if (!video_info.has_width() || !video_info.has_height()) {
306  LOG(ERROR) << "Missing width or height for adding a video info.";
307  return false;
308  }
309 
310  if (video_info.has_pixel_width() && video_info.has_pixel_height()) {
311  SetStringAttribute("sar", base::IntToString(video_info.pixel_width()) +
312  ":" +
313  base::IntToString(video_info.pixel_height()));
314  }
315 
316  if (set_width)
317  SetIntegerAttribute("width", video_info.width());
318  if (set_height)
319  SetIntegerAttribute("height", video_info.height());
320  if (set_frame_rate) {
321  SetStringAttribute("frameRate",
322  base::IntToString(video_info.time_scale()) + "/" +
323  base::IntToString(video_info.frame_duration()));
324  }
325 
326  if (video_info.has_playback_rate()) {
327  SetStringAttribute("maxPlayoutRate",
328  base::IntToString(video_info.playback_rate()));
329  // Since the trick play stream contains only key frames, there is no coding
330  // dependency on the main stream. Simply set the codingDependency to false.
331  // TODO(hmchen): propagate this attribute up to the AdaptationSet, since
332  // all are set to false.
333  SetStringAttribute("codingDependency", "false");
334  }
335  return true;
336 }
337 
338 bool RepresentationXmlNode::AddAudioInfo(const AudioInfo& audio_info) {
339  if (!AddAudioChannelInfo(audio_info))
340  return false;
341 
342  AddAudioSamplingRateInfo(audio_info);
343  return true;
344 }
345 
346 bool RepresentationXmlNode::AddVODOnlyInfo(const MediaInfo& media_info) {
347  if (media_info.has_media_file_url()) {
348  XmlNode base_url("BaseURL");
349  base_url.SetContent(media_info.media_file_url());
350 
351  if (!AddChild(base_url.PassScopedPtr()))
352  return false;
353  }
354 
355  const bool need_segment_base = media_info.has_index_range() ||
356  media_info.has_init_range() ||
357  media_info.has_reference_time_scale();
358 
359  if (need_segment_base) {
360  XmlNode segment_base("SegmentBase");
361  if (media_info.has_index_range()) {
362  segment_base.SetStringAttribute("indexRange",
363  RangeToString(media_info.index_range()));
364  }
365 
366  if (media_info.has_reference_time_scale()) {
367  segment_base.SetIntegerAttribute("timescale",
368  media_info.reference_time_scale());
369  }
370 
371  if (media_info.has_presentation_time_offset()) {
372  segment_base.SetIntegerAttribute("presentationTimeOffset",
373  media_info.presentation_time_offset());
374  }
375 
376  if (media_info.has_init_range()) {
377  XmlNode initialization("Initialization");
378  initialization.SetStringAttribute("range",
379  RangeToString(media_info.init_range()));
380 
381  if (!segment_base.AddChild(initialization.PassScopedPtr()))
382  return false;
383  }
384 
385  if (!AddChild(segment_base.PassScopedPtr()))
386  return false;
387  }
388 
389  return true;
390 }
391 
393  const MediaInfo& media_info,
394  const std::list<SegmentInfo>& segment_infos,
395  uint32_t start_number) {
396  XmlNode segment_template("SegmentTemplate");
397  if (media_info.has_reference_time_scale()) {
398  segment_template.SetIntegerAttribute("timescale",
399  media_info.reference_time_scale());
400  }
401 
402  if (media_info.has_presentation_time_offset()) {
403  segment_template.SetIntegerAttribute("presentationTimeOffset",
404  media_info.presentation_time_offset());
405  }
406 
407  if (media_info.has_init_segment_url()) {
408  segment_template.SetStringAttribute("initialization",
409  media_info.init_segment_url());
410  }
411 
412  if (media_info.has_segment_template_url()) {
413  segment_template.SetStringAttribute("media",
414  media_info.segment_template_url());
415  segment_template.SetIntegerAttribute("startNumber", start_number);
416  }
417 
418  if (!segment_infos.empty()) {
419  // Don't use SegmentTimeline if all segments except the last one are of
420  // the same duration.
421  if (IsTimelineConstantDuration(segment_infos, start_number)) {
422  segment_template.SetIntegerAttribute("duration",
423  segment_infos.front().duration);
424  } else {
425  XmlNode segment_timeline("SegmentTimeline");
426  if (!PopulateSegmentTimeline(segment_infos, &segment_timeline) ||
427  !segment_template.AddChild(segment_timeline.PassScopedPtr())) {
428  return false;
429  }
430  }
431  }
432  return AddChild(segment_template.PassScopedPtr());
433 }
434 
435 bool RepresentationXmlNode::AddAudioChannelInfo(const AudioInfo& audio_info) {
436  std::string audio_channel_config_scheme;
437  std::string audio_channel_config_value;
438 
439  if (audio_info.codec() == kEC3Codec) {
440  // Convert EC3 channel map into string of hexadecimal digits. Spec: DASH-IF
441  // Interoperability Points v3.0 9.2.1.2.
442  const uint16_t ec3_channel_map =
443  base::HostToNet16(audio_info.codec_specific_data().ec3_channel_map());
444  audio_channel_config_value =
445  base::HexEncode(&ec3_channel_map, sizeof(ec3_channel_map));
446  audio_channel_config_scheme =
447  "tag:dolby.com,2014:dash:audio_channel_configuration:2011";
448  } else {
449  audio_channel_config_value = base::UintToString(audio_info.num_channels());
450  audio_channel_config_scheme =
451  "urn:mpeg:dash:23003:3:audio_channel_configuration:2011";
452  }
453 
454  XmlNode audio_channel_config("AudioChannelConfiguration");
455  audio_channel_config.SetStringAttribute("schemeIdUri",
456  audio_channel_config_scheme);
457  audio_channel_config.SetStringAttribute("value", audio_channel_config_value);
458 
459  return AddChild(audio_channel_config.PassScopedPtr());
460 }
461 
462 // MPD expects one number for sampling frequency, or if it is a range it should
463 // be space separated.
464 void RepresentationXmlNode::AddAudioSamplingRateInfo(
465  const AudioInfo& audio_info) {
466  if (audio_info.has_sampling_frequency())
467  SetIntegerAttribute("audioSamplingRate", audio_info.sampling_frequency());
468 }
469 
470 } // namespace xml
471 } // namespace shaka
bool AddVideoInfo(const MediaInfo::VideoInfo &video_info, bool set_width, bool set_height, bool set_frame_rate)
Definition: xml_node.cc:301
std::set< std::string > ExtractReferencedNamespaces()
Definition: xml_node.cc:198
void SetFloatingPointAttribute(const char *attribute_name, double number)
Definition: xml_node.cc:181
scoped_xml_ptr< xmlNode > PassScopedPtr()
Definition: xml_node.cc:204
XmlNode(const char *name)
Definition: xml_node.cc:114
All the methods that are virtual are virtual for mocking.
bool AddVODOnlyInfo(const MediaInfo &media_info)
Definition: xml_node.cc:346
void AddEssentialProperty(const std::string &scheme_id_uri, const std::string &value)
Definition: xml_node.cc:246
void SetStringAttribute(const char *attribute_name, const std::string &attribute)
Definition: xml_node.cc:166
bool AddChild(scoped_xml_ptr< xmlNode > child)
Definition: xml_node.cc:121
xmlNodePtr Release()
Definition: xml_node.cc:210
bool AddLiveOnlyInfo(const MediaInfo &media_info, const std::list< SegmentInfo > &segment_infos, uint32_t start_number)
Definition: xml_node.cc:392
void SetId(uint32_t id)
Definition: xml_node.cc:189
bool AddElements(const std::vector< Element > &elements)
Adds Elements to this node using the Element struct.
Definition: xml_node.cc:133
void AddSupplementalProperty(const std::string &scheme_id_uri, const std::string &value)
Definition: xml_node.cc:237
void SetIntegerAttribute(const char *attribute_name, uint64_t number)
Definition: xml_node.cc:173
void AddRoleElement(const std::string &scheme_id_uri, const std::string &value)
Definition: xml_node.cc:289
void SetContent(const std::string &content)
Definition: xml_node.cc:193
bool AddAudioInfo(const MediaInfo::AudioInfo &audio_info)
Definition: xml_node.cc:338
xmlNodePtr GetRawPtr()
Definition: xml_node.cc:216