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 "content/renderer/media/webmediaplayer_impl.h"
12 #include "base/bind.h"
13 #include "base/callback.h"
14 #include "base/callback_helpers.h"
15 #include "base/command_line.h"
16 #include "base/debug/alias.h"
17 #include "base/debug/crash_logging.h"
18 #include "base/debug/trace_event.h"
19 #include "base/message_loop/message_loop_proxy.h"
20 #include "base/metrics/histogram.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/synchronization/waitable_event.h"
24 #include "cc/layers/video_layer.h"
25 #include "content/public/common/content_switches.h"
26 #include "content/public/renderer/render_frame.h"
27 #include "content/renderer/compositor_bindings/web_layer_impl.h"
28 #include "content/renderer/media/buffered_data_source.h"
29 #include "content/renderer/media/crypto/key_systems.h"
30 #include "content/renderer/media/render_media_log.h"
31 #include "content/renderer/media/texttrack_impl.h"
32 #include "content/renderer/media/webaudiosourceprovider_impl.h"
33 #include "content/renderer/media/webcontentdecryptionmodule_impl.h"
34 #include "content/renderer/media/webinbandtexttrack_impl.h"
35 #include "content/renderer/media/webmediaplayer_delegate.h"
36 #include "content/renderer/media/webmediaplayer_params.h"
37 #include "content/renderer/media/webmediaplayer_util.h"
38 #include "content/renderer/media/webmediasource_impl.h"
39 #include "content/renderer/pepper/pepper_webplugin_impl.h"
40 #include "content/renderer/render_thread_impl.h"
41 #include "gpu/GLES2/gl2extchromium.h"
42 #include "gpu/command_buffer/common/mailbox_holder.h"
43 #include "media/audio/null_audio_sink.h"
44 #include "media/base/audio_hardware_config.h"
45 #include "media/base/bind_to_current_loop.h"
46 #include "media/base/filter_collection.h"
47 #include "media/base/limits.h"
48 #include "media/base/media_log.h"
49 #include "media/base/media_switches.h"
50 #include "media/base/pipeline.h"
51 #include "media/base/text_renderer.h"
52 #include "media/base/video_frame.h"
53 #include "media/filters/audio_renderer_impl.h"
54 #include "media/filters/chunk_demuxer.h"
55 #include "media/filters/ffmpeg_audio_decoder.h"
56 #include "media/filters/ffmpeg_demuxer.h"
57 #include "media/filters/ffmpeg_video_decoder.h"
58 #include "media/filters/gpu_video_accelerator_factories.h"
59 #include "media/filters/gpu_video_decoder.h"
60 #include "media/filters/opus_audio_decoder.h"
61 #include "media/filters/video_renderer_impl.h"
62 #include "media/filters/vpx_video_decoder.h"
63 #include "third_party/WebKit/public/platform/WebContentDecryptionModule.h"
64 #include "third_party/WebKit/public/platform/WebContentDecryptionModuleResult.h"
65 #include "third_party/WebKit/public/platform/WebMediaSource.h"
66 #include "third_party/WebKit/public/platform/WebRect.h"
67 #include "third_party/WebKit/public/platform/WebSize.h"
68 #include "third_party/WebKit/public/platform/WebString.h"
69 #include "third_party/WebKit/public/platform/WebURL.h"
70 #include "third_party/WebKit/public/web/WebDocument.h"
71 #include "third_party/WebKit/public/web/WebLocalFrame.h"
72 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
73 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
74 #include "third_party/WebKit/public/web/WebView.h"
75 #include "v8/include/v8.h"
77 #if defined(ENABLE_PEPPER_CDMS)
78 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
81 using blink::WebCanvas;
82 using blink::WebMediaPlayer;
85 using blink::WebString;
86 using media::PipelineStatus;
90 // Amount of extra memory used by each player instance reported to V8.
91 // It is not exact number -- first, it differs on different platforms,
92 // and second, it is very hard to calculate. Instead, use some arbitrary
93 // value that will cause garbage collection from time to time. We don't want
94 // it to happen on every allocation, but don't want 5k players to sit in memory
95 // either. Looks that chosen constant achieves both goals, at least for audio
96 // objects. (Do not worry about video objects yet, JS programs do not create
97 // thousands of them...)
98 const int kPlayerExtraMemory = 1024 * 1024;
100 // Limits the range of playback rate.
102 // TODO(kylep): Revisit these.
104 // Vista has substantially lower performance than XP or Windows7. If you speed
105 // up a video too much, it can't keep up, and rendering stops updating except on
106 // the time bar. For really high speeds, audio becomes a bottleneck and we just
107 // use up the data we have, which may not achieve the speed requested, but will
108 // not crash the tab.
110 // A very slow speed, ie 0.00000001x, causes the machine to lock up. (It seems
111 // like a busy loop). It gets unresponsive, although its not completely dead.
113 // Also our timers are not very accurate (especially for ogg), which becomes
114 // evident at low speeds and on Vista. Since other speeds are risky and outside
115 // the norms, we think 1/16x to 16x is a safe and useful range for now.
116 const double kMinRate = 0.0625;
117 const double kMaxRate = 16.0;
119 // Prefix for histograms related to Encrypted Media Extensions.
120 const char* kMediaEme = "Media.EME.";
122 class SyncPointClientImpl : public media::VideoFrame::SyncPointClient {
124 explicit SyncPointClientImpl(
125 blink::WebGraphicsContext3D* web_graphics_context)
126 : web_graphics_context_(web_graphics_context) {}
127 virtual ~SyncPointClientImpl() {}
128 virtual uint32 InsertSyncPoint() OVERRIDE {
129 return web_graphics_context_->insertSyncPoint();
131 virtual void WaitSyncPoint(uint32 sync_point) OVERRIDE {
132 web_graphics_context_->waitSyncPoint(sync_point);
136 blink::WebGraphicsContext3D* web_graphics_context_;
139 // Used for calls to decryptor_ready_cb where the result can be ignored.
140 void DoNothing(bool) {
147 class BufferedDataSourceHostImpl;
149 #define COMPILE_ASSERT_MATCHING_ENUM(name) \
150 COMPILE_ASSERT(static_cast<int>(WebMediaPlayer::CORSMode ## name) == \
151 static_cast<int>(BufferedResourceLoader::k ## name), \
153 COMPILE_ASSERT_MATCHING_ENUM(Unspecified);
154 COMPILE_ASSERT_MATCHING_ENUM(Anonymous);
155 COMPILE_ASSERT_MATCHING_ENUM(UseCredentials);
156 #undef COMPILE_ASSERT_MATCHING_ENUM
158 #define BIND_TO_RENDER_LOOP(function) \
159 (DCHECK(main_loop_->BelongsToCurrentThread()), \
160 media::BindToCurrentLoop(base::Bind(function, AsWeakPtr())))
162 #define BIND_TO_RENDER_LOOP1(function, arg1) \
163 (DCHECK(main_loop_->BelongsToCurrentThread()), \
164 media::BindToCurrentLoop(base::Bind(function, AsWeakPtr(), arg1)))
166 static void LogMediaSourceError(const scoped_refptr<media::MediaLog>& media_log,
167 const std::string& error) {
168 media_log->AddEvent(media_log->CreateMediaSourceErrorEvent(error));
171 WebMediaPlayerImpl::WebMediaPlayerImpl(
172 blink::WebLocalFrame* frame,
173 blink::WebMediaPlayerClient* client,
174 base::WeakPtr<WebMediaPlayerDelegate> delegate,
175 const WebMediaPlayerParams& params)
177 network_state_(WebMediaPlayer::NetworkStateEmpty),
178 ready_state_(WebMediaPlayer::ReadyStateHaveNothing),
180 main_loop_(base::MessageLoopProxy::current()),
182 RenderThreadImpl::current()->GetMediaThreadMessageLoopProxy()),
183 media_log_(new RenderMediaLog()),
184 pipeline_(media_loop_, media_log_.get()),
185 load_type_(LoadTypeURL),
189 playback_rate_(0.0f),
190 pending_seek_(false),
191 pending_seek_seconds_(0.0f),
192 should_notify_time_changed_(false),
195 defer_load_cb_(params.defer_load_cb()),
196 incremented_externally_allocated_memory_(false),
197 gpu_factories_(RenderThreadImpl::current()->GetGpuFactories()),
198 supports_save_(true),
199 chunk_demuxer_(NULL),
200 // Threaded compositing isn't enabled universally yet.
201 compositor_task_runner_(
202 RenderThreadImpl::current()->compositor_message_loop_proxy()
203 ? RenderThreadImpl::current()->compositor_message_loop_proxy()
204 : base::MessageLoopProxy::current()),
205 compositor_(new VideoFrameCompositor(
206 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnNaturalSizeChanged),
207 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnOpacityChanged))),
208 text_track_index_(0),
210 media_log_->AddEvent(
211 media_log_->CreateEvent(media::MediaLogEvent::WEBMEDIAPLAYER_CREATED));
213 // |gpu_factories_| requires that its entry points be called on its
214 // |GetTaskRunner()|. Since |pipeline_| will own decoders created from the
215 // factories, require that their message loops are identical.
216 DCHECK(!gpu_factories_ || (gpu_factories_->GetTaskRunner() == media_loop_));
218 // Let V8 know we started new thread if we did not do it yet.
219 // Made separate task to avoid deletion of player currently being created.
220 // Also, delaying GC until after player starts gets rid of starting lag --
221 // collection happens in parallel with playing.
223 // TODO(enal): remove when we get rid of per-audio-stream thread.
224 main_loop_->PostTask(
226 base::Bind(&WebMediaPlayerImpl::IncrementExternallyAllocatedMemory,
229 // Use the null sink if no sink was provided.
230 audio_source_provider_ = new WebAudioSourceProviderImpl(
231 params.audio_renderer_sink().get()
232 ? params.audio_renderer_sink()
233 : new media::NullAudioSink(media_loop_));
236 WebMediaPlayerImpl::~WebMediaPlayerImpl() {
237 client_->setWebLayer(NULL);
239 DCHECK(main_loop_->BelongsToCurrentThread());
240 media_log_->AddEvent(
241 media_log_->CreateEvent(media::MediaLogEvent::WEBMEDIAPLAYER_DESTROYED));
244 delegate_->PlayerGone(this);
246 // Abort any pending IO so stopping the pipeline doesn't get blocked.
248 data_source_->Abort();
249 if (chunk_demuxer_) {
250 chunk_demuxer_->Shutdown();
251 chunk_demuxer_ = NULL;
254 gpu_factories_ = NULL;
256 // Make sure to kill the pipeline so there's no more media threads running.
257 // Note: stopping the pipeline might block for a long time.
258 base::WaitableEvent waiter(false, false);
260 base::Bind(&base::WaitableEvent::Signal, base::Unretained(&waiter)));
263 compositor_task_runner_->DeleteSoon(FROM_HERE, compositor_);
265 // Let V8 know we are not using extra resources anymore.
266 if (incremented_externally_allocated_memory_) {
267 v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(
268 -kPlayerExtraMemory);
269 incremented_externally_allocated_memory_ = false;
273 void WebMediaPlayerImpl::load(LoadType load_type, const blink::WebURL& url,
274 CORSMode cors_mode) {
275 DVLOG(1) << __FUNCTION__ << "(" << load_type << ", " << url << ", "
277 if (!defer_load_cb_.is_null()) {
278 defer_load_cb_.Run(base::Bind(
279 &WebMediaPlayerImpl::DoLoad, AsWeakPtr(), load_type, url, cors_mode));
282 DoLoad(load_type, url, cors_mode);
285 void WebMediaPlayerImpl::DoLoad(LoadType load_type,
286 const blink::WebURL& url,
287 CORSMode cors_mode) {
288 DCHECK(main_loop_->BelongsToCurrentThread());
291 ReportMediaSchemeUma(gurl);
293 // Set subresource URL for crash reporting.
294 base::debug::SetCrashKeyValue("subresource_url", gurl.spec());
296 load_type_ = load_type;
298 SetNetworkState(WebMediaPlayer::NetworkStateLoading);
299 SetReadyState(WebMediaPlayer::ReadyStateHaveNothing);
300 media_log_->AddEvent(media_log_->CreateLoadEvent(url.spec()));
302 // Media source pipelines can start immediately.
303 if (load_type == LoadTypeMediaSource) {
304 supports_save_ = false;
309 // Otherwise it's a regular request which requires resolving the URL first.
310 data_source_.reset(new BufferedDataSource(
312 static_cast<BufferedResourceLoader::CORSMode>(cors_mode),
316 &buffered_data_source_host_,
317 base::Bind(&WebMediaPlayerImpl::NotifyDownloading, AsWeakPtr())));
318 data_source_->Initialize(
319 base::Bind(&WebMediaPlayerImpl::DataSourceInitialized, AsWeakPtr()));
320 data_source_->SetPreload(preload_);
323 void WebMediaPlayerImpl::play() {
324 DVLOG(1) << __FUNCTION__;
325 DCHECK(main_loop_->BelongsToCurrentThread());
328 pipeline_.SetPlaybackRate(playback_rate_);
330 data_source_->MediaIsPlaying();
332 media_log_->AddEvent(media_log_->CreateEvent(media::MediaLogEvent::PLAY));
335 delegate_->DidPlay(this);
338 void WebMediaPlayerImpl::pause() {
339 DVLOG(1) << __FUNCTION__;
340 DCHECK(main_loop_->BelongsToCurrentThread());
343 pipeline_.SetPlaybackRate(0.0f);
345 data_source_->MediaIsPaused();
346 paused_time_ = pipeline_.GetMediaTime();
348 media_log_->AddEvent(media_log_->CreateEvent(media::MediaLogEvent::PAUSE));
351 delegate_->DidPause(this);
354 bool WebMediaPlayerImpl::supportsSave() const {
355 DCHECK(main_loop_->BelongsToCurrentThread());
356 return supports_save_;
359 void WebMediaPlayerImpl::seek(double seconds) {
360 DVLOG(1) << __FUNCTION__ << "(" << seconds << ")";
361 DCHECK(main_loop_->BelongsToCurrentThread());
363 if (ready_state_ > WebMediaPlayer::ReadyStateHaveMetadata)
364 SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata);
366 base::TimeDelta seek_time = ConvertSecondsToTimestamp(seconds);
369 pending_seek_ = true;
370 pending_seek_seconds_ = seconds;
372 chunk_demuxer_->CancelPendingSeek(seek_time);
376 media_log_->AddEvent(media_log_->CreateSeekEvent(seconds));
378 // Update our paused time.
380 paused_time_ = seek_time;
385 chunk_demuxer_->StartWaitingForSeek(seek_time);
387 // Kick off the asynchronous seek!
390 BIND_TO_RENDER_LOOP1(&WebMediaPlayerImpl::OnPipelineSeeked, true));
393 void WebMediaPlayerImpl::setRate(double rate) {
394 DVLOG(1) << __FUNCTION__ << "(" << rate << ")";
395 DCHECK(main_loop_->BelongsToCurrentThread());
397 // TODO(kylep): Remove when support for negatives is added. Also, modify the
398 // following checks so rewind uses reasonable values also.
402 // Limit rates to reasonable values by clamping.
406 else if (rate > kMaxRate)
410 playback_rate_ = rate;
412 pipeline_.SetPlaybackRate(rate);
414 data_source_->MediaPlaybackRateChanged(rate);
418 void WebMediaPlayerImpl::setVolume(double volume) {
419 DVLOG(1) << __FUNCTION__ << "(" << volume << ")";
420 DCHECK(main_loop_->BelongsToCurrentThread());
422 pipeline_.SetVolume(volume);
425 #define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, chromium_name) \
426 COMPILE_ASSERT(static_cast<int>(WebMediaPlayer::webkit_name) == \
427 static_cast<int>(content::chromium_name), \
429 COMPILE_ASSERT_MATCHING_ENUM(PreloadNone, NONE);
430 COMPILE_ASSERT_MATCHING_ENUM(PreloadMetaData, METADATA);
431 COMPILE_ASSERT_MATCHING_ENUM(PreloadAuto, AUTO);
432 #undef COMPILE_ASSERT_MATCHING_ENUM
434 void WebMediaPlayerImpl::setPreload(WebMediaPlayer::Preload preload) {
435 DVLOG(1) << __FUNCTION__ << "(" << preload << ")";
436 DCHECK(main_loop_->BelongsToCurrentThread());
438 preload_ = static_cast<content::Preload>(preload);
440 data_source_->SetPreload(preload_);
443 bool WebMediaPlayerImpl::hasVideo() const {
444 DCHECK(main_loop_->BelongsToCurrentThread());
446 return pipeline_metadata_.has_video;
449 bool WebMediaPlayerImpl::hasAudio() const {
450 DCHECK(main_loop_->BelongsToCurrentThread());
452 return pipeline_metadata_.has_audio;
455 blink::WebSize WebMediaPlayerImpl::naturalSize() const {
456 DCHECK(main_loop_->BelongsToCurrentThread());
458 return blink::WebSize(pipeline_metadata_.natural_size);
461 bool WebMediaPlayerImpl::paused() const {
462 DCHECK(main_loop_->BelongsToCurrentThread());
464 return pipeline_.GetPlaybackRate() == 0.0f;
467 bool WebMediaPlayerImpl::seeking() const {
468 DCHECK(main_loop_->BelongsToCurrentThread());
470 if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
476 double WebMediaPlayerImpl::duration() const {
477 DCHECK(main_loop_->BelongsToCurrentThread());
479 if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
480 return std::numeric_limits<double>::quiet_NaN();
482 return GetPipelineDuration();
485 double WebMediaPlayerImpl::timelineOffset() const {
486 DCHECK(main_loop_->BelongsToCurrentThread());
488 if (pipeline_metadata_.timeline_offset.is_null())
489 return std::numeric_limits<double>::quiet_NaN();
491 return pipeline_metadata_.timeline_offset.ToJsTime();
494 double WebMediaPlayerImpl::currentTime() const {
495 DCHECK(main_loop_->BelongsToCurrentThread());
496 return (paused_ ? paused_time_ : pipeline_.GetMediaTime()).InSecondsF();
499 WebMediaPlayer::NetworkState WebMediaPlayerImpl::networkState() const {
500 DCHECK(main_loop_->BelongsToCurrentThread());
501 return network_state_;
504 WebMediaPlayer::ReadyState WebMediaPlayerImpl::readyState() const {
505 DCHECK(main_loop_->BelongsToCurrentThread());
509 blink::WebTimeRanges WebMediaPlayerImpl::buffered() const {
510 DCHECK(main_loop_->BelongsToCurrentThread());
511 media::Ranges<base::TimeDelta> buffered_time_ranges =
512 pipeline_.GetBufferedTimeRanges();
513 buffered_data_source_host_.AddBufferedTimeRanges(
514 &buffered_time_ranges, pipeline_.GetMediaDuration());
515 return ConvertToWebTimeRanges(buffered_time_ranges);
518 double WebMediaPlayerImpl::maxTimeSeekable() const {
519 DCHECK(main_loop_->BelongsToCurrentThread());
521 // If we haven't even gotten to ReadyStateHaveMetadata yet then just
522 // return 0 so that the seekable range is empty.
523 if (ready_state_ < WebMediaPlayer::ReadyStateHaveMetadata)
526 // We don't support seeking in streaming media.
527 if (data_source_ && data_source_->IsStreaming())
532 bool WebMediaPlayerImpl::didLoadingProgress() {
533 DCHECK(main_loop_->BelongsToCurrentThread());
534 bool pipeline_progress = pipeline_.DidLoadingProgress();
535 bool data_progress = buffered_data_source_host_.DidLoadingProgress();
536 return pipeline_progress || data_progress;
539 void WebMediaPlayerImpl::paint(WebCanvas* canvas,
541 unsigned char alpha) {
542 DCHECK(main_loop_->BelongsToCurrentThread());
543 TRACE_EVENT0("media", "WebMediaPlayerImpl:paint");
545 // TODO(scherkus): Clarify paint() API contract to better understand when and
546 // why it's being called. For example, today paint() is called when:
547 // - We haven't reached HAVE_CURRENT_DATA and need to paint black
548 // - We're painting to a canvas
549 // See http://crbug.com/341225 http://crbug.com/342621 for details.
550 scoped_refptr<media::VideoFrame> video_frame =
551 GetCurrentFrameFromCompositor();
553 gfx::Rect gfx_rect(rect);
555 skcanvas_video_renderer_.Paint(video_frame.get(),
559 pipeline_metadata_.video_rotation);
562 bool WebMediaPlayerImpl::hasSingleSecurityOrigin() const {
564 return data_source_->HasSingleOrigin();
568 bool WebMediaPlayerImpl::didPassCORSAccessCheck() const {
570 return data_source_->DidPassCORSAccessCheck();
574 double WebMediaPlayerImpl::mediaTimeForTimeValue(double timeValue) const {
575 return ConvertSecondsToTimestamp(timeValue).InSecondsF();
578 unsigned WebMediaPlayerImpl::decodedFrameCount() const {
579 DCHECK(main_loop_->BelongsToCurrentThread());
581 media::PipelineStatistics stats = pipeline_.GetStatistics();
582 return stats.video_frames_decoded;
585 unsigned WebMediaPlayerImpl::droppedFrameCount() const {
586 DCHECK(main_loop_->BelongsToCurrentThread());
588 media::PipelineStatistics stats = pipeline_.GetStatistics();
589 return stats.video_frames_dropped;
592 unsigned WebMediaPlayerImpl::audioDecodedByteCount() const {
593 DCHECK(main_loop_->BelongsToCurrentThread());
595 media::PipelineStatistics stats = pipeline_.GetStatistics();
596 return stats.audio_bytes_decoded;
599 unsigned WebMediaPlayerImpl::videoDecodedByteCount() const {
600 DCHECK(main_loop_->BelongsToCurrentThread());
602 media::PipelineStatistics stats = pipeline_.GetStatistics();
603 return stats.video_bytes_decoded;
606 bool WebMediaPlayerImpl::copyVideoTextureToPlatformTexture(
607 blink::WebGraphicsContext3D* web_graphics_context,
608 unsigned int texture,
610 unsigned int internal_format,
612 bool premultiply_alpha,
614 TRACE_EVENT0("media", "WebMediaPlayerImpl:copyVideoTextureToPlatformTexture");
616 scoped_refptr<media::VideoFrame> video_frame =
617 GetCurrentFrameFromCompositor();
621 if (video_frame->format() != media::VideoFrame::NATIVE_TEXTURE)
624 const gpu::MailboxHolder* mailbox_holder = video_frame->mailbox_holder();
625 if (mailbox_holder->texture_target != GL_TEXTURE_2D)
628 web_graphics_context->waitSyncPoint(mailbox_holder->sync_point);
629 uint32 source_texture = web_graphics_context->createAndConsumeTextureCHROMIUM(
630 GL_TEXTURE_2D, mailbox_holder->mailbox.name);
632 // The video is stored in a unmultiplied format, so premultiply
634 web_graphics_context->pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM,
636 // Application itself needs to take care of setting the right flip_y
637 // value down to get the expected result.
638 // flip_y==true means to reverse the video orientation while
639 // flip_y==false means to keep the intrinsic orientation.
640 web_graphics_context->pixelStorei(GL_UNPACK_FLIP_Y_CHROMIUM, flip_y);
641 web_graphics_context->copyTextureCHROMIUM(GL_TEXTURE_2D,
647 web_graphics_context->pixelStorei(GL_UNPACK_FLIP_Y_CHROMIUM, false);
648 web_graphics_context->pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM,
651 web_graphics_context->deleteTexture(source_texture);
652 web_graphics_context->flush();
654 SyncPointClientImpl client(web_graphics_context);
655 video_frame->UpdateReleaseSyncPoint(&client);
659 // Helper functions to report media EME related stats to UMA. They follow the
660 // convention of more commonly used macros UMA_HISTOGRAM_ENUMERATION and
661 // UMA_HISTOGRAM_COUNTS. The reason that we cannot use those macros directly is
662 // that UMA_* macros require the names to be constant throughout the process'
664 static void EmeUMAHistogramEnumeration(const std::string& key_system,
665 const std::string& method,
667 int boundary_value) {
668 base::LinearHistogram::FactoryGet(
669 kMediaEme + KeySystemNameForUMA(key_system) + "." + method,
670 1, boundary_value, boundary_value + 1,
671 base::Histogram::kUmaTargetedHistogramFlag)->Add(sample);
674 static void EmeUMAHistogramCounts(const std::string& key_system,
675 const std::string& method,
677 // Use the same parameters as UMA_HISTOGRAM_COUNTS.
678 base::Histogram::FactoryGet(
679 kMediaEme + KeySystemNameForUMA(key_system) + "." + method,
680 1, 1000000, 50, base::Histogram::kUmaTargetedHistogramFlag)->Add(sample);
683 // Helper enum for reporting generateKeyRequest/addKey histograms.
684 enum MediaKeyException {
687 kKeySystemNotSupported,
689 kMaxMediaKeyException
692 static MediaKeyException MediaKeyExceptionForUMA(
693 WebMediaPlayer::MediaKeyException e) {
695 case WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported:
696 return kKeySystemNotSupported;
697 case WebMediaPlayer::MediaKeyExceptionInvalidPlayerState:
698 return kInvalidPlayerState;
699 case WebMediaPlayer::MediaKeyExceptionNoError:
702 return kUnknownResultId;
706 // Helper for converting |key_system| name and exception |e| to a pair of enum
707 // values from above, for reporting to UMA.
708 static void ReportMediaKeyExceptionToUMA(const std::string& method,
709 const std::string& key_system,
710 WebMediaPlayer::MediaKeyException e) {
711 MediaKeyException result_id = MediaKeyExceptionForUMA(e);
712 DCHECK_NE(result_id, kUnknownResultId) << e;
713 EmeUMAHistogramEnumeration(
714 key_system, method, result_id, kMaxMediaKeyException);
717 // Convert a WebString to ASCII, falling back on an empty string in the case
718 // of a non-ASCII string.
719 static std::string ToASCIIOrEmpty(const blink::WebString& string) {
720 return base::IsStringASCII(string) ? base::UTF16ToASCII(string)
724 WebMediaPlayer::MediaKeyException
725 WebMediaPlayerImpl::generateKeyRequest(const WebString& key_system,
726 const unsigned char* init_data,
727 unsigned init_data_length) {
728 DVLOG(1) << "generateKeyRequest: " << base::string16(key_system) << ": "
729 << std::string(reinterpret_cast<const char*>(init_data),
730 static_cast<size_t>(init_data_length));
732 std::string ascii_key_system =
733 GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
735 WebMediaPlayer::MediaKeyException e =
736 GenerateKeyRequestInternal(ascii_key_system, init_data, init_data_length);
737 ReportMediaKeyExceptionToUMA("generateKeyRequest", ascii_key_system, e);
741 // Guess the type of |init_data|. This is only used to handle some corner cases
742 // so we keep it as simple as possible without breaking major use cases.
743 static std::string GuessInitDataType(const unsigned char* init_data,
744 unsigned init_data_length) {
745 // Most WebM files use KeyId of 16 bytes. MP4 init data are always >16 bytes.
746 if (init_data_length == 16)
752 WebMediaPlayer::MediaKeyException
753 WebMediaPlayerImpl::GenerateKeyRequestInternal(const std::string& key_system,
754 const unsigned char* init_data,
755 unsigned init_data_length) {
756 DCHECK(main_loop_->BelongsToCurrentThread());
758 if (!IsConcreteSupportedKeySystem(key_system))
759 return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
761 // We do not support run-time switching between key systems for now.
762 if (current_key_system_.empty()) {
763 if (!proxy_decryptor_) {
764 proxy_decryptor_.reset(new ProxyDecryptor(
765 #if defined(ENABLE_PEPPER_CDMS)
766 // Create() must be called synchronously as |frame_| may not be
768 base::Bind(&PepperCdmWrapperImpl::Create, frame_),
769 #elif defined(ENABLE_BROWSER_CDMS)
770 #error Browser side CDM in WMPI for prefixed EME API not supported yet.
772 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnKeyAdded),
773 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnKeyError),
774 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnKeyMessage)));
777 GURL security_origin(frame_->document().securityOrigin().toString());
778 if (!proxy_decryptor_->InitializeCDM(key_system, security_origin))
779 return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
781 if (proxy_decryptor_ && !decryptor_ready_cb_.is_null()) {
782 base::ResetAndReturn(&decryptor_ready_cb_)
783 .Run(proxy_decryptor_->GetDecryptor(), base::Bind(DoNothing));
786 current_key_system_ = key_system;
787 } else if (key_system != current_key_system_) {
788 return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
791 std::string init_data_type = init_data_type_;
792 if (init_data_type.empty())
793 init_data_type = GuessInitDataType(init_data, init_data_length);
795 // TODO(xhwang): We assume all streams are from the same container (thus have
796 // the same "type") for now. In the future, the "type" should be passed down
797 // from the application.
798 if (!proxy_decryptor_->GenerateKeyRequest(
799 init_data_type, init_data, init_data_length)) {
800 current_key_system_.clear();
801 return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
804 return WebMediaPlayer::MediaKeyExceptionNoError;
807 WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::addKey(
808 const WebString& key_system,
809 const unsigned char* key,
811 const unsigned char* init_data,
812 unsigned init_data_length,
813 const WebString& session_id) {
814 DVLOG(1) << "addKey: " << base::string16(key_system) << ": "
815 << std::string(reinterpret_cast<const char*>(key),
816 static_cast<size_t>(key_length)) << ", "
817 << std::string(reinterpret_cast<const char*>(init_data),
818 static_cast<size_t>(init_data_length)) << " ["
819 << base::string16(session_id) << "]";
821 std::string ascii_key_system =
822 GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
823 std::string ascii_session_id = ToASCIIOrEmpty(session_id);
825 WebMediaPlayer::MediaKeyException e = AddKeyInternal(ascii_key_system,
831 ReportMediaKeyExceptionToUMA("addKey", ascii_key_system, e);
835 WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::AddKeyInternal(
836 const std::string& key_system,
837 const unsigned char* key,
839 const unsigned char* init_data,
840 unsigned init_data_length,
841 const std::string& session_id) {
843 DCHECK_GT(key_length, 0u);
845 if (!IsConcreteSupportedKeySystem(key_system))
846 return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
848 if (current_key_system_.empty() || key_system != current_key_system_)
849 return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
851 proxy_decryptor_->AddKey(
852 key, key_length, init_data, init_data_length, session_id);
853 return WebMediaPlayer::MediaKeyExceptionNoError;
856 WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::cancelKeyRequest(
857 const WebString& key_system,
858 const WebString& session_id) {
859 DVLOG(1) << "cancelKeyRequest: " << base::string16(key_system) << ": "
860 << " [" << base::string16(session_id) << "]";
862 std::string ascii_key_system =
863 GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
864 std::string ascii_session_id = ToASCIIOrEmpty(session_id);
866 WebMediaPlayer::MediaKeyException e =
867 CancelKeyRequestInternal(ascii_key_system, ascii_session_id);
868 ReportMediaKeyExceptionToUMA("cancelKeyRequest", ascii_key_system, e);
872 WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::CancelKeyRequestInternal(
873 const std::string& key_system,
874 const std::string& session_id) {
875 if (!IsConcreteSupportedKeySystem(key_system))
876 return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
878 if (current_key_system_.empty() || key_system != current_key_system_)
879 return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
881 proxy_decryptor_->CancelKeyRequest(session_id);
882 return WebMediaPlayer::MediaKeyExceptionNoError;
885 void WebMediaPlayerImpl::setContentDecryptionModule(
886 blink::WebContentDecryptionModule* cdm) {
887 DCHECK(main_loop_->BelongsToCurrentThread());
889 // TODO(xhwang): Support setMediaKeys(0) if necessary: http://crbug.com/330324
893 web_cdm_ = ToWebContentDecryptionModuleImpl(cdm);
895 if (web_cdm_ && !decryptor_ready_cb_.is_null())
896 base::ResetAndReturn(&decryptor_ready_cb_)
897 .Run(web_cdm_->GetDecryptor(), base::Bind(DoNothing));
900 void WebMediaPlayerImpl::setContentDecryptionModule(
901 blink::WebContentDecryptionModule* cdm,
902 blink::WebContentDecryptionModuleResult result) {
903 DCHECK(main_loop_->BelongsToCurrentThread());
905 // TODO(xhwang): Support setMediaKeys(0) if necessary: http://crbug.com/330324
907 result.completeWithError(
908 blink::WebContentDecryptionModuleExceptionNotSupportedError,
910 "Null MediaKeys object is not supported.");
914 web_cdm_ = ToWebContentDecryptionModuleImpl(cdm);
916 if (web_cdm_ && !decryptor_ready_cb_.is_null()) {
917 base::ResetAndReturn(&decryptor_ready_cb_)
918 .Run(web_cdm_->GetDecryptor(),
919 BIND_TO_RENDER_LOOP1(
920 &WebMediaPlayerImpl::ContentDecryptionModuleAttached, result));
922 // No pipeline/decoder connected, so resolve the promise. When something
923 // is connected, setting the CDM will happen in SetDecryptorReadyCB().
924 ContentDecryptionModuleAttached(result, true);
928 void WebMediaPlayerImpl::setContentDecryptionModuleSync(
929 blink::WebContentDecryptionModule* cdm) {
930 DCHECK(main_loop_->BelongsToCurrentThread());
932 // Used when loading media and no pipeline/decoder attached yet.
933 DCHECK(decryptor_ready_cb_.is_null());
935 web_cdm_ = ToWebContentDecryptionModuleImpl(cdm);
938 void WebMediaPlayerImpl::ContentDecryptionModuleAttached(
939 blink::WebContentDecryptionModuleResult result,
946 result.completeWithError(
947 blink::WebContentDecryptionModuleExceptionNotSupportedError,
949 "Unable to set MediaKeys object");
952 void WebMediaPlayerImpl::OnPipelineSeeked(bool time_changed,
953 PipelineStatus status) {
954 DVLOG(1) << __FUNCTION__ << "(" << time_changed << ", " << status << ")";
955 DCHECK(main_loop_->BelongsToCurrentThread());
958 pending_seek_ = false;
959 seek(pending_seek_seconds_);
963 if (status != media::PIPELINE_OK) {
964 OnPipelineError(status);
968 // Update our paused time.
970 paused_time_ = pipeline_.GetMediaTime();
972 should_notify_time_changed_ = time_changed;
975 void WebMediaPlayerImpl::OnPipelineEnded() {
976 DVLOG(1) << __FUNCTION__;
977 DCHECK(main_loop_->BelongsToCurrentThread());
978 client_->timeChanged();
981 void WebMediaPlayerImpl::OnPipelineError(PipelineStatus error) {
982 DCHECK(main_loop_->BelongsToCurrentThread());
983 DCHECK_NE(error, media::PIPELINE_OK);
985 if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing) {
986 // Any error that occurs before reaching ReadyStateHaveMetadata should
987 // be considered a format error.
988 SetNetworkState(WebMediaPlayer::NetworkStateFormatError);
992 SetNetworkState(PipelineErrorToNetworkState(error));
994 if (error == media::PIPELINE_ERROR_DECRYPT)
995 EmeUMAHistogramCounts(current_key_system_, "DecryptError", 1);
998 void WebMediaPlayerImpl::OnPipelineMetadata(
999 media::PipelineMetadata metadata) {
1000 DVLOG(1) << __FUNCTION__;
1002 pipeline_metadata_ = metadata;
1004 UMA_HISTOGRAM_ENUMERATION("Media.VideoRotation",
1005 metadata.video_rotation,
1006 media::VIDEO_ROTATION_MAX + 1);
1007 SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata);
1010 DCHECK(!video_weblayer_);
1011 scoped_refptr<cc::VideoLayer> layer =
1012 cc::VideoLayer::Create(compositor_, pipeline_metadata_.video_rotation);
1014 if (pipeline_metadata_.video_rotation == media::VIDEO_ROTATION_90 ||
1015 pipeline_metadata_.video_rotation == media::VIDEO_ROTATION_270) {
1016 gfx::Size size = pipeline_metadata_.natural_size;
1017 pipeline_metadata_.natural_size = gfx::Size(size.height(), size.width());
1020 video_weblayer_.reset(new WebLayerImpl(layer));
1021 video_weblayer_->setOpaque(opaque_);
1022 client_->setWebLayer(video_weblayer_.get());
1026 void WebMediaPlayerImpl::OnPipelineBufferingStateChanged(
1027 media::BufferingState buffering_state) {
1028 DVLOG(1) << __FUNCTION__ << "(" << buffering_state << ")";
1030 // Ignore buffering state changes until we've completed all outstanding seeks.
1031 if (seeking_ || pending_seek_)
1034 // TODO(scherkus): Handle other buffering states when Pipeline starts using
1035 // them and translate them ready state changes http://crbug.com/144683
1036 DCHECK_EQ(buffering_state, media::BUFFERING_HAVE_ENOUGH);
1037 SetReadyState(WebMediaPlayer::ReadyStateHaveEnoughData);
1039 // Blink expects a timeChanged() in response to a seek().
1040 if (should_notify_time_changed_)
1041 client_->timeChanged();
1044 void WebMediaPlayerImpl::OnDemuxerOpened() {
1045 DCHECK(main_loop_->BelongsToCurrentThread());
1046 client_->mediaSourceOpened(new WebMediaSourceImpl(
1047 chunk_demuxer_, base::Bind(&LogMediaSourceError, media_log_)));
1050 void WebMediaPlayerImpl::OnKeyAdded(const std::string& session_id) {
1051 DCHECK(main_loop_->BelongsToCurrentThread());
1052 EmeUMAHistogramCounts(current_key_system_, "KeyAdded", 1);
1054 WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
1055 WebString::fromUTF8(session_id));
1058 void WebMediaPlayerImpl::OnNeedKey(const std::string& type,
1059 const std::vector<uint8>& init_data) {
1060 DCHECK(main_loop_->BelongsToCurrentThread());
1062 // Do not fire NeedKey event if encrypted media is not enabled.
1063 if (!blink::WebRuntimeFeatures::isPrefixedEncryptedMediaEnabled() &&
1064 !blink::WebRuntimeFeatures::isEncryptedMediaEnabled()) {
1068 UMA_HISTOGRAM_COUNTS(kMediaEme + std::string("NeedKey"), 1);
1070 DCHECK(init_data_type_.empty() || type.empty() || type == init_data_type_);
1071 if (init_data_type_.empty())
1072 init_data_type_ = type;
1074 const uint8* init_data_ptr = init_data.empty() ? NULL : &init_data[0];
1076 WebString::fromUTF8(type), init_data_ptr, init_data.size());
1079 void WebMediaPlayerImpl::OnAddTextTrack(
1080 const media::TextTrackConfig& config,
1081 const media::AddTextTrackDoneCB& done_cb) {
1082 DCHECK(main_loop_->BelongsToCurrentThread());
1084 const WebInbandTextTrackImpl::Kind web_kind =
1085 static_cast<WebInbandTextTrackImpl::Kind>(config.kind());
1086 const blink::WebString web_label =
1087 blink::WebString::fromUTF8(config.label());
1088 const blink::WebString web_language =
1089 blink::WebString::fromUTF8(config.language());
1090 const blink::WebString web_id =
1091 blink::WebString::fromUTF8(config.id());
1093 scoped_ptr<WebInbandTextTrackImpl> web_inband_text_track(
1094 new WebInbandTextTrackImpl(web_kind, web_label, web_language, web_id,
1095 text_track_index_++));
1097 scoped_ptr<media::TextTrack> text_track(
1098 new TextTrackImpl(main_loop_, client_, web_inband_text_track.Pass()));
1100 done_cb.Run(text_track.Pass());
1103 void WebMediaPlayerImpl::OnKeyError(const std::string& session_id,
1104 media::MediaKeys::KeyError error_code,
1105 uint32 system_code) {
1106 DCHECK(main_loop_->BelongsToCurrentThread());
1108 EmeUMAHistogramEnumeration(current_key_system_, "KeyError",
1109 error_code, media::MediaKeys::kMaxKeyError);
1111 unsigned short short_system_code = 0;
1112 if (system_code > std::numeric_limits<unsigned short>::max()) {
1113 LOG(WARNING) << "system_code exceeds unsigned short limit.";
1114 short_system_code = std::numeric_limits<unsigned short>::max();
1116 short_system_code = static_cast<unsigned short>(system_code);
1120 WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
1121 WebString::fromUTF8(session_id),
1122 static_cast<blink::WebMediaPlayerClient::MediaKeyErrorCode>(error_code),
1126 void WebMediaPlayerImpl::OnKeyMessage(const std::string& session_id,
1127 const std::vector<uint8>& message,
1128 const GURL& destination_url) {
1129 DCHECK(main_loop_->BelongsToCurrentThread());
1131 DCHECK(destination_url.is_empty() || destination_url.is_valid());
1133 client_->keyMessage(
1134 WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
1135 WebString::fromUTF8(session_id),
1136 message.empty() ? NULL : &message[0],
1141 void WebMediaPlayerImpl::DataSourceInitialized(bool success) {
1142 DCHECK(main_loop_->BelongsToCurrentThread());
1145 SetNetworkState(WebMediaPlayer::NetworkStateFormatError);
1152 void WebMediaPlayerImpl::NotifyDownloading(bool is_downloading) {
1153 if (!is_downloading && network_state_ == WebMediaPlayer::NetworkStateLoading)
1154 SetNetworkState(WebMediaPlayer::NetworkStateIdle);
1155 else if (is_downloading && network_state_ == WebMediaPlayer::NetworkStateIdle)
1156 SetNetworkState(WebMediaPlayer::NetworkStateLoading);
1157 media_log_->AddEvent(
1158 media_log_->CreateBooleanEvent(
1159 media::MediaLogEvent::NETWORK_ACTIVITY_SET,
1160 "is_downloading_data", is_downloading));
1163 void WebMediaPlayerImpl::StartPipeline() {
1164 DCHECK(main_loop_->BelongsToCurrentThread());
1165 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
1167 // Keep track if this is a MSE or non-MSE playback.
1168 UMA_HISTOGRAM_BOOLEAN("Media.MSE.Playback",
1169 (load_type_ == LoadTypeMediaSource));
1171 media::LogCB mse_log_cb;
1173 // Figure out which demuxer to use.
1174 if (load_type_ != LoadTypeMediaSource) {
1175 DCHECK(!chunk_demuxer_);
1176 DCHECK(data_source_);
1178 demuxer_.reset(new media::FFmpegDemuxer(
1179 media_loop_, data_source_.get(),
1180 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnNeedKey),
1183 DCHECK(!chunk_demuxer_);
1184 DCHECK(!data_source_);
1186 mse_log_cb = base::Bind(&LogMediaSourceError, media_log_);
1188 chunk_demuxer_ = new media::ChunkDemuxer(
1189 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnDemuxerOpened),
1190 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnNeedKey),
1193 demuxer_.reset(chunk_demuxer_);
1196 scoped_ptr<media::FilterCollection> filter_collection(
1197 new media::FilterCollection());
1198 filter_collection->SetDemuxer(demuxer_.get());
1200 media::SetDecryptorReadyCB set_decryptor_ready_cb =
1201 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::SetDecryptorReadyCB);
1203 // Create our audio decoders and renderer.
1204 ScopedVector<media::AudioDecoder> audio_decoders;
1205 audio_decoders.push_back(new media::FFmpegAudioDecoder(media_loop_,
1207 audio_decoders.push_back(new media::OpusAudioDecoder(media_loop_));
1209 scoped_ptr<media::AudioRenderer> audio_renderer(new media::AudioRendererImpl(
1211 audio_source_provider_.get(),
1212 audio_decoders.Pass(),
1213 set_decryptor_ready_cb,
1214 RenderThreadImpl::current()->GetAudioHardwareConfig()));
1215 filter_collection->SetAudioRenderer(audio_renderer.Pass());
1217 // Create our video decoders and renderer.
1218 ScopedVector<media::VideoDecoder> video_decoders;
1220 if (gpu_factories_.get()) {
1221 video_decoders.push_back(
1222 new media::GpuVideoDecoder(gpu_factories_, media_log_));
1225 #if !defined(MEDIA_DISABLE_LIBVPX)
1226 video_decoders.push_back(new media::VpxVideoDecoder(media_loop_));
1227 #endif // !defined(MEDIA_DISABLE_LIBVPX)
1229 video_decoders.push_back(new media::FFmpegVideoDecoder(media_loop_));
1231 scoped_ptr<media::VideoRenderer> video_renderer(
1232 new media::VideoRendererImpl(
1234 video_decoders.Pass(),
1235 set_decryptor_ready_cb,
1236 base::Bind(&WebMediaPlayerImpl::FrameReady, base::Unretained(this)),
1238 filter_collection->SetVideoRenderer(video_renderer.Pass());
1240 if (cmd_line->HasSwitch(switches::kEnableInbandTextTracks)) {
1241 scoped_ptr<media::TextRenderer> text_renderer(
1242 new media::TextRenderer(
1244 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnAddTextTrack)));
1246 filter_collection->SetTextRenderer(text_renderer.Pass());
1249 // ... and we're ready to go!
1252 filter_collection.Pass(),
1253 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineEnded),
1254 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineError),
1255 BIND_TO_RENDER_LOOP1(&WebMediaPlayerImpl::OnPipelineSeeked, false),
1256 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineMetadata),
1257 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineBufferingStateChanged),
1258 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnDurationChanged));
1261 void WebMediaPlayerImpl::SetNetworkState(WebMediaPlayer::NetworkState state) {
1262 DVLOG(1) << __FUNCTION__ << "(" << state << ")";
1263 DCHECK(main_loop_->BelongsToCurrentThread());
1264 network_state_ = state;
1265 // Always notify to ensure client has the latest value.
1266 client_->networkStateChanged();
1269 void WebMediaPlayerImpl::SetReadyState(WebMediaPlayer::ReadyState state) {
1270 DVLOG(1) << __FUNCTION__ << "(" << state << ")";
1271 DCHECK(main_loop_->BelongsToCurrentThread());
1273 if (state == WebMediaPlayer::ReadyStateHaveEnoughData && data_source_ &&
1274 data_source_->assume_fully_buffered() &&
1275 network_state_ == WebMediaPlayer::NetworkStateLoading)
1276 SetNetworkState(WebMediaPlayer::NetworkStateLoaded);
1278 ready_state_ = state;
1279 // Always notify to ensure client has the latest value.
1280 client_->readyStateChanged();
1283 blink::WebAudioSourceProvider* WebMediaPlayerImpl::audioSourceProvider() {
1284 return audio_source_provider_.get();
1287 void WebMediaPlayerImpl::IncrementExternallyAllocatedMemory() {
1288 DCHECK(main_loop_->BelongsToCurrentThread());
1289 incremented_externally_allocated_memory_ = true;
1290 v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(
1291 kPlayerExtraMemory);
1294 double WebMediaPlayerImpl::GetPipelineDuration() const {
1295 base::TimeDelta duration = pipeline_.GetMediaDuration();
1297 // Return positive infinity if the resource is unbounded.
1298 // http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#dom-media-duration
1299 if (duration == media::kInfiniteDuration())
1300 return std::numeric_limits<double>::infinity();
1302 return duration.InSecondsF();
1305 void WebMediaPlayerImpl::OnDurationChanged() {
1306 if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
1309 client_->durationChanged();
1312 void WebMediaPlayerImpl::OnNaturalSizeChanged(gfx::Size size) {
1313 DCHECK(main_loop_->BelongsToCurrentThread());
1314 DCHECK_NE(ready_state_, WebMediaPlayer::ReadyStateHaveNothing);
1315 TRACE_EVENT0("media", "WebMediaPlayerImpl::OnNaturalSizeChanged");
1317 media_log_->AddEvent(
1318 media_log_->CreateVideoSizeSetEvent(size.width(), size.height()));
1319 pipeline_metadata_.natural_size = size;
1321 client_->sizeChanged();
1324 void WebMediaPlayerImpl::OnOpacityChanged(bool opaque) {
1325 DCHECK(main_loop_->BelongsToCurrentThread());
1326 DCHECK_NE(ready_state_, WebMediaPlayer::ReadyStateHaveNothing);
1329 if (video_weblayer_)
1330 video_weblayer_->setOpaque(opaque_);
1333 void WebMediaPlayerImpl::FrameReady(
1334 const scoped_refptr<media::VideoFrame>& frame) {
1335 compositor_task_runner_->PostTask(
1337 base::Bind(&VideoFrameCompositor::UpdateCurrentFrame,
1338 base::Unretained(compositor_),
1342 void WebMediaPlayerImpl::SetDecryptorReadyCB(
1343 const media::DecryptorReadyCB& decryptor_ready_cb) {
1344 DCHECK(main_loop_->BelongsToCurrentThread());
1346 // Cancels the previous decryptor request.
1347 if (decryptor_ready_cb.is_null()) {
1348 if (!decryptor_ready_cb_.is_null()) {
1349 base::ResetAndReturn(&decryptor_ready_cb_)
1350 .Run(NULL, base::Bind(DoNothing));
1355 // TODO(xhwang): Support multiple decryptor notification request (e.g. from
1356 // video and audio). The current implementation is okay for the current
1357 // media pipeline since we initialize audio and video decoders in sequence.
1358 // But WebMediaPlayerImpl should not depend on media pipeline's implementation
1360 DCHECK(decryptor_ready_cb_.is_null());
1362 // Mixed use of prefixed and unprefixed EME APIs is disallowed by Blink.
1363 DCHECK(!proxy_decryptor_ || !web_cdm_);
1365 if (proxy_decryptor_) {
1366 decryptor_ready_cb.Run(proxy_decryptor_->GetDecryptor(),
1367 base::Bind(DoNothing));
1372 decryptor_ready_cb.Run(web_cdm_->GetDecryptor(), base::Bind(DoNothing));
1376 decryptor_ready_cb_ = decryptor_ready_cb;
1379 static void GetCurrentFrameAndSignal(
1380 VideoFrameCompositor* compositor,
1381 scoped_refptr<media::VideoFrame>* video_frame_out,
1382 base::WaitableEvent* event) {
1383 TRACE_EVENT0("media", "GetCurrentFrameAndSignal");
1384 *video_frame_out = compositor->GetCurrentFrame();
1388 scoped_refptr<media::VideoFrame>
1389 WebMediaPlayerImpl::GetCurrentFrameFromCompositor() {
1390 TRACE_EVENT0("media", "WebMediaPlayerImpl::GetCurrentFrameFromCompositor");
1391 if (compositor_task_runner_->BelongsToCurrentThread())
1392 return compositor_->GetCurrentFrame();
1394 // Use a posted task and waitable event instead of a lock otherwise
1395 // WebGL/Canvas can see different content than what the compositor is seeing.
1396 scoped_refptr<media::VideoFrame> video_frame;
1397 base::WaitableEvent event(false, false);
1398 compositor_task_runner_->PostTask(FROM_HERE,
1399 base::Bind(&GetCurrentFrameAndSignal,
1400 base::Unretained(compositor_),
1407 } // namespace content