cd5f9efdd82b4d91a74e5e7e4b3cdfa46ad2ffe5
[platform/framework/web/crosswalk.git] / src / content / renderer / media / webmediaplayer_impl.cc
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.
4
5 #include "content/renderer/media/webmediaplayer_impl.h"
6
7 #include <algorithm>
8 #include <limits>
9 #include <string>
10 #include <vector>
11
12 #include "base/bind.h"
13 #include "base/callback.h"
14 #include "base/callback_helpers.h"
15 #include "base/command_line.h"
16 #include "base/debug/alias.h"
17 #include "base/debug/crash_logging.h"
18 #include "base/debug/trace_event.h"
19 #include "base/message_loop/message_loop_proxy.h"
20 #include "base/metrics/histogram.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/synchronization/waitable_event.h"
24 #include "cc/layers/video_layer.h"
25 #include "content/public/common/content_switches.h"
26 #include "content/public/renderer/render_frame.h"
27 #include "content/renderer/compositor_bindings/web_layer_impl.h"
28 #include "content/renderer/media/buffered_data_source.h"
29 #include "content/renderer/media/crypto/key_systems.h"
30 #include "content/renderer/media/render_media_log.h"
31 #include "content/renderer/media/texttrack_impl.h"
32 #include "content/renderer/media/webaudiosourceprovider_impl.h"
33 #include "content/renderer/media/webcontentdecryptionmodule_impl.h"
34 #include "content/renderer/media/webinbandtexttrack_impl.h"
35 #include "content/renderer/media/webmediaplayer_delegate.h"
36 #include "content/renderer/media/webmediaplayer_params.h"
37 #include "content/renderer/media/webmediaplayer_util.h"
38 #include "content/renderer/media/webmediasource_impl.h"
39 #include "content/renderer/pepper/pepper_webplugin_impl.h"
40 #include "content/renderer/render_thread_impl.h"
41 #include "gpu/GLES2/gl2extchromium.h"
42 #include "gpu/command_buffer/common/mailbox_holder.h"
43 #include "media/audio/null_audio_sink.h"
44 #include "media/base/audio_hardware_config.h"
45 #include "media/base/bind_to_current_loop.h"
46 #include "media/base/filter_collection.h"
47 #include "media/base/limits.h"
48 #include "media/base/media_log.h"
49 #include "media/base/media_switches.h"
50 #include "media/base/pipeline.h"
51 #include "media/base/text_renderer.h"
52 #include "media/base/video_frame.h"
53 #include "media/filters/audio_renderer_impl.h"
54 #include "media/filters/chunk_demuxer.h"
55 #include "media/filters/ffmpeg_audio_decoder.h"
56 #include "media/filters/ffmpeg_demuxer.h"
57 #include "media/filters/ffmpeg_video_decoder.h"
58 #include "media/filters/gpu_video_accelerator_factories.h"
59 #include "media/filters/gpu_video_decoder.h"
60 #include "media/filters/opus_audio_decoder.h"
61 #include "media/filters/video_renderer_impl.h"
62 #include "media/filters/vpx_video_decoder.h"
63 #include "third_party/WebKit/public/platform/WebContentDecryptionModule.h"
64 #include "third_party/WebKit/public/platform/WebContentDecryptionModuleResult.h"
65 #include "third_party/WebKit/public/platform/WebMediaSource.h"
66 #include "third_party/WebKit/public/platform/WebRect.h"
67 #include "third_party/WebKit/public/platform/WebSize.h"
68 #include "third_party/WebKit/public/platform/WebString.h"
69 #include "third_party/WebKit/public/platform/WebURL.h"
70 #include "third_party/WebKit/public/web/WebDocument.h"
71 #include "third_party/WebKit/public/web/WebLocalFrame.h"
72 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
73 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
74 #include "third_party/WebKit/public/web/WebView.h"
75 #include "v8/include/v8.h"
76
77 #if defined(ENABLE_PEPPER_CDMS)
78 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
79 #endif
80
81 using blink::WebCanvas;
82 using blink::WebMediaPlayer;
83 using blink::WebRect;
84 using blink::WebSize;
85 using blink::WebString;
86 using media::PipelineStatus;
87
88 namespace {
89
90 // Amount of extra memory used by each player instance reported to V8.
91 // It is not exact number -- first, it differs on different platforms,
92 // and second, it is very hard to calculate. Instead, use some arbitrary
93 // value that will cause garbage collection from time to time. We don't want
94 // it to happen on every allocation, but don't want 5k players to sit in memory
95 // either. Looks that chosen constant achieves both goals, at least for audio
96 // objects. (Do not worry about video objects yet, JS programs do not create
97 // thousands of them...)
98 const int kPlayerExtraMemory = 1024 * 1024;
99
100 // Limits the range of playback rate.
101 //
102 // TODO(kylep): Revisit these.
103 //
104 // Vista has substantially lower performance than XP or Windows7.  If you speed
105 // up a video too much, it can't keep up, and rendering stops updating except on
106 // the time bar. For really high speeds, audio becomes a bottleneck and we just
107 // use up the data we have, which may not achieve the speed requested, but will
108 // not crash the tab.
109 //
110 // A very slow speed, ie 0.00000001x, causes the machine to lock up. (It seems
111 // like a busy loop). It gets unresponsive, although its not completely dead.
112 //
113 // Also our timers are not very accurate (especially for ogg), which becomes
114 // evident at low speeds and on Vista. Since other speeds are risky and outside
115 // the norms, we think 1/16x to 16x is a safe and useful range for now.
116 const double kMinRate = 0.0625;
117 const double kMaxRate = 16.0;
118
119 // Prefix for histograms related to Encrypted Media Extensions.
120 const char* kMediaEme = "Media.EME.";
121
122 class SyncPointClientImpl : public media::VideoFrame::SyncPointClient {
123  public:
124   explicit SyncPointClientImpl(
125       blink::WebGraphicsContext3D* web_graphics_context)
126       : web_graphics_context_(web_graphics_context) {}
127   virtual ~SyncPointClientImpl() {}
128   virtual uint32 InsertSyncPoint() OVERRIDE {
129     return web_graphics_context_->insertSyncPoint();
130   }
131   virtual void WaitSyncPoint(uint32 sync_point) OVERRIDE {
132     web_graphics_context_->waitSyncPoint(sync_point);
133   }
134
135  private:
136   blink::WebGraphicsContext3D* web_graphics_context_;
137 };
138
139 // Used for calls to decryptor_ready_cb where the result can be ignored.
140 void DoNothing(bool) {
141 }
142
143 }  // namespace
144
145 namespace content {
146
147 class BufferedDataSourceHostImpl;
148
149 #define COMPILE_ASSERT_MATCHING_ENUM(name) \
150   COMPILE_ASSERT(static_cast<int>(WebMediaPlayer::CORSMode ## name) == \
151                  static_cast<int>(BufferedResourceLoader::k ## name), \
152                  mismatching_enums)
153 COMPILE_ASSERT_MATCHING_ENUM(Unspecified);
154 COMPILE_ASSERT_MATCHING_ENUM(Anonymous);
155 COMPILE_ASSERT_MATCHING_ENUM(UseCredentials);
156 #undef COMPILE_ASSERT_MATCHING_ENUM
157
158 #define BIND_TO_RENDER_LOOP(function) \
159   (DCHECK(main_loop_->BelongsToCurrentThread()), \
160   media::BindToCurrentLoop(base::Bind(function, AsWeakPtr())))
161
162 #define BIND_TO_RENDER_LOOP1(function, arg1) \
163   (DCHECK(main_loop_->BelongsToCurrentThread()), \
164   media::BindToCurrentLoop(base::Bind(function, AsWeakPtr(), arg1)))
165
166 static void LogMediaSourceError(const scoped_refptr<media::MediaLog>& media_log,
167                                 const std::string& error) {
168   media_log->AddEvent(media_log->CreateMediaSourceErrorEvent(error));
169 }
170
171 WebMediaPlayerImpl::WebMediaPlayerImpl(
172     blink::WebLocalFrame* frame,
173     blink::WebMediaPlayerClient* client,
174     base::WeakPtr<WebMediaPlayerDelegate> delegate,
175     const WebMediaPlayerParams& params)
176     : frame_(frame),
177       network_state_(WebMediaPlayer::NetworkStateEmpty),
178       ready_state_(WebMediaPlayer::ReadyStateHaveNothing),
179       preload_(AUTO),
180       main_loop_(base::MessageLoopProxy::current()),
181       media_loop_(
182           RenderThreadImpl::current()->GetMediaThreadMessageLoopProxy()),
183       media_log_(new RenderMediaLog()),
184       pipeline_(media_loop_, media_log_.get()),
185       load_type_(LoadTypeURL),
186       opaque_(false),
187       paused_(true),
188       seeking_(false),
189       playback_rate_(0.0f),
190       pending_seek_(false),
191       pending_seek_seconds_(0.0f),
192       should_notify_time_changed_(false),
193       client_(client),
194       delegate_(delegate),
195       defer_load_cb_(params.defer_load_cb()),
196       incremented_externally_allocated_memory_(false),
197       gpu_factories_(RenderThreadImpl::current()->GetGpuFactories()),
198       supports_save_(true),
199       chunk_demuxer_(NULL),
200       // Threaded compositing isn't enabled universally yet.
201       compositor_task_runner_(
202           RenderThreadImpl::current()->compositor_message_loop_proxy()
203               ? RenderThreadImpl::current()->compositor_message_loop_proxy()
204               : base::MessageLoopProxy::current()),
205       compositor_(new VideoFrameCompositor(
206           BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnNaturalSizeChanged),
207           BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnOpacityChanged))),
208       text_track_index_(0),
209       web_cdm_(NULL) {
210   media_log_->AddEvent(
211       media_log_->CreateEvent(media::MediaLogEvent::WEBMEDIAPLAYER_CREATED));
212
213   // |gpu_factories_| requires that its entry points be called on its
214   // |GetTaskRunner()|.  Since |pipeline_| will own decoders created from the
215   // factories, require that their message loops are identical.
216   DCHECK(!gpu_factories_ || (gpu_factories_->GetTaskRunner() == media_loop_));
217
218   // Let V8 know we started new thread if we did not do it yet.
219   // Made separate task to avoid deletion of player currently being created.
220   // Also, delaying GC until after player starts gets rid of starting lag --
221   // collection happens in parallel with playing.
222   //
223   // TODO(enal): remove when we get rid of per-audio-stream thread.
224   main_loop_->PostTask(
225       FROM_HERE,
226       base::Bind(&WebMediaPlayerImpl::IncrementExternallyAllocatedMemory,
227                  AsWeakPtr()));
228
229   // Use the null sink if no sink was provided.
230   audio_source_provider_ = new WebAudioSourceProviderImpl(
231       params.audio_renderer_sink().get()
232           ? params.audio_renderer_sink()
233           : new media::NullAudioSink(media_loop_));
234 }
235
236 WebMediaPlayerImpl::~WebMediaPlayerImpl() {
237   client_->setWebLayer(NULL);
238
239   DCHECK(main_loop_->BelongsToCurrentThread());
240   media_log_->AddEvent(
241       media_log_->CreateEvent(media::MediaLogEvent::WEBMEDIAPLAYER_DESTROYED));
242
243   if (delegate_.get())
244     delegate_->PlayerGone(this);
245
246   // Abort any pending IO so stopping the pipeline doesn't get blocked.
247   if (data_source_)
248     data_source_->Abort();
249   if (chunk_demuxer_) {
250     chunk_demuxer_->Shutdown();
251     chunk_demuxer_ = NULL;
252   }
253
254   gpu_factories_ = NULL;
255
256   // Make sure to kill the pipeline so there's no more media threads running.
257   // Note: stopping the pipeline might block for a long time.
258   base::WaitableEvent waiter(false, false);
259   pipeline_.Stop(
260       base::Bind(&base::WaitableEvent::Signal, base::Unretained(&waiter)));
261   waiter.Wait();
262
263   compositor_task_runner_->DeleteSoon(FROM_HERE, compositor_);
264
265   // Let V8 know we are not using extra resources anymore.
266   if (incremented_externally_allocated_memory_) {
267     v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(
268         -kPlayerExtraMemory);
269     incremented_externally_allocated_memory_ = false;
270   }
271 }
272
273 void WebMediaPlayerImpl::load(LoadType load_type, const blink::WebURL& url,
274                               CORSMode cors_mode) {
275   DVLOG(1) << __FUNCTION__ << "(" << load_type << ", " << url << ", "
276            << cors_mode << ")";
277   if (!defer_load_cb_.is_null()) {
278     defer_load_cb_.Run(base::Bind(
279         &WebMediaPlayerImpl::DoLoad, AsWeakPtr(), load_type, url, cors_mode));
280     return;
281   }
282   DoLoad(load_type, url, cors_mode);
283 }
284
285 void WebMediaPlayerImpl::DoLoad(LoadType load_type,
286                                 const blink::WebURL& url,
287                                 CORSMode cors_mode) {
288   DCHECK(main_loop_->BelongsToCurrentThread());
289
290   GURL gurl(url);
291   ReportMediaSchemeUma(gurl);
292
293   // Set subresource URL for crash reporting.
294   base::debug::SetCrashKeyValue("subresource_url", gurl.spec());
295
296   load_type_ = load_type;
297
298   SetNetworkState(WebMediaPlayer::NetworkStateLoading);
299   SetReadyState(WebMediaPlayer::ReadyStateHaveNothing);
300   media_log_->AddEvent(media_log_->CreateLoadEvent(url.spec()));
301
302   // Media source pipelines can start immediately.
303   if (load_type == LoadTypeMediaSource) {
304     supports_save_ = false;
305     StartPipeline();
306     return;
307   }
308
309   // Otherwise it's a regular request which requires resolving the URL first.
310   data_source_.reset(new BufferedDataSource(
311       url,
312       static_cast<BufferedResourceLoader::CORSMode>(cors_mode),
313       main_loop_,
314       frame_,
315       media_log_.get(),
316       &buffered_data_source_host_,
317       base::Bind(&WebMediaPlayerImpl::NotifyDownloading, AsWeakPtr())));
318   data_source_->Initialize(
319       base::Bind(&WebMediaPlayerImpl::DataSourceInitialized, AsWeakPtr()));
320   data_source_->SetPreload(preload_);
321 }
322
323 void WebMediaPlayerImpl::play() {
324   DVLOG(1) << __FUNCTION__;
325   DCHECK(main_loop_->BelongsToCurrentThread());
326
327   paused_ = false;
328   pipeline_.SetPlaybackRate(playback_rate_);
329   if (data_source_)
330     data_source_->MediaIsPlaying();
331
332   media_log_->AddEvent(media_log_->CreateEvent(media::MediaLogEvent::PLAY));
333
334   if (delegate_.get())
335     delegate_->DidPlay(this);
336 }
337
338 void WebMediaPlayerImpl::pause() {
339   DVLOG(1) << __FUNCTION__;
340   DCHECK(main_loop_->BelongsToCurrentThread());
341
342   paused_ = true;
343   pipeline_.SetPlaybackRate(0.0f);
344   if (data_source_)
345     data_source_->MediaIsPaused();
346   paused_time_ = pipeline_.GetMediaTime();
347
348   media_log_->AddEvent(media_log_->CreateEvent(media::MediaLogEvent::PAUSE));
349
350   if (delegate_.get())
351     delegate_->DidPause(this);
352 }
353
354 bool WebMediaPlayerImpl::supportsSave() const {
355   DCHECK(main_loop_->BelongsToCurrentThread());
356   return supports_save_;
357 }
358
359 void WebMediaPlayerImpl::seek(double seconds) {
360   DVLOG(1) << __FUNCTION__ << "(" << seconds << ")";
361   DCHECK(main_loop_->BelongsToCurrentThread());
362
363   if (ready_state_ > WebMediaPlayer::ReadyStateHaveMetadata)
364     SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata);
365
366   base::TimeDelta seek_time = ConvertSecondsToTimestamp(seconds);
367
368   if (seeking_) {
369     pending_seek_ = true;
370     pending_seek_seconds_ = seconds;
371     if (chunk_demuxer_)
372       chunk_demuxer_->CancelPendingSeek(seek_time);
373     return;
374   }
375
376   media_log_->AddEvent(media_log_->CreateSeekEvent(seconds));
377
378   // Update our paused time.
379   if (paused_)
380     paused_time_ = seek_time;
381
382   seeking_ = true;
383
384   if (chunk_demuxer_)
385     chunk_demuxer_->StartWaitingForSeek(seek_time);
386
387   // Kick off the asynchronous seek!
388   pipeline_.Seek(
389       seek_time,
390       BIND_TO_RENDER_LOOP1(&WebMediaPlayerImpl::OnPipelineSeeked, true));
391 }
392
393 void WebMediaPlayerImpl::setRate(double rate) {
394   DVLOG(1) << __FUNCTION__ << "(" << rate << ")";
395   DCHECK(main_loop_->BelongsToCurrentThread());
396
397   // TODO(kylep): Remove when support for negatives is added. Also, modify the
398   // following checks so rewind uses reasonable values also.
399   if (rate < 0.0)
400     return;
401
402   // Limit rates to reasonable values by clamping.
403   if (rate != 0.0) {
404     if (rate < kMinRate)
405       rate = kMinRate;
406     else if (rate > kMaxRate)
407       rate = kMaxRate;
408   }
409
410   playback_rate_ = rate;
411   if (!paused_) {
412     pipeline_.SetPlaybackRate(rate);
413     if (data_source_)
414       data_source_->MediaPlaybackRateChanged(rate);
415   }
416 }
417
418 void WebMediaPlayerImpl::setVolume(double volume) {
419   DVLOG(1) << __FUNCTION__ << "(" << volume << ")";
420   DCHECK(main_loop_->BelongsToCurrentThread());
421
422   pipeline_.SetVolume(volume);
423 }
424
425 #define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, chromium_name) \
426     COMPILE_ASSERT(static_cast<int>(WebMediaPlayer::webkit_name) == \
427                    static_cast<int>(content::chromium_name), \
428                    mismatching_enums)
429 COMPILE_ASSERT_MATCHING_ENUM(PreloadNone, NONE);
430 COMPILE_ASSERT_MATCHING_ENUM(PreloadMetaData, METADATA);
431 COMPILE_ASSERT_MATCHING_ENUM(PreloadAuto, AUTO);
432 #undef COMPILE_ASSERT_MATCHING_ENUM
433
434 void WebMediaPlayerImpl::setPreload(WebMediaPlayer::Preload preload) {
435   DVLOG(1) << __FUNCTION__ << "(" << preload << ")";
436   DCHECK(main_loop_->BelongsToCurrentThread());
437
438   preload_ = static_cast<content::Preload>(preload);
439   if (data_source_)
440     data_source_->SetPreload(preload_);
441 }
442
443 bool WebMediaPlayerImpl::hasVideo() const {
444   DCHECK(main_loop_->BelongsToCurrentThread());
445
446   return pipeline_metadata_.has_video;
447 }
448
449 bool WebMediaPlayerImpl::hasAudio() const {
450   DCHECK(main_loop_->BelongsToCurrentThread());
451
452   return pipeline_metadata_.has_audio;
453 }
454
455 blink::WebSize WebMediaPlayerImpl::naturalSize() const {
456   DCHECK(main_loop_->BelongsToCurrentThread());
457
458   return blink::WebSize(pipeline_metadata_.natural_size);
459 }
460
461 bool WebMediaPlayerImpl::paused() const {
462   DCHECK(main_loop_->BelongsToCurrentThread());
463
464   return pipeline_.GetPlaybackRate() == 0.0f;
465 }
466
467 bool WebMediaPlayerImpl::seeking() const {
468   DCHECK(main_loop_->BelongsToCurrentThread());
469
470   if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
471     return false;
472
473   return seeking_;
474 }
475
476 double WebMediaPlayerImpl::duration() const {
477   DCHECK(main_loop_->BelongsToCurrentThread());
478
479   if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
480     return std::numeric_limits<double>::quiet_NaN();
481
482   return GetPipelineDuration();
483 }
484
485 double WebMediaPlayerImpl::timelineOffset() const {
486   DCHECK(main_loop_->BelongsToCurrentThread());
487
488   if (pipeline_metadata_.timeline_offset.is_null())
489     return std::numeric_limits<double>::quiet_NaN();
490
491   return pipeline_metadata_.timeline_offset.ToJsTime();
492 }
493
494 double WebMediaPlayerImpl::currentTime() const {
495   DCHECK(main_loop_->BelongsToCurrentThread());
496   return (paused_ ? paused_time_ : pipeline_.GetMediaTime()).InSecondsF();
497 }
498
499 WebMediaPlayer::NetworkState WebMediaPlayerImpl::networkState() const {
500   DCHECK(main_loop_->BelongsToCurrentThread());
501   return network_state_;
502 }
503
504 WebMediaPlayer::ReadyState WebMediaPlayerImpl::readyState() const {
505   DCHECK(main_loop_->BelongsToCurrentThread());
506   return ready_state_;
507 }
508
509 blink::WebTimeRanges WebMediaPlayerImpl::buffered() const {
510   DCHECK(main_loop_->BelongsToCurrentThread());
511   media::Ranges<base::TimeDelta> buffered_time_ranges =
512       pipeline_.GetBufferedTimeRanges();
513   buffered_data_source_host_.AddBufferedTimeRanges(
514       &buffered_time_ranges, pipeline_.GetMediaDuration());
515   return ConvertToWebTimeRanges(buffered_time_ranges);
516 }
517
518 double WebMediaPlayerImpl::maxTimeSeekable() const {
519   DCHECK(main_loop_->BelongsToCurrentThread());
520
521   // If we haven't even gotten to ReadyStateHaveMetadata yet then just
522   // return 0 so that the seekable range is empty.
523   if (ready_state_ < WebMediaPlayer::ReadyStateHaveMetadata)
524     return 0.0;
525
526   // We don't support seeking in streaming media.
527   if (data_source_ && data_source_->IsStreaming())
528     return 0.0;
529   return duration();
530 }
531
532 bool WebMediaPlayerImpl::didLoadingProgress() {
533   DCHECK(main_loop_->BelongsToCurrentThread());
534   bool pipeline_progress = pipeline_.DidLoadingProgress();
535   bool data_progress = buffered_data_source_host_.DidLoadingProgress();
536   return pipeline_progress || data_progress;
537 }
538
539 void WebMediaPlayerImpl::paint(WebCanvas* canvas,
540                                const WebRect& rect,
541                                unsigned char alpha) {
542   DCHECK(main_loop_->BelongsToCurrentThread());
543   TRACE_EVENT0("media", "WebMediaPlayerImpl:paint");
544
545   // TODO(scherkus): Clarify paint() API contract to better understand when and
546   // why it's being called. For example, today paint() is called when:
547   //   - We haven't reached HAVE_CURRENT_DATA and need to paint black
548   //   - We're painting to a canvas
549   // See http://crbug.com/341225 http://crbug.com/342621 for details.
550   scoped_refptr<media::VideoFrame> video_frame =
551       GetCurrentFrameFromCompositor();
552
553   gfx::Rect gfx_rect(rect);
554
555   skcanvas_video_renderer_.Paint(video_frame.get(),
556                                  canvas,
557                                  gfx_rect,
558                                  alpha,
559                                  pipeline_metadata_.video_rotation);
560 }
561
562 bool WebMediaPlayerImpl::hasSingleSecurityOrigin() const {
563   if (data_source_)
564     return data_source_->HasSingleOrigin();
565   return true;
566 }
567
568 bool WebMediaPlayerImpl::didPassCORSAccessCheck() const {
569   if (data_source_)
570     return data_source_->DidPassCORSAccessCheck();
571   return false;
572 }
573
574 double WebMediaPlayerImpl::mediaTimeForTimeValue(double timeValue) const {
575   return ConvertSecondsToTimestamp(timeValue).InSecondsF();
576 }
577
578 unsigned WebMediaPlayerImpl::decodedFrameCount() const {
579   DCHECK(main_loop_->BelongsToCurrentThread());
580
581   media::PipelineStatistics stats = pipeline_.GetStatistics();
582   return stats.video_frames_decoded;
583 }
584
585 unsigned WebMediaPlayerImpl::droppedFrameCount() const {
586   DCHECK(main_loop_->BelongsToCurrentThread());
587
588   media::PipelineStatistics stats = pipeline_.GetStatistics();
589   return stats.video_frames_dropped;
590 }
591
592 unsigned WebMediaPlayerImpl::audioDecodedByteCount() const {
593   DCHECK(main_loop_->BelongsToCurrentThread());
594
595   media::PipelineStatistics stats = pipeline_.GetStatistics();
596   return stats.audio_bytes_decoded;
597 }
598
599 unsigned WebMediaPlayerImpl::videoDecodedByteCount() const {
600   DCHECK(main_loop_->BelongsToCurrentThread());
601
602   media::PipelineStatistics stats = pipeline_.GetStatistics();
603   return stats.video_bytes_decoded;
604 }
605
606 bool WebMediaPlayerImpl::copyVideoTextureToPlatformTexture(
607     blink::WebGraphicsContext3D* web_graphics_context,
608     unsigned int texture,
609     unsigned int level,
610     unsigned int internal_format,
611     unsigned int type,
612     bool premultiply_alpha,
613     bool flip_y) {
614   TRACE_EVENT0("media", "WebMediaPlayerImpl:copyVideoTextureToPlatformTexture");
615
616   scoped_refptr<media::VideoFrame> video_frame =
617       GetCurrentFrameFromCompositor();
618
619   if (!video_frame)
620     return false;
621   if (video_frame->format() != media::VideoFrame::NATIVE_TEXTURE)
622     return false;
623
624   const gpu::MailboxHolder* mailbox_holder = video_frame->mailbox_holder();
625   if (mailbox_holder->texture_target != GL_TEXTURE_2D)
626     return false;
627
628   web_graphics_context->waitSyncPoint(mailbox_holder->sync_point);
629   uint32 source_texture = web_graphics_context->createAndConsumeTextureCHROMIUM(
630       GL_TEXTURE_2D, mailbox_holder->mailbox.name);
631
632   // The video is stored in a unmultiplied format, so premultiply
633   // if necessary.
634   web_graphics_context->pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM,
635                                     premultiply_alpha);
636   // Application itself needs to take care of setting the right flip_y
637   // value down to get the expected result.
638   // flip_y==true means to reverse the video orientation while
639   // flip_y==false means to keep the intrinsic orientation.
640   web_graphics_context->pixelStorei(GL_UNPACK_FLIP_Y_CHROMIUM, flip_y);
641   web_graphics_context->copyTextureCHROMIUM(GL_TEXTURE_2D,
642                                             source_texture,
643                                             texture,
644                                             level,
645                                             internal_format,
646                                             type);
647   web_graphics_context->pixelStorei(GL_UNPACK_FLIP_Y_CHROMIUM, false);
648   web_graphics_context->pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM,
649                                     false);
650
651   web_graphics_context->deleteTexture(source_texture);
652   web_graphics_context->flush();
653
654   SyncPointClientImpl client(web_graphics_context);
655   video_frame->UpdateReleaseSyncPoint(&client);
656   return true;
657 }
658
659 // Helper functions to report media EME related stats to UMA. They follow the
660 // convention of more commonly used macros UMA_HISTOGRAM_ENUMERATION and
661 // UMA_HISTOGRAM_COUNTS. The reason that we cannot use those macros directly is
662 // that UMA_* macros require the names to be constant throughout the process'
663 // lifetime.
664 static void EmeUMAHistogramEnumeration(const std::string& key_system,
665                                        const std::string& method,
666                                        int sample,
667                                        int boundary_value) {
668   base::LinearHistogram::FactoryGet(
669       kMediaEme + KeySystemNameForUMA(key_system) + "." + method,
670       1, boundary_value, boundary_value + 1,
671       base::Histogram::kUmaTargetedHistogramFlag)->Add(sample);
672 }
673
674 static void EmeUMAHistogramCounts(const std::string& key_system,
675                                   const std::string& method,
676                                   int sample) {
677   // Use the same parameters as UMA_HISTOGRAM_COUNTS.
678   base::Histogram::FactoryGet(
679       kMediaEme + KeySystemNameForUMA(key_system) + "." + method,
680       1, 1000000, 50, base::Histogram::kUmaTargetedHistogramFlag)->Add(sample);
681 }
682
683 // Helper enum for reporting generateKeyRequest/addKey histograms.
684 enum MediaKeyException {
685   kUnknownResultId,
686   kSuccess,
687   kKeySystemNotSupported,
688   kInvalidPlayerState,
689   kMaxMediaKeyException
690 };
691
692 static MediaKeyException MediaKeyExceptionForUMA(
693     WebMediaPlayer::MediaKeyException e) {
694   switch (e) {
695     case WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported:
696       return kKeySystemNotSupported;
697     case WebMediaPlayer::MediaKeyExceptionInvalidPlayerState:
698       return kInvalidPlayerState;
699     case WebMediaPlayer::MediaKeyExceptionNoError:
700       return kSuccess;
701     default:
702       return kUnknownResultId;
703   }
704 }
705
706 // Helper for converting |key_system| name and exception |e| to a pair of enum
707 // values from above, for reporting to UMA.
708 static void ReportMediaKeyExceptionToUMA(const std::string& method,
709                                          const std::string& key_system,
710                                          WebMediaPlayer::MediaKeyException e) {
711   MediaKeyException result_id = MediaKeyExceptionForUMA(e);
712   DCHECK_NE(result_id, kUnknownResultId) << e;
713   EmeUMAHistogramEnumeration(
714       key_system, method, result_id, kMaxMediaKeyException);
715 }
716
717 // Convert a WebString to ASCII, falling back on an empty string in the case
718 // of a non-ASCII string.
719 static std::string ToASCIIOrEmpty(const blink::WebString& string) {
720   return base::IsStringASCII(string) ? base::UTF16ToASCII(string)
721                                      : std::string();
722 }
723
724 WebMediaPlayer::MediaKeyException
725 WebMediaPlayerImpl::generateKeyRequest(const WebString& key_system,
726                                        const unsigned char* init_data,
727                                        unsigned init_data_length) {
728   DVLOG(1) << "generateKeyRequest: " << base::string16(key_system) << ": "
729            << std::string(reinterpret_cast<const char*>(init_data),
730                           static_cast<size_t>(init_data_length));
731
732   std::string ascii_key_system =
733       GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
734
735   WebMediaPlayer::MediaKeyException e =
736       GenerateKeyRequestInternal(ascii_key_system, init_data, init_data_length);
737   ReportMediaKeyExceptionToUMA("generateKeyRequest", ascii_key_system, e);
738   return e;
739 }
740
741 // Guess the type of |init_data|. This is only used to handle some corner cases
742 // so we keep it as simple as possible without breaking major use cases.
743 static std::string GuessInitDataType(const unsigned char* init_data,
744                                      unsigned init_data_length) {
745   // Most WebM files use KeyId of 16 bytes. MP4 init data are always >16 bytes.
746   if (init_data_length == 16)
747     return "video/webm";
748
749   return "video/mp4";
750 }
751
752 WebMediaPlayer::MediaKeyException
753 WebMediaPlayerImpl::GenerateKeyRequestInternal(const std::string& key_system,
754                                                const unsigned char* init_data,
755                                                unsigned init_data_length) {
756   DCHECK(main_loop_->BelongsToCurrentThread());
757
758   if (!IsConcreteSupportedKeySystem(key_system))
759     return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
760
761   // We do not support run-time switching between key systems for now.
762   if (current_key_system_.empty()) {
763     if (!proxy_decryptor_) {
764       proxy_decryptor_.reset(new ProxyDecryptor(
765 #if defined(ENABLE_PEPPER_CDMS)
766           // Create() must be called synchronously as |frame_| may not be
767           // valid afterwards.
768           base::Bind(&PepperCdmWrapperImpl::Create, frame_),
769 #elif defined(ENABLE_BROWSER_CDMS)
770 #error Browser side CDM in WMPI for prefixed EME API not supported yet.
771 #endif
772           BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnKeyAdded),
773           BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnKeyError),
774           BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnKeyMessage)));
775     }
776
777     GURL security_origin(frame_->document().securityOrigin().toString());
778     if (!proxy_decryptor_->InitializeCDM(key_system, security_origin))
779       return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
780
781     if (proxy_decryptor_ && !decryptor_ready_cb_.is_null()) {
782       base::ResetAndReturn(&decryptor_ready_cb_)
783           .Run(proxy_decryptor_->GetDecryptor(), base::Bind(DoNothing));
784     }
785
786     current_key_system_ = key_system;
787   } else if (key_system != current_key_system_) {
788     return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
789   }
790
791   std::string init_data_type = init_data_type_;
792   if (init_data_type.empty())
793     init_data_type = GuessInitDataType(init_data, init_data_length);
794
795   // TODO(xhwang): We assume all streams are from the same container (thus have
796   // the same "type") for now. In the future, the "type" should be passed down
797   // from the application.
798   if (!proxy_decryptor_->GenerateKeyRequest(
799            init_data_type, init_data, init_data_length)) {
800     current_key_system_.clear();
801     return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
802   }
803
804   return WebMediaPlayer::MediaKeyExceptionNoError;
805 }
806
807 WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::addKey(
808     const WebString& key_system,
809     const unsigned char* key,
810     unsigned key_length,
811     const unsigned char* init_data,
812     unsigned init_data_length,
813     const WebString& session_id) {
814   DVLOG(1) << "addKey: " << base::string16(key_system) << ": "
815            << std::string(reinterpret_cast<const char*>(key),
816                           static_cast<size_t>(key_length)) << ", "
817            << std::string(reinterpret_cast<const char*>(init_data),
818                           static_cast<size_t>(init_data_length)) << " ["
819            << base::string16(session_id) << "]";
820
821   std::string ascii_key_system =
822       GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
823   std::string ascii_session_id = ToASCIIOrEmpty(session_id);
824
825   WebMediaPlayer::MediaKeyException e = AddKeyInternal(ascii_key_system,
826                                                        key,
827                                                        key_length,
828                                                        init_data,
829                                                        init_data_length,
830                                                        ascii_session_id);
831   ReportMediaKeyExceptionToUMA("addKey", ascii_key_system, e);
832   return e;
833 }
834
835 WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::AddKeyInternal(
836     const std::string& key_system,
837     const unsigned char* key,
838     unsigned key_length,
839     const unsigned char* init_data,
840     unsigned init_data_length,
841     const std::string& session_id) {
842   DCHECK(key);
843   DCHECK_GT(key_length, 0u);
844
845   if (!IsConcreteSupportedKeySystem(key_system))
846     return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
847
848   if (current_key_system_.empty() || key_system != current_key_system_)
849     return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
850
851   proxy_decryptor_->AddKey(
852       key, key_length, init_data, init_data_length, session_id);
853   return WebMediaPlayer::MediaKeyExceptionNoError;
854 }
855
856 WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::cancelKeyRequest(
857     const WebString& key_system,
858     const WebString& session_id) {
859   DVLOG(1) << "cancelKeyRequest: " << base::string16(key_system) << ": "
860            << " [" << base::string16(session_id) << "]";
861
862   std::string ascii_key_system =
863       GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
864   std::string ascii_session_id = ToASCIIOrEmpty(session_id);
865
866   WebMediaPlayer::MediaKeyException e =
867       CancelKeyRequestInternal(ascii_key_system, ascii_session_id);
868   ReportMediaKeyExceptionToUMA("cancelKeyRequest", ascii_key_system, e);
869   return e;
870 }
871
872 WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::CancelKeyRequestInternal(
873     const std::string& key_system,
874     const std::string& session_id) {
875   if (!IsConcreteSupportedKeySystem(key_system))
876     return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
877
878   if (current_key_system_.empty() || key_system != current_key_system_)
879     return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
880
881   proxy_decryptor_->CancelKeyRequest(session_id);
882   return WebMediaPlayer::MediaKeyExceptionNoError;
883 }
884
885 void WebMediaPlayerImpl::setContentDecryptionModule(
886     blink::WebContentDecryptionModule* cdm) {
887   DCHECK(main_loop_->BelongsToCurrentThread());
888
889   // TODO(xhwang): Support setMediaKeys(0) if necessary: http://crbug.com/330324
890   if (!cdm)
891     return;
892
893   web_cdm_ = ToWebContentDecryptionModuleImpl(cdm);
894
895   if (web_cdm_ && !decryptor_ready_cb_.is_null())
896     base::ResetAndReturn(&decryptor_ready_cb_)
897         .Run(web_cdm_->GetDecryptor(), base::Bind(DoNothing));
898 }
899
900 void WebMediaPlayerImpl::setContentDecryptionModule(
901     blink::WebContentDecryptionModule* cdm,
902     blink::WebContentDecryptionModuleResult result) {
903   DCHECK(main_loop_->BelongsToCurrentThread());
904
905   // TODO(xhwang): Support setMediaKeys(0) if necessary: http://crbug.com/330324
906   if (!cdm) {
907     result.completeWithError(
908         blink::WebContentDecryptionModuleExceptionNotSupportedError,
909         0,
910         "Null MediaKeys object is not supported.");
911     return;
912   }
913
914   web_cdm_ = ToWebContentDecryptionModuleImpl(cdm);
915
916   if (web_cdm_ && !decryptor_ready_cb_.is_null()) {
917     base::ResetAndReturn(&decryptor_ready_cb_)
918         .Run(web_cdm_->GetDecryptor(),
919              BIND_TO_RENDER_LOOP1(
920                  &WebMediaPlayerImpl::ContentDecryptionModuleAttached, result));
921   } else {
922     // No pipeline/decoder connected, so resolve the promise. When something
923     // is connected, setting the CDM will happen in SetDecryptorReadyCB().
924     ContentDecryptionModuleAttached(result, true);
925   }
926 }
927
928 void WebMediaPlayerImpl::setContentDecryptionModuleSync(
929     blink::WebContentDecryptionModule* cdm) {
930   DCHECK(main_loop_->BelongsToCurrentThread());
931
932   // Used when loading media and no pipeline/decoder attached yet.
933   DCHECK(decryptor_ready_cb_.is_null());
934
935   web_cdm_ = ToWebContentDecryptionModuleImpl(cdm);
936 }
937
938 void WebMediaPlayerImpl::ContentDecryptionModuleAttached(
939     blink::WebContentDecryptionModuleResult result,
940     bool success) {
941   if (success) {
942     result.complete();
943     return;
944   }
945
946   result.completeWithError(
947       blink::WebContentDecryptionModuleExceptionNotSupportedError,
948       0,
949       "Unable to set MediaKeys object");
950 }
951
952 void WebMediaPlayerImpl::OnPipelineSeeked(bool time_changed,
953                                           PipelineStatus status) {
954   DVLOG(1) << __FUNCTION__ << "(" << time_changed << ", " << status << ")";
955   DCHECK(main_loop_->BelongsToCurrentThread());
956   seeking_ = false;
957   if (pending_seek_) {
958     pending_seek_ = false;
959     seek(pending_seek_seconds_);
960     return;
961   }
962
963   if (status != media::PIPELINE_OK) {
964     OnPipelineError(status);
965     return;
966   }
967
968   // Update our paused time.
969   if (paused_)
970     paused_time_ = pipeline_.GetMediaTime();
971
972   should_notify_time_changed_ = time_changed;
973 }
974
975 void WebMediaPlayerImpl::OnPipelineEnded() {
976   DVLOG(1) << __FUNCTION__;
977   DCHECK(main_loop_->BelongsToCurrentThread());
978   client_->timeChanged();
979 }
980
981 void WebMediaPlayerImpl::OnPipelineError(PipelineStatus error) {
982   DCHECK(main_loop_->BelongsToCurrentThread());
983   DCHECK_NE(error, media::PIPELINE_OK);
984
985   if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing) {
986     // Any error that occurs before reaching ReadyStateHaveMetadata should
987     // be considered a format error.
988     SetNetworkState(WebMediaPlayer::NetworkStateFormatError);
989     return;
990   }
991
992   SetNetworkState(PipelineErrorToNetworkState(error));
993
994   if (error == media::PIPELINE_ERROR_DECRYPT)
995     EmeUMAHistogramCounts(current_key_system_, "DecryptError", 1);
996 }
997
998 void WebMediaPlayerImpl::OnPipelineMetadata(
999     media::PipelineMetadata metadata) {
1000   DVLOG(1) << __FUNCTION__;
1001
1002   pipeline_metadata_ = metadata;
1003
1004   UMA_HISTOGRAM_ENUMERATION("Media.VideoRotation",
1005                             metadata.video_rotation,
1006                             media::VIDEO_ROTATION_MAX + 1);
1007   SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata);
1008
1009   if (hasVideo()) {
1010     DCHECK(!video_weblayer_);
1011     scoped_refptr<cc::VideoLayer> layer =
1012         cc::VideoLayer::Create(compositor_, pipeline_metadata_.video_rotation);
1013
1014     if (pipeline_metadata_.video_rotation == media::VIDEO_ROTATION_90 ||
1015         pipeline_metadata_.video_rotation == media::VIDEO_ROTATION_270) {
1016       gfx::Size size = pipeline_metadata_.natural_size;
1017       pipeline_metadata_.natural_size = gfx::Size(size.height(), size.width());
1018     }
1019
1020     video_weblayer_.reset(new WebLayerImpl(layer));
1021     video_weblayer_->setOpaque(opaque_);
1022     client_->setWebLayer(video_weblayer_.get());
1023   }
1024 }
1025
1026 void WebMediaPlayerImpl::OnPipelineBufferingStateChanged(
1027     media::BufferingState buffering_state) {
1028   DVLOG(1) << __FUNCTION__ << "(" << buffering_state << ")";
1029
1030   // Ignore buffering state changes until we've completed all outstanding seeks.
1031   if (seeking_ || pending_seek_)
1032     return;
1033
1034   // TODO(scherkus): Handle other buffering states when Pipeline starts using
1035   // them and translate them ready state changes http://crbug.com/144683
1036   DCHECK_EQ(buffering_state, media::BUFFERING_HAVE_ENOUGH);
1037   SetReadyState(WebMediaPlayer::ReadyStateHaveEnoughData);
1038
1039   // Blink expects a timeChanged() in response to a seek().
1040   if (should_notify_time_changed_)
1041     client_->timeChanged();
1042 }
1043
1044 void WebMediaPlayerImpl::OnDemuxerOpened() {
1045   DCHECK(main_loop_->BelongsToCurrentThread());
1046   client_->mediaSourceOpened(new WebMediaSourceImpl(
1047       chunk_demuxer_, base::Bind(&LogMediaSourceError, media_log_)));
1048 }
1049
1050 void WebMediaPlayerImpl::OnKeyAdded(const std::string& session_id) {
1051   DCHECK(main_loop_->BelongsToCurrentThread());
1052   EmeUMAHistogramCounts(current_key_system_, "KeyAdded", 1);
1053   client_->keyAdded(
1054       WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
1055       WebString::fromUTF8(session_id));
1056 }
1057
1058 void WebMediaPlayerImpl::OnNeedKey(const std::string& type,
1059                                    const std::vector<uint8>& init_data) {
1060   DCHECK(main_loop_->BelongsToCurrentThread());
1061
1062   // Do not fire NeedKey event if encrypted media is not enabled.
1063   if (!blink::WebRuntimeFeatures::isPrefixedEncryptedMediaEnabled() &&
1064       !blink::WebRuntimeFeatures::isEncryptedMediaEnabled()) {
1065     return;
1066   }
1067
1068   UMA_HISTOGRAM_COUNTS(kMediaEme + std::string("NeedKey"), 1);
1069
1070   DCHECK(init_data_type_.empty() || type.empty() || type == init_data_type_);
1071   if (init_data_type_.empty())
1072     init_data_type_ = type;
1073
1074   const uint8* init_data_ptr = init_data.empty() ? NULL : &init_data[0];
1075   client_->keyNeeded(
1076       WebString::fromUTF8(type), init_data_ptr, init_data.size());
1077 }
1078
1079 void WebMediaPlayerImpl::OnAddTextTrack(
1080     const media::TextTrackConfig& config,
1081     const media::AddTextTrackDoneCB& done_cb) {
1082   DCHECK(main_loop_->BelongsToCurrentThread());
1083
1084   const WebInbandTextTrackImpl::Kind web_kind =
1085       static_cast<WebInbandTextTrackImpl::Kind>(config.kind());
1086   const blink::WebString web_label =
1087       blink::WebString::fromUTF8(config.label());
1088   const blink::WebString web_language =
1089       blink::WebString::fromUTF8(config.language());
1090   const blink::WebString web_id =
1091       blink::WebString::fromUTF8(config.id());
1092
1093   scoped_ptr<WebInbandTextTrackImpl> web_inband_text_track(
1094       new WebInbandTextTrackImpl(web_kind, web_label, web_language, web_id,
1095                                  text_track_index_++));
1096
1097   scoped_ptr<media::TextTrack> text_track(
1098       new TextTrackImpl(main_loop_, client_, web_inband_text_track.Pass()));
1099
1100   done_cb.Run(text_track.Pass());
1101 }
1102
1103 void WebMediaPlayerImpl::OnKeyError(const std::string& session_id,
1104                                     media::MediaKeys::KeyError error_code,
1105                                     uint32 system_code) {
1106   DCHECK(main_loop_->BelongsToCurrentThread());
1107
1108   EmeUMAHistogramEnumeration(current_key_system_, "KeyError",
1109                              error_code, media::MediaKeys::kMaxKeyError);
1110
1111   unsigned short short_system_code = 0;
1112   if (system_code > std::numeric_limits<unsigned short>::max()) {
1113     LOG(WARNING) << "system_code exceeds unsigned short limit.";
1114     short_system_code = std::numeric_limits<unsigned short>::max();
1115   } else {
1116     short_system_code = static_cast<unsigned short>(system_code);
1117   }
1118
1119   client_->keyError(
1120       WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
1121       WebString::fromUTF8(session_id),
1122       static_cast<blink::WebMediaPlayerClient::MediaKeyErrorCode>(error_code),
1123       short_system_code);
1124 }
1125
1126 void WebMediaPlayerImpl::OnKeyMessage(const std::string& session_id,
1127                                       const std::vector<uint8>& message,
1128                                       const GURL& destination_url) {
1129   DCHECK(main_loop_->BelongsToCurrentThread());
1130
1131   DCHECK(destination_url.is_empty() || destination_url.is_valid());
1132
1133   client_->keyMessage(
1134       WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
1135       WebString::fromUTF8(session_id),
1136       message.empty() ? NULL : &message[0],
1137       message.size(),
1138       destination_url);
1139 }
1140
1141 void WebMediaPlayerImpl::DataSourceInitialized(bool success) {
1142   DCHECK(main_loop_->BelongsToCurrentThread());
1143
1144   if (!success) {
1145     SetNetworkState(WebMediaPlayer::NetworkStateFormatError);
1146     return;
1147   }
1148
1149   StartPipeline();
1150 }
1151
1152 void WebMediaPlayerImpl::NotifyDownloading(bool is_downloading) {
1153   if (!is_downloading && network_state_ == WebMediaPlayer::NetworkStateLoading)
1154     SetNetworkState(WebMediaPlayer::NetworkStateIdle);
1155   else if (is_downloading && network_state_ == WebMediaPlayer::NetworkStateIdle)
1156     SetNetworkState(WebMediaPlayer::NetworkStateLoading);
1157   media_log_->AddEvent(
1158       media_log_->CreateBooleanEvent(
1159           media::MediaLogEvent::NETWORK_ACTIVITY_SET,
1160           "is_downloading_data", is_downloading));
1161 }
1162
1163 void WebMediaPlayerImpl::StartPipeline() {
1164   DCHECK(main_loop_->BelongsToCurrentThread());
1165   const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
1166
1167   // Keep track if this is a MSE or non-MSE playback.
1168   UMA_HISTOGRAM_BOOLEAN("Media.MSE.Playback",
1169                         (load_type_ == LoadTypeMediaSource));
1170
1171   media::LogCB mse_log_cb;
1172
1173   // Figure out which demuxer to use.
1174   if (load_type_ != LoadTypeMediaSource) {
1175     DCHECK(!chunk_demuxer_);
1176     DCHECK(data_source_);
1177
1178     demuxer_.reset(new media::FFmpegDemuxer(
1179         media_loop_, data_source_.get(),
1180         BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnNeedKey),
1181         media_log_));
1182   } else {
1183     DCHECK(!chunk_demuxer_);
1184     DCHECK(!data_source_);
1185
1186     mse_log_cb = base::Bind(&LogMediaSourceError, media_log_);
1187
1188     chunk_demuxer_ = new media::ChunkDemuxer(
1189         BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnDemuxerOpened),
1190         BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnNeedKey),
1191         mse_log_cb,
1192         true);
1193     demuxer_.reset(chunk_demuxer_);
1194   }
1195
1196   scoped_ptr<media::FilterCollection> filter_collection(
1197       new media::FilterCollection());
1198   filter_collection->SetDemuxer(demuxer_.get());
1199
1200   media::SetDecryptorReadyCB set_decryptor_ready_cb =
1201       BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::SetDecryptorReadyCB);
1202
1203   // Create our audio decoders and renderer.
1204   ScopedVector<media::AudioDecoder> audio_decoders;
1205   audio_decoders.push_back(new media::FFmpegAudioDecoder(media_loop_,
1206                                                          mse_log_cb));
1207   audio_decoders.push_back(new media::OpusAudioDecoder(media_loop_));
1208
1209   scoped_ptr<media::AudioRenderer> audio_renderer(new media::AudioRendererImpl(
1210       media_loop_,
1211       audio_source_provider_.get(),
1212       audio_decoders.Pass(),
1213       set_decryptor_ready_cb,
1214       RenderThreadImpl::current()->GetAudioHardwareConfig()));
1215   filter_collection->SetAudioRenderer(audio_renderer.Pass());
1216
1217   // Create our video decoders and renderer.
1218   ScopedVector<media::VideoDecoder> video_decoders;
1219
1220   if (gpu_factories_.get()) {
1221     video_decoders.push_back(
1222         new media::GpuVideoDecoder(gpu_factories_, media_log_));
1223   }
1224
1225 #if !defined(MEDIA_DISABLE_LIBVPX)
1226   video_decoders.push_back(new media::VpxVideoDecoder(media_loop_));
1227 #endif  // !defined(MEDIA_DISABLE_LIBVPX)
1228
1229   video_decoders.push_back(new media::FFmpegVideoDecoder(media_loop_));
1230
1231   scoped_ptr<media::VideoRenderer> video_renderer(
1232       new media::VideoRendererImpl(
1233           media_loop_,
1234           video_decoders.Pass(),
1235           set_decryptor_ready_cb,
1236           base::Bind(&WebMediaPlayerImpl::FrameReady, base::Unretained(this)),
1237           true));
1238   filter_collection->SetVideoRenderer(video_renderer.Pass());
1239
1240   if (cmd_line->HasSwitch(switches::kEnableInbandTextTracks)) {
1241     scoped_ptr<media::TextRenderer> text_renderer(
1242         new media::TextRenderer(
1243             media_loop_,
1244             BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnAddTextTrack)));
1245
1246     filter_collection->SetTextRenderer(text_renderer.Pass());
1247   }
1248
1249   // ... and we're ready to go!
1250   seeking_ = true;
1251   pipeline_.Start(
1252       filter_collection.Pass(),
1253       BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineEnded),
1254       BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineError),
1255       BIND_TO_RENDER_LOOP1(&WebMediaPlayerImpl::OnPipelineSeeked, false),
1256       BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineMetadata),
1257       BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineBufferingStateChanged),
1258       BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnDurationChanged));
1259 }
1260
1261 void WebMediaPlayerImpl::SetNetworkState(WebMediaPlayer::NetworkState state) {
1262   DVLOG(1) << __FUNCTION__ << "(" << state << ")";
1263   DCHECK(main_loop_->BelongsToCurrentThread());
1264   network_state_ = state;
1265   // Always notify to ensure client has the latest value.
1266   client_->networkStateChanged();
1267 }
1268
1269 void WebMediaPlayerImpl::SetReadyState(WebMediaPlayer::ReadyState state) {
1270   DVLOG(1) << __FUNCTION__ << "(" << state << ")";
1271   DCHECK(main_loop_->BelongsToCurrentThread());
1272
1273   if (state == WebMediaPlayer::ReadyStateHaveEnoughData && data_source_ &&
1274       data_source_->assume_fully_buffered() &&
1275       network_state_ == WebMediaPlayer::NetworkStateLoading)
1276     SetNetworkState(WebMediaPlayer::NetworkStateLoaded);
1277
1278   ready_state_ = state;
1279   // Always notify to ensure client has the latest value.
1280   client_->readyStateChanged();
1281 }
1282
1283 blink::WebAudioSourceProvider* WebMediaPlayerImpl::audioSourceProvider() {
1284   return audio_source_provider_.get();
1285 }
1286
1287 void WebMediaPlayerImpl::IncrementExternallyAllocatedMemory() {
1288   DCHECK(main_loop_->BelongsToCurrentThread());
1289   incremented_externally_allocated_memory_ = true;
1290   v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(
1291       kPlayerExtraMemory);
1292 }
1293
1294 double WebMediaPlayerImpl::GetPipelineDuration() const {
1295   base::TimeDelta duration = pipeline_.GetMediaDuration();
1296
1297   // Return positive infinity if the resource is unbounded.
1298   // http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#dom-media-duration
1299   if (duration == media::kInfiniteDuration())
1300     return std::numeric_limits<double>::infinity();
1301
1302   return duration.InSecondsF();
1303 }
1304
1305 void WebMediaPlayerImpl::OnDurationChanged() {
1306   if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
1307     return;
1308
1309   client_->durationChanged();
1310 }
1311
1312 void WebMediaPlayerImpl::OnNaturalSizeChanged(gfx::Size size) {
1313   DCHECK(main_loop_->BelongsToCurrentThread());
1314   DCHECK_NE(ready_state_, WebMediaPlayer::ReadyStateHaveNothing);
1315   TRACE_EVENT0("media", "WebMediaPlayerImpl::OnNaturalSizeChanged");
1316
1317   media_log_->AddEvent(
1318       media_log_->CreateVideoSizeSetEvent(size.width(), size.height()));
1319   pipeline_metadata_.natural_size = size;
1320
1321   client_->sizeChanged();
1322 }
1323
1324 void WebMediaPlayerImpl::OnOpacityChanged(bool opaque) {
1325   DCHECK(main_loop_->BelongsToCurrentThread());
1326   DCHECK_NE(ready_state_, WebMediaPlayer::ReadyStateHaveNothing);
1327
1328   opaque_ = opaque;
1329   if (video_weblayer_)
1330     video_weblayer_->setOpaque(opaque_);
1331 }
1332
1333 void WebMediaPlayerImpl::FrameReady(
1334     const scoped_refptr<media::VideoFrame>& frame) {
1335   compositor_task_runner_->PostTask(
1336       FROM_HERE,
1337       base::Bind(&VideoFrameCompositor::UpdateCurrentFrame,
1338                  base::Unretained(compositor_),
1339                  frame));
1340 }
1341
1342 void WebMediaPlayerImpl::SetDecryptorReadyCB(
1343      const media::DecryptorReadyCB& decryptor_ready_cb) {
1344   DCHECK(main_loop_->BelongsToCurrentThread());
1345
1346   // Cancels the previous decryptor request.
1347   if (decryptor_ready_cb.is_null()) {
1348     if (!decryptor_ready_cb_.is_null()) {
1349       base::ResetAndReturn(&decryptor_ready_cb_)
1350           .Run(NULL, base::Bind(DoNothing));
1351     }
1352     return;
1353   }
1354
1355   // TODO(xhwang): Support multiple decryptor notification request (e.g. from
1356   // video and audio). The current implementation is okay for the current
1357   // media pipeline since we initialize audio and video decoders in sequence.
1358   // But WebMediaPlayerImpl should not depend on media pipeline's implementation
1359   // detail.
1360   DCHECK(decryptor_ready_cb_.is_null());
1361
1362   // Mixed use of prefixed and unprefixed EME APIs is disallowed by Blink.
1363   DCHECK(!proxy_decryptor_ || !web_cdm_);
1364
1365   if (proxy_decryptor_) {
1366     decryptor_ready_cb.Run(proxy_decryptor_->GetDecryptor(),
1367                            base::Bind(DoNothing));
1368     return;
1369   }
1370
1371   if (web_cdm_) {
1372     decryptor_ready_cb.Run(web_cdm_->GetDecryptor(), base::Bind(DoNothing));
1373     return;
1374   }
1375
1376   decryptor_ready_cb_ = decryptor_ready_cb;
1377 }
1378
1379 static void GetCurrentFrameAndSignal(
1380     VideoFrameCompositor* compositor,
1381     scoped_refptr<media::VideoFrame>* video_frame_out,
1382     base::WaitableEvent* event) {
1383   TRACE_EVENT0("media", "GetCurrentFrameAndSignal");
1384   *video_frame_out = compositor->GetCurrentFrame();
1385   event->Signal();
1386 }
1387
1388 scoped_refptr<media::VideoFrame>
1389 WebMediaPlayerImpl::GetCurrentFrameFromCompositor() {
1390   TRACE_EVENT0("media", "WebMediaPlayerImpl::GetCurrentFrameFromCompositor");
1391   if (compositor_task_runner_->BelongsToCurrentThread())
1392     return compositor_->GetCurrentFrame();
1393
1394   // Use a posted task and waitable event instead of a lock otherwise
1395   // WebGL/Canvas can see different content than what the compositor is seeing.
1396   scoped_refptr<media::VideoFrame> video_frame;
1397   base::WaitableEvent event(false, false);
1398   compositor_task_runner_->PostTask(FROM_HERE,
1399                                     base::Bind(&GetCurrentFrameAndSignal,
1400                                                base::Unretained(compositor_),
1401                                                &video_frame,
1402                                                &event));
1403   event.Wait();
1404   return video_frame;
1405 }
1406
1407 }  // namespace content