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