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/protection_system_specific_info.h"
18 #include "packager/media/base/request_signer.h"
19 #include "packager/media/base/widevine_pssh_data.pb.h"
24 LOG(ERROR) << "Failure while processing: " << #x; \
29 namespace edash_packager {
32 const bool kEnableKeyRotation =
true;
34 const char kLicenseStatusOK[] =
"OK";
37 const char kLicenseStatusTransientError[] =
"INTERNAL_ERROR";
41 const int kNumTransientErrorRetries = 5;
42 const int kFirstRetryDelayMilliseconds = 1000;
46 const int kDefaultCryptoPeriodCount = 10;
47 const int kGetKeyTimeoutInSeconds = 5 * 60;
48 const int kKeyFetchTimeoutInSeconds = 60;
50 bool Base64StringToBytes(
const std::string& base64_string,
51 std::vector<uint8_t>* bytes) {
54 if (!base::Base64Decode(base64_string, &str))
56 bytes->assign(str.begin(), str.end());
60 void BytesToBase64String(
const std::vector<uint8_t>& bytes,
61 std::string* base64_string) {
62 DCHECK(base64_string);
63 base::Base64Encode(base::StringPiece(reinterpret_cast<const char*>
64 (bytes.data()), bytes.size()),
68 bool GetKeyFromTrack(
const base::DictionaryValue& track_dict,
69 std::vector<uint8_t>* key) {
71 std::string key_base64_string;
72 RCHECK(track_dict.GetString(
"key", &key_base64_string));
73 VLOG(2) <<
"Key:" << key_base64_string;
74 RCHECK(Base64StringToBytes(key_base64_string, key));
78 bool GetKeyIdFromTrack(
const base::DictionaryValue& track_dict,
79 std::vector<uint8_t>* key_id) {
81 std::string key_id_base64_string;
82 RCHECK(track_dict.GetString(
"key_id", &key_id_base64_string));
83 VLOG(2) <<
"Keyid:" << key_id_base64_string;
84 RCHECK(Base64StringToBytes(key_id_base64_string, key_id));
88 bool GetPsshDataFromTrack(
const base::DictionaryValue& track_dict,
89 std::vector<uint8_t>* pssh_data) {
92 const base::ListValue* pssh_list;
93 RCHECK(track_dict.GetList(
"pssh", &pssh_list));
96 DCHECK_EQ(1u, pssh_list->GetSize());
98 const base::DictionaryValue* pssh_dict;
99 RCHECK(pssh_list->GetDictionary(0, &pssh_dict));
100 std::string drm_type;
101 RCHECK(pssh_dict->GetString(
"drm_type", &drm_type));
102 if (drm_type !=
"WIDEVINE") {
103 LOG(ERROR) <<
"Expecting drm_type 'WIDEVINE', get '" << drm_type <<
"'.";
106 std::string pssh_data_base64_string;
107 RCHECK(pssh_dict->GetString(
"data", &pssh_data_base64_string));
109 VLOG(2) <<
"Pssh Data:" << pssh_data_base64_string;
110 RCHECK(Base64StringToBytes(pssh_data_base64_string, pssh_data));
119 class WidevineKeySource::RefCountedEncryptionKeyMap
120 :
public base::RefCountedThreadSafe<RefCountedEncryptionKeyMap> {
122 explicit RefCountedEncryptionKeyMap(EncryptionKeyMap* encryption_key_map) {
123 DCHECK(encryption_key_map);
124 encryption_key_map_.swap(*encryption_key_map);
127 std::map<KeySource::TrackType, EncryptionKey*>& map() {
128 return encryption_key_map_;
132 friend class base::RefCountedThreadSafe<RefCountedEncryptionKeyMap>;
134 ~RefCountedEncryptionKeyMap() { STLDeleteValues(&encryption_key_map_); }
136 EncryptionKeyMap encryption_key_map_;
138 DISALLOW_COPY_AND_ASSIGN(RefCountedEncryptionKeyMap);
142 : key_production_thread_(
"KeyProductionThread",
144 base::Unretained(this))),
146 server_url_(server_url),
147 crypto_period_count_(kDefaultCryptoPeriodCount),
148 key_production_started_(false),
149 start_key_production_(false, false),
150 first_crypto_period_index_(0) {
151 key_production_thread_.Start();
154 WidevineKeySource::~WidevineKeySource() {
157 if (key_production_thread_.HasBeenStarted()) {
160 start_key_production_.Signal();
161 key_production_thread_.Join();
163 STLDeleteValues(&encryption_key_map_);
167 const std::string& policy) {
168 base::AutoLock scoped_lock(lock_);
169 request_dict_.Clear();
170 std::string content_id_base64_string;
171 BytesToBase64String(content_id, &content_id_base64_string);
172 request_dict_.SetString(
"content_id", content_id_base64_string);
173 request_dict_.SetString(
"policy", policy);
174 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
178 const std::vector<uint8_t> widevine_system_id(
179 kWidevineSystemId, kWidevineSystemId + arraysize(kWidevineSystemId));
182 if (!info.
Parse(pssh_box.data(), pssh_box.size()))
183 return Status(error::PARSER_FAILURE,
"Error parsing the PSSH box.");
185 if (info.system_id() == widevine_system_id) {
186 base::AutoLock scoped_lock(lock_);
187 request_dict_.Clear();
188 std::string pssh_data_base64_string;
190 BytesToBase64String(info.pssh_data(), &pssh_data_base64_string);
191 request_dict_.SetString(
"pssh_data", pssh_data_base64_string);
192 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
193 }
else if (!info.key_ids().empty()) {
200 return Status(error::NOT_FOUND,
"No key IDs given in PSSH box.");
205 const std::vector<std::vector<uint8_t>>& key_ids) {
206 base::AutoLock scoped_lock(lock_);
207 request_dict_.Clear();
208 std::string pssh_data_base64_string;
211 WidevinePsshData widevine_pssh_data;
212 for (
size_t i = 0; i < key_ids.size(); i++) {
213 widevine_pssh_data.add_key_id(key_ids[i].data(), key_ids[i].size());
216 const std::string serialized_string = widevine_pssh_data.SerializeAsString();
217 std::vector<uint8_t> pssh_data(serialized_string.begin(),
218 serialized_string.end());
220 BytesToBase64String(pssh_data, &pssh_data_base64_string);
221 request_dict_.SetString(
"pssh_data", pssh_data_base64_string);
222 return FetchKeysInternal(!kEnableKeyRotation, 0,
false);
226 base::AutoLock scoped_lock(lock_);
227 request_dict_.Clear();
230 request_dict_.SetDouble(
"asset_id", asset_id);
231 return FetchKeysInternal(!kEnableKeyRotation, 0,
true);
236 if (encryption_key_map_.find(track_type) == encryption_key_map_.end()) {
237 return Status(error::INTERNAL_ERROR,
240 *key = *encryption_key_map_[track_type];
247 for (std::map<TrackType, EncryptionKey*>::iterator iter =
248 encryption_key_map_.begin();
249 iter != encryption_key_map_.end();
251 if (iter->second->key_id == key_id) {
252 *key = *iter->second;
256 return Status(error::INTERNAL_ERROR,
257 "Cannot find key with specified key ID");
261 TrackType track_type,
263 DCHECK(key_production_thread_.HasBeenStarted());
266 base::AutoLock scoped_lock(lock_);
267 if (!key_production_started_) {
270 first_crypto_period_index_ =
271 crypto_period_index ? crypto_period_index - 1 : 0;
274 first_crypto_period_index_));
275 start_key_production_.Signal();
276 key_production_started_ =
true;
279 return GetKeyInternal(crypto_period_index, track_type, key);
283 return "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";
287 signer_ = signer.Pass();
291 key_fetcher_ = key_fetcher.Pass();
294 Status WidevineKeySource::GetKeyInternal(uint32_t crypto_period_index,
295 TrackType track_type,
299 DCHECK_LE(track_type, NUM_VALID_TRACK_TYPES);
300 DCHECK_NE(track_type, TRACK_TYPE_UNKNOWN);
302 scoped_refptr<RefCountedEncryptionKeyMap> ref_counted_encryption_key_map;
304 key_pool_->Peek(crypto_period_index, &ref_counted_encryption_key_map,
305 kGetKeyTimeoutInSeconds * 1000);
307 if (status.error_code() == error::STOPPED) {
308 CHECK(!common_encryption_request_status_.ok());
309 return common_encryption_request_status_;
314 EncryptionKeyMap& encryption_key_map = ref_counted_encryption_key_map->map();
315 if (encryption_key_map.find(track_type) == encryption_key_map.end()) {
316 return Status(error::INTERNAL_ERROR,
319 *key = *encryption_key_map[track_type];
323 void WidevineKeySource::FetchKeysTask() {
325 start_key_production_.Wait();
326 if (!key_pool_ || key_pool_->Stopped())
329 Status status = FetchKeysInternal(kEnableKeyRotation,
330 first_crypto_period_index_,
332 while (status.ok()) {
333 first_crypto_period_index_ += crypto_period_count_;
334 status = FetchKeysInternal(kEnableKeyRotation,
335 first_crypto_period_index_,
338 common_encryption_request_status_ = status;
342 Status WidevineKeySource::FetchKeysInternal(
bool enable_key_rotation,
343 uint32_t first_crypto_period_index,
344 bool widevine_classic) {
346 FillRequest(enable_key_rotation,
347 first_crypto_period_index,
351 Status status = GenerateKeyMessage(request, &message);
354 VLOG(1) <<
"Message: " << message;
356 std::string raw_response;
357 int64_t sleep_duration = kFirstRetryDelayMilliseconds;
361 for (
int i = 0; i < kNumTransientErrorRetries; ++i) {
362 status = key_fetcher_->FetchKeys(server_url_, message, &raw_response);
364 VLOG(1) <<
"Retry [" << i <<
"] Response:" << raw_response;
366 std::string response;
367 if (!DecodeResponse(raw_response, &response)) {
368 return Status(error::SERVER_ERROR,
369 "Failed to decode response '" + raw_response +
"'.");
372 bool transient_error =
false;
373 if (ExtractEncryptionKey(enable_key_rotation,
379 if (!transient_error) {
382 "Failed to extract encryption key from '" + response +
"'.");
384 }
else if (status.error_code() != error::TIME_OUT) {
389 if (i != kNumTransientErrorRetries - 1) {
390 base::PlatformThread::Sleep(
391 base::TimeDelta::FromMilliseconds(sleep_duration));
395 return Status(error::SERVER_ERROR,
396 "Failed to recover from server internal error.");
399 void WidevineKeySource::FillRequest(
bool enable_key_rotation,
400 uint32_t first_crypto_period_index,
401 std::string* request) {
403 DCHECK(!request_dict_.empty());
406 base::ListValue* tracks =
new base::ListValue();
408 base::DictionaryValue* track_sd =
new base::DictionaryValue();
409 track_sd->SetString(
"type",
"SD");
410 tracks->Append(track_sd);
411 base::DictionaryValue* track_hd =
new base::DictionaryValue();
412 track_hd->SetString(
"type",
"HD");
413 tracks->Append(track_hd);
414 base::DictionaryValue* track_audio =
new base::DictionaryValue();
415 track_audio->SetString(
"type",
"AUDIO");
416 tracks->Append(track_audio);
418 request_dict_.Set(
"tracks", tracks);
421 base::ListValue* drm_types =
new base::ListValue();
422 drm_types->AppendString(
"WIDEVINE");
423 request_dict_.Set(
"drm_types", drm_types);
426 if (enable_key_rotation) {
429 request_dict_.SetDouble(
"first_crypto_period_index",
430 first_crypto_period_index);
431 request_dict_.SetInteger(
"crypto_period_count", crypto_period_count_);
434 base::JSONWriter::WriteWithOptions(
438 base::JSONWriter::OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION, request);
441 Status WidevineKeySource::GenerateKeyMessage(
const std::string& request,
442 std::string* message) {
445 std::string request_base64_string;
446 base::Base64Encode(request, &request_base64_string);
448 base::DictionaryValue request_dict;
449 request_dict.SetString(
"request", request_base64_string);
453 std::string signature;
454 if (!signer_->GenerateSignature(request, &signature))
455 return Status(error::INTERNAL_ERROR,
"Signature generation failed.");
457 std::string signature_base64_string;
458 base::Base64Encode(signature, &signature_base64_string);
460 request_dict.SetString(
"signature", signature_base64_string);
461 request_dict.SetString(
"signer", signer_->signer_name());
464 base::JSONWriter::Write(request_dict, message);
468 bool WidevineKeySource::DecodeResponse(
469 const std::string& raw_response,
470 std::string* response) {
474 scoped_ptr<base::Value> root(base::JSONReader::Read(raw_response));
476 LOG(ERROR) <<
"'" << raw_response <<
"' is not in JSON format.";
479 const base::DictionaryValue* response_dict = NULL;
480 RCHECK(root->GetAsDictionary(&response_dict));
482 std::string response_base64_string;
483 RCHECK(response_dict->GetString(
"response", &response_base64_string));
484 RCHECK(base::Base64Decode(response_base64_string, response));
488 bool WidevineKeySource::ExtractEncryptionKey(
489 bool enable_key_rotation,
490 bool widevine_classic,
491 const std::string& response,
492 bool* transient_error) {
493 DCHECK(transient_error);
494 *transient_error =
false;
496 scoped_ptr<base::Value> root(base::JSONReader::Read(response));
498 LOG(ERROR) <<
"'" << response <<
"' is not in JSON format.";
502 const base::DictionaryValue* license_dict = NULL;
503 RCHECK(root->GetAsDictionary(&license_dict));
505 std::string license_status;
506 RCHECK(license_dict->GetString(
"status", &license_status));
507 if (license_status != kLicenseStatusOK) {
508 LOG(ERROR) <<
"Received non-OK license response: " << response;
509 *transient_error = (license_status == kLicenseStatusTransientError);
513 const base::ListValue* tracks;
514 RCHECK(license_dict->GetList(
"tracks", &tracks));
516 RCHECK(enable_key_rotation ? tracks->GetSize() >= 1 * crypto_period_count_
517 : tracks->GetSize() >= 1);
519 int current_crypto_period_index = first_crypto_period_index_;
521 EncryptionKeyMap encryption_key_map;
522 for (
size_t i = 0; i < tracks->GetSize(); ++i) {
523 const base::DictionaryValue* track_dict;
524 RCHECK(tracks->GetDictionary(i, &track_dict));
526 if (enable_key_rotation) {
527 int crypto_period_index;
529 track_dict->GetInteger(
"crypto_period_index", &crypto_period_index));
530 if (crypto_period_index != current_crypto_period_index) {
531 if (crypto_period_index != current_crypto_period_index + 1) {
532 LOG(ERROR) <<
"Expecting crypto period index "
533 << current_crypto_period_index <<
" or "
534 << current_crypto_period_index + 1 <<
"; Seen "
535 << crypto_period_index <<
" at track " << i;
538 if (!PushToKeyPool(&encryption_key_map))
540 ++current_crypto_period_index;
544 std::string track_type_str;
545 RCHECK(track_dict->GetString(
"type", &track_type_str));
547 DCHECK_NE(TRACK_TYPE_UNKNOWN, track_type);
548 RCHECK(encryption_key_map.find(track_type) == encryption_key_map.end());
550 scoped_ptr<EncryptionKey> encryption_key(
new EncryptionKey());
552 if (!GetKeyFromTrack(*track_dict, &encryption_key->key))
556 if (!widevine_classic) {
557 if (!GetKeyIdFromTrack(*track_dict, &encryption_key->key_id))
560 std::vector<uint8_t> pssh_data;
561 if (!GetPsshDataFromTrack(*track_dict, &pssh_data))
565 encryption_key_map[track_type] = encryption_key.release();
568 DCHECK(!encryption_key_map.empty());
569 if (!enable_key_rotation) {
570 encryption_key_map_ = encryption_key_map;
573 return PushToKeyPool(&encryption_key_map);
576 bool WidevineKeySource::PushToKeyPool(
577 EncryptionKeyMap* encryption_key_map) {
579 DCHECK(encryption_key_map);
581 key_pool_->Push(scoped_refptr<RefCountedEncryptionKeyMap>(
582 new RefCountedEncryptionKeyMap(encryption_key_map)),
584 encryption_key_map->clear();
586 DCHECK_EQ(error::STOPPED, status.error_code());