DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerator
widevine_key_source.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/media/base/widevine_key_source.h"
8 
9 #include "packager/base/base64.h"
10 #include "packager/base/bind.h"
11 #include "packager/base/json/json_reader.h"
12 #include "packager/base/json/json_writer.h"
13 #include "packager/base/memory/ref_counted.h"
14 #include "packager/base/stl_util.h"
15 #include "packager/media/base/http_key_fetcher.h"
16 #include "packager/media/base/producer_consumer_queue.h"
17 #include "packager/media/base/protection_system_specific_info.h"
18 #include "packager/media/base/request_signer.h"
19 #include "packager/media/base/widevine_pssh_data.pb.h"
20 
21 #define RCHECK(x) \
22  do { \
23  if (!(x)) { \
24  LOG(ERROR) << "Failure while processing: " << #x; \
25  return false; \
26  } \
27  } while (0)
28 
29 namespace edash_packager {
30 namespace {
31 
32 const bool kEnableKeyRotation = true;
33 
34 const char kLicenseStatusOK[] = "OK";
35 // Server may return INTERNAL_ERROR intermittently, which is a transient error
36 // and the next client request may succeed without problem.
37 const char kLicenseStatusTransientError[] = "INTERNAL_ERROR";
38 
39 // Number of times to retry requesting keys in case of a transient error from
40 // the server.
41 const int kNumTransientErrorRetries = 5;
42 const int kFirstRetryDelayMilliseconds = 1000;
43 
44 // Default crypto period count, which is the number of keys to fetch on every
45 // key rotation enabled request.
46 const int kDefaultCryptoPeriodCount = 10;
47 const int kGetKeyTimeoutInSeconds = 5 * 60; // 5 minutes.
48 const int kKeyFetchTimeoutInSeconds = 60; // 1 minute.
49 
50 bool Base64StringToBytes(const std::string& base64_string,
51  std::vector<uint8_t>* bytes) {
52  DCHECK(bytes);
53  std::string str;
54  if (!base::Base64Decode(base64_string, &str))
55  return false;
56  bytes->assign(str.begin(), str.end());
57  return true;
58 }
59 
60 void BytesToBase64String(const std::vector<uint8_t>& bytes,
61  std::string* base64_string) {
62  DCHECK(base64_string);
63  base::Base64Encode(base::StringPiece(reinterpret_cast<const char*>
64  (bytes.data()), bytes.size()),
65  base64_string);
66 }
67 
68 bool GetKeyFromTrack(const base::DictionaryValue& track_dict,
69  std::vector<uint8_t>* key) {
70  DCHECK(key);
71  std::string key_base64_string;
72  RCHECK(track_dict.GetString("key", &key_base64_string));
73  VLOG(2) << "Key:" << key_base64_string;
74  RCHECK(Base64StringToBytes(key_base64_string, key));
75  return true;
76 }
77 
78 bool GetKeyIdFromTrack(const base::DictionaryValue& track_dict,
79  std::vector<uint8_t>* key_id) {
80  DCHECK(key_id);
81  std::string key_id_base64_string;
82  RCHECK(track_dict.GetString("key_id", &key_id_base64_string));
83  VLOG(2) << "Keyid:" << key_id_base64_string;
84  RCHECK(Base64StringToBytes(key_id_base64_string, key_id));
85  return true;
86 }
87 
88 bool GetPsshDataFromTrack(const base::DictionaryValue& track_dict,
89  std::vector<uint8_t>* pssh_data) {
90  DCHECK(pssh_data);
91 
92  const base::ListValue* pssh_list;
93  RCHECK(track_dict.GetList("pssh", &pssh_list));
94  // Invariant check. We don't want to crash in release mode if possible.
95  // The following code handles it gracefully if GetSize() does not return 1.
96  DCHECK_EQ(1u, pssh_list->GetSize());
97 
98  const base::DictionaryValue* pssh_dict;
99  RCHECK(pssh_list->GetDictionary(0, &pssh_dict));
100  std::string drm_type;
101  RCHECK(pssh_dict->GetString("drm_type", &drm_type));
102  if (drm_type != "WIDEVINE") {
103  LOG(ERROR) << "Expecting drm_type 'WIDEVINE', get '" << drm_type << "'.";
104  return false;
105  }
106  std::string pssh_data_base64_string;
107  RCHECK(pssh_dict->GetString("data", &pssh_data_base64_string));
108 
109  VLOG(2) << "Pssh Data:" << pssh_data_base64_string;
110  RCHECK(Base64StringToBytes(pssh_data_base64_string, pssh_data));
111  return true;
112 }
113 
114 } // namespace
115 
116 namespace media {
117 
118 // A ref counted wrapper for EncryptionKeyMap.
119 class WidevineKeySource::RefCountedEncryptionKeyMap
120  : public base::RefCountedThreadSafe<RefCountedEncryptionKeyMap> {
121  public:
122  explicit RefCountedEncryptionKeyMap(EncryptionKeyMap* encryption_key_map) {
123  DCHECK(encryption_key_map);
124  encryption_key_map_.swap(*encryption_key_map);
125  }
126 
127  std::map<KeySource::TrackType, EncryptionKey*>& map() {
128  return encryption_key_map_;
129  }
130 
131  private:
132  friend class base::RefCountedThreadSafe<RefCountedEncryptionKeyMap>;
133 
134  ~RefCountedEncryptionKeyMap() { STLDeleteValues(&encryption_key_map_); }
135 
136  EncryptionKeyMap encryption_key_map_;
137 
138  DISALLOW_COPY_AND_ASSIGN(RefCountedEncryptionKeyMap);
139 };
140 
141 WidevineKeySource::WidevineKeySource(const std::string& server_url)
142  : key_production_thread_("KeyProductionThread",
143  base::Bind(&WidevineKeySource::FetchKeysTask,
144  base::Unretained(this))),
145  key_fetcher_(new HttpKeyFetcher(kKeyFetchTimeoutInSeconds)),
146  server_url_(server_url),
147  crypto_period_count_(kDefaultCryptoPeriodCount),
148  key_production_started_(false),
149  start_key_production_(false, false),
150  first_crypto_period_index_(0) {
151  key_production_thread_.Start();
152 }
153 
154 WidevineKeySource::~WidevineKeySource() {
155  if (key_pool_)
156  key_pool_->Stop();
157  if (key_production_thread_.HasBeenStarted()) {
158  // Signal the production thread to start key production if it is not
159  // signaled yet so the thread can be joined.
160  start_key_production_.Signal();
161  key_production_thread_.Join();
162  }
163  STLDeleteValues(&encryption_key_map_);
164 }
165 
166 Status WidevineKeySource::FetchKeys(const std::vector<uint8_t>& content_id,
167  const std::string& policy) {
168  base::AutoLock scoped_lock(lock_);
169  request_dict_.Clear();
170  std::string content_id_base64_string;
171  BytesToBase64String(content_id, &content_id_base64_string);
172  request_dict_.SetString("content_id", content_id_base64_string);
173  request_dict_.SetString("policy", policy);
174  return FetchKeysInternal(!kEnableKeyRotation, 0, false);
175 }
176 
177 Status WidevineKeySource::FetchKeys(const std::vector<uint8_t>& pssh_box) {
178  const std::vector<uint8_t> widevine_system_id(
179  kWidevineSystemId, kWidevineSystemId + arraysize(kWidevineSystemId));
180 
182  if (!info.Parse(pssh_box.data(), pssh_box.size()))
183  return Status(error::PARSER_FAILURE, "Error parsing the PSSH box.");
184 
185  if (info.system_id() == widevine_system_id) {
186  base::AutoLock scoped_lock(lock_);
187  request_dict_.Clear();
188  std::string pssh_data_base64_string;
189 
190  BytesToBase64String(info.pssh_data(), &pssh_data_base64_string);
191  request_dict_.SetString("pssh_data", pssh_data_base64_string);
192  return FetchKeysInternal(!kEnableKeyRotation, 0, false);
193  } else if (!info.key_ids().empty()) {
194  // This is not a Widevine PSSH box. Try making the request for the key-IDs.
195  // Even if this is a different key-system, it should still work. Either
196  // the server will not recognize it and return an error, or it will
197  // recognize it and the key must be correct (or the content is bad).
198  return FetchKeys(info.key_ids());
199  } else {
200  return Status(error::NOT_FOUND, "No key IDs given in PSSH box.");
201  }
202 }
203 
205  const std::vector<std::vector<uint8_t>>& key_ids) {
206  base::AutoLock scoped_lock(lock_);
207  request_dict_.Clear();
208  std::string pssh_data_base64_string;
209 
210  // Generate Widevine PSSH data from the key-IDs.
211  WidevinePsshData widevine_pssh_data;
212  for (size_t i = 0; i < key_ids.size(); i++) {
213  widevine_pssh_data.add_key_id(key_ids[i].data(), key_ids[i].size());
214  }
215 
216  const std::string serialized_string = widevine_pssh_data.SerializeAsString();
217  std::vector<uint8_t> pssh_data(serialized_string.begin(),
218  serialized_string.end());
219 
220  BytesToBase64String(pssh_data, &pssh_data_base64_string);
221  request_dict_.SetString("pssh_data", pssh_data_base64_string);
222  return FetchKeysInternal(!kEnableKeyRotation, 0, false);
223 }
224 
226  base::AutoLock scoped_lock(lock_);
227  request_dict_.Clear();
228  // Javascript/JSON does not support int64_t or unsigned numbers. Use double
229  // instead as 32-bit integer can be lossless represented using double.
230  request_dict_.SetDouble("asset_id", asset_id);
231  return FetchKeysInternal(!kEnableKeyRotation, 0, true);
232 }
233 
234 Status WidevineKeySource::GetKey(TrackType track_type, EncryptionKey* key) {
235  DCHECK(key);
236  if (encryption_key_map_.find(track_type) == encryption_key_map_.end()) {
237  return Status(error::INTERNAL_ERROR,
238  "Cannot find key of type " + TrackTypeToString(track_type));
239  }
240  *key = *encryption_key_map_[track_type];
241  return Status::OK;
242 }
243 
244 Status WidevineKeySource::GetKey(const std::vector<uint8_t>& key_id,
245  EncryptionKey* key) {
246  DCHECK(key);
247  for (std::map<TrackType, EncryptionKey*>::iterator iter =
248  encryption_key_map_.begin();
249  iter != encryption_key_map_.end();
250  ++iter) {
251  if (iter->second->key_id == key_id) {
252  *key = *iter->second;
253  return Status::OK;
254  }
255  }
256  return Status(error::INTERNAL_ERROR,
257  "Cannot find key with specified key ID");
258 }
259 
260 Status WidevineKeySource::GetCryptoPeriodKey(uint32_t crypto_period_index,
261  TrackType track_type,
262  EncryptionKey* key) {
263  DCHECK(key_production_thread_.HasBeenStarted());
264  // TODO(kqyang): This is not elegant. Consider refactoring later.
265  {
266  base::AutoLock scoped_lock(lock_);
267  if (!key_production_started_) {
268  // Another client may have a slightly smaller starting crypto period
269  // index. Set the initial value to account for that.
270  first_crypto_period_index_ =
271  crypto_period_index ? crypto_period_index - 1 : 0;
272  DCHECK(!key_pool_);
273  key_pool_.reset(new EncryptionKeyQueue(crypto_period_count_,
274  first_crypto_period_index_));
275  start_key_production_.Signal();
276  key_production_started_ = true;
277  }
278  }
279  return GetKeyInternal(crypto_period_index, track_type, key);
280 }
281 
282 void WidevineKeySource::set_signer(scoped_ptr<RequestSigner> signer) {
283  signer_ = signer.Pass();
284 }
285 
286 void WidevineKeySource::set_key_fetcher(scoped_ptr<KeyFetcher> key_fetcher) {
287  key_fetcher_ = key_fetcher.Pass();
288 }
289 
290 Status WidevineKeySource::GetKeyInternal(uint32_t crypto_period_index,
291  TrackType track_type,
292  EncryptionKey* key) {
293  DCHECK(key_pool_);
294  DCHECK(key);
295  DCHECK_LE(track_type, NUM_VALID_TRACK_TYPES);
296  DCHECK_NE(track_type, TRACK_TYPE_UNKNOWN);
297 
298  scoped_refptr<RefCountedEncryptionKeyMap> ref_counted_encryption_key_map;
299  Status status =
300  key_pool_->Peek(crypto_period_index, &ref_counted_encryption_key_map,
301  kGetKeyTimeoutInSeconds * 1000);
302  if (!status.ok()) {
303  if (status.error_code() == error::STOPPED) {
304  CHECK(!common_encryption_request_status_.ok());
305  return common_encryption_request_status_;
306  }
307  return status;
308  }
309 
310  EncryptionKeyMap& encryption_key_map = ref_counted_encryption_key_map->map();
311  if (encryption_key_map.find(track_type) == encryption_key_map.end()) {
312  return Status(error::INTERNAL_ERROR,
313  "Cannot find key of type " + TrackTypeToString(track_type));
314  }
315  *key = *encryption_key_map[track_type];
316  return Status::OK;
317 }
318 
319 void WidevineKeySource::FetchKeysTask() {
320  // Wait until key production is signaled.
321  start_key_production_.Wait();
322  if (!key_pool_ || key_pool_->Stopped())
323  return;
324 
325  Status status = FetchKeysInternal(kEnableKeyRotation,
326  first_crypto_period_index_,
327  false);
328  while (status.ok()) {
329  first_crypto_period_index_ += crypto_period_count_;
330  status = FetchKeysInternal(kEnableKeyRotation,
331  first_crypto_period_index_,
332  false);
333  }
334  common_encryption_request_status_ = status;
335  key_pool_->Stop();
336 }
337 
338 Status WidevineKeySource::FetchKeysInternal(bool enable_key_rotation,
339  uint32_t first_crypto_period_index,
340  bool widevine_classic) {
341  std::string request;
342  FillRequest(enable_key_rotation,
343  first_crypto_period_index,
344  &request);
345 
346  std::string message;
347  Status status = GenerateKeyMessage(request, &message);
348  if (!status.ok())
349  return status;
350  VLOG(1) << "Message: " << message;
351 
352  std::string raw_response;
353  int64_t sleep_duration = kFirstRetryDelayMilliseconds;
354 
355  // Perform client side retries if seeing server transient error to workaround
356  // server limitation.
357  for (int i = 0; i < kNumTransientErrorRetries; ++i) {
358  status = key_fetcher_->FetchKeys(server_url_, message, &raw_response);
359  if (status.ok()) {
360  VLOG(1) << "Retry [" << i << "] Response:" << raw_response;
361 
362  std::string response;
363  if (!DecodeResponse(raw_response, &response)) {
364  return Status(error::SERVER_ERROR,
365  "Failed to decode response '" + raw_response + "'.");
366  }
367 
368  bool transient_error = false;
369  if (ExtractEncryptionKey(enable_key_rotation,
370  widevine_classic,
371  response,
372  &transient_error))
373  return Status::OK;
374 
375  if (!transient_error) {
376  return Status(
377  error::SERVER_ERROR,
378  "Failed to extract encryption key from '" + response + "'.");
379  }
380  } else if (status.error_code() != error::TIME_OUT) {
381  return status;
382  }
383 
384  // Exponential backoff.
385  if (i != kNumTransientErrorRetries - 1) {
386  base::PlatformThread::Sleep(
387  base::TimeDelta::FromMilliseconds(sleep_duration));
388  sleep_duration *= 2;
389  }
390  }
391  return Status(error::SERVER_ERROR,
392  "Failed to recover from server internal error.");
393 }
394 
395 void WidevineKeySource::FillRequest(bool enable_key_rotation,
396  uint32_t first_crypto_period_index,
397  std::string* request) {
398  DCHECK(request);
399  DCHECK(!request_dict_.empty());
400 
401  // Build tracks.
402  base::ListValue* tracks = new base::ListValue();
403 
404  base::DictionaryValue* track_sd = new base::DictionaryValue();
405  track_sd->SetString("type", "SD");
406  tracks->Append(track_sd);
407  base::DictionaryValue* track_hd = new base::DictionaryValue();
408  track_hd->SetString("type", "HD");
409  tracks->Append(track_hd);
410  base::DictionaryValue* track_audio = new base::DictionaryValue();
411  track_audio->SetString("type", "AUDIO");
412  tracks->Append(track_audio);
413 
414  request_dict_.Set("tracks", tracks);
415 
416  // Build DRM types.
417  base::ListValue* drm_types = new base::ListValue();
418  drm_types->AppendString("WIDEVINE");
419  request_dict_.Set("drm_types", drm_types);
420 
421  // Build key rotation fields.
422  if (enable_key_rotation) {
423  // Javascript/JSON does not support int64_t or unsigned numbers. Use double
424  // instead as 32-bit integer can be lossless represented using double.
425  request_dict_.SetDouble("first_crypto_period_index",
426  first_crypto_period_index);
427  request_dict_.SetInteger("crypto_period_count", crypto_period_count_);
428  }
429 
430  base::JSONWriter::WriteWithOptions(
431  request_dict_,
432  // Write doubles that have no fractional part as a normal integer, i.e.
433  // without using exponential notation or appending a '.0'.
434  base::JSONWriter::OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION, request);
435 }
436 
437 Status WidevineKeySource::GenerateKeyMessage(const std::string& request,
438  std::string* message) {
439  DCHECK(message);
440 
441  std::string request_base64_string;
442  base::Base64Encode(request, &request_base64_string);
443 
444  base::DictionaryValue request_dict;
445  request_dict.SetString("request", request_base64_string);
446 
447  // Sign the request.
448  if (signer_) {
449  std::string signature;
450  if (!signer_->GenerateSignature(request, &signature))
451  return Status(error::INTERNAL_ERROR, "Signature generation failed.");
452 
453  std::string signature_base64_string;
454  base::Base64Encode(signature, &signature_base64_string);
455 
456  request_dict.SetString("signature", signature_base64_string);
457  request_dict.SetString("signer", signer_->signer_name());
458  }
459 
460  base::JSONWriter::Write(request_dict, message);
461  return Status::OK;
462 }
463 
464 bool WidevineKeySource::DecodeResponse(
465  const std::string& raw_response,
466  std::string* response) {
467  DCHECK(response);
468 
469  // Extract base64 formatted response from JSON formatted raw response.
470  scoped_ptr<base::Value> root(base::JSONReader::Read(raw_response));
471  if (!root) {
472  LOG(ERROR) << "'" << raw_response << "' is not in JSON format.";
473  return false;
474  }
475  const base::DictionaryValue* response_dict = NULL;
476  RCHECK(root->GetAsDictionary(&response_dict));
477 
478  std::string response_base64_string;
479  RCHECK(response_dict->GetString("response", &response_base64_string));
480  RCHECK(base::Base64Decode(response_base64_string, response));
481  return true;
482 }
483 
484 bool WidevineKeySource::ExtractEncryptionKey(
485  bool enable_key_rotation,
486  bool widevine_classic,
487  const std::string& response,
488  bool* transient_error) {
489  DCHECK(transient_error);
490  *transient_error = false;
491 
492  scoped_ptr<base::Value> root(base::JSONReader::Read(response));
493  if (!root) {
494  LOG(ERROR) << "'" << response << "' is not in JSON format.";
495  return false;
496  }
497 
498  const base::DictionaryValue* license_dict = NULL;
499  RCHECK(root->GetAsDictionary(&license_dict));
500 
501  std::string license_status;
502  RCHECK(license_dict->GetString("status", &license_status));
503  if (license_status != kLicenseStatusOK) {
504  LOG(ERROR) << "Received non-OK license response: " << response;
505  *transient_error = (license_status == kLicenseStatusTransientError);
506  return false;
507  }
508 
509  const base::ListValue* tracks;
510  RCHECK(license_dict->GetList("tracks", &tracks));
511  // Should have at least one track per crypto_period.
512  RCHECK(enable_key_rotation ? tracks->GetSize() >= 1 * crypto_period_count_
513  : tracks->GetSize() >= 1);
514 
515  int current_crypto_period_index = first_crypto_period_index_;
516 
517  EncryptionKeyMap encryption_key_map;
518  for (size_t i = 0; i < tracks->GetSize(); ++i) {
519  const base::DictionaryValue* track_dict;
520  RCHECK(tracks->GetDictionary(i, &track_dict));
521 
522  if (enable_key_rotation) {
523  int crypto_period_index;
524  RCHECK(
525  track_dict->GetInteger("crypto_period_index", &crypto_period_index));
526  if (crypto_period_index != current_crypto_period_index) {
527  if (crypto_period_index != current_crypto_period_index + 1) {
528  LOG(ERROR) << "Expecting crypto period index "
529  << current_crypto_period_index << " or "
530  << current_crypto_period_index + 1 << "; Seen "
531  << crypto_period_index << " at track " << i;
532  return false;
533  }
534  if (!PushToKeyPool(&encryption_key_map))
535  return false;
536  ++current_crypto_period_index;
537  }
538  }
539 
540  std::string track_type_str;
541  RCHECK(track_dict->GetString("type", &track_type_str));
542  TrackType track_type = GetTrackTypeFromString(track_type_str);
543  DCHECK_NE(TRACK_TYPE_UNKNOWN, track_type);
544  RCHECK(encryption_key_map.find(track_type) == encryption_key_map.end());
545 
546  scoped_ptr<EncryptionKey> encryption_key(new EncryptionKey());
547 
548  if (!GetKeyFromTrack(*track_dict, &encryption_key->key))
549  return false;
550 
551  // Get key ID and PSSH data for CENC content only.
552  if (!widevine_classic) {
553  if (!GetKeyIdFromTrack(*track_dict, &encryption_key->key_id))
554  return false;
555 
556  ProtectionSystemSpecificInfo info;
557  info.add_key_id(encryption_key->key_id);
558  info.set_system_id(kWidevineSystemId, arraysize(kWidevineSystemId));
559  info.set_pssh_box_version(0);
560 
561  std::vector<uint8_t> pssh_data;
562  if (!GetPsshDataFromTrack(*track_dict, &pssh_data))
563  return false;
564  info.set_pssh_data(pssh_data);
565 
566  encryption_key->key_system_info.push_back(info);
567  }
568  encryption_key_map[track_type] = encryption_key.release();
569  }
570 
571  // NOTE: To support version 1 pssh, update ProtectionSystemSpecificInfo to
572  // include all key IDs in |encryption_key_map|.
573  DCHECK(!encryption_key_map.empty());
574  if (!enable_key_rotation) {
575  encryption_key_map_ = encryption_key_map;
576  return true;
577  }
578  return PushToKeyPool(&encryption_key_map);
579 }
580 
581 bool WidevineKeySource::PushToKeyPool(
582  EncryptionKeyMap* encryption_key_map) {
583  DCHECK(key_pool_);
584  DCHECK(encryption_key_map);
585  Status status =
586  key_pool_->Push(scoped_refptr<RefCountedEncryptionKeyMap>(
587  new RefCountedEncryptionKeyMap(encryption_key_map)),
588  kInfiniteTimeout);
589  encryption_key_map->clear();
590  if (!status.ok()) {
591  DCHECK_EQ(error::STOPPED, status.error_code());
592  return false;
593  }
594  return true;
595 }
596 
597 } // namespace media
598 } // namespace edash_packager
WidevineKeySource(const std::string &server_url)
void set_signer(scoped_ptr< RequestSigner > signer)
Status GetKey(TrackType track_type, EncryptionKey *key) override
void set_key_fetcher(scoped_ptr< KeyFetcher > key_fetcher)
Status FetchKeys(const std::vector< uint8_t > &content_id, const std::string &policy) override
Status GetCryptoPeriodKey(uint32_t crypto_period_index, TrackType track_type, EncryptionKey *key) override
static TrackType GetTrackTypeFromString(const std::string &track_type_string)
Convert string representation of track type to enum representation.
Definition: key_source.cc:142
static std::string TrackTypeToString(TrackType track_type)
Convert TrackType to string.
Definition: key_source.cc:156