Shaka Packager SDK
Loading...
Searching...
No Matches
mpd_utils.cc
1// Copyright 2014 Google LLC. 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_utils.h>
8
9#include <cstddef>
10#include <cstdint>
11#include <list>
12#include <map>
13#include <memory>
14#include <string>
15#include <string_view>
16#include <vector>
17
18#include <absl/flags/flag.h>
19#include <absl/log/check.h>
20#include <absl/log/log.h>
21#include <absl/strings/ascii.h>
22#include <absl/strings/escaping.h>
23#include <absl/strings/numbers.h>
24#include <absl/strings/str_format.h>
25#include <libxml/tree.h>
26#include <libxml/xmlstring.h>
27
28#include <packager/macros/logging.h>
29#include <packager/media/base/fourccs.h>
30#include <packager/media/base/language_utils.h>
31#include <packager/media/base/protection_system_specific_info.h>
32#include <packager/mpd/base/adaptation_set.h>
33#include <packager/mpd/base/content_protection_element.h>
34#include <packager/mpd/base/media_info.pb.h>
35#include <packager/mpd/base/representation.h>
36#include <packager/mpd/base/xml/scoped_xml_ptr.h>
37
38ABSL_FLAG(
39 bool,
40 use_legacy_vp9_codec_string,
41 false,
42 "Use legacy vp9 codec string 'vp9' if set to true; otherwise new style "
43 "vp09.xx.xx.xx... codec string will be used. Default to false as indicated "
44 "in https://github.com/shaka-project/shaka-packager/issues/406, all major "
45 "browsers and platforms already support the new 'vp09' codec string.");
46
47namespace shaka {
48namespace {
49
50bool IsKeyRotationDefaultKeyId(const std::string& key_id) {
51 for (char c : key_id) {
52 if (c != '\0')
53 return false;
54 }
55 return true;
56}
57
58std::string TextCodecString(const MediaInfo& media_info) {
59 CHECK(media_info.has_text_info());
60 const auto container_type = media_info.container_type();
61
62 // Codecs are not needed when mimeType is "text/*". Having a codec would be
63 // redundant.
64 if (container_type == MediaInfo::CONTAINER_TEXT) {
65 return "";
66 }
67
68 // DASH IOP mentions that the codec for ttml in mp4 is stpp, so override
69 // the default codec value.
70 const std::string& codec = media_info.text_info().codec();
71 if (codec == "ttml" && container_type == MediaInfo::CONTAINER_MP4) {
72 return "stpp";
73 }
74
75 return codec;
76}
77
78} // namespace
79
80bool HasVODOnlyFields(const MediaInfo& media_info) {
81 return media_info.has_init_range() || media_info.has_index_range() ||
82 media_info.has_media_file_url();
83}
84
85bool HasLiveOnlyFields(const MediaInfo& media_info) {
86 return media_info.has_init_segment_url() ||
87 media_info.has_segment_template_url();
88}
89
90void RemoveDuplicateAttributes(
91 ContentProtectionElement* content_protection_element) {
92 DCHECK(content_protection_element);
93 typedef std::map<std::string, std::string> AttributesMap;
94
95 AttributesMap& attributes = content_protection_element->additional_attributes;
96 if (!content_protection_element->value.empty())
97 attributes.erase("value");
98
99 if (!content_protection_element->scheme_id_uri.empty())
100 attributes.erase("schemeIdUri");
101}
102
103std::string GetLanguage(const MediaInfo& media_info) {
104 std::string lang;
105 if (media_info.has_audio_info()) {
106 lang = media_info.audio_info().language();
107 } else if (media_info.has_text_info()) {
108 lang = media_info.text_info().language();
109 }
110 return LanguageToShortestForm(lang);
111}
112
113std::string GetCodecs(const MediaInfo& media_info) {
114 CHECK(OnlyOneTrue(media_info.has_video_info(), media_info.has_audio_info(),
115 media_info.has_text_info()));
116
117 if (media_info.has_video_info()) {
118 if (media_info.container_type() == MediaInfo::CONTAINER_WEBM) {
119 std::string codec = media_info.video_info().codec().substr(0, 4);
120 // media_info.video_info().codec() contains new revised codec string
121 // specified by "VPx in ISO BMFF" document, which is not compatible to
122 // old codec strings in WebM. Hack it here before all browsers support
123 // new codec strings.
124 if (codec == "vp08")
125 return "vp8";
126 if (absl::GetFlag(FLAGS_use_legacy_vp9_codec_string)) {
127 if (codec == "vp09")
128 return "vp9";
129 }
130 }
131 return media_info.video_info().codec();
132 }
133
134 if (media_info.has_audio_info())
135 return media_info.audio_info().codec();
136
137 if (media_info.has_text_info())
138 return TextCodecString(media_info);
139
140 NOTIMPLEMENTED();
141 return "";
142}
143
144std::string GetSupplementalCodecs(const MediaInfo& media_info) {
145 CHECK(OnlyOneTrue(media_info.has_video_info(), media_info.has_audio_info(),
146 media_info.has_text_info()));
147
148 if (media_info.has_video_info() &&
149 media_info.video_info().has_supplemental_codec()) {
150 return media_info.video_info().supplemental_codec();
151 }
152 return "";
153}
154
155std::string GetSupplementalProfiles(const MediaInfo& media_info) {
156 CHECK(OnlyOneTrue(media_info.has_video_info(), media_info.has_audio_info(),
157 media_info.has_text_info()));
158
159 if (media_info.has_video_info() &&
160 media_info.video_info().has_compatible_brand()) {
161 return FourCCToString(
162 static_cast<media::FourCC>(media_info.video_info().compatible_brand()));
163 }
164 return "";
165}
166
167std::string GetBaseCodec(const MediaInfo& media_info) {
168 std::string codec;
169 if (media_info.has_video_info()) {
170 codec = media_info.video_info().codec();
171 } else if (media_info.has_audio_info()) {
172 codec = media_info.audio_info().codec();
173 } else if (media_info.has_text_info()) {
174 codec = media_info.text_info().codec();
175 }
176 // Convert, for example, "mp4a.40.2" to simply "mp4a".
177 // "mp4a.40.2" and "mp4a.40.5" can exist in the same AdaptationSet.
178 size_t dot = codec.find('.');
179 if (dot != std::string::npos) {
180 codec.erase(dot);
181 }
182 return codec;
183}
184
185std::string GetAdaptationSetKey(const MediaInfo& media_info,
186 bool ignore_codec) {
187 std::string key;
188
189 if (media_info.has_video_info()) {
190 key.append("video:");
191 } else if (media_info.has_audio_info()) {
192 key.append("audio:");
193 } else if (media_info.has_text_info()) {
194 key.append(MediaInfo_TextInfo_TextType_Name(media_info.text_info().type()));
195 key.append(":");
196 } else {
197 key.append("unknown:");
198 }
199
200 if (media_info.has_dash_label())
201 key.append(media_info.dash_label() + ":");
202
203 key.append(MediaInfo_ContainerType_Name(media_info.container_type()));
204 if (!ignore_codec) {
205 key.append(":");
206 key.append(GetBaseCodec(media_info));
207
208 if (GetBaseCodec(media_info).find("dvh") == 0) {
209 // Transfer characteristics for Dolby Vision (dvh1 or dvhe) must be PQ
210 // irrespective of value present in SPS VUI.
211 key.append(":");
212 key.append(std::to_string(kTransferFunctionPQ));
213 } else if (media_info.video_info().has_transfer_characteristics()) {
214 key.append(":");
215 key.append(
216 std::to_string(media_info.video_info().transfer_characteristics()));
217 }
218 }
219 key.append(":");
220 key.append(GetLanguage(media_info));
221
222 // Trick play streams of the same original stream, but possibly with
223 // different trick_play_factors, belong to the same trick play AdaptationSet.
224 if (media_info.video_info().has_playback_rate()) {
225 key.append(":trick_play");
226 }
227
228 if (!media_info.dash_accessibilities().empty()) {
229 key.append(":accessibility_");
230 for (const std::string& accessibility : media_info.dash_accessibilities())
231 key.append(accessibility);
232 }
233
234 if (!media_info.dash_roles().empty()) {
235 key.append(":roles_");
236 for (const std::string& role : media_info.dash_roles())
237 key.append(role);
238 }
239
240 return key;
241}
242
243std::string FloatToXmlString(double number) {
244 // Keep up to microsecond accuracy but trim trailing 0s
245 std::string formatted = absl::StrFormat("%.6f", number);
246 size_t decimalPos = formatted.find('.');
247 if (decimalPos != std::string::npos) {
248 size_t lastNonZeroPos = formatted.find_last_not_of('0');
249 if (lastNonZeroPos >= decimalPos) {
250 formatted.erase(lastNonZeroPos + 1);
251 }
252 if (formatted.back() == '.') {
253 formatted.pop_back();
254 }
255 }
256
257 return formatted;
258}
259
260std::string SecondsToXmlDuration(double seconds) {
261 // Chrome internally uses time accurate to microseconds, which is implemented
262 // per MSE spec (https://www.w3.org/TR/media-source/).
263 // We need a string formatter that has at least microseconds accuracy for a
264 // normal video (with duration up to 3 hours). FloatToXmlString
265 // implementation meets the requirement.
266 return absl::StrFormat("PT%sS", FloatToXmlString(seconds));
267}
268
269bool GetDurationAttribute(xmlNodePtr node, float* duration) {
270 DCHECK(node);
271 DCHECK(duration);
272 static const char kDuration[] = "duration";
273 xml::scoped_xml_ptr<xmlChar> duration_value(
274 xmlGetProp(node, BAD_CAST kDuration));
275
276 if (!duration_value)
277 return false;
278
279 double duration_double_precision = 0.0;
280 if (!absl::SimpleAtod(reinterpret_cast<const char*>(duration_value.get()),
281 &duration_double_precision)) {
282 return false;
283 }
284
285 *duration = static_cast<float>(duration_double_precision);
286 return true;
287}
288
289bool MoreThanOneTrue(bool b1, bool b2, bool b3) {
290 return (b1 && b2) || (b2 && b3) || (b3 && b1);
291}
292
293bool AtLeastOneTrue(bool b1, bool b2, bool b3) {
294 return b1 || b2 || b3;
295}
296
297bool OnlyOneTrue(bool b1, bool b2, bool b3) {
298 return !MoreThanOneTrue(b1, b2, b3) && AtLeastOneTrue(b1, b2, b3);
299}
300
301// Coverts binary data into human readable UUID format.
302bool HexToUUID(const std::string& data, std::string* uuid_format) {
303 DCHECK(uuid_format);
304 const size_t kExpectedUUIDSize = 16;
305 if (data.size() != kExpectedUUIDSize) {
306 LOG(ERROR) << "UUID size is expected to be " << kExpectedUUIDSize
307 << " but is " << data.size() << " and the data in hex is "
308 << absl::BytesToHexString(data);
309 return false;
310 }
311
312 const std::string hex_encoded =
313 absl::AsciiStrToLower(absl::BytesToHexString(data));
314 DCHECK_EQ(hex_encoded.size(), kExpectedUUIDSize * 2);
315 std::string_view all(hex_encoded);
316 // Note UUID has 5 parts separated with dashes.
317 // e.g. 123e4567-e89b-12d3-a456-426655440000
318 // These StringPieces have each part.
319 std::string_view first = all.substr(0, 8);
320 std::string_view second = all.substr(8, 4);
321 std::string_view third = all.substr(12, 4);
322 std::string_view fourth = all.substr(16, 4);
323 std::string_view fifth = all.substr(20, 12);
324
325 // 32 hexadecimal characters with 4 hyphens.
326 const size_t kHumanReadableUUIDSize = 36;
327 uuid_format->reserve(kHumanReadableUUIDSize);
328 absl::StrAppendFormat(uuid_format, "%s-%s-%s-%s-%s", first, second, third,
329 fourth, fifth);
330 return true;
331}
332
333void UpdateContentProtectionPsshHelper(
334 const std::string& drm_uuid,
335 const std::string& pssh,
336 std::list<ContentProtectionElement>* content_protection_elements) {
337 const std::string drm_uuid_schemd_id_uri_form = "urn:uuid:" + drm_uuid;
338 for (std::list<ContentProtectionElement>::iterator protection =
339 content_protection_elements->begin();
340 protection != content_protection_elements->end(); ++protection) {
341 if (protection->scheme_id_uri != drm_uuid_schemd_id_uri_form) {
342 continue;
343 }
344
345 for (std::vector<Element>::iterator subelement =
346 protection->subelements.begin();
347 subelement != protection->subelements.end(); ++subelement) {
348 if (subelement->name == kPsshElementName) {
349 // For now, we want to remove the PSSH element because some players do
350 // not support updating pssh.
351 protection->subelements.erase(subelement);
352
353 // TODO(rkuroiwa): Uncomment this and remove the line above when
354 // shaka-player supports updating PSSH.
355 // subelement->content = pssh;
356 return;
357 }
358 }
359
360 // Reaching here means <cenc:pssh> does not exist under the
361 // ContentProtection element. Add it.
362 // TODO(rkuroiwa): Uncomment this when shaka-player supports updating PSSH.
363 // Element cenc_pssh;
364 // cenc_pssh.name = kPsshElementName;
365 // cenc_pssh.content = pssh;
366 // protection->subelements.push_back(cenc_pssh);
367 return;
368 }
369
370 // Reaching here means that ContentProtection for the DRM does not exist.
371 // Add it.
372 ContentProtectionElement content_protection;
373 content_protection.scheme_id_uri = drm_uuid_schemd_id_uri_form;
374 // TODO(rkuroiwa): Uncomment this when shaka-player supports updating PSSH.
375 // Element cenc_pssh;
376 // cenc_pssh.name = kPsshElementName;
377 // cenc_pssh.content = pssh;
378 // content_protection.subelements.push_back(cenc_pssh);
379 content_protection_elements->push_back(content_protection);
380 return;
381}
382
383namespace {
384
385// UUID for Marlin Adaptive Streaming Specification – Simple Profile from
386// https://dashif.org/identifiers/content_protection/.
387const char kMarlinUUID[] = "5e629af5-38da-4063-8977-97ffbd9902d4";
388// String representation of media::kFairPlaySystemId.
389const char kFairPlayUUID[] = "94ce86fb-07ff-4f43-adb8-93d2fa968ca2";
390// String representation of media::kPlayReadySystemId.
391const char kPlayReadyUUID[] = "9a04f079-9840-4286-ab92-e65be0885f95";
392// It is RECOMMENDED to include the @value attribute with name and version
393// "MSPR 2.0". See
394// https://docs.microsoft.com/en-us/playready/specifications/mpeg-dash-playready#221-general.
395const char kContentProtectionValueMSPR20[] = "MSPR 2.0";
396
397Element GenerateMarlinContentIds(const std::string& key_id) {
398 // See https://github.com/shaka-project/shaka-packager/issues/381 for details.
399 static const char kMarlinContentIdName[] = "mas:MarlinContentId";
400 static const char kMarlinContentIdPrefix[] = "urn:marlin:kid:";
401 static const char kMarlinContentIdsName[] = "mas:MarlinContentIds";
402
403 Element marlin_content_id;
404 marlin_content_id.name = kMarlinContentIdName;
405 marlin_content_id.content =
406 kMarlinContentIdPrefix +
407 absl::AsciiStrToLower(absl::BytesToHexString(key_id));
408
409 Element marlin_content_ids;
410 marlin_content_ids.name = kMarlinContentIdsName;
411 marlin_content_ids.subelements.push_back(marlin_content_id);
412
413 return marlin_content_ids;
414}
415
416Element GenerateCencPsshElement(const std::string& pssh) {
417 std::string base64_encoded_pssh;
418 absl::Base64Escape(std::string_view(pssh.data(), pssh.size()),
419 &base64_encoded_pssh);
420 Element cenc_pssh;
421 cenc_pssh.name = kPsshElementName;
422 cenc_pssh.content = base64_encoded_pssh;
423 return cenc_pssh;
424}
425
426// Extract MS PlayReady Object from given PSSH
427// and encode it in base64.
428Element GenerateMsprProElement(const std::string& pssh) {
429 std::unique_ptr<media::PsshBoxBuilder> b =
431 reinterpret_cast<const uint8_t*>(pssh.data()), pssh.size());
432
433 const std::vector<uint8_t>* p_pssh = &b->pssh_data();
434 std::string base64_encoded_mspr;
435 absl::Base64Escape(
436 std::string_view(reinterpret_cast<const char*>(p_pssh->data()),
437 p_pssh->size()),
438 &base64_encoded_mspr);
439 Element mspr_pro;
440 mspr_pro.name = kMsproElementName;
441 mspr_pro.content = base64_encoded_mspr;
442 return mspr_pro;
443}
444
445// Helper function. This works because Representation and AdaptationSet both
446// have AddContentProtectionElement().
447template <typename ContentProtectionParent>
448void AddContentProtectionElementsHelperTemplated(
449 const MediaInfo& media_info,
450 ContentProtectionParent* parent) {
451 DCHECK(parent);
452 if (!media_info.has_protected_content())
453 return;
454
455 const MediaInfo::ProtectedContent& protected_content =
456 media_info.protected_content();
457
458 // DASH MPD spec specifies a default ContentProtection element for ISO BMFF
459 // (MP4) files.
460 const bool is_mp4_container =
461 media_info.container_type() == MediaInfo::CONTAINER_MP4;
462 std::string key_id_uuid_format;
463 if (protected_content.has_default_key_id() &&
464 !IsKeyRotationDefaultKeyId(protected_content.default_key_id())) {
465 if (!HexToUUID(protected_content.default_key_id(), &key_id_uuid_format)) {
466 LOG(ERROR) << "Failed to convert default key ID into UUID format.";
467 }
468 }
469
470 if (is_mp4_container) {
471 ContentProtectionElement mp4_content_protection;
472 mp4_content_protection.scheme_id_uri = kEncryptedMp4Scheme;
473 mp4_content_protection.value = protected_content.protection_scheme();
474 if (!key_id_uuid_format.empty()) {
475 mp4_content_protection.additional_attributes["cenc:default_KID"] =
476 key_id_uuid_format;
477 }
478
479 parent->AddContentProtectionElement(mp4_content_protection);
480 }
481
482 for (const auto& entry : protected_content.content_protection_entry()) {
483 if (!entry.has_uuid()) {
484 LOG(WARNING)
485 << "ContentProtectionEntry was specified but no UUID is set for "
486 << entry.name_version() << ", skipping.";
487 continue;
488 }
489
490 ContentProtectionElement drm_content_protection;
491
492 if (entry.has_name_version())
493 drm_content_protection.value = entry.name_version();
494
495 if (entry.uuid() == kFairPlayUUID) {
496 VLOG(1) << "Skipping FairPlay ContentProtection element as FairPlay does "
497 "not support DASH signaling.";
498 continue;
499 } else if (entry.uuid() == kMarlinUUID) {
500 // Marlin requires its uuid to be in upper case. See #525 for details.
501 drm_content_protection.scheme_id_uri =
502 "urn:uuid:" + absl::AsciiStrToUpper(entry.uuid());
503 drm_content_protection.subelements.push_back(
504 GenerateMarlinContentIds(protected_content.default_key_id()));
505 } else {
506 drm_content_protection.scheme_id_uri = "urn:uuid:" + entry.uuid();
507 if (!entry.pssh().empty()) {
508 drm_content_protection.subelements.push_back(
509 GenerateCencPsshElement(entry.pssh()));
510 if (entry.uuid() == kPlayReadyUUID &&
511 protected_content.include_mspr_pro()) {
512 drm_content_protection.subelements.push_back(
513 GenerateMsprProElement(entry.pssh()));
514 drm_content_protection.value = kContentProtectionValueMSPR20;
515 }
516 }
517 }
518
519 if (!key_id_uuid_format.empty() && !is_mp4_container) {
520 drm_content_protection.additional_attributes["cenc:default_KID"] =
521 key_id_uuid_format;
522 }
523
524 parent->AddContentProtectionElement(drm_content_protection);
525 }
526
527 if (protected_content.content_protection_entry().size() == 0) {
528 VLOG(1) << "The media is encrypted but no content protection specified "
529 << "(can happen with key rotation).";
530 }
531}
532} // namespace
533
534void AddContentProtectionElements(const MediaInfo& media_info,
535 Representation* parent) {
536 AddContentProtectionElementsHelperTemplated(media_info, parent);
537}
538
539void AddContentProtectionElements(const MediaInfo& media_info,
540 AdaptationSet* parent) {
541 AddContentProtectionElementsHelperTemplated(media_info, parent);
542}
543
544} // namespace shaka
static std::unique_ptr< PsshBoxBuilder > ParseFromBox(const uint8_t *data, size_t data_size)
All the methods that are virtual are virtual for mocking.
bool HexToUUID(const std::string &data, std::string *uuid_format)
Definition mpd_utils.cc:302
std::string LanguageToShortestForm(const std::string &language)
void AddContentProtectionElements(const MediaInfo &media_info, Representation *parent)
Definition mpd_utils.cc:534