Update V8 to version 4.7.56.
[chromium-blink-merge.git] / media / blink / webmediaplayer_impl.cc
blob2cb8eccf5171862b7d9843e2e5f7c05e2fe5ee06
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"
7 #include <algorithm>
8 #include <cmath>
9 #include <limits>
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;
58 using blink::WebRect;
59 using blink::WebSize;
60 using blink::WebString;
62 namespace {
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
72 // not crash the tab.
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;
83 } // namespace
85 namespace media {
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)
114 : frame_(frame),
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),
124 opaque_(false),
125 playback_rate_(0.0),
126 paused_(true),
127 seeking_(false),
128 ended_(false),
129 pending_seek_(false),
130 should_notify_time_changed_(false),
131 client_(client),
132 encrypted_client_(encrypted_client),
133 delegate_(delegate),
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,
148 encrypted_client,
149 params.media_permission(),
150 base::Bind(&WebMediaPlayerImpl::SetCdm,
151 AsWeakPtr(),
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())
160 ->GetCdmContext());
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());
178 if (delegate_)
179 delegate_->PlayerGone(this);
181 // Abort any pending IO so stopping the pipeline doesn't get blocked.
182 if (data_source_)
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);
194 pipeline_.Stop(
195 base::Bind(&base::WaitableEvent::Signal, base::Unretained(&waiter)));
196 waiter.Wait();
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 << ", "
207 << cors_mode << ")";
208 if (!defer_load_cb_.is_null()) {
209 defer_load_cb_.Run(base::Bind(
210 &WebMediaPlayerImpl::DoLoad, AsWeakPtr(), load_type, url, cors_mode));
211 return;
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());
221 GURL gurl(url);
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;
237 StartPipeline();
238 return;
241 // Otherwise it's a regular request which requires resolving the URL first.
242 data_source_.reset(new BufferedDataSource(
243 url,
244 static_cast<BufferedResourceLoader::CORSMode>(cors_mode),
245 main_task_runner_,
246 frame_,
247 media_log_.get(),
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());
259 paused_ = false;
260 pipeline_.SetPlaybackRate(playback_rate_);
261 if (data_source_)
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;
275 paused_ = true;
276 pipeline_.SetPlaybackRate(0.0);
277 if (data_source_)
278 data_source_->MediaIsPaused();
279 UpdatePausedTime();
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());
296 ended_ = false;
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);
304 if (seeking_) {
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
310 // seek.
311 MEDIA_LOG(DEBUG, media_log_)
312 << "Detected MediaSource seek to same time as in-progress seek to "
313 << seek_time_ << ".";
314 } else {
315 // Suppress all redundant seeks if unrestricted by media source demuxer
316 // API.
317 pending_seek_ = false;
318 pending_seek_time_ = base::TimeDelta();
319 return;
323 pending_seek_ = true;
324 pending_seek_time_ = new_seek_time;
325 if (chunk_demuxer_)
326 chunk_demuxer_->CancelPendingSeek(pending_seek_time_);
327 return;
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
340 // old ones.
341 if (paused_) {
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(
346 FROM_HERE,
347 base::Bind(&WebMediaPlayerImpl::OnPipelineBufferingStateChanged,
348 AsWeakPtr(), BUFFERING_HAVE_ENOUGH));
349 return;
353 seeking_ = true;
354 seek_time_ = new_seek_time;
356 if (chunk_demuxer_)
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.
370 if (rate < 0.0)
371 return;
373 // Limit rates to reasonable values by clamping.
374 if (rate != 0.0) {
375 if (rate < kMinRate)
376 rate = kMinRate;
377 else if (rate > kMaxRate)
378 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;
386 if (!paused_) {
387 pipeline_.SetPlaybackRate(rate);
388 if (data_source_)
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();
407 if (output_device) {
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);
411 } else {
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);
430 if (data_source_)
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)
462 return false;
464 return seeking_;
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
491 if (ended_)
492 return duration();
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().
497 if (seeking()) {
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());
512 return ready_state_;
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,
559 unsigned char alpha,
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.
577 if (!context_3d.gl)
578 return;
580 skcanvas_video_renderer_.Paint(video_frame, canvas, gfx::RectF(gfx_rect),
581 alpha, mode, pipeline_metadata_.video_rotation,
582 context_3d);
585 bool WebMediaPlayerImpl::hasSingleSecurityOrigin() const {
586 if (data_source_)
587 return data_source_->HasSingleOrigin();
588 return true;
591 bool WebMediaPlayerImpl::didPassCORSAccessCheck() const {
592 if (data_source_)
593 return data_source_->DidPassCORSAccessCheck();
594 return false;
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,
633 unsigned int type,
634 bool premultiply_alpha,
635 bool flip_y) {
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) {
642 return false;
645 // TODO(dshwang): need more elegant way to convert WebGraphicsContext3D to
646 // GLES2Interface.
647 gpu::gles2::GLES2Interface* gl =
648 static_cast<gpu_blink::WebGraphicsContext3DImpl*>(web_graphics_context)
649 ->GetGLInterface();
650 SkCanvasVideoRenderer::CopyVideoFrameSingleTextureToGLTexture(
651 gl, video_frame.get(), texture, internal_format, type, premultiply_alpha,
652 flip_y);
653 return true;
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,
669 unsigned key_length,
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.
695 if (!cdm) {
696 result.completeWithError(
697 blink::WebContentDecryptionModuleExceptionInvalidStateError, 0,
698 "The existing MediaKeys object cannot be removed at this time.");
699 return;
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.");
708 return;
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()) {
729 return;
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.
754 if (cdm_context)
755 pipeline_.SetCdm(cdm_context, cdm_attached_cb);
758 void WebMediaPlayerImpl::OnCdmAttached(bool success) {
759 if (success) {
760 set_cdm_result_->complete();
761 set_cdm_result_.reset();
762 return;
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());
775 seeking_ = false;
776 seek_time_ = base::TimeDelta();
777 if (pending_seek_) {
778 double pending_seek_seconds = pending_seek_time_.InSecondsF();
779 pending_seek_ = false;
780 pending_seek_time_ = base::TimeDelta();
781 seek(pending_seek_seconds);
782 return;
785 if (status != PIPELINE_OK) {
786 OnPipelineError(status);
787 return;
790 // Update our paused time.
791 if (paused_)
792 UpdatePausedTime();
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_)
803 return;
805 ended_ = true;
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);
817 return;
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);
833 if (hasVideo()) {
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_)
858 return;
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.
867 if (data_source_)
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());
907 if (!success) {
908 SetNetworkState(WebMediaPlayer::NetworkStateFormatError);
909 return;
912 StartPipeline();
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_));
939 } else {
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!
950 seeking_ = true;
952 pipeline_.Start(
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)
1005 return;
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);
1026 opaque_ = opaque;
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();
1039 event->Signal();
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_),
1055 &video_frame,
1056 &event));
1057 event.Wait();
1058 return video_frame;
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.
1068 paused_time_ =
1069 ended_ ? pipeline_.GetMediaDuration() : pipeline_.GetMediaTime();
1072 } // namespace media