1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "media/blink/webmediaplayer_impl.h"
11 #include "base/bind.h"
12 #include "base/callback.h"
13 #include "base/callback_helpers.h"
14 #include "base/debug/alias.h"
15 #include "base/debug/crash_logging.h"
16 #include "base/metrics/histogram.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/synchronization/waitable_event.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "base/trace_event/trace_event.h"
21 #include "cc/blink/web_layer_impl.h"
22 #include "cc/layers/video_layer.h"
23 #include "gpu/blink/webgraphicscontext3d_impl.h"
24 #include "media/audio/null_audio_sink.h"
25 #include "media/base/bind_to_current_loop.h"
26 #include "media/base/cdm_context.h"
27 #include "media/base/limits.h"
28 #include "media/base/media_log.h"
29 #include "media/base/text_renderer.h"
30 #include "media/base/timestamp_constants.h"
31 #include "media/base/video_frame.h"
32 #include "media/blink/texttrack_impl.h"
33 #include "media/blink/webaudiosourceprovider_impl.h"
34 #include "media/blink/webcontentdecryptionmodule_impl.h"
35 #include "media/blink/webinbandtexttrack_impl.h"
36 #include "media/blink/webmediaplayer_delegate.h"
37 #include "media/blink/webmediaplayer_util.h"
38 #include "media/blink/webmediasource_impl.h"
39 #include "media/filters/chunk_demuxer.h"
40 #include "media/filters/ffmpeg_demuxer.h"
41 #include "third_party/WebKit/public/platform/WebEncryptedMediaTypes.h"
42 #include "third_party/WebKit/public/platform/WebMediaPlayerClient.h"
43 #include "third_party/WebKit/public/platform/WebMediaPlayerEncryptedMediaClient.h"
44 #include "third_party/WebKit/public/platform/WebMediaSource.h"
45 #include "third_party/WebKit/public/platform/WebRect.h"
46 #include "third_party/WebKit/public/platform/WebSize.h"
47 #include "third_party/WebKit/public/platform/WebString.h"
48 #include "third_party/WebKit/public/platform/WebURL.h"
49 #include "third_party/WebKit/public/web/WebDocument.h"
50 #include "third_party/WebKit/public/web/WebFrame.h"
51 #include "third_party/WebKit/public/web/WebLocalFrame.h"
52 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
53 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
54 #include "third_party/WebKit/public/web/WebView.h"
56 using blink::WebCanvas
;
57 using blink::WebMediaPlayer
;
60 using blink::WebString
;
64 // Limits the range of playback rate.
66 // TODO(kylep): Revisit these.
68 // Vista has substantially lower performance than XP or Windows7. If you speed
69 // up a video too much, it can't keep up, and rendering stops updating except on
70 // the time bar. For really high speeds, audio becomes a bottleneck and we just
71 // use up the data we have, which may not achieve the speed requested, but will
74 // A very slow speed, ie 0.00000001x, causes the machine to lock up. (It seems
75 // like a busy loop). It gets unresponsive, although its not completely dead.
77 // Also our timers are not very accurate (especially for ogg), which becomes
78 // evident at low speeds and on Vista. Since other speeds are risky and outside
79 // the norms, we think 1/16x to 16x is a safe and useful range for now.
80 const double kMinRate
= 0.0625;
81 const double kMaxRate
= 16.0;
87 class BufferedDataSourceHostImpl
;
89 #define STATIC_ASSERT_MATCHING_ENUM(name) \
90 static_assert(static_cast<int>(WebMediaPlayer::CORSMode ## name) == \
91 static_cast<int>(BufferedResourceLoader::k ## name), \
92 "mismatching enum values: " #name)
93 STATIC_ASSERT_MATCHING_ENUM(Unspecified
);
94 STATIC_ASSERT_MATCHING_ENUM(Anonymous
);
95 STATIC_ASSERT_MATCHING_ENUM(UseCredentials
);
96 #undef STATIC_ASSERT_MATCHING_ENUM
98 #define BIND_TO_RENDER_LOOP(function) \
99 (DCHECK(main_task_runner_->BelongsToCurrentThread()), \
100 BindToCurrentLoop(base::Bind(function, AsWeakPtr())))
102 #define BIND_TO_RENDER_LOOP1(function, arg1) \
103 (DCHECK(main_task_runner_->BelongsToCurrentThread()), \
104 BindToCurrentLoop(base::Bind(function, AsWeakPtr(), arg1)))
106 WebMediaPlayerImpl::WebMediaPlayerImpl(
107 blink::WebLocalFrame
* frame
,
108 blink::WebMediaPlayerClient
* client
,
109 blink::WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
110 base::WeakPtr
<WebMediaPlayerDelegate
> delegate
,
111 scoped_ptr
<RendererFactory
> renderer_factory
,
112 CdmFactory
* cdm_factory
,
113 const WebMediaPlayerParams
& params
)
115 network_state_(WebMediaPlayer::NetworkStateEmpty
),
116 ready_state_(WebMediaPlayer::ReadyStateHaveNothing
),
117 preload_(BufferedDataSource::AUTO
),
118 main_task_runner_(base::ThreadTaskRunnerHandle::Get()),
119 media_task_runner_(params
.media_task_runner()),
120 worker_task_runner_(params
.worker_task_runner()),
121 media_log_(params
.media_log()),
122 pipeline_(media_task_runner_
, media_log_
.get()),
123 load_type_(LoadTypeURL
),
129 pending_seek_(false),
130 should_notify_time_changed_(false),
132 encrypted_client_(encrypted_client
),
134 defer_load_cb_(params
.defer_load_cb()),
135 context_3d_cb_(params
.context_3d_cb()),
136 supports_save_(true),
137 chunk_demuxer_(NULL
),
138 // Threaded compositing isn't enabled universally yet.
139 compositor_task_runner_(
140 params
.compositor_task_runner()
141 ? params
.compositor_task_runner()
142 : base::MessageLoop::current()->task_runner()),
143 compositor_(new VideoFrameCompositor(
144 compositor_task_runner_
,
145 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnNaturalSizeChanged
),
146 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnOpacityChanged
))),
147 encrypted_media_support_(cdm_factory
,
149 params
.media_permission(),
150 base::Bind(&WebMediaPlayerImpl::SetCdm
,
152 base::Bind(&IgnoreCdmAttached
))),
153 renderer_factory_(renderer_factory
.Pass()) {
154 media_log_
->AddEvent(
155 media_log_
->CreateEvent(MediaLogEvent::WEBMEDIAPLAYER_CREATED
));
157 if (params
.initial_cdm()) {
158 SetCdm(base::Bind(&IgnoreCdmAttached
),
159 ToWebContentDecryptionModuleImpl(params
.initial_cdm())
163 // TODO(xhwang): When we use an external Renderer, many methods won't work,
164 // e.g. GetCurrentFrameFromCompositor(). See http://crbug.com/434861
166 // Use the null sink if no sink was provided.
167 audio_source_provider_
= new WebAudioSourceProviderImpl(
168 params
.audio_renderer_sink().get()
169 ? params
.audio_renderer_sink()
170 : new NullAudioSink(media_task_runner_
));
173 WebMediaPlayerImpl::~WebMediaPlayerImpl() {
174 client_
->setWebLayer(NULL
);
176 DCHECK(main_task_runner_
->BelongsToCurrentThread());
179 delegate_
->PlayerGone(this);
181 // Abort any pending IO so stopping the pipeline doesn't get blocked.
183 data_source_
->Abort();
184 if (chunk_demuxer_
) {
185 chunk_demuxer_
->Shutdown();
186 chunk_demuxer_
= NULL
;
189 renderer_factory_
.reset();
191 // Make sure to kill the pipeline so there's no more media threads running.
192 // Note: stopping the pipeline might block for a long time.
193 base::WaitableEvent
waiter(false, false);
195 base::Bind(&base::WaitableEvent::Signal
, base::Unretained(&waiter
)));
198 compositor_task_runner_
->DeleteSoon(FROM_HERE
, compositor_
);
200 media_log_
->AddEvent(
201 media_log_
->CreateEvent(MediaLogEvent::WEBMEDIAPLAYER_DESTROYED
));
204 void WebMediaPlayerImpl::load(LoadType load_type
, const blink::WebURL
& url
,
205 CORSMode cors_mode
) {
206 DVLOG(1) << __FUNCTION__
<< "(" << load_type
<< ", " << url
<< ", "
208 if (!defer_load_cb_
.is_null()) {
209 defer_load_cb_
.Run(base::Bind(
210 &WebMediaPlayerImpl::DoLoad
, AsWeakPtr(), load_type
, url
, cors_mode
));
213 DoLoad(load_type
, url
, cors_mode
);
216 void WebMediaPlayerImpl::DoLoad(LoadType load_type
,
217 const blink::WebURL
& url
,
218 CORSMode cors_mode
) {
219 DCHECK(main_task_runner_
->BelongsToCurrentThread());
222 ReportMetrics(load_type
, gurl
,
223 GURL(frame_
->document().securityOrigin().toString()));
225 // Set subresource URL for crash reporting.
226 base::debug::SetCrashKeyValue("subresource_url", gurl
.spec());
228 load_type_
= load_type
;
230 SetNetworkState(WebMediaPlayer::NetworkStateLoading
);
231 SetReadyState(WebMediaPlayer::ReadyStateHaveNothing
);
232 media_log_
->AddEvent(media_log_
->CreateLoadEvent(url
.spec()));
234 // Media source pipelines can start immediately.
235 if (load_type
== LoadTypeMediaSource
) {
236 supports_save_
= false;
241 // Otherwise it's a regular request which requires resolving the URL first.
242 data_source_
.reset(new BufferedDataSource(
244 static_cast<BufferedResourceLoader::CORSMode
>(cors_mode
),
248 &buffered_data_source_host_
,
249 base::Bind(&WebMediaPlayerImpl::NotifyDownloading
, AsWeakPtr())));
250 data_source_
->SetPreload(preload_
);
251 data_source_
->Initialize(
252 base::Bind(&WebMediaPlayerImpl::DataSourceInitialized
, AsWeakPtr()));
255 void WebMediaPlayerImpl::play() {
256 DVLOG(1) << __FUNCTION__
;
257 DCHECK(main_task_runner_
->BelongsToCurrentThread());
260 pipeline_
.SetPlaybackRate(playback_rate_
);
262 data_source_
->MediaIsPlaying();
264 media_log_
->AddEvent(media_log_
->CreateEvent(MediaLogEvent::PLAY
));
266 if (delegate_
&& playback_rate_
> 0)
267 delegate_
->DidPlay(this);
270 void WebMediaPlayerImpl::pause() {
271 DVLOG(1) << __FUNCTION__
;
272 DCHECK(main_task_runner_
->BelongsToCurrentThread());
274 const bool was_already_paused
= paused_
|| playback_rate_
== 0;
276 pipeline_
.SetPlaybackRate(0.0);
278 data_source_
->MediaIsPaused();
281 media_log_
->AddEvent(media_log_
->CreateEvent(MediaLogEvent::PAUSE
));
283 if (!was_already_paused
&& delegate_
)
284 delegate_
->DidPause(this);
287 bool WebMediaPlayerImpl::supportsSave() const {
288 DCHECK(main_task_runner_
->BelongsToCurrentThread());
289 return supports_save_
;
292 void WebMediaPlayerImpl::seek(double seconds
) {
293 DVLOG(1) << __FUNCTION__
<< "(" << seconds
<< "s)";
294 DCHECK(main_task_runner_
->BelongsToCurrentThread());
298 ReadyState old_state
= ready_state_
;
299 if (ready_state_
> WebMediaPlayer::ReadyStateHaveMetadata
)
300 SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata
);
302 base::TimeDelta new_seek_time
= base::TimeDelta::FromSecondsD(seconds
);
305 if (new_seek_time
== seek_time_
) {
306 if (chunk_demuxer_
) {
307 // Don't suppress any redundant in-progress MSE seek. There could have
308 // been changes to the underlying buffers after seeking the demuxer and
309 // before receiving OnPipelineSeeked() for the currently in-progress
311 MEDIA_LOG(DEBUG
, media_log_
)
312 << "Detected MediaSource seek to same time as in-progress seek to "
313 << seek_time_
<< ".";
315 // Suppress all redundant seeks if unrestricted by media source demuxer
317 pending_seek_
= false;
318 pending_seek_time_
= base::TimeDelta();
323 pending_seek_
= true;
324 pending_seek_time_
= new_seek_time
;
326 chunk_demuxer_
->CancelPendingSeek(pending_seek_time_
);
330 media_log_
->AddEvent(media_log_
->CreateSeekEvent(seconds
));
332 // Update our paused time.
333 // For non-MSE playbacks, in paused state ignore the seek operations to
334 // current time if the loading is completed and generate
335 // OnPipelineBufferingStateChanged event to eventually fire seeking and seeked
336 // events. We don't short-circuit MSE seeks in this logic because the
337 // underlying buffers around the seek time might have changed (or even been
338 // removed) since previous seek/preroll/pause action, and the pipeline might
339 // need to flush so the new buffers are decoded and rendered instead of the
342 if (paused_time_
!= new_seek_time
|| chunk_demuxer_
) {
343 paused_time_
= new_seek_time
;
344 } else if (old_state
== ReadyStateHaveEnoughData
) {
345 main_task_runner_
->PostTask(
347 base::Bind(&WebMediaPlayerImpl::OnPipelineBufferingStateChanged
,
348 AsWeakPtr(), BUFFERING_HAVE_ENOUGH
));
354 seek_time_
= new_seek_time
;
357 chunk_demuxer_
->StartWaitingForSeek(seek_time_
);
359 // Kick off the asynchronous seek!
360 pipeline_
.Seek(seek_time_
, BIND_TO_RENDER_LOOP1(
361 &WebMediaPlayerImpl::OnPipelineSeeked
, true));
364 void WebMediaPlayerImpl::setRate(double rate
) {
365 DVLOG(1) << __FUNCTION__
<< "(" << rate
<< ")";
366 DCHECK(main_task_runner_
->BelongsToCurrentThread());
368 // TODO(kylep): Remove when support for negatives is added. Also, modify the
369 // following checks so rewind uses reasonable values also.
373 // Limit rates to reasonable values by clamping.
377 else if (rate
> kMaxRate
)
379 if (playback_rate_
== 0 && !paused_
&& delegate_
)
380 delegate_
->DidPlay(this);
381 } else if (playback_rate_
!= 0 && !paused_
&& delegate_
) {
382 delegate_
->DidPause(this);
385 playback_rate_
= rate
;
387 pipeline_
.SetPlaybackRate(rate
);
389 data_source_
->MediaPlaybackRateChanged(rate
);
393 void WebMediaPlayerImpl::setVolume(double volume
) {
394 DVLOG(1) << __FUNCTION__
<< "(" << volume
<< ")";
395 DCHECK(main_task_runner_
->BelongsToCurrentThread());
397 pipeline_
.SetVolume(volume
);
400 void WebMediaPlayerImpl::setSinkId(const blink::WebString
& device_id
,
401 WebSetSinkIdCB
* web_callback
) {
402 DCHECK(main_task_runner_
->BelongsToCurrentThread());
403 DVLOG(1) << __FUNCTION__
;
404 media::SwitchOutputDeviceCB callback
=
405 media::ConvertToSwitchOutputDeviceCB(web_callback
);
406 OutputDevice
* output_device
= audio_source_provider_
->GetOutputDevice();
408 std::string
device_id_str(device_id
.utf8());
409 GURL
security_origin(frame_
->securityOrigin().toString().utf8());
410 output_device
->SwitchOutputDevice(device_id_str
, security_origin
, callback
);
412 callback
.Run(SWITCH_OUTPUT_DEVICE_RESULT_ERROR_NOT_SUPPORTED
);
416 #define STATIC_ASSERT_MATCHING_ENUM(webkit_name, chromium_name) \
417 static_assert(static_cast<int>(WebMediaPlayer::webkit_name) == \
418 static_cast<int>(BufferedDataSource::chromium_name), \
419 "mismatching enum values: " #webkit_name)
420 STATIC_ASSERT_MATCHING_ENUM(PreloadNone
, NONE
);
421 STATIC_ASSERT_MATCHING_ENUM(PreloadMetaData
, METADATA
);
422 STATIC_ASSERT_MATCHING_ENUM(PreloadAuto
, AUTO
);
423 #undef STATIC_ASSERT_MATCHING_ENUM
425 void WebMediaPlayerImpl::setPreload(WebMediaPlayer::Preload preload
) {
426 DVLOG(1) << __FUNCTION__
<< "(" << preload
<< ")";
427 DCHECK(main_task_runner_
->BelongsToCurrentThread());
429 preload_
= static_cast<BufferedDataSource::Preload
>(preload
);
431 data_source_
->SetPreload(preload_
);
434 bool WebMediaPlayerImpl::hasVideo() const {
435 DCHECK(main_task_runner_
->BelongsToCurrentThread());
437 return pipeline_metadata_
.has_video
;
440 bool WebMediaPlayerImpl::hasAudio() const {
441 DCHECK(main_task_runner_
->BelongsToCurrentThread());
443 return pipeline_metadata_
.has_audio
;
446 blink::WebSize
WebMediaPlayerImpl::naturalSize() const {
447 DCHECK(main_task_runner_
->BelongsToCurrentThread());
449 return blink::WebSize(pipeline_metadata_
.natural_size
);
452 bool WebMediaPlayerImpl::paused() const {
453 DCHECK(main_task_runner_
->BelongsToCurrentThread());
455 return pipeline_
.GetPlaybackRate() == 0.0f
;
458 bool WebMediaPlayerImpl::seeking() const {
459 DCHECK(main_task_runner_
->BelongsToCurrentThread());
461 if (ready_state_
== WebMediaPlayer::ReadyStateHaveNothing
)
467 double WebMediaPlayerImpl::duration() const {
468 DCHECK(main_task_runner_
->BelongsToCurrentThread());
470 if (ready_state_
== WebMediaPlayer::ReadyStateHaveNothing
)
471 return std::numeric_limits
<double>::quiet_NaN();
473 return GetPipelineDuration();
476 double WebMediaPlayerImpl::timelineOffset() const {
477 DCHECK(main_task_runner_
->BelongsToCurrentThread());
479 if (pipeline_metadata_
.timeline_offset
.is_null())
480 return std::numeric_limits
<double>::quiet_NaN();
482 return pipeline_metadata_
.timeline_offset
.ToJsTime();
485 double WebMediaPlayerImpl::currentTime() const {
486 DCHECK(main_task_runner_
->BelongsToCurrentThread());
487 DCHECK_NE(ready_state_
, WebMediaPlayer::ReadyStateHaveNothing
);
489 // TODO(scherkus): Replace with an explicit ended signal to HTMLMediaElement,
490 // see http://crbug.com/409280
494 // We know the current seek time better than pipeline: pipeline may processing
495 // an earlier seek before a pending seek has been started, or it might not yet
496 // have the current seek time returnable via GetMediaTime().
498 return pending_seek_
? pending_seek_time_
.InSecondsF()
499 : seek_time_
.InSecondsF();
502 return (paused_
? paused_time_
: pipeline_
.GetMediaTime()).InSecondsF();
505 WebMediaPlayer::NetworkState
WebMediaPlayerImpl::networkState() const {
506 DCHECK(main_task_runner_
->BelongsToCurrentThread());
507 return network_state_
;
510 WebMediaPlayer::ReadyState
WebMediaPlayerImpl::readyState() const {
511 DCHECK(main_task_runner_
->BelongsToCurrentThread());
515 blink::WebTimeRanges
WebMediaPlayerImpl::buffered() const {
516 DCHECK(main_task_runner_
->BelongsToCurrentThread());
518 Ranges
<base::TimeDelta
> buffered_time_ranges
=
519 pipeline_
.GetBufferedTimeRanges();
521 const base::TimeDelta duration
= pipeline_
.GetMediaDuration();
522 if (duration
!= kInfiniteDuration()) {
523 buffered_data_source_host_
.AddBufferedTimeRanges(
524 &buffered_time_ranges
, duration
);
526 return ConvertToWebTimeRanges(buffered_time_ranges
);
529 blink::WebTimeRanges
WebMediaPlayerImpl::seekable() const {
530 DCHECK(main_task_runner_
->BelongsToCurrentThread());
532 if (ready_state_
< WebMediaPlayer::ReadyStateHaveMetadata
)
533 return blink::WebTimeRanges();
535 const double seekable_end
= duration();
537 // Allow a special exception for seeks to zero for streaming sources with a
538 // finite duration; this allows looping to work.
539 const bool allow_seek_to_zero
= data_source_
&& data_source_
->IsStreaming() &&
540 std::isfinite(seekable_end
);
542 // TODO(dalecurtis): Technically this allows seeking on media which return an
543 // infinite duration so long as DataSource::IsStreaming() is false. While not
544 // expected, disabling this breaks semi-live players, http://crbug.com/427412.
545 const blink::WebTimeRange
seekable_range(
546 0.0, allow_seek_to_zero
? 0.0 : seekable_end
);
547 return blink::WebTimeRanges(&seekable_range
, 1);
550 bool WebMediaPlayerImpl::didLoadingProgress() {
551 DCHECK(main_task_runner_
->BelongsToCurrentThread());
552 bool pipeline_progress
= pipeline_
.DidLoadingProgress();
553 bool data_progress
= buffered_data_source_host_
.DidLoadingProgress();
554 return pipeline_progress
|| data_progress
;
557 void WebMediaPlayerImpl::paint(blink::WebCanvas
* canvas
,
558 const blink::WebRect
& rect
,
560 SkXfermode::Mode mode
) {
561 DCHECK(main_task_runner_
->BelongsToCurrentThread());
562 TRACE_EVENT0("media", "WebMediaPlayerImpl:paint");
564 // TODO(scherkus): Clarify paint() API contract to better understand when and
565 // why it's being called. For example, today paint() is called when:
566 // - We haven't reached HAVE_CURRENT_DATA and need to paint black
567 // - We're painting to a canvas
568 // See http://crbug.com/341225 http://crbug.com/342621 for details.
569 scoped_refptr
<VideoFrame
> video_frame
= GetCurrentFrameFromCompositor();
571 gfx::Rect
gfx_rect(rect
);
572 Context3D context_3d
;
573 if (video_frame
.get() && video_frame
->HasTextures()) {
574 if (!context_3d_cb_
.is_null())
575 context_3d
= context_3d_cb_
.Run();
576 // GPU Process crashed.
580 skcanvas_video_renderer_
.Paint(video_frame
, canvas
, gfx::RectF(gfx_rect
),
581 alpha
, mode
, pipeline_metadata_
.video_rotation
,
585 bool WebMediaPlayerImpl::hasSingleSecurityOrigin() const {
587 return data_source_
->HasSingleOrigin();
591 bool WebMediaPlayerImpl::didPassCORSAccessCheck() const {
593 return data_source_
->DidPassCORSAccessCheck();
597 double WebMediaPlayerImpl::mediaTimeForTimeValue(double timeValue
) const {
598 return base::TimeDelta::FromSecondsD(timeValue
).InSecondsF();
601 unsigned WebMediaPlayerImpl::decodedFrameCount() const {
602 DCHECK(main_task_runner_
->BelongsToCurrentThread());
604 PipelineStatistics stats
= pipeline_
.GetStatistics();
605 return stats
.video_frames_decoded
;
608 unsigned WebMediaPlayerImpl::droppedFrameCount() const {
609 DCHECK(main_task_runner_
->BelongsToCurrentThread());
611 PipelineStatistics stats
= pipeline_
.GetStatistics();
612 return stats
.video_frames_dropped
;
615 unsigned WebMediaPlayerImpl::audioDecodedByteCount() const {
616 DCHECK(main_task_runner_
->BelongsToCurrentThread());
618 PipelineStatistics stats
= pipeline_
.GetStatistics();
619 return stats
.audio_bytes_decoded
;
622 unsigned WebMediaPlayerImpl::videoDecodedByteCount() const {
623 DCHECK(main_task_runner_
->BelongsToCurrentThread());
625 PipelineStatistics stats
= pipeline_
.GetStatistics();
626 return stats
.video_bytes_decoded
;
629 bool WebMediaPlayerImpl::copyVideoTextureToPlatformTexture(
630 blink::WebGraphicsContext3D
* web_graphics_context
,
631 unsigned int texture
,
632 unsigned int internal_format
,
634 bool premultiply_alpha
,
636 TRACE_EVENT0("media", "WebMediaPlayerImpl:copyVideoTextureToPlatformTexture");
638 scoped_refptr
<VideoFrame
> video_frame
= GetCurrentFrameFromCompositor();
640 if (!video_frame
.get() || !video_frame
->HasTextures() ||
641 media::VideoFrame::NumPlanes(video_frame
->format()) != 1) {
645 // TODO(dshwang): need more elegant way to convert WebGraphicsContext3D to
647 gpu::gles2::GLES2Interface
* gl
=
648 static_cast<gpu_blink::WebGraphicsContext3DImpl
*>(web_graphics_context
)
650 SkCanvasVideoRenderer::CopyVideoFrameSingleTextureToGLTexture(
651 gl
, video_frame
.get(), texture
, internal_format
, type
, premultiply_alpha
,
656 WebMediaPlayer::MediaKeyException
657 WebMediaPlayerImpl::generateKeyRequest(const WebString
& key_system
,
658 const unsigned char* init_data
,
659 unsigned init_data_length
) {
660 DCHECK(main_task_runner_
->BelongsToCurrentThread());
662 return encrypted_media_support_
.GenerateKeyRequest(
663 frame_
, key_system
, init_data
, init_data_length
);
666 WebMediaPlayer::MediaKeyException
WebMediaPlayerImpl::addKey(
667 const WebString
& key_system
,
668 const unsigned char* key
,
670 const unsigned char* init_data
,
671 unsigned init_data_length
,
672 const WebString
& session_id
) {
673 DCHECK(main_task_runner_
->BelongsToCurrentThread());
675 return encrypted_media_support_
.AddKey(
676 key_system
, key
, key_length
, init_data
, init_data_length
, session_id
);
679 WebMediaPlayer::MediaKeyException
WebMediaPlayerImpl::cancelKeyRequest(
680 const WebString
& key_system
,
681 const WebString
& session_id
) {
682 DCHECK(main_task_runner_
->BelongsToCurrentThread());
684 return encrypted_media_support_
.CancelKeyRequest(key_system
, session_id
);
687 void WebMediaPlayerImpl::setContentDecryptionModule(
688 blink::WebContentDecryptionModule
* cdm
,
689 blink::WebContentDecryptionModuleResult result
) {
690 DCHECK(main_task_runner_
->BelongsToCurrentThread());
692 // Once the CDM is set it can't be cleared as there may be frames being
693 // decrypted on other threads. So fail this request.
694 // http://crbug.com/462365#c7.
696 result
.completeWithError(
697 blink::WebContentDecryptionModuleExceptionInvalidStateError
, 0,
698 "The existing MediaKeys object cannot be removed at this time.");
702 // Although unlikely, it is possible that multiple calls happen
703 // simultaneously, so fail this call if there is already one pending.
704 if (set_cdm_result_
) {
705 result
.completeWithError(
706 blink::WebContentDecryptionModuleExceptionInvalidStateError
, 0,
707 "Unable to set MediaKeys object at this time.");
711 // Create a local copy of |result| to avoid problems with the callback
712 // getting passed to the media thread and causing |result| to be destructed
713 // on the wrong thread in some failure conditions.
714 set_cdm_result_
.reset(new blink::WebContentDecryptionModuleResult(result
));
716 SetCdm(BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnCdmAttached
),
717 ToWebContentDecryptionModuleImpl(cdm
)->GetCdmContext());
720 void WebMediaPlayerImpl::OnEncryptedMediaInitData(
721 EmeInitDataType init_data_type
,
722 const std::vector
<uint8
>& init_data
) {
723 DCHECK(init_data_type
!= EmeInitDataType::UNKNOWN
);
725 // Do not fire "encrypted" event if encrypted media is not enabled.
726 // TODO(xhwang): Handle this in |client_|.
727 if (!blink::WebRuntimeFeatures::isPrefixedEncryptedMediaEnabled() &&
728 !blink::WebRuntimeFeatures::isEncryptedMediaEnabled()) {
732 // TODO(xhwang): Update this UMA name.
733 UMA_HISTOGRAM_COUNTS("Media.EME.NeedKey", 1);
735 encrypted_media_support_
.SetInitDataType(init_data_type
);
737 encrypted_client_
->encrypted(
738 ConvertToWebInitDataType(init_data_type
), vector_as_array(&init_data
),
739 base::saturated_cast
<unsigned int>(init_data
.size()));
742 void WebMediaPlayerImpl::OnWaitingForDecryptionKey() {
743 encrypted_client_
->didBlockPlaybackWaitingForKey();
745 // TODO(jrummell): didResumePlaybackBlockedForKey() should only be called
746 // when a key has been successfully added (e.g. OnSessionKeysChange() with
747 // |has_additional_usable_key| = true). http://crbug.com/461903
748 encrypted_client_
->didResumePlaybackBlockedForKey();
751 void WebMediaPlayerImpl::SetCdm(const CdmAttachedCB
& cdm_attached_cb
,
752 CdmContext
* cdm_context
) {
753 // If CDM initialization succeeded, tell the pipeline about it.
755 pipeline_
.SetCdm(cdm_context
, cdm_attached_cb
);
758 void WebMediaPlayerImpl::OnCdmAttached(bool success
) {
760 set_cdm_result_
->complete();
761 set_cdm_result_
.reset();
765 set_cdm_result_
->completeWithError(
766 blink::WebContentDecryptionModuleExceptionNotSupportedError
, 0,
767 "Unable to set MediaKeys object");
768 set_cdm_result_
.reset();
771 void WebMediaPlayerImpl::OnPipelineSeeked(bool time_changed
,
772 PipelineStatus status
) {
773 DVLOG(1) << __FUNCTION__
<< "(" << time_changed
<< ", " << status
<< ")";
774 DCHECK(main_task_runner_
->BelongsToCurrentThread());
776 seek_time_
= base::TimeDelta();
778 double pending_seek_seconds
= pending_seek_time_
.InSecondsF();
779 pending_seek_
= false;
780 pending_seek_time_
= base::TimeDelta();
781 seek(pending_seek_seconds
);
785 if (status
!= PIPELINE_OK
) {
786 OnPipelineError(status
);
790 // Update our paused time.
794 should_notify_time_changed_
= time_changed
;
797 void WebMediaPlayerImpl::OnPipelineEnded() {
798 DVLOG(1) << __FUNCTION__
;
799 DCHECK(main_task_runner_
->BelongsToCurrentThread());
801 // Ignore state changes until we've completed all outstanding seeks.
802 if (seeking_
|| pending_seek_
)
806 client_
->timeChanged();
809 void WebMediaPlayerImpl::OnPipelineError(PipelineStatus error
) {
810 DCHECK(main_task_runner_
->BelongsToCurrentThread());
811 DCHECK_NE(error
, PIPELINE_OK
);
813 if (ready_state_
== WebMediaPlayer::ReadyStateHaveNothing
) {
814 // Any error that occurs before reaching ReadyStateHaveMetadata should
815 // be considered a format error.
816 SetNetworkState(WebMediaPlayer::NetworkStateFormatError
);
820 SetNetworkState(PipelineErrorToNetworkState(error
));
823 void WebMediaPlayerImpl::OnPipelineMetadata(
824 PipelineMetadata metadata
) {
825 DVLOG(1) << __FUNCTION__
;
827 pipeline_metadata_
= metadata
;
829 UMA_HISTOGRAM_ENUMERATION("Media.VideoRotation", metadata
.video_rotation
,
830 VIDEO_ROTATION_MAX
+ 1);
831 SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata
);
834 DCHECK(!video_weblayer_
);
835 scoped_refptr
<cc::VideoLayer
> layer
=
836 cc::VideoLayer::Create(cc_blink::WebLayerImpl::LayerSettings(),
837 compositor_
, pipeline_metadata_
.video_rotation
);
839 if (pipeline_metadata_
.video_rotation
== VIDEO_ROTATION_90
||
840 pipeline_metadata_
.video_rotation
== VIDEO_ROTATION_270
) {
841 gfx::Size size
= pipeline_metadata_
.natural_size
;
842 pipeline_metadata_
.natural_size
= gfx::Size(size
.height(), size
.width());
845 video_weblayer_
.reset(new cc_blink::WebLayerImpl(layer
));
846 video_weblayer_
->layer()->SetContentsOpaque(opaque_
);
847 video_weblayer_
->SetContentsOpaqueIsFixed(true);
848 client_
->setWebLayer(video_weblayer_
.get());
852 void WebMediaPlayerImpl::OnPipelineBufferingStateChanged(
853 BufferingState buffering_state
) {
854 DVLOG(1) << __FUNCTION__
<< "(" << buffering_state
<< ")";
856 // Ignore buffering state changes until we've completed all outstanding seeks.
857 if (seeking_
|| pending_seek_
)
860 // TODO(scherkus): Handle other buffering states when Pipeline starts using
861 // them and translate them ready state changes http://crbug.com/144683
862 DCHECK_EQ(buffering_state
, BUFFERING_HAVE_ENOUGH
);
863 SetReadyState(WebMediaPlayer::ReadyStateHaveEnoughData
);
865 // Let the DataSource know we have enough data. It may use this information to
866 // release unused network connections.
868 data_source_
->OnBufferingHaveEnough();
870 // Blink expects a timeChanged() in response to a seek().
871 if (should_notify_time_changed_
)
872 client_
->timeChanged();
875 void WebMediaPlayerImpl::OnDemuxerOpened() {
876 DCHECK(main_task_runner_
->BelongsToCurrentThread());
877 client_
->mediaSourceOpened(
878 new WebMediaSourceImpl(chunk_demuxer_
, media_log_
));
881 void WebMediaPlayerImpl::OnAddTextTrack(
882 const TextTrackConfig
& config
,
883 const AddTextTrackDoneCB
& done_cb
) {
884 DCHECK(main_task_runner_
->BelongsToCurrentThread());
886 const WebInbandTextTrackImpl::Kind web_kind
=
887 static_cast<WebInbandTextTrackImpl::Kind
>(config
.kind());
888 const blink::WebString web_label
=
889 blink::WebString::fromUTF8(config
.label());
890 const blink::WebString web_language
=
891 blink::WebString::fromUTF8(config
.language());
892 const blink::WebString web_id
=
893 blink::WebString::fromUTF8(config
.id());
895 scoped_ptr
<WebInbandTextTrackImpl
> web_inband_text_track(
896 new WebInbandTextTrackImpl(web_kind
, web_label
, web_language
, web_id
));
898 scoped_ptr
<TextTrack
> text_track(new TextTrackImpl(
899 main_task_runner_
, client_
, web_inband_text_track
.Pass()));
901 done_cb
.Run(text_track
.Pass());
904 void WebMediaPlayerImpl::DataSourceInitialized(bool success
) {
905 DCHECK(main_task_runner_
->BelongsToCurrentThread());
908 SetNetworkState(WebMediaPlayer::NetworkStateFormatError
);
915 void WebMediaPlayerImpl::NotifyDownloading(bool is_downloading
) {
916 if (!is_downloading
&& network_state_
== WebMediaPlayer::NetworkStateLoading
)
917 SetNetworkState(WebMediaPlayer::NetworkStateIdle
);
918 else if (is_downloading
&& network_state_
== WebMediaPlayer::NetworkStateIdle
)
919 SetNetworkState(WebMediaPlayer::NetworkStateLoading
);
920 media_log_
->AddEvent(
921 media_log_
->CreateBooleanEvent(
922 MediaLogEvent::NETWORK_ACTIVITY_SET
,
923 "is_downloading_data", is_downloading
));
926 void WebMediaPlayerImpl::StartPipeline() {
927 DCHECK(main_task_runner_
->BelongsToCurrentThread());
929 Demuxer::EncryptedMediaInitDataCB encrypted_media_init_data_cb
=
930 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnEncryptedMediaInitData
);
932 // Figure out which demuxer to use.
933 if (load_type_
!= LoadTypeMediaSource
) {
934 DCHECK(!chunk_demuxer_
);
935 DCHECK(data_source_
);
937 demuxer_
.reset(new FFmpegDemuxer(media_task_runner_
, data_source_
.get(),
938 encrypted_media_init_data_cb
, media_log_
));
940 DCHECK(!chunk_demuxer_
);
941 DCHECK(!data_source_
);
943 chunk_demuxer_
= new ChunkDemuxer(
944 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnDemuxerOpened
),
945 encrypted_media_init_data_cb
, media_log_
, true);
946 demuxer_
.reset(chunk_demuxer_
);
949 // ... and we're ready to go!
953 demuxer_
.get(), renderer_factory_
->CreateRenderer(
954 media_task_runner_
, worker_task_runner_
,
955 audio_source_provider_
.get(), compositor_
),
956 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineEnded
),
957 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineError
),
958 BIND_TO_RENDER_LOOP1(&WebMediaPlayerImpl::OnPipelineSeeked
, false),
959 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineMetadata
),
960 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineBufferingStateChanged
),
961 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnDurationChanged
),
962 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnAddTextTrack
),
963 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnWaitingForDecryptionKey
));
966 void WebMediaPlayerImpl::SetNetworkState(WebMediaPlayer::NetworkState state
) {
967 DVLOG(1) << __FUNCTION__
<< "(" << state
<< ")";
968 DCHECK(main_task_runner_
->BelongsToCurrentThread());
969 network_state_
= state
;
970 // Always notify to ensure client has the latest value.
971 client_
->networkStateChanged();
974 void WebMediaPlayerImpl::SetReadyState(WebMediaPlayer::ReadyState state
) {
975 DVLOG(1) << __FUNCTION__
<< "(" << state
<< ")";
976 DCHECK(main_task_runner_
->BelongsToCurrentThread());
978 if (state
== WebMediaPlayer::ReadyStateHaveEnoughData
&& data_source_
&&
979 data_source_
->assume_fully_buffered() &&
980 network_state_
== WebMediaPlayer::NetworkStateLoading
)
981 SetNetworkState(WebMediaPlayer::NetworkStateLoaded
);
983 ready_state_
= state
;
984 // Always notify to ensure client has the latest value.
985 client_
->readyStateChanged();
988 blink::WebAudioSourceProvider
* WebMediaPlayerImpl::audioSourceProvider() {
989 return audio_source_provider_
.get();
992 double WebMediaPlayerImpl::GetPipelineDuration() const {
993 base::TimeDelta duration
= pipeline_
.GetMediaDuration();
995 // Return positive infinity if the resource is unbounded.
996 // http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#dom-media-duration
997 if (duration
== kInfiniteDuration())
998 return std::numeric_limits
<double>::infinity();
1000 return duration
.InSecondsF();
1003 void WebMediaPlayerImpl::OnDurationChanged() {
1004 if (ready_state_
== WebMediaPlayer::ReadyStateHaveNothing
)
1007 client_
->durationChanged();
1010 void WebMediaPlayerImpl::OnNaturalSizeChanged(gfx::Size size
) {
1011 DCHECK(main_task_runner_
->BelongsToCurrentThread());
1012 DCHECK_NE(ready_state_
, WebMediaPlayer::ReadyStateHaveNothing
);
1013 TRACE_EVENT0("media", "WebMediaPlayerImpl::OnNaturalSizeChanged");
1015 media_log_
->AddEvent(
1016 media_log_
->CreateVideoSizeSetEvent(size
.width(), size
.height()));
1017 pipeline_metadata_
.natural_size
= size
;
1019 client_
->sizeChanged();
1022 void WebMediaPlayerImpl::OnOpacityChanged(bool opaque
) {
1023 DCHECK(main_task_runner_
->BelongsToCurrentThread());
1024 DCHECK_NE(ready_state_
, WebMediaPlayer::ReadyStateHaveNothing
);
1027 // Modify content opaqueness of cc::Layer directly so that
1028 // SetContentsOpaqueIsFixed is ignored.
1029 if (video_weblayer_
)
1030 video_weblayer_
->layer()->SetContentsOpaque(opaque_
);
1033 static void GetCurrentFrameAndSignal(
1034 VideoFrameCompositor
* compositor
,
1035 scoped_refptr
<VideoFrame
>* video_frame_out
,
1036 base::WaitableEvent
* event
) {
1037 TRACE_EVENT0("media", "GetCurrentFrameAndSignal");
1038 *video_frame_out
= compositor
->GetCurrentFrameAndUpdateIfStale();
1042 scoped_refptr
<VideoFrame
>
1043 WebMediaPlayerImpl::GetCurrentFrameFromCompositor() {
1044 TRACE_EVENT0("media", "WebMediaPlayerImpl::GetCurrentFrameFromCompositor");
1045 if (compositor_task_runner_
->BelongsToCurrentThread())
1046 return compositor_
->GetCurrentFrameAndUpdateIfStale();
1048 // Use a posted task and waitable event instead of a lock otherwise
1049 // WebGL/Canvas can see different content than what the compositor is seeing.
1050 scoped_refptr
<VideoFrame
> video_frame
;
1051 base::WaitableEvent
event(false, false);
1052 compositor_task_runner_
->PostTask(FROM_HERE
,
1053 base::Bind(&GetCurrentFrameAndSignal
,
1054 base::Unretained(compositor_
),
1061 void WebMediaPlayerImpl::UpdatePausedTime() {
1062 DCHECK(main_task_runner_
->BelongsToCurrentThread());
1064 // pause() may be called after playback has ended and the HTMLMediaElement
1065 // requires that currentTime() == duration() after ending. We want to ensure
1066 // |paused_time_| matches currentTime() in this case or a future seek() may
1067 // incorrectly discard what it thinks is a seek to the existing time.
1069 ended_
? pipeline_
.GetMediaDuration() : pipeline_
.GetMediaTime();
1072 } // namespace media