1 // Copyright 2013 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "media/cdm/ppapi/cdm_adapter.h" 6 7 #include "media/cdm/ppapi/cdm_helpers.h" 8 #include "media/cdm/ppapi/cdm_logging.h" 9 #include "media/cdm/ppapi/supported_cdm_versions.h" 10 #include "ppapi/c/ppb_console.h" 11 12 #if defined(CHECK_DOCUMENT_URL) 13 #include "ppapi/cpp/dev/url_util_dev.h" 14 #include "ppapi/cpp/instance_handle.h" 15 #endif // defined(CHECK_DOCUMENT_URL) 16 17 namespace { 18 19 #if !defined(NDEBUG) 20 #define DLOG_TO_CONSOLE(message) LogToConsole(message); 21 #else 22 #define DLOG_TO_CONSOLE(message) (void)(message); 23 #endif 24 25 bool IsMainThread() { 26 return pp::Module::Get()->core()->IsMainThread(); 27 } 28 29 // Posts a task to run |cb| on the main thread. The task is posted even if the 30 // current thread is the main thread. 31 void PostOnMain(pp::CompletionCallback cb) { 32 pp::Module::Get()->core()->CallOnMainThread(0, cb, PP_OK); 33 } 34 35 // Ensures |cb| is called on the main thread, either because the current thread 36 // is the main thread or by posting it to the main thread. 37 void CallOnMain(pp::CompletionCallback cb) { 38 // TODO(tomfinegan): This is only necessary because PPAPI doesn't allow calls 39 // off the main thread yet. Remove this once the change lands. 40 if (IsMainThread()) 41 cb.Run(PP_OK); 42 else 43 PostOnMain(cb); 44 } 45 46 // Configures a cdm::InputBuffer. |subsamples| must exist as long as 47 // |input_buffer| is in use. 48 void ConfigureInputBuffer( 49 const pp::Buffer_Dev& encrypted_buffer, 50 const PP_EncryptedBlockInfo& encrypted_block_info, 51 std::vector<cdm::SubsampleEntry>* subsamples, 52 cdm::InputBuffer* input_buffer) { 53 PP_DCHECK(subsamples); 54 PP_DCHECK(!encrypted_buffer.is_null()); 55 56 input_buffer->data = static_cast<uint8_t*>(encrypted_buffer.data()); 57 input_buffer->data_size = encrypted_block_info.data_size; 58 PP_DCHECK(encrypted_buffer.size() >= input_buffer->data_size); 59 input_buffer->data_offset = encrypted_block_info.data_offset; 60 61 PP_DCHECK(encrypted_block_info.key_id_size <= 62 arraysize(encrypted_block_info.key_id)); 63 input_buffer->key_id_size = encrypted_block_info.key_id_size; 64 input_buffer->key_id = input_buffer->key_id_size > 0 ? 65 encrypted_block_info.key_id : NULL; 66 67 PP_DCHECK(encrypted_block_info.iv_size <= arraysize(encrypted_block_info.iv)); 68 input_buffer->iv_size = encrypted_block_info.iv_size; 69 input_buffer->iv = encrypted_block_info.iv_size > 0 ? 70 encrypted_block_info.iv : NULL; 71 72 input_buffer->num_subsamples = encrypted_block_info.num_subsamples; 73 if (encrypted_block_info.num_subsamples > 0) { 74 subsamples->reserve(encrypted_block_info.num_subsamples); 75 76 for (uint32_t i = 0; i < encrypted_block_info.num_subsamples; ++i) { 77 subsamples->push_back(cdm::SubsampleEntry( 78 encrypted_block_info.subsamples[i].clear_bytes, 79 encrypted_block_info.subsamples[i].cipher_bytes)); 80 } 81 82 input_buffer->subsamples = &(*subsamples)[0]; 83 } 84 85 input_buffer->timestamp = encrypted_block_info.tracking_info.timestamp; 86 } 87 88 PP_DecryptResult CdmStatusToPpDecryptResult(cdm::Status status) { 89 switch (status) { 90 case cdm::kSuccess: 91 return PP_DECRYPTRESULT_SUCCESS; 92 case cdm::kNoKey: 93 return PP_DECRYPTRESULT_DECRYPT_NOKEY; 94 case cdm::kNeedMoreData: 95 return PP_DECRYPTRESULT_NEEDMOREDATA; 96 case cdm::kDecryptError: 97 return PP_DECRYPTRESULT_DECRYPT_ERROR; 98 case cdm::kDecodeError: 99 return PP_DECRYPTRESULT_DECODE_ERROR; 100 default: 101 PP_NOTREACHED(); 102 return PP_DECRYPTRESULT_DECODE_ERROR; 103 } 104 } 105 106 PP_DecryptedFrameFormat CdmVideoFormatToPpDecryptedFrameFormat( 107 cdm::VideoFormat format) { 108 switch (format) { 109 case cdm::kYv12: 110 return PP_DECRYPTEDFRAMEFORMAT_YV12; 111 case cdm::kI420: 112 return PP_DECRYPTEDFRAMEFORMAT_I420; 113 default: 114 return PP_DECRYPTEDFRAMEFORMAT_UNKNOWN; 115 } 116 } 117 118 PP_DecryptedSampleFormat CdmAudioFormatToPpDecryptedSampleFormat( 119 cdm::AudioFormat format) { 120 switch (format) { 121 case cdm::kAudioFormatU8: 122 return PP_DECRYPTEDSAMPLEFORMAT_U8; 123 case cdm::kAudioFormatS16: 124 return PP_DECRYPTEDSAMPLEFORMAT_S16; 125 case cdm::kAudioFormatS32: 126 return PP_DECRYPTEDSAMPLEFORMAT_S32; 127 case cdm::kAudioFormatF32: 128 return PP_DECRYPTEDSAMPLEFORMAT_F32; 129 case cdm::kAudioFormatPlanarS16: 130 return PP_DECRYPTEDSAMPLEFORMAT_PLANAR_S16; 131 case cdm::kAudioFormatPlanarF32: 132 return PP_DECRYPTEDSAMPLEFORMAT_PLANAR_F32; 133 default: 134 return PP_DECRYPTEDSAMPLEFORMAT_UNKNOWN; 135 } 136 } 137 138 cdm::AudioDecoderConfig::AudioCodec PpAudioCodecToCdmAudioCodec( 139 PP_AudioCodec codec) { 140 switch (codec) { 141 case PP_AUDIOCODEC_VORBIS: 142 return cdm::AudioDecoderConfig::kCodecVorbis; 143 case PP_AUDIOCODEC_AAC: 144 return cdm::AudioDecoderConfig::kCodecAac; 145 default: 146 return cdm::AudioDecoderConfig::kUnknownAudioCodec; 147 } 148 } 149 150 cdm::VideoDecoderConfig::VideoCodec PpVideoCodecToCdmVideoCodec( 151 PP_VideoCodec codec) { 152 switch (codec) { 153 case PP_VIDEOCODEC_VP8: 154 return cdm::VideoDecoderConfig::kCodecVp8; 155 case PP_VIDEOCODEC_H264: 156 return cdm::VideoDecoderConfig::kCodecH264; 157 default: 158 return cdm::VideoDecoderConfig::kUnknownVideoCodec; 159 } 160 } 161 162 cdm::VideoDecoderConfig::VideoCodecProfile PpVCProfileToCdmVCProfile( 163 PP_VideoCodecProfile profile) { 164 switch (profile) { 165 case PP_VIDEOCODECPROFILE_VP8_MAIN: 166 return cdm::VideoDecoderConfig::kVp8ProfileMain; 167 case PP_VIDEOCODECPROFILE_H264_BASELINE: 168 return cdm::VideoDecoderConfig::kH264ProfileBaseline; 169 case PP_VIDEOCODECPROFILE_H264_MAIN: 170 return cdm::VideoDecoderConfig::kH264ProfileMain; 171 case PP_VIDEOCODECPROFILE_H264_EXTENDED: 172 return cdm::VideoDecoderConfig::kH264ProfileExtended; 173 case PP_VIDEOCODECPROFILE_H264_HIGH: 174 return cdm::VideoDecoderConfig::kH264ProfileHigh; 175 case PP_VIDEOCODECPROFILE_H264_HIGH_10: 176 return cdm::VideoDecoderConfig::kH264ProfileHigh10; 177 case PP_VIDEOCODECPROFILE_H264_HIGH_422: 178 return cdm::VideoDecoderConfig::kH264ProfileHigh422; 179 case PP_VIDEOCODECPROFILE_H264_HIGH_444_PREDICTIVE: 180 return cdm::VideoDecoderConfig::kH264ProfileHigh444Predictive; 181 default: 182 return cdm::VideoDecoderConfig::kUnknownVideoCodecProfile; 183 } 184 } 185 186 cdm::VideoFormat PpDecryptedFrameFormatToCdmVideoFormat( 187 PP_DecryptedFrameFormat format) { 188 switch (format) { 189 case PP_DECRYPTEDFRAMEFORMAT_YV12: 190 return cdm::kYv12; 191 case PP_DECRYPTEDFRAMEFORMAT_I420: 192 return cdm::kI420; 193 default: 194 return cdm::kUnknownVideoFormat; 195 } 196 } 197 198 cdm::StreamType PpDecryptorStreamTypeToCdmStreamType( 199 PP_DecryptorStreamType stream_type) { 200 switch (stream_type) { 201 case PP_DECRYPTORSTREAMTYPE_AUDIO: 202 return cdm::kStreamTypeAudio; 203 case PP_DECRYPTORSTREAMTYPE_VIDEO: 204 return cdm::kStreamTypeVideo; 205 } 206 207 PP_NOTREACHED(); 208 return cdm::kStreamTypeVideo; 209 } 210 211 } // namespace 212 213 namespace media { 214 215 CdmAdapter::CdmAdapter(PP_Instance instance, pp::Module* module) 216 : pp::Instance(instance), 217 pp::ContentDecryptor_Private(this), 218 #if defined(OS_CHROMEOS) 219 output_protection_(this), 220 platform_verification_(this), 221 challenge_in_progress_(false), 222 output_link_mask_(0), 223 output_protection_mask_(0), 224 query_output_protection_in_progress_(false), 225 #endif 226 allocator_(this), 227 cdm_(NULL), 228 deferred_initialize_audio_decoder_(false), 229 deferred_audio_decoder_config_id_(0), 230 deferred_initialize_video_decoder_(false), 231 deferred_video_decoder_config_id_(0) { 232 callback_factory_.Initialize(this); 233 } 234 235 CdmAdapter::~CdmAdapter() {} 236 237 bool CdmAdapter::CreateCdmInstance(const std::string& key_system) { 238 PP_DCHECK(!cdm_); 239 cdm_ = make_linked_ptr(CdmWrapper::Create( 240 key_system.data(), key_system.size(), GetCdmHost, this)); 241 bool success = cdm_ != NULL; 242 243 const std::string message = "CDM instance for " + key_system + 244 (success ? "" : " could not be") + " created."; 245 DLOG_TO_CONSOLE(message); 246 CDM_DLOG() << message; 247 248 return success; 249 } 250 251 // No KeyErrors should be reported in this function because they cannot be 252 // bubbled up in the WD EME API. Those errors will be reported during session 253 // creation (CreateSession). 254 void CdmAdapter::Initialize(const std::string& key_system) { 255 PP_DCHECK(!key_system.empty()); 256 PP_DCHECK(key_system_.empty() || (key_system_ == key_system && cdm_)); 257 258 if (!cdm_ && !CreateCdmInstance(key_system)) 259 return; 260 261 PP_DCHECK(cdm_); 262 key_system_ = key_system; 263 } 264 265 void CdmAdapter::CreateSession(uint32_t session_id, 266 const std::string& type, 267 pp::VarArrayBuffer init_data) { 268 // Initialize() doesn't report an error, so CreateSession() can be called 269 // even if Initialize() failed. 270 if (!cdm_) { 271 OnSessionError(session_id, cdm::kUnknownError, 0); 272 return; 273 } 274 275 #if defined(CHECK_DOCUMENT_URL) 276 PP_URLComponents_Dev url_components = {}; 277 const pp::URLUtil_Dev* url_util = pp::URLUtil_Dev::Get(); 278 if (!url_util) { 279 OnSessionError(session_id, cdm::kUnknownError, 0); 280 return; 281 } 282 pp::Var href = url_util->GetDocumentURL( 283 pp::InstanceHandle(pp_instance()), &url_components); 284 PP_DCHECK(href.is_string()); 285 PP_DCHECK(!href.AsString().empty()); 286 PP_DCHECK(url_components.host.begin); 287 PP_DCHECK(0 < url_components.host.len); 288 #endif // defined(CHECK_DOCUMENT_URL) 289 290 cdm_->CreateSession(session_id, 291 type.data(), 292 type.size(), 293 static_cast<const uint8_t*>(init_data.Map()), 294 init_data.ByteLength()); 295 } 296 297 void CdmAdapter::UpdateSession(uint32_t session_id, 298 pp::VarArrayBuffer response) { 299 // TODO(jrummell): In EME WD, AddKey() can only be called on valid sessions. 300 // We should be able to DCHECK(cdm_) when addressing http://crbug.com/249976. 301 if (!cdm_) { 302 OnSessionError(session_id, cdm::kUnknownError, 0); 303 return; 304 } 305 306 const uint8_t* response_ptr = static_cast<const uint8_t*>(response.Map()); 307 const uint32_t response_size = response.ByteLength(); 308 309 if (!response_ptr || response_size <= 0) { 310 OnSessionError(session_id, cdm::kUnknownError, 0); 311 return; 312 } 313 CdmWrapper::Result result = 314 cdm_->UpdateSession(session_id, response_ptr, response_size); 315 switch (result) { 316 case CdmWrapper::NO_ACTION: 317 break; 318 case CdmWrapper::CALL_KEY_ADDED: 319 OnSessionReady(session_id); 320 break; 321 case CdmWrapper::CALL_KEY_ERROR: 322 OnSessionError(session_id, cdm::kUnknownError, 0); 323 break; 324 } 325 } 326 327 void CdmAdapter::ReleaseSession(uint32_t session_id) { 328 // TODO(jrummell): In EME WD, AddKey() can only be called on valid sessions. 329 // We should be able to DCHECK(cdm_) when addressing http://crbug.com/249976. 330 if (!cdm_) { 331 OnSessionError(session_id, cdm::kUnknownError, 0); 332 return; 333 } 334 335 CdmWrapper::Result result = cdm_->ReleaseSession(session_id); 336 switch (result) { 337 case CdmWrapper::NO_ACTION: 338 break; 339 case CdmWrapper::CALL_KEY_ADDED: 340 PP_NOTREACHED(); 341 break; 342 case CdmWrapper::CALL_KEY_ERROR: 343 OnSessionError(session_id, cdm::kUnknownError, 0); 344 break; 345 } 346 } 347 348 // Note: In the following decryption/decoding related functions, errors are NOT 349 // reported via KeyError, but are reported via corresponding PPB calls. 350 351 void CdmAdapter::Decrypt(pp::Buffer_Dev encrypted_buffer, 352 const PP_EncryptedBlockInfo& encrypted_block_info) { 353 PP_DCHECK(!encrypted_buffer.is_null()); 354 355 // Release a buffer that the caller indicated it is finished with. 356 allocator_.Release(encrypted_block_info.tracking_info.buffer_id); 357 358 cdm::Status status = cdm::kDecryptError; 359 LinkedDecryptedBlock decrypted_block(new DecryptedBlockImpl()); 360 361 if (cdm_) { 362 cdm::InputBuffer input_buffer; 363 std::vector<cdm::SubsampleEntry> subsamples; 364 ConfigureInputBuffer(encrypted_buffer, encrypted_block_info, &subsamples, 365 &input_buffer); 366 status = cdm_->Decrypt(input_buffer, decrypted_block.get()); 367 PP_DCHECK(status != cdm::kSuccess || 368 (decrypted_block->DecryptedBuffer() && 369 decrypted_block->DecryptedBuffer()->Size())); 370 } 371 372 CallOnMain(callback_factory_.NewCallback( 373 &CdmAdapter::DeliverBlock, 374 status, 375 decrypted_block, 376 encrypted_block_info.tracking_info)); 377 } 378 379 void CdmAdapter::InitializeAudioDecoder( 380 const PP_AudioDecoderConfig& decoder_config, 381 pp::Buffer_Dev extra_data_buffer) { 382 PP_DCHECK(!deferred_initialize_audio_decoder_); 383 PP_DCHECK(deferred_audio_decoder_config_id_ == 0); 384 cdm::Status status = cdm::kSessionError; 385 if (cdm_) { 386 cdm::AudioDecoderConfig cdm_decoder_config; 387 cdm_decoder_config.codec = 388 PpAudioCodecToCdmAudioCodec(decoder_config.codec); 389 cdm_decoder_config.channel_count = decoder_config.channel_count; 390 cdm_decoder_config.bits_per_channel = decoder_config.bits_per_channel; 391 cdm_decoder_config.samples_per_second = decoder_config.samples_per_second; 392 cdm_decoder_config.extra_data = 393 static_cast<uint8_t*>(extra_data_buffer.data()); 394 cdm_decoder_config.extra_data_size = extra_data_buffer.size(); 395 status = cdm_->InitializeAudioDecoder(cdm_decoder_config); 396 } 397 398 if (status == cdm::kDeferredInitialization) { 399 deferred_initialize_audio_decoder_ = true; 400 deferred_audio_decoder_config_id_ = decoder_config.request_id; 401 return; 402 } 403 404 CallOnMain(callback_factory_.NewCallback( 405 &CdmAdapter::DecoderInitializeDone, 406 PP_DECRYPTORSTREAMTYPE_AUDIO, 407 decoder_config.request_id, 408 status == cdm::kSuccess)); 409 } 410 411 void CdmAdapter::InitializeVideoDecoder( 412 const PP_VideoDecoderConfig& decoder_config, 413 pp::Buffer_Dev extra_data_buffer) { 414 PP_DCHECK(!deferred_initialize_video_decoder_); 415 PP_DCHECK(deferred_video_decoder_config_id_ == 0); 416 cdm::Status status = cdm::kSessionError; 417 if (cdm_) { 418 cdm::VideoDecoderConfig cdm_decoder_config; 419 cdm_decoder_config.codec = 420 PpVideoCodecToCdmVideoCodec(decoder_config.codec); 421 cdm_decoder_config.profile = 422 PpVCProfileToCdmVCProfile(decoder_config.profile); 423 cdm_decoder_config.format = 424 PpDecryptedFrameFormatToCdmVideoFormat(decoder_config.format); 425 cdm_decoder_config.coded_size.width = decoder_config.width; 426 cdm_decoder_config.coded_size.height = decoder_config.height; 427 cdm_decoder_config.extra_data = 428 static_cast<uint8_t*>(extra_data_buffer.data()); 429 cdm_decoder_config.extra_data_size = extra_data_buffer.size(); 430 status = cdm_->InitializeVideoDecoder(cdm_decoder_config); 431 } 432 433 if (status == cdm::kDeferredInitialization) { 434 deferred_initialize_video_decoder_ = true; 435 deferred_video_decoder_config_id_ = decoder_config.request_id; 436 return; 437 } 438 439 CallOnMain(callback_factory_.NewCallback( 440 &CdmAdapter::DecoderInitializeDone, 441 PP_DECRYPTORSTREAMTYPE_VIDEO, 442 decoder_config.request_id, 443 status == cdm::kSuccess)); 444 } 445 446 void CdmAdapter::DeinitializeDecoder(PP_DecryptorStreamType decoder_type, 447 uint32_t request_id) { 448 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded. 449 if (cdm_) { 450 cdm_->DeinitializeDecoder( 451 PpDecryptorStreamTypeToCdmStreamType(decoder_type)); 452 } 453 454 CallOnMain(callback_factory_.NewCallback( 455 &CdmAdapter::DecoderDeinitializeDone, 456 decoder_type, 457 request_id)); 458 } 459 460 void CdmAdapter::ResetDecoder(PP_DecryptorStreamType decoder_type, 461 uint32_t request_id) { 462 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded. 463 if (cdm_) 464 cdm_->ResetDecoder(PpDecryptorStreamTypeToCdmStreamType(decoder_type)); 465 466 CallOnMain(callback_factory_.NewCallback(&CdmAdapter::DecoderResetDone, 467 decoder_type, 468 request_id)); 469 } 470 471 void CdmAdapter::DecryptAndDecode( 472 PP_DecryptorStreamType decoder_type, 473 pp::Buffer_Dev encrypted_buffer, 474 const PP_EncryptedBlockInfo& encrypted_block_info) { 475 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded. 476 // Release a buffer that the caller indicated it is finished with. 477 allocator_.Release(encrypted_block_info.tracking_info.buffer_id); 478 479 cdm::InputBuffer input_buffer; 480 std::vector<cdm::SubsampleEntry> subsamples; 481 if (cdm_ && !encrypted_buffer.is_null()) { 482 ConfigureInputBuffer(encrypted_buffer, 483 encrypted_block_info, 484 &subsamples, 485 &input_buffer); 486 } 487 488 cdm::Status status = cdm::kDecodeError; 489 490 switch (decoder_type) { 491 case PP_DECRYPTORSTREAMTYPE_VIDEO: { 492 LinkedVideoFrame video_frame(new VideoFrameImpl()); 493 if (cdm_) 494 status = cdm_->DecryptAndDecodeFrame(input_buffer, video_frame.get()); 495 CallOnMain(callback_factory_.NewCallback( 496 &CdmAdapter::DeliverFrame, 497 status, 498 video_frame, 499 encrypted_block_info.tracking_info)); 500 return; 501 } 502 503 case PP_DECRYPTORSTREAMTYPE_AUDIO: { 504 LinkedAudioFrames audio_frames(new AudioFramesImpl()); 505 if (cdm_) { 506 status = cdm_->DecryptAndDecodeSamples(input_buffer, 507 audio_frames.get()); 508 } 509 CallOnMain(callback_factory_.NewCallback( 510 &CdmAdapter::DeliverSamples, 511 status, 512 audio_frames, 513 encrypted_block_info.tracking_info)); 514 return; 515 } 516 517 default: 518 PP_NOTREACHED(); 519 return; 520 } 521 } 522 523 cdm::Buffer* CdmAdapter::Allocate(uint32_t capacity) { 524 return allocator_.Allocate(capacity); 525 } 526 527 void CdmAdapter::SetTimer(int64_t delay_ms, void* context) { 528 // NOTE: doesn't really need to run on the main thread; could just as well run 529 // on a helper thread if |cdm_| were thread-friendly and care was taken. We 530 // only use CallOnMainThread() here to get delayed-execution behavior. 531 pp::Module::Get()->core()->CallOnMainThread( 532 delay_ms, 533 callback_factory_.NewCallback(&CdmAdapter::TimerExpired, context), 534 PP_OK); 535 } 536 537 void CdmAdapter::TimerExpired(int32_t result, void* context) { 538 PP_DCHECK(result == PP_OK); 539 cdm_->TimerExpired(context); 540 } 541 542 double CdmAdapter::GetCurrentWallTimeInSeconds() { 543 return pp::Module::Get()->core()->GetTime(); 544 } 545 546 void CdmAdapter::SendKeyMessage( 547 const char* session_id, uint32_t session_id_length, 548 const char* message, uint32_t message_length, 549 const char* default_url, uint32_t default_url_length) { 550 PP_DCHECK(!key_system_.empty()); 551 552 std::string session_id_str(session_id, session_id_length); 553 PP_DCHECK(!session_id_str.empty()); 554 uint32_t session_reference_id = cdm_->LookupSessionId(session_id_str); 555 556 OnSessionCreated(session_reference_id, session_id, session_id_length); 557 OnSessionMessage(session_reference_id, 558 message, message_length, 559 default_url, default_url_length); 560 } 561 562 void CdmAdapter::SendKeyError(const char* session_id, 563 uint32_t session_id_length, 564 cdm::MediaKeyError error_code, 565 uint32_t system_code) { 566 std::string session_id_str(session_id, session_id_length); 567 uint32_t session_reference_id = cdm_->LookupSessionId(session_id_str); 568 OnSessionError(session_reference_id, error_code, system_code); 569 } 570 571 void CdmAdapter::GetPrivateData(int32_t* instance, 572 GetPrivateInterface* get_interface) { 573 *instance = pp_instance(); 574 *get_interface = pp::Module::Get()->get_browser_interface(); 575 } 576 577 void CdmAdapter::OnSessionCreated(uint32_t session_id, 578 const char* web_session_id, 579 uint32_t web_session_id_length) { 580 PostOnMain(callback_factory_.NewCallback( 581 &CdmAdapter::SendSessionCreatedInternal, 582 session_id, 583 std::string(web_session_id, web_session_id_length))); 584 } 585 586 void CdmAdapter::OnSessionMessage(uint32_t session_id, 587 const char* message, 588 uint32_t message_length, 589 const char* destination_url, 590 uint32_t destination_url_length) { 591 PostOnMain(callback_factory_.NewCallback( 592 &CdmAdapter::SendSessionMessageInternal, 593 session_id, 594 std::vector<uint8>(message, message + message_length), 595 std::string(destination_url, destination_url_length))); 596 } 597 598 void CdmAdapter::OnSessionReady(uint32_t session_id) { 599 PostOnMain(callback_factory_.NewCallback( 600 &CdmAdapter::SendSessionReadyInternal, session_id)); 601 } 602 603 void CdmAdapter::OnSessionClosed(uint32_t session_id) { 604 PostOnMain(callback_factory_.NewCallback( 605 &CdmAdapter::SendSessionClosedInternal, session_id)); 606 } 607 608 void CdmAdapter::OnSessionError(uint32_t session_id, 609 cdm::MediaKeyError error_code, 610 uint32_t system_code) { 611 PostOnMain(callback_factory_.NewCallback( 612 &CdmAdapter::SendSessionErrorInternal, 613 session_id, 614 error_code, 615 system_code)); 616 } 617 618 void CdmAdapter::SendSessionCreatedInternal(int32_t result, 619 uint32_t session_id, 620 const std::string& web_session_id) { 621 PP_DCHECK(result == PP_OK); 622 pp::ContentDecryptor_Private::SessionCreated(session_id, web_session_id); 623 } 624 625 void CdmAdapter::SendSessionMessageInternal(int32_t result, 626 uint32_t session_id, 627 const std::vector<uint8>& message, 628 const std::string& default_url) { 629 PP_DCHECK(result == PP_OK); 630 631 pp::VarArrayBuffer message_array_buffer(message.size()); 632 if (message.size() > 0) { 633 memcpy(message_array_buffer.Map(), message.data(), message.size()); 634 } 635 636 pp::ContentDecryptor_Private::SessionMessage( 637 session_id, message_array_buffer, default_url); 638 } 639 640 void CdmAdapter::SendSessionReadyInternal(int32_t result, uint32_t session_id) { 641 PP_DCHECK(result == PP_OK); 642 pp::ContentDecryptor_Private::SessionReady(session_id); 643 } 644 645 void CdmAdapter::SendSessionClosedInternal(int32_t result, 646 uint32_t session_id) { 647 PP_DCHECK(result == PP_OK); 648 pp::ContentDecryptor_Private::SessionClosed(session_id); 649 } 650 651 void CdmAdapter::SendSessionErrorInternal(int32_t result, 652 uint32_t session_id, 653 cdm::MediaKeyError error_code, 654 uint32_t system_code) { 655 PP_DCHECK(result == PP_OK); 656 pp::ContentDecryptor_Private::SessionError( 657 session_id, error_code, system_code); 658 } 659 660 void CdmAdapter::DeliverBlock(int32_t result, 661 const cdm::Status& status, 662 const LinkedDecryptedBlock& decrypted_block, 663 const PP_DecryptTrackingInfo& tracking_info) { 664 PP_DCHECK(result == PP_OK); 665 PP_DecryptedBlockInfo decrypted_block_info; 666 decrypted_block_info.tracking_info = tracking_info; 667 decrypted_block_info.tracking_info.timestamp = decrypted_block->Timestamp(); 668 decrypted_block_info.tracking_info.buffer_id = 0; 669 decrypted_block_info.data_size = 0; 670 decrypted_block_info.result = CdmStatusToPpDecryptResult(status); 671 672 pp::Buffer_Dev buffer; 673 674 if (decrypted_block_info.result == PP_DECRYPTRESULT_SUCCESS) { 675 PP_DCHECK(decrypted_block.get() && decrypted_block->DecryptedBuffer()); 676 if (!decrypted_block.get() || !decrypted_block->DecryptedBuffer()) { 677 PP_NOTREACHED(); 678 decrypted_block_info.result = PP_DECRYPTRESULT_DECRYPT_ERROR; 679 } else { 680 PpbBuffer* ppb_buffer = 681 static_cast<PpbBuffer*>(decrypted_block->DecryptedBuffer()); 682 buffer = ppb_buffer->buffer_dev(); 683 decrypted_block_info.tracking_info.buffer_id = ppb_buffer->buffer_id(); 684 decrypted_block_info.data_size = ppb_buffer->Size(); 685 } 686 } 687 688 pp::ContentDecryptor_Private::DeliverBlock(buffer, decrypted_block_info); 689 } 690 691 void CdmAdapter::DecoderInitializeDone(int32_t result, 692 PP_DecryptorStreamType decoder_type, 693 uint32_t request_id, 694 bool success) { 695 PP_DCHECK(result == PP_OK); 696 pp::ContentDecryptor_Private::DecoderInitializeDone(decoder_type, 697 request_id, 698 success); 699 } 700 701 void CdmAdapter::DecoderDeinitializeDone(int32_t result, 702 PP_DecryptorStreamType decoder_type, 703 uint32_t request_id) { 704 pp::ContentDecryptor_Private::DecoderDeinitializeDone(decoder_type, 705 request_id); 706 } 707 708 void CdmAdapter::DecoderResetDone(int32_t result, 709 PP_DecryptorStreamType decoder_type, 710 uint32_t request_id) { 711 pp::ContentDecryptor_Private::DecoderResetDone(decoder_type, request_id); 712 } 713 714 void CdmAdapter::DeliverFrame( 715 int32_t result, 716 const cdm::Status& status, 717 const LinkedVideoFrame& video_frame, 718 const PP_DecryptTrackingInfo& tracking_info) { 719 PP_DCHECK(result == PP_OK); 720 PP_DecryptedFrameInfo decrypted_frame_info; 721 decrypted_frame_info.tracking_info.request_id = tracking_info.request_id; 722 decrypted_frame_info.tracking_info.buffer_id = 0; 723 decrypted_frame_info.result = CdmStatusToPpDecryptResult(status); 724 725 pp::Buffer_Dev buffer; 726 727 if (decrypted_frame_info.result == PP_DECRYPTRESULT_SUCCESS) { 728 if (!IsValidVideoFrame(video_frame)) { 729 PP_NOTREACHED(); 730 decrypted_frame_info.result = PP_DECRYPTRESULT_DECODE_ERROR; 731 } else { 732 PpbBuffer* ppb_buffer = 733 static_cast<PpbBuffer*>(video_frame->FrameBuffer()); 734 735 buffer = ppb_buffer->buffer_dev(); 736 737 decrypted_frame_info.tracking_info.timestamp = video_frame->Timestamp(); 738 decrypted_frame_info.tracking_info.buffer_id = ppb_buffer->buffer_id(); 739 decrypted_frame_info.format = 740 CdmVideoFormatToPpDecryptedFrameFormat(video_frame->Format()); 741 decrypted_frame_info.width = video_frame->Size().width; 742 decrypted_frame_info.height = video_frame->Size().height; 743 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_Y] = 744 video_frame->PlaneOffset(cdm::VideoFrame::kYPlane); 745 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_U] = 746 video_frame->PlaneOffset(cdm::VideoFrame::kUPlane); 747 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_V] = 748 video_frame->PlaneOffset(cdm::VideoFrame::kVPlane); 749 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_Y] = 750 video_frame->Stride(cdm::VideoFrame::kYPlane); 751 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_U] = 752 video_frame->Stride(cdm::VideoFrame::kUPlane); 753 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_V] = 754 video_frame->Stride(cdm::VideoFrame::kVPlane); 755 } 756 } 757 pp::ContentDecryptor_Private::DeliverFrame(buffer, decrypted_frame_info); 758 } 759 760 void CdmAdapter::DeliverSamples(int32_t result, 761 const cdm::Status& status, 762 const LinkedAudioFrames& audio_frames, 763 const PP_DecryptTrackingInfo& tracking_info) { 764 PP_DCHECK(result == PP_OK); 765 766 PP_DecryptedSampleInfo decrypted_sample_info; 767 decrypted_sample_info.tracking_info = tracking_info; 768 decrypted_sample_info.tracking_info.timestamp = 0; 769 decrypted_sample_info.tracking_info.buffer_id = 0; 770 decrypted_sample_info.data_size = 0; 771 decrypted_sample_info.result = CdmStatusToPpDecryptResult(status); 772 773 pp::Buffer_Dev buffer; 774 775 if (decrypted_sample_info.result == PP_DECRYPTRESULT_SUCCESS) { 776 PP_DCHECK(audio_frames.get() && audio_frames->FrameBuffer()); 777 if (!audio_frames.get() || !audio_frames->FrameBuffer()) { 778 PP_NOTREACHED(); 779 decrypted_sample_info.result = PP_DECRYPTRESULT_DECRYPT_ERROR; 780 } else { 781 PpbBuffer* ppb_buffer = 782 static_cast<PpbBuffer*>(audio_frames->FrameBuffer()); 783 buffer = ppb_buffer->buffer_dev(); 784 decrypted_sample_info.tracking_info.buffer_id = ppb_buffer->buffer_id(); 785 decrypted_sample_info.data_size = ppb_buffer->Size(); 786 decrypted_sample_info.format = 787 CdmAudioFormatToPpDecryptedSampleFormat(audio_frames->Format()); 788 } 789 } 790 791 pp::ContentDecryptor_Private::DeliverSamples(buffer, decrypted_sample_info); 792 } 793 794 bool CdmAdapter::IsValidVideoFrame(const LinkedVideoFrame& video_frame) { 795 if (!video_frame.get() || 796 !video_frame->FrameBuffer() || 797 (video_frame->Format() != cdm::kI420 && 798 video_frame->Format() != cdm::kYv12)) { 799 CDM_DLOG() << "Invalid video frame!"; 800 return false; 801 } 802 803 PpbBuffer* ppb_buffer = static_cast<PpbBuffer*>(video_frame->FrameBuffer()); 804 805 for (uint32_t i = 0; i < cdm::VideoFrame::kMaxPlanes; ++i) { 806 int plane_height = (i == cdm::VideoFrame::kYPlane) ? 807 video_frame->Size().height : (video_frame->Size().height + 1) / 2; 808 cdm::VideoFrame::VideoPlane plane = 809 static_cast<cdm::VideoFrame::VideoPlane>(i); 810 if (ppb_buffer->Size() < video_frame->PlaneOffset(plane) + 811 plane_height * video_frame->Stride(plane)) { 812 return false; 813 } 814 } 815 816 return true; 817 } 818 819 #if !defined(NDEBUG) 820 void CdmAdapter::LogToConsole(const pp::Var& value) { 821 PP_DCHECK(IsMainThread()); 822 const PPB_Console* console = reinterpret_cast<const PPB_Console*>( 823 pp::Module::Get()->GetBrowserInterface(PPB_CONSOLE_INTERFACE)); 824 console->Log(pp_instance(), PP_LOGLEVEL_LOG, value.pp_var()); 825 } 826 #endif // !defined(NDEBUG) 827 828 void CdmAdapter::SendPlatformChallenge( 829 const char* service_id, uint32_t service_id_length, 830 const char* challenge, uint32_t challenge_length) { 831 #if defined(OS_CHROMEOS) 832 PP_DCHECK(!challenge_in_progress_); 833 834 // Ensure member variables set by the callback are in a clean state. 835 signed_data_output_ = pp::Var(); 836 signed_data_signature_output_ = pp::Var(); 837 platform_key_certificate_output_ = pp::Var(); 838 839 pp::VarArrayBuffer challenge_var(challenge_length); 840 uint8_t* var_data = static_cast<uint8_t*>(challenge_var.Map()); 841 memcpy(var_data, challenge, challenge_length); 842 843 std::string service_id_str(service_id, service_id_length); 844 int32_t result = platform_verification_.ChallengePlatform( 845 pp::Var(service_id_str), challenge_var, &signed_data_output_, 846 &signed_data_signature_output_, &platform_key_certificate_output_, 847 callback_factory_.NewCallback(&CdmAdapter::SendPlatformChallengeDone)); 848 challenge_var.Unmap(); 849 if (result == PP_OK_COMPLETIONPENDING) { 850 challenge_in_progress_ = true; 851 return; 852 } 853 854 // Fall through on error and issue an empty OnPlatformChallengeResponse(). 855 PP_DCHECK(result != PP_OK); 856 #endif 857 858 cdm::PlatformChallengeResponse response = {}; 859 cdm_->OnPlatformChallengeResponse(response); 860 } 861 862 void CdmAdapter::EnableOutputProtection(uint32_t desired_protection_mask) { 863 #if defined(OS_CHROMEOS) 864 int32_t result = output_protection_.EnableProtection( 865 desired_protection_mask, callback_factory_.NewCallback( 866 &CdmAdapter::EnableProtectionDone)); 867 868 // Errors are ignored since clients must call QueryOutputProtectionStatus() to 869 // inspect the protection status on a regular basis. 870 871 if (result != PP_OK && result != PP_OK_COMPLETIONPENDING) 872 CDM_DLOG() << __FUNCTION__ << " failed!"; 873 #endif 874 } 875 876 void CdmAdapter::QueryOutputProtectionStatus() { 877 #if defined(OS_CHROMEOS) 878 PP_DCHECK(!query_output_protection_in_progress_); 879 880 output_link_mask_ = output_protection_mask_ = 0; 881 const int32_t result = output_protection_.QueryStatus( 882 &output_link_mask_, 883 &output_protection_mask_, 884 callback_factory_.NewCallback( 885 &CdmAdapter::QueryOutputProtectionStatusDone)); 886 if (result == PP_OK_COMPLETIONPENDING) { 887 query_output_protection_in_progress_ = true; 888 return; 889 } 890 891 // Fall through on error and issue an empty OnQueryOutputProtectionStatus(). 892 PP_DCHECK(result != PP_OK); 893 #endif 894 895 cdm_->OnQueryOutputProtectionStatus(0, 0); 896 } 897 898 void CdmAdapter::OnDeferredInitializationDone(cdm::StreamType stream_type, 899 cdm::Status decoder_status) { 900 switch (stream_type) { 901 case cdm::kStreamTypeAudio: 902 PP_DCHECK(deferred_initialize_audio_decoder_); 903 CallOnMain( 904 callback_factory_.NewCallback(&CdmAdapter::DecoderInitializeDone, 905 PP_DECRYPTORSTREAMTYPE_AUDIO, 906 deferred_audio_decoder_config_id_, 907 decoder_status == cdm::kSuccess)); 908 deferred_initialize_audio_decoder_ = false; 909 deferred_audio_decoder_config_id_ = 0; 910 break; 911 case cdm::kStreamTypeVideo: 912 PP_DCHECK(deferred_initialize_video_decoder_); 913 CallOnMain( 914 callback_factory_.NewCallback(&CdmAdapter::DecoderInitializeDone, 915 PP_DECRYPTORSTREAMTYPE_VIDEO, 916 deferred_video_decoder_config_id_, 917 decoder_status == cdm::kSuccess)); 918 deferred_initialize_video_decoder_ = false; 919 deferred_video_decoder_config_id_ = 0; 920 break; 921 } 922 } 923 924 #if defined(OS_CHROMEOS) 925 void CdmAdapter::SendPlatformChallengeDone(int32_t result) { 926 challenge_in_progress_ = false; 927 928 if (result != PP_OK) { 929 CDM_DLOG() << __FUNCTION__ << ": Platform challenge failed!"; 930 cdm::PlatformChallengeResponse response = {}; 931 cdm_->OnPlatformChallengeResponse(response); 932 return; 933 } 934 935 pp::VarArrayBuffer signed_data_var(signed_data_output_); 936 pp::VarArrayBuffer signed_data_signature_var(signed_data_signature_output_); 937 std::string platform_key_certificate_string = 938 platform_key_certificate_output_.AsString(); 939 940 cdm::PlatformChallengeResponse response = { 941 static_cast<uint8_t*>(signed_data_var.Map()), 942 signed_data_var.ByteLength(), 943 944 static_cast<uint8_t*>(signed_data_signature_var.Map()), 945 signed_data_signature_var.ByteLength(), 946 947 reinterpret_cast<const uint8_t*>(platform_key_certificate_string.c_str()), 948 static_cast<uint32_t>(platform_key_certificate_string.length()) 949 }; 950 cdm_->OnPlatformChallengeResponse(response); 951 952 signed_data_var.Unmap(); 953 signed_data_signature_var.Unmap(); 954 } 955 956 void CdmAdapter::EnableProtectionDone(int32_t result) { 957 // Does nothing since clients must call QueryOutputProtectionStatus() to 958 // inspect the protection status on a regular basis. 959 CDM_DLOG() << __FUNCTION__ << " : " << result; 960 } 961 962 void CdmAdapter::QueryOutputProtectionStatusDone(int32_t result) { 963 PP_DCHECK(query_output_protection_in_progress_); 964 query_output_protection_in_progress_ = false; 965 966 // Return a protection status of none on error. 967 if (result != PP_OK) 968 output_link_mask_ = output_protection_mask_ = 0; 969 970 cdm_->OnQueryOutputProtectionStatus(output_link_mask_, 971 output_protection_mask_); 972 } 973 #endif 974 975 void* GetCdmHost(int host_interface_version, void* user_data) { 976 if (!host_interface_version || !user_data) 977 return NULL; 978 979 COMPILE_ASSERT(cdm::ContentDecryptionModule::Host::kVersion == 980 cdm::ContentDecryptionModule_3::Host::kVersion, 981 update_code_below); 982 983 // Ensure IsSupportedCdmHostVersion matches implementation of this function. 984 // Always update this DCHECK when updating this function. 985 // If this check fails, update this function and DCHECK or update 986 // IsSupportedCdmHostVersion. 987 PP_DCHECK( 988 // Future version is not supported. 989 !IsSupportedCdmHostVersion( 990 cdm::ContentDecryptionModule::Host::kVersion + 1) && 991 // Current version is supported. 992 IsSupportedCdmHostVersion(cdm::ContentDecryptionModule::Host::kVersion) && 993 // Include all previous supported versions here. 994 IsSupportedCdmHostVersion(cdm::Host_1::kVersion) && 995 // One older than the oldest supported version is not supported. 996 !IsSupportedCdmHostVersion(cdm::Host_1::kVersion - 1)); 997 PP_DCHECK(IsSupportedCdmHostVersion(host_interface_version)); 998 999 CdmAdapter* cdm_adapter = static_cast<CdmAdapter*>(user_data); 1000 CDM_DLOG() << "Create CDM Host with version " << host_interface_version; 1001 switch (host_interface_version) { 1002 case cdm::Host_3::kVersion: 1003 return static_cast<cdm::Host_3*>(cdm_adapter); 1004 case cdm::Host_2::kVersion: 1005 return static_cast<cdm::Host_2*>(cdm_adapter); 1006 case cdm::Host_1::kVersion: 1007 return static_cast<cdm::Host_1*>(cdm_adapter); 1008 default: 1009 PP_NOTREACHED(); 1010 return NULL; 1011 } 1012 } 1013 1014 // This object is the global object representing this plugin library as long 1015 // as it is loaded. 1016 class CdmAdapterModule : public pp::Module { 1017 public: 1018 CdmAdapterModule() : pp::Module() { 1019 // This function blocks the renderer thread (PluginInstance::Initialize()). 1020 // Move this call to other places if this may be a concern in the future. 1021 INITIALIZE_CDM_MODULE(); 1022 } 1023 virtual ~CdmAdapterModule() { 1024 DeinitializeCdmModule(); 1025 } 1026 1027 virtual pp::Instance* CreateInstance(PP_Instance instance) { 1028 return new CdmAdapter(instance, this); 1029 } 1030 }; 1031 1032 } // namespace media 1033 1034 namespace pp { 1035 1036 // Factory function for your specialization of the Module object. 1037 Module* CreateModule() { 1038 return new media::CdmAdapterModule(); 1039 } 1040 1041 } // namespace pp 1042