Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / media / cdm / ppapi / cdm_adapter.cc
blob092ab5443eecd0ad61567a98192ee93574fa9cc0
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 // TODO(jrummell): Remove kOutputNotAllowed, add kOutputRestricted to CDM
293 // interface. http://crbug.com/507791.
294 switch (status) {
295 case cdm::kUsable:
296 return PP_CDMKEYSTATUS_USABLE;
297 case cdm::kInternalError:
298 return PP_CDMKEYSTATUS_INVALID;
299 case cdm::kExpired:
300 return PP_CDMKEYSTATUS_EXPIRED;
301 case cdm::kOutputNotAllowed:
302 return PP_CDMKEYSTATUS_OUTPUTRESTRICTED;
303 case cdm::kOutputDownscaled:
304 return PP_CDMKEYSTATUS_OUTPUTDOWNSCALED;
305 case cdm::kStatusPending:
306 return PP_CDMKEYSTATUS_STATUSPENDING;
309 PP_NOTREACHED();
310 return PP_CDMKEYSTATUS_INVALID;
313 } // namespace
315 namespace media {
317 CdmAdapter::CdmAdapter(PP_Instance instance, pp::Module* module)
318 : pp::Instance(instance),
319 pp::ContentDecryptor_Private(this),
320 #if defined(OS_CHROMEOS)
321 output_protection_(this),
322 platform_verification_(this),
323 output_link_mask_(0),
324 output_protection_mask_(0),
325 query_output_protection_in_progress_(false),
326 uma_for_output_protection_query_reported_(false),
327 uma_for_output_protection_positive_result_reported_(false),
328 #endif
329 allocator_(this),
330 cdm_(NULL),
331 allow_distinctive_identifier_(false),
332 allow_persistent_state_(false),
333 deferred_initialize_audio_decoder_(false),
334 deferred_audio_decoder_config_id_(0),
335 deferred_initialize_video_decoder_(false),
336 deferred_video_decoder_config_id_(0),
337 last_read_file_size_kb_(0),
338 file_size_uma_reported_(false) {
339 callback_factory_.Initialize(this);
342 CdmAdapter::~CdmAdapter() {}
344 CdmWrapper* CdmAdapter::CreateCdmInstance(const std::string& key_system) {
345 CdmWrapper* cdm = CdmWrapper::Create(key_system.data(), key_system.size(),
346 GetCdmHost, this);
348 const std::string message = "CDM instance for " + key_system +
349 (cdm ? "" : " could not be") + " created.";
350 DLOG_TO_CONSOLE(message);
351 CDM_DLOG() << message;
353 return cdm;
356 void CdmAdapter::Initialize(uint32_t promise_id,
357 const std::string& key_system,
358 bool allow_distinctive_identifier,
359 bool allow_persistent_state) {
360 PP_DCHECK(!key_system.empty());
361 PP_DCHECK(!cdm_);
363 #if defined(CHECK_DOCUMENT_URL)
364 PP_URLComponents_Dev url_components = {};
365 const pp::URLUtil_Dev* url_util = pp::URLUtil_Dev::Get();
366 if (!url_util) {
367 RejectPromise(promise_id, cdm::kUnknownError, 0,
368 "Unable to determine origin.");
369 return;
372 pp::Var href = url_util->GetDocumentURL(pp::InstanceHandle(pp_instance()),
373 &url_components);
374 PP_DCHECK(href.is_string());
375 std::string url = href.AsString();
376 PP_DCHECK(!url.empty());
377 std::string url_scheme =
378 url.substr(url_components.scheme.begin, url_components.scheme.len);
379 if (url_scheme != "file") {
380 // Skip this check for file:// URLs as they don't have a host component.
381 PP_DCHECK(url_components.host.begin);
382 PP_DCHECK(0 < url_components.host.len);
384 #endif // defined(CHECK_DOCUMENT_URL)
386 cdm_ = make_linked_ptr(CreateCdmInstance(key_system));
387 if (!cdm_) {
388 RejectPromise(promise_id, cdm::kInvalidAccessError, 0,
389 "Unable to create CDM.");
390 return;
393 key_system_ = key_system;
394 allow_distinctive_identifier_ = allow_distinctive_identifier;
395 allow_persistent_state_ = allow_persistent_state;
396 cdm_->Initialize(allow_distinctive_identifier, allow_persistent_state);
397 OnResolvePromise(promise_id);
400 void CdmAdapter::SetServerCertificate(uint32_t promise_id,
401 pp::VarArrayBuffer server_certificate) {
402 const uint8_t* server_certificate_ptr =
403 static_cast<const uint8_t*>(server_certificate.Map());
404 const uint32_t server_certificate_size = server_certificate.ByteLength();
406 if (!server_certificate_ptr ||
407 server_certificate_size < media::limits::kMinCertificateLength ||
408 server_certificate_size > media::limits::kMaxCertificateLength) {
409 RejectPromise(
410 promise_id, cdm::kInvalidAccessError, 0, "Incorrect certificate.");
411 return;
414 cdm_->SetServerCertificate(
415 promise_id, server_certificate_ptr, server_certificate_size);
418 void CdmAdapter::CreateSessionAndGenerateRequest(uint32_t promise_id,
419 PP_SessionType session_type,
420 PP_InitDataType init_data_type,
421 pp::VarArrayBuffer init_data) {
422 cdm_->CreateSessionAndGenerateRequest(
423 promise_id, PpSessionTypeToCdmSessionType(session_type),
424 PpInitDataTypeToCdmInitDataType(init_data_type),
425 static_cast<const uint8_t*>(init_data.Map()), init_data.ByteLength());
428 void CdmAdapter::LoadSession(uint32_t promise_id,
429 PP_SessionType session_type,
430 const std::string& session_id) {
431 cdm_->LoadSession(promise_id, PpSessionTypeToCdmSessionType(session_type),
432 session_id.data(), session_id.size());
435 void CdmAdapter::UpdateSession(uint32_t promise_id,
436 const std::string& session_id,
437 pp::VarArrayBuffer response) {
438 const uint8_t* response_ptr = static_cast<const uint8_t*>(response.Map());
439 const uint32_t response_size = response.ByteLength();
441 PP_DCHECK(!session_id.empty());
442 PP_DCHECK(response_ptr);
443 PP_DCHECK(response_size > 0);
445 cdm_->UpdateSession(promise_id, session_id.data(), session_id.length(),
446 response_ptr, response_size);
449 void CdmAdapter::CloseSession(uint32_t promise_id,
450 const std::string& session_id) {
451 cdm_->CloseSession(promise_id, session_id.data(), session_id.length());
454 void CdmAdapter::RemoveSession(uint32_t promise_id,
455 const std::string& session_id) {
456 cdm_->RemoveSession(promise_id, session_id.data(), session_id.length());
459 // Note: In the following decryption/decoding related functions, errors are NOT
460 // reported via KeyError, but are reported via corresponding PPB calls.
462 void CdmAdapter::Decrypt(pp::Buffer_Dev encrypted_buffer,
463 const PP_EncryptedBlockInfo& encrypted_block_info) {
464 PP_DCHECK(!encrypted_buffer.is_null());
466 // Release a buffer that the caller indicated it is finished with.
467 allocator_.Release(encrypted_block_info.tracking_info.buffer_id);
469 cdm::Status status = cdm::kDecryptError;
470 LinkedDecryptedBlock decrypted_block(new DecryptedBlockImpl());
472 if (cdm_) {
473 cdm::InputBuffer input_buffer;
474 std::vector<cdm::SubsampleEntry> subsamples;
475 ConfigureInputBuffer(encrypted_buffer, encrypted_block_info, &subsamples,
476 &input_buffer);
477 status = cdm_->Decrypt(input_buffer, decrypted_block.get());
478 PP_DCHECK(status != cdm::kSuccess ||
479 (decrypted_block->DecryptedBuffer() &&
480 decrypted_block->DecryptedBuffer()->Size()));
483 CallOnMain(callback_factory_.NewCallback(
484 &CdmAdapter::DeliverBlock,
485 status,
486 decrypted_block,
487 encrypted_block_info.tracking_info));
490 void CdmAdapter::InitializeAudioDecoder(
491 const PP_AudioDecoderConfig& decoder_config,
492 pp::Buffer_Dev extra_data_buffer) {
493 PP_DCHECK(!deferred_initialize_audio_decoder_);
494 PP_DCHECK(deferred_audio_decoder_config_id_ == 0);
495 cdm::Status status = cdm::kSessionError;
496 if (cdm_) {
497 cdm::AudioDecoderConfig cdm_decoder_config;
498 cdm_decoder_config.codec =
499 PpAudioCodecToCdmAudioCodec(decoder_config.codec);
500 cdm_decoder_config.channel_count = decoder_config.channel_count;
501 cdm_decoder_config.bits_per_channel = decoder_config.bits_per_channel;
502 cdm_decoder_config.samples_per_second = decoder_config.samples_per_second;
503 cdm_decoder_config.extra_data =
504 static_cast<uint8_t*>(extra_data_buffer.data());
505 cdm_decoder_config.extra_data_size = extra_data_buffer.size();
506 status = cdm_->InitializeAudioDecoder(cdm_decoder_config);
509 if (status == cdm::kDeferredInitialization) {
510 deferred_initialize_audio_decoder_ = true;
511 deferred_audio_decoder_config_id_ = decoder_config.request_id;
512 return;
515 CallOnMain(callback_factory_.NewCallback(
516 &CdmAdapter::DecoderInitializeDone,
517 PP_DECRYPTORSTREAMTYPE_AUDIO,
518 decoder_config.request_id,
519 status == cdm::kSuccess));
522 void CdmAdapter::InitializeVideoDecoder(
523 const PP_VideoDecoderConfig& decoder_config,
524 pp::Buffer_Dev extra_data_buffer) {
525 PP_DCHECK(!deferred_initialize_video_decoder_);
526 PP_DCHECK(deferred_video_decoder_config_id_ == 0);
527 cdm::Status status = cdm::kSessionError;
528 if (cdm_) {
529 cdm::VideoDecoderConfig cdm_decoder_config;
530 cdm_decoder_config.codec =
531 PpVideoCodecToCdmVideoCodec(decoder_config.codec);
532 cdm_decoder_config.profile =
533 PpVCProfileToCdmVCProfile(decoder_config.profile);
534 cdm_decoder_config.format =
535 PpDecryptedFrameFormatToCdmVideoFormat(decoder_config.format);
536 cdm_decoder_config.coded_size.width = decoder_config.width;
537 cdm_decoder_config.coded_size.height = decoder_config.height;
538 cdm_decoder_config.extra_data =
539 static_cast<uint8_t*>(extra_data_buffer.data());
540 cdm_decoder_config.extra_data_size = extra_data_buffer.size();
541 status = cdm_->InitializeVideoDecoder(cdm_decoder_config);
544 if (status == cdm::kDeferredInitialization) {
545 deferred_initialize_video_decoder_ = true;
546 deferred_video_decoder_config_id_ = decoder_config.request_id;
547 return;
550 CallOnMain(callback_factory_.NewCallback(
551 &CdmAdapter::DecoderInitializeDone,
552 PP_DECRYPTORSTREAMTYPE_VIDEO,
553 decoder_config.request_id,
554 status == cdm::kSuccess));
557 void CdmAdapter::DeinitializeDecoder(PP_DecryptorStreamType decoder_type,
558 uint32_t request_id) {
559 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded.
560 if (cdm_) {
561 cdm_->DeinitializeDecoder(
562 PpDecryptorStreamTypeToCdmStreamType(decoder_type));
565 CallOnMain(callback_factory_.NewCallback(
566 &CdmAdapter::DecoderDeinitializeDone,
567 decoder_type,
568 request_id));
571 void CdmAdapter::ResetDecoder(PP_DecryptorStreamType decoder_type,
572 uint32_t request_id) {
573 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded.
574 if (cdm_)
575 cdm_->ResetDecoder(PpDecryptorStreamTypeToCdmStreamType(decoder_type));
577 CallOnMain(callback_factory_.NewCallback(&CdmAdapter::DecoderResetDone,
578 decoder_type,
579 request_id));
582 void CdmAdapter::DecryptAndDecode(
583 PP_DecryptorStreamType decoder_type,
584 pp::Buffer_Dev encrypted_buffer,
585 const PP_EncryptedBlockInfo& encrypted_block_info) {
586 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded.
587 // Release a buffer that the caller indicated it is finished with.
588 allocator_.Release(encrypted_block_info.tracking_info.buffer_id);
590 cdm::InputBuffer input_buffer;
591 std::vector<cdm::SubsampleEntry> subsamples;
592 if (cdm_ && !encrypted_buffer.is_null()) {
593 ConfigureInputBuffer(encrypted_buffer,
594 encrypted_block_info,
595 &subsamples,
596 &input_buffer);
599 cdm::Status status = cdm::kDecodeError;
601 switch (decoder_type) {
602 case PP_DECRYPTORSTREAMTYPE_VIDEO: {
603 LinkedVideoFrame video_frame(new VideoFrameImpl());
604 if (cdm_)
605 status = cdm_->DecryptAndDecodeFrame(input_buffer, video_frame.get());
606 CallOnMain(callback_factory_.NewCallback(
607 &CdmAdapter::DeliverFrame,
608 status,
609 video_frame,
610 encrypted_block_info.tracking_info));
611 return;
614 case PP_DECRYPTORSTREAMTYPE_AUDIO: {
615 LinkedAudioFrames audio_frames(new AudioFramesImpl());
616 if (cdm_) {
617 status = cdm_->DecryptAndDecodeSamples(input_buffer,
618 audio_frames.get());
620 CallOnMain(callback_factory_.NewCallback(
621 &CdmAdapter::DeliverSamples,
622 status,
623 audio_frames,
624 encrypted_block_info.tracking_info));
625 return;
628 default:
629 PP_NOTREACHED();
630 return;
634 cdm::Buffer* CdmAdapter::Allocate(uint32_t capacity) {
635 return allocator_.Allocate(capacity);
638 void CdmAdapter::SetTimer(int64_t delay_ms, void* context) {
639 // NOTE: doesn't really need to run on the main thread; could just as well run
640 // on a helper thread if |cdm_| were thread-friendly and care was taken. We
641 // only use CallOnMainThread() here to get delayed-execution behavior.
642 pp::Module::Get()->core()->CallOnMainThread(
643 delay_ms,
644 callback_factory_.NewCallback(&CdmAdapter::TimerExpired, context),
645 PP_OK);
648 void CdmAdapter::TimerExpired(int32_t result, void* context) {
649 PP_DCHECK(result == PP_OK);
650 cdm_->TimerExpired(context);
653 cdm::Time CdmAdapter::GetCurrentWallTime() {
654 return pp::Module::Get()->core()->GetTime();
657 void CdmAdapter::OnResolveNewSessionPromise(uint32_t promise_id,
658 const char* session_id,
659 uint32_t session_id_size) {
660 PostOnMain(callback_factory_.NewCallback(
661 &CdmAdapter::SendPromiseResolvedWithSessionInternal, promise_id,
662 std::string(session_id, session_id_size)));
665 void CdmAdapter::OnResolvePromise(uint32_t promise_id) {
666 PostOnMain(callback_factory_.NewCallback(
667 &CdmAdapter::SendPromiseResolvedInternal, promise_id));
670 void CdmAdapter::OnRejectPromise(uint32_t promise_id,
671 cdm::Error error,
672 uint32_t system_code,
673 const char* error_message,
674 uint32_t error_message_size) {
675 // UMA to investigate http://crbug.com/410630
676 // TODO(xhwang): Remove after bug is fixed.
677 if (system_code == 0x27) {
678 pp::UMAPrivate uma_interface(this);
679 uma_interface.HistogramCustomCounts("Media.EME.CdmFileIO.FileSizeKBOnError",
680 last_read_file_size_kb_,
681 kSizeKBMin,
682 kSizeKBMax,
683 kSizeKBBuckets);
686 RejectPromise(promise_id, error, system_code,
687 std::string(error_message, error_message_size));
690 void CdmAdapter::RejectPromise(uint32_t promise_id,
691 cdm::Error error,
692 uint32_t system_code,
693 const std::string& error_message) {
694 PostOnMain(callback_factory_.NewCallback(
695 &CdmAdapter::SendPromiseRejectedInternal,
696 promise_id,
697 SessionError(error, system_code, error_message)));
700 void CdmAdapter::OnSessionMessage(const char* session_id,
701 uint32_t session_id_size,
702 cdm::MessageType message_type,
703 const char* message,
704 uint32_t message_size,
705 const char* legacy_destination_url,
706 uint32_t legacy_destination_url_size) {
707 // License requests should not specify |legacy_destination_url|.
708 // |legacy_destination_url| is not passed to unprefixed EME applications,
709 // so it can be removed when the prefixed API is removed.
710 PP_DCHECK(legacy_destination_url_size == 0 ||
711 message_type != cdm::MessageType::kLicenseRequest);
713 PostOnMain(callback_factory_.NewCallback(
714 &CdmAdapter::SendSessionMessageInternal,
715 SessionMessage(
716 std::string(session_id, session_id_size), message_type, message,
717 message_size,
718 std::string(legacy_destination_url, legacy_destination_url_size))));
721 void CdmAdapter::OnSessionKeysChange(const char* session_id,
722 uint32_t session_id_size,
723 bool has_additional_usable_key,
724 const cdm::KeyInformation* keys_info,
725 uint32_t keys_info_count) {
726 std::vector<PP_KeyInformation> key_information;
727 for (uint32_t i = 0; i < keys_info_count; ++i) {
728 const auto& key_info = keys_info[i];
729 PP_KeyInformation next_key = {};
731 if (key_info.key_id_size > sizeof(next_key.key_id)) {
732 PP_NOTREACHED();
733 continue;
736 // Copy key_id into |next_key|.
737 memcpy(next_key.key_id, key_info.key_id, key_info.key_id_size);
739 // Set remaining fields on |next_key|.
740 next_key.key_id_size = key_info.key_id_size;
741 next_key.key_status = CdmKeyStatusToPpKeyStatus(key_info.status);
742 next_key.system_code = key_info.system_code;
743 key_information.push_back(next_key);
746 PostOnMain(callback_factory_.NewCallback(
747 &CdmAdapter::SendSessionKeysChangeInternal,
748 std::string(session_id, session_id_size), has_additional_usable_key,
749 key_information));
752 void CdmAdapter::OnExpirationChange(const char* session_id,
753 uint32_t session_id_size,
754 cdm::Time new_expiry_time) {
755 PostOnMain(callback_factory_.NewCallback(
756 &CdmAdapter::SendExpirationChangeInternal,
757 std::string(session_id, session_id_size), new_expiry_time));
760 void CdmAdapter::OnSessionClosed(const char* session_id,
761 uint32_t session_id_size) {
762 PostOnMain(
763 callback_factory_.NewCallback(&CdmAdapter::SendSessionClosedInternal,
764 std::string(session_id, session_id_size)));
767 void CdmAdapter::OnLegacySessionError(const char* session_id,
768 uint32_t session_id_size,
769 cdm::Error error,
770 uint32_t system_code,
771 const char* error_message,
772 uint32_t error_message_size) {
773 PostOnMain(callback_factory_.NewCallback(
774 &CdmAdapter::SendSessionErrorInternal,
775 std::string(session_id, session_id_size),
776 SessionError(error, system_code,
777 std::string(error_message, error_message_size))));
780 // Helpers to pass the event to Pepper.
782 void CdmAdapter::SendPromiseResolvedInternal(int32_t result,
783 uint32_t promise_id) {
784 PP_DCHECK(result == PP_OK);
785 pp::ContentDecryptor_Private::PromiseResolved(promise_id);
788 void CdmAdapter::SendPromiseResolvedWithSessionInternal(
789 int32_t result,
790 uint32_t promise_id,
791 const std::string& session_id) {
792 PP_DCHECK(result == PP_OK);
793 pp::ContentDecryptor_Private::PromiseResolvedWithSession(promise_id,
794 session_id);
797 void CdmAdapter::SendPromiseRejectedInternal(int32_t result,
798 uint32_t promise_id,
799 const SessionError& error) {
800 PP_DCHECK(result == PP_OK);
801 pp::ContentDecryptor_Private::PromiseRejected(
802 promise_id,
803 CdmExceptionTypeToPpCdmExceptionType(error.error),
804 error.system_code,
805 error.error_description);
808 void CdmAdapter::SendSessionMessageInternal(int32_t result,
809 const SessionMessage& message) {
810 PP_DCHECK(result == PP_OK);
812 pp::VarArrayBuffer message_array_buffer(message.message.size());
813 if (message.message.size() > 0) {
814 memcpy(message_array_buffer.Map(), message.message.data(),
815 message.message.size());
818 pp::ContentDecryptor_Private::SessionMessage(
819 message.session_id, CdmMessageTypeToPpMessageType(message.message_type),
820 message_array_buffer, message.legacy_destination_url);
823 void CdmAdapter::SendSessionClosedInternal(int32_t result,
824 const std::string& session_id) {
825 PP_DCHECK(result == PP_OK);
826 pp::ContentDecryptor_Private::SessionClosed(session_id);
829 void CdmAdapter::SendSessionErrorInternal(int32_t result,
830 const std::string& session_id,
831 const SessionError& error) {
832 PP_DCHECK(result == PP_OK);
833 pp::ContentDecryptor_Private::LegacySessionError(
834 session_id, CdmExceptionTypeToPpCdmExceptionType(error.error),
835 error.system_code, error.error_description);
838 void CdmAdapter::SendSessionKeysChangeInternal(
839 int32_t result,
840 const std::string& session_id,
841 bool has_additional_usable_key,
842 const std::vector<PP_KeyInformation>& key_info) {
843 PP_DCHECK(result == PP_OK);
844 pp::ContentDecryptor_Private::SessionKeysChange(
845 session_id, has_additional_usable_key, key_info);
848 void CdmAdapter::SendExpirationChangeInternal(int32_t result,
849 const std::string& session_id,
850 cdm::Time new_expiry_time) {
851 PP_DCHECK(result == PP_OK);
852 pp::ContentDecryptor_Private::SessionExpirationChange(session_id,
853 new_expiry_time);
856 void CdmAdapter::DeliverBlock(int32_t result,
857 const cdm::Status& status,
858 const LinkedDecryptedBlock& decrypted_block,
859 const PP_DecryptTrackingInfo& tracking_info) {
860 PP_DCHECK(result == PP_OK);
861 PP_DecryptedBlockInfo decrypted_block_info = {};
862 decrypted_block_info.tracking_info = tracking_info;
863 decrypted_block_info.tracking_info.timestamp = decrypted_block->Timestamp();
864 decrypted_block_info.tracking_info.buffer_id = 0;
865 decrypted_block_info.data_size = 0;
866 decrypted_block_info.result = CdmStatusToPpDecryptResult(status);
868 pp::Buffer_Dev buffer;
870 if (decrypted_block_info.result == PP_DECRYPTRESULT_SUCCESS) {
871 PP_DCHECK(decrypted_block.get() && decrypted_block->DecryptedBuffer());
872 if (!decrypted_block.get() || !decrypted_block->DecryptedBuffer()) {
873 PP_NOTREACHED();
874 decrypted_block_info.result = PP_DECRYPTRESULT_DECRYPT_ERROR;
875 } else {
876 PpbBuffer* ppb_buffer =
877 static_cast<PpbBuffer*>(decrypted_block->DecryptedBuffer());
878 decrypted_block_info.tracking_info.buffer_id = ppb_buffer->buffer_id();
879 decrypted_block_info.data_size = ppb_buffer->Size();
881 buffer = ppb_buffer->TakeBuffer();
885 pp::ContentDecryptor_Private::DeliverBlock(buffer, decrypted_block_info);
888 void CdmAdapter::DecoderInitializeDone(int32_t result,
889 PP_DecryptorStreamType decoder_type,
890 uint32_t request_id,
891 bool success) {
892 PP_DCHECK(result == PP_OK);
893 pp::ContentDecryptor_Private::DecoderInitializeDone(decoder_type,
894 request_id,
895 success);
898 void CdmAdapter::DecoderDeinitializeDone(int32_t result,
899 PP_DecryptorStreamType decoder_type,
900 uint32_t request_id) {
901 pp::ContentDecryptor_Private::DecoderDeinitializeDone(decoder_type,
902 request_id);
905 void CdmAdapter::DecoderResetDone(int32_t result,
906 PP_DecryptorStreamType decoder_type,
907 uint32_t request_id) {
908 pp::ContentDecryptor_Private::DecoderResetDone(decoder_type, request_id);
911 void CdmAdapter::DeliverFrame(
912 int32_t result,
913 const cdm::Status& status,
914 const LinkedVideoFrame& video_frame,
915 const PP_DecryptTrackingInfo& tracking_info) {
916 PP_DCHECK(result == PP_OK);
917 PP_DecryptedFrameInfo decrypted_frame_info = {};
918 decrypted_frame_info.tracking_info.request_id = tracking_info.request_id;
919 decrypted_frame_info.tracking_info.buffer_id = 0;
920 decrypted_frame_info.result = CdmStatusToPpDecryptResult(status);
922 pp::Buffer_Dev buffer;
924 if (decrypted_frame_info.result == PP_DECRYPTRESULT_SUCCESS) {
925 if (!IsValidVideoFrame(video_frame)) {
926 PP_NOTREACHED();
927 decrypted_frame_info.result = PP_DECRYPTRESULT_DECODE_ERROR;
928 } else {
929 PpbBuffer* ppb_buffer =
930 static_cast<PpbBuffer*>(video_frame->FrameBuffer());
932 decrypted_frame_info.tracking_info.timestamp = video_frame->Timestamp();
933 decrypted_frame_info.tracking_info.buffer_id = ppb_buffer->buffer_id();
934 decrypted_frame_info.format =
935 CdmVideoFormatToPpDecryptedFrameFormat(video_frame->Format());
936 decrypted_frame_info.width = video_frame->Size().width;
937 decrypted_frame_info.height = video_frame->Size().height;
938 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_Y] =
939 video_frame->PlaneOffset(cdm::VideoFrame::kYPlane);
940 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_U] =
941 video_frame->PlaneOffset(cdm::VideoFrame::kUPlane);
942 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_V] =
943 video_frame->PlaneOffset(cdm::VideoFrame::kVPlane);
944 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_Y] =
945 video_frame->Stride(cdm::VideoFrame::kYPlane);
946 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_U] =
947 video_frame->Stride(cdm::VideoFrame::kUPlane);
948 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_V] =
949 video_frame->Stride(cdm::VideoFrame::kVPlane);
951 buffer = ppb_buffer->TakeBuffer();
955 pp::ContentDecryptor_Private::DeliverFrame(buffer, decrypted_frame_info);
958 void CdmAdapter::DeliverSamples(int32_t result,
959 const cdm::Status& status,
960 const LinkedAudioFrames& audio_frames,
961 const PP_DecryptTrackingInfo& tracking_info) {
962 PP_DCHECK(result == PP_OK);
964 PP_DecryptedSampleInfo decrypted_sample_info = {};
965 decrypted_sample_info.tracking_info = tracking_info;
966 decrypted_sample_info.tracking_info.timestamp = 0;
967 decrypted_sample_info.tracking_info.buffer_id = 0;
968 decrypted_sample_info.data_size = 0;
969 decrypted_sample_info.result = CdmStatusToPpDecryptResult(status);
971 pp::Buffer_Dev buffer;
973 if (decrypted_sample_info.result == PP_DECRYPTRESULT_SUCCESS) {
974 PP_DCHECK(audio_frames.get() && audio_frames->FrameBuffer());
975 if (!audio_frames.get() || !audio_frames->FrameBuffer()) {
976 PP_NOTREACHED();
977 decrypted_sample_info.result = PP_DECRYPTRESULT_DECRYPT_ERROR;
978 } else {
979 PpbBuffer* ppb_buffer =
980 static_cast<PpbBuffer*>(audio_frames->FrameBuffer());
982 decrypted_sample_info.tracking_info.buffer_id = ppb_buffer->buffer_id();
983 decrypted_sample_info.data_size = ppb_buffer->Size();
984 decrypted_sample_info.format =
985 CdmAudioFormatToPpDecryptedSampleFormat(audio_frames->Format());
987 buffer = ppb_buffer->TakeBuffer();
991 pp::ContentDecryptor_Private::DeliverSamples(buffer, decrypted_sample_info);
994 bool CdmAdapter::IsValidVideoFrame(const LinkedVideoFrame& video_frame) {
995 if (!video_frame.get() ||
996 !video_frame->FrameBuffer() ||
997 (video_frame->Format() != cdm::kI420 &&
998 video_frame->Format() != cdm::kYv12)) {
999 CDM_DLOG() << "Invalid video frame!";
1000 return false;
1003 PpbBuffer* ppb_buffer = static_cast<PpbBuffer*>(video_frame->FrameBuffer());
1005 for (uint32_t i = 0; i < cdm::VideoFrame::kMaxPlanes; ++i) {
1006 int plane_height = (i == cdm::VideoFrame::kYPlane) ?
1007 video_frame->Size().height : (video_frame->Size().height + 1) / 2;
1008 cdm::VideoFrame::VideoPlane plane =
1009 static_cast<cdm::VideoFrame::VideoPlane>(i);
1010 if (ppb_buffer->Size() < video_frame->PlaneOffset(plane) +
1011 plane_height * video_frame->Stride(plane)) {
1012 return false;
1016 return true;
1019 void CdmAdapter::OnFirstFileRead(int32_t file_size_bytes) {
1020 PP_DCHECK(IsMainThread());
1021 PP_DCHECK(file_size_bytes >= 0);
1023 last_read_file_size_kb_ = file_size_bytes / 1024;
1025 if (file_size_uma_reported_)
1026 return;
1028 pp::UMAPrivate uma_interface(this);
1029 uma_interface.HistogramCustomCounts(
1030 "Media.EME.CdmFileIO.FileSizeKBOnFirstRead",
1031 last_read_file_size_kb_,
1032 kSizeKBMin,
1033 kSizeKBMax,
1034 kSizeKBBuckets);
1035 file_size_uma_reported_ = true;
1038 #if !defined(NDEBUG)
1039 void CdmAdapter::LogToConsole(const pp::Var& value) {
1040 PP_DCHECK(IsMainThread());
1041 const PPB_Console* console = reinterpret_cast<const PPB_Console*>(
1042 pp::Module::Get()->GetBrowserInterface(PPB_CONSOLE_INTERFACE));
1043 console->Log(pp_instance(), PP_LOGLEVEL_LOG, value.pp_var());
1045 #endif // !defined(NDEBUG)
1047 void CdmAdapter::SendPlatformChallenge(const char* service_id,
1048 uint32_t service_id_size,
1049 const char* challenge,
1050 uint32_t challenge_size) {
1051 #if defined(OS_CHROMEOS)
1052 // If access to a distinctive identifier is not allowed, block platform
1053 // verification to prevent access to such an identifier.
1054 if (allow_distinctive_identifier_) {
1055 pp::VarArrayBuffer challenge_var(challenge_size);
1056 uint8_t* var_data = static_cast<uint8_t*>(challenge_var.Map());
1057 memcpy(var_data, challenge, challenge_size);
1059 std::string service_id_str(service_id, service_id_size);
1061 linked_ptr<PepperPlatformChallengeResponse> response(
1062 new PepperPlatformChallengeResponse());
1064 int32_t result = platform_verification_.ChallengePlatform(
1065 pp::Var(service_id_str),
1066 challenge_var,
1067 &response->signed_data,
1068 &response->signed_data_signature,
1069 &response->platform_key_certificate,
1070 callback_factory_.NewCallback(&CdmAdapter::SendPlatformChallengeDone,
1071 response));
1072 challenge_var.Unmap();
1073 if (result == PP_OK_COMPLETIONPENDING)
1074 return;
1076 // Fall through on error and issue an empty OnPlatformChallengeResponse().
1077 PP_DCHECK(result != PP_OK);
1079 #endif
1081 cdm::PlatformChallengeResponse platform_challenge_response = {};
1082 cdm_->OnPlatformChallengeResponse(platform_challenge_response);
1085 void CdmAdapter::EnableOutputProtection(uint32_t desired_protection_mask) {
1086 #if defined(OS_CHROMEOS)
1087 int32_t result = output_protection_.EnableProtection(
1088 desired_protection_mask, callback_factory_.NewCallback(
1089 &CdmAdapter::EnableProtectionDone));
1091 // Errors are ignored since clients must call QueryOutputProtectionStatus() to
1092 // inspect the protection status on a regular basis.
1094 if (result != PP_OK && result != PP_OK_COMPLETIONPENDING)
1095 CDM_DLOG() << __FUNCTION__ << " failed!";
1096 #endif
1099 void CdmAdapter::QueryOutputProtectionStatus() {
1100 #if defined(OS_CHROMEOS)
1101 PP_DCHECK(!query_output_protection_in_progress_);
1103 output_link_mask_ = output_protection_mask_ = 0;
1104 const int32_t result = output_protection_.QueryStatus(
1105 &output_link_mask_,
1106 &output_protection_mask_,
1107 callback_factory_.NewCallback(
1108 &CdmAdapter::QueryOutputProtectionStatusDone));
1109 if (result == PP_OK_COMPLETIONPENDING) {
1110 query_output_protection_in_progress_ = true;
1111 ReportOutputProtectionQuery();
1112 return;
1115 // Fall through on error and issue an empty OnQueryOutputProtectionStatus().
1116 PP_DCHECK(result != PP_OK);
1117 CDM_DLOG() << __FUNCTION__ << " failed, result = " << result;
1118 #endif
1119 cdm_->OnQueryOutputProtectionStatus(cdm::kQueryFailed, 0, 0);
1122 void CdmAdapter::OnDeferredInitializationDone(cdm::StreamType stream_type,
1123 cdm::Status decoder_status) {
1124 switch (stream_type) {
1125 case cdm::kStreamTypeAudio:
1126 PP_DCHECK(deferred_initialize_audio_decoder_);
1127 CallOnMain(
1128 callback_factory_.NewCallback(&CdmAdapter::DecoderInitializeDone,
1129 PP_DECRYPTORSTREAMTYPE_AUDIO,
1130 deferred_audio_decoder_config_id_,
1131 decoder_status == cdm::kSuccess));
1132 deferred_initialize_audio_decoder_ = false;
1133 deferred_audio_decoder_config_id_ = 0;
1134 break;
1135 case cdm::kStreamTypeVideo:
1136 PP_DCHECK(deferred_initialize_video_decoder_);
1137 CallOnMain(
1138 callback_factory_.NewCallback(&CdmAdapter::DecoderInitializeDone,
1139 PP_DECRYPTORSTREAMTYPE_VIDEO,
1140 deferred_video_decoder_config_id_,
1141 decoder_status == cdm::kSuccess));
1142 deferred_initialize_video_decoder_ = false;
1143 deferred_video_decoder_config_id_ = 0;
1144 break;
1148 // The CDM owns the returned object and must call FileIO::Close() to release it.
1149 cdm::FileIO* CdmAdapter::CreateFileIO(cdm::FileIOClient* client) {
1150 if (!allow_persistent_state_) {
1151 CDM_DLOG()
1152 << "Cannot create FileIO because persistent state is not allowed.";
1153 return nullptr;
1156 return new CdmFileIOImpl(
1157 client, pp_instance(),
1158 callback_factory_.NewCallback(&CdmAdapter::OnFirstFileRead));
1161 #if defined(OS_CHROMEOS)
1162 void CdmAdapter::ReportOutputProtectionUMA(OutputProtectionStatus status) {
1163 pp::UMAPrivate uma_interface(this);
1164 uma_interface.HistogramEnumeration(
1165 "Media.EME.OutputProtection", status, OUTPUT_PROTECTION_MAX);
1168 void CdmAdapter::ReportOutputProtectionQuery() {
1169 if (uma_for_output_protection_query_reported_)
1170 return;
1172 ReportOutputProtectionUMA(OUTPUT_PROTECTION_QUERIED);
1173 uma_for_output_protection_query_reported_ = true;
1176 void CdmAdapter::ReportOutputProtectionQueryResult() {
1177 if (uma_for_output_protection_positive_result_reported_)
1178 return;
1180 // Report UMAs for output protection query result.
1181 uint32_t external_links = (output_link_mask_ & ~cdm::kLinkTypeInternal);
1183 if (!external_links) {
1184 ReportOutputProtectionUMA(OUTPUT_PROTECTION_NO_EXTERNAL_LINK);
1185 uma_for_output_protection_positive_result_reported_ = true;
1186 return;
1189 const uint32_t kProtectableLinks =
1190 cdm::kLinkTypeHDMI | cdm::kLinkTypeDVI | cdm::kLinkTypeDisplayPort;
1191 bool is_unprotectable_link_connected = external_links & ~kProtectableLinks;
1192 bool is_hdcp_enabled_on_all_protectable_links =
1193 output_protection_mask_ & cdm::kProtectionHDCP;
1195 if (!is_unprotectable_link_connected &&
1196 is_hdcp_enabled_on_all_protectable_links) {
1197 ReportOutputProtectionUMA(
1198 OUTPUT_PROTECTION_ALL_EXTERNAL_LINKS_PROTECTED);
1199 uma_for_output_protection_positive_result_reported_ = true;
1200 return;
1203 // Do not report a negative result because it could be a false negative.
1204 // Instead, we will calculate number of negatives using the total number of
1205 // queries and success results.
1208 void CdmAdapter::SendPlatformChallengeDone(
1209 int32_t result,
1210 const linked_ptr<PepperPlatformChallengeResponse>& response) {
1211 if (result != PP_OK) {
1212 CDM_DLOG() << __FUNCTION__ << ": Platform challenge failed!";
1213 cdm::PlatformChallengeResponse platform_challenge_response = {};
1214 cdm_->OnPlatformChallengeResponse(platform_challenge_response);
1215 return;
1218 pp::VarArrayBuffer signed_data_var(response->signed_data);
1219 pp::VarArrayBuffer signed_data_signature_var(response->signed_data_signature);
1220 std::string platform_key_certificate_string =
1221 response->platform_key_certificate.AsString();
1223 cdm::PlatformChallengeResponse platform_challenge_response = {
1224 static_cast<uint8_t*>(signed_data_var.Map()),
1225 signed_data_var.ByteLength(),
1226 static_cast<uint8_t*>(signed_data_signature_var.Map()),
1227 signed_data_signature_var.ByteLength(),
1228 reinterpret_cast<const uint8_t*>(platform_key_certificate_string.data()),
1229 static_cast<uint32_t>(platform_key_certificate_string.length())};
1230 cdm_->OnPlatformChallengeResponse(platform_challenge_response);
1232 signed_data_var.Unmap();
1233 signed_data_signature_var.Unmap();
1236 void CdmAdapter::EnableProtectionDone(int32_t result) {
1237 // Does nothing since clients must call QueryOutputProtectionStatus() to
1238 // inspect the protection status on a regular basis.
1239 CDM_DLOG() << __FUNCTION__ << " : " << result;
1242 void CdmAdapter::QueryOutputProtectionStatusDone(int32_t result) {
1243 PP_DCHECK(query_output_protection_in_progress_);
1244 query_output_protection_in_progress_ = false;
1246 // Return a query status of failed on error.
1247 cdm::QueryResult query_result;
1248 if (result != PP_OK) {
1249 CDM_DLOG() << __FUNCTION__ << " failed, result = " << result;
1250 output_link_mask_ = output_protection_mask_ = 0;
1251 query_result = cdm::kQueryFailed;
1252 } else {
1253 query_result = cdm::kQuerySucceeded;
1254 ReportOutputProtectionQueryResult();
1257 cdm_->OnQueryOutputProtectionStatus(query_result, output_link_mask_,
1258 output_protection_mask_);
1260 #endif
1262 CdmAdapter::SessionError::SessionError(cdm::Error error,
1263 uint32_t system_code,
1264 const std::string& error_description)
1265 : error(error),
1266 system_code(system_code),
1267 error_description(error_description) {
1270 CdmAdapter::SessionMessage::SessionMessage(
1271 const std::string& session_id,
1272 cdm::MessageType message_type,
1273 const char* message,
1274 uint32_t message_size,
1275 const std::string& legacy_destination_url)
1276 : session_id(session_id),
1277 message_type(message_type),
1278 message(message, message + message_size),
1279 legacy_destination_url(legacy_destination_url) {
1282 void* GetCdmHost(int host_interface_version, void* user_data) {
1283 if (!host_interface_version || !user_data)
1284 return NULL;
1286 static_assert(
1287 cdm::ContentDecryptionModule::Host::kVersion == cdm::Host_8::kVersion,
1288 "update the code below");
1290 // Ensure IsSupportedCdmHostVersion matches implementation of this function.
1291 // Always update this DCHECK when updating this function.
1292 // If this check fails, update this function and DCHECK or update
1293 // IsSupportedCdmHostVersion.
1295 PP_DCHECK(
1296 // Future version is not supported.
1297 !IsSupportedCdmHostVersion(cdm::Host_8::kVersion + 1) &&
1298 // Current version is supported.
1299 IsSupportedCdmHostVersion(cdm::Host_8::kVersion) &&
1300 // Include all previous supported versions (if any) here.
1301 IsSupportedCdmHostVersion(cdm::Host_7::kVersion) &&
1302 // One older than the oldest supported version is not supported.
1303 !IsSupportedCdmHostVersion(cdm::Host_7::kVersion - 1));
1304 PP_DCHECK(IsSupportedCdmHostVersion(host_interface_version));
1306 CdmAdapter* cdm_adapter = static_cast<CdmAdapter*>(user_data);
1307 CDM_DLOG() << "Create CDM Host with version " << host_interface_version;
1308 switch (host_interface_version) {
1309 case cdm::Host_8::kVersion:
1310 return static_cast<cdm::Host_8*>(cdm_adapter);
1311 case cdm::Host_7::kVersion:
1312 return static_cast<cdm::Host_7*>(cdm_adapter);
1313 default:
1314 PP_NOTREACHED();
1315 return NULL;
1319 // This object is the global object representing this plugin library as long
1320 // as it is loaded.
1321 class CdmAdapterModule : public pp::Module {
1322 public:
1323 CdmAdapterModule() : pp::Module() {
1324 // This function blocks the renderer thread (PluginInstance::Initialize()).
1325 // Move this call to other places if this may be a concern in the future.
1326 INITIALIZE_CDM_MODULE();
1328 virtual ~CdmAdapterModule() {
1329 DeinitializeCdmModule();
1332 virtual pp::Instance* CreateInstance(PP_Instance instance) {
1333 return new CdmAdapter(instance, this);
1336 private:
1337 CdmFileIOImpl::ResourceTracker cdm_file_io_impl_resource_tracker;
1340 } // namespace media
1342 namespace pp {
1344 // Factory function for your specialization of the Module object.
1345 Module* CreateModule() {
1346 return new media::CdmAdapterModule();
1349 } // namespace pp