[ServiceWorker] Implement WebServiceWorkerContextClient::openWindow().
[chromium-blink-merge.git] / content / renderer / pepper / content_decryptor_delegate.cc
blob8be0fba8a08461ba7930315082aa5c6900f4f803
1 // Copyright (c) 2012 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 "content/renderer/pepper/content_decryptor_delegate.h"
7 #include "base/callback_helpers.h"
8 #include "base/message_loop/message_loop_proxy.h"
9 #include "base/metrics/sparse_histogram.h"
10 #include "base/numerics/safe_conversions.h"
11 #include "base/trace_event/trace_event.h"
12 #include "content/renderer/pepper/ppb_buffer_impl.h"
13 #include "media/base/audio_buffer.h"
14 #include "media/base/audio_decoder_config.h"
15 #include "media/base/bind_to_current_loop.h"
16 #include "media/base/cdm_key_information.h"
17 #include "media/base/channel_layout.h"
18 #include "media/base/data_buffer.h"
19 #include "media/base/decoder_buffer.h"
20 #include "media/base/decrypt_config.h"
21 #include "media/base/key_systems.h"
22 #include "media/base/limits.h"
23 #include "media/base/video_decoder_config.h"
24 #include "media/base/video_frame.h"
25 #include "media/base/video_util.h"
26 #include "ppapi/shared_impl/array_var.h"
27 #include "ppapi/shared_impl/scoped_pp_resource.h"
28 #include "ppapi/shared_impl/time_conversion.h"
29 #include "ppapi/shared_impl/var.h"
30 #include "ppapi/shared_impl/var_tracker.h"
31 #include "ppapi/thunk/enter.h"
32 #include "ppapi/thunk/ppb_buffer_api.h"
33 #include "ui/gfx/geometry/rect.h"
35 using media::Decryptor;
36 using media::MediaKeys;
37 using media::NewSessionCdmPromise;
38 using media::SimpleCdmPromise;
39 using ppapi::ArrayBufferVar;
40 using ppapi::ArrayVar;
41 using ppapi::PpapiGlobals;
42 using ppapi::ScopedPPResource;
43 using ppapi::StringVar;
44 using ppapi::thunk::EnterResourceNoLock;
45 using ppapi::thunk::PPB_Buffer_API;
47 namespace content {
49 namespace {
51 // Fills |resource| with a PPB_Buffer_Impl and copies |data| into the buffer
52 // resource. The |*resource|, if valid, will be in the ResourceTracker with a
53 // reference-count of 0. If |data| is NULL, sets |*resource| to NULL. Returns
54 // true upon success and false if any error happened.
55 bool MakeBufferResource(PP_Instance instance,
56 const uint8* data,
57 uint32_t size,
58 scoped_refptr<PPB_Buffer_Impl>* resource) {
59 TRACE_EVENT0("media", "ContentDecryptorDelegate - MakeBufferResource");
60 DCHECK(resource);
62 if (!data || !size) {
63 DCHECK(!data && !size);
64 resource = NULL;
65 return true;
68 scoped_refptr<PPB_Buffer_Impl> buffer(
69 PPB_Buffer_Impl::CreateResource(instance, size));
70 if (!buffer.get())
71 return false;
73 BufferAutoMapper mapper(buffer.get());
74 if (!mapper.data() || mapper.size() < size)
75 return false;
76 memcpy(mapper.data(), data, size);
78 *resource = buffer;
79 return true;
82 // Copies the content of |str| into |array|.
83 // Returns true if copy succeeded. Returns false if copy failed, e.g. if the
84 // |array_size| is smaller than the |str| length.
85 template <uint32_t array_size>
86 bool CopyStringToArray(const std::string& str, uint8 (&array)[array_size]) {
87 if (array_size < str.size())
88 return false;
90 memcpy(array, str.data(), str.size());
91 return true;
94 // Fills the |block_info| with information from |encrypted_buffer|.
96 // Returns true if |block_info| is successfully filled. Returns false
97 // otherwise.
98 bool MakeEncryptedBlockInfo(
99 const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
100 uint32_t request_id,
101 PP_EncryptedBlockInfo* block_info) {
102 // TODO(xhwang): Fix initialization of PP_EncryptedBlockInfo here and
103 // anywhere else.
104 memset(block_info, 0, sizeof(*block_info));
105 block_info->tracking_info.request_id = request_id;
107 // EOS buffers need a request ID and nothing more.
108 if (encrypted_buffer->end_of_stream())
109 return true;
111 DCHECK(encrypted_buffer->data_size())
112 << "DecryptConfig is set on an empty buffer";
114 block_info->tracking_info.timestamp =
115 encrypted_buffer->timestamp().InMicroseconds();
116 block_info->data_size = encrypted_buffer->data_size();
118 const media::DecryptConfig* decrypt_config =
119 encrypted_buffer->decrypt_config();
121 if (!CopyStringToArray(decrypt_config->key_id(), block_info->key_id) ||
122 !CopyStringToArray(decrypt_config->iv(), block_info->iv))
123 return false;
125 block_info->key_id_size = decrypt_config->key_id().size();
126 block_info->iv_size = decrypt_config->iv().size();
128 if (decrypt_config->subsamples().size() > arraysize(block_info->subsamples))
129 return false;
131 block_info->num_subsamples = decrypt_config->subsamples().size();
132 for (uint32_t i = 0; i < block_info->num_subsamples; ++i) {
133 block_info->subsamples[i].clear_bytes =
134 decrypt_config->subsamples()[i].clear_bytes;
135 block_info->subsamples[i].cipher_bytes =
136 decrypt_config->subsamples()[i].cypher_bytes;
139 return true;
142 PP_AudioCodec MediaAudioCodecToPpAudioCodec(media::AudioCodec codec) {
143 switch (codec) {
144 case media::kCodecVorbis:
145 return PP_AUDIOCODEC_VORBIS;
146 case media::kCodecAAC:
147 return PP_AUDIOCODEC_AAC;
148 default:
149 return PP_AUDIOCODEC_UNKNOWN;
153 PP_VideoCodec MediaVideoCodecToPpVideoCodec(media::VideoCodec codec) {
154 switch (codec) {
155 case media::kCodecVP8:
156 return PP_VIDEOCODEC_VP8;
157 case media::kCodecH264:
158 return PP_VIDEOCODEC_H264;
159 case media::kCodecVP9:
160 return PP_VIDEOCODEC_VP9;
161 default:
162 return PP_VIDEOCODEC_UNKNOWN;
166 PP_VideoCodecProfile MediaVideoCodecProfileToPpVideoCodecProfile(
167 media::VideoCodecProfile profile) {
168 switch (profile) {
169 case media::VP8PROFILE_ANY:
170 case media::VP9PROFILE_ANY:
171 return PP_VIDEOCODECPROFILE_NOT_NEEDED;
172 case media::H264PROFILE_BASELINE:
173 return PP_VIDEOCODECPROFILE_H264_BASELINE;
174 case media::H264PROFILE_MAIN:
175 return PP_VIDEOCODECPROFILE_H264_MAIN;
176 case media::H264PROFILE_EXTENDED:
177 return PP_VIDEOCODECPROFILE_H264_EXTENDED;
178 case media::H264PROFILE_HIGH:
179 return PP_VIDEOCODECPROFILE_H264_HIGH;
180 case media::H264PROFILE_HIGH10PROFILE:
181 return PP_VIDEOCODECPROFILE_H264_HIGH_10;
182 case media::H264PROFILE_HIGH422PROFILE:
183 return PP_VIDEOCODECPROFILE_H264_HIGH_422;
184 case media::H264PROFILE_HIGH444PREDICTIVEPROFILE:
185 return PP_VIDEOCODECPROFILE_H264_HIGH_444_PREDICTIVE;
186 default:
187 return PP_VIDEOCODECPROFILE_UNKNOWN;
191 PP_DecryptedFrameFormat MediaVideoFormatToPpDecryptedFrameFormat(
192 media::VideoFrame::Format format) {
193 switch (format) {
194 case media::VideoFrame::YV12:
195 return PP_DECRYPTEDFRAMEFORMAT_YV12;
196 case media::VideoFrame::I420:
197 return PP_DECRYPTEDFRAMEFORMAT_I420;
198 default:
199 return PP_DECRYPTEDFRAMEFORMAT_UNKNOWN;
203 Decryptor::Status PpDecryptResultToMediaDecryptorStatus(
204 PP_DecryptResult result) {
205 switch (result) {
206 case PP_DECRYPTRESULT_SUCCESS:
207 return Decryptor::kSuccess;
208 case PP_DECRYPTRESULT_DECRYPT_NOKEY:
209 return Decryptor::kNoKey;
210 case PP_DECRYPTRESULT_NEEDMOREDATA:
211 return Decryptor::kNeedMoreData;
212 case PP_DECRYPTRESULT_DECRYPT_ERROR:
213 return Decryptor::kError;
214 case PP_DECRYPTRESULT_DECODE_ERROR:
215 return Decryptor::kError;
216 default:
217 NOTREACHED();
218 return Decryptor::kError;
222 PP_DecryptorStreamType MediaDecryptorStreamTypeToPpStreamType(
223 Decryptor::StreamType stream_type) {
224 switch (stream_type) {
225 case Decryptor::kAudio:
226 return PP_DECRYPTORSTREAMTYPE_AUDIO;
227 case Decryptor::kVideo:
228 return PP_DECRYPTORSTREAMTYPE_VIDEO;
229 default:
230 NOTREACHED();
231 return PP_DECRYPTORSTREAMTYPE_VIDEO;
235 media::SampleFormat PpDecryptedSampleFormatToMediaSampleFormat(
236 PP_DecryptedSampleFormat result) {
237 switch (result) {
238 case PP_DECRYPTEDSAMPLEFORMAT_U8:
239 return media::kSampleFormatU8;
240 case PP_DECRYPTEDSAMPLEFORMAT_S16:
241 return media::kSampleFormatS16;
242 case PP_DECRYPTEDSAMPLEFORMAT_S32:
243 return media::kSampleFormatS32;
244 case PP_DECRYPTEDSAMPLEFORMAT_F32:
245 return media::kSampleFormatF32;
246 case PP_DECRYPTEDSAMPLEFORMAT_PLANAR_S16:
247 return media::kSampleFormatPlanarS16;
248 case PP_DECRYPTEDSAMPLEFORMAT_PLANAR_F32:
249 return media::kSampleFormatPlanarF32;
250 default:
251 NOTREACHED();
252 return media::kUnknownSampleFormat;
256 PP_SessionType MediaSessionTypeToPpSessionType(
257 MediaKeys::SessionType session_type) {
258 switch (session_type) {
259 case MediaKeys::TEMPORARY_SESSION:
260 return PP_SESSIONTYPE_TEMPORARY;
261 case MediaKeys::PERSISTENT_LICENSE_SESSION:
262 return PP_SESSIONTYPE_PERSISTENT_LICENSE;
263 case MediaKeys::PERSISTENT_RELEASE_MESSAGE_SESSION:
264 return PP_SESSIONTYPE_PERSISTENT_RELEASE;
265 default:
266 NOTREACHED();
267 return PP_SESSIONTYPE_TEMPORARY;
271 MediaKeys::Exception PpExceptionTypeToMediaException(
272 PP_CdmExceptionCode exception_code) {
273 switch (exception_code) {
274 case PP_CDMEXCEPTIONCODE_NOTSUPPORTEDERROR:
275 return MediaKeys::NOT_SUPPORTED_ERROR;
276 case PP_CDMEXCEPTIONCODE_INVALIDSTATEERROR:
277 return MediaKeys::INVALID_STATE_ERROR;
278 case PP_CDMEXCEPTIONCODE_INVALIDACCESSERROR:
279 return MediaKeys::INVALID_ACCESS_ERROR;
280 case PP_CDMEXCEPTIONCODE_QUOTAEXCEEDEDERROR:
281 return MediaKeys::QUOTA_EXCEEDED_ERROR;
282 case PP_CDMEXCEPTIONCODE_UNKNOWNERROR:
283 return MediaKeys::UNKNOWN_ERROR;
284 case PP_CDMEXCEPTIONCODE_CLIENTERROR:
285 return MediaKeys::CLIENT_ERROR;
286 case PP_CDMEXCEPTIONCODE_OUTPUTERROR:
287 return MediaKeys::OUTPUT_ERROR;
288 default:
289 NOTREACHED();
290 return MediaKeys::UNKNOWN_ERROR;
294 media::CdmKeyInformation::KeyStatus PpCdmKeyStatusToCdmKeyInformationKeyStatus(
295 PP_CdmKeyStatus status) {
296 switch (status) {
297 case PP_CDMKEYSTATUS_USABLE:
298 return media::CdmKeyInformation::USABLE;
299 case PP_CDMKEYSTATUS_INVALID:
300 return media::CdmKeyInformation::INTERNAL_ERROR;
301 case PP_CDMKEYSTATUS_EXPIRED:
302 return media::CdmKeyInformation::EXPIRED;
303 case PP_CDMKEYSTATUS_OUTPUTNOTALLOWED:
304 return media::CdmKeyInformation::OUTPUT_NOT_ALLOWED;
305 default:
306 NOTREACHED();
307 return media::CdmKeyInformation::INTERNAL_ERROR;
311 MediaKeys::MessageType PpCdmMessageTypeToMediaMessageType(
312 PP_CdmMessageType message_type) {
313 switch (message_type) {
314 case PP_CDMMESSAGETYPE_LICENSE_REQUEST:
315 return MediaKeys::LICENSE_REQUEST;
316 case PP_CDMMESSAGETYPE_LICENSE_RENEWAL:
317 return MediaKeys::LICENSE_RENEWAL;
318 case PP_CDMMESSAGETYPE_LICENSE_RELEASE:
319 return MediaKeys::LICENSE_RELEASE;
320 default:
321 NOTREACHED();
322 return MediaKeys::LICENSE_REQUEST;
326 // TODO(xhwang): Unify EME UMA reporting code when prefixed EME is deprecated.
327 // See http://crbug.com/412987 for details.
328 void ReportSystemCodeUMA(const std::string& key_system, uint32 system_code) {
329 // Sparse histogram macro does not cache the histogram, so it's safe to use
330 // macro with non-static histogram name here.
331 UMA_HISTOGRAM_SPARSE_SLOWLY(
332 "Media.EME." + media::GetKeySystemNameForUMA(key_system) + ".SystemCode",
333 system_code);
336 } // namespace
338 ContentDecryptorDelegate::ContentDecryptorDelegate(
339 PP_Instance pp_instance,
340 const PPP_ContentDecryptor_Private* plugin_decryption_interface)
341 : pp_instance_(pp_instance),
342 plugin_decryption_interface_(plugin_decryption_interface),
343 next_decryption_request_id_(1),
344 audio_samples_per_second_(0),
345 audio_channel_count_(0),
346 audio_channel_layout_(media::CHANNEL_LAYOUT_NONE),
347 weak_ptr_factory_(this) {
348 weak_this_ = weak_ptr_factory_.GetWeakPtr();
351 ContentDecryptorDelegate::~ContentDecryptorDelegate() {
352 SatisfyAllPendingCallbacksOnError();
355 // TODO(jrummell): Remove |session_ready_cb| and |session_keys_change_cb|.
356 void ContentDecryptorDelegate::Initialize(
357 const std::string& key_system,
358 const media::SessionMessageCB& session_message_cb,
359 const media::SessionClosedCB& session_closed_cb,
360 const media::SessionErrorCB& session_error_cb,
361 const media::SessionKeysChangeCB& session_keys_change_cb,
362 const media::SessionExpirationUpdateCB& session_expiration_update_cb,
363 const base::Closure& fatal_plugin_error_cb) {
364 DCHECK(!key_system.empty());
365 DCHECK(key_system_.empty());
366 key_system_ = key_system;
368 session_message_cb_ = session_message_cb;
369 session_closed_cb_ = session_closed_cb;
370 session_error_cb_ = session_error_cb;
371 session_keys_change_cb_ = session_keys_change_cb;
372 session_expiration_update_cb_ = session_expiration_update_cb;
373 fatal_plugin_error_cb_ = fatal_plugin_error_cb;
375 plugin_decryption_interface_->Initialize(
376 pp_instance_, StringVar::StringToPPVar(key_system_));
379 void ContentDecryptorDelegate::InstanceCrashed() {
380 fatal_plugin_error_cb_.Run();
381 SatisfyAllPendingCallbacksOnError();
384 void ContentDecryptorDelegate::SetServerCertificate(
385 const uint8_t* certificate,
386 uint32_t certificate_length,
387 scoped_ptr<media::SimpleCdmPromise> promise) {
388 if (!certificate ||
389 certificate_length < media::limits::kMinCertificateLength ||
390 certificate_length > media::limits::kMaxCertificateLength) {
391 promise->reject(
392 media::MediaKeys::INVALID_ACCESS_ERROR, 0, "Incorrect certificate.");
393 return;
396 uint32_t promise_id = cdm_promise_adapter_.SavePromise(promise.Pass());
397 PP_Var certificate_array =
398 PpapiGlobals::Get()->GetVarTracker()->MakeArrayBufferPPVar(
399 certificate_length, certificate);
400 plugin_decryption_interface_->SetServerCertificate(
401 pp_instance_, promise_id, certificate_array);
404 void ContentDecryptorDelegate::CreateSessionAndGenerateRequest(
405 MediaKeys::SessionType session_type,
406 const std::string& init_data_type,
407 const uint8* init_data,
408 int init_data_length,
409 scoped_ptr<NewSessionCdmPromise> promise) {
410 uint32_t promise_id = cdm_promise_adapter_.SavePromise(promise.Pass());
411 PP_Var init_data_array =
412 PpapiGlobals::Get()->GetVarTracker()->MakeArrayBufferPPVar(
413 init_data_length, init_data);
414 plugin_decryption_interface_->CreateSessionAndGenerateRequest(
415 pp_instance_, promise_id, MediaSessionTypeToPpSessionType(session_type),
416 StringVar::StringToPPVar(init_data_type), init_data_array);
419 void ContentDecryptorDelegate::LoadSession(
420 media::MediaKeys::SessionType session_type,
421 const std::string& session_id,
422 scoped_ptr<NewSessionCdmPromise> promise) {
423 uint32_t promise_id = cdm_promise_adapter_.SavePromise(promise.Pass());
424 plugin_decryption_interface_->LoadSession(
425 pp_instance_, promise_id, MediaSessionTypeToPpSessionType(session_type),
426 StringVar::StringToPPVar(session_id));
429 void ContentDecryptorDelegate::UpdateSession(
430 const std::string& session_id,
431 const uint8* response,
432 int response_length,
433 scoped_ptr<SimpleCdmPromise> promise) {
434 uint32_t promise_id = cdm_promise_adapter_.SavePromise(promise.Pass());
435 PP_Var response_array =
436 PpapiGlobals::Get()->GetVarTracker()->MakeArrayBufferPPVar(
437 response_length, response);
438 plugin_decryption_interface_->UpdateSession(
439 pp_instance_, promise_id, StringVar::StringToPPVar(session_id),
440 response_array);
443 void ContentDecryptorDelegate::CloseSession(
444 const std::string& session_id,
445 scoped_ptr<SimpleCdmPromise> promise) {
446 if (session_id.length() > media::limits::kMaxSessionIdLength) {
447 promise->reject(
448 media::MediaKeys::INVALID_ACCESS_ERROR, 0, "Incorrect session.");
449 return;
452 uint32_t promise_id = cdm_promise_adapter_.SavePromise(promise.Pass());
453 plugin_decryption_interface_->CloseSession(
454 pp_instance_, promise_id, StringVar::StringToPPVar(session_id));
457 void ContentDecryptorDelegate::RemoveSession(
458 const std::string& session_id,
459 scoped_ptr<SimpleCdmPromise> promise) {
460 if (session_id.length() > media::limits::kMaxSessionIdLength) {
461 promise->reject(
462 media::MediaKeys::INVALID_ACCESS_ERROR, 0, "Incorrect session.");
463 return;
466 uint32_t promise_id = cdm_promise_adapter_.SavePromise(promise.Pass());
467 plugin_decryption_interface_->RemoveSession(
468 pp_instance_, promise_id, StringVar::StringToPPVar(session_id));
471 // TODO(xhwang): Remove duplication of code in Decrypt(),
472 // DecryptAndDecodeAudio() and DecryptAndDecodeVideo().
473 bool ContentDecryptorDelegate::Decrypt(
474 Decryptor::StreamType stream_type,
475 const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
476 const Decryptor::DecryptCB& decrypt_cb) {
477 DVLOG(3) << "Decrypt() - stream_type: " << stream_type;
479 // |{audio|video}_input_resource_| is not being used by the plugin
480 // now because there is only one pending audio/video decrypt request at any
481 // time. This is enforced by the media pipeline.
482 scoped_refptr<PPB_Buffer_Impl> encrypted_resource;
483 if (!MakeMediaBufferResource(
484 stream_type, encrypted_buffer, &encrypted_resource) ||
485 !encrypted_resource.get()) {
486 return false;
488 ScopedPPResource pp_resource(encrypted_resource.get());
490 const uint32_t request_id = next_decryption_request_id_++;
491 DVLOG(2) << "Decrypt() - request_id " << request_id;
493 PP_EncryptedBlockInfo block_info = {};
494 DCHECK(encrypted_buffer->decrypt_config());
495 if (!MakeEncryptedBlockInfo(encrypted_buffer, request_id, &block_info)) {
496 return false;
499 // There is only one pending decrypt request at any time per stream. This is
500 // enforced by the media pipeline.
501 switch (stream_type) {
502 case Decryptor::kAudio:
503 audio_decrypt_cb_.Set(request_id, decrypt_cb);
504 break;
505 case Decryptor::kVideo:
506 video_decrypt_cb_.Set(request_id, decrypt_cb);
507 break;
508 default:
509 NOTREACHED();
510 return false;
513 SetBufferToFreeInTrackingInfo(&block_info.tracking_info);
515 plugin_decryption_interface_->Decrypt(pp_instance_, pp_resource, &block_info);
516 return true;
519 bool ContentDecryptorDelegate::CancelDecrypt(
520 Decryptor::StreamType stream_type) {
521 DVLOG(3) << "CancelDecrypt() - stream_type: " << stream_type;
523 Decryptor::DecryptCB decrypt_cb;
524 switch (stream_type) {
525 case Decryptor::kAudio:
526 // Release the shared memory as it can still be in use by the plugin.
527 // The next Decrypt() call will need to allocate a new shared memory
528 // buffer.
529 audio_input_resource_ = NULL;
530 decrypt_cb = audio_decrypt_cb_.ResetAndReturn();
531 break;
532 case Decryptor::kVideo:
533 // Release the shared memory as it can still be in use by the plugin.
534 // The next Decrypt() call will need to allocate a new shared memory
535 // buffer.
536 video_input_resource_ = NULL;
537 decrypt_cb = video_decrypt_cb_.ResetAndReturn();
538 break;
539 default:
540 NOTREACHED();
541 return false;
544 if (!decrypt_cb.is_null())
545 decrypt_cb.Run(Decryptor::kSuccess, NULL);
547 return true;
550 bool ContentDecryptorDelegate::InitializeAudioDecoder(
551 const media::AudioDecoderConfig& decoder_config,
552 const Decryptor::DecoderInitCB& init_cb) {
553 PP_AudioDecoderConfig pp_decoder_config;
554 pp_decoder_config.codec =
555 MediaAudioCodecToPpAudioCodec(decoder_config.codec());
556 pp_decoder_config.channel_count =
557 media::ChannelLayoutToChannelCount(decoder_config.channel_layout());
558 pp_decoder_config.bits_per_channel = decoder_config.bits_per_channel();
559 pp_decoder_config.samples_per_second = decoder_config.samples_per_second();
560 pp_decoder_config.request_id = next_decryption_request_id_++;
562 audio_samples_per_second_ = pp_decoder_config.samples_per_second;
563 audio_channel_count_ = pp_decoder_config.channel_count;
564 audio_channel_layout_ = decoder_config.channel_layout();
566 scoped_refptr<PPB_Buffer_Impl> extra_data_resource;
567 if (!MakeBufferResource(pp_instance_,
568 decoder_config.extra_data(),
569 decoder_config.extra_data_size(),
570 &extra_data_resource)) {
571 return false;
573 ScopedPPResource pp_resource(extra_data_resource.get());
575 audio_decoder_init_cb_.Set(pp_decoder_config.request_id, init_cb);
576 plugin_decryption_interface_->InitializeAudioDecoder(
577 pp_instance_, &pp_decoder_config, pp_resource);
578 return true;
581 bool ContentDecryptorDelegate::InitializeVideoDecoder(
582 const media::VideoDecoderConfig& decoder_config,
583 const Decryptor::DecoderInitCB& init_cb) {
584 PP_VideoDecoderConfig pp_decoder_config;
585 pp_decoder_config.codec =
586 MediaVideoCodecToPpVideoCodec(decoder_config.codec());
587 pp_decoder_config.profile =
588 MediaVideoCodecProfileToPpVideoCodecProfile(decoder_config.profile());
589 pp_decoder_config.format =
590 MediaVideoFormatToPpDecryptedFrameFormat(decoder_config.format());
591 pp_decoder_config.width = decoder_config.coded_size().width();
592 pp_decoder_config.height = decoder_config.coded_size().height();
593 pp_decoder_config.request_id = next_decryption_request_id_++;
595 scoped_refptr<PPB_Buffer_Impl> extra_data_resource;
596 if (!MakeBufferResource(pp_instance_,
597 decoder_config.extra_data(),
598 decoder_config.extra_data_size(),
599 &extra_data_resource)) {
600 return false;
602 ScopedPPResource pp_resource(extra_data_resource.get());
604 video_decoder_init_cb_.Set(pp_decoder_config.request_id, init_cb);
605 natural_size_ = decoder_config.natural_size();
607 plugin_decryption_interface_->InitializeVideoDecoder(
608 pp_instance_, &pp_decoder_config, pp_resource);
609 return true;
612 bool ContentDecryptorDelegate::DeinitializeDecoder(
613 Decryptor::StreamType stream_type) {
614 CancelDecode(stream_type);
616 if (stream_type == Decryptor::kVideo)
617 natural_size_ = gfx::Size();
619 // TODO(tomfinegan): Add decoder deinitialize request tracking, and get
620 // stream type from media stack.
621 plugin_decryption_interface_->DeinitializeDecoder(
622 pp_instance_, MediaDecryptorStreamTypeToPpStreamType(stream_type), 0);
623 return true;
626 bool ContentDecryptorDelegate::ResetDecoder(Decryptor::StreamType stream_type) {
627 CancelDecode(stream_type);
629 // TODO(tomfinegan): Add decoder reset request tracking.
630 plugin_decryption_interface_->ResetDecoder(
631 pp_instance_, MediaDecryptorStreamTypeToPpStreamType(stream_type), 0);
632 return true;
635 bool ContentDecryptorDelegate::DecryptAndDecodeAudio(
636 const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
637 const Decryptor::AudioDecodeCB& audio_decode_cb) {
638 // |audio_input_resource_| is not being used by the plugin now
639 // because there is only one pending audio decode request at any time.
640 // This is enforced by the media pipeline.
641 scoped_refptr<PPB_Buffer_Impl> encrypted_resource;
642 if (!MakeMediaBufferResource(
643 Decryptor::kAudio, encrypted_buffer, &encrypted_resource)) {
644 return false;
647 // The resource should not be NULL for non-EOS buffer.
648 if (!encrypted_buffer->end_of_stream() && !encrypted_resource.get())
649 return false;
651 const uint32_t request_id = next_decryption_request_id_++;
652 DVLOG(2) << "DecryptAndDecodeAudio() - request_id " << request_id;
654 PP_EncryptedBlockInfo block_info = {};
655 if (!MakeEncryptedBlockInfo(encrypted_buffer, request_id, &block_info)) {
656 return false;
659 SetBufferToFreeInTrackingInfo(&block_info.tracking_info);
661 // There is only one pending audio decode request at any time. This is
662 // enforced by the media pipeline. If this DCHECK is violated, our buffer
663 // reuse policy is not valid, and we may have race problems for the shared
664 // buffer.
665 audio_decode_cb_.Set(request_id, audio_decode_cb);
667 ScopedPPResource pp_resource(encrypted_resource.get());
668 plugin_decryption_interface_->DecryptAndDecode(
669 pp_instance_, PP_DECRYPTORSTREAMTYPE_AUDIO, pp_resource, &block_info);
670 return true;
673 bool ContentDecryptorDelegate::DecryptAndDecodeVideo(
674 const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
675 const Decryptor::VideoDecodeCB& video_decode_cb) {
676 // |video_input_resource_| is not being used by the plugin now
677 // because there is only one pending video decode request at any time.
678 // This is enforced by the media pipeline.
679 scoped_refptr<PPB_Buffer_Impl> encrypted_resource;
680 if (!MakeMediaBufferResource(
681 Decryptor::kVideo, encrypted_buffer, &encrypted_resource)) {
682 return false;
685 // The resource should not be 0 for non-EOS buffer.
686 if (!encrypted_buffer->end_of_stream() && !encrypted_resource.get())
687 return false;
689 const uint32_t request_id = next_decryption_request_id_++;
690 DVLOG(2) << "DecryptAndDecodeVideo() - request_id " << request_id;
691 TRACE_EVENT_ASYNC_BEGIN0(
692 "media", "ContentDecryptorDelegate::DecryptAndDecodeVideo", request_id);
694 PP_EncryptedBlockInfo block_info = {};
695 if (!MakeEncryptedBlockInfo(encrypted_buffer, request_id, &block_info)) {
696 return false;
699 SetBufferToFreeInTrackingInfo(&block_info.tracking_info);
701 // Only one pending video decode request at any time. This is enforced by the
702 // media pipeline. If this DCHECK is violated, our buffer
703 // reuse policy is not valid, and we may have race problems for the shared
704 // buffer.
705 video_decode_cb_.Set(request_id, video_decode_cb);
707 // TODO(tomfinegan): Need to get stream type from media stack.
708 ScopedPPResource pp_resource(encrypted_resource.get());
709 plugin_decryption_interface_->DecryptAndDecode(
710 pp_instance_, PP_DECRYPTORSTREAMTYPE_VIDEO, pp_resource, &block_info);
711 return true;
714 void ContentDecryptorDelegate::OnPromiseResolved(uint32 promise_id) {
715 cdm_promise_adapter_.ResolvePromise(promise_id);
718 void ContentDecryptorDelegate::OnPromiseResolvedWithSession(uint32 promise_id,
719 PP_Var session_id) {
720 StringVar* session_id_string = StringVar::FromPPVar(session_id);
721 DCHECK(session_id_string);
722 cdm_promise_adapter_.ResolvePromise(promise_id, session_id_string->value());
725 void ContentDecryptorDelegate::OnPromiseRejected(
726 uint32 promise_id,
727 PP_CdmExceptionCode exception_code,
728 uint32 system_code,
729 PP_Var error_description) {
730 ReportSystemCodeUMA(key_system_, system_code);
732 StringVar* error_description_string = StringVar::FromPPVar(error_description);
733 DCHECK(error_description_string);
734 cdm_promise_adapter_.RejectPromise(
735 promise_id, PpExceptionTypeToMediaException(exception_code), system_code,
736 error_description_string->value());
739 void ContentDecryptorDelegate::OnSessionMessage(PP_Var session_id,
740 PP_CdmMessageType message_type,
741 PP_Var message,
742 PP_Var legacy_destination_url) {
743 if (session_message_cb_.is_null())
744 return;
746 StringVar* session_id_string = StringVar::FromPPVar(session_id);
747 DCHECK(session_id_string);
749 ArrayBufferVar* message_array_buffer = ArrayBufferVar::FromPPVar(message);
750 std::vector<uint8> message_vector;
751 if (message_array_buffer) {
752 const uint8* data = static_cast<const uint8*>(message_array_buffer->Map());
753 message_vector.assign(data, data + message_array_buffer->ByteLength());
756 StringVar* destination_url_string =
757 StringVar::FromPPVar(legacy_destination_url);
758 if (!destination_url_string) {
759 NOTREACHED();
760 return;
763 GURL verified_gurl = GURL(destination_url_string->value());
764 if (!verified_gurl.is_valid()) {
765 DLOG(WARNING) << "SessionMessage legacy_destination_url is invalid : "
766 << verified_gurl.possibly_invalid_spec();
767 verified_gurl = GURL::EmptyGURL(); // Replace invalid destination_url.
770 session_message_cb_.Run(session_id_string->value(),
771 PpCdmMessageTypeToMediaMessageType(message_type),
772 message_vector, verified_gurl);
775 void ContentDecryptorDelegate::OnSessionKeysChange(
776 PP_Var session_id,
777 PP_Bool has_additional_usable_key,
778 uint32_t key_count,
779 const struct PP_KeyInformation key_information[]) {
780 if (session_keys_change_cb_.is_null())
781 return;
783 StringVar* session_id_string = StringVar::FromPPVar(session_id);
784 DCHECK(session_id_string);
786 media::CdmKeysInfo keys_info;
787 keys_info.reserve(key_count);
788 for (uint32_t i = 0; i < key_count; ++i) {
789 scoped_ptr<media::CdmKeyInformation> key_info(new media::CdmKeyInformation);
790 const auto& info = key_information[i];
791 key_info->key_id.assign(info.key_id, info.key_id + info.key_id_size);
792 key_info->status =
793 PpCdmKeyStatusToCdmKeyInformationKeyStatus(info.key_status);
794 key_info->system_code = info.system_code;
795 keys_info.push_back(key_info.release());
798 session_keys_change_cb_.Run(session_id_string->value(),
799 PP_ToBool(has_additional_usable_key),
800 keys_info.Pass());
803 void ContentDecryptorDelegate::OnSessionExpirationChange(
804 PP_Var session_id,
805 PP_Time new_expiry_time) {
806 if (session_expiration_update_cb_.is_null())
807 return;
809 StringVar* session_id_string = StringVar::FromPPVar(session_id);
810 DCHECK(session_id_string);
812 session_expiration_update_cb_.Run(session_id_string->value(),
813 ppapi::PPTimeToTime(new_expiry_time));
816 void ContentDecryptorDelegate::OnSessionClosed(PP_Var session_id) {
817 if (session_closed_cb_.is_null())
818 return;
820 StringVar* session_id_string = StringVar::FromPPVar(session_id);
821 DCHECK(session_id_string);
823 session_closed_cb_.Run(session_id_string->value());
826 void ContentDecryptorDelegate::OnSessionError(
827 PP_Var session_id,
828 PP_CdmExceptionCode exception_code,
829 uint32 system_code,
830 PP_Var error_description) {
831 ReportSystemCodeUMA(key_system_, system_code);
833 if (session_error_cb_.is_null())
834 return;
836 StringVar* session_id_string = StringVar::FromPPVar(session_id);
837 DCHECK(session_id_string);
839 StringVar* error_description_string = StringVar::FromPPVar(error_description);
840 DCHECK(error_description_string);
842 session_error_cb_.Run(session_id_string->value(),
843 PpExceptionTypeToMediaException(exception_code),
844 system_code, error_description_string->value());
847 void ContentDecryptorDelegate::DecoderInitializeDone(
848 PP_DecryptorStreamType decoder_type,
849 uint32_t request_id,
850 PP_Bool success) {
851 if (decoder_type == PP_DECRYPTORSTREAMTYPE_AUDIO) {
852 // If the request ID is not valid or does not match what's saved, do
853 // nothing.
854 if (request_id == 0 || !audio_decoder_init_cb_.Matches(request_id))
855 return;
857 audio_decoder_init_cb_.ResetAndReturn().Run(PP_ToBool(success));
858 } else {
859 if (request_id == 0 || !video_decoder_init_cb_.Matches(request_id))
860 return;
862 if (!success)
863 natural_size_ = gfx::Size();
865 video_decoder_init_cb_.ResetAndReturn().Run(PP_ToBool(success));
869 void ContentDecryptorDelegate::DecoderDeinitializeDone(
870 PP_DecryptorStreamType decoder_type,
871 uint32_t request_id) {
872 // TODO(tomfinegan): Add decoder stop completion handling.
875 void ContentDecryptorDelegate::DecoderResetDone(
876 PP_DecryptorStreamType decoder_type,
877 uint32_t request_id) {
878 // TODO(tomfinegan): Add decoder reset completion handling.
881 void ContentDecryptorDelegate::DeliverBlock(
882 PP_Resource decrypted_block,
883 const PP_DecryptedBlockInfo* block_info) {
884 DCHECK(block_info);
886 FreeBuffer(block_info->tracking_info.buffer_id);
888 const uint32_t request_id = block_info->tracking_info.request_id;
889 DVLOG(2) << "DeliverBlock() - request_id: " << request_id;
891 // If the request ID is not valid or does not match what's saved, do nothing.
892 if (request_id == 0) {
893 DVLOG(1) << "DeliverBlock() - invalid request_id " << request_id;
894 return;
897 Decryptor::DecryptCB decrypt_cb;
898 if (audio_decrypt_cb_.Matches(request_id)) {
899 decrypt_cb = audio_decrypt_cb_.ResetAndReturn();
900 } else if (video_decrypt_cb_.Matches(request_id)) {
901 decrypt_cb = video_decrypt_cb_.ResetAndReturn();
902 } else {
903 DVLOG(1) << "DeliverBlock() - request_id " << request_id << " not found";
904 return;
907 Decryptor::Status status =
908 PpDecryptResultToMediaDecryptorStatus(block_info->result);
909 if (status != Decryptor::kSuccess) {
910 decrypt_cb.Run(status, NULL);
911 return;
914 EnterResourceNoLock<PPB_Buffer_API> enter(decrypted_block, true);
915 if (!enter.succeeded()) {
916 decrypt_cb.Run(Decryptor::kError, NULL);
917 return;
919 BufferAutoMapper mapper(enter.object());
920 if (!mapper.data() || !mapper.size() ||
921 mapper.size() < block_info->data_size) {
922 decrypt_cb.Run(Decryptor::kError, NULL);
923 return;
926 // TODO(tomfinegan): Find a way to take ownership of the shared memory
927 // managed by the PPB_Buffer_Dev, and avoid the extra copy.
928 scoped_refptr<media::DecoderBuffer> decrypted_buffer(
929 media::DecoderBuffer::CopyFrom(static_cast<uint8*>(mapper.data()),
930 block_info->data_size));
931 decrypted_buffer->set_timestamp(
932 base::TimeDelta::FromMicroseconds(block_info->tracking_info.timestamp));
933 decrypt_cb.Run(Decryptor::kSuccess, decrypted_buffer);
936 // Use a non-class-member function here so that if for some reason
937 // ContentDecryptorDelegate is destroyed before VideoFrame calls this callback,
938 // we can still get the shared memory unmapped.
939 static void BufferNoLongerNeeded(
940 const scoped_refptr<PPB_Buffer_Impl>& ppb_buffer,
941 base::Closure buffer_no_longer_needed_cb) {
942 ppb_buffer->Unmap();
943 buffer_no_longer_needed_cb.Run();
946 // Enters |resource|, maps shared memory and returns pointer of mapped data.
947 // Returns NULL if any error occurs.
948 static uint8* GetMappedBuffer(PP_Resource resource,
949 scoped_refptr<PPB_Buffer_Impl>* ppb_buffer) {
950 EnterResourceNoLock<PPB_Buffer_API> enter(resource, true);
951 if (!enter.succeeded())
952 return NULL;
954 uint8* mapped_data = static_cast<uint8*>(enter.object()->Map());
955 if (!enter.object()->IsMapped() || !mapped_data)
956 return NULL;
958 uint32_t mapped_size = 0;
959 if (!enter.object()->Describe(&mapped_size) || !mapped_size) {
960 enter.object()->Unmap();
961 return NULL;
964 *ppb_buffer = static_cast<PPB_Buffer_Impl*>(enter.object());
966 return mapped_data;
969 void ContentDecryptorDelegate::DeliverFrame(
970 PP_Resource decrypted_frame,
971 const PP_DecryptedFrameInfo* frame_info) {
972 DCHECK(frame_info);
974 const uint32_t request_id = frame_info->tracking_info.request_id;
975 DVLOG(2) << "DeliverFrame() - request_id: " << request_id;
977 // If the request ID is not valid or does not match what's saved, do nothing.
978 if (request_id == 0 || !video_decode_cb_.Matches(request_id)) {
979 DVLOG(1) << "DeliverFrame() - request_id " << request_id << " not found";
980 FreeBuffer(frame_info->tracking_info.buffer_id);
981 return;
984 TRACE_EVENT_ASYNC_END0(
985 "media", "ContentDecryptorDelegate::DecryptAndDecodeVideo", request_id);
987 Decryptor::VideoDecodeCB video_decode_cb = video_decode_cb_.ResetAndReturn();
989 Decryptor::Status status =
990 PpDecryptResultToMediaDecryptorStatus(frame_info->result);
991 if (status != Decryptor::kSuccess) {
992 DCHECK(!frame_info->tracking_info.buffer_id);
993 video_decode_cb.Run(status, NULL);
994 return;
997 scoped_refptr<PPB_Buffer_Impl> ppb_buffer;
998 uint8* frame_data = GetMappedBuffer(decrypted_frame, &ppb_buffer);
999 if (!frame_data) {
1000 FreeBuffer(frame_info->tracking_info.buffer_id);
1001 video_decode_cb.Run(Decryptor::kError, NULL);
1002 return;
1005 gfx::Size frame_size(frame_info->width, frame_info->height);
1006 DCHECK_EQ(frame_info->format, PP_DECRYPTEDFRAMEFORMAT_YV12);
1008 scoped_refptr<media::VideoFrame> decoded_frame =
1009 media::VideoFrame::WrapExternalYuvData(
1010 media::VideoFrame::YV12,
1011 frame_size,
1012 gfx::Rect(frame_size),
1013 natural_size_,
1014 frame_info->strides[PP_DECRYPTEDFRAMEPLANES_Y],
1015 frame_info->strides[PP_DECRYPTEDFRAMEPLANES_U],
1016 frame_info->strides[PP_DECRYPTEDFRAMEPLANES_V],
1017 frame_data + frame_info->plane_offsets[PP_DECRYPTEDFRAMEPLANES_Y],
1018 frame_data + frame_info->plane_offsets[PP_DECRYPTEDFRAMEPLANES_U],
1019 frame_data + frame_info->plane_offsets[PP_DECRYPTEDFRAMEPLANES_V],
1020 base::TimeDelta::FromMicroseconds(
1021 frame_info->tracking_info.timestamp),
1022 media::BindToCurrentLoop(
1023 base::Bind(&BufferNoLongerNeeded,
1024 ppb_buffer,
1025 base::Bind(&ContentDecryptorDelegate::FreeBuffer,
1026 weak_this_,
1027 frame_info->tracking_info.buffer_id))));
1029 video_decode_cb.Run(Decryptor::kSuccess, decoded_frame);
1032 void ContentDecryptorDelegate::DeliverSamples(
1033 PP_Resource audio_frames,
1034 const PP_DecryptedSampleInfo* sample_info) {
1035 DCHECK(sample_info);
1037 FreeBuffer(sample_info->tracking_info.buffer_id);
1039 const uint32_t request_id = sample_info->tracking_info.request_id;
1040 DVLOG(2) << "DeliverSamples() - request_id: " << request_id;
1042 // If the request ID is not valid or does not match what's saved, do nothing.
1043 if (request_id == 0 || !audio_decode_cb_.Matches(request_id)) {
1044 DVLOG(1) << "DeliverSamples() - request_id " << request_id << " not found";
1045 return;
1048 Decryptor::AudioDecodeCB audio_decode_cb = audio_decode_cb_.ResetAndReturn();
1050 const Decryptor::AudioFrames empty_frames;
1052 Decryptor::Status status =
1053 PpDecryptResultToMediaDecryptorStatus(sample_info->result);
1054 if (status != Decryptor::kSuccess) {
1055 audio_decode_cb.Run(status, empty_frames);
1056 return;
1059 media::SampleFormat sample_format =
1060 PpDecryptedSampleFormatToMediaSampleFormat(sample_info->format);
1062 Decryptor::AudioFrames audio_frame_list;
1063 if (!DeserializeAudioFrames(audio_frames,
1064 sample_info->data_size,
1065 sample_format,
1066 &audio_frame_list)) {
1067 NOTREACHED() << "CDM did not serialize the buffer correctly.";
1068 audio_decode_cb.Run(Decryptor::kError, empty_frames);
1069 return;
1072 audio_decode_cb.Run(Decryptor::kSuccess, audio_frame_list);
1075 // TODO(xhwang): Try to remove duplicate logic here and in CancelDecrypt().
1076 void ContentDecryptorDelegate::CancelDecode(Decryptor::StreamType stream_type) {
1077 switch (stream_type) {
1078 case Decryptor::kAudio:
1079 // Release the shared memory as it can still be in use by the plugin.
1080 // The next DecryptAndDecode() call will need to allocate a new shared
1081 // memory buffer.
1082 audio_input_resource_ = NULL;
1083 if (!audio_decode_cb_.is_null())
1084 audio_decode_cb_.ResetAndReturn().Run(Decryptor::kSuccess,
1085 Decryptor::AudioFrames());
1086 break;
1087 case Decryptor::kVideo:
1088 // Release the shared memory as it can still be in use by the plugin.
1089 // The next DecryptAndDecode() call will need to allocate a new shared
1090 // memory buffer.
1091 video_input_resource_ = NULL;
1092 if (!video_decode_cb_.is_null())
1093 video_decode_cb_.ResetAndReturn().Run(Decryptor::kSuccess, NULL);
1094 break;
1095 default:
1096 NOTREACHED();
1100 bool ContentDecryptorDelegate::MakeMediaBufferResource(
1101 Decryptor::StreamType stream_type,
1102 const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
1103 scoped_refptr<PPB_Buffer_Impl>* resource) {
1104 TRACE_EVENT0("media", "ContentDecryptorDelegate::MakeMediaBufferResource");
1106 // End of stream buffers are represented as null resources.
1107 if (encrypted_buffer->end_of_stream()) {
1108 *resource = NULL;
1109 return true;
1112 DCHECK(stream_type == Decryptor::kAudio || stream_type == Decryptor::kVideo);
1113 scoped_refptr<PPB_Buffer_Impl>& media_resource =
1114 (stream_type == Decryptor::kAudio) ? audio_input_resource_
1115 : video_input_resource_;
1117 const size_t data_size = static_cast<size_t>(encrypted_buffer->data_size());
1118 if (!media_resource.get() || media_resource->size() < data_size) {
1119 // Either the buffer hasn't been created yet, or we have one that isn't big
1120 // enough to fit |size| bytes.
1122 // Media resource size starts from |kMinimumMediaBufferSize| and grows
1123 // exponentially to avoid frequent re-allocation of PPB_Buffer_Impl,
1124 // which is usually expensive. Since input media buffers are compressed,
1125 // they are usually small (compared to outputs). The over-allocated memory
1126 // should be negligible.
1127 const uint32_t kMinimumMediaBufferSize = 1024;
1128 uint32_t media_resource_size =
1129 media_resource.get() ? media_resource->size() : kMinimumMediaBufferSize;
1130 while (media_resource_size < data_size)
1131 media_resource_size *= 2;
1133 DVLOG(2) << "Size of media buffer for "
1134 << ((stream_type == Decryptor::kAudio) ? "audio" : "video")
1135 << " stream bumped to " << media_resource_size
1136 << " bytes to fit input.";
1137 media_resource =
1138 PPB_Buffer_Impl::CreateResource(pp_instance_, media_resource_size);
1139 if (!media_resource.get())
1140 return false;
1143 BufferAutoMapper mapper(media_resource.get());
1144 if (!mapper.data() || mapper.size() < data_size) {
1145 media_resource = NULL;
1146 return false;
1148 memcpy(mapper.data(), encrypted_buffer->data(), data_size);
1150 *resource = media_resource;
1151 return true;
1154 void ContentDecryptorDelegate::FreeBuffer(uint32_t buffer_id) {
1155 if (buffer_id)
1156 free_buffers_.push(buffer_id);
1159 void ContentDecryptorDelegate::SetBufferToFreeInTrackingInfo(
1160 PP_DecryptTrackingInfo* tracking_info) {
1161 DCHECK_EQ(tracking_info->buffer_id, 0u);
1163 if (free_buffers_.empty())
1164 return;
1166 tracking_info->buffer_id = free_buffers_.front();
1167 free_buffers_.pop();
1170 bool ContentDecryptorDelegate::DeserializeAudioFrames(
1171 PP_Resource audio_frames,
1172 size_t data_size,
1173 media::SampleFormat sample_format,
1174 Decryptor::AudioFrames* frames) {
1175 DCHECK(frames);
1176 EnterResourceNoLock<PPB_Buffer_API> enter(audio_frames, true);
1177 if (!enter.succeeded())
1178 return false;
1180 BufferAutoMapper mapper(enter.object());
1181 if (!mapper.data() || !mapper.size() ||
1182 mapper.size() < static_cast<uint32_t>(data_size))
1183 return false;
1185 // TODO(jrummell): Pass ownership of data() directly to AudioBuffer to avoid
1186 // the copy. Since it is possible to get multiple buffers, it would need to be
1187 // sliced and ref counted appropriately. http://crbug.com/255576.
1188 const uint8* cur = static_cast<uint8*>(mapper.data());
1189 size_t bytes_left = data_size;
1191 const int audio_bytes_per_frame =
1192 media::SampleFormatToBytesPerChannel(sample_format) *
1193 audio_channel_count_;
1194 if (audio_bytes_per_frame <= 0)
1195 return false;
1197 // Allocate space for the channel pointers given to AudioBuffer.
1198 std::vector<const uint8*> channel_ptrs(audio_channel_count_,
1199 static_cast<const uint8*>(NULL));
1200 do {
1201 int64 timestamp = 0;
1202 int64 frame_size = -1;
1203 const size_t kHeaderSize = sizeof(timestamp) + sizeof(frame_size);
1205 if (bytes_left < kHeaderSize)
1206 return false;
1208 memcpy(&timestamp, cur, sizeof(timestamp));
1209 cur += sizeof(timestamp);
1210 bytes_left -= sizeof(timestamp);
1212 memcpy(&frame_size, cur, sizeof(frame_size));
1213 cur += sizeof(frame_size);
1214 bytes_left -= sizeof(frame_size);
1216 // We should *not* have empty frames in the list.
1217 if (frame_size <= 0 ||
1218 bytes_left < base::checked_cast<size_t>(frame_size)) {
1219 return false;
1222 // Setup channel pointers. AudioBuffer::CopyFrom() will only use the first
1223 // one in the case of interleaved data.
1224 const int size_per_channel = frame_size / audio_channel_count_;
1225 for (int i = 0; i < audio_channel_count_; ++i)
1226 channel_ptrs[i] = cur + i * size_per_channel;
1228 const int frame_count = frame_size / audio_bytes_per_frame;
1229 scoped_refptr<media::AudioBuffer> frame = media::AudioBuffer::CopyFrom(
1230 sample_format,
1231 audio_channel_layout_,
1232 audio_channel_count_,
1233 audio_samples_per_second_,
1234 frame_count,
1235 &channel_ptrs[0],
1236 base::TimeDelta::FromMicroseconds(timestamp));
1237 frames->push_back(frame);
1239 cur += frame_size;
1240 bytes_left -= frame_size;
1241 } while (bytes_left > 0);
1243 return true;
1246 void ContentDecryptorDelegate::SatisfyAllPendingCallbacksOnError() {
1247 if (!audio_decoder_init_cb_.is_null())
1248 audio_decoder_init_cb_.ResetAndReturn().Run(false);
1250 if (!video_decoder_init_cb_.is_null())
1251 video_decoder_init_cb_.ResetAndReturn().Run(false);
1253 audio_input_resource_ = NULL;
1254 video_input_resource_ = NULL;
1256 if (!audio_decrypt_cb_.is_null())
1257 audio_decrypt_cb_.ResetAndReturn().Run(media::Decryptor::kError, NULL);
1259 if (!video_decrypt_cb_.is_null())
1260 video_decrypt_cb_.ResetAndReturn().Run(media::Decryptor::kError, NULL);
1262 if (!audio_decode_cb_.is_null()) {
1263 const media::Decryptor::AudioFrames empty_frames;
1264 audio_decode_cb_.ResetAndReturn().Run(media::Decryptor::kError,
1265 empty_frames);
1268 if (!video_decode_cb_.is_null())
1269 video_decode_cb_.ResetAndReturn().Run(media::Decryptor::kError, NULL);
1271 cdm_promise_adapter_.Clear();
1274 } // namespace content