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/media/base/fixed_key_source.h"
17 #include "packager/media/base/http_key_fetcher.h"
18 #include "packager/media/base/producer_consumer_queue.h"
19 #include "packager/media/base/protection_system_specific_info.h"
20 #include "packager/media/base/rcheck.h"
21 #include "packager/media/base/request_signer.h"
22 #include "packager/media/base/widevine_pssh_data.pb.h"
27 const bool kEnableKeyRotation =
true;
29 const char kLicenseStatusOK[] =
"OK";
32 const char kLicenseStatusTransientError[] =
"INTERNAL_ERROR";
36 const int kNumTransientErrorRetries = 5;
37 const int kFirstRetryDelayMilliseconds = 1000;
41 const int kDefaultCryptoPeriodCount = 10;
42 const int kGetKeyTimeoutInSeconds = 5 * 60;
43 const int kKeyFetchTimeoutInSeconds = 60;
45 bool Base64StringToBytes(
const std::string& base64_string,
46 std::vector<uint8_t>* bytes) {
49 if (!base::Base64Decode(base64_string, &str))
51 bytes->assign(str.begin(), str.end());
55 void BytesToBase64String(
const std::vector<uint8_t>& bytes,
56 std::string* base64_string) {
57 DCHECK(base64_string);
58 base::Base64Encode(base::StringPiece(reinterpret_cast<const char*>
59 (bytes.data()), bytes.size()),
63 bool GetKeyFromTrack(
const base::DictionaryValue& track_dict,
64 std::vector<uint8_t>* key) {
66 std::string key_base64_string;
67 RCHECK(track_dict.GetString(
"key", &key_base64_string));
68 VLOG(2) <<
"Key:" << key_base64_string;
69 RCHECK(Base64StringToBytes(key_base64_string, key));
73 bool GetKeyIdFromTrack(
const base::DictionaryValue& track_dict,
74 std::vector<uint8_t>* key_id) {
76 std::string key_id_base64_string;
77 RCHECK(track_dict.GetString(
"key_id", &key_id_base64_string));
78 VLOG(2) <<
"Keyid:" << key_id_base64_string;
79 RCHECK(Base64StringToBytes(key_id_base64_string, key_id));
83 bool GetPsshDataFromTrack(
const base::DictionaryValue& track_dict,
84 std::vector<uint8_t>* pssh_data) {
87 const base::ListValue* pssh_list;
88 RCHECK(track_dict.GetList(
"pssh", &pssh_list));
91 DCHECK_EQ(1u, pssh_list->GetSize());
93 const base::DictionaryValue* pssh_dict;
94 RCHECK(pssh_list->GetDictionary(0, &pssh_dict));
96 RCHECK(pssh_dict->GetString(
"drm_type", &drm_type));
97 if (drm_type !=
"WIDEVINE") {
98 LOG(ERROR) <<
"Expecting drm_type 'WIDEVINE', get '" << drm_type <<
"'.";
101 std::string pssh_data_base64_string;
102 RCHECK(pssh_dict->GetString(
"data", &pssh_data_base64_string));
104 VLOG(2) <<
"Pssh Data:" << pssh_data_base64_string;
105 RCHECK(Base64StringToBytes(pssh_data_base64_string, pssh_data));
114 class WidevineKeySource::RefCountedEncryptionKeyMap
115 :
public base::RefCountedThreadSafe<RefCountedEncryptionKeyMap> {
117 explicit RefCountedEncryptionKeyMap(EncryptionKeyMap* encryption_key_map) {
118 DCHECK(encryption_key_map);
119 encryption_key_map_.swap(*encryption_key_map);
122 const EncryptionKeyMap& map() {
return encryption_key_map_; }
125 friend class base::RefCountedThreadSafe<RefCountedEncryptionKeyMap>;
127 ~RefCountedEncryptionKeyMap() {}
129 EncryptionKeyMap encryption_key_map_;
131 DISALLOW_COPY_AND_ASSIGN(RefCountedEncryptionKeyMap);
135 bool add_common_pssh)
136 : key_production_thread_(
"KeyProductionThread",
138 base::Unretained(this))),
140 server_url_(server_url),
141 crypto_period_count_(kDefaultCryptoPeriodCount),
142 add_common_pssh_(add_common_pssh),
143 key_production_started_(false),
144 start_key_production_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
145 base::WaitableEvent::InitialState::NOT_SIGNALED),
146 first_crypto_period_index_(0) {
147 key_production_thread_.Start();
150 WidevineKeySource::~WidevineKeySource() {
153 if (key_production_thread_.HasBeenStarted()) {
156 start_key_production_.Signal();
157 key_production_thread_.Join();
162 const std::string& policy) {
163 base::AutoLock scoped_lock(lock_);
164 request_dict_.Clear();
165 std::string content_id_base64_string;
166 BytesToBase64String(content_id, &content_id_base64_string);
167 request_dict_.SetString(
"content_id", content_id_base64_string);
168 request_dict_.SetString(
"policy", policy);
169 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
173 const std::vector<uint8_t> widevine_system_id(
174 kWidevineSystemId, kWidevineSystemId + arraysize(kWidevineSystemId));
177 if (!info.
Parse(pssh_box.data(), pssh_box.size()))
178 return Status(error::PARSER_FAILURE,
"Error parsing the PSSH box.");
180 if (info.system_id() == widevine_system_id) {
181 base::AutoLock scoped_lock(lock_);
182 request_dict_.Clear();
183 std::string pssh_data_base64_string;
185 BytesToBase64String(info.pssh_data(), &pssh_data_base64_string);
186 request_dict_.SetString(
"pssh_data", pssh_data_base64_string);
187 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
188 }
else if (!info.key_ids().empty()) {
195 return Status(error::NOT_FOUND,
"No key IDs given in PSSH box.");
200 const std::vector<std::vector<uint8_t>>& key_ids) {
201 base::AutoLock scoped_lock(lock_);
202 request_dict_.Clear();
203 std::string pssh_data_base64_string;
206 WidevinePsshData widevine_pssh_data;
207 for (
size_t i = 0; i < key_ids.size(); i++) {
208 widevine_pssh_data.add_key_id(key_ids[i].data(), key_ids[i].size());
211 const std::string serialized_string = widevine_pssh_data.SerializeAsString();
212 std::vector<uint8_t> pssh_data(serialized_string.begin(),
213 serialized_string.end());
215 BytesToBase64String(pssh_data, &pssh_data_base64_string);
216 request_dict_.SetString(
"pssh_data", pssh_data_base64_string);
217 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
221 base::AutoLock scoped_lock(lock_);
222 request_dict_.Clear();
225 request_dict_.SetDouble(
"asset_id", asset_id);
226 return FetchKeysInternal(!kEnableKeyRotation, 0,
true);
231 if (encryption_key_map_.find(track_type) == encryption_key_map_.end()) {
232 return Status(error::INTERNAL_ERROR,
235 *key = *encryption_key_map_[track_type];
242 for (
const auto& pair : encryption_key_map_) {
243 if (pair.second->key_id == key_id) {
248 return Status(error::INTERNAL_ERROR,
249 "Cannot find key with specified key ID");
253 TrackType track_type,
255 DCHECK(key_production_thread_.HasBeenStarted());
258 base::AutoLock scoped_lock(lock_);
259 if (!key_production_started_) {
262 first_crypto_period_index_ =
263 crypto_period_index ? crypto_period_index - 1 : 0;
266 first_crypto_period_index_));
267 start_key_production_.Signal();
268 key_production_started_ =
true;
271 return GetKeyInternal(crypto_period_index, track_type, key);
275 signer_ = std::move(signer);
279 std::unique_ptr<KeyFetcher> key_fetcher) {
280 key_fetcher_ = std::move(key_fetcher);
283 Status WidevineKeySource::GetKeyInternal(uint32_t crypto_period_index,
284 TrackType track_type,
288 DCHECK_LE(track_type, NUM_VALID_TRACK_TYPES);
289 DCHECK_NE(track_type, TRACK_TYPE_UNKNOWN);
291 scoped_refptr<RefCountedEncryptionKeyMap> ref_counted_encryption_key_map;
293 key_pool_->Peek(crypto_period_index, &ref_counted_encryption_key_map,
294 kGetKeyTimeoutInSeconds * 1000);
296 if (status.error_code() == error::STOPPED) {
297 CHECK(!common_encryption_request_status_.ok());
298 return common_encryption_request_status_;
303 const EncryptionKeyMap& encryption_key_map =
304 ref_counted_encryption_key_map->map();
305 if (encryption_key_map.find(track_type) == encryption_key_map.end()) {
306 return Status(error::INTERNAL_ERROR,
309 *key = *encryption_key_map.at(track_type);
313 void WidevineKeySource::FetchKeysTask() {
315 start_key_production_.Wait();
316 if (!key_pool_ || key_pool_->Stopped())
319 Status status = FetchKeysInternal(kEnableKeyRotation,
320 first_crypto_period_index_,
322 while (status.ok()) {
323 first_crypto_period_index_ += crypto_period_count_;
324 status = FetchKeysInternal(kEnableKeyRotation,
325 first_crypto_period_index_,
328 common_encryption_request_status_ = status;
332 Status WidevineKeySource::FetchKeysInternal(
bool enable_key_rotation,
333 uint32_t first_crypto_period_index,
334 bool widevine_classic) {
336 FillRequest(enable_key_rotation,
337 first_crypto_period_index,
341 Status status = GenerateKeyMessage(request, &message);
344 VLOG(1) <<
"Message: " << message;
346 std::string raw_response;
347 int64_t sleep_duration = kFirstRetryDelayMilliseconds;
351 for (
int i = 0; i < kNumTransientErrorRetries; ++i) {
352 status = key_fetcher_->FetchKeys(server_url_, message, &raw_response);
354 VLOG(1) <<
"Retry [" << i <<
"] Response:" << raw_response;
356 std::string response;
357 if (!DecodeResponse(raw_response, &response)) {
358 return Status(error::SERVER_ERROR,
359 "Failed to decode response '" + raw_response +
"'.");
362 bool transient_error =
false;
363 if (ExtractEncryptionKey(enable_key_rotation,
369 if (!transient_error) {
372 "Failed to extract encryption key from '" + response +
"'.");
374 }
else if (status.error_code() != error::TIME_OUT) {
379 if (i != kNumTransientErrorRetries - 1) {
380 base::PlatformThread::Sleep(
381 base::TimeDelta::FromMilliseconds(sleep_duration));
385 return Status(error::SERVER_ERROR,
386 "Failed to recover from server internal error.");
389 void WidevineKeySource::FillRequest(
bool enable_key_rotation,
390 uint32_t first_crypto_period_index,
391 std::string* request) {
393 DCHECK(!request_dict_.empty());
396 base::ListValue* tracks =
new base::ListValue();
398 base::DictionaryValue* track_sd =
new base::DictionaryValue();
399 track_sd->SetString(
"type",
"SD");
400 tracks->Append(track_sd);
401 base::DictionaryValue* track_hd =
new base::DictionaryValue();
402 track_hd->SetString(
"type",
"HD");
403 tracks->Append(track_hd);
404 base::DictionaryValue* track_uhd1 =
new base::DictionaryValue();
405 track_uhd1->SetString(
"type",
"UHD1");
406 tracks->Append(track_uhd1);
407 base::DictionaryValue* track_uhd2 =
new base::DictionaryValue();
408 track_uhd2->SetString(
"type",
"UHD2");
409 tracks->Append(track_uhd2);
410 base::DictionaryValue* track_audio =
new base::DictionaryValue();
411 track_audio->SetString(
"type",
"AUDIO");
412 tracks->Append(track_audio);
414 request_dict_.Set(
"tracks", tracks);
417 base::ListValue* drm_types =
new base::ListValue();
418 drm_types->AppendString(
"WIDEVINE");
419 request_dict_.Set(
"drm_types", drm_types);
422 if (enable_key_rotation) {
425 request_dict_.SetDouble(
"first_crypto_period_index",
426 first_crypto_period_index);
427 request_dict_.SetInteger(
"crypto_period_count", crypto_period_count_);
430 base::JSONWriter::WriteWithOptions(
434 base::JSONWriter::OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION, request);
437 Status WidevineKeySource::GenerateKeyMessage(
const std::string& request,
438 std::string* message) {
441 std::string request_base64_string;
442 base::Base64Encode(request, &request_base64_string);
444 base::DictionaryValue request_dict;
445 request_dict.SetString(
"request", request_base64_string);
449 std::string signature;
450 if (!signer_->GenerateSignature(request, &signature))
451 return Status(error::INTERNAL_ERROR,
"Signature generation failed.");
453 std::string signature_base64_string;
454 base::Base64Encode(signature, &signature_base64_string);
456 request_dict.SetString(
"signature", signature_base64_string);
457 request_dict.SetString(
"signer", signer_->signer_name());
460 base::JSONWriter::Write(request_dict, message);
464 bool WidevineKeySource::DecodeResponse(
465 const std::string& raw_response,
466 std::string* response) {
470 std::unique_ptr<base::Value> root(base::JSONReader::Read(raw_response));
472 LOG(ERROR) <<
"'" << raw_response <<
"' is not in JSON format.";
475 const base::DictionaryValue* response_dict = NULL;
476 RCHECK(root->GetAsDictionary(&response_dict));
478 std::string response_base64_string;
479 RCHECK(response_dict->GetString(
"response", &response_base64_string));
480 RCHECK(base::Base64Decode(response_base64_string, response));
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;
492 std::unique_ptr<base::Value> root(base::JSONReader::Read(response));
494 LOG(ERROR) <<
"'" << response <<
"' is not in JSON format.";
498 const base::DictionaryValue* license_dict = NULL;
499 RCHECK(root->GetAsDictionary(&license_dict));
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);
509 const base::ListValue* tracks;
510 RCHECK(license_dict->GetList(
"tracks", &tracks));
512 RCHECK(enable_key_rotation ? tracks->GetSize() >= 1 * crypto_period_count_
513 : tracks->GetSize() >= 1);
515 int current_crypto_period_index = first_crypto_period_index_;
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));
522 if (enable_key_rotation) {
523 int crypto_period_index;
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;
534 if (!PushToKeyPool(&encryption_key_map))
536 ++current_crypto_period_index;
540 std::string track_type_str;
541 RCHECK(track_dict->GetString(
"type", &track_type_str));
543 DCHECK_NE(TRACK_TYPE_UNKNOWN, track_type);
544 RCHECK(encryption_key_map.find(track_type) == encryption_key_map.end());
546 std::unique_ptr<EncryptionKey> encryption_key(
new EncryptionKey());
548 if (!GetKeyFromTrack(*track_dict, &encryption_key->key))
552 if (!widevine_classic) {
553 if (!GetKeyIdFromTrack(*track_dict, &encryption_key->key_id))
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);
561 std::vector<uint8_t> pssh_data;
562 if (!GetPsshDataFromTrack(*track_dict, &pssh_data))
564 info.set_pssh_data(pssh_data);
566 encryption_key->key_system_info.push_back(info);
568 encryption_key_map[track_type] = std::move(encryption_key);
573 if (add_common_pssh_ && !widevine_classic) {
574 std::set<std::vector<uint8_t>> key_ids;
575 for (
const EncryptionKeyMap::value_type& pair : encryption_key_map) {
576 key_ids.insert(pair.second->key_id);
580 ProtectionSystemSpecificInfo info;
581 info.set_system_id(kCommonSystemId, arraysize(kCommonSystemId));
582 info.set_pssh_box_version(1);
583 for (
const std::vector<uint8_t>& key_id : key_ids) {
584 info.add_key_id(key_id);
587 for (
const EncryptionKeyMap::value_type& pair : encryption_key_map) {
588 pair.second->key_system_info.push_back(info);
592 DCHECK(!encryption_key_map.empty());
593 if (!enable_key_rotation) {
594 encryption_key_map_.swap(encryption_key_map);
597 return PushToKeyPool(&encryption_key_map);
600 bool WidevineKeySource::PushToKeyPool(
601 EncryptionKeyMap* encryption_key_map) {
603 DCHECK(encryption_key_map);
605 key_pool_->Push(scoped_refptr<RefCountedEncryptionKeyMap>(
606 new RefCountedEncryptionKeyMap(encryption_key_map)),
608 encryption_key_map->clear();
610 DCHECK_EQ(error::STOPPED, status.error_code());