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();
189 request_dict_.SetDouble(
"asset_id", asset_id);
190 return FetchKeysInternal(!kEnableKeyRotation, 0,
true);
195 if (encryption_key_map_.find(track_type) == encryption_key_map_.end()) {
196 return Status(error::INTERNAL_ERROR,
199 *key = *encryption_key_map_[track_type];
206 for (std::map<TrackType, EncryptionKey*>::iterator iter =
207 encryption_key_map_.begin();
208 iter != encryption_key_map_.end();
210 if (iter->second->key_id == key_id) {
211 *key = *iter->second;
215 return Status(error::INTERNAL_ERROR,
216 "Cannot find key with specified key ID");
220 TrackType track_type,
222 DCHECK(key_production_thread_.HasBeenStarted());
225 base::AutoLock scoped_lock(lock_);
226 if (!key_production_started_) {
229 first_crypto_period_index_ =
230 crypto_period_index ? crypto_period_index - 1 : 0;
233 first_crypto_period_index_));
234 start_key_production_.Signal();
235 key_production_started_ =
true;
238 return GetKeyInternal(crypto_period_index, track_type, key);
242 return "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";
246 signer_ = signer.Pass();
250 key_fetcher_ = key_fetcher.Pass();
253 Status WidevineKeySource::GetKeyInternal(uint32_t crypto_period_index,
254 TrackType track_type,
258 DCHECK_LE(track_type, NUM_VALID_TRACK_TYPES);
259 DCHECK_NE(track_type, TRACK_TYPE_UNKNOWN);
261 scoped_refptr<RefCountedEncryptionKeyMap> ref_counted_encryption_key_map;
263 key_pool_->Peek(crypto_period_index, &ref_counted_encryption_key_map,
264 kGetKeyTimeoutInSeconds * 1000);
266 if (status.error_code() == error::STOPPED) {
267 CHECK(!common_encryption_request_status_.ok());
268 return common_encryption_request_status_;
273 EncryptionKeyMap& encryption_key_map = ref_counted_encryption_key_map->map();
274 if (encryption_key_map.find(track_type) == encryption_key_map.end()) {
275 return Status(error::INTERNAL_ERROR,
278 *key = *encryption_key_map[track_type];
282 void WidevineKeySource::FetchKeysTask() {
284 start_key_production_.Wait();
285 if (!key_pool_ || key_pool_->Stopped())
288 Status status = FetchKeysInternal(kEnableKeyRotation,
289 first_crypto_period_index_,
291 while (status.ok()) {
292 first_crypto_period_index_ += crypto_period_count_;
293 status = FetchKeysInternal(kEnableKeyRotation,
294 first_crypto_period_index_,
297 common_encryption_request_status_ = status;
301 Status WidevineKeySource::FetchKeysInternal(
bool enable_key_rotation,
302 uint32_t first_crypto_period_index,
303 bool widevine_classic) {
305 FillRequest(enable_key_rotation,
306 first_crypto_period_index,
310 Status status = GenerateKeyMessage(request, &message);
313 VLOG(1) <<
"Message: " << message;
315 std::string raw_response;
316 int64_t sleep_duration = kFirstRetryDelayMilliseconds;
320 for (
int i = 0; i < kNumTransientErrorRetries; ++i) {
321 status = key_fetcher_->FetchKeys(server_url_, message, &raw_response);
323 VLOG(1) <<
"Retry [" << i <<
"] Response:" << raw_response;
325 std::string response;
326 if (!DecodeResponse(raw_response, &response)) {
327 return Status(error::SERVER_ERROR,
328 "Failed to decode response '" + raw_response +
"'.");
331 bool transient_error =
false;
332 if (ExtractEncryptionKey(enable_key_rotation,
338 if (!transient_error) {
341 "Failed to extract encryption key from '" + response +
"'.");
343 }
else if (status.error_code() != error::TIME_OUT) {
348 if (i != kNumTransientErrorRetries - 1) {
349 base::PlatformThread::Sleep(
350 base::TimeDelta::FromMilliseconds(sleep_duration));
354 return Status(error::SERVER_ERROR,
355 "Failed to recover from server internal error.");
358 void WidevineKeySource::FillRequest(
bool enable_key_rotation,
359 uint32_t first_crypto_period_index,
360 std::string* request) {
362 DCHECK(!request_dict_.empty());
365 base::ListValue* tracks =
new base::ListValue();
367 base::DictionaryValue* track_sd =
new base::DictionaryValue();
368 track_sd->SetString(
"type",
"SD");
369 tracks->Append(track_sd);
370 base::DictionaryValue* track_hd =
new base::DictionaryValue();
371 track_hd->SetString(
"type",
"HD");
372 tracks->Append(track_hd);
373 base::DictionaryValue* track_audio =
new base::DictionaryValue();
374 track_audio->SetString(
"type",
"AUDIO");
375 tracks->Append(track_audio);
377 request_dict_.Set(
"tracks", tracks);
380 base::ListValue* drm_types =
new base::ListValue();
381 drm_types->AppendString(
"WIDEVINE");
382 request_dict_.Set(
"drm_types", drm_types);
385 if (enable_key_rotation) {
388 request_dict_.SetDouble(
"first_crypto_period_index",
389 first_crypto_period_index);
390 request_dict_.SetInteger(
"crypto_period_count", crypto_period_count_);
393 base::JSONWriter::WriteWithOptions(
397 base::JSONWriter::OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION, request);
400 Status WidevineKeySource::GenerateKeyMessage(
const std::string& request,
401 std::string* message) {
404 std::string request_base64_string;
405 base::Base64Encode(request, &request_base64_string);
407 base::DictionaryValue request_dict;
408 request_dict.SetString(
"request", request_base64_string);
412 std::string signature;
413 if (!signer_->GenerateSignature(request, &signature))
414 return Status(error::INTERNAL_ERROR,
"Signature generation failed.");
416 std::string signature_base64_string;
417 base::Base64Encode(signature, &signature_base64_string);
419 request_dict.SetString(
"signature", signature_base64_string);
420 request_dict.SetString(
"signer", signer_->signer_name());
423 base::JSONWriter::Write(request_dict, message);
427 bool WidevineKeySource::DecodeResponse(
428 const std::string& raw_response,
429 std::string* response) {
433 scoped_ptr<base::Value> root(base::JSONReader::Read(raw_response));
435 LOG(ERROR) <<
"'" << raw_response <<
"' is not in JSON format.";
438 const base::DictionaryValue* response_dict = NULL;
439 RCHECK(root->GetAsDictionary(&response_dict));
441 std::string response_base64_string;
442 RCHECK(response_dict->GetString(
"response", &response_base64_string));
443 RCHECK(base::Base64Decode(response_base64_string, response));
447 bool WidevineKeySource::ExtractEncryptionKey(
448 bool enable_key_rotation,
449 bool widevine_classic,
450 const std::string& response,
451 bool* transient_error) {
452 DCHECK(transient_error);
453 *transient_error =
false;
455 scoped_ptr<base::Value> root(base::JSONReader::Read(response));
457 LOG(ERROR) <<
"'" << response <<
"' is not in JSON format.";
461 const base::DictionaryValue* license_dict = NULL;
462 RCHECK(root->GetAsDictionary(&license_dict));
464 std::string license_status;
465 RCHECK(license_dict->GetString(
"status", &license_status));
466 if (license_status != kLicenseStatusOK) {
467 LOG(ERROR) <<
"Received non-OK license response: " << response;
468 *transient_error = (license_status == kLicenseStatusTransientError);
472 const base::ListValue* tracks;
473 RCHECK(license_dict->GetList(
"tracks", &tracks));
475 RCHECK(enable_key_rotation ? tracks->GetSize() >= 1 * crypto_period_count_
476 : tracks->GetSize() >= 1);
478 int current_crypto_period_index = first_crypto_period_index_;
480 EncryptionKeyMap encryption_key_map;
481 for (
size_t i = 0; i < tracks->GetSize(); ++i) {
482 const base::DictionaryValue* track_dict;
483 RCHECK(tracks->GetDictionary(i, &track_dict));
485 if (enable_key_rotation) {
486 int crypto_period_index;
488 track_dict->GetInteger(
"crypto_period_index", &crypto_period_index));
489 if (crypto_period_index != current_crypto_period_index) {
490 if (crypto_period_index != current_crypto_period_index + 1) {
491 LOG(ERROR) <<
"Expecting crypto period index "
492 << current_crypto_period_index <<
" or "
493 << current_crypto_period_index + 1 <<
"; Seen "
494 << crypto_period_index <<
" at track " << i;
497 if (!PushToKeyPool(&encryption_key_map))
499 ++current_crypto_period_index;
503 std::string track_type_str;
504 RCHECK(track_dict->GetString(
"type", &track_type_str));
506 DCHECK_NE(TRACK_TYPE_UNKNOWN, track_type);
507 RCHECK(encryption_key_map.find(track_type) == encryption_key_map.end());
509 scoped_ptr<EncryptionKey> encryption_key(
new EncryptionKey());
511 if (!GetKeyFromTrack(*track_dict, &encryption_key->key))
515 if (!widevine_classic) {
516 if (!GetKeyIdFromTrack(*track_dict, &encryption_key->key_id))
519 std::vector<uint8_t> pssh_data;
520 if (!GetPsshDataFromTrack(*track_dict, &pssh_data))
524 encryption_key_map[track_type] = encryption_key.release();
527 DCHECK(!encryption_key_map.empty());
528 if (!enable_key_rotation) {
529 encryption_key_map_ = encryption_key_map;
532 return PushToKeyPool(&encryption_key_map);
535 bool WidevineKeySource::PushToKeyPool(
536 EncryptionKeyMap* encryption_key_map) {
538 DCHECK(encryption_key_map);
540 key_pool_->Push(scoped_refptr<RefCountedEncryptionKeyMap>(
541 new RefCountedEncryptionKeyMap(encryption_key_map)),
543 encryption_key_map->clear();
545 DCHECK_EQ(error::STOPPED, status.error_code());