Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / media / cdm / ppapi / cdm_adapter.cc
blob29ca3ea9849f223140d1cec53fb9dfd15f633f60
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.
5 #include "media/cdm/ppapi/cdm_adapter.h"
7 #include "media/base/limits.h"
8 #include "media/cdm/ppapi/cdm_file_io_impl.h"
9 #include "media/cdm/ppapi/cdm_logging.h"
10 #include "media/cdm/ppapi/supported_cdm_versions.h"
11 #include "ppapi/c/ppb_console.h"
12 #include "ppapi/cpp/private/uma_private.h"
14 #if defined(CHECK_DOCUMENT_URL)
15 #include "ppapi/cpp/dev/url_util_dev.h"
16 #include "ppapi/cpp/instance_handle.h"
17 #endif // defined(CHECK_DOCUMENT_URL)
19 namespace {
21 // Constants for UMA reporting of file size (in KB) via HistogramCustomCounts().
22 // Note that the histogram is log-scaled (rather than linear).
23 const uint32_t kSizeKBMin = 1;
24 const uint32_t kSizeKBMax = 512 * 1024; // 512MB
25 const uint32_t kSizeKBBuckets = 100;
27 #if !defined(NDEBUG)
28 #define DLOG_TO_CONSOLE(message) LogToConsole(message);
29 #else
30 #define DLOG_TO_CONSOLE(message) (void)(message);
31 #endif
33 bool IsMainThread() {
34 return pp::Module::Get()->core()->IsMainThread();
37 // Posts a task to run |cb| on the main thread. The task is posted even if the
38 // current thread is the main thread.
39 void PostOnMain(pp::CompletionCallback cb) {
40 pp::Module::Get()->core()->CallOnMainThread(0, cb, PP_OK);
43 // Ensures |cb| is called on the main thread, either because the current thread
44 // is the main thread or by posting it to the main thread.
45 void CallOnMain(pp::CompletionCallback cb) {
46 // TODO(tomfinegan): This is only necessary because PPAPI doesn't allow calls
47 // off the main thread yet. Remove this once the change lands.
48 if (IsMainThread())
49 cb.Run(PP_OK);
50 else
51 PostOnMain(cb);
54 // Configures a cdm::InputBuffer. |subsamples| must exist as long as
55 // |input_buffer| is in use.
56 void ConfigureInputBuffer(
57 const pp::Buffer_Dev& encrypted_buffer,
58 const PP_EncryptedBlockInfo& encrypted_block_info,
59 std::vector<cdm::SubsampleEntry>* subsamples,
60 cdm::InputBuffer* input_buffer) {
61 PP_DCHECK(subsamples);
62 PP_DCHECK(!encrypted_buffer.is_null());
64 input_buffer->data = static_cast<uint8_t*>(encrypted_buffer.data());
65 input_buffer->data_size = encrypted_block_info.data_size;
66 PP_DCHECK(encrypted_buffer.size() >= input_buffer->data_size);
68 PP_DCHECK(encrypted_block_info.key_id_size <=
69 arraysize(encrypted_block_info.key_id));
70 input_buffer->key_id_size = encrypted_block_info.key_id_size;
71 input_buffer->key_id = input_buffer->key_id_size > 0 ?
72 encrypted_block_info.key_id : NULL;
74 PP_DCHECK(encrypted_block_info.iv_size <= arraysize(encrypted_block_info.iv));
75 input_buffer->iv_size = encrypted_block_info.iv_size;
76 input_buffer->iv = encrypted_block_info.iv_size > 0 ?
77 encrypted_block_info.iv : NULL;
79 input_buffer->num_subsamples = encrypted_block_info.num_subsamples;
80 if (encrypted_block_info.num_subsamples > 0) {
81 subsamples->reserve(encrypted_block_info.num_subsamples);
83 for (uint32_t i = 0; i < encrypted_block_info.num_subsamples; ++i) {
84 subsamples->push_back(cdm::SubsampleEntry(
85 encrypted_block_info.subsamples[i].clear_bytes,
86 encrypted_block_info.subsamples[i].cipher_bytes));
89 input_buffer->subsamples = &(*subsamples)[0];
92 input_buffer->timestamp = encrypted_block_info.tracking_info.timestamp;
95 PP_DecryptResult CdmStatusToPpDecryptResult(cdm::Status status) {
96 switch (status) {
97 case cdm::kSuccess:
98 return PP_DECRYPTRESULT_SUCCESS;
99 case cdm::kNoKey:
100 return PP_DECRYPTRESULT_DECRYPT_NOKEY;
101 case cdm::kNeedMoreData:
102 return PP_DECRYPTRESULT_NEEDMOREDATA;
103 case cdm::kDecryptError:
104 return PP_DECRYPTRESULT_DECRYPT_ERROR;
105 case cdm::kDecodeError:
106 return PP_DECRYPTRESULT_DECODE_ERROR;
107 case cdm::kSessionError:
108 case cdm::kDeferredInitialization:
109 // kSessionError and kDeferredInitialization are only used by the
110 // Initialize* methods internally and never returned. Deliver*
111 // methods should never use these values.
112 break;
115 PP_NOTREACHED();
116 return PP_DECRYPTRESULT_DECRYPT_ERROR;
119 PP_DecryptedFrameFormat CdmVideoFormatToPpDecryptedFrameFormat(
120 cdm::VideoFormat format) {
121 switch (format) {
122 case cdm::kYv12:
123 return PP_DECRYPTEDFRAMEFORMAT_YV12;
124 case cdm::kI420:
125 return PP_DECRYPTEDFRAMEFORMAT_I420;
126 default:
127 return PP_DECRYPTEDFRAMEFORMAT_UNKNOWN;
131 PP_DecryptedSampleFormat CdmAudioFormatToPpDecryptedSampleFormat(
132 cdm::AudioFormat format) {
133 switch (format) {
134 case cdm::kAudioFormatU8:
135 return PP_DECRYPTEDSAMPLEFORMAT_U8;
136 case cdm::kAudioFormatS16:
137 return PP_DECRYPTEDSAMPLEFORMAT_S16;
138 case cdm::kAudioFormatS32:
139 return PP_DECRYPTEDSAMPLEFORMAT_S32;
140 case cdm::kAudioFormatF32:
141 return PP_DECRYPTEDSAMPLEFORMAT_F32;
142 case cdm::kAudioFormatPlanarS16:
143 return PP_DECRYPTEDSAMPLEFORMAT_PLANAR_S16;
144 case cdm::kAudioFormatPlanarF32:
145 return PP_DECRYPTEDSAMPLEFORMAT_PLANAR_F32;
146 default:
147 return PP_DECRYPTEDSAMPLEFORMAT_UNKNOWN;
151 cdm::AudioDecoderConfig::AudioCodec PpAudioCodecToCdmAudioCodec(
152 PP_AudioCodec codec) {
153 switch (codec) {
154 case PP_AUDIOCODEC_VORBIS:
155 return cdm::AudioDecoderConfig::kCodecVorbis;
156 case PP_AUDIOCODEC_AAC:
157 return cdm::AudioDecoderConfig::kCodecAac;
158 default:
159 return cdm::AudioDecoderConfig::kUnknownAudioCodec;
163 cdm::VideoDecoderConfig::VideoCodec PpVideoCodecToCdmVideoCodec(
164 PP_VideoCodec codec) {
165 switch (codec) {
166 case PP_VIDEOCODEC_VP8:
167 return cdm::VideoDecoderConfig::kCodecVp8;
168 case PP_VIDEOCODEC_H264:
169 return cdm::VideoDecoderConfig::kCodecH264;
170 case PP_VIDEOCODEC_VP9:
171 return cdm::VideoDecoderConfig::kCodecVp9;
172 default:
173 return cdm::VideoDecoderConfig::kUnknownVideoCodec;
177 cdm::VideoDecoderConfig::VideoCodecProfile PpVCProfileToCdmVCProfile(
178 PP_VideoCodecProfile profile) {
179 switch (profile) {
180 case PP_VIDEOCODECPROFILE_NOT_NEEDED:
181 return cdm::VideoDecoderConfig::kProfileNotNeeded;
182 case PP_VIDEOCODECPROFILE_H264_BASELINE:
183 return cdm::VideoDecoderConfig::kH264ProfileBaseline;
184 case PP_VIDEOCODECPROFILE_H264_MAIN:
185 return cdm::VideoDecoderConfig::kH264ProfileMain;
186 case PP_VIDEOCODECPROFILE_H264_EXTENDED:
187 return cdm::VideoDecoderConfig::kH264ProfileExtended;
188 case PP_VIDEOCODECPROFILE_H264_HIGH:
189 return cdm::VideoDecoderConfig::kH264ProfileHigh;
190 case PP_VIDEOCODECPROFILE_H264_HIGH_10:
191 return cdm::VideoDecoderConfig::kH264ProfileHigh10;
192 case PP_VIDEOCODECPROFILE_H264_HIGH_422:
193 return cdm::VideoDecoderConfig::kH264ProfileHigh422;
194 case PP_VIDEOCODECPROFILE_H264_HIGH_444_PREDICTIVE:
195 return cdm::VideoDecoderConfig::kH264ProfileHigh444Predictive;
196 default:
197 return cdm::VideoDecoderConfig::kUnknownVideoCodecProfile;
201 cdm::VideoFormat PpDecryptedFrameFormatToCdmVideoFormat(
202 PP_DecryptedFrameFormat format) {
203 switch (format) {
204 case PP_DECRYPTEDFRAMEFORMAT_YV12:
205 return cdm::kYv12;
206 case PP_DECRYPTEDFRAMEFORMAT_I420:
207 return cdm::kI420;
208 default:
209 return cdm::kUnknownVideoFormat;
213 cdm::StreamType PpDecryptorStreamTypeToCdmStreamType(
214 PP_DecryptorStreamType stream_type) {
215 switch (stream_type) {
216 case PP_DECRYPTORSTREAMTYPE_AUDIO:
217 return cdm::kStreamTypeAudio;
218 case PP_DECRYPTORSTREAMTYPE_VIDEO:
219 return cdm::kStreamTypeVideo;
222 PP_NOTREACHED();
223 return cdm::kStreamTypeVideo;
226 cdm::SessionType PpSessionTypeToCdmSessionType(PP_SessionType session_type) {
227 switch (session_type) {
228 case PP_SESSIONTYPE_TEMPORARY:
229 return cdm::kTemporary;
230 case PP_SESSIONTYPE_PERSISTENT_LICENSE:
231 return cdm::kPersistentLicense;
232 case PP_SESSIONTYPE_PERSISTENT_RELEASE:
233 return cdm::kPersistentKeyRelease;
236 PP_NOTREACHED();
237 return cdm::kTemporary;
240 cdm::InitDataType PpInitDataTypeToCdmInitDataType(
241 PP_InitDataType init_data_type) {
242 switch (init_data_type) {
243 case PP_INITDATATYPE_CENC:
244 return cdm::kCenc;
245 case PP_INITDATATYPE_KEYIDS:
246 return cdm::kKeyIds;
247 case PP_INITDATATYPE_WEBM:
248 return cdm::kWebM;
251 PP_NOTREACHED();
252 return cdm::kKeyIds;
255 PP_CdmExceptionCode CdmExceptionTypeToPpCdmExceptionType(cdm::Error error) {
256 switch (error) {
257 case cdm::kNotSupportedError:
258 return PP_CDMEXCEPTIONCODE_NOTSUPPORTEDERROR;
259 case cdm::kInvalidStateError:
260 return PP_CDMEXCEPTIONCODE_INVALIDSTATEERROR;
261 case cdm::kInvalidAccessError:
262 return PP_CDMEXCEPTIONCODE_INVALIDACCESSERROR;
263 case cdm::kQuotaExceededError:
264 return PP_CDMEXCEPTIONCODE_QUOTAEXCEEDEDERROR;
265 case cdm::kUnknownError:
266 return PP_CDMEXCEPTIONCODE_UNKNOWNERROR;
267 case cdm::kClientError:
268 return PP_CDMEXCEPTIONCODE_CLIENTERROR;
269 case cdm::kOutputError:
270 return PP_CDMEXCEPTIONCODE_OUTPUTERROR;
273 PP_NOTREACHED();
274 return PP_CDMEXCEPTIONCODE_UNKNOWNERROR;
277 PP_CdmMessageType CdmMessageTypeToPpMessageType(cdm::MessageType message) {
278 switch (message) {
279 case cdm::kLicenseRequest:
280 return PP_CDMMESSAGETYPE_LICENSE_REQUEST;
281 case cdm::kLicenseRenewal:
282 return PP_CDMMESSAGETYPE_LICENSE_RENEWAL;
283 case cdm::kLicenseRelease:
284 return PP_CDMMESSAGETYPE_LICENSE_RELEASE;
287 PP_NOTREACHED();
288 return PP_CDMMESSAGETYPE_LICENSE_REQUEST;
291 PP_CdmKeyStatus CdmKeyStatusToPpKeyStatus(cdm::KeyStatus status) {
292 switch (status) {
293 case cdm::kUsable:
294 return PP_CDMKEYSTATUS_USABLE;
295 case cdm::kInternalError:
296 return PP_CDMKEYSTATUS_INVALID;
297 case cdm::kExpired:
298 return PP_CDMKEYSTATUS_EXPIRED;
299 case cdm::kOutputNotAllowed:
300 return PP_CDMKEYSTATUS_OUTPUTNOTALLOWED;
301 case cdm::kOutputDownscaled:
302 return PP_CDMKEYSTATUS_OUTPUTDOWNSCALED;
303 case cdm::kStatusPending:
304 return PP_CDMKEYSTATUS_STATUSPENDING;
307 PP_NOTREACHED();
308 return PP_CDMKEYSTATUS_INVALID;
311 } // namespace
313 namespace media {
315 CdmAdapter::CdmAdapter(PP_Instance instance, pp::Module* module)
316 : pp::Instance(instance),
317 pp::ContentDecryptor_Private(this),
318 #if defined(OS_CHROMEOS)
319 output_protection_(this),
320 platform_verification_(this),
321 output_link_mask_(0),
322 output_protection_mask_(0),
323 query_output_protection_in_progress_(false),
324 uma_for_output_protection_query_reported_(false),
325 uma_for_output_protection_positive_result_reported_(false),
326 #endif
327 allocator_(this),
328 cdm_(NULL),
329 allow_distinctive_identifier_(false),
330 allow_persistent_state_(false),
331 deferred_initialize_audio_decoder_(false),
332 deferred_audio_decoder_config_id_(0),
333 deferred_initialize_video_decoder_(false),
334 deferred_video_decoder_config_id_(0),
335 last_read_file_size_kb_(0),
336 file_size_uma_reported_(false) {
337 callback_factory_.Initialize(this);
340 CdmAdapter::~CdmAdapter() {}
342 CdmWrapper* CdmAdapter::CreateCdmInstance(const std::string& key_system) {
343 CdmWrapper* cdm = CdmWrapper::Create(key_system.data(), key_system.size(),
344 GetCdmHost, this);
346 const std::string message = "CDM instance for " + key_system +
347 (cdm ? "" : " could not be") + " created.";
348 DLOG_TO_CONSOLE(message);
349 CDM_DLOG() << message;
351 return cdm;
354 void CdmAdapter::Initialize(uint32_t promise_id,
355 const std::string& key_system,
356 bool allow_distinctive_identifier,
357 bool allow_persistent_state) {
358 PP_DCHECK(!key_system.empty());
359 PP_DCHECK(!cdm_);
361 #if defined(CHECK_DOCUMENT_URL)
362 PP_URLComponents_Dev url_components = {};
363 const pp::URLUtil_Dev* url_util = pp::URLUtil_Dev::Get();
364 if (!url_util) {
365 RejectPromise(promise_id, cdm::kUnknownError, 0,
366 "Unable to determine origin.");
367 return;
370 pp::Var href = url_util->GetDocumentURL(pp::InstanceHandle(pp_instance()),
371 &url_components);
372 PP_DCHECK(href.is_string());
373 std::string url = href.AsString();
374 PP_DCHECK(!url.empty());
375 std::string url_scheme =
376 url.substr(url_components.scheme.begin, url_components.scheme.len);
377 if (url_scheme != "file") {
378 // Skip this check for file:// URLs as they don't have a host component.
379 PP_DCHECK(url_components.host.begin);
380 PP_DCHECK(0 < url_components.host.len);
382 #endif // defined(CHECK_DOCUMENT_URL)
384 cdm_ = make_linked_ptr(CreateCdmInstance(key_system));
385 if (!cdm_) {
386 RejectPromise(promise_id, cdm::kInvalidAccessError, 0,
387 "Unable to create CDM.");
388 return;
391 key_system_ = key_system;
392 allow_distinctive_identifier_ = allow_distinctive_identifier;
393 allow_persistent_state_ = allow_persistent_state;
394 cdm_->Initialize(allow_distinctive_identifier, allow_persistent_state);
395 OnResolvePromise(promise_id);
398 void CdmAdapter::SetServerCertificate(uint32_t promise_id,
399 pp::VarArrayBuffer server_certificate) {
400 const uint8_t* server_certificate_ptr =
401 static_cast<const uint8_t*>(server_certificate.Map());
402 const uint32_t server_certificate_size = server_certificate.ByteLength();
404 if (!server_certificate_ptr ||
405 server_certificate_size < media::limits::kMinCertificateLength ||
406 server_certificate_size > media::limits::kMaxCertificateLength) {
407 RejectPromise(
408 promise_id, cdm::kInvalidAccessError, 0, "Incorrect certificate.");
409 return;
412 cdm_->SetServerCertificate(
413 promise_id, server_certificate_ptr, server_certificate_size);
416 void CdmAdapter::CreateSessionAndGenerateRequest(uint32_t promise_id,
417 PP_SessionType session_type,
418 PP_InitDataType init_data_type,
419 pp::VarArrayBuffer init_data) {
420 cdm_->CreateSessionAndGenerateRequest(
421 promise_id, PpSessionTypeToCdmSessionType(session_type),
422 PpInitDataTypeToCdmInitDataType(init_data_type),
423 static_cast<const uint8_t*>(init_data.Map()), init_data.ByteLength());
426 void CdmAdapter::LoadSession(uint32_t promise_id,
427 PP_SessionType session_type,
428 const std::string& session_id) {
429 cdm_->LoadSession(promise_id, PpSessionTypeToCdmSessionType(session_type),
430 session_id.data(), session_id.size());
433 void CdmAdapter::UpdateSession(uint32_t promise_id,
434 const std::string& session_id,
435 pp::VarArrayBuffer response) {
436 const uint8_t* response_ptr = static_cast<const uint8_t*>(response.Map());
437 const uint32_t response_size = response.ByteLength();
439 PP_DCHECK(!session_id.empty());
440 PP_DCHECK(response_ptr);
441 PP_DCHECK(response_size > 0);
443 cdm_->UpdateSession(promise_id, session_id.data(), session_id.length(),
444 response_ptr, response_size);
447 void CdmAdapter::CloseSession(uint32_t promise_id,
448 const std::string& session_id) {
449 cdm_->CloseSession(promise_id, session_id.data(), session_id.length());
452 void CdmAdapter::RemoveSession(uint32_t promise_id,
453 const std::string& session_id) {
454 cdm_->RemoveSession(promise_id, session_id.data(), session_id.length());
457 // Note: In the following decryption/decoding related functions, errors are NOT
458 // reported via KeyError, but are reported via corresponding PPB calls.
460 void CdmAdapter::Decrypt(pp::Buffer_Dev encrypted_buffer,
461 const PP_EncryptedBlockInfo& encrypted_block_info) {
462 PP_DCHECK(!encrypted_buffer.is_null());
464 // Release a buffer that the caller indicated it is finished with.
465 allocator_.Release(encrypted_block_info.tracking_info.buffer_id);
467 cdm::Status status = cdm::kDecryptError;
468 LinkedDecryptedBlock decrypted_block(new DecryptedBlockImpl());
470 if (cdm_) {
471 cdm::InputBuffer input_buffer;
472 std::vector<cdm::SubsampleEntry> subsamples;
473 ConfigureInputBuffer(encrypted_buffer, encrypted_block_info, &subsamples,
474 &input_buffer);
475 status = cdm_->Decrypt(input_buffer, decrypted_block.get());
476 PP_DCHECK(status != cdm::kSuccess ||
477 (decrypted_block->DecryptedBuffer() &&
478 decrypted_block->DecryptedBuffer()->Size()));
481 CallOnMain(callback_factory_.NewCallback(
482 &CdmAdapter::DeliverBlock,
483 status,
484 decrypted_block,
485 encrypted_block_info.tracking_info));
488 void CdmAdapter::InitializeAudioDecoder(
489 const PP_AudioDecoderConfig& decoder_config,
490 pp::Buffer_Dev extra_data_buffer) {
491 PP_DCHECK(!deferred_initialize_audio_decoder_);
492 PP_DCHECK(deferred_audio_decoder_config_id_ == 0);
493 cdm::Status status = cdm::kSessionError;
494 if (cdm_) {
495 cdm::AudioDecoderConfig cdm_decoder_config;
496 cdm_decoder_config.codec =
497 PpAudioCodecToCdmAudioCodec(decoder_config.codec);
498 cdm_decoder_config.channel_count = decoder_config.channel_count;
499 cdm_decoder_config.bits_per_channel = decoder_config.bits_per_channel;
500 cdm_decoder_config.samples_per_second = decoder_config.samples_per_second;
501 cdm_decoder_config.extra_data =
502 static_cast<uint8_t*>(extra_data_buffer.data());
503 cdm_decoder_config.extra_data_size = extra_data_buffer.size();
504 status = cdm_->InitializeAudioDecoder(cdm_decoder_config);
507 if (status == cdm::kDeferredInitialization) {
508 deferred_initialize_audio_decoder_ = true;
509 deferred_audio_decoder_config_id_ = decoder_config.request_id;
510 return;
513 CallOnMain(callback_factory_.NewCallback(
514 &CdmAdapter::DecoderInitializeDone,
515 PP_DECRYPTORSTREAMTYPE_AUDIO,
516 decoder_config.request_id,
517 status == cdm::kSuccess));
520 void CdmAdapter::InitializeVideoDecoder(
521 const PP_VideoDecoderConfig& decoder_config,
522 pp::Buffer_Dev extra_data_buffer) {
523 PP_DCHECK(!deferred_initialize_video_decoder_);
524 PP_DCHECK(deferred_video_decoder_config_id_ == 0);
525 cdm::Status status = cdm::kSessionError;
526 if (cdm_) {
527 cdm::VideoDecoderConfig cdm_decoder_config;
528 cdm_decoder_config.codec =
529 PpVideoCodecToCdmVideoCodec(decoder_config.codec);
530 cdm_decoder_config.profile =
531 PpVCProfileToCdmVCProfile(decoder_config.profile);
532 cdm_decoder_config.format =
533 PpDecryptedFrameFormatToCdmVideoFormat(decoder_config.format);
534 cdm_decoder_config.coded_size.width = decoder_config.width;
535 cdm_decoder_config.coded_size.height = decoder_config.height;
536 cdm_decoder_config.extra_data =
537 static_cast<uint8_t*>(extra_data_buffer.data());
538 cdm_decoder_config.extra_data_size = extra_data_buffer.size();
539 status = cdm_->InitializeVideoDecoder(cdm_decoder_config);
542 if (status == cdm::kDeferredInitialization) {
543 deferred_initialize_video_decoder_ = true;
544 deferred_video_decoder_config_id_ = decoder_config.request_id;
545 return;
548 CallOnMain(callback_factory_.NewCallback(
549 &CdmAdapter::DecoderInitializeDone,
550 PP_DECRYPTORSTREAMTYPE_VIDEO,
551 decoder_config.request_id,
552 status == cdm::kSuccess));
555 void CdmAdapter::DeinitializeDecoder(PP_DecryptorStreamType decoder_type,
556 uint32_t request_id) {
557 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded.
558 if (cdm_) {
559 cdm_->DeinitializeDecoder(
560 PpDecryptorStreamTypeToCdmStreamType(decoder_type));
563 CallOnMain(callback_factory_.NewCallback(
564 &CdmAdapter::DecoderDeinitializeDone,
565 decoder_type,
566 request_id));
569 void CdmAdapter::ResetDecoder(PP_DecryptorStreamType decoder_type,
570 uint32_t request_id) {
571 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded.
572 if (cdm_)
573 cdm_->ResetDecoder(PpDecryptorStreamTypeToCdmStreamType(decoder_type));
575 CallOnMain(callback_factory_.NewCallback(&CdmAdapter::DecoderResetDone,
576 decoder_type,
577 request_id));
580 void CdmAdapter::DecryptAndDecode(
581 PP_DecryptorStreamType decoder_type,
582 pp::Buffer_Dev encrypted_buffer,
583 const PP_EncryptedBlockInfo& encrypted_block_info) {
584 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded.
585 // Release a buffer that the caller indicated it is finished with.
586 allocator_.Release(encrypted_block_info.tracking_info.buffer_id);
588 cdm::InputBuffer input_buffer;
589 std::vector<cdm::SubsampleEntry> subsamples;
590 if (cdm_ && !encrypted_buffer.is_null()) {
591 ConfigureInputBuffer(encrypted_buffer,
592 encrypted_block_info,
593 &subsamples,
594 &input_buffer);
597 cdm::Status status = cdm::kDecodeError;
599 switch (decoder_type) {
600 case PP_DECRYPTORSTREAMTYPE_VIDEO: {
601 LinkedVideoFrame video_frame(new VideoFrameImpl());
602 if (cdm_)
603 status = cdm_->DecryptAndDecodeFrame(input_buffer, video_frame.get());
604 CallOnMain(callback_factory_.NewCallback(
605 &CdmAdapter::DeliverFrame,
606 status,
607 video_frame,
608 encrypted_block_info.tracking_info));
609 return;
612 case PP_DECRYPTORSTREAMTYPE_AUDIO: {
613 LinkedAudioFrames audio_frames(new AudioFramesImpl());
614 if (cdm_) {
615 status = cdm_->DecryptAndDecodeSamples(input_buffer,
616 audio_frames.get());
618 CallOnMain(callback_factory_.NewCallback(
619 &CdmAdapter::DeliverSamples,
620 status,
621 audio_frames,
622 encrypted_block_info.tracking_info));
623 return;
626 default:
627 PP_NOTREACHED();
628 return;
632 cdm::Buffer* CdmAdapter::Allocate(uint32_t capacity) {
633 return allocator_.Allocate(capacity);
636 void CdmAdapter::SetTimer(int64_t delay_ms, void* context) {
637 // NOTE: doesn't really need to run on the main thread; could just as well run
638 // on a helper thread if |cdm_| were thread-friendly and care was taken. We
639 // only use CallOnMainThread() here to get delayed-execution behavior.
640 pp::Module::Get()->core()->CallOnMainThread(
641 delay_ms,
642 callback_factory_.NewCallback(&CdmAdapter::TimerExpired, context),
643 PP_OK);
646 void CdmAdapter::TimerExpired(int32_t result, void* context) {
647 PP_DCHECK(result == PP_OK);
648 cdm_->TimerExpired(context);
651 cdm::Time CdmAdapter::GetCurrentWallTime() {
652 return pp::Module::Get()->core()->GetTime();
655 void CdmAdapter::OnResolveNewSessionPromise(uint32_t promise_id,
656 const char* session_id,
657 uint32_t session_id_size) {
658 PostOnMain(callback_factory_.NewCallback(
659 &CdmAdapter::SendPromiseResolvedWithSessionInternal, promise_id,
660 std::string(session_id, session_id_size)));
663 void CdmAdapter::OnResolvePromise(uint32_t promise_id) {
664 PostOnMain(callback_factory_.NewCallback(
665 &CdmAdapter::SendPromiseResolvedInternal, promise_id));
668 void CdmAdapter::OnRejectPromise(uint32_t promise_id,
669 cdm::Error error,
670 uint32_t system_code,
671 const char* error_message,
672 uint32_t error_message_size) {
673 // UMA to investigate http://crbug.com/410630
674 // TODO(xhwang): Remove after bug is fixed.
675 if (system_code == 0x27) {
676 pp::UMAPrivate uma_interface(this);
677 uma_interface.HistogramCustomCounts("Media.EME.CdmFileIO.FileSizeKBOnError",
678 last_read_file_size_kb_,
679 kSizeKBMin,
680 kSizeKBMax,
681 kSizeKBBuckets);
684 RejectPromise(promise_id, error, system_code,
685 std::string(error_message, error_message_size));
688 void CdmAdapter::RejectPromise(uint32_t promise_id,
689 cdm::Error error,
690 uint32_t system_code,
691 const std::string& error_message) {
692 PostOnMain(callback_factory_.NewCallback(
693 &CdmAdapter::SendPromiseRejectedInternal,
694 promise_id,
695 SessionError(error, system_code, error_message)));
698 void CdmAdapter::OnSessionMessage(const char* session_id,
699 uint32_t session_id_size,
700 cdm::MessageType message_type,
701 const char* message,
702 uint32_t message_size,
703 const char* legacy_destination_url,
704 uint32_t legacy_destination_url_size) {
705 // License requests should not specify |legacy_destination_url|.
706 // |legacy_destination_url| is not passed to unprefixed EME applications,
707 // so it can be removed when the prefixed API is removed.
708 PP_DCHECK(legacy_destination_url_size == 0 ||
709 message_type != cdm::MessageType::kLicenseRequest);
711 PostOnMain(callback_factory_.NewCallback(
712 &CdmAdapter::SendSessionMessageInternal,
713 SessionMessage(
714 std::string(session_id, session_id_size), message_type, message,
715 message_size,
716 std::string(legacy_destination_url, legacy_destination_url_size))));
719 void CdmAdapter::OnSessionKeysChange(const char* session_id,
720 uint32_t session_id_size,
721 bool has_additional_usable_key,
722 const cdm::KeyInformation* keys_info,
723 uint32_t keys_info_count) {
724 std::vector<PP_KeyInformation> key_information;
725 for (uint32_t i = 0; i < keys_info_count; ++i) {
726 const auto& key_info = keys_info[i];
727 PP_KeyInformation next_key = {};
729 if (key_info.key_id_size > sizeof(next_key.key_id)) {
730 PP_NOTREACHED();
731 continue;
734 // Copy key_id into |next_key|.
735 memcpy(next_key.key_id, key_info.key_id, key_info.key_id_size);
737 // Set remaining fields on |next_key|.
738 next_key.key_id_size = key_info.key_id_size;
739 next_key.key_status = CdmKeyStatusToPpKeyStatus(key_info.status);
740 next_key.system_code = key_info.system_code;
741 key_information.push_back(next_key);
744 PostOnMain(callback_factory_.NewCallback(
745 &CdmAdapter::SendSessionKeysChangeInternal,
746 std::string(session_id, session_id_size), has_additional_usable_key,
747 key_information));
750 void CdmAdapter::OnExpirationChange(const char* session_id,
751 uint32_t session_id_size,
752 cdm::Time new_expiry_time) {
753 PostOnMain(callback_factory_.NewCallback(
754 &CdmAdapter::SendExpirationChangeInternal,
755 std::string(session_id, session_id_size), new_expiry_time));
758 void CdmAdapter::OnSessionClosed(const char* session_id,
759 uint32_t session_id_size) {
760 PostOnMain(
761 callback_factory_.NewCallback(&CdmAdapter::SendSessionClosedInternal,
762 std::string(session_id, session_id_size)));
765 void CdmAdapter::OnLegacySessionError(const char* session_id,
766 uint32_t session_id_size,
767 cdm::Error error,
768 uint32_t system_code,
769 const char* error_message,
770 uint32_t error_message_size) {
771 PostOnMain(callback_factory_.NewCallback(
772 &CdmAdapter::SendSessionErrorInternal,
773 std::string(session_id, session_id_size),
774 SessionError(error, system_code,
775 std::string(error_message, error_message_size))));
778 // Helpers to pass the event to Pepper.
780 void CdmAdapter::SendPromiseResolvedInternal(int32_t result,
781 uint32_t promise_id) {
782 PP_DCHECK(result == PP_OK);
783 pp::ContentDecryptor_Private::PromiseResolved(promise_id);
786 void CdmAdapter::SendPromiseResolvedWithSessionInternal(
787 int32_t result,
788 uint32_t promise_id,
789 const std::string& session_id) {
790 PP_DCHECK(result == PP_OK);
791 pp::ContentDecryptor_Private::PromiseResolvedWithSession(promise_id,
792 session_id);
795 void CdmAdapter::SendPromiseRejectedInternal(int32_t result,
796 uint32_t promise_id,
797 const SessionError& error) {
798 PP_DCHECK(result == PP_OK);
799 pp::ContentDecryptor_Private::PromiseRejected(
800 promise_id,
801 CdmExceptionTypeToPpCdmExceptionType(error.error),
802 error.system_code,
803 error.error_description);
806 void CdmAdapter::SendSessionMessageInternal(int32_t result,
807 const SessionMessage& message) {
808 PP_DCHECK(result == PP_OK);
810 pp::VarArrayBuffer message_array_buffer(message.message.size());
811 if (message.message.size() > 0) {
812 memcpy(message_array_buffer.Map(), message.message.data(),
813 message.message.size());
816 pp::ContentDecryptor_Private::SessionMessage(
817 message.session_id, CdmMessageTypeToPpMessageType(message.message_type),
818 message_array_buffer, message.legacy_destination_url);
821 void CdmAdapter::SendSessionClosedInternal(int32_t result,
822 const std::string& session_id) {
823 PP_DCHECK(result == PP_OK);
824 pp::ContentDecryptor_Private::SessionClosed(session_id);
827 void CdmAdapter::SendSessionErrorInternal(int32_t result,
828 const std::string& session_id,
829 const SessionError& error) {
830 PP_DCHECK(result == PP_OK);
831 pp::ContentDecryptor_Private::LegacySessionError(
832 session_id, CdmExceptionTypeToPpCdmExceptionType(error.error),
833 error.system_code, error.error_description);
836 void CdmAdapter::SendSessionKeysChangeInternal(
837 int32_t result,
838 const std::string& session_id,
839 bool has_additional_usable_key,
840 const std::vector<PP_KeyInformation>& key_info) {
841 PP_DCHECK(result == PP_OK);
842 pp::ContentDecryptor_Private::SessionKeysChange(
843 session_id, has_additional_usable_key, key_info);
846 void CdmAdapter::SendExpirationChangeInternal(int32_t result,
847 const std::string& session_id,
848 cdm::Time new_expiry_time) {
849 PP_DCHECK(result == PP_OK);
850 pp::ContentDecryptor_Private::SessionExpirationChange(session_id,
851 new_expiry_time);
854 void CdmAdapter::DeliverBlock(int32_t result,
855 const cdm::Status& status,
856 const LinkedDecryptedBlock& decrypted_block,
857 const PP_DecryptTrackingInfo& tracking_info) {
858 PP_DCHECK(result == PP_OK);
859 PP_DecryptedBlockInfo decrypted_block_info = {};
860 decrypted_block_info.tracking_info = tracking_info;
861 decrypted_block_info.tracking_info.timestamp = decrypted_block->Timestamp();
862 decrypted_block_info.tracking_info.buffer_id = 0;
863 decrypted_block_info.data_size = 0;
864 decrypted_block_info.result = CdmStatusToPpDecryptResult(status);
866 pp::Buffer_Dev buffer;
868 if (decrypted_block_info.result == PP_DECRYPTRESULT_SUCCESS) {
869 PP_DCHECK(decrypted_block.get() && decrypted_block->DecryptedBuffer());
870 if (!decrypted_block.get() || !decrypted_block->DecryptedBuffer()) {
871 PP_NOTREACHED();
872 decrypted_block_info.result = PP_DECRYPTRESULT_DECRYPT_ERROR;
873 } else {
874 PpbBuffer* ppb_buffer =
875 static_cast<PpbBuffer*>(decrypted_block->DecryptedBuffer());
876 decrypted_block_info.tracking_info.buffer_id = ppb_buffer->buffer_id();
877 decrypted_block_info.data_size = ppb_buffer->Size();
879 buffer = ppb_buffer->TakeBuffer();
883 pp::ContentDecryptor_Private::DeliverBlock(buffer, decrypted_block_info);
886 void CdmAdapter::DecoderInitializeDone(int32_t result,
887 PP_DecryptorStreamType decoder_type,
888 uint32_t request_id,
889 bool success) {
890 PP_DCHECK(result == PP_OK);
891 pp::ContentDecryptor_Private::DecoderInitializeDone(decoder_type,
892 request_id,
893 success);
896 void CdmAdapter::DecoderDeinitializeDone(int32_t result,
897 PP_DecryptorStreamType decoder_type,
898 uint32_t request_id) {
899 pp::ContentDecryptor_Private::DecoderDeinitializeDone(decoder_type,
900 request_id);
903 void CdmAdapter::DecoderResetDone(int32_t result,
904 PP_DecryptorStreamType decoder_type,
905 uint32_t request_id) {
906 pp::ContentDecryptor_Private::DecoderResetDone(decoder_type, request_id);
909 void CdmAdapter::DeliverFrame(
910 int32_t result,
911 const cdm::Status& status,
912 const LinkedVideoFrame& video_frame,
913 const PP_DecryptTrackingInfo& tracking_info) {
914 PP_DCHECK(result == PP_OK);
915 PP_DecryptedFrameInfo decrypted_frame_info = {};
916 decrypted_frame_info.tracking_info.request_id = tracking_info.request_id;
917 decrypted_frame_info.tracking_info.buffer_id = 0;
918 decrypted_frame_info.result = CdmStatusToPpDecryptResult(status);
920 pp::Buffer_Dev buffer;
922 if (decrypted_frame_info.result == PP_DECRYPTRESULT_SUCCESS) {
923 if (!IsValidVideoFrame(video_frame)) {
924 PP_NOTREACHED();
925 decrypted_frame_info.result = PP_DECRYPTRESULT_DECODE_ERROR;
926 } else {
927 PpbBuffer* ppb_buffer =
928 static_cast<PpbBuffer*>(video_frame->FrameBuffer());
930 decrypted_frame_info.tracking_info.timestamp = video_frame->Timestamp();
931 decrypted_frame_info.tracking_info.buffer_id = ppb_buffer->buffer_id();
932 decrypted_frame_info.format =
933 CdmVideoFormatToPpDecryptedFrameFormat(video_frame->Format());
934 decrypted_frame_info.width = video_frame->Size().width;
935 decrypted_frame_info.height = video_frame->Size().height;
936 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_Y] =
937 video_frame->PlaneOffset(cdm::VideoFrame::kYPlane);
938 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_U] =
939 video_frame->PlaneOffset(cdm::VideoFrame::kUPlane);
940 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_V] =
941 video_frame->PlaneOffset(cdm::VideoFrame::kVPlane);
942 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_Y] =
943 video_frame->Stride(cdm::VideoFrame::kYPlane);
944 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_U] =
945 video_frame->Stride(cdm::VideoFrame::kUPlane);
946 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_V] =
947 video_frame->Stride(cdm::VideoFrame::kVPlane);
949 buffer = ppb_buffer->TakeBuffer();
953 pp::ContentDecryptor_Private::DeliverFrame(buffer, decrypted_frame_info);
956 void CdmAdapter::DeliverSamples(int32_t result,
957 const cdm::Status& status,
958 const LinkedAudioFrames& audio_frames,
959 const PP_DecryptTrackingInfo& tracking_info) {
960 PP_DCHECK(result == PP_OK);
962 PP_DecryptedSampleInfo decrypted_sample_info = {};
963 decrypted_sample_info.tracking_info = tracking_info;
964 decrypted_sample_info.tracking_info.timestamp = 0;
965 decrypted_sample_info.tracking_info.buffer_id = 0;
966 decrypted_sample_info.data_size = 0;
967 decrypted_sample_info.result = CdmStatusToPpDecryptResult(status);
969 pp::Buffer_Dev buffer;
971 if (decrypted_sample_info.result == PP_DECRYPTRESULT_SUCCESS) {
972 PP_DCHECK(audio_frames.get() && audio_frames->FrameBuffer());
973 if (!audio_frames.get() || !audio_frames->FrameBuffer()) {
974 PP_NOTREACHED();
975 decrypted_sample_info.result = PP_DECRYPTRESULT_DECRYPT_ERROR;
976 } else {
977 PpbBuffer* ppb_buffer =
978 static_cast<PpbBuffer*>(audio_frames->FrameBuffer());
980 decrypted_sample_info.tracking_info.buffer_id = ppb_buffer->buffer_id();
981 decrypted_sample_info.data_size = ppb_buffer->Size();
982 decrypted_sample_info.format =
983 CdmAudioFormatToPpDecryptedSampleFormat(audio_frames->Format());
985 buffer = ppb_buffer->TakeBuffer();
989 pp::ContentDecryptor_Private::DeliverSamples(buffer, decrypted_sample_info);
992 bool CdmAdapter::IsValidVideoFrame(const LinkedVideoFrame& video_frame) {
993 if (!video_frame.get() ||
994 !video_frame->FrameBuffer() ||
995 (video_frame->Format() != cdm::kI420 &&
996 video_frame->Format() != cdm::kYv12)) {
997 CDM_DLOG() << "Invalid video frame!";
998 return false;
1001 PpbBuffer* ppb_buffer = static_cast<PpbBuffer*>(video_frame->FrameBuffer());
1003 for (uint32_t i = 0; i < cdm::VideoFrame::kMaxPlanes; ++i) {
1004 int plane_height = (i == cdm::VideoFrame::kYPlane) ?
1005 video_frame->Size().height : (video_frame->Size().height + 1) / 2;
1006 cdm::VideoFrame::VideoPlane plane =
1007 static_cast<cdm::VideoFrame::VideoPlane>(i);
1008 if (ppb_buffer->Size() < video_frame->PlaneOffset(plane) +
1009 plane_height * video_frame->Stride(plane)) {
1010 return false;
1014 return true;
1017 void CdmAdapter::OnFirstFileRead(int32_t file_size_bytes) {
1018 PP_DCHECK(IsMainThread());
1019 PP_DCHECK(file_size_bytes >= 0);
1021 last_read_file_size_kb_ = file_size_bytes / 1024;
1023 if (file_size_uma_reported_)
1024 return;
1026 pp::UMAPrivate uma_interface(this);
1027 uma_interface.HistogramCustomCounts(
1028 "Media.EME.CdmFileIO.FileSizeKBOnFirstRead",
1029 last_read_file_size_kb_,
1030 kSizeKBMin,
1031 kSizeKBMax,
1032 kSizeKBBuckets);
1033 file_size_uma_reported_ = true;
1036 #if !defined(NDEBUG)
1037 void CdmAdapter::LogToConsole(const pp::Var& value) {
1038 PP_DCHECK(IsMainThread());
1039 const PPB_Console* console = reinterpret_cast<const PPB_Console*>(
1040 pp::Module::Get()->GetBrowserInterface(PPB_CONSOLE_INTERFACE));
1041 console->Log(pp_instance(), PP_LOGLEVEL_LOG, value.pp_var());
1043 #endif // !defined(NDEBUG)
1045 void CdmAdapter::SendPlatformChallenge(const char* service_id,
1046 uint32_t service_id_size,
1047 const char* challenge,
1048 uint32_t challenge_size) {
1049 #if defined(OS_CHROMEOS)
1050 // If access to a distinctive identifier is not allowed, block platform
1051 // verification to prevent access to such an identifier.
1052 if (allow_distinctive_identifier_) {
1053 pp::VarArrayBuffer challenge_var(challenge_size);
1054 uint8_t* var_data = static_cast<uint8_t*>(challenge_var.Map());
1055 memcpy(var_data, challenge, challenge_size);
1057 std::string service_id_str(service_id, service_id_size);
1059 linked_ptr<PepperPlatformChallengeResponse> response(
1060 new PepperPlatformChallengeResponse());
1062 int32_t result = platform_verification_.ChallengePlatform(
1063 pp::Var(service_id_str),
1064 challenge_var,
1065 &response->signed_data,
1066 &response->signed_data_signature,
1067 &response->platform_key_certificate,
1068 callback_factory_.NewCallback(&CdmAdapter::SendPlatformChallengeDone,
1069 response));
1070 challenge_var.Unmap();
1071 if (result == PP_OK_COMPLETIONPENDING)
1072 return;
1074 // Fall through on error and issue an empty OnPlatformChallengeResponse().
1075 PP_DCHECK(result != PP_OK);
1077 #endif
1079 cdm::PlatformChallengeResponse platform_challenge_response = {};
1080 cdm_->OnPlatformChallengeResponse(platform_challenge_response);
1083 void CdmAdapter::EnableOutputProtection(uint32_t desired_protection_mask) {
1084 #if defined(OS_CHROMEOS)
1085 int32_t result = output_protection_.EnableProtection(
1086 desired_protection_mask, callback_factory_.NewCallback(
1087 &CdmAdapter::EnableProtectionDone));
1089 // Errors are ignored since clients must call QueryOutputProtectionStatus() to
1090 // inspect the protection status on a regular basis.
1092 if (result != PP_OK && result != PP_OK_COMPLETIONPENDING)
1093 CDM_DLOG() << __FUNCTION__ << " failed!";
1094 #endif
1097 void CdmAdapter::QueryOutputProtectionStatus() {
1098 #if defined(OS_CHROMEOS)
1099 PP_DCHECK(!query_output_protection_in_progress_);
1101 output_link_mask_ = output_protection_mask_ = 0;
1102 const int32_t result = output_protection_.QueryStatus(
1103 &output_link_mask_,
1104 &output_protection_mask_,
1105 callback_factory_.NewCallback(
1106 &CdmAdapter::QueryOutputProtectionStatusDone));
1107 if (result == PP_OK_COMPLETIONPENDING) {
1108 query_output_protection_in_progress_ = true;
1109 ReportOutputProtectionQuery();
1110 return;
1113 // Fall through on error and issue an empty OnQueryOutputProtectionStatus().
1114 PP_DCHECK(result != PP_OK);
1115 CDM_DLOG() << __FUNCTION__ << " failed, result = " << result;
1116 #endif
1117 cdm_->OnQueryOutputProtectionStatus(cdm::kQueryFailed, 0, 0);
1120 void CdmAdapter::OnDeferredInitializationDone(cdm::StreamType stream_type,
1121 cdm::Status decoder_status) {
1122 switch (stream_type) {
1123 case cdm::kStreamTypeAudio:
1124 PP_DCHECK(deferred_initialize_audio_decoder_);
1125 CallOnMain(
1126 callback_factory_.NewCallback(&CdmAdapter::DecoderInitializeDone,
1127 PP_DECRYPTORSTREAMTYPE_AUDIO,
1128 deferred_audio_decoder_config_id_,
1129 decoder_status == cdm::kSuccess));
1130 deferred_initialize_audio_decoder_ = false;
1131 deferred_audio_decoder_config_id_ = 0;
1132 break;
1133 case cdm::kStreamTypeVideo:
1134 PP_DCHECK(deferred_initialize_video_decoder_);
1135 CallOnMain(
1136 callback_factory_.NewCallback(&CdmAdapter::DecoderInitializeDone,
1137 PP_DECRYPTORSTREAMTYPE_VIDEO,
1138 deferred_video_decoder_config_id_,
1139 decoder_status == cdm::kSuccess));
1140 deferred_initialize_video_decoder_ = false;
1141 deferred_video_decoder_config_id_ = 0;
1142 break;
1146 // The CDM owns the returned object and must call FileIO::Close() to release it.
1147 cdm::FileIO* CdmAdapter::CreateFileIO(cdm::FileIOClient* client) {
1148 if (!allow_persistent_state_) {
1149 CDM_DLOG()
1150 << "Cannot create FileIO because persistent state is not allowed.";
1151 return nullptr;
1154 return new CdmFileIOImpl(
1155 client, pp_instance(),
1156 callback_factory_.NewCallback(&CdmAdapter::OnFirstFileRead));
1159 #if defined(OS_CHROMEOS)
1160 void CdmAdapter::ReportOutputProtectionUMA(OutputProtectionStatus status) {
1161 pp::UMAPrivate uma_interface(this);
1162 uma_interface.HistogramEnumeration(
1163 "Media.EME.OutputProtection", status, OUTPUT_PROTECTION_MAX);
1166 void CdmAdapter::ReportOutputProtectionQuery() {
1167 if (uma_for_output_protection_query_reported_)
1168 return;
1170 ReportOutputProtectionUMA(OUTPUT_PROTECTION_QUERIED);
1171 uma_for_output_protection_query_reported_ = true;
1174 void CdmAdapter::ReportOutputProtectionQueryResult() {
1175 if (uma_for_output_protection_positive_result_reported_)
1176 return;
1178 // Report UMAs for output protection query result.
1179 uint32_t external_links = (output_link_mask_ & ~cdm::kLinkTypeInternal);
1181 if (!external_links) {
1182 ReportOutputProtectionUMA(OUTPUT_PROTECTION_NO_EXTERNAL_LINK);
1183 uma_for_output_protection_positive_result_reported_ = true;
1184 return;
1187 const uint32_t kProtectableLinks =
1188 cdm::kLinkTypeHDMI | cdm::kLinkTypeDVI | cdm::kLinkTypeDisplayPort;
1189 bool is_unprotectable_link_connected = external_links & ~kProtectableLinks;
1190 bool is_hdcp_enabled_on_all_protectable_links =
1191 output_protection_mask_ & cdm::kProtectionHDCP;
1193 if (!is_unprotectable_link_connected &&
1194 is_hdcp_enabled_on_all_protectable_links) {
1195 ReportOutputProtectionUMA(
1196 OUTPUT_PROTECTION_ALL_EXTERNAL_LINKS_PROTECTED);
1197 uma_for_output_protection_positive_result_reported_ = true;
1198 return;
1201 // Do not report a negative result because it could be a false negative.
1202 // Instead, we will calculate number of negatives using the total number of
1203 // queries and success results.
1206 void CdmAdapter::SendPlatformChallengeDone(
1207 int32_t result,
1208 const linked_ptr<PepperPlatformChallengeResponse>& response) {
1209 if (result != PP_OK) {
1210 CDM_DLOG() << __FUNCTION__ << ": Platform challenge failed!";
1211 cdm::PlatformChallengeResponse platform_challenge_response = {};
1212 cdm_->OnPlatformChallengeResponse(platform_challenge_response);
1213 return;
1216 pp::VarArrayBuffer signed_data_var(response->signed_data);
1217 pp::VarArrayBuffer signed_data_signature_var(response->signed_data_signature);
1218 std::string platform_key_certificate_string =
1219 response->platform_key_certificate.AsString();
1221 cdm::PlatformChallengeResponse platform_challenge_response = {
1222 static_cast<uint8_t*>(signed_data_var.Map()),
1223 signed_data_var.ByteLength(),
1224 static_cast<uint8_t*>(signed_data_signature_var.Map()),
1225 signed_data_signature_var.ByteLength(),
1226 reinterpret_cast<const uint8_t*>(platform_key_certificate_string.data()),
1227 static_cast<uint32_t>(platform_key_certificate_string.length())};
1228 cdm_->OnPlatformChallengeResponse(platform_challenge_response);
1230 signed_data_var.Unmap();
1231 signed_data_signature_var.Unmap();
1234 void CdmAdapter::EnableProtectionDone(int32_t result) {
1235 // Does nothing since clients must call QueryOutputProtectionStatus() to
1236 // inspect the protection status on a regular basis.
1237 CDM_DLOG() << __FUNCTION__ << " : " << result;
1240 void CdmAdapter::QueryOutputProtectionStatusDone(int32_t result) {
1241 PP_DCHECK(query_output_protection_in_progress_);
1242 query_output_protection_in_progress_ = false;
1244 // Return a query status of failed on error.
1245 cdm::QueryResult query_result;
1246 if (result != PP_OK) {
1247 CDM_DLOG() << __FUNCTION__ << " failed, result = " << result;
1248 output_link_mask_ = output_protection_mask_ = 0;
1249 query_result = cdm::kQueryFailed;
1250 } else {
1251 query_result = cdm::kQuerySucceeded;
1252 ReportOutputProtectionQueryResult();
1255 cdm_->OnQueryOutputProtectionStatus(query_result, output_link_mask_,
1256 output_protection_mask_);
1258 #endif
1260 CdmAdapter::SessionError::SessionError(cdm::Error error,
1261 uint32_t system_code,
1262 const std::string& error_description)
1263 : error(error),
1264 system_code(system_code),
1265 error_description(error_description) {
1268 CdmAdapter::SessionMessage::SessionMessage(
1269 const std::string& session_id,
1270 cdm::MessageType message_type,
1271 const char* message,
1272 uint32_t message_size,
1273 const std::string& legacy_destination_url)
1274 : session_id(session_id),
1275 message_type(message_type),
1276 message(message, message + message_size),
1277 legacy_destination_url(legacy_destination_url) {
1280 void* GetCdmHost(int host_interface_version, void* user_data) {
1281 if (!host_interface_version || !user_data)
1282 return NULL;
1284 static_assert(
1285 cdm::ContentDecryptionModule::Host::kVersion == cdm::Host_8::kVersion,
1286 "update the code below");
1288 // Ensure IsSupportedCdmHostVersion matches implementation of this function.
1289 // Always update this DCHECK when updating this function.
1290 // If this check fails, update this function and DCHECK or update
1291 // IsSupportedCdmHostVersion.
1293 PP_DCHECK(
1294 // Future version is not supported.
1295 !IsSupportedCdmHostVersion(cdm::Host_8::kVersion + 1) &&
1296 // Current version is supported.
1297 IsSupportedCdmHostVersion(cdm::Host_8::kVersion) &&
1298 // Include all previous supported versions (if any) here.
1299 IsSupportedCdmHostVersion(cdm::Host_7::kVersion) &&
1300 // One older than the oldest supported version is not supported.
1301 !IsSupportedCdmHostVersion(cdm::Host_7::kVersion - 1));
1302 PP_DCHECK(IsSupportedCdmHostVersion(host_interface_version));
1304 CdmAdapter* cdm_adapter = static_cast<CdmAdapter*>(user_data);
1305 CDM_DLOG() << "Create CDM Host with version " << host_interface_version;
1306 switch (host_interface_version) {
1307 case cdm::Host_8::kVersion:
1308 return static_cast<cdm::Host_8*>(cdm_adapter);
1309 case cdm::Host_7::kVersion:
1310 return static_cast<cdm::Host_7*>(cdm_adapter);
1311 default:
1312 PP_NOTREACHED();
1313 return NULL;
1317 // This object is the global object representing this plugin library as long
1318 // as it is loaded.
1319 class CdmAdapterModule : public pp::Module {
1320 public:
1321 CdmAdapterModule() : pp::Module() {
1322 // This function blocks the renderer thread (PluginInstance::Initialize()).
1323 // Move this call to other places if this may be a concern in the future.
1324 INITIALIZE_CDM_MODULE();
1326 virtual ~CdmAdapterModule() {
1327 DeinitializeCdmModule();
1330 virtual pp::Instance* CreateInstance(PP_Instance instance) {
1331 return new CdmAdapter(instance, this);
1334 private:
1335 CdmFileIOImpl::ResourceTracker cdm_file_io_impl_resource_tracker;
1338 } // namespace media
1340 namespace pp {
1342 // Factory function for your specialization of the Module object.
1343 Module* CreateModule() {
1344 return new media::CdmAdapterModule();
1347 } // namespace pp