Handle all possible cdm::Status values before passing through Pepper
[chromium-blink-merge.git] / media / cdm / ppapi / cdm_adapter.cc
blob636ea3284be2ae2bdcf0bb28a9904940aa1fbb09
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_helpers.h"
10 #include "media/cdm/ppapi/cdm_logging.h"
11 #include "media/cdm/ppapi/supported_cdm_versions.h"
12 #include "ppapi/c/ppb_console.h"
13 #include "ppapi/cpp/private/uma_private.h"
15 #if defined(CHECK_DOCUMENT_URL)
16 #include "ppapi/cpp/dev/url_util_dev.h"
17 #include "ppapi/cpp/instance_handle.h"
18 #endif // defined(CHECK_DOCUMENT_URL)
20 namespace {
22 // Constants for UMA reporting of file size (in KB) via HistogramCustomCounts().
23 // Note that the histogram is log-scaled (rather than linear).
24 const uint32_t kSizeKBMin = 1;
25 const uint32_t kSizeKBMax = 512 * 1024; // 512MB
26 const uint32_t kSizeKBBuckets = 100;
28 #if !defined(NDEBUG)
29 #define DLOG_TO_CONSOLE(message) LogToConsole(message);
30 #else
31 #define DLOG_TO_CONSOLE(message) (void)(message);
32 #endif
34 bool IsMainThread() {
35 return pp::Module::Get()->core()->IsMainThread();
38 // Posts a task to run |cb| on the main thread. The task is posted even if the
39 // current thread is the main thread.
40 void PostOnMain(pp::CompletionCallback cb) {
41 pp::Module::Get()->core()->CallOnMainThread(0, cb, PP_OK);
44 // Ensures |cb| is called on the main thread, either because the current thread
45 // is the main thread or by posting it to the main thread.
46 void CallOnMain(pp::CompletionCallback cb) {
47 // TODO(tomfinegan): This is only necessary because PPAPI doesn't allow calls
48 // off the main thread yet. Remove this once the change lands.
49 if (IsMainThread())
50 cb.Run(PP_OK);
51 else
52 PostOnMain(cb);
55 // Configures a cdm::InputBuffer. |subsamples| must exist as long as
56 // |input_buffer| is in use.
57 void ConfigureInputBuffer(
58 const pp::Buffer_Dev& encrypted_buffer,
59 const PP_EncryptedBlockInfo& encrypted_block_info,
60 std::vector<cdm::SubsampleEntry>* subsamples,
61 cdm::InputBuffer* input_buffer) {
62 PP_DCHECK(subsamples);
63 PP_DCHECK(!encrypted_buffer.is_null());
65 input_buffer->data = static_cast<uint8_t*>(encrypted_buffer.data());
66 input_buffer->data_size = encrypted_block_info.data_size;
67 PP_DCHECK(encrypted_buffer.size() >= input_buffer->data_size);
69 PP_DCHECK(encrypted_block_info.key_id_size <=
70 arraysize(encrypted_block_info.key_id));
71 input_buffer->key_id_size = encrypted_block_info.key_id_size;
72 input_buffer->key_id = input_buffer->key_id_size > 0 ?
73 encrypted_block_info.key_id : NULL;
75 PP_DCHECK(encrypted_block_info.iv_size <= arraysize(encrypted_block_info.iv));
76 input_buffer->iv_size = encrypted_block_info.iv_size;
77 input_buffer->iv = encrypted_block_info.iv_size > 0 ?
78 encrypted_block_info.iv : NULL;
80 input_buffer->num_subsamples = encrypted_block_info.num_subsamples;
81 if (encrypted_block_info.num_subsamples > 0) {
82 subsamples->reserve(encrypted_block_info.num_subsamples);
84 for (uint32_t i = 0; i < encrypted_block_info.num_subsamples; ++i) {
85 subsamples->push_back(cdm::SubsampleEntry(
86 encrypted_block_info.subsamples[i].clear_bytes,
87 encrypted_block_info.subsamples[i].cipher_bytes));
90 input_buffer->subsamples = &(*subsamples)[0];
93 input_buffer->timestamp = encrypted_block_info.tracking_info.timestamp;
96 PP_DecryptResult CdmStatusToPpDecryptResult(cdm::Status status) {
97 switch (status) {
98 case cdm::kSuccess:
99 return PP_DECRYPTRESULT_SUCCESS;
100 case cdm::kNoKey:
101 return PP_DECRYPTRESULT_DECRYPT_NOKEY;
102 case cdm::kNeedMoreData:
103 return PP_DECRYPTRESULT_NEEDMOREDATA;
104 case cdm::kDecryptError:
105 return PP_DECRYPTRESULT_DECRYPT_ERROR;
106 case cdm::kDecodeError:
107 return PP_DECRYPTRESULT_DECODE_ERROR;
108 case cdm::kSessionError:
109 case cdm::kDeferredInitialization:
110 // kSessionError and kDeferredInitialization are only used by the
111 // Initialize* methods internally and never returned. Deliver*
112 // methods should never use these values.
113 break;
116 PP_NOTREACHED();
117 return PP_DECRYPTRESULT_DECRYPT_ERROR;
120 PP_DecryptedFrameFormat CdmVideoFormatToPpDecryptedFrameFormat(
121 cdm::VideoFormat format) {
122 switch (format) {
123 case cdm::kYv12:
124 return PP_DECRYPTEDFRAMEFORMAT_YV12;
125 case cdm::kI420:
126 return PP_DECRYPTEDFRAMEFORMAT_I420;
127 default:
128 return PP_DECRYPTEDFRAMEFORMAT_UNKNOWN;
132 PP_DecryptedSampleFormat CdmAudioFormatToPpDecryptedSampleFormat(
133 cdm::AudioFormat format) {
134 switch (format) {
135 case cdm::kAudioFormatU8:
136 return PP_DECRYPTEDSAMPLEFORMAT_U8;
137 case cdm::kAudioFormatS16:
138 return PP_DECRYPTEDSAMPLEFORMAT_S16;
139 case cdm::kAudioFormatS32:
140 return PP_DECRYPTEDSAMPLEFORMAT_S32;
141 case cdm::kAudioFormatF32:
142 return PP_DECRYPTEDSAMPLEFORMAT_F32;
143 case cdm::kAudioFormatPlanarS16:
144 return PP_DECRYPTEDSAMPLEFORMAT_PLANAR_S16;
145 case cdm::kAudioFormatPlanarF32:
146 return PP_DECRYPTEDSAMPLEFORMAT_PLANAR_F32;
147 default:
148 return PP_DECRYPTEDSAMPLEFORMAT_UNKNOWN;
152 cdm::AudioDecoderConfig::AudioCodec PpAudioCodecToCdmAudioCodec(
153 PP_AudioCodec codec) {
154 switch (codec) {
155 case PP_AUDIOCODEC_VORBIS:
156 return cdm::AudioDecoderConfig::kCodecVorbis;
157 case PP_AUDIOCODEC_AAC:
158 return cdm::AudioDecoderConfig::kCodecAac;
159 default:
160 return cdm::AudioDecoderConfig::kUnknownAudioCodec;
164 cdm::VideoDecoderConfig::VideoCodec PpVideoCodecToCdmVideoCodec(
165 PP_VideoCodec codec) {
166 switch (codec) {
167 case PP_VIDEOCODEC_VP8:
168 return cdm::VideoDecoderConfig::kCodecVp8;
169 case PP_VIDEOCODEC_H264:
170 return cdm::VideoDecoderConfig::kCodecH264;
171 case PP_VIDEOCODEC_VP9:
172 return cdm::VideoDecoderConfig::kCodecVp9;
173 default:
174 return cdm::VideoDecoderConfig::kUnknownVideoCodec;
178 cdm::VideoDecoderConfig::VideoCodecProfile PpVCProfileToCdmVCProfile(
179 PP_VideoCodecProfile profile) {
180 switch (profile) {
181 case PP_VIDEOCODECPROFILE_NOT_NEEDED:
182 return cdm::VideoDecoderConfig::kProfileNotNeeded;
183 case PP_VIDEOCODECPROFILE_H264_BASELINE:
184 return cdm::VideoDecoderConfig::kH264ProfileBaseline;
185 case PP_VIDEOCODECPROFILE_H264_MAIN:
186 return cdm::VideoDecoderConfig::kH264ProfileMain;
187 case PP_VIDEOCODECPROFILE_H264_EXTENDED:
188 return cdm::VideoDecoderConfig::kH264ProfileExtended;
189 case PP_VIDEOCODECPROFILE_H264_HIGH:
190 return cdm::VideoDecoderConfig::kH264ProfileHigh;
191 case PP_VIDEOCODECPROFILE_H264_HIGH_10:
192 return cdm::VideoDecoderConfig::kH264ProfileHigh10;
193 case PP_VIDEOCODECPROFILE_H264_HIGH_422:
194 return cdm::VideoDecoderConfig::kH264ProfileHigh422;
195 case PP_VIDEOCODECPROFILE_H264_HIGH_444_PREDICTIVE:
196 return cdm::VideoDecoderConfig::kH264ProfileHigh444Predictive;
197 default:
198 return cdm::VideoDecoderConfig::kUnknownVideoCodecProfile;
202 cdm::VideoFormat PpDecryptedFrameFormatToCdmVideoFormat(
203 PP_DecryptedFrameFormat format) {
204 switch (format) {
205 case PP_DECRYPTEDFRAMEFORMAT_YV12:
206 return cdm::kYv12;
207 case PP_DECRYPTEDFRAMEFORMAT_I420:
208 return cdm::kI420;
209 default:
210 return cdm::kUnknownVideoFormat;
214 cdm::StreamType PpDecryptorStreamTypeToCdmStreamType(
215 PP_DecryptorStreamType stream_type) {
216 switch (stream_type) {
217 case PP_DECRYPTORSTREAMTYPE_AUDIO:
218 return cdm::kStreamTypeAudio;
219 case PP_DECRYPTORSTREAMTYPE_VIDEO:
220 return cdm::kStreamTypeVideo;
223 PP_NOTREACHED();
224 return cdm::kStreamTypeVideo;
227 cdm::SessionType PpSessionTypeToCdmSessionType(PP_SessionType session_type) {
228 switch (session_type) {
229 case PP_SESSIONTYPE_TEMPORARY:
230 return cdm::kTemporary;
231 case PP_SESSIONTYPE_PERSISTENT_LICENSE:
232 return cdm::kPersistentLicense;
233 case PP_SESSIONTYPE_PERSISTENT_RELEASE:
234 return cdm::kPersistentKeyRelease;
237 PP_NOTREACHED();
238 return cdm::kTemporary;
241 cdm::InitDataType PpInitDataTypeToCdmInitDataType(
242 PP_InitDataType init_data_type) {
243 switch (init_data_type) {
244 case PP_INITDATATYPE_CENC:
245 return cdm::kCenc;
246 case PP_INITDATATYPE_KEYIDS:
247 return cdm::kKeyIds;
248 case PP_INITDATATYPE_WEBM:
249 return cdm::kWebM;
252 PP_NOTREACHED();
253 return cdm::kKeyIds;
256 PP_CdmExceptionCode CdmExceptionTypeToPpCdmExceptionType(cdm::Error error) {
257 switch (error) {
258 case cdm::kNotSupportedError:
259 return PP_CDMEXCEPTIONCODE_NOTSUPPORTEDERROR;
260 case cdm::kInvalidStateError:
261 return PP_CDMEXCEPTIONCODE_INVALIDSTATEERROR;
262 case cdm::kInvalidAccessError:
263 return PP_CDMEXCEPTIONCODE_INVALIDACCESSERROR;
264 case cdm::kQuotaExceededError:
265 return PP_CDMEXCEPTIONCODE_QUOTAEXCEEDEDERROR;
266 case cdm::kUnknownError:
267 return PP_CDMEXCEPTIONCODE_UNKNOWNERROR;
268 case cdm::kClientError:
269 return PP_CDMEXCEPTIONCODE_CLIENTERROR;
270 case cdm::kOutputError:
271 return PP_CDMEXCEPTIONCODE_OUTPUTERROR;
274 PP_NOTREACHED();
275 return PP_CDMEXCEPTIONCODE_UNKNOWNERROR;
278 PP_CdmMessageType CdmMessageTypeToPpMessageType(cdm::MessageType message) {
279 switch (message) {
280 case cdm::kLicenseRequest:
281 return PP_CDMMESSAGETYPE_LICENSE_REQUEST;
282 case cdm::kLicenseRenewal:
283 return PP_CDMMESSAGETYPE_LICENSE_RENEWAL;
284 case cdm::kLicenseRelease:
285 return PP_CDMMESSAGETYPE_LICENSE_RELEASE;
288 PP_NOTREACHED();
289 return PP_CDMMESSAGETYPE_LICENSE_REQUEST;
292 PP_CdmKeyStatus CdmKeyStatusToPpKeyStatus(cdm::KeyStatus status) {
293 switch (status) {
294 case cdm::kUsable:
295 return PP_CDMKEYSTATUS_USABLE;
296 case cdm::kInternalError:
297 return PP_CDMKEYSTATUS_INVALID;
298 case cdm::kExpired:
299 return PP_CDMKEYSTATUS_EXPIRED;
300 case cdm::kOutputNotAllowed:
301 return PP_CDMKEYSTATUS_OUTPUTNOTALLOWED;
302 case cdm::kOutputDownscaled:
303 return PP_CDMKEYSTATUS_OUTPUTDOWNSCALED;
304 case cdm::kStatusPending:
305 return PP_CDMKEYSTATUS_STATUSPENDING;
308 PP_NOTREACHED();
309 return PP_CDMKEYSTATUS_INVALID;
312 } // namespace
314 namespace media {
316 CdmAdapter::CdmAdapter(PP_Instance instance, pp::Module* module)
317 : pp::Instance(instance),
318 pp::ContentDecryptor_Private(this),
319 #if defined(OS_CHROMEOS)
320 output_protection_(this),
321 platform_verification_(this),
322 output_link_mask_(0),
323 output_protection_mask_(0),
324 query_output_protection_in_progress_(false),
325 uma_for_output_protection_query_reported_(false),
326 uma_for_output_protection_positive_result_reported_(false),
327 #endif
328 allocator_(this),
329 cdm_(NULL),
330 allow_distinctive_identifier_(false),
331 allow_persistent_state_(false),
332 deferred_initialize_audio_decoder_(false),
333 deferred_audio_decoder_config_id_(0),
334 deferred_initialize_video_decoder_(false),
335 deferred_video_decoder_config_id_(0),
336 last_read_file_size_kb_(0),
337 file_size_uma_reported_(false) {
338 callback_factory_.Initialize(this);
341 CdmAdapter::~CdmAdapter() {}
343 bool CdmAdapter::CreateCdmInstance(const std::string& key_system) {
344 PP_DCHECK(!cdm_);
345 cdm_ = make_linked_ptr(CdmWrapper::Create(
346 key_system.data(), key_system.size(), GetCdmHost, this));
347 bool success = cdm_ != NULL;
349 const std::string message = "CDM instance for " + key_system +
350 (success ? "" : " could not be") + " created.";
351 DLOG_TO_CONSOLE(message);
352 CDM_DLOG() << message;
354 return success;
357 // No errors should be reported in this function because the spec says:
358 // "Store this new error object internally with the MediaKeys instance being
359 // created. This will be used to fire an error against any session created for
360 // this instance." These errors will be reported during session creation
361 // (CreateSession()) or session loading (LoadSession()).
362 // TODO(xhwang): If necessary, we need to store the error here if we want to
363 // support more specific error reporting (other than "Unknown").
364 void CdmAdapter::Initialize(const std::string& key_system,
365 bool allow_distinctive_identifier,
366 bool allow_persistent_state) {
367 PP_DCHECK(!key_system.empty());
368 // TODO(jrummell): Remove this check when CDM creation is asynchronous.
369 // http://crbug.com/469003
370 PP_DCHECK(key_system_.empty() || (key_system_ == key_system && cdm_));
372 #if defined(CHECK_DOCUMENT_URL)
373 PP_URLComponents_Dev url_components = {};
374 const pp::URLUtil_Dev* url_util = pp::URLUtil_Dev::Get();
375 if (!url_util)
376 return;
377 pp::Var href = url_util->GetDocumentURL(pp::InstanceHandle(pp_instance()),
378 &url_components);
379 PP_DCHECK(href.is_string());
380 std::string url = href.AsString();
381 PP_DCHECK(!url.empty());
382 std::string url_scheme =
383 url.substr(url_components.scheme.begin, url_components.scheme.len);
384 if (url_scheme != "file") {
385 // Skip this check for file:// URLs as they don't have a host component.
386 PP_DCHECK(url_components.host.begin);
387 PP_DCHECK(0 < url_components.host.len);
389 #endif // defined(CHECK_DOCUMENT_URL)
391 if (!cdm_ && !CreateCdmInstance(key_system))
392 return;
394 PP_DCHECK(cdm_);
395 key_system_ = key_system;
396 allow_distinctive_identifier_ = allow_distinctive_identifier;
397 allow_persistent_state_ = allow_persistent_state;
398 cdm_->Initialize(allow_distinctive_identifier, allow_persistent_state);
401 void CdmAdapter::SetServerCertificate(uint32_t promise_id,
402 pp::VarArrayBuffer server_certificate) {
403 const uint8_t* server_certificate_ptr =
404 static_cast<const uint8_t*>(server_certificate.Map());
405 const uint32_t server_certificate_size = server_certificate.ByteLength();
407 if (!server_certificate_ptr ||
408 server_certificate_size < media::limits::kMinCertificateLength ||
409 server_certificate_size > media::limits::kMaxCertificateLength) {
410 RejectPromise(
411 promise_id, cdm::kInvalidAccessError, 0, "Incorrect certificate.");
412 return;
415 // Initialize() doesn't report an error, so SetServerCertificate() can be
416 // called even if Initialize() failed.
417 // TODO(jrummell): Remove this code when prefixed EME gets removed.
418 if (!cdm_) {
419 RejectPromise(promise_id,
420 cdm::kInvalidStateError,
422 "CDM has not been initialized.");
423 return;
426 cdm_->SetServerCertificate(
427 promise_id, server_certificate_ptr, server_certificate_size);
430 void CdmAdapter::CreateSessionAndGenerateRequest(uint32_t promise_id,
431 PP_SessionType session_type,
432 PP_InitDataType init_data_type,
433 pp::VarArrayBuffer init_data) {
434 // Initialize() doesn't report an error, so CreateSession() can be called
435 // even if Initialize() failed.
436 // TODO(jrummell): Remove this code when prefixed EME gets removed.
437 // TODO(jrummell): Verify that Initialize() failing does not resolve the
438 // MediaKeys.create() promise.
439 if (!cdm_) {
440 RejectPromise(promise_id,
441 cdm::kInvalidStateError,
443 "CDM has not been initialized.");
444 return;
447 cdm_->CreateSessionAndGenerateRequest(
448 promise_id, PpSessionTypeToCdmSessionType(session_type),
449 PpInitDataTypeToCdmInitDataType(init_data_type),
450 static_cast<const uint8_t*>(init_data.Map()), init_data.ByteLength());
453 void CdmAdapter::LoadSession(uint32_t promise_id,
454 PP_SessionType session_type,
455 const std::string& session_id) {
456 // Initialize() doesn't report an error, so LoadSession() can be called
457 // even if Initialize() failed.
458 // TODO(jrummell): Remove this code when prefixed EME gets removed.
459 // TODO(jrummell): Verify that Initialize() failing does not resolve the
460 // MediaKeys.create() promise.
461 if (!cdm_) {
462 RejectPromise(promise_id,
463 cdm::kInvalidStateError,
465 "CDM has not been initialized.");
466 return;
469 cdm_->LoadSession(promise_id, PpSessionTypeToCdmSessionType(session_type),
470 session_id.data(), session_id.size());
473 void CdmAdapter::UpdateSession(uint32_t promise_id,
474 const std::string& session_id,
475 pp::VarArrayBuffer response) {
476 const uint8_t* response_ptr = static_cast<const uint8_t*>(response.Map());
477 const uint32_t response_size = response.ByteLength();
479 PP_DCHECK(!session_id.empty());
480 PP_DCHECK(response_ptr);
481 PP_DCHECK(response_size > 0);
483 cdm_->UpdateSession(promise_id, session_id.data(), session_id.length(),
484 response_ptr, response_size);
487 void CdmAdapter::CloseSession(uint32_t promise_id,
488 const std::string& session_id) {
489 cdm_->CloseSession(promise_id, session_id.data(), session_id.length());
492 void CdmAdapter::RemoveSession(uint32_t promise_id,
493 const std::string& session_id) {
494 cdm_->RemoveSession(promise_id, session_id.data(), session_id.length());
497 // Note: In the following decryption/decoding related functions, errors are NOT
498 // reported via KeyError, but are reported via corresponding PPB calls.
500 void CdmAdapter::Decrypt(pp::Buffer_Dev encrypted_buffer,
501 const PP_EncryptedBlockInfo& encrypted_block_info) {
502 PP_DCHECK(!encrypted_buffer.is_null());
504 // Release a buffer that the caller indicated it is finished with.
505 allocator_.Release(encrypted_block_info.tracking_info.buffer_id);
507 cdm::Status status = cdm::kDecryptError;
508 LinkedDecryptedBlock decrypted_block(new DecryptedBlockImpl());
510 if (cdm_) {
511 cdm::InputBuffer input_buffer;
512 std::vector<cdm::SubsampleEntry> subsamples;
513 ConfigureInputBuffer(encrypted_buffer, encrypted_block_info, &subsamples,
514 &input_buffer);
515 status = cdm_->Decrypt(input_buffer, decrypted_block.get());
516 PP_DCHECK(status != cdm::kSuccess ||
517 (decrypted_block->DecryptedBuffer() &&
518 decrypted_block->DecryptedBuffer()->Size()));
521 CallOnMain(callback_factory_.NewCallback(
522 &CdmAdapter::DeliverBlock,
523 status,
524 decrypted_block,
525 encrypted_block_info.tracking_info));
528 void CdmAdapter::InitializeAudioDecoder(
529 const PP_AudioDecoderConfig& decoder_config,
530 pp::Buffer_Dev extra_data_buffer) {
531 PP_DCHECK(!deferred_initialize_audio_decoder_);
532 PP_DCHECK(deferred_audio_decoder_config_id_ == 0);
533 cdm::Status status = cdm::kSessionError;
534 if (cdm_) {
535 cdm::AudioDecoderConfig cdm_decoder_config;
536 cdm_decoder_config.codec =
537 PpAudioCodecToCdmAudioCodec(decoder_config.codec);
538 cdm_decoder_config.channel_count = decoder_config.channel_count;
539 cdm_decoder_config.bits_per_channel = decoder_config.bits_per_channel;
540 cdm_decoder_config.samples_per_second = decoder_config.samples_per_second;
541 cdm_decoder_config.extra_data =
542 static_cast<uint8_t*>(extra_data_buffer.data());
543 cdm_decoder_config.extra_data_size = extra_data_buffer.size();
544 status = cdm_->InitializeAudioDecoder(cdm_decoder_config);
547 if (status == cdm::kDeferredInitialization) {
548 deferred_initialize_audio_decoder_ = true;
549 deferred_audio_decoder_config_id_ = decoder_config.request_id;
550 return;
553 CallOnMain(callback_factory_.NewCallback(
554 &CdmAdapter::DecoderInitializeDone,
555 PP_DECRYPTORSTREAMTYPE_AUDIO,
556 decoder_config.request_id,
557 status == cdm::kSuccess));
560 void CdmAdapter::InitializeVideoDecoder(
561 const PP_VideoDecoderConfig& decoder_config,
562 pp::Buffer_Dev extra_data_buffer) {
563 PP_DCHECK(!deferred_initialize_video_decoder_);
564 PP_DCHECK(deferred_video_decoder_config_id_ == 0);
565 cdm::Status status = cdm::kSessionError;
566 if (cdm_) {
567 cdm::VideoDecoderConfig cdm_decoder_config;
568 cdm_decoder_config.codec =
569 PpVideoCodecToCdmVideoCodec(decoder_config.codec);
570 cdm_decoder_config.profile =
571 PpVCProfileToCdmVCProfile(decoder_config.profile);
572 cdm_decoder_config.format =
573 PpDecryptedFrameFormatToCdmVideoFormat(decoder_config.format);
574 cdm_decoder_config.coded_size.width = decoder_config.width;
575 cdm_decoder_config.coded_size.height = decoder_config.height;
576 cdm_decoder_config.extra_data =
577 static_cast<uint8_t*>(extra_data_buffer.data());
578 cdm_decoder_config.extra_data_size = extra_data_buffer.size();
579 status = cdm_->InitializeVideoDecoder(cdm_decoder_config);
582 if (status == cdm::kDeferredInitialization) {
583 deferred_initialize_video_decoder_ = true;
584 deferred_video_decoder_config_id_ = decoder_config.request_id;
585 return;
588 CallOnMain(callback_factory_.NewCallback(
589 &CdmAdapter::DecoderInitializeDone,
590 PP_DECRYPTORSTREAMTYPE_VIDEO,
591 decoder_config.request_id,
592 status == cdm::kSuccess));
595 void CdmAdapter::DeinitializeDecoder(PP_DecryptorStreamType decoder_type,
596 uint32_t request_id) {
597 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded.
598 if (cdm_) {
599 cdm_->DeinitializeDecoder(
600 PpDecryptorStreamTypeToCdmStreamType(decoder_type));
603 CallOnMain(callback_factory_.NewCallback(
604 &CdmAdapter::DecoderDeinitializeDone,
605 decoder_type,
606 request_id));
609 void CdmAdapter::ResetDecoder(PP_DecryptorStreamType decoder_type,
610 uint32_t request_id) {
611 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded.
612 if (cdm_)
613 cdm_->ResetDecoder(PpDecryptorStreamTypeToCdmStreamType(decoder_type));
615 CallOnMain(callback_factory_.NewCallback(&CdmAdapter::DecoderResetDone,
616 decoder_type,
617 request_id));
620 void CdmAdapter::DecryptAndDecode(
621 PP_DecryptorStreamType decoder_type,
622 pp::Buffer_Dev encrypted_buffer,
623 const PP_EncryptedBlockInfo& encrypted_block_info) {
624 PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded.
625 // Release a buffer that the caller indicated it is finished with.
626 allocator_.Release(encrypted_block_info.tracking_info.buffer_id);
628 cdm::InputBuffer input_buffer;
629 std::vector<cdm::SubsampleEntry> subsamples;
630 if (cdm_ && !encrypted_buffer.is_null()) {
631 ConfigureInputBuffer(encrypted_buffer,
632 encrypted_block_info,
633 &subsamples,
634 &input_buffer);
637 cdm::Status status = cdm::kDecodeError;
639 switch (decoder_type) {
640 case PP_DECRYPTORSTREAMTYPE_VIDEO: {
641 LinkedVideoFrame video_frame(new VideoFrameImpl());
642 if (cdm_)
643 status = cdm_->DecryptAndDecodeFrame(input_buffer, video_frame.get());
644 CallOnMain(callback_factory_.NewCallback(
645 &CdmAdapter::DeliverFrame,
646 status,
647 video_frame,
648 encrypted_block_info.tracking_info));
649 return;
652 case PP_DECRYPTORSTREAMTYPE_AUDIO: {
653 LinkedAudioFrames audio_frames(new AudioFramesImpl());
654 if (cdm_) {
655 status = cdm_->DecryptAndDecodeSamples(input_buffer,
656 audio_frames.get());
658 CallOnMain(callback_factory_.NewCallback(
659 &CdmAdapter::DeliverSamples,
660 status,
661 audio_frames,
662 encrypted_block_info.tracking_info));
663 return;
666 default:
667 PP_NOTREACHED();
668 return;
672 cdm::Buffer* CdmAdapter::Allocate(uint32_t capacity) {
673 return allocator_.Allocate(capacity);
676 void CdmAdapter::SetTimer(int64_t delay_ms, void* context) {
677 // NOTE: doesn't really need to run on the main thread; could just as well run
678 // on a helper thread if |cdm_| were thread-friendly and care was taken. We
679 // only use CallOnMainThread() here to get delayed-execution behavior.
680 pp::Module::Get()->core()->CallOnMainThread(
681 delay_ms,
682 callback_factory_.NewCallback(&CdmAdapter::TimerExpired, context),
683 PP_OK);
686 void CdmAdapter::TimerExpired(int32_t result, void* context) {
687 PP_DCHECK(result == PP_OK);
688 cdm_->TimerExpired(context);
691 cdm::Time CdmAdapter::GetCurrentWallTime() {
692 return pp::Module::Get()->core()->GetTime();
695 void CdmAdapter::OnResolveNewSessionPromise(uint32_t promise_id,
696 const char* session_id,
697 uint32_t session_id_size) {
698 PostOnMain(callback_factory_.NewCallback(
699 &CdmAdapter::SendPromiseResolvedWithSessionInternal, promise_id,
700 std::string(session_id, session_id_size)));
703 void CdmAdapter::OnResolvePromise(uint32_t promise_id) {
704 PostOnMain(callback_factory_.NewCallback(
705 &CdmAdapter::SendPromiseResolvedInternal, promise_id));
708 void CdmAdapter::OnRejectPromise(uint32_t promise_id,
709 cdm::Error error,
710 uint32_t system_code,
711 const char* error_message,
712 uint32_t error_message_size) {
713 // UMA to investigate http://crbug.com/410630
714 // TODO(xhwang): Remove after bug is fixed.
715 if (system_code == 0x27) {
716 pp::UMAPrivate uma_interface(this);
717 uma_interface.HistogramCustomCounts("Media.EME.CdmFileIO.FileSizeKBOnError",
718 last_read_file_size_kb_,
719 kSizeKBMin,
720 kSizeKBMax,
721 kSizeKBBuckets);
724 RejectPromise(promise_id, error, system_code,
725 std::string(error_message, error_message_size));
728 void CdmAdapter::RejectPromise(uint32_t promise_id,
729 cdm::Error error,
730 uint32_t system_code,
731 const std::string& error_message) {
732 PostOnMain(callback_factory_.NewCallback(
733 &CdmAdapter::SendPromiseRejectedInternal,
734 promise_id,
735 SessionError(error, system_code, error_message)));
738 void CdmAdapter::OnSessionMessage(const char* session_id,
739 uint32_t session_id_size,
740 cdm::MessageType message_type,
741 const char* message,
742 uint32_t message_size,
743 const char* legacy_destination_url,
744 uint32_t legacy_destination_url_size) {
745 // License requests should not specify |legacy_destination_url|.
746 // |legacy_destination_url| is not passed to unprefixed EME applications,
747 // so it can be removed when the prefixed API is removed.
748 PP_DCHECK(legacy_destination_url_size == 0 ||
749 message_type != cdm::MessageType::kLicenseRequest);
751 PostOnMain(callback_factory_.NewCallback(
752 &CdmAdapter::SendSessionMessageInternal,
753 SessionMessage(
754 std::string(session_id, session_id_size), message_type, message,
755 message_size,
756 std::string(legacy_destination_url, legacy_destination_url_size))));
759 void CdmAdapter::OnSessionKeysChange(const char* session_id,
760 uint32_t session_id_size,
761 bool has_additional_usable_key,
762 const cdm::KeyInformation* keys_info,
763 uint32_t keys_info_count) {
764 std::vector<PP_KeyInformation> key_information;
765 for (uint32_t i = 0; i < keys_info_count; ++i) {
766 const auto& key_info = keys_info[i];
767 PP_KeyInformation next_key = {};
769 if (key_info.key_id_size > sizeof(next_key.key_id)) {
770 PP_NOTREACHED();
771 continue;
774 // Copy key_id into |next_key|.
775 memcpy(next_key.key_id, key_info.key_id, key_info.key_id_size);
777 // Set remaining fields on |next_key|.
778 next_key.key_id_size = key_info.key_id_size;
779 next_key.key_status = CdmKeyStatusToPpKeyStatus(key_info.status);
780 next_key.system_code = key_info.system_code;
781 key_information.push_back(next_key);
784 PostOnMain(callback_factory_.NewCallback(
785 &CdmAdapter::SendSessionKeysChangeInternal,
786 std::string(session_id, session_id_size), has_additional_usable_key,
787 key_information));
790 void CdmAdapter::OnExpirationChange(const char* session_id,
791 uint32_t session_id_size,
792 cdm::Time new_expiry_time) {
793 PostOnMain(callback_factory_.NewCallback(
794 &CdmAdapter::SendExpirationChangeInternal,
795 std::string(session_id, session_id_size), new_expiry_time));
798 void CdmAdapter::OnSessionClosed(const char* session_id,
799 uint32_t session_id_size) {
800 PostOnMain(
801 callback_factory_.NewCallback(&CdmAdapter::SendSessionClosedInternal,
802 std::string(session_id, session_id_size)));
805 void CdmAdapter::OnLegacySessionError(const char* session_id,
806 uint32_t session_id_size,
807 cdm::Error error,
808 uint32_t system_code,
809 const char* error_message,
810 uint32_t error_message_size) {
811 PostOnMain(callback_factory_.NewCallback(
812 &CdmAdapter::SendSessionErrorInternal,
813 std::string(session_id, session_id_size),
814 SessionError(error, system_code,
815 std::string(error_message, error_message_size))));
818 // Helpers to pass the event to Pepper.
820 void CdmAdapter::SendPromiseResolvedInternal(int32_t result,
821 uint32_t promise_id) {
822 PP_DCHECK(result == PP_OK);
823 pp::ContentDecryptor_Private::PromiseResolved(promise_id);
826 void CdmAdapter::SendPromiseResolvedWithSessionInternal(
827 int32_t result,
828 uint32_t promise_id,
829 const std::string& session_id) {
830 PP_DCHECK(result == PP_OK);
831 pp::ContentDecryptor_Private::PromiseResolvedWithSession(promise_id,
832 session_id);
835 void CdmAdapter::SendPromiseRejectedInternal(int32_t result,
836 uint32_t promise_id,
837 const SessionError& error) {
838 PP_DCHECK(result == PP_OK);
839 pp::ContentDecryptor_Private::PromiseRejected(
840 promise_id,
841 CdmExceptionTypeToPpCdmExceptionType(error.error),
842 error.system_code,
843 error.error_description);
846 void CdmAdapter::SendSessionMessageInternal(int32_t result,
847 const SessionMessage& message) {
848 PP_DCHECK(result == PP_OK);
850 pp::VarArrayBuffer message_array_buffer(message.message.size());
851 if (message.message.size() > 0) {
852 memcpy(message_array_buffer.Map(), message.message.data(),
853 message.message.size());
856 pp::ContentDecryptor_Private::SessionMessage(
857 message.session_id, CdmMessageTypeToPpMessageType(message.message_type),
858 message_array_buffer, message.legacy_destination_url);
861 void CdmAdapter::SendSessionClosedInternal(int32_t result,
862 const std::string& session_id) {
863 PP_DCHECK(result == PP_OK);
864 pp::ContentDecryptor_Private::SessionClosed(session_id);
867 void CdmAdapter::SendSessionErrorInternal(int32_t result,
868 const std::string& session_id,
869 const SessionError& error) {
870 PP_DCHECK(result == PP_OK);
871 pp::ContentDecryptor_Private::LegacySessionError(
872 session_id, CdmExceptionTypeToPpCdmExceptionType(error.error),
873 error.system_code, error.error_description);
876 void CdmAdapter::SendSessionKeysChangeInternal(
877 int32_t result,
878 const std::string& session_id,
879 bool has_additional_usable_key,
880 const std::vector<PP_KeyInformation>& key_info) {
881 PP_DCHECK(result == PP_OK);
882 pp::ContentDecryptor_Private::SessionKeysChange(
883 session_id, has_additional_usable_key, key_info);
886 void CdmAdapter::SendExpirationChangeInternal(int32_t result,
887 const std::string& session_id,
888 cdm::Time new_expiry_time) {
889 PP_DCHECK(result == PP_OK);
890 pp::ContentDecryptor_Private::SessionExpirationChange(session_id,
891 new_expiry_time);
894 void CdmAdapter::DeliverBlock(int32_t result,
895 const cdm::Status& status,
896 const LinkedDecryptedBlock& decrypted_block,
897 const PP_DecryptTrackingInfo& tracking_info) {
898 PP_DCHECK(result == PP_OK);
899 PP_DecryptedBlockInfo decrypted_block_info = {};
900 decrypted_block_info.tracking_info = tracking_info;
901 decrypted_block_info.tracking_info.timestamp = decrypted_block->Timestamp();
902 decrypted_block_info.tracking_info.buffer_id = 0;
903 decrypted_block_info.data_size = 0;
904 decrypted_block_info.result = CdmStatusToPpDecryptResult(status);
906 pp::Buffer_Dev buffer;
908 if (decrypted_block_info.result == PP_DECRYPTRESULT_SUCCESS) {
909 PP_DCHECK(decrypted_block.get() && decrypted_block->DecryptedBuffer());
910 if (!decrypted_block.get() || !decrypted_block->DecryptedBuffer()) {
911 PP_NOTREACHED();
912 decrypted_block_info.result = PP_DECRYPTRESULT_DECRYPT_ERROR;
913 } else {
914 PpbBuffer* ppb_buffer =
915 static_cast<PpbBuffer*>(decrypted_block->DecryptedBuffer());
916 decrypted_block_info.tracking_info.buffer_id = ppb_buffer->buffer_id();
917 decrypted_block_info.data_size = ppb_buffer->Size();
919 buffer = ppb_buffer->TakeBuffer();
923 pp::ContentDecryptor_Private::DeliverBlock(buffer, decrypted_block_info);
926 void CdmAdapter::DecoderInitializeDone(int32_t result,
927 PP_DecryptorStreamType decoder_type,
928 uint32_t request_id,
929 bool success) {
930 PP_DCHECK(result == PP_OK);
931 pp::ContentDecryptor_Private::DecoderInitializeDone(decoder_type,
932 request_id,
933 success);
936 void CdmAdapter::DecoderDeinitializeDone(int32_t result,
937 PP_DecryptorStreamType decoder_type,
938 uint32_t request_id) {
939 pp::ContentDecryptor_Private::DecoderDeinitializeDone(decoder_type,
940 request_id);
943 void CdmAdapter::DecoderResetDone(int32_t result,
944 PP_DecryptorStreamType decoder_type,
945 uint32_t request_id) {
946 pp::ContentDecryptor_Private::DecoderResetDone(decoder_type, request_id);
949 void CdmAdapter::DeliverFrame(
950 int32_t result,
951 const cdm::Status& status,
952 const LinkedVideoFrame& video_frame,
953 const PP_DecryptTrackingInfo& tracking_info) {
954 PP_DCHECK(result == PP_OK);
955 PP_DecryptedFrameInfo decrypted_frame_info = {};
956 decrypted_frame_info.tracking_info.request_id = tracking_info.request_id;
957 decrypted_frame_info.tracking_info.buffer_id = 0;
958 decrypted_frame_info.result = CdmStatusToPpDecryptResult(status);
960 pp::Buffer_Dev buffer;
962 if (decrypted_frame_info.result == PP_DECRYPTRESULT_SUCCESS) {
963 if (!IsValidVideoFrame(video_frame)) {
964 PP_NOTREACHED();
965 decrypted_frame_info.result = PP_DECRYPTRESULT_DECODE_ERROR;
966 } else {
967 PpbBuffer* ppb_buffer =
968 static_cast<PpbBuffer*>(video_frame->FrameBuffer());
970 decrypted_frame_info.tracking_info.timestamp = video_frame->Timestamp();
971 decrypted_frame_info.tracking_info.buffer_id = ppb_buffer->buffer_id();
972 decrypted_frame_info.format =
973 CdmVideoFormatToPpDecryptedFrameFormat(video_frame->Format());
974 decrypted_frame_info.width = video_frame->Size().width;
975 decrypted_frame_info.height = video_frame->Size().height;
976 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_Y] =
977 video_frame->PlaneOffset(cdm::VideoFrame::kYPlane);
978 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_U] =
979 video_frame->PlaneOffset(cdm::VideoFrame::kUPlane);
980 decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_V] =
981 video_frame->PlaneOffset(cdm::VideoFrame::kVPlane);
982 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_Y] =
983 video_frame->Stride(cdm::VideoFrame::kYPlane);
984 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_U] =
985 video_frame->Stride(cdm::VideoFrame::kUPlane);
986 decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_V] =
987 video_frame->Stride(cdm::VideoFrame::kVPlane);
989 buffer = ppb_buffer->TakeBuffer();
993 pp::ContentDecryptor_Private::DeliverFrame(buffer, decrypted_frame_info);
996 void CdmAdapter::DeliverSamples(int32_t result,
997 const cdm::Status& status,
998 const LinkedAudioFrames& audio_frames,
999 const PP_DecryptTrackingInfo& tracking_info) {
1000 PP_DCHECK(result == PP_OK);
1002 PP_DecryptedSampleInfo decrypted_sample_info = {};
1003 decrypted_sample_info.tracking_info = tracking_info;
1004 decrypted_sample_info.tracking_info.timestamp = 0;
1005 decrypted_sample_info.tracking_info.buffer_id = 0;
1006 decrypted_sample_info.data_size = 0;
1007 decrypted_sample_info.result = CdmStatusToPpDecryptResult(status);
1009 pp::Buffer_Dev buffer;
1011 if (decrypted_sample_info.result == PP_DECRYPTRESULT_SUCCESS) {
1012 PP_DCHECK(audio_frames.get() && audio_frames->FrameBuffer());
1013 if (!audio_frames.get() || !audio_frames->FrameBuffer()) {
1014 PP_NOTREACHED();
1015 decrypted_sample_info.result = PP_DECRYPTRESULT_DECRYPT_ERROR;
1016 } else {
1017 PpbBuffer* ppb_buffer =
1018 static_cast<PpbBuffer*>(audio_frames->FrameBuffer());
1020 decrypted_sample_info.tracking_info.buffer_id = ppb_buffer->buffer_id();
1021 decrypted_sample_info.data_size = ppb_buffer->Size();
1022 decrypted_sample_info.format =
1023 CdmAudioFormatToPpDecryptedSampleFormat(audio_frames->Format());
1025 buffer = ppb_buffer->TakeBuffer();
1029 pp::ContentDecryptor_Private::DeliverSamples(buffer, decrypted_sample_info);
1032 bool CdmAdapter::IsValidVideoFrame(const LinkedVideoFrame& video_frame) {
1033 if (!video_frame.get() ||
1034 !video_frame->FrameBuffer() ||
1035 (video_frame->Format() != cdm::kI420 &&
1036 video_frame->Format() != cdm::kYv12)) {
1037 CDM_DLOG() << "Invalid video frame!";
1038 return false;
1041 PpbBuffer* ppb_buffer = static_cast<PpbBuffer*>(video_frame->FrameBuffer());
1043 for (uint32_t i = 0; i < cdm::VideoFrame::kMaxPlanes; ++i) {
1044 int plane_height = (i == cdm::VideoFrame::kYPlane) ?
1045 video_frame->Size().height : (video_frame->Size().height + 1) / 2;
1046 cdm::VideoFrame::VideoPlane plane =
1047 static_cast<cdm::VideoFrame::VideoPlane>(i);
1048 if (ppb_buffer->Size() < video_frame->PlaneOffset(plane) +
1049 plane_height * video_frame->Stride(plane)) {
1050 return false;
1054 return true;
1057 void CdmAdapter::OnFirstFileRead(int32_t file_size_bytes) {
1058 PP_DCHECK(IsMainThread());
1059 PP_DCHECK(file_size_bytes >= 0);
1061 last_read_file_size_kb_ = file_size_bytes / 1024;
1063 if (file_size_uma_reported_)
1064 return;
1066 pp::UMAPrivate uma_interface(this);
1067 uma_interface.HistogramCustomCounts(
1068 "Media.EME.CdmFileIO.FileSizeKBOnFirstRead",
1069 last_read_file_size_kb_,
1070 kSizeKBMin,
1071 kSizeKBMax,
1072 kSizeKBBuckets);
1073 file_size_uma_reported_ = true;
1076 #if !defined(NDEBUG)
1077 void CdmAdapter::LogToConsole(const pp::Var& value) {
1078 PP_DCHECK(IsMainThread());
1079 const PPB_Console* console = reinterpret_cast<const PPB_Console*>(
1080 pp::Module::Get()->GetBrowserInterface(PPB_CONSOLE_INTERFACE));
1081 console->Log(pp_instance(), PP_LOGLEVEL_LOG, value.pp_var());
1083 #endif // !defined(NDEBUG)
1085 void CdmAdapter::SendPlatformChallenge(const char* service_id,
1086 uint32_t service_id_size,
1087 const char* challenge,
1088 uint32_t challenge_size) {
1089 #if defined(OS_CHROMEOS)
1090 // If access to a distinctive identifier is not allowed, block platform
1091 // verification to prevent access to such an identifier.
1092 if (allow_distinctive_identifier_) {
1093 pp::VarArrayBuffer challenge_var(challenge_size);
1094 uint8_t* var_data = static_cast<uint8_t*>(challenge_var.Map());
1095 memcpy(var_data, challenge, challenge_size);
1097 std::string service_id_str(service_id, service_id_size);
1099 linked_ptr<PepperPlatformChallengeResponse> response(
1100 new PepperPlatformChallengeResponse());
1102 int32_t result = platform_verification_.ChallengePlatform(
1103 pp::Var(service_id_str),
1104 challenge_var,
1105 &response->signed_data,
1106 &response->signed_data_signature,
1107 &response->platform_key_certificate,
1108 callback_factory_.NewCallback(&CdmAdapter::SendPlatformChallengeDone,
1109 response));
1110 challenge_var.Unmap();
1111 if (result == PP_OK_COMPLETIONPENDING)
1112 return;
1114 // Fall through on error and issue an empty OnPlatformChallengeResponse().
1115 PP_DCHECK(result != PP_OK);
1117 #endif
1119 cdm::PlatformChallengeResponse platform_challenge_response = {};
1120 cdm_->OnPlatformChallengeResponse(platform_challenge_response);
1123 void CdmAdapter::EnableOutputProtection(uint32_t desired_protection_mask) {
1124 #if defined(OS_CHROMEOS)
1125 int32_t result = output_protection_.EnableProtection(
1126 desired_protection_mask, callback_factory_.NewCallback(
1127 &CdmAdapter::EnableProtectionDone));
1129 // Errors are ignored since clients must call QueryOutputProtectionStatus() to
1130 // inspect the protection status on a regular basis.
1132 if (result != PP_OK && result != PP_OK_COMPLETIONPENDING)
1133 CDM_DLOG() << __FUNCTION__ << " failed!";
1134 #endif
1137 void CdmAdapter::QueryOutputProtectionStatus() {
1138 #if defined(OS_CHROMEOS)
1139 PP_DCHECK(!query_output_protection_in_progress_);
1141 output_link_mask_ = output_protection_mask_ = 0;
1142 const int32_t result = output_protection_.QueryStatus(
1143 &output_link_mask_,
1144 &output_protection_mask_,
1145 callback_factory_.NewCallback(
1146 &CdmAdapter::QueryOutputProtectionStatusDone));
1147 if (result == PP_OK_COMPLETIONPENDING) {
1148 query_output_protection_in_progress_ = true;
1149 ReportOutputProtectionQuery();
1150 return;
1153 // Fall through on error and issue an empty OnQueryOutputProtectionStatus().
1154 PP_DCHECK(result != PP_OK);
1155 CDM_DLOG() << __FUNCTION__ << " failed, result = " << result;
1156 #endif
1157 cdm_->OnQueryOutputProtectionStatus(cdm::kQueryFailed, 0, 0);
1160 void CdmAdapter::OnDeferredInitializationDone(cdm::StreamType stream_type,
1161 cdm::Status decoder_status) {
1162 switch (stream_type) {
1163 case cdm::kStreamTypeAudio:
1164 PP_DCHECK(deferred_initialize_audio_decoder_);
1165 CallOnMain(
1166 callback_factory_.NewCallback(&CdmAdapter::DecoderInitializeDone,
1167 PP_DECRYPTORSTREAMTYPE_AUDIO,
1168 deferred_audio_decoder_config_id_,
1169 decoder_status == cdm::kSuccess));
1170 deferred_initialize_audio_decoder_ = false;
1171 deferred_audio_decoder_config_id_ = 0;
1172 break;
1173 case cdm::kStreamTypeVideo:
1174 PP_DCHECK(deferred_initialize_video_decoder_);
1175 CallOnMain(
1176 callback_factory_.NewCallback(&CdmAdapter::DecoderInitializeDone,
1177 PP_DECRYPTORSTREAMTYPE_VIDEO,
1178 deferred_video_decoder_config_id_,
1179 decoder_status == cdm::kSuccess));
1180 deferred_initialize_video_decoder_ = false;
1181 deferred_video_decoder_config_id_ = 0;
1182 break;
1186 // The CDM owns the returned object and must call FileIO::Close() to release it.
1187 cdm::FileIO* CdmAdapter::CreateFileIO(cdm::FileIOClient* client) {
1188 if (!allow_persistent_state_) {
1189 CDM_DLOG()
1190 << "Cannot create FileIO because persistent state is not allowed.";
1191 return nullptr;
1194 return new CdmFileIOImpl(
1195 client, pp_instance(),
1196 callback_factory_.NewCallback(&CdmAdapter::OnFirstFileRead));
1199 #if defined(OS_CHROMEOS)
1200 void CdmAdapter::ReportOutputProtectionUMA(OutputProtectionStatus status) {
1201 pp::UMAPrivate uma_interface(this);
1202 uma_interface.HistogramEnumeration(
1203 "Media.EME.OutputProtection", status, OUTPUT_PROTECTION_MAX);
1206 void CdmAdapter::ReportOutputProtectionQuery() {
1207 if (uma_for_output_protection_query_reported_)
1208 return;
1210 ReportOutputProtectionUMA(OUTPUT_PROTECTION_QUERIED);
1211 uma_for_output_protection_query_reported_ = true;
1214 void CdmAdapter::ReportOutputProtectionQueryResult() {
1215 if (uma_for_output_protection_positive_result_reported_)
1216 return;
1218 // Report UMAs for output protection query result.
1219 uint32_t external_links = (output_link_mask_ & ~cdm::kLinkTypeInternal);
1221 if (!external_links) {
1222 ReportOutputProtectionUMA(OUTPUT_PROTECTION_NO_EXTERNAL_LINK);
1223 uma_for_output_protection_positive_result_reported_ = true;
1224 return;
1227 const uint32_t kProtectableLinks =
1228 cdm::kLinkTypeHDMI | cdm::kLinkTypeDVI | cdm::kLinkTypeDisplayPort;
1229 bool is_unprotectable_link_connected = external_links & ~kProtectableLinks;
1230 bool is_hdcp_enabled_on_all_protectable_links =
1231 output_protection_mask_ & cdm::kProtectionHDCP;
1233 if (!is_unprotectable_link_connected &&
1234 is_hdcp_enabled_on_all_protectable_links) {
1235 ReportOutputProtectionUMA(
1236 OUTPUT_PROTECTION_ALL_EXTERNAL_LINKS_PROTECTED);
1237 uma_for_output_protection_positive_result_reported_ = true;
1238 return;
1241 // Do not report a negative result because it could be a false negative.
1242 // Instead, we will calculate number of negatives using the total number of
1243 // queries and success results.
1246 void CdmAdapter::SendPlatformChallengeDone(
1247 int32_t result,
1248 const linked_ptr<PepperPlatformChallengeResponse>& response) {
1249 if (result != PP_OK) {
1250 CDM_DLOG() << __FUNCTION__ << ": Platform challenge failed!";
1251 cdm::PlatformChallengeResponse platform_challenge_response = {};
1252 cdm_->OnPlatformChallengeResponse(platform_challenge_response);
1253 return;
1256 pp::VarArrayBuffer signed_data_var(response->signed_data);
1257 pp::VarArrayBuffer signed_data_signature_var(response->signed_data_signature);
1258 std::string platform_key_certificate_string =
1259 response->platform_key_certificate.AsString();
1261 cdm::PlatformChallengeResponse platform_challenge_response = {
1262 static_cast<uint8_t*>(signed_data_var.Map()),
1263 signed_data_var.ByteLength(),
1264 static_cast<uint8_t*>(signed_data_signature_var.Map()),
1265 signed_data_signature_var.ByteLength(),
1266 reinterpret_cast<const uint8_t*>(platform_key_certificate_string.data()),
1267 static_cast<uint32_t>(platform_key_certificate_string.length())};
1268 cdm_->OnPlatformChallengeResponse(platform_challenge_response);
1270 signed_data_var.Unmap();
1271 signed_data_signature_var.Unmap();
1274 void CdmAdapter::EnableProtectionDone(int32_t result) {
1275 // Does nothing since clients must call QueryOutputProtectionStatus() to
1276 // inspect the protection status on a regular basis.
1277 CDM_DLOG() << __FUNCTION__ << " : " << result;
1280 void CdmAdapter::QueryOutputProtectionStatusDone(int32_t result) {
1281 PP_DCHECK(query_output_protection_in_progress_);
1282 query_output_protection_in_progress_ = false;
1284 // Return a query status of failed on error.
1285 cdm::QueryResult query_result;
1286 if (result != PP_OK) {
1287 CDM_DLOG() << __FUNCTION__ << " failed, result = " << result;
1288 output_link_mask_ = output_protection_mask_ = 0;
1289 query_result = cdm::kQueryFailed;
1290 } else {
1291 query_result = cdm::kQuerySucceeded;
1292 ReportOutputProtectionQueryResult();
1295 cdm_->OnQueryOutputProtectionStatus(query_result, output_link_mask_,
1296 output_protection_mask_);
1298 #endif
1300 CdmAdapter::SessionError::SessionError(cdm::Error error,
1301 uint32_t system_code,
1302 const std::string& error_description)
1303 : error(error),
1304 system_code(system_code),
1305 error_description(error_description) {
1308 CdmAdapter::SessionMessage::SessionMessage(
1309 const std::string& session_id,
1310 cdm::MessageType message_type,
1311 const char* message,
1312 uint32_t message_size,
1313 const std::string& legacy_destination_url)
1314 : session_id(session_id),
1315 message_type(message_type),
1316 message(message, message + message_size),
1317 legacy_destination_url(legacy_destination_url) {
1320 void* GetCdmHost(int host_interface_version, void* user_data) {
1321 if (!host_interface_version || !user_data)
1322 return NULL;
1324 static_assert(
1325 cdm::ContentDecryptionModule::Host::kVersion == cdm::Host_8::kVersion,
1326 "update the code below");
1328 // Ensure IsSupportedCdmHostVersion matches implementation of this function.
1329 // Always update this DCHECK when updating this function.
1330 // If this check fails, update this function and DCHECK or update
1331 // IsSupportedCdmHostVersion.
1333 PP_DCHECK(
1334 // Future version is not supported.
1335 !IsSupportedCdmHostVersion(cdm::Host_8::kVersion + 1) &&
1336 // Current version is supported.
1337 IsSupportedCdmHostVersion(cdm::Host_8::kVersion) &&
1338 // Include all previous supported versions (if any) here.
1339 IsSupportedCdmHostVersion(cdm::Host_7::kVersion) &&
1340 // One older than the oldest supported version is not supported.
1341 !IsSupportedCdmHostVersion(cdm::Host_7::kVersion - 1));
1342 PP_DCHECK(IsSupportedCdmHostVersion(host_interface_version));
1344 CdmAdapter* cdm_adapter = static_cast<CdmAdapter*>(user_data);
1345 CDM_DLOG() << "Create CDM Host with version " << host_interface_version;
1346 switch (host_interface_version) {
1347 case cdm::Host_8::kVersion:
1348 return static_cast<cdm::Host_8*>(cdm_adapter);
1349 case cdm::Host_7::kVersion:
1350 return static_cast<cdm::Host_7*>(cdm_adapter);
1351 default:
1352 PP_NOTREACHED();
1353 return NULL;
1357 // This object is the global object representing this plugin library as long
1358 // as it is loaded.
1359 class CdmAdapterModule : public pp::Module {
1360 public:
1361 CdmAdapterModule() : pp::Module() {
1362 // This function blocks the renderer thread (PluginInstance::Initialize()).
1363 // Move this call to other places if this may be a concern in the future.
1364 INITIALIZE_CDM_MODULE();
1366 virtual ~CdmAdapterModule() {
1367 DeinitializeCdmModule();
1370 virtual pp::Instance* CreateInstance(PP_Instance instance) {
1371 return new CdmAdapter(instance, this);
1374 private:
1375 CdmFileIOImpl::ResourceTracker cdm_file_io_impl_resource_tracker;
1378 } // namespace media
1380 namespace pp {
1382 // Factory function for your specialization of the Module object.
1383 Module* CreateModule() {
1384 return new media::CdmAdapterModule();
1387 } // namespace pp