extensions: Remove dependency on libxml.
[chromium-blink-merge.git] / media / blink / webmediaplayer_impl.cc
blob21e151990a6da6aa5601412c6e92de0f2afaf6a0
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/video_frame.h"
31 #include "media/blink/texttrack_impl.h"
32 #include "media/blink/webaudiosourceprovider_impl.h"
33 #include "media/blink/webcontentdecryptionmodule_impl.h"
34 #include "media/blink/webinbandtexttrack_impl.h"
35 #include "media/blink/webmediaplayer_delegate.h"
36 #include "media/blink/webmediaplayer_util.h"
37 #include "media/blink/webmediasource_impl.h"
38 #include "media/filters/chunk_demuxer.h"
39 #include "media/filters/ffmpeg_demuxer.h"
40 #include "third_party/WebKit/public/platform/WebEncryptedMediaTypes.h"
41 #include "third_party/WebKit/public/platform/WebMediaPlayerClient.h"
42 #include "third_party/WebKit/public/platform/WebMediaPlayerEncryptedMediaClient.h"
43 #include "third_party/WebKit/public/platform/WebMediaSource.h"
44 #include "third_party/WebKit/public/platform/WebRect.h"
45 #include "third_party/WebKit/public/platform/WebSize.h"
46 #include "third_party/WebKit/public/platform/WebString.h"
47 #include "third_party/WebKit/public/platform/WebURL.h"
48 #include "third_party/WebKit/public/web/WebDocument.h"
49 #include "third_party/WebKit/public/web/WebFrame.h"
50 #include "third_party/WebKit/public/web/WebLocalFrame.h"
51 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
52 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
53 #include "third_party/WebKit/public/web/WebView.h"
55 using blink::WebCanvas;
56 using blink::WebMediaPlayer;
57 using blink::WebRect;
58 using blink::WebSize;
59 using blink::WebString;
61 namespace {
63 // Limits the range of playback rate.
65 // TODO(kylep): Revisit these.
67 // Vista has substantially lower performance than XP or Windows7. If you speed
68 // up a video too much, it can't keep up, and rendering stops updating except on
69 // the time bar. For really high speeds, audio becomes a bottleneck and we just
70 // use up the data we have, which may not achieve the speed requested, but will
71 // not crash the tab.
73 // A very slow speed, ie 0.00000001x, causes the machine to lock up. (It seems
74 // like a busy loop). It gets unresponsive, although its not completely dead.
76 // Also our timers are not very accurate (especially for ogg), which becomes
77 // evident at low speeds and on Vista. Since other speeds are risky and outside
78 // the norms, we think 1/16x to 16x is a safe and useful range for now.
79 const double kMinRate = 0.0625;
80 const double kMaxRate = 16.0;
82 } // namespace
84 namespace media {
86 class BufferedDataSourceHostImpl;
88 #define STATIC_ASSERT_MATCHING_ENUM(name) \
89 static_assert(static_cast<int>(WebMediaPlayer::CORSMode ## name) == \
90 static_cast<int>(BufferedResourceLoader::k ## name), \
91 "mismatching enum values: " #name)
92 STATIC_ASSERT_MATCHING_ENUM(Unspecified);
93 STATIC_ASSERT_MATCHING_ENUM(Anonymous);
94 STATIC_ASSERT_MATCHING_ENUM(UseCredentials);
95 #undef STATIC_ASSERT_MATCHING_ENUM
97 #define BIND_TO_RENDER_LOOP(function) \
98 (DCHECK(main_task_runner_->BelongsToCurrentThread()), \
99 BindToCurrentLoop(base::Bind(function, AsWeakPtr())))
101 #define BIND_TO_RENDER_LOOP1(function, arg1) \
102 (DCHECK(main_task_runner_->BelongsToCurrentThread()), \
103 BindToCurrentLoop(base::Bind(function, AsWeakPtr(), arg1)))
105 WebMediaPlayerImpl::WebMediaPlayerImpl(
106 blink::WebLocalFrame* frame,
107 blink::WebMediaPlayerClient* client,
108 blink::WebMediaPlayerEncryptedMediaClient* encrypted_client,
109 base::WeakPtr<WebMediaPlayerDelegate> delegate,
110 scoped_ptr<RendererFactory> renderer_factory,
111 CdmFactory* cdm_factory,
112 const WebMediaPlayerParams& params)
113 : frame_(frame),
114 network_state_(WebMediaPlayer::NetworkStateEmpty),
115 ready_state_(WebMediaPlayer::ReadyStateHaveNothing),
116 preload_(BufferedDataSource::AUTO),
117 main_task_runner_(base::ThreadTaskRunnerHandle::Get()),
118 media_task_runner_(params.media_task_runner()),
119 media_log_(params.media_log()),
120 pipeline_(media_task_runner_, media_log_.get()),
121 load_type_(LoadTypeURL),
122 opaque_(false),
123 playback_rate_(0.0),
124 paused_(true),
125 seeking_(false),
126 ended_(false),
127 pending_seek_(false),
128 should_notify_time_changed_(false),
129 client_(client),
130 encrypted_client_(encrypted_client),
131 delegate_(delegate),
132 defer_load_cb_(params.defer_load_cb()),
133 context_3d_cb_(params.context_3d_cb()),
134 supports_save_(true),
135 chunk_demuxer_(NULL),
136 // Threaded compositing isn't enabled universally yet.
137 compositor_task_runner_(
138 params.compositor_task_runner()
139 ? params.compositor_task_runner()
140 : base::MessageLoop::current()->task_runner()),
141 compositor_(new VideoFrameCompositor(
142 compositor_task_runner_,
143 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnNaturalSizeChanged),
144 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnOpacityChanged))),
145 encrypted_media_support_(cdm_factory,
146 encrypted_client,
147 params.media_permission(),
148 base::Bind(&WebMediaPlayerImpl::SetCdm,
149 AsWeakPtr(),
150 base::Bind(&IgnoreCdmAttached))),
151 renderer_factory_(renderer_factory.Pass()) {
152 media_log_->AddEvent(
153 media_log_->CreateEvent(MediaLogEvent::WEBMEDIAPLAYER_CREATED));
155 if (params.initial_cdm()) {
156 SetCdm(base::Bind(&IgnoreCdmAttached),
157 ToWebContentDecryptionModuleImpl(params.initial_cdm())
158 ->GetCdmContext());
161 // TODO(xhwang): When we use an external Renderer, many methods won't work,
162 // e.g. GetCurrentFrameFromCompositor(). See http://crbug.com/434861
164 // Use the null sink if no sink was provided.
165 audio_source_provider_ = new WebAudioSourceProviderImpl(
166 params.audio_renderer_sink().get()
167 ? params.audio_renderer_sink()
168 : new NullAudioSink(media_task_runner_));
171 WebMediaPlayerImpl::~WebMediaPlayerImpl() {
172 client_->setWebLayer(NULL);
174 DCHECK(main_task_runner_->BelongsToCurrentThread());
176 if (delegate_)
177 delegate_->PlayerGone(this);
179 // Abort any pending IO so stopping the pipeline doesn't get blocked.
180 if (data_source_)
181 data_source_->Abort();
182 if (chunk_demuxer_) {
183 chunk_demuxer_->Shutdown();
184 chunk_demuxer_ = NULL;
187 renderer_factory_.reset();
189 // Make sure to kill the pipeline so there's no more media threads running.
190 // Note: stopping the pipeline might block for a long time.
191 base::WaitableEvent waiter(false, false);
192 pipeline_.Stop(
193 base::Bind(&base::WaitableEvent::Signal, base::Unretained(&waiter)));
194 waiter.Wait();
196 compositor_task_runner_->DeleteSoon(FROM_HERE, compositor_);
198 media_log_->AddEvent(
199 media_log_->CreateEvent(MediaLogEvent::WEBMEDIAPLAYER_DESTROYED));
202 void WebMediaPlayerImpl::load(LoadType load_type, const blink::WebURL& url,
203 CORSMode cors_mode) {
204 DVLOG(1) << __FUNCTION__ << "(" << load_type << ", " << url << ", "
205 << cors_mode << ")";
206 if (!defer_load_cb_.is_null()) {
207 defer_load_cb_.Run(base::Bind(
208 &WebMediaPlayerImpl::DoLoad, AsWeakPtr(), load_type, url, cors_mode));
209 return;
211 DoLoad(load_type, url, cors_mode);
214 void WebMediaPlayerImpl::DoLoad(LoadType load_type,
215 const blink::WebURL& url,
216 CORSMode cors_mode) {
217 DCHECK(main_task_runner_->BelongsToCurrentThread());
219 GURL gurl(url);
220 ReportMetrics(load_type, gurl,
221 GURL(frame_->document().securityOrigin().toString()));
223 // Set subresource URL for crash reporting.
224 base::debug::SetCrashKeyValue("subresource_url", gurl.spec());
226 load_type_ = load_type;
228 SetNetworkState(WebMediaPlayer::NetworkStateLoading);
229 SetReadyState(WebMediaPlayer::ReadyStateHaveNothing);
230 media_log_->AddEvent(media_log_->CreateLoadEvent(url.spec()));
232 // Media source pipelines can start immediately.
233 if (load_type == LoadTypeMediaSource) {
234 supports_save_ = false;
235 StartPipeline();
236 return;
239 // Otherwise it's a regular request which requires resolving the URL first.
240 data_source_.reset(new BufferedDataSource(
241 url,
242 static_cast<BufferedResourceLoader::CORSMode>(cors_mode),
243 main_task_runner_,
244 frame_,
245 media_log_.get(),
246 &buffered_data_source_host_,
247 base::Bind(&WebMediaPlayerImpl::NotifyDownloading, AsWeakPtr())));
248 data_source_->SetPreload(preload_);
249 data_source_->Initialize(
250 base::Bind(&WebMediaPlayerImpl::DataSourceInitialized, AsWeakPtr()));
253 void WebMediaPlayerImpl::play() {
254 DVLOG(1) << __FUNCTION__;
255 DCHECK(main_task_runner_->BelongsToCurrentThread());
257 paused_ = false;
258 pipeline_.SetPlaybackRate(playback_rate_);
259 if (data_source_)
260 data_source_->MediaIsPlaying();
262 media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::PLAY));
264 if (delegate_ && playback_rate_ > 0)
265 delegate_->DidPlay(this);
268 void WebMediaPlayerImpl::pause() {
269 DVLOG(1) << __FUNCTION__;
270 DCHECK(main_task_runner_->BelongsToCurrentThread());
272 const bool was_already_paused = paused_ || playback_rate_ == 0;
273 paused_ = true;
274 pipeline_.SetPlaybackRate(0.0);
275 if (data_source_)
276 data_source_->MediaIsPaused();
277 UpdatePausedTime();
279 media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::PAUSE));
281 if (!was_already_paused && delegate_)
282 delegate_->DidPause(this);
285 bool WebMediaPlayerImpl::supportsSave() const {
286 DCHECK(main_task_runner_->BelongsToCurrentThread());
287 return supports_save_;
290 void WebMediaPlayerImpl::seek(double seconds) {
291 DVLOG(1) << __FUNCTION__ << "(" << seconds << "s)";
292 DCHECK(main_task_runner_->BelongsToCurrentThread());
294 ended_ = false;
296 ReadyState old_state = ready_state_;
297 if (ready_state_ > WebMediaPlayer::ReadyStateHaveMetadata)
298 SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata);
300 base::TimeDelta new_seek_time = ConvertSecondsToTimestamp(seconds);
302 if (seeking_) {
303 if (new_seek_time == seek_time_) {
304 if (chunk_demuxer_) {
305 if (!pending_seek_) {
306 // If using media source demuxer, only suppress redundant seeks if
307 // there is no pending seek. This enforces that any pending seek that
308 // results in a demuxer seek is preceded by matching
309 // CancelPendingSeek() and StartWaitingForSeek() calls.
310 return;
312 } else {
313 // Suppress all redundant seeks if unrestricted by media source demuxer
314 // API.
315 pending_seek_ = false;
316 pending_seek_time_ = base::TimeDelta();
317 return;
321 pending_seek_ = true;
322 pending_seek_time_ = new_seek_time;
323 if (chunk_demuxer_)
324 chunk_demuxer_->CancelPendingSeek(pending_seek_time_);
325 return;
328 media_log_->AddEvent(media_log_->CreateSeekEvent(seconds));
330 // Update our paused time.
331 // In paused state ignore the seek operations to current time if the loading
332 // is completed and generate OnPipelineBufferingStateChanged event to
333 // eventually fire seeking and seeked events
334 if (paused_) {
335 if (paused_time_ != new_seek_time) {
336 paused_time_ = new_seek_time;
337 } else if (old_state == ReadyStateHaveEnoughData) {
338 main_task_runner_->PostTask(
339 FROM_HERE,
340 base::Bind(&WebMediaPlayerImpl::OnPipelineBufferingStateChanged,
341 AsWeakPtr(), BUFFERING_HAVE_ENOUGH));
342 return;
346 seeking_ = true;
347 seek_time_ = new_seek_time;
349 if (chunk_demuxer_)
350 chunk_demuxer_->StartWaitingForSeek(seek_time_);
352 // Kick off the asynchronous seek!
353 pipeline_.Seek(seek_time_, BIND_TO_RENDER_LOOP1(
354 &WebMediaPlayerImpl::OnPipelineSeeked, true));
357 void WebMediaPlayerImpl::setRate(double rate) {
358 DVLOG(1) << __FUNCTION__ << "(" << rate << ")";
359 DCHECK(main_task_runner_->BelongsToCurrentThread());
361 // TODO(kylep): Remove when support for negatives is added. Also, modify the
362 // following checks so rewind uses reasonable values also.
363 if (rate < 0.0)
364 return;
366 // Limit rates to reasonable values by clamping.
367 if (rate != 0.0) {
368 if (rate < kMinRate)
369 rate = kMinRate;
370 else if (rate > kMaxRate)
371 rate = kMaxRate;
372 if (playback_rate_ == 0 && !paused_ && delegate_)
373 delegate_->DidPlay(this);
374 } else if (playback_rate_ != 0 && !paused_ && delegate_) {
375 delegate_->DidPause(this);
378 playback_rate_ = rate;
379 if (!paused_) {
380 pipeline_.SetPlaybackRate(rate);
381 if (data_source_)
382 data_source_->MediaPlaybackRateChanged(rate);
386 void WebMediaPlayerImpl::setVolume(double volume) {
387 DVLOG(1) << __FUNCTION__ << "(" << volume << ")";
388 DCHECK(main_task_runner_->BelongsToCurrentThread());
390 pipeline_.SetVolume(volume);
393 void WebMediaPlayerImpl::setSinkId(const blink::WebString& device_id,
394 WebSetSinkIdCB* web_callbacks) {
395 DCHECK(main_task_runner_->BelongsToCurrentThread());
396 std::string device_id_str(device_id.utf8());
397 GURL security_origin(frame_->securityOrigin().toString().utf8());
398 DVLOG(1) << __FUNCTION__
399 << "(" << device_id_str << ", " << security_origin << ")";
400 audio_source_provider_->SwitchOutputDevice(
401 device_id_str, security_origin,
402 ConvertToSwitchOutputDeviceCB(web_callbacks));
405 #define STATIC_ASSERT_MATCHING_ENUM(webkit_name, chromium_name) \
406 static_assert(static_cast<int>(WebMediaPlayer::webkit_name) == \
407 static_cast<int>(BufferedDataSource::chromium_name), \
408 "mismatching enum values: " #webkit_name)
409 STATIC_ASSERT_MATCHING_ENUM(PreloadNone, NONE);
410 STATIC_ASSERT_MATCHING_ENUM(PreloadMetaData, METADATA);
411 STATIC_ASSERT_MATCHING_ENUM(PreloadAuto, AUTO);
412 #undef STATIC_ASSERT_MATCHING_ENUM
414 void WebMediaPlayerImpl::setPreload(WebMediaPlayer::Preload preload) {
415 DVLOG(1) << __FUNCTION__ << "(" << preload << ")";
416 DCHECK(main_task_runner_->BelongsToCurrentThread());
418 preload_ = static_cast<BufferedDataSource::Preload>(preload);
419 if (data_source_)
420 data_source_->SetPreload(preload_);
423 bool WebMediaPlayerImpl::hasVideo() const {
424 DCHECK(main_task_runner_->BelongsToCurrentThread());
426 return pipeline_metadata_.has_video;
429 bool WebMediaPlayerImpl::hasAudio() const {
430 DCHECK(main_task_runner_->BelongsToCurrentThread());
432 return pipeline_metadata_.has_audio;
435 blink::WebSize WebMediaPlayerImpl::naturalSize() const {
436 DCHECK(main_task_runner_->BelongsToCurrentThread());
438 return blink::WebSize(pipeline_metadata_.natural_size);
441 bool WebMediaPlayerImpl::paused() const {
442 DCHECK(main_task_runner_->BelongsToCurrentThread());
444 return pipeline_.GetPlaybackRate() == 0.0f;
447 bool WebMediaPlayerImpl::seeking() const {
448 DCHECK(main_task_runner_->BelongsToCurrentThread());
450 if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
451 return false;
453 return seeking_;
456 double WebMediaPlayerImpl::duration() const {
457 DCHECK(main_task_runner_->BelongsToCurrentThread());
459 if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
460 return std::numeric_limits<double>::quiet_NaN();
462 return GetPipelineDuration();
465 double WebMediaPlayerImpl::timelineOffset() const {
466 DCHECK(main_task_runner_->BelongsToCurrentThread());
468 if (pipeline_metadata_.timeline_offset.is_null())
469 return std::numeric_limits<double>::quiet_NaN();
471 return pipeline_metadata_.timeline_offset.ToJsTime();
474 double WebMediaPlayerImpl::currentTime() const {
475 DCHECK(main_task_runner_->BelongsToCurrentThread());
476 DCHECK_NE(ready_state_, WebMediaPlayer::ReadyStateHaveNothing);
478 // TODO(scherkus): Replace with an explicit ended signal to HTMLMediaElement,
479 // see http://crbug.com/409280
480 if (ended_)
481 return duration();
483 // We know the current seek time better than pipeline: pipeline may processing
484 // an earlier seek before a pending seek has been started, or it might not yet
485 // have the current seek time returnable via GetMediaTime().
486 if (seeking()) {
487 return pending_seek_ ? pending_seek_time_.InSecondsF()
488 : seek_time_.InSecondsF();
491 return (paused_ ? paused_time_ : pipeline_.GetMediaTime()).InSecondsF();
494 WebMediaPlayer::NetworkState WebMediaPlayerImpl::networkState() const {
495 DCHECK(main_task_runner_->BelongsToCurrentThread());
496 return network_state_;
499 WebMediaPlayer::ReadyState WebMediaPlayerImpl::readyState() const {
500 DCHECK(main_task_runner_->BelongsToCurrentThread());
501 return ready_state_;
504 blink::WebTimeRanges WebMediaPlayerImpl::buffered() const {
505 DCHECK(main_task_runner_->BelongsToCurrentThread());
507 Ranges<base::TimeDelta> buffered_time_ranges =
508 pipeline_.GetBufferedTimeRanges();
510 const base::TimeDelta duration = pipeline_.GetMediaDuration();
511 if (duration != kInfiniteDuration()) {
512 buffered_data_source_host_.AddBufferedTimeRanges(
513 &buffered_time_ranges, duration);
515 return ConvertToWebTimeRanges(buffered_time_ranges);
518 blink::WebTimeRanges WebMediaPlayerImpl::seekable() const {
519 DCHECK(main_task_runner_->BelongsToCurrentThread());
521 if (ready_state_ < WebMediaPlayer::ReadyStateHaveMetadata)
522 return blink::WebTimeRanges();
524 const double seekable_end = duration();
526 // Allow a special exception for seeks to zero for streaming sources with a
527 // finite duration; this allows looping to work.
528 const bool allow_seek_to_zero = data_source_ && data_source_->IsStreaming() &&
529 std::isfinite(seekable_end);
531 // TODO(dalecurtis): Technically this allows seeking on media which return an
532 // infinite duration so long as DataSource::IsStreaming() is false. While not
533 // expected, disabling this breaks semi-live players, http://crbug.com/427412.
534 const blink::WebTimeRange seekable_range(
535 0.0, allow_seek_to_zero ? 0.0 : seekable_end);
536 return blink::WebTimeRanges(&seekable_range, 1);
539 bool WebMediaPlayerImpl::didLoadingProgress() {
540 DCHECK(main_task_runner_->BelongsToCurrentThread());
541 bool pipeline_progress = pipeline_.DidLoadingProgress();
542 bool data_progress = buffered_data_source_host_.DidLoadingProgress();
543 return pipeline_progress || data_progress;
546 void WebMediaPlayerImpl::paint(blink::WebCanvas* canvas,
547 const blink::WebRect& rect,
548 unsigned char alpha,
549 SkXfermode::Mode mode) {
550 DCHECK(main_task_runner_->BelongsToCurrentThread());
551 TRACE_EVENT0("media", "WebMediaPlayerImpl:paint");
553 // TODO(scherkus): Clarify paint() API contract to better understand when and
554 // why it's being called. For example, today paint() is called when:
555 // - We haven't reached HAVE_CURRENT_DATA and need to paint black
556 // - We're painting to a canvas
557 // See http://crbug.com/341225 http://crbug.com/342621 for details.
558 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
560 gfx::Rect gfx_rect(rect);
561 Context3D context_3d;
562 if (video_frame.get() && video_frame->HasTextures()) {
563 if (!context_3d_cb_.is_null())
564 context_3d = context_3d_cb_.Run();
565 // GPU Process crashed.
566 if (!context_3d.gl)
567 return;
569 skcanvas_video_renderer_.Paint(video_frame, canvas, gfx_rect, alpha, mode,
570 pipeline_metadata_.video_rotation, context_3d);
573 bool WebMediaPlayerImpl::hasSingleSecurityOrigin() const {
574 if (data_source_)
575 return data_source_->HasSingleOrigin();
576 return true;
579 bool WebMediaPlayerImpl::didPassCORSAccessCheck() const {
580 if (data_source_)
581 return data_source_->DidPassCORSAccessCheck();
582 return false;
585 double WebMediaPlayerImpl::mediaTimeForTimeValue(double timeValue) const {
586 return ConvertSecondsToTimestamp(timeValue).InSecondsF();
589 unsigned WebMediaPlayerImpl::decodedFrameCount() const {
590 DCHECK(main_task_runner_->BelongsToCurrentThread());
592 PipelineStatistics stats = pipeline_.GetStatistics();
593 return stats.video_frames_decoded;
596 unsigned WebMediaPlayerImpl::droppedFrameCount() const {
597 DCHECK(main_task_runner_->BelongsToCurrentThread());
599 PipelineStatistics stats = pipeline_.GetStatistics();
600 return stats.video_frames_dropped;
603 unsigned WebMediaPlayerImpl::audioDecodedByteCount() const {
604 DCHECK(main_task_runner_->BelongsToCurrentThread());
606 PipelineStatistics stats = pipeline_.GetStatistics();
607 return stats.audio_bytes_decoded;
610 unsigned WebMediaPlayerImpl::videoDecodedByteCount() const {
611 DCHECK(main_task_runner_->BelongsToCurrentThread());
613 PipelineStatistics stats = pipeline_.GetStatistics();
614 return stats.video_bytes_decoded;
617 bool WebMediaPlayerImpl::copyVideoTextureToPlatformTexture(
618 blink::WebGraphicsContext3D* web_graphics_context,
619 unsigned int texture,
620 unsigned int internal_format,
621 unsigned int type,
622 bool premultiply_alpha,
623 bool flip_y) {
624 TRACE_EVENT0("media", "WebMediaPlayerImpl:copyVideoTextureToPlatformTexture");
626 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
628 if (!video_frame.get() || !video_frame->HasTextures() ||
629 media::VideoFrame::NumPlanes(video_frame->format()) != 1) {
630 return false;
633 // TODO(dshwang): need more elegant way to convert WebGraphicsContext3D to
634 // GLES2Interface.
635 gpu::gles2::GLES2Interface* gl =
636 static_cast<gpu_blink::WebGraphicsContext3DImpl*>(web_graphics_context)
637 ->GetGLInterface();
638 SkCanvasVideoRenderer::CopyVideoFrameSingleTextureToGLTexture(
639 gl, video_frame.get(), texture, internal_format, type, premultiply_alpha,
640 flip_y);
641 return true;
644 WebMediaPlayer::MediaKeyException
645 WebMediaPlayerImpl::generateKeyRequest(const WebString& key_system,
646 const unsigned char* init_data,
647 unsigned init_data_length) {
648 DCHECK(main_task_runner_->BelongsToCurrentThread());
650 return encrypted_media_support_.GenerateKeyRequest(
651 frame_, key_system, init_data, init_data_length);
654 WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::addKey(
655 const WebString& key_system,
656 const unsigned char* key,
657 unsigned key_length,
658 const unsigned char* init_data,
659 unsigned init_data_length,
660 const WebString& session_id) {
661 DCHECK(main_task_runner_->BelongsToCurrentThread());
663 return encrypted_media_support_.AddKey(
664 key_system, key, key_length, init_data, init_data_length, session_id);
667 WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::cancelKeyRequest(
668 const WebString& key_system,
669 const WebString& session_id) {
670 DCHECK(main_task_runner_->BelongsToCurrentThread());
672 return encrypted_media_support_.CancelKeyRequest(key_system, session_id);
675 void WebMediaPlayerImpl::setContentDecryptionModule(
676 blink::WebContentDecryptionModule* cdm,
677 blink::WebContentDecryptionModuleResult result) {
678 DCHECK(main_task_runner_->BelongsToCurrentThread());
680 // Once the CDM is set it can't be cleared as there may be frames being
681 // decrypted on other threads. So fail this request.
682 // http://crbug.com/462365#c7.
683 if (!cdm) {
684 result.completeWithError(
685 blink::WebContentDecryptionModuleExceptionInvalidStateError, 0,
686 "The existing MediaKeys object cannot be removed at this time.");
687 return;
690 SetCdm(BIND_TO_RENDER_LOOP1(&WebMediaPlayerImpl::OnCdmAttached, result),
691 ToWebContentDecryptionModuleImpl(cdm)->GetCdmContext());
694 void WebMediaPlayerImpl::OnEncryptedMediaInitData(
695 EmeInitDataType init_data_type,
696 const std::vector<uint8>& init_data) {
697 DCHECK(init_data_type != EmeInitDataType::UNKNOWN);
699 // Do not fire "encrypted" event if encrypted media is not enabled.
700 // TODO(xhwang): Handle this in |client_|.
701 if (!blink::WebRuntimeFeatures::isPrefixedEncryptedMediaEnabled() &&
702 !blink::WebRuntimeFeatures::isEncryptedMediaEnabled()) {
703 return;
706 // TODO(xhwang): Update this UMA name.
707 UMA_HISTOGRAM_COUNTS("Media.EME.NeedKey", 1);
709 encrypted_media_support_.SetInitDataType(init_data_type);
711 encrypted_client_->encrypted(
712 ConvertToWebInitDataType(init_data_type), vector_as_array(&init_data),
713 base::saturated_cast<unsigned int>(init_data.size()));
716 void WebMediaPlayerImpl::OnWaitingForDecryptionKey() {
717 encrypted_client_->didBlockPlaybackWaitingForKey();
719 // TODO(jrummell): didResumePlaybackBlockedForKey() should only be called
720 // when a key has been successfully added (e.g. OnSessionKeysChange() with
721 // |has_additional_usable_key| = true). http://crbug.com/461903
722 encrypted_client_->didResumePlaybackBlockedForKey();
725 void WebMediaPlayerImpl::SetCdm(const CdmAttachedCB& cdm_attached_cb,
726 CdmContext* cdm_context) {
727 // If CDM initialization succeeded, tell the pipeline about it.
728 if (cdm_context)
729 pipeline_.SetCdm(cdm_context, cdm_attached_cb);
732 void WebMediaPlayerImpl::OnCdmAttached(
733 blink::WebContentDecryptionModuleResult result,
734 bool success) {
735 if (success) {
736 result.complete();
737 return;
740 result.completeWithError(
741 blink::WebContentDecryptionModuleExceptionNotSupportedError, 0,
742 "Unable to set MediaKeys object");
745 void WebMediaPlayerImpl::OnPipelineSeeked(bool time_changed,
746 PipelineStatus status) {
747 DVLOG(1) << __FUNCTION__ << "(" << time_changed << ", " << status << ")";
748 DCHECK(main_task_runner_->BelongsToCurrentThread());
749 seeking_ = false;
750 seek_time_ = base::TimeDelta();
751 if (pending_seek_) {
752 double pending_seek_seconds = pending_seek_time_.InSecondsF();
753 pending_seek_ = false;
754 pending_seek_time_ = base::TimeDelta();
755 seek(pending_seek_seconds);
756 return;
759 if (status != PIPELINE_OK) {
760 OnPipelineError(status);
761 return;
764 // Update our paused time.
765 if (paused_)
766 UpdatePausedTime();
768 should_notify_time_changed_ = time_changed;
771 void WebMediaPlayerImpl::OnPipelineEnded() {
772 DVLOG(1) << __FUNCTION__;
773 DCHECK(main_task_runner_->BelongsToCurrentThread());
775 // Ignore state changes until we've completed all outstanding seeks.
776 if (seeking_ || pending_seek_)
777 return;
779 ended_ = true;
780 client_->timeChanged();
783 void WebMediaPlayerImpl::OnPipelineError(PipelineStatus error) {
784 DCHECK(main_task_runner_->BelongsToCurrentThread());
785 DCHECK_NE(error, PIPELINE_OK);
787 if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing) {
788 // Any error that occurs before reaching ReadyStateHaveMetadata should
789 // be considered a format error.
790 SetNetworkState(WebMediaPlayer::NetworkStateFormatError);
791 return;
794 SetNetworkState(PipelineErrorToNetworkState(error));
797 void WebMediaPlayerImpl::OnPipelineMetadata(
798 PipelineMetadata metadata) {
799 DVLOG(1) << __FUNCTION__;
801 pipeline_metadata_ = metadata;
803 UMA_HISTOGRAM_ENUMERATION("Media.VideoRotation", metadata.video_rotation,
804 VIDEO_ROTATION_MAX + 1);
805 SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata);
807 if (hasVideo()) {
808 DCHECK(!video_weblayer_);
809 scoped_refptr<cc::VideoLayer> layer =
810 cc::VideoLayer::Create(cc_blink::WebLayerImpl::LayerSettings(),
811 compositor_, pipeline_metadata_.video_rotation);
813 if (pipeline_metadata_.video_rotation == VIDEO_ROTATION_90 ||
814 pipeline_metadata_.video_rotation == VIDEO_ROTATION_270) {
815 gfx::Size size = pipeline_metadata_.natural_size;
816 pipeline_metadata_.natural_size = gfx::Size(size.height(), size.width());
819 video_weblayer_.reset(new cc_blink::WebLayerImpl(layer));
820 video_weblayer_->setOpaque(opaque_);
821 client_->setWebLayer(video_weblayer_.get());
825 void WebMediaPlayerImpl::OnPipelineBufferingStateChanged(
826 BufferingState buffering_state) {
827 DVLOG(1) << __FUNCTION__ << "(" << buffering_state << ")";
829 // Ignore buffering state changes until we've completed all outstanding seeks.
830 if (seeking_ || pending_seek_)
831 return;
833 // TODO(scherkus): Handle other buffering states when Pipeline starts using
834 // them and translate them ready state changes http://crbug.com/144683
835 DCHECK_EQ(buffering_state, BUFFERING_HAVE_ENOUGH);
836 SetReadyState(WebMediaPlayer::ReadyStateHaveEnoughData);
838 // Let the DataSource know we have enough data. It may use this information to
839 // release unused network connections.
840 if (data_source_)
841 data_source_->OnBufferingHaveEnough();
843 // Blink expects a timeChanged() in response to a seek().
844 if (should_notify_time_changed_)
845 client_->timeChanged();
848 void WebMediaPlayerImpl::OnDemuxerOpened() {
849 DCHECK(main_task_runner_->BelongsToCurrentThread());
850 client_->mediaSourceOpened(
851 new WebMediaSourceImpl(chunk_demuxer_, media_log_));
854 void WebMediaPlayerImpl::OnAddTextTrack(
855 const TextTrackConfig& config,
856 const AddTextTrackDoneCB& done_cb) {
857 DCHECK(main_task_runner_->BelongsToCurrentThread());
859 const WebInbandTextTrackImpl::Kind web_kind =
860 static_cast<WebInbandTextTrackImpl::Kind>(config.kind());
861 const blink::WebString web_label =
862 blink::WebString::fromUTF8(config.label());
863 const blink::WebString web_language =
864 blink::WebString::fromUTF8(config.language());
865 const blink::WebString web_id =
866 blink::WebString::fromUTF8(config.id());
868 scoped_ptr<WebInbandTextTrackImpl> web_inband_text_track(
869 new WebInbandTextTrackImpl(web_kind, web_label, web_language, web_id));
871 scoped_ptr<TextTrack> text_track(new TextTrackImpl(
872 main_task_runner_, client_, web_inband_text_track.Pass()));
874 done_cb.Run(text_track.Pass());
877 void WebMediaPlayerImpl::DataSourceInitialized(bool success) {
878 DCHECK(main_task_runner_->BelongsToCurrentThread());
880 if (!success) {
881 SetNetworkState(WebMediaPlayer::NetworkStateFormatError);
882 return;
885 StartPipeline();
888 void WebMediaPlayerImpl::NotifyDownloading(bool is_downloading) {
889 if (!is_downloading && network_state_ == WebMediaPlayer::NetworkStateLoading)
890 SetNetworkState(WebMediaPlayer::NetworkStateIdle);
891 else if (is_downloading && network_state_ == WebMediaPlayer::NetworkStateIdle)
892 SetNetworkState(WebMediaPlayer::NetworkStateLoading);
893 media_log_->AddEvent(
894 media_log_->CreateBooleanEvent(
895 MediaLogEvent::NETWORK_ACTIVITY_SET,
896 "is_downloading_data", is_downloading));
899 void WebMediaPlayerImpl::StartPipeline() {
900 DCHECK(main_task_runner_->BelongsToCurrentThread());
902 Demuxer::EncryptedMediaInitDataCB encrypted_media_init_data_cb =
903 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnEncryptedMediaInitData);
905 // Figure out which demuxer to use.
906 if (load_type_ != LoadTypeMediaSource) {
907 DCHECK(!chunk_demuxer_);
908 DCHECK(data_source_);
910 demuxer_.reset(new FFmpegDemuxer(media_task_runner_, data_source_.get(),
911 encrypted_media_init_data_cb, media_log_));
912 } else {
913 DCHECK(!chunk_demuxer_);
914 DCHECK(!data_source_);
916 chunk_demuxer_ = new ChunkDemuxer(
917 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnDemuxerOpened),
918 encrypted_media_init_data_cb, media_log_, true);
919 demuxer_.reset(chunk_demuxer_);
922 // ... and we're ready to go!
923 seeking_ = true;
925 pipeline_.Start(
926 demuxer_.get(),
927 renderer_factory_->CreateRenderer(
928 media_task_runner_, audio_source_provider_.get(), compositor_),
929 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineEnded),
930 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineError),
931 BIND_TO_RENDER_LOOP1(&WebMediaPlayerImpl::OnPipelineSeeked, false),
932 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineMetadata),
933 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineBufferingStateChanged),
934 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnDurationChanged),
935 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnAddTextTrack),
936 BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnWaitingForDecryptionKey));
939 void WebMediaPlayerImpl::SetNetworkState(WebMediaPlayer::NetworkState state) {
940 DVLOG(1) << __FUNCTION__ << "(" << state << ")";
941 DCHECK(main_task_runner_->BelongsToCurrentThread());
942 network_state_ = state;
943 // Always notify to ensure client has the latest value.
944 client_->networkStateChanged();
947 void WebMediaPlayerImpl::SetReadyState(WebMediaPlayer::ReadyState state) {
948 DVLOG(1) << __FUNCTION__ << "(" << state << ")";
949 DCHECK(main_task_runner_->BelongsToCurrentThread());
951 if (state == WebMediaPlayer::ReadyStateHaveEnoughData && data_source_ &&
952 data_source_->assume_fully_buffered() &&
953 network_state_ == WebMediaPlayer::NetworkStateLoading)
954 SetNetworkState(WebMediaPlayer::NetworkStateLoaded);
956 ready_state_ = state;
957 // Always notify to ensure client has the latest value.
958 client_->readyStateChanged();
961 blink::WebAudioSourceProvider* WebMediaPlayerImpl::audioSourceProvider() {
962 return audio_source_provider_.get();
965 double WebMediaPlayerImpl::GetPipelineDuration() const {
966 base::TimeDelta duration = pipeline_.GetMediaDuration();
968 // Return positive infinity if the resource is unbounded.
969 // http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#dom-media-duration
970 if (duration == kInfiniteDuration())
971 return std::numeric_limits<double>::infinity();
973 return duration.InSecondsF();
976 void WebMediaPlayerImpl::OnDurationChanged() {
977 if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
978 return;
980 client_->durationChanged();
983 void WebMediaPlayerImpl::OnNaturalSizeChanged(gfx::Size size) {
984 DCHECK(main_task_runner_->BelongsToCurrentThread());
985 DCHECK_NE(ready_state_, WebMediaPlayer::ReadyStateHaveNothing);
986 TRACE_EVENT0("media", "WebMediaPlayerImpl::OnNaturalSizeChanged");
988 media_log_->AddEvent(
989 media_log_->CreateVideoSizeSetEvent(size.width(), size.height()));
990 pipeline_metadata_.natural_size = size;
992 client_->sizeChanged();
995 void WebMediaPlayerImpl::OnOpacityChanged(bool opaque) {
996 DCHECK(main_task_runner_->BelongsToCurrentThread());
997 DCHECK_NE(ready_state_, WebMediaPlayer::ReadyStateHaveNothing);
999 opaque_ = opaque;
1000 if (video_weblayer_)
1001 video_weblayer_->setOpaque(opaque_);
1004 static void GetCurrentFrameAndSignal(
1005 VideoFrameCompositor* compositor,
1006 scoped_refptr<VideoFrame>* video_frame_out,
1007 base::WaitableEvent* event) {
1008 TRACE_EVENT0("media", "GetCurrentFrameAndSignal");
1009 *video_frame_out = compositor->GetCurrentFrameAndUpdateIfStale();
1010 event->Signal();
1013 scoped_refptr<VideoFrame>
1014 WebMediaPlayerImpl::GetCurrentFrameFromCompositor() {
1015 TRACE_EVENT0("media", "WebMediaPlayerImpl::GetCurrentFrameFromCompositor");
1016 if (compositor_task_runner_->BelongsToCurrentThread())
1017 return compositor_->GetCurrentFrameAndUpdateIfStale();
1019 // Use a posted task and waitable event instead of a lock otherwise
1020 // WebGL/Canvas can see different content than what the compositor is seeing.
1021 scoped_refptr<VideoFrame> video_frame;
1022 base::WaitableEvent event(false, false);
1023 compositor_task_runner_->PostTask(FROM_HERE,
1024 base::Bind(&GetCurrentFrameAndSignal,
1025 base::Unretained(compositor_),
1026 &video_frame,
1027 &event));
1028 event.Wait();
1029 return video_frame;
1032 void WebMediaPlayerImpl::UpdatePausedTime() {
1033 DCHECK(main_task_runner_->BelongsToCurrentThread());
1035 // pause() may be called after playback has ended and the HTMLMediaElement
1036 // requires that currentTime() == duration() after ending. We want to ensure
1037 // |paused_time_| matches currentTime() in this case or a future seek() may
1038 // incorrectly discard what it thinks is a seek to the existing time.
1039 paused_time_ =
1040 ended_ ? pipeline_.GetMediaDuration() : pipeline_.GetMediaTime();
1043 } // namespace media