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/rcheck.h"
22 #include "packager/media/base/request_signer.h"
23 #include "packager/media/base/widevine_pssh_data.pb.h"
28 const bool kEnableKeyRotation =
true;
30 const char kLicenseStatusOK[] =
"OK";
33 const char kLicenseStatusTransientError[] =
"INTERNAL_ERROR";
37 const int kNumTransientErrorRetries = 5;
38 const int kFirstRetryDelayMilliseconds = 1000;
42 const int kDefaultCryptoPeriodCount = 10;
43 const int kGetKeyTimeoutInSeconds = 5 * 60;
44 const int kKeyFetchTimeoutInSeconds = 60;
46 bool Base64StringToBytes(
const std::string& base64_string,
47 std::vector<uint8_t>* bytes) {
50 if (!base::Base64Decode(base64_string, &str))
52 bytes->assign(str.begin(), str.end());
56 void BytesToBase64String(
const std::vector<uint8_t>& bytes,
57 std::string* base64_string) {
58 DCHECK(base64_string);
59 base::Base64Encode(base::StringPiece(reinterpret_cast<const char*>
60 (bytes.data()), bytes.size()),
64 bool GetKeyFromTrack(
const base::DictionaryValue& track_dict,
65 std::vector<uint8_t>* key) {
67 std::string key_base64_string;
68 RCHECK(track_dict.GetString(
"key", &key_base64_string));
69 VLOG(2) <<
"Key:" << key_base64_string;
70 RCHECK(Base64StringToBytes(key_base64_string, key));
74 bool GetKeyIdFromTrack(
const base::DictionaryValue& track_dict,
75 std::vector<uint8_t>* key_id) {
77 std::string key_id_base64_string;
78 RCHECK(track_dict.GetString(
"key_id", &key_id_base64_string));
79 VLOG(2) <<
"Keyid:" << key_id_base64_string;
80 RCHECK(Base64StringToBytes(key_id_base64_string, key_id));
84 bool GetPsshDataFromTrack(
const base::DictionaryValue& track_dict,
85 std::vector<uint8_t>* pssh_data) {
88 const base::ListValue* pssh_list;
89 RCHECK(track_dict.GetList(
"pssh", &pssh_list));
92 DCHECK_EQ(1u, pssh_list->GetSize());
94 const base::DictionaryValue* pssh_dict;
95 RCHECK(pssh_list->GetDictionary(0, &pssh_dict));
97 RCHECK(pssh_dict->GetString(
"drm_type", &drm_type));
98 if (drm_type !=
"WIDEVINE") {
99 LOG(ERROR) <<
"Expecting drm_type 'WIDEVINE', get '" << drm_type <<
"'.";
102 std::string pssh_data_base64_string;
103 RCHECK(pssh_dict->GetString(
"data", &pssh_data_base64_string));
105 VLOG(2) <<
"Pssh Data:" << pssh_data_base64_string;
106 RCHECK(Base64StringToBytes(pssh_data_base64_string, pssh_data));
115 class WidevineKeySource::RefCountedEncryptionKeyMap
116 :
public base::RefCountedThreadSafe<RefCountedEncryptionKeyMap> {
118 explicit RefCountedEncryptionKeyMap(EncryptionKeyMap* encryption_key_map) {
119 DCHECK(encryption_key_map);
120 encryption_key_map_.swap(*encryption_key_map);
123 std::map<KeySource::TrackType, EncryptionKey*>& map() {
124 return encryption_key_map_;
128 friend class base::RefCountedThreadSafe<RefCountedEncryptionKeyMap>;
130 ~RefCountedEncryptionKeyMap() { STLDeleteValues(&encryption_key_map_); }
132 EncryptionKeyMap encryption_key_map_;
134 DISALLOW_COPY_AND_ASSIGN(RefCountedEncryptionKeyMap);
138 bool add_common_pssh)
139 : key_production_thread_(
"KeyProductionThread",
141 base::Unretained(this))),
143 server_url_(server_url),
144 crypto_period_count_(kDefaultCryptoPeriodCount),
145 add_common_pssh_(add_common_pssh),
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 const std::vector<uint8_t> widevine_system_id(
177 kWidevineSystemId, kWidevineSystemId + arraysize(kWidevineSystemId));
180 if (!info.
Parse(pssh_box.data(), pssh_box.size()))
181 return Status(error::PARSER_FAILURE,
"Error parsing the PSSH box.");
183 if (info.system_id() == widevine_system_id) {
184 base::AutoLock scoped_lock(lock_);
185 request_dict_.Clear();
186 std::string pssh_data_base64_string;
188 BytesToBase64String(info.pssh_data(), &pssh_data_base64_string);
189 request_dict_.SetString(
"pssh_data", pssh_data_base64_string);
190 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
191 }
else if (!info.key_ids().empty()) {
198 return Status(error::NOT_FOUND,
"No key IDs given in PSSH box.");
203 const std::vector<std::vector<uint8_t>>& key_ids) {
204 base::AutoLock scoped_lock(lock_);
205 request_dict_.Clear();
206 std::string pssh_data_base64_string;
209 WidevinePsshData widevine_pssh_data;
210 for (
size_t i = 0; i < key_ids.size(); i++) {
211 widevine_pssh_data.add_key_id(key_ids[i].data(), key_ids[i].size());
214 const std::string serialized_string = widevine_pssh_data.SerializeAsString();
215 std::vector<uint8_t> pssh_data(serialized_string.begin(),
216 serialized_string.end());
218 BytesToBase64String(pssh_data, &pssh_data_base64_string);
219 request_dict_.SetString(
"pssh_data", pssh_data_base64_string);
220 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
224 base::AutoLock scoped_lock(lock_);
225 request_dict_.Clear();
228 request_dict_.SetDouble(
"asset_id", asset_id);
229 return FetchKeysInternal(!kEnableKeyRotation, 0,
true);
234 if (encryption_key_map_.find(track_type) == encryption_key_map_.end()) {
235 return Status(error::INTERNAL_ERROR,
238 *key = *encryption_key_map_[track_type];
245 for (std::map<TrackType, EncryptionKey*>::iterator iter =
246 encryption_key_map_.begin();
247 iter != encryption_key_map_.end();
249 if (iter->second->key_id == key_id) {
250 *key = *iter->second;
254 return Status(error::INTERNAL_ERROR,
255 "Cannot find key with specified key ID");
259 TrackType track_type,
261 DCHECK(key_production_thread_.HasBeenStarted());
264 base::AutoLock scoped_lock(lock_);
265 if (!key_production_started_) {
268 first_crypto_period_index_ =
269 crypto_period_index ? crypto_period_index - 1 : 0;
272 first_crypto_period_index_));
273 start_key_production_.Signal();
274 key_production_started_ =
true;
277 return GetKeyInternal(crypto_period_index, track_type, key);
281 signer_ = std::move(signer);
285 std::unique_ptr<KeyFetcher> key_fetcher) {
286 key_fetcher_ = std::move(key_fetcher);
289 Status WidevineKeySource::GetKeyInternal(uint32_t crypto_period_index,
290 TrackType track_type,
294 DCHECK_LE(track_type, NUM_VALID_TRACK_TYPES);
295 DCHECK_NE(track_type, TRACK_TYPE_UNKNOWN);
297 scoped_refptr<RefCountedEncryptionKeyMap> ref_counted_encryption_key_map;
299 key_pool_->Peek(crypto_period_index, &ref_counted_encryption_key_map,
300 kGetKeyTimeoutInSeconds * 1000);
302 if (status.error_code() == error::STOPPED) {
303 CHECK(!common_encryption_request_status_.ok());
304 return common_encryption_request_status_;
309 EncryptionKeyMap& encryption_key_map = ref_counted_encryption_key_map->map();
310 if (encryption_key_map.find(track_type) == encryption_key_map.end()) {
311 return Status(error::INTERNAL_ERROR,
314 *key = *encryption_key_map[track_type];
318 void WidevineKeySource::FetchKeysTask() {
320 start_key_production_.Wait();
321 if (!key_pool_ || key_pool_->Stopped())
324 Status status = FetchKeysInternal(kEnableKeyRotation,
325 first_crypto_period_index_,
327 while (status.ok()) {
328 first_crypto_period_index_ += crypto_period_count_;
329 status = FetchKeysInternal(kEnableKeyRotation,
330 first_crypto_period_index_,
333 common_encryption_request_status_ = status;
337 Status WidevineKeySource::FetchKeysInternal(
bool enable_key_rotation,
338 uint32_t first_crypto_period_index,
339 bool widevine_classic) {
341 FillRequest(enable_key_rotation,
342 first_crypto_period_index,
346 Status status = GenerateKeyMessage(request, &message);
349 VLOG(1) <<
"Message: " << message;
351 std::string raw_response;
352 int64_t sleep_duration = kFirstRetryDelayMilliseconds;
356 for (
int i = 0; i < kNumTransientErrorRetries; ++i) {
357 status = key_fetcher_->FetchKeys(server_url_, message, &raw_response);
359 VLOG(1) <<
"Retry [" << i <<
"] Response:" << raw_response;
361 std::string response;
362 if (!DecodeResponse(raw_response, &response)) {
363 return Status(error::SERVER_ERROR,
364 "Failed to decode response '" + raw_response +
"'.");
367 bool transient_error =
false;
368 if (ExtractEncryptionKey(enable_key_rotation,
374 if (!transient_error) {
377 "Failed to extract encryption key from '" + response +
"'.");
379 }
else if (status.error_code() != error::TIME_OUT) {
384 if (i != kNumTransientErrorRetries - 1) {
385 base::PlatformThread::Sleep(
386 base::TimeDelta::FromMilliseconds(sleep_duration));
390 return Status(error::SERVER_ERROR,
391 "Failed to recover from server internal error.");
394 void WidevineKeySource::FillRequest(
bool enable_key_rotation,
395 uint32_t first_crypto_period_index,
396 std::string* request) {
398 DCHECK(!request_dict_.empty());
401 base::ListValue* tracks =
new base::ListValue();
403 base::DictionaryValue* track_sd =
new base::DictionaryValue();
404 track_sd->SetString(
"type",
"SD");
405 tracks->Append(track_sd);
406 base::DictionaryValue* track_hd =
new base::DictionaryValue();
407 track_hd->SetString(
"type",
"HD");
408 tracks->Append(track_hd);
409 base::DictionaryValue* track_audio =
new base::DictionaryValue();
410 track_audio->SetString(
"type",
"AUDIO");
411 tracks->Append(track_audio);
413 request_dict_.Set(
"tracks", tracks);
416 base::ListValue* drm_types =
new base::ListValue();
417 drm_types->AppendString(
"WIDEVINE");
418 request_dict_.Set(
"drm_types", drm_types);
421 if (enable_key_rotation) {
424 request_dict_.SetDouble(
"first_crypto_period_index",
425 first_crypto_period_index);
426 request_dict_.SetInteger(
"crypto_period_count", crypto_period_count_);
429 base::JSONWriter::WriteWithOptions(
433 base::JSONWriter::OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION, request);
436 Status WidevineKeySource::GenerateKeyMessage(
const std::string& request,
437 std::string* message) {
440 std::string request_base64_string;
441 base::Base64Encode(request, &request_base64_string);
443 base::DictionaryValue request_dict;
444 request_dict.SetString(
"request", request_base64_string);
448 std::string signature;
449 if (!signer_->GenerateSignature(request, &signature))
450 return Status(error::INTERNAL_ERROR,
"Signature generation failed.");
452 std::string signature_base64_string;
453 base::Base64Encode(signature, &signature_base64_string);
455 request_dict.SetString(
"signature", signature_base64_string);
456 request_dict.SetString(
"signer", signer_->signer_name());
459 base::JSONWriter::Write(request_dict, message);
463 bool WidevineKeySource::DecodeResponse(
464 const std::string& raw_response,
465 std::string* response) {
470 std::unique_ptr<base::Value> root(
471 base::JSONReader::Read(raw_response).release());
473 LOG(ERROR) <<
"'" << raw_response <<
"' is not in JSON format.";
476 const base::DictionaryValue* response_dict = NULL;
477 RCHECK(root->GetAsDictionary(&response_dict));
479 std::string response_base64_string;
480 RCHECK(response_dict->GetString(
"response", &response_base64_string));
481 RCHECK(base::Base64Decode(response_base64_string, response));
485 bool WidevineKeySource::ExtractEncryptionKey(
486 bool enable_key_rotation,
487 bool widevine_classic,
488 const std::string& response,
489 bool* transient_error) {
490 DCHECK(transient_error);
491 *transient_error =
false;
494 std::unique_ptr<base::Value> root(base::JSONReader::Read(response).release());
496 LOG(ERROR) <<
"'" << response <<
"' is not in JSON format.";
500 const base::DictionaryValue* license_dict = NULL;
501 RCHECK(root->GetAsDictionary(&license_dict));
503 std::string license_status;
504 RCHECK(license_dict->GetString(
"status", &license_status));
505 if (license_status != kLicenseStatusOK) {
506 LOG(ERROR) <<
"Received non-OK license response: " << response;
507 *transient_error = (license_status == kLicenseStatusTransientError);
511 const base::ListValue* tracks;
512 RCHECK(license_dict->GetList(
"tracks", &tracks));
514 RCHECK(enable_key_rotation ? tracks->GetSize() >= 1 * crypto_period_count_
515 : tracks->GetSize() >= 1);
517 int current_crypto_period_index = first_crypto_period_index_;
519 EncryptionKeyMap encryption_key_map;
520 for (
size_t i = 0; i < tracks->GetSize(); ++i) {
521 const base::DictionaryValue* track_dict;
522 RCHECK(tracks->GetDictionary(i, &track_dict));
524 if (enable_key_rotation) {
525 int crypto_period_index;
527 track_dict->GetInteger(
"crypto_period_index", &crypto_period_index));
528 if (crypto_period_index != current_crypto_period_index) {
529 if (crypto_period_index != current_crypto_period_index + 1) {
530 LOG(ERROR) <<
"Expecting crypto period index "
531 << current_crypto_period_index <<
" or "
532 << current_crypto_period_index + 1 <<
"; Seen "
533 << crypto_period_index <<
" at track " << i;
536 if (!PushToKeyPool(&encryption_key_map))
538 ++current_crypto_period_index;
542 std::string track_type_str;
543 RCHECK(track_dict->GetString(
"type", &track_type_str));
545 DCHECK_NE(TRACK_TYPE_UNKNOWN, track_type);
546 RCHECK(encryption_key_map.find(track_type) == encryption_key_map.end());
548 std::unique_ptr<EncryptionKey> encryption_key(
new EncryptionKey());
550 if (!GetKeyFromTrack(*track_dict, &encryption_key->key))
554 if (!widevine_classic) {
555 if (!GetKeyIdFromTrack(*track_dict, &encryption_key->key_id))
558 ProtectionSystemSpecificInfo info;
559 info.add_key_id(encryption_key->key_id);
560 info.set_system_id(kWidevineSystemId, arraysize(kWidevineSystemId));
561 info.set_pssh_box_version(0);
563 std::vector<uint8_t> pssh_data;
564 if (!GetPsshDataFromTrack(*track_dict, &pssh_data))
566 info.set_pssh_data(pssh_data);
568 encryption_key->key_system_info.push_back(info);
570 encryption_key_map[track_type] = encryption_key.release();
575 if (add_common_pssh_ && !widevine_classic) {
576 std::set<std::vector<uint8_t>> key_ids;
577 for (
const EncryptionKeyMap::value_type& pair : encryption_key_map) {
578 key_ids.insert(pair.second->key_id);
582 ProtectionSystemSpecificInfo info;
583 info.set_system_id(kCommonSystemId, arraysize(kCommonSystemId));
584 info.set_pssh_box_version(1);
585 for (
const std::vector<uint8_t>& key_id : key_ids) {
586 info.add_key_id(key_id);
589 for (
const EncryptionKeyMap::value_type& pair : encryption_key_map) {
590 pair.second->key_system_info.push_back(info);
594 DCHECK(!encryption_key_map.empty());
595 if (!enable_key_rotation) {
596 encryption_key_map_ = encryption_key_map;
599 return PushToKeyPool(&encryption_key_map);
602 bool WidevineKeySource::PushToKeyPool(
603 EncryptionKeyMap* encryption_key_map) {
605 DCHECK(encryption_key_map);
607 key_pool_->Push(scoped_refptr<RefCountedEncryptionKeyMap>(
608 new RefCountedEncryptionKeyMap(encryption_key_map)),
610 encryption_key_map->clear();
612 DCHECK_EQ(error::STOPPED, status.error_code());