Shaka Packager SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
simple_hls_notifier.cc
1 // Copyright 2016 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/hls/base/simple_hls_notifier.h"
8 
9 #include <cmath>
10 
11 #include "packager/base/base64.h"
12 #include "packager/base/files/file_path.h"
13 #include "packager/base/json/json_writer.h"
14 #include "packager/base/logging.h"
15 #include "packager/base/optional.h"
16 #include "packager/base/strings/string_number_conversions.h"
17 #include "packager/base/strings/stringprintf.h"
18 #include "packager/hls/base/media_playlist.h"
19 #include "packager/media/base/fixed_key_source.h"
20 #include "packager/media/base/protection_system_specific_info.h"
21 #include "packager/media/base/widevine_key_source.h"
22 #include "packager/media/base/widevine_pssh_data.pb.h"
23 
24 namespace shaka {
25 
26 using base::FilePath;
27 
28 namespace hls {
29 
30 namespace {
31 
32 const char kUriBase64Prefix[] = "data:text/plain;base64,";
33 const char kUriFairplayPrefix[] = "skd://";
34 const char kWidevineDashIfIopUUID[] =
35  "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";
36 
37 bool IsWidevineSystemId(const std::vector<uint8_t>& system_id) {
38  return system_id.size() == arraysize(media::kWidevineSystemId) &&
39  std::equal(system_id.begin(), system_id.end(),
40  media::kWidevineSystemId);
41 }
42 
43 bool IsCommonSystemId(const std::vector<uint8_t>& system_id) {
44  return system_id.size() == arraysize(media::kCommonSystemId) &&
45  std::equal(system_id.begin(), system_id.end(), media::kCommonSystemId);
46 }
47 
48 bool IsFairplaySystemId(const std::vector<uint8_t>& system_id) {
49  return system_id.size() == arraysize(media::kFairplaySystemId) &&
50  std::equal(system_id.begin(), system_id.end(), media::kFairplaySystemId);
51 }
52 
53 std::string Base64EncodeData(const std::string& prefix,
54  const std::string& data) {
55  std::string data_base64;
56  base::Base64Encode(data, &data_base64);
57  return prefix + data_base64;
58 }
59 
60 std::string VectorToString(const std::vector<uint8_t>& v) {
61  return std::string(v.begin(), v.end());
62 }
63 
64 // TODO(rkuroiwa): Dedup these with the functions in MpdBuilder.
65 // If |media_path| is contained in |parent_path|, then
66 // Strips the common path and keep only the relative part of |media_path|.
67 // e.g. if |parent_path| is /some/parent/ and
68 // |media_path| is /some/parent/abc/child/item.ext,
69 // abc/child/item.ext is returned.
70 // else
71 // Returns |media_path|.
72 // The path separator of the output is also changed to "/" if it is not.
73 std::string MakePathRelative(const std::string& media_path,
74  const FilePath& parent_path) {
75  FilePath relative_path;
76  const FilePath child_path = FilePath::FromUTF8Unsafe(media_path);
77  const bool is_child =
78  parent_path.AppendRelativePath(child_path, &relative_path);
79  if (!is_child)
80  relative_path = child_path;
81  return relative_path.NormalizePathSeparatorsTo('/').AsUTF8Unsafe();
82 }
83 
84 // Segment URL is relative to either output directory or the directory
85 // containing the media playlist depends on whether base_url is set.
86 std::string GenerateSegmentUrl(const std::string& segment_name,
87  const std::string& base_url,
88  const std::string& output_dir,
89  const std::string& playlist_file_name) {
90  FilePath output_path = FilePath::FromUTF8Unsafe(output_dir);
91  if (!base_url.empty()) {
92  // Media segment URL is base_url + segment path relative to output
93  // directory.
94  return base_url + MakePathRelative(segment_name, output_path);
95  }
96  // Media segment URL is segment path relative to the directory containing the
97  // playlist.
98  const FilePath playlist_dir =
99  output_path.Append(FilePath::FromUTF8Unsafe(playlist_file_name))
100  .DirName()
101  .AsEndingWithSeparator();
102  return MakePathRelative(segment_name, playlist_dir);
103 }
104 
105 bool WidevinePsshToJson(const std::vector<uint8_t>& pssh_box,
106  const std::vector<uint8_t>& key_id,
107  std::string* pssh_json) {
108  media::ProtectionSystemSpecificInfo pssh_info;
109  if (!pssh_info.Parse(pssh_box.data(), pssh_box.size())) {
110  LOG(ERROR) << "Failed to parse PSSH box.";
111  return false;
112  }
113 
114  media::WidevinePsshData pssh_proto;
115  if (!pssh_proto.ParseFromArray(pssh_info.pssh_data().data(),
116  pssh_info.pssh_data().size())) {
117  LOG(ERROR) << "Failed to parse protection_system_specific_data.";
118  return false;
119  }
120  if (!pssh_proto.has_provider() ||
121  (!pssh_proto.has_content_id() && pssh_proto.key_id_size() == 0)) {
122  LOG(ERROR) << "Missing fields to generate URI.";
123  return false;
124  }
125 
126  base::DictionaryValue pssh_dict;
127  pssh_dict.SetString("provider", pssh_proto.provider());
128  if (pssh_proto.has_content_id()) {
129  std::string content_id_base64;
130  base::Base64Encode(base::StringPiece(pssh_proto.content_id().data(),
131  pssh_proto.content_id().size()),
132  &content_id_base64);
133  pssh_dict.SetString("content_id", content_id_base64);
134  }
135  base::ListValue* key_ids = new base::ListValue();
136 
137  key_ids->AppendString(base::HexEncode(key_id.data(), key_id.size()));
138  for (const std::string& id : pssh_proto.key_id()) {
139  if (key_id.size() == id.size() &&
140  memcmp(key_id.data(), id.data(), id.size()) == 0) {
141  continue;
142  }
143  key_ids->AppendString(base::HexEncode(id.data(), id.size()));
144  }
145  pssh_dict.Set("key_ids", key_ids);
146 
147  if (!base::JSONWriter::Write(pssh_dict, pssh_json)) {
148  LOG(ERROR) << "Failed to write to JSON.";
149  return false;
150  }
151  return true;
152 }
153 
154 base::Optional<MediaPlaylist::EncryptionMethod> StringToEncryptionMethod(
155  const std::string& method) {
156  if (method == "cenc") {
157  return MediaPlaylist::EncryptionMethod::kSampleAesCenc;
158  } else if (method == "cbcs") {
159  return MediaPlaylist::EncryptionMethod::kSampleAes;
160  } else if (method == "cbca") {
161  // cbca is a place holder for sample aes.
162  return MediaPlaylist::EncryptionMethod::kSampleAes;
163  } else {
164  return base::nullopt;
165  }
166 }
167 
168 void NotifyEncryptionToMediaPlaylist(
169  MediaPlaylist::EncryptionMethod encryption_method,
170  const std::string& uri,
171  const std::vector<uint8_t>& key_id,
172  const std::vector<uint8_t>& iv,
173  const std::string& key_format,
174  const std::string& key_format_version,
175  MediaPlaylist* media_playlist) {
176  std::string iv_string;
177  if (!iv.empty()) {
178  iv_string = "0x" + base::HexEncode(iv.data(), iv.size());
179  }
180  std::string key_id_string;
181  if (!key_id.empty()) {
182  key_id_string = "0x" + base::HexEncode(key_id.data(), key_id.size());
183  }
184 
185  media_playlist->AddEncryptionInfo(
186  encryption_method,
187  uri, key_id_string, iv_string,
188  key_format, key_format_version);
189 }
190 
191 // Creates JSON format and the format similar to MPD.
192 bool HandleWidevineKeyFormats(
193  MediaPlaylist::EncryptionMethod encryption_method,
194  const std::vector<uint8_t>& key_id,
195  const std::vector<uint8_t>& iv,
196  const std::vector<uint8_t>& protection_system_specific_data,
197  MediaPlaylist* media_playlist) {
198  if (encryption_method == MediaPlaylist::EncryptionMethod::kSampleAes) {
199  // This format allows SAMPLE-AES only.
200  std::string key_uri_data;
201  if (!WidevinePsshToJson(protection_system_specific_data, key_id,
202  &key_uri_data)) {
203  return false;
204  }
205  std::string key_uri_data_base64 =
206  Base64EncodeData(kUriBase64Prefix, key_uri_data);
207  NotifyEncryptionToMediaPlaylist(encryption_method, key_uri_data_base64,
208  std::vector<uint8_t>(), iv, "com.widevine",
209  "1", media_playlist);
210  }
211 
212  std::string pssh_as_string(
213  reinterpret_cast<const char*>(protection_system_specific_data.data()),
214  protection_system_specific_data.size());
215  std::string key_uri_data_base64 =
216  Base64EncodeData(kUriBase64Prefix, pssh_as_string);
217  NotifyEncryptionToMediaPlaylist(encryption_method, key_uri_data_base64,
218  key_id, iv, kWidevineDashIfIopUUID, "1",
219  media_playlist);
220  return true;
221 }
222 
223 bool WriteMediaPlaylist(const std::string& output_dir,
224  MediaPlaylist* playlist) {
225  std::string file_path =
226  FilePath::FromUTF8Unsafe(output_dir)
227  .Append(FilePath::FromUTF8Unsafe(playlist->file_name()))
228  .AsUTF8Unsafe();
229  if (!playlist->WriteToFile(file_path)) {
230  LOG(ERROR) << "Failed to write playlist " << file_path;
231  return false;
232  }
233  return true;
234 }
235 
236 } // namespace
237 
238 MediaPlaylistFactory::~MediaPlaylistFactory() {}
239 
240 std::unique_ptr<MediaPlaylist> MediaPlaylistFactory::Create(
241  HlsPlaylistType type,
242  double time_shift_buffer_depth,
243  const std::string& file_name,
244  const std::string& name,
245  const std::string& group_id) {
246  return std::unique_ptr<MediaPlaylist>(new MediaPlaylist(
247  type, time_shift_buffer_depth, file_name, name, group_id));
248 }
249 
251  double time_shift_buffer_depth,
252  const std::string& prefix,
253  const std::string& output_dir,
254  const std::string& master_playlist_name)
255  : HlsNotifier(playlist_type),
256  time_shift_buffer_depth_(time_shift_buffer_depth),
257  prefix_(prefix),
258  output_dir_(output_dir),
259  media_playlist_factory_(new MediaPlaylistFactory()),
260  master_playlist_(new MasterPlaylist(master_playlist_name)) {}
261 
262 SimpleHlsNotifier::~SimpleHlsNotifier() {}
263 
265  return true;
266 }
267 
268 bool SimpleHlsNotifier::NotifyNewStream(const MediaInfo& media_info,
269  const std::string& playlist_name,
270  const std::string& name,
271  const std::string& group_id,
272  uint32_t* stream_id) {
273  DCHECK(stream_id);
274 
275  std::unique_ptr<MediaPlaylist> media_playlist =
276  media_playlist_factory_->Create(playlist_type(), time_shift_buffer_depth_,
277  playlist_name, name, group_id);
278  if (!media_playlist->SetMediaInfo(media_info)) {
279  LOG(ERROR) << "Failed to set media info for playlist " << playlist_name;
280  return false;
281  }
282 
283  MediaPlaylist::EncryptionMethod encryption_method =
284  MediaPlaylist::EncryptionMethod::kNone;
285  if (media_info.protected_content().has_protection_scheme()) {
286  const std::string& protection_scheme =
287  media_info.protected_content().protection_scheme();
288  base::Optional<MediaPlaylist::EncryptionMethod> enc_method =
289  StringToEncryptionMethod(protection_scheme);
290  if (!enc_method) {
291  LOG(ERROR) << "Failed to recognize protection scheme "
292  << protection_scheme;
293  return false;
294  }
295  encryption_method = enc_method.value();
296  }
297 
298  *stream_id = sequence_number_.GetNext();
299  base::AutoLock auto_lock(lock_);
300  master_playlist_->AddMediaPlaylist(media_playlist.get());
301  stream_map_[*stream_id].reset(
302  new StreamEntry{std::move(media_playlist), encryption_method});
303  return true;
304 }
305 
306 bool SimpleHlsNotifier::NotifyNewSegment(uint32_t stream_id,
307  const std::string& segment_name,
308  uint64_t start_time,
309  uint64_t duration,
310  uint64_t start_byte_offset,
311  uint64_t size) {
312  base::AutoLock auto_lock(lock_);
313  auto stream_iterator = stream_map_.find(stream_id);
314  if (stream_iterator == stream_map_.end()) {
315  LOG(ERROR) << "Cannot find stream with ID: " << stream_id;
316  return false;
317  }
318  auto& media_playlist = stream_iterator->second->media_playlist;
319  const std::string& segment_url = GenerateSegmentUrl(
320  segment_name, prefix_, output_dir_, media_playlist->file_name());
321  media_playlist->AddSegment(segment_url, start_time, duration,
322  start_byte_offset, size);
323 
324  // Update target duration.
325  uint32_t longest_segment_duration =
326  static_cast<uint32_t>(ceil(media_playlist->GetLongestSegmentDuration()));
327  bool target_duration_updated = false;
328  if (longest_segment_duration > target_duration_) {
329  target_duration_ = longest_segment_duration;
330  target_duration_updated = true;
331  }
332 
333  // Update the playlists when there is new segments in live mode.
334  if (playlist_type() == HlsPlaylistType::kLive ||
335  playlist_type() == HlsPlaylistType::kEvent) {
336  if (!master_playlist_->WriteMasterPlaylist(prefix_, output_dir_)) {
337  LOG(ERROR) << "Failed to write master playlist.";
338  return false;
339  }
340  // Update all playlists if target duration is updated.
341  if (target_duration_updated) {
342  for (auto& streams : stream_map_) {
343  MediaPlaylist* playlist = streams.second->media_playlist.get();
344  playlist->SetTargetDuration(target_duration_);
345  if (!WriteMediaPlaylist(output_dir_, playlist))
346  return false;
347  }
348  } else {
349  return WriteMediaPlaylist(output_dir_, media_playlist.get());
350  }
351  }
352  return true;
353 }
354 
356  uint32_t stream_id,
357  const std::vector<uint8_t>& key_id,
358  const std::vector<uint8_t>& system_id,
359  const std::vector<uint8_t>& iv,
360  const std::vector<uint8_t>& protection_system_specific_data) {
361  base::AutoLock auto_lock(lock_);
362  auto stream_iterator = stream_map_.find(stream_id);
363  if (stream_iterator == stream_map_.end()) {
364  LOG(ERROR) << "Cannot find stream with ID: " << stream_id;
365  return false;
366  }
367 
368  std::unique_ptr<MediaPlaylist>& media_playlist =
369  stream_iterator->second->media_playlist;
370  const MediaPlaylist::EncryptionMethod encryption_method =
371  stream_iterator->second->encryption_method;
372  LOG_IF(WARNING, encryption_method == MediaPlaylist::EncryptionMethod::kNone)
373  << "Got encryption notification but the encryption method is NONE";
374  if (IsWidevineSystemId(system_id)) {
375  return HandleWidevineKeyFormats(encryption_method,
376  key_id, iv, protection_system_specific_data,
377  media_playlist.get());
378  }
379  if (IsCommonSystemId(system_id)) {
380  // Use key_id as the key_uri. The player needs to have custom logic to
381  // convert it to the actual key url.
382  std::string key_uri_data = VectorToString(key_id);
383  std::string key_uri_data_base64 =
384  Base64EncodeData(kUriBase64Prefix, key_uri_data);
385  NotifyEncryptionToMediaPlaylist(encryption_method,
386  key_uri_data_base64, std::vector<uint8_t>(),
387  iv, "identity", "", media_playlist.get());
388  return true;
389  }
390 
391  if (IsFairplaySystemId(system_id)) {
392  // Use key_id as the key_uri. The player needs to have custom logic to
393  // convert it to the actual key url.
394  std::string key_uri_data = VectorToString(key_id);
395  std::string key_uri_data_base64 =
396  Base64EncodeData(kUriFairplayPrefix, key_uri_data);
397 
398  // Fairplay defines IV to be carried with the key, not the playlist.
399  NotifyEncryptionToMediaPlaylist(encryption_method,
400  key_uri_data_base64, std::vector<uint8_t>(),
401  std::vector<uint8_t>(),
402  "com.apple.streamingkeydelivery", "1",
403  media_playlist.get());
404  return true;
405  }
406 
407  LOG(ERROR) << "Unknown system ID: "
408  << base::HexEncode(system_id.data(), system_id.size());
409  return false;
410 }
411 
413  base::AutoLock auto_lock(lock_);
414  if (!master_playlist_->WriteMasterPlaylist(prefix_, output_dir_)) {
415  LOG(ERROR) << "Failed to write master playlist.";
416  return false;
417  }
418  for (auto& streams : stream_map_) {
419  MediaPlaylist* playlist = streams.second->media_playlist.get();
420  playlist->SetTargetDuration(target_duration_);
421  if (!WriteMediaPlaylist(output_dir_, playlist))
422  return false;
423  }
424  return true;
425 }
426 
427 } // namespace hls
428 } // namespace shaka
SimpleHlsNotifier(HlsPlaylistType playlist_type, double time_shift_buffer_depth, const std::string &prefix, const std::string &output_dir, const std::string &master_playlist_name)
HlsPlaylistType
Definition: hls_params.h:16
bool NotifyNewSegment(uint32_t stream_id, const std::string &segment_name, uint64_t start_time, uint64_t duration, uint64_t start_byte_offset, uint64_t size) override
virtual void SetTargetDuration(uint32_t target_duration)
Methods are virtual for mocking.
HlsPlaylistType playlist_type() const
Definition: hls_notifier.h:80
bool NotifyNewStream(const MediaInfo &media_info, const std::string &playlist_name, const std::string &stream_name, const std::string &group_id, uint32_t *stream_id) override
bool NotifyEncryptionUpdate(uint32_t stream_id, const std::vector< uint8_t > &key_id, const std::vector< uint8_t > &system_id, const std::vector< uint8_t > &iv, const std::vector< uint8_t > &protection_system_specific_data) override