7 #include "packager/media/base/widevine_key_source.h"
11 #include "packager/base/base64.h"
12 #include "packager/base/bind.h"
13 #include "packager/base/json/json_reader.h"
14 #include "packager/base/json/json_writer.h"
15 #include "packager/base/memory/ref_counted.h"
16 #include "packager/base/stl_util.h"
17 #include "packager/media/base/fixed_key_source.h"
18 #include "packager/media/base/http_key_fetcher.h"
19 #include "packager/media/base/producer_consumer_queue.h"
20 #include "packager/media/base/protection_system_specific_info.h"
21 #include "packager/media/base/request_signer.h"
22 #include "packager/media/base/widevine_pssh_data.pb.h"
27 LOG(ERROR) << "Failure while processing: " << #x; \
32 namespace edash_packager {
35 const bool kEnableKeyRotation =
true;
37 const char kLicenseStatusOK[] =
"OK";
40 const char kLicenseStatusTransientError[] =
"INTERNAL_ERROR";
44 const int kNumTransientErrorRetries = 5;
45 const int kFirstRetryDelayMilliseconds = 1000;
49 const int kDefaultCryptoPeriodCount = 10;
50 const int kGetKeyTimeoutInSeconds = 5 * 60;
51 const int kKeyFetchTimeoutInSeconds = 60;
53 const uint8_t kWidevineSystemId[] = {0xed, 0xef, 0x8b, 0xa9, 0x79, 0xd6,
54 0x4a, 0xce, 0xa3, 0xc8, 0x27, 0xdc,
55 0xd5, 0x1d, 0x21, 0xed};
57 bool Base64StringToBytes(
const std::string& base64_string,
58 std::vector<uint8_t>* bytes) {
61 if (!base::Base64Decode(base64_string, &str))
63 bytes->assign(str.begin(), str.end());
67 void BytesToBase64String(
const std::vector<uint8_t>& bytes,
68 std::string* base64_string) {
69 DCHECK(base64_string);
70 base::Base64Encode(base::StringPiece(reinterpret_cast<const char*>
71 (bytes.data()), bytes.size()),
75 bool GetKeyFromTrack(
const base::DictionaryValue& track_dict,
76 std::vector<uint8_t>* key) {
78 std::string key_base64_string;
79 RCHECK(track_dict.GetString(
"key", &key_base64_string));
80 VLOG(2) <<
"Key:" << key_base64_string;
81 RCHECK(Base64StringToBytes(key_base64_string, key));
85 bool GetKeyIdFromTrack(
const base::DictionaryValue& track_dict,
86 std::vector<uint8_t>* key_id) {
88 std::string key_id_base64_string;
89 RCHECK(track_dict.GetString(
"key_id", &key_id_base64_string));
90 VLOG(2) <<
"Keyid:" << key_id_base64_string;
91 RCHECK(Base64StringToBytes(key_id_base64_string, key_id));
95 bool GetPsshDataFromTrack(
const base::DictionaryValue& track_dict,
96 std::vector<uint8_t>* pssh_data) {
99 const base::ListValue* pssh_list;
100 RCHECK(track_dict.GetList(
"pssh", &pssh_list));
103 DCHECK_EQ(1u, pssh_list->GetSize());
105 const base::DictionaryValue* pssh_dict;
106 RCHECK(pssh_list->GetDictionary(0, &pssh_dict));
107 std::string drm_type;
108 RCHECK(pssh_dict->GetString(
"drm_type", &drm_type));
109 if (drm_type !=
"WIDEVINE") {
110 LOG(ERROR) <<
"Expecting drm_type 'WIDEVINE', get '" << drm_type <<
"'.";
113 std::string pssh_data_base64_string;
114 RCHECK(pssh_dict->GetString(
"data", &pssh_data_base64_string));
116 VLOG(2) <<
"Pssh Data:" << pssh_data_base64_string;
117 RCHECK(Base64StringToBytes(pssh_data_base64_string, pssh_data));
126 class WidevineKeySource::RefCountedEncryptionKeyMap
127 :
public base::RefCountedThreadSafe<RefCountedEncryptionKeyMap> {
129 explicit RefCountedEncryptionKeyMap(EncryptionKeyMap* encryption_key_map) {
130 DCHECK(encryption_key_map);
131 encryption_key_map_.swap(*encryption_key_map);
134 std::map<KeySource::TrackType, EncryptionKey*>& map() {
135 return encryption_key_map_;
139 friend class base::RefCountedThreadSafe<RefCountedEncryptionKeyMap>;
141 ~RefCountedEncryptionKeyMap() { STLDeleteValues(&encryption_key_map_); }
143 EncryptionKeyMap encryption_key_map_;
145 DISALLOW_COPY_AND_ASSIGN(RefCountedEncryptionKeyMap);
149 bool add_common_pssh)
150 : key_production_thread_(
"KeyProductionThread",
152 base::Unretained(this))),
154 server_url_(server_url),
155 crypto_period_count_(kDefaultCryptoPeriodCount),
156 add_common_pssh_(add_common_pssh),
157 key_production_started_(false),
158 start_key_production_(false, false),
159 first_crypto_period_index_(0) {
160 key_production_thread_.Start();
163 WidevineKeySource::~WidevineKeySource() {
166 if (key_production_thread_.HasBeenStarted()) {
169 start_key_production_.Signal();
170 key_production_thread_.Join();
172 STLDeleteValues(&encryption_key_map_);
176 const std::string& policy) {
177 base::AutoLock scoped_lock(lock_);
178 request_dict_.Clear();
179 std::string content_id_base64_string;
180 BytesToBase64String(content_id, &content_id_base64_string);
181 request_dict_.SetString(
"content_id", content_id_base64_string);
182 request_dict_.SetString(
"policy", policy);
183 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
187 const std::vector<uint8_t> widevine_system_id(
188 kWidevineSystemId, kWidevineSystemId + arraysize(kWidevineSystemId));
191 if (!info.
Parse(pssh_box.data(), pssh_box.size()))
192 return Status(error::PARSER_FAILURE,
"Error parsing the PSSH box.");
194 if (info.system_id() == widevine_system_id) {
195 base::AutoLock scoped_lock(lock_);
196 request_dict_.Clear();
197 std::string pssh_data_base64_string;
199 BytesToBase64String(info.pssh_data(), &pssh_data_base64_string);
200 request_dict_.SetString(
"pssh_data", pssh_data_base64_string);
201 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
202 }
else if (!info.key_ids().empty()) {
209 return Status(error::NOT_FOUND,
"No key IDs given in PSSH box.");
214 const std::vector<std::vector<uint8_t>>& key_ids) {
215 base::AutoLock scoped_lock(lock_);
216 request_dict_.Clear();
217 std::string pssh_data_base64_string;
220 WidevinePsshData widevine_pssh_data;
221 for (
size_t i = 0; i < key_ids.size(); i++) {
222 widevine_pssh_data.add_key_id(key_ids[i].data(), key_ids[i].size());
225 const std::string serialized_string = widevine_pssh_data.SerializeAsString();
226 std::vector<uint8_t> pssh_data(serialized_string.begin(),
227 serialized_string.end());
229 BytesToBase64String(pssh_data, &pssh_data_base64_string);
230 request_dict_.SetString(
"pssh_data", pssh_data_base64_string);
231 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
235 base::AutoLock scoped_lock(lock_);
236 request_dict_.Clear();
239 request_dict_.SetDouble(
"asset_id", asset_id);
240 return FetchKeysInternal(!kEnableKeyRotation, 0,
true);
245 if (encryption_key_map_.find(track_type) == encryption_key_map_.end()) {
246 return Status(error::INTERNAL_ERROR,
249 *key = *encryption_key_map_[track_type];
256 for (std::map<TrackType, EncryptionKey*>::iterator iter =
257 encryption_key_map_.begin();
258 iter != encryption_key_map_.end();
260 if (iter->second->key_id == key_id) {
261 *key = *iter->second;
265 return Status(error::INTERNAL_ERROR,
266 "Cannot find key with specified key ID");
270 TrackType track_type,
272 DCHECK(key_production_thread_.HasBeenStarted());
275 base::AutoLock scoped_lock(lock_);
276 if (!key_production_started_) {
279 first_crypto_period_index_ =
280 crypto_period_index ? crypto_period_index - 1 : 0;
283 first_crypto_period_index_));
284 start_key_production_.Signal();
285 key_production_started_ =
true;
288 return GetKeyInternal(crypto_period_index, track_type, key);
292 signer_ = signer.Pass();
296 key_fetcher_ = key_fetcher.Pass();
299 Status WidevineKeySource::GetKeyInternal(uint32_t crypto_period_index,
300 TrackType track_type,
304 DCHECK_LE(track_type, NUM_VALID_TRACK_TYPES);
305 DCHECK_NE(track_type, TRACK_TYPE_UNKNOWN);
307 scoped_refptr<RefCountedEncryptionKeyMap> ref_counted_encryption_key_map;
309 key_pool_->Peek(crypto_period_index, &ref_counted_encryption_key_map,
310 kGetKeyTimeoutInSeconds * 1000);
312 if (status.error_code() == error::STOPPED) {
313 CHECK(!common_encryption_request_status_.ok());
314 return common_encryption_request_status_;
319 EncryptionKeyMap& encryption_key_map = ref_counted_encryption_key_map->map();
320 if (encryption_key_map.find(track_type) == encryption_key_map.end()) {
321 return Status(error::INTERNAL_ERROR,
324 *key = *encryption_key_map[track_type];
328 void WidevineKeySource::FetchKeysTask() {
330 start_key_production_.Wait();
331 if (!key_pool_ || key_pool_->Stopped())
334 Status status = FetchKeysInternal(kEnableKeyRotation,
335 first_crypto_period_index_,
337 while (status.ok()) {
338 first_crypto_period_index_ += crypto_period_count_;
339 status = FetchKeysInternal(kEnableKeyRotation,
340 first_crypto_period_index_,
343 common_encryption_request_status_ = status;
347 Status WidevineKeySource::FetchKeysInternal(
bool enable_key_rotation,
348 uint32_t first_crypto_period_index,
349 bool widevine_classic) {
351 FillRequest(enable_key_rotation,
352 first_crypto_period_index,
356 Status status = GenerateKeyMessage(request, &message);
359 VLOG(1) <<
"Message: " << message;
361 std::string raw_response;
362 int64_t sleep_duration = kFirstRetryDelayMilliseconds;
366 for (
int i = 0; i < kNumTransientErrorRetries; ++i) {
367 status = key_fetcher_->FetchKeys(server_url_, message, &raw_response);
369 VLOG(1) <<
"Retry [" << i <<
"] Response:" << raw_response;
371 std::string response;
372 if (!DecodeResponse(raw_response, &response)) {
373 return Status(error::SERVER_ERROR,
374 "Failed to decode response '" + raw_response +
"'.");
377 bool transient_error =
false;
378 if (ExtractEncryptionKey(enable_key_rotation,
384 if (!transient_error) {
387 "Failed to extract encryption key from '" + response +
"'.");
389 }
else if (status.error_code() != error::TIME_OUT) {
394 if (i != kNumTransientErrorRetries - 1) {
395 base::PlatformThread::Sleep(
396 base::TimeDelta::FromMilliseconds(sleep_duration));
400 return Status(error::SERVER_ERROR,
401 "Failed to recover from server internal error.");
404 void WidevineKeySource::FillRequest(
bool enable_key_rotation,
405 uint32_t first_crypto_period_index,
406 std::string* request) {
408 DCHECK(!request_dict_.empty());
411 base::ListValue* tracks =
new base::ListValue();
413 base::DictionaryValue* track_sd =
new base::DictionaryValue();
414 track_sd->SetString(
"type",
"SD");
415 tracks->Append(track_sd);
416 base::DictionaryValue* track_hd =
new base::DictionaryValue();
417 track_hd->SetString(
"type",
"HD");
418 tracks->Append(track_hd);
419 base::DictionaryValue* track_audio =
new base::DictionaryValue();
420 track_audio->SetString(
"type",
"AUDIO");
421 tracks->Append(track_audio);
423 request_dict_.Set(
"tracks", tracks);
426 base::ListValue* drm_types =
new base::ListValue();
427 drm_types->AppendString(
"WIDEVINE");
428 request_dict_.Set(
"drm_types", drm_types);
431 if (enable_key_rotation) {
434 request_dict_.SetDouble(
"first_crypto_period_index",
435 first_crypto_period_index);
436 request_dict_.SetInteger(
"crypto_period_count", crypto_period_count_);
439 base::JSONWriter::WriteWithOptions(
443 base::JSONWriter::OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION, request);
446 Status WidevineKeySource::GenerateKeyMessage(
const std::string& request,
447 std::string* message) {
450 std::string request_base64_string;
451 base::Base64Encode(request, &request_base64_string);
453 base::DictionaryValue request_dict;
454 request_dict.SetString(
"request", request_base64_string);
458 std::string signature;
459 if (!signer_->GenerateSignature(request, &signature))
460 return Status(error::INTERNAL_ERROR,
"Signature generation failed.");
462 std::string signature_base64_string;
463 base::Base64Encode(signature, &signature_base64_string);
465 request_dict.SetString(
"signature", signature_base64_string);
466 request_dict.SetString(
"signer", signer_->signer_name());
469 base::JSONWriter::Write(request_dict, message);
473 bool WidevineKeySource::DecodeResponse(
474 const std::string& raw_response,
475 std::string* response) {
479 scoped_ptr<base::Value> root(base::JSONReader::Read(raw_response));
481 LOG(ERROR) <<
"'" << raw_response <<
"' is not in JSON format.";
484 const base::DictionaryValue* response_dict = NULL;
485 RCHECK(root->GetAsDictionary(&response_dict));
487 std::string response_base64_string;
488 RCHECK(response_dict->GetString(
"response", &response_base64_string));
489 RCHECK(base::Base64Decode(response_base64_string, response));
493 bool WidevineKeySource::ExtractEncryptionKey(
494 bool enable_key_rotation,
495 bool widevine_classic,
496 const std::string& response,
497 bool* transient_error) {
498 DCHECK(transient_error);
499 *transient_error =
false;
501 scoped_ptr<base::Value> root(base::JSONReader::Read(response));
503 LOG(ERROR) <<
"'" << response <<
"' is not in JSON format.";
507 const base::DictionaryValue* license_dict = NULL;
508 RCHECK(root->GetAsDictionary(&license_dict));
510 std::string license_status;
511 RCHECK(license_dict->GetString(
"status", &license_status));
512 if (license_status != kLicenseStatusOK) {
513 LOG(ERROR) <<
"Received non-OK license response: " << response;
514 *transient_error = (license_status == kLicenseStatusTransientError);
518 const base::ListValue* tracks;
519 RCHECK(license_dict->GetList(
"tracks", &tracks));
521 RCHECK(enable_key_rotation ? tracks->GetSize() >= 1 * crypto_period_count_
522 : tracks->GetSize() >= 1);
524 int current_crypto_period_index = first_crypto_period_index_;
526 EncryptionKeyMap encryption_key_map;
527 for (
size_t i = 0; i < tracks->GetSize(); ++i) {
528 const base::DictionaryValue* track_dict;
529 RCHECK(tracks->GetDictionary(i, &track_dict));
531 if (enable_key_rotation) {
532 int crypto_period_index;
534 track_dict->GetInteger(
"crypto_period_index", &crypto_period_index));
535 if (crypto_period_index != current_crypto_period_index) {
536 if (crypto_period_index != current_crypto_period_index + 1) {
537 LOG(ERROR) <<
"Expecting crypto period index "
538 << current_crypto_period_index <<
" or "
539 << current_crypto_period_index + 1 <<
"; Seen "
540 << crypto_period_index <<
" at track " << i;
543 if (!PushToKeyPool(&encryption_key_map))
545 ++current_crypto_period_index;
549 std::string track_type_str;
550 RCHECK(track_dict->GetString(
"type", &track_type_str));
552 DCHECK_NE(TRACK_TYPE_UNKNOWN, track_type);
553 RCHECK(encryption_key_map.find(track_type) == encryption_key_map.end());
555 scoped_ptr<EncryptionKey> encryption_key(
new EncryptionKey());
557 if (!GetKeyFromTrack(*track_dict, &encryption_key->key))
561 if (!widevine_classic) {
562 if (!GetKeyIdFromTrack(*track_dict, &encryption_key->key_id))
565 ProtectionSystemSpecificInfo info;
566 info.add_key_id(encryption_key->key_id);
567 info.set_system_id(kWidevineSystemId, arraysize(kWidevineSystemId));
568 info.set_pssh_box_version(0);
570 std::vector<uint8_t> pssh_data;
571 if (!GetPsshDataFromTrack(*track_dict, &pssh_data))
573 info.set_pssh_data(pssh_data);
575 encryption_key->key_system_info.push_back(info);
577 encryption_key_map[track_type] = encryption_key.release();
582 if (add_common_pssh_ && !widevine_classic) {
583 std::set<std::vector<uint8_t>> key_ids;
584 for (
const EncryptionKeyMap::value_type& pair : encryption_key_map) {
585 key_ids.insert(pair.second->key_id);
589 ProtectionSystemSpecificInfo info;
590 info.set_system_id(kCommonSystemId, arraysize(kCommonSystemId));
591 info.set_pssh_box_version(1);
592 for (
const std::vector<uint8_t>& key_id : key_ids) {
593 info.add_key_id(key_id);
596 for (
const EncryptionKeyMap::value_type& pair : encryption_key_map) {
597 pair.second->key_system_info.push_back(info);
601 DCHECK(!encryption_key_map.empty());
602 if (!enable_key_rotation) {
603 encryption_key_map_ = encryption_key_map;
606 return PushToKeyPool(&encryption_key_map);
609 bool WidevineKeySource::PushToKeyPool(
610 EncryptionKeyMap* encryption_key_map) {
612 DCHECK(encryption_key_map);
614 key_pool_->Push(scoped_refptr<RefCountedEncryptionKeyMap>(
615 new RefCountedEncryptionKeyMap(encryption_key_map)),
617 encryption_key_map->clear();
619 DCHECK_EQ(error::STOPPED, status.error_code());