7 #include "packager/media/base/widevine_key_source.h"
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/request_signer.h"
22 LOG(ERROR) << "Failure while processing: " << #x; \
27 namespace edash_packager {
30 const bool kEnableKeyRotation =
true;
32 const char kLicenseStatusOK[] =
"OK";
35 const char kLicenseStatusTransientError[] =
"INTERNAL_ERROR";
39 const int kNumTransientErrorRetries = 5;
40 const int kFirstRetryDelayMilliseconds = 1000;
44 const int kDefaultCryptoPeriodCount = 10;
45 const int kGetKeyTimeoutInSeconds = 5 * 60;
46 const int kKeyFetchTimeoutInSeconds = 60;
48 bool Base64StringToBytes(
const std::string& base64_string,
49 std::vector<uint8_t>* bytes) {
52 if (!base::Base64Decode(base64_string, &str))
54 bytes->assign(str.begin(), str.end());
58 void BytesToBase64String(
const std::vector<uint8_t>& bytes,
59 std::string* base64_string) {
60 DCHECK(base64_string);
61 base::Base64Encode(base::StringPiece(reinterpret_cast<const char*>
62 (bytes.data()), bytes.size()),
66 bool GetKeyFromTrack(
const base::DictionaryValue& track_dict,
67 std::vector<uint8_t>* key) {
69 std::string key_base64_string;
70 RCHECK(track_dict.GetString(
"key", &key_base64_string));
71 VLOG(2) <<
"Key:" << key_base64_string;
72 RCHECK(Base64StringToBytes(key_base64_string, key));
76 bool GetKeyIdFromTrack(
const base::DictionaryValue& track_dict,
77 std::vector<uint8_t>* key_id) {
79 std::string key_id_base64_string;
80 RCHECK(track_dict.GetString(
"key_id", &key_id_base64_string));
81 VLOG(2) <<
"Keyid:" << key_id_base64_string;
82 RCHECK(Base64StringToBytes(key_id_base64_string, key_id));
86 bool GetPsshDataFromTrack(
const base::DictionaryValue& track_dict,
87 std::vector<uint8_t>* pssh_data) {
90 const base::ListValue* pssh_list;
91 RCHECK(track_dict.GetList(
"pssh", &pssh_list));
94 DCHECK_EQ(1u, pssh_list->GetSize());
96 const base::DictionaryValue* pssh_dict;
97 RCHECK(pssh_list->GetDictionary(0, &pssh_dict));
99 RCHECK(pssh_dict->GetString(
"drm_type", &drm_type));
100 if (drm_type !=
"WIDEVINE") {
101 LOG(ERROR) <<
"Expecting drm_type 'WIDEVINE', get '" << drm_type <<
"'.";
104 std::string pssh_data_base64_string;
105 RCHECK(pssh_dict->GetString(
"data", &pssh_data_base64_string));
107 VLOG(2) <<
"Pssh Data:" << pssh_data_base64_string;
108 RCHECK(Base64StringToBytes(pssh_data_base64_string, pssh_data));
117 class WidevineKeySource::RefCountedEncryptionKeyMap
118 :
public base::RefCountedThreadSafe<RefCountedEncryptionKeyMap> {
120 explicit RefCountedEncryptionKeyMap(EncryptionKeyMap* encryption_key_map) {
121 DCHECK(encryption_key_map);
122 encryption_key_map_.swap(*encryption_key_map);
125 std::map<KeySource::TrackType, EncryptionKey*>& map() {
126 return encryption_key_map_;
130 friend class base::RefCountedThreadSafe<RefCountedEncryptionKeyMap>;
132 ~RefCountedEncryptionKeyMap() { STLDeleteValues(&encryption_key_map_); }
134 EncryptionKeyMap encryption_key_map_;
136 DISALLOW_COPY_AND_ASSIGN(RefCountedEncryptionKeyMap);
140 : key_production_thread_(
"KeyProductionThread",
142 base::Unretained(this))),
144 server_url_(server_url),
145 crypto_period_count_(kDefaultCryptoPeriodCount),
146 key_production_started_(false),
147 start_key_production_(false, false),
148 first_crypto_period_index_(0) {
149 key_production_thread_.Start();
152 WidevineKeySource::~WidevineKeySource() {
155 if (key_production_thread_.HasBeenStarted()) {
158 start_key_production_.Signal();
159 key_production_thread_.Join();
161 STLDeleteValues(&encryption_key_map_);
165 const std::string& policy) {
166 base::AutoLock scoped_lock(lock_);
167 request_dict_.Clear();
168 std::string content_id_base64_string;
169 BytesToBase64String(content_id, &content_id_base64_string);
170 request_dict_.SetString(
"content_id", content_id_base64_string);
171 request_dict_.SetString(
"policy", policy);
172 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
176 base::AutoLock scoped_lock(lock_);
177 request_dict_.Clear();
178 std::string pssh_data_base64_string;
179 BytesToBase64String(pssh_data, &pssh_data_base64_string);
180 request_dict_.SetString(
"pssh_data", pssh_data_base64_string);
181 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
185 base::AutoLock scoped_lock(lock_);
186 request_dict_.Clear();
187 request_dict_.SetInteger(
"asset_id", asset_id);
188 return FetchKeysInternal(!kEnableKeyRotation, 0,
true);
193 if (encryption_key_map_.find(track_type) == encryption_key_map_.end()) {
194 return Status(error::INTERNAL_ERROR,
197 *key = *encryption_key_map_[track_type];
204 for (std::map<TrackType, EncryptionKey*>::iterator iter =
205 encryption_key_map_.begin();
206 iter != encryption_key_map_.end();
208 if (iter->second->key_id == key_id) {
209 *key = *iter->second;
213 return Status(error::INTERNAL_ERROR,
214 "Cannot find key with specified key ID");
218 TrackType track_type,
220 DCHECK(key_production_thread_.HasBeenStarted());
223 base::AutoLock scoped_lock(lock_);
224 if (!key_production_started_) {
227 first_crypto_period_index_ =
228 crypto_period_index ? crypto_period_index - 1 : 0;
231 first_crypto_period_index_));
232 start_key_production_.Signal();
233 key_production_started_ =
true;
236 return GetKeyInternal(crypto_period_index, track_type, key);
240 return "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";
244 signer_ = signer.Pass();
248 key_fetcher_ = key_fetcher.Pass();
251 Status WidevineKeySource::GetKeyInternal(uint32_t crypto_period_index,
252 TrackType track_type,
256 DCHECK_LE(track_type, NUM_VALID_TRACK_TYPES);
257 DCHECK_NE(track_type, TRACK_TYPE_UNKNOWN);
259 scoped_refptr<RefCountedEncryptionKeyMap> ref_counted_encryption_key_map;
261 key_pool_->Peek(crypto_period_index, &ref_counted_encryption_key_map,
262 kGetKeyTimeoutInSeconds * 1000);
264 if (status.error_code() == error::STOPPED) {
265 CHECK(!common_encryption_request_status_.ok());
266 return common_encryption_request_status_;
271 EncryptionKeyMap& encryption_key_map = ref_counted_encryption_key_map->map();
272 if (encryption_key_map.find(track_type) == encryption_key_map.end()) {
273 return Status(error::INTERNAL_ERROR,
276 *key = *encryption_key_map[track_type];
280 void WidevineKeySource::FetchKeysTask() {
282 start_key_production_.Wait();
283 if (!key_pool_ || key_pool_->Stopped())
286 Status status = FetchKeysInternal(kEnableKeyRotation,
287 first_crypto_period_index_,
289 while (status.ok()) {
290 first_crypto_period_index_ += crypto_period_count_;
291 status = FetchKeysInternal(kEnableKeyRotation,
292 first_crypto_period_index_,
295 common_encryption_request_status_ = status;
299 Status WidevineKeySource::FetchKeysInternal(
bool enable_key_rotation,
300 uint32_t first_crypto_period_index,
301 bool widevine_classic) {
303 FillRequest(enable_key_rotation,
304 first_crypto_period_index,
308 Status status = GenerateKeyMessage(request, &message);
311 VLOG(1) <<
"Message: " << message;
313 std::string raw_response;
314 int64_t sleep_duration = kFirstRetryDelayMilliseconds;
318 for (
int i = 0; i < kNumTransientErrorRetries; ++i) {
319 status = key_fetcher_->FetchKeys(server_url_, message, &raw_response);
321 VLOG(1) <<
"Retry [" << i <<
"] Response:" << raw_response;
323 std::string response;
324 if (!DecodeResponse(raw_response, &response)) {
325 return Status(error::SERVER_ERROR,
326 "Failed to decode response '" + raw_response +
"'.");
329 bool transient_error =
false;
330 if (ExtractEncryptionKey(enable_key_rotation,
336 if (!transient_error) {
339 "Failed to extract encryption key from '" + response +
"'.");
341 }
else if (status.error_code() != error::TIME_OUT) {
346 if (i != kNumTransientErrorRetries - 1) {
347 base::PlatformThread::Sleep(
348 base::TimeDelta::FromMilliseconds(sleep_duration));
352 return Status(error::SERVER_ERROR,
353 "Failed to recover from server internal error.");
356 void WidevineKeySource::FillRequest(
bool enable_key_rotation,
357 uint32_t first_crypto_period_index,
358 std::string* request) {
360 DCHECK(!request_dict_.empty());
363 base::ListValue* tracks =
new base::ListValue();
365 base::DictionaryValue* track_sd =
new base::DictionaryValue();
366 track_sd->SetString(
"type",
"SD");
367 tracks->Append(track_sd);
368 base::DictionaryValue* track_hd =
new base::DictionaryValue();
369 track_hd->SetString(
"type",
"HD");
370 tracks->Append(track_hd);
371 base::DictionaryValue* track_audio =
new base::DictionaryValue();
372 track_audio->SetString(
"type",
"AUDIO");
373 tracks->Append(track_audio);
375 request_dict_.Set(
"tracks", tracks);
378 base::ListValue* drm_types =
new base::ListValue();
379 drm_types->AppendString(
"WIDEVINE");
380 request_dict_.Set(
"drm_types", drm_types);
383 if (enable_key_rotation) {
384 request_dict_.SetInteger(
"first_crypto_period_index",
385 first_crypto_period_index);
386 request_dict_.SetInteger(
"crypto_period_count", crypto_period_count_);
389 base::JSONWriter::Write(request_dict_, request);
392 Status WidevineKeySource::GenerateKeyMessage(
const std::string& request,
393 std::string* message) {
396 std::string request_base64_string;
397 base::Base64Encode(request, &request_base64_string);
399 base::DictionaryValue request_dict;
400 request_dict.SetString(
"request", request_base64_string);
404 std::string signature;
405 if (!signer_->GenerateSignature(request, &signature))
406 return Status(error::INTERNAL_ERROR,
"Signature generation failed.");
408 std::string signature_base64_string;
409 base::Base64Encode(signature, &signature_base64_string);
411 request_dict.SetString(
"signature", signature_base64_string);
412 request_dict.SetString(
"signer", signer_->signer_name());
415 base::JSONWriter::Write(request_dict, message);
419 bool WidevineKeySource::DecodeResponse(
420 const std::string& raw_response,
421 std::string* response) {
425 scoped_ptr<base::Value> root(base::JSONReader::Read(raw_response));
427 LOG(ERROR) <<
"'" << raw_response <<
"' is not in JSON format.";
430 const base::DictionaryValue* response_dict = NULL;
431 RCHECK(root->GetAsDictionary(&response_dict));
433 std::string response_base64_string;
434 RCHECK(response_dict->GetString(
"response", &response_base64_string));
435 RCHECK(base::Base64Decode(response_base64_string, response));
439 bool WidevineKeySource::ExtractEncryptionKey(
440 bool enable_key_rotation,
441 bool widevine_classic,
442 const std::string& response,
443 bool* transient_error) {
444 DCHECK(transient_error);
445 *transient_error =
false;
447 scoped_ptr<base::Value> root(base::JSONReader::Read(response));
449 LOG(ERROR) <<
"'" << response <<
"' is not in JSON format.";
453 const base::DictionaryValue* license_dict = NULL;
454 RCHECK(root->GetAsDictionary(&license_dict));
456 std::string license_status;
457 RCHECK(license_dict->GetString(
"status", &license_status));
458 if (license_status != kLicenseStatusOK) {
459 LOG(ERROR) <<
"Received non-OK license response: " << response;
460 *transient_error = (license_status == kLicenseStatusTransientError);
464 const base::ListValue* tracks;
465 RCHECK(license_dict->GetList(
"tracks", &tracks));
467 RCHECK(enable_key_rotation ? tracks->GetSize() >= 1 * crypto_period_count_
468 : tracks->GetSize() >= 1);
470 int current_crypto_period_index = first_crypto_period_index_;
472 EncryptionKeyMap encryption_key_map;
473 for (
size_t i = 0; i < tracks->GetSize(); ++i) {
474 const base::DictionaryValue* track_dict;
475 RCHECK(tracks->GetDictionary(i, &track_dict));
477 if (enable_key_rotation) {
478 int crypto_period_index;
480 track_dict->GetInteger(
"crypto_period_index", &crypto_period_index));
481 if (crypto_period_index != current_crypto_period_index) {
482 if (crypto_period_index != current_crypto_period_index + 1) {
483 LOG(ERROR) <<
"Expecting crypto period index "
484 << current_crypto_period_index <<
" or "
485 << current_crypto_period_index + 1 <<
"; Seen "
486 << crypto_period_index <<
" at track " << i;
489 if (!PushToKeyPool(&encryption_key_map))
491 ++current_crypto_period_index;
495 std::string track_type_str;
496 RCHECK(track_dict->GetString(
"type", &track_type_str));
498 DCHECK_NE(TRACK_TYPE_UNKNOWN, track_type);
499 RCHECK(encryption_key_map.find(track_type) == encryption_key_map.end());
501 scoped_ptr<EncryptionKey> encryption_key(
new EncryptionKey());
503 if (!GetKeyFromTrack(*track_dict, &encryption_key->key))
507 if (!widevine_classic) {
508 if (!GetKeyIdFromTrack(*track_dict, &encryption_key->key_id))
511 std::vector<uint8_t> pssh_data;
512 if (!GetPsshDataFromTrack(*track_dict, &pssh_data))
516 encryption_key_map[track_type] = encryption_key.release();
519 DCHECK(!encryption_key_map.empty());
520 if (!enable_key_rotation) {
521 encryption_key_map_ = encryption_key_map;
524 return PushToKeyPool(&encryption_key_map);
527 bool WidevineKeySource::PushToKeyPool(
528 EncryptionKeyMap* encryption_key_map) {
530 DCHECK(encryption_key_map);
532 key_pool_->Push(scoped_refptr<RefCountedEncryptionKeyMap>(
533 new RefCountedEncryptionKeyMap(encryption_key_map)),
535 encryption_key_map->clear();
537 DCHECK_EQ(error::STOPPED, status.error_code());