Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / content / renderer / media / android / webmediaplayer_android.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/android/webmediaplayer_android.h"
6
7 #include <algorithm>
8 #include <limits>
9
10 #include "base/android/build_info.h"
11 #include "base/bind.h"
12 #include "base/callback_helpers.h"
13 #include "base/command_line.h"
14 #include "base/files/file_path.h"
15 #include "base/logging.h"
16 #include "base/metrics/histogram.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "cc/blink/web_layer_impl.h"
21 #include "cc/layers/video_layer.h"
22 #include "content/public/common/content_client.h"
23 #include "content/public/common/content_switches.h"
24 #include "content/public/renderer/render_frame.h"
25 #include "content/renderer/media/android/renderer_demuxer_android.h"
26 #include "content/renderer/media/android/renderer_media_player_manager.h"
27 #include "content/renderer/media/crypto/key_systems.h"
28 #include "content/renderer/media/crypto/render_cdm_factory.h"
29 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
30 #include "content/renderer/media/webcontentdecryptionmodule_impl.h"
31 #include "content/renderer/render_frame_impl.h"
32 #include "content/renderer/render_thread_impl.h"
33 #include "gpu/GLES2/gl2extchromium.h"
34 #include "gpu/command_buffer/client/gles2_interface.h"
35 #include "gpu/command_buffer/common/mailbox_holder.h"
36 #include "media/base/android/media_common_android.h"
37 #include "media/base/android/media_player_android.h"
38 #include "media/base/bind_to_current_loop.h"
39 #include "media/base/media_keys.h"
40 #include "media/base/media_log.h"
41 #include "media/base/media_switches.h"
42 #include "media/base/video_frame.h"
43 #include "media/blink/webmediaplayer_delegate.h"
44 #include "media/blink/webmediaplayer_util.h"
45 #include "net/base/mime_util.h"
46 #include "third_party/WebKit/public/platform/Platform.h"
47 #include "third_party/WebKit/public/platform/WebContentDecryptionModuleResult.h"
48 #include "third_party/WebKit/public/platform/WebGraphicsContext3DProvider.h"
49 #include "third_party/WebKit/public/platform/WebMediaPlayerClient.h"
50 #include "third_party/WebKit/public/platform/WebString.h"
51 #include "third_party/WebKit/public/platform/WebURL.h"
52 #include "third_party/WebKit/public/web/WebDocument.h"
53 #include "third_party/WebKit/public/web/WebFrame.h"
54 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
55 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
56 #include "third_party/WebKit/public/web/WebView.h"
57 #include "third_party/skia/include/core/SkCanvas.h"
58 #include "third_party/skia/include/core/SkPaint.h"
59 #include "third_party/skia/include/core/SkTypeface.h"
60 #include "ui/gfx/image/image.h"
61
62 static const uint32 kGLTextureExternalOES = 0x8D65;
63 static const int kSDKVersionToSupportSecurityOriginCheck = 20;
64
65 using blink::WebMediaPlayer;
66 using blink::WebSize;
67 using blink::WebString;
68 using blink::WebURL;
69 using gpu::gles2::GLES2Interface;
70 using media::MediaPlayerAndroid;
71 using media::VideoFrame;
72
73 namespace {
74 // Prefix for histograms related to Encrypted Media Extensions.
75 const char* kMediaEme = "Media.EME.";
76
77 // File-static function is to allow it to run even after WMPA is deleted.
78 void OnReleaseTexture(
79     const scoped_refptr<content::StreamTextureFactory>& factories,
80     uint32 texture_id,
81     uint32 release_sync_point) {
82   GLES2Interface* gl = factories->ContextGL();
83   gl->WaitSyncPointCHROMIUM(release_sync_point);
84   gl->DeleteTextures(1, &texture_id);
85 }
86
87 class SyncPointClientImpl : public media::VideoFrame::SyncPointClient {
88  public:
89   explicit SyncPointClientImpl(
90       blink::WebGraphicsContext3D* web_graphics_context)
91       : web_graphics_context_(web_graphics_context) {}
92   virtual ~SyncPointClientImpl() {}
93   virtual uint32 InsertSyncPoint() override {
94     return web_graphics_context_->insertSyncPoint();
95   }
96   virtual void WaitSyncPoint(uint32 sync_point) override {
97     web_graphics_context_->waitSyncPoint(sync_point);
98   }
99
100  private:
101   blink::WebGraphicsContext3D* web_graphics_context_;
102 };
103
104 // Used for calls to decryptor_ready_cb_ where the result can be ignored.
105 void DoNothing(bool) {
106 }
107
108 }  // namespace
109
110 namespace content {
111
112 WebMediaPlayerAndroid::WebMediaPlayerAndroid(
113     blink::WebFrame* frame,
114     blink::WebMediaPlayerClient* client,
115     base::WeakPtr<media::WebMediaPlayerDelegate> delegate,
116     RendererMediaPlayerManager* player_manager,
117     RendererCdmManager* cdm_manager,
118     blink::WebContentDecryptionModule* initial_cdm,
119     scoped_refptr<StreamTextureFactory> factory,
120     const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
121     media::MediaLog* media_log)
122     : RenderFrameObserver(RenderFrame::FromWebFrame(frame)),
123       frame_(frame),
124       client_(client),
125       delegate_(delegate),
126       buffered_(static_cast<size_t>(1)),
127       media_task_runner_(task_runner),
128       ignore_metadata_duration_change_(false),
129       pending_seek_(false),
130       seeking_(false),
131       did_loading_progress_(false),
132       player_manager_(player_manager),
133       cdm_manager_(cdm_manager),
134       network_state_(WebMediaPlayer::NetworkStateEmpty),
135       ready_state_(WebMediaPlayer::ReadyStateHaveNothing),
136       texture_id_(0),
137       stream_id_(0),
138       is_playing_(false),
139       needs_establish_peer_(true),
140       has_size_info_(false),
141       // Compositor thread does not exist in layout tests.
142       compositor_loop_(
143           RenderThreadImpl::current()->compositor_message_loop_proxy().get()
144               ? RenderThreadImpl::current()->compositor_message_loop_proxy()
145               : base::MessageLoopProxy::current()),
146       stream_texture_factory_(factory),
147       needs_external_surface_(false),
148       video_frame_provider_client_(NULL),
149       player_type_(MEDIA_PLAYER_TYPE_URL),
150       is_remote_(false),
151       media_log_(media_log),
152       web_cdm_(NULL),
153       allow_stored_credentials_(false),
154       is_local_resource_(false),
155       interpolator_(&default_tick_clock_),
156       weak_factory_(this) {
157   DCHECK(player_manager_);
158   DCHECK(cdm_manager_);
159
160   DCHECK(main_thread_checker_.CalledOnValidThread());
161   stream_texture_factory_->AddObserver(this);
162
163   player_id_ = player_manager_->RegisterMediaPlayer(this);
164
165 #if defined(VIDEO_HOLE)
166   force_use_overlay_embedded_video_ = CommandLine::ForCurrentProcess()->
167       HasSwitch(switches::kForceUseOverlayEmbeddedVideo);
168   if (force_use_overlay_embedded_video_ ||
169     player_manager_->ShouldUseVideoOverlayForEmbeddedEncryptedVideo()) {
170     // Defer stream texture creation until we are sure it's necessary.
171     needs_establish_peer_ = false;
172     current_frame_ = VideoFrame::CreateBlackFrame(gfx::Size(1, 1));
173   }
174 #endif  // defined(VIDEO_HOLE)
175   TryCreateStreamTextureProxyIfNeeded();
176   interpolator_.SetUpperBound(base::TimeDelta());
177
178   // Set the initial CDM, if specified.
179   if (initial_cdm) {
180     web_cdm_ = ToWebContentDecryptionModuleImpl(initial_cdm);
181     if (web_cdm_->GetCdmId() != media::MediaKeys::kInvalidCdmId)
182       player_manager_->SetCdm(player_id_, web_cdm_->GetCdmId());
183   }
184 }
185
186 WebMediaPlayerAndroid::~WebMediaPlayerAndroid() {
187   DCHECK(main_thread_checker_.CalledOnValidThread());
188   SetVideoFrameProviderClient(NULL);
189   client_->setWebLayer(NULL);
190
191   if (player_manager_) {
192     player_manager_->DestroyPlayer(player_id_);
193     player_manager_->UnregisterMediaPlayer(player_id_);
194   }
195
196   if (stream_id_) {
197     GLES2Interface* gl = stream_texture_factory_->ContextGL();
198     gl->DeleteTextures(1, &texture_id_);
199     texture_id_ = 0;
200     texture_mailbox_ = gpu::Mailbox();
201     stream_id_ = 0;
202   }
203
204   {
205     base::AutoLock auto_lock(current_frame_lock_);
206     current_frame_ = NULL;
207   }
208
209   if (delegate_)
210     delegate_->PlayerGone(this);
211
212   stream_texture_factory_->RemoveObserver(this);
213
214   if (media_source_delegate_) {
215     // Part of |media_source_delegate_| needs to be stopped on the media thread.
216     // Wait until |media_source_delegate_| is fully stopped before tearing
217     // down other objects.
218     base::WaitableEvent waiter(false, false);
219     media_source_delegate_->Stop(
220         base::Bind(&base::WaitableEvent::Signal, base::Unretained(&waiter)));
221     waiter.Wait();
222   }
223 }
224
225 void WebMediaPlayerAndroid::load(LoadType load_type,
226                                  const blink::WebURL& url,
227                                  CORSMode cors_mode) {
228   DCHECK(main_thread_checker_.CalledOnValidThread());
229   media::ReportMediaSchemeUma(GURL(url));
230
231   switch (load_type) {
232     case LoadTypeURL:
233       player_type_ = MEDIA_PLAYER_TYPE_URL;
234       break;
235
236     case LoadTypeMediaSource:
237       player_type_ = MEDIA_PLAYER_TYPE_MEDIA_SOURCE;
238       break;
239
240     case LoadTypeMediaStream:
241       CHECK(false) << "WebMediaPlayerAndroid doesn't support MediaStream on "
242                       "this platform";
243       return;
244   }
245
246   url_ = url;
247   is_local_resource_ = IsLocalResource();
248   int demuxer_client_id = 0;
249   if (player_type_ != MEDIA_PLAYER_TYPE_URL) {
250     RendererDemuxerAndroid* demuxer =
251         RenderThreadImpl::current()->renderer_demuxer();
252     demuxer_client_id = demuxer->GetNextDemuxerClientID();
253
254     media_source_delegate_.reset(new MediaSourceDelegate(
255         demuxer, demuxer_client_id, media_task_runner_, media_log_));
256
257     if (player_type_ == MEDIA_PLAYER_TYPE_MEDIA_SOURCE) {
258       media::SetDecryptorReadyCB set_decryptor_ready_cb =
259           media::BindToCurrentLoop(
260               base::Bind(&WebMediaPlayerAndroid::SetDecryptorReadyCB,
261                          weak_factory_.GetWeakPtr()));
262
263       media_source_delegate_->InitializeMediaSource(
264           base::Bind(&WebMediaPlayerAndroid::OnMediaSourceOpened,
265                      weak_factory_.GetWeakPtr()),
266           base::Bind(&WebMediaPlayerAndroid::OnNeedKey,
267                      weak_factory_.GetWeakPtr()),
268           set_decryptor_ready_cb,
269           base::Bind(&WebMediaPlayerAndroid::UpdateNetworkState,
270                      weak_factory_.GetWeakPtr()),
271           base::Bind(&WebMediaPlayerAndroid::OnDurationChanged,
272                      weak_factory_.GetWeakPtr()));
273       InitializePlayer(url_, frame_->document().firstPartyForCookies(),
274                        true, demuxer_client_id);
275     }
276   } else {
277     info_loader_.reset(
278         new MediaInfoLoader(
279             url,
280             cors_mode,
281             base::Bind(&WebMediaPlayerAndroid::DidLoadMediaInfo,
282                        weak_factory_.GetWeakPtr())));
283     info_loader_->Start(frame_);
284   }
285
286   UpdateNetworkState(WebMediaPlayer::NetworkStateLoading);
287   UpdateReadyState(WebMediaPlayer::ReadyStateHaveNothing);
288   UMA_HISTOGRAM_BOOLEAN(
289       "Media.MSE.Playback", player_type_ == MEDIA_PLAYER_TYPE_MEDIA_SOURCE);
290 }
291
292 void WebMediaPlayerAndroid::DidLoadMediaInfo(
293     MediaInfoLoader::Status status,
294     const GURL& redirected_url,
295     const GURL& first_party_for_cookies,
296     bool allow_stored_credentials) {
297   DCHECK(main_thread_checker_.CalledOnValidThread());
298   DCHECK(!media_source_delegate_);
299   if (status == MediaInfoLoader::kFailed) {
300     info_loader_.reset();
301     UpdateNetworkState(WebMediaPlayer::NetworkStateNetworkError);
302     return;
303   }
304   redirected_url_ = redirected_url;
305   InitializePlayer(
306       redirected_url, first_party_for_cookies, allow_stored_credentials, 0);
307
308   UpdateNetworkState(WebMediaPlayer::NetworkStateIdle);
309 }
310
311 bool WebMediaPlayerAndroid::IsLocalResource() {
312   if (url_.SchemeIsFile() || url_.SchemeIsBlob())
313     return true;
314
315   std::string host = url_.host();
316   if (!host.compare("localhost") || !host.compare("127.0.0.1") ||
317       !host.compare("[::1]")) {
318     return true;
319   }
320
321   return false;
322 }
323
324 void WebMediaPlayerAndroid::play() {
325   DCHECK(main_thread_checker_.CalledOnValidThread());
326
327   // For HLS streams, some devices cannot detect the video size unless a surface
328   // texture is bind to it. See http://crbug.com/400145.
329 #if defined(VIDEO_HOLE)
330   if ((hasVideo() || IsHLSStream()) && needs_external_surface_ &&
331       !player_manager_->IsInFullscreen(frame_)) {
332     DCHECK(!needs_establish_peer_);
333     player_manager_->RequestExternalSurface(player_id_, last_computed_rect_);
334   }
335 #endif  // defined(VIDEO_HOLE)
336
337   TryCreateStreamTextureProxyIfNeeded();
338   // There is no need to establish the surface texture peer for fullscreen
339   // video.
340   if ((hasVideo() || IsHLSStream()) && needs_establish_peer_ &&
341       !player_manager_->IsInFullscreen(frame_)) {
342     EstablishSurfaceTexturePeer();
343   }
344
345   if (paused())
346     player_manager_->Start(player_id_);
347   UpdatePlayingState(true);
348   UpdateNetworkState(WebMediaPlayer::NetworkStateLoading);
349 }
350
351 void WebMediaPlayerAndroid::pause() {
352   DCHECK(main_thread_checker_.CalledOnValidThread());
353   Pause(true);
354 }
355
356 void WebMediaPlayerAndroid::requestRemotePlayback() {
357   player_manager_->RequestRemotePlayback(player_id_);
358 }
359
360 void WebMediaPlayerAndroid::requestRemotePlaybackControl() {
361   player_manager_->RequestRemotePlaybackControl(player_id_);
362 }
363
364 void WebMediaPlayerAndroid::seek(double seconds) {
365   DCHECK(main_thread_checker_.CalledOnValidThread());
366   DVLOG(1) << __FUNCTION__ << "(" << seconds << ")";
367
368   base::TimeDelta new_seek_time = media::ConvertSecondsToTimestamp(seconds);
369
370   if (seeking_) {
371     if (new_seek_time == seek_time_) {
372       if (media_source_delegate_) {
373         if (!pending_seek_) {
374           // If using media source demuxer, only suppress redundant seeks if
375           // there is no pending seek. This enforces that any pending seek that
376           // results in a demuxer seek is preceded by matching
377           // CancelPendingSeek() and StartWaitingForSeek() calls.
378           return;
379         }
380       } else {
381         // Suppress all redundant seeks if unrestricted by media source
382         // demuxer API.
383         pending_seek_ = false;
384         return;
385       }
386     }
387
388     pending_seek_ = true;
389     pending_seek_time_ = new_seek_time;
390
391     if (media_source_delegate_)
392       media_source_delegate_->CancelPendingSeek(pending_seek_time_);
393
394     // Later, OnSeekComplete will trigger the pending seek.
395     return;
396   }
397
398   seeking_ = true;
399   seek_time_ = new_seek_time;
400
401   if (media_source_delegate_)
402     media_source_delegate_->StartWaitingForSeek(seek_time_);
403
404   // Kick off the asynchronous seek!
405   player_manager_->Seek(player_id_, seek_time_);
406 }
407
408 bool WebMediaPlayerAndroid::supportsSave() const {
409   return false;
410 }
411
412 void WebMediaPlayerAndroid::setRate(double rate) {
413   NOTIMPLEMENTED();
414 }
415
416 void WebMediaPlayerAndroid::setVolume(double volume) {
417   DCHECK(main_thread_checker_.CalledOnValidThread());
418   player_manager_->SetVolume(player_id_, volume);
419 }
420
421 bool WebMediaPlayerAndroid::hasVideo() const {
422   DCHECK(main_thread_checker_.CalledOnValidThread());
423   // If we have obtained video size information before, use it.
424   if (has_size_info_)
425     return !natural_size_.isEmpty();
426
427   // TODO(qinmin): need a better method to determine whether the current media
428   // content contains video. Android does not provide any function to do
429   // this.
430   // We don't know whether the current media content has video unless
431   // the player is prepared. If the player is not prepared, we fall back
432   // to the mime-type. There may be no mime-type on a redirect URL.
433   // In that case, we conservatively assume it contains video so that
434   // enterfullscreen call will not fail.
435   if (!url_.has_path())
436     return false;
437   std::string mime;
438   if (!net::GetMimeTypeFromFile(base::FilePath(url_.path()), &mime))
439     return true;
440   return mime.find("audio/") == std::string::npos;
441 }
442
443 bool WebMediaPlayerAndroid::hasAudio() const {
444   DCHECK(main_thread_checker_.CalledOnValidThread());
445   if (!url_.has_path())
446     return false;
447   std::string mime;
448   if (!net::GetMimeTypeFromFile(base::FilePath(url_.path()), &mime))
449     return true;
450
451   if (mime.find("audio/") != std::string::npos ||
452       mime.find("video/") != std::string::npos ||
453       mime.find("application/ogg") != std::string::npos) {
454     return true;
455   }
456   return false;
457 }
458
459 bool WebMediaPlayerAndroid::isRemote() const {
460   return is_remote_;
461 }
462
463 bool WebMediaPlayerAndroid::paused() const {
464   return !is_playing_;
465 }
466
467 bool WebMediaPlayerAndroid::seeking() const {
468   return seeking_;
469 }
470
471 double WebMediaPlayerAndroid::duration() const {
472   DCHECK(main_thread_checker_.CalledOnValidThread());
473   // HTML5 spec requires duration to be NaN if readyState is HAVE_NOTHING
474   if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
475     return std::numeric_limits<double>::quiet_NaN();
476
477   if (duration_ == media::kInfiniteDuration())
478     return std::numeric_limits<double>::infinity();
479
480   return duration_.InSecondsF();
481 }
482
483 double WebMediaPlayerAndroid::timelineOffset() const {
484   DCHECK(main_thread_checker_.CalledOnValidThread());
485   base::Time timeline_offset;
486   if (media_source_delegate_)
487     timeline_offset = media_source_delegate_->GetTimelineOffset();
488
489   if (timeline_offset.is_null())
490     return std::numeric_limits<double>::quiet_NaN();
491
492   return timeline_offset.ToJsTime();
493 }
494
495 double WebMediaPlayerAndroid::currentTime() const {
496   DCHECK(main_thread_checker_.CalledOnValidThread());
497   // If the player is processing a seek, return the seek time.
498   // Blink may still query us if updatePlaybackState() occurs while seeking.
499   if (seeking()) {
500     return pending_seek_ ?
501         pending_seek_time_.InSecondsF() : seek_time_.InSecondsF();
502   }
503
504   return std::min(
505       (const_cast<media::TimeDeltaInterpolator*>(
506           &interpolator_))->GetInterpolatedTime(), duration_).InSecondsF();
507 }
508
509 WebSize WebMediaPlayerAndroid::naturalSize() const {
510   return natural_size_;
511 }
512
513 WebMediaPlayer::NetworkState WebMediaPlayerAndroid::networkState() const {
514   return network_state_;
515 }
516
517 WebMediaPlayer::ReadyState WebMediaPlayerAndroid::readyState() const {
518   return ready_state_;
519 }
520
521 blink::WebTimeRanges WebMediaPlayerAndroid::buffered() const {
522   if (media_source_delegate_)
523     return media_source_delegate_->Buffered();
524   return buffered_;
525 }
526
527 blink::WebTimeRanges WebMediaPlayerAndroid::seekable() const {
528   if (ready_state_ < WebMediaPlayer::ReadyStateHaveMetadata)
529     return blink::WebTimeRanges();
530
531   // TODO(dalecurtis): Technically this allows seeking on media which return an
532   // infinite duration.  While not expected, disabling this breaks semi-live
533   // players, http://crbug.com/427412.
534   const blink::WebTimeRange seekable_range(0.0, duration());
535   return blink::WebTimeRanges(&seekable_range, 1);
536 }
537
538 bool WebMediaPlayerAndroid::didLoadingProgress() {
539   bool ret = did_loading_progress_;
540   did_loading_progress_ = false;
541   return ret;
542 }
543
544 bool WebMediaPlayerAndroid::EnsureTextureBackedSkBitmap(GrContext* gr,
545                                                         SkBitmap& bitmap,
546                                                         const WebSize& size,
547                                                         GrSurfaceOrigin origin,
548                                                         GrPixelConfig config) {
549   DCHECK(main_thread_checker_.CalledOnValidThread());
550   if (!bitmap.getTexture() || bitmap.width() != size.width
551       || bitmap.height() != size.height) {
552     if (!gr)
553       return false;
554     GrTextureDesc desc;
555     desc.fConfig = config;
556     desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
557     desc.fSampleCnt = 0;
558     desc.fOrigin = origin;
559     desc.fWidth = size.width;
560     desc.fHeight = size.height;
561     skia::RefPtr<GrTexture> texture;
562     texture = skia::AdoptRef(gr->createUncachedTexture(desc, 0, 0));
563     if (!texture.get())
564       return false;
565
566     SkImageInfo info = SkImageInfo::MakeN32Premul(desc.fWidth, desc.fHeight);
567     SkGrPixelRef* pixelRef = SkNEW_ARGS(SkGrPixelRef, (info, texture.get()));
568     if (!pixelRef)
569       return false;
570     bitmap.setInfo(info);
571     bitmap.setPixelRef(pixelRef)->unref();
572   }
573
574   return true;
575 }
576
577 void WebMediaPlayerAndroid::paint(blink::WebCanvas* canvas,
578                                   const blink::WebRect& rect,
579                                   unsigned char alpha,
580                                   SkXfermode::Mode mode) {
581   DCHECK(main_thread_checker_.CalledOnValidThread());
582   scoped_ptr<blink::WebGraphicsContext3DProvider> provider =
583     scoped_ptr<blink::WebGraphicsContext3DProvider>(blink::Platform::current(
584       )->createSharedOffscreenGraphicsContext3DProvider());
585   if (!provider)
586     return;
587   blink::WebGraphicsContext3D* context3D = provider->context3d();
588   if (!context3D)
589     return;
590
591   // Copy video texture into a RGBA texture based bitmap first as video texture
592   // on Android is GL_TEXTURE_EXTERNAL_OES which is not supported by Skia yet.
593   // The bitmap's size needs to be the same as the video and use naturalSize()
594   // here. Check if we could reuse existing texture based bitmap.
595   // Otherwise, release existing texture based bitmap and allocate
596   // a new one based on video size.
597   if (!EnsureTextureBackedSkBitmap(provider->grContext(), bitmap_,
598       naturalSize(), kTopLeft_GrSurfaceOrigin, kSkia8888_GrPixelConfig)) {
599     return;
600   }
601
602   unsigned textureId = static_cast<unsigned>(
603     (bitmap_.getTexture())->getTextureHandle());
604   if (!copyVideoTextureToPlatformTexture(context3D, textureId, 0,
605       GL_RGBA, GL_UNSIGNED_BYTE, true, false)) {
606     return;
607   }
608
609   // Draw the texture based bitmap onto the Canvas. If the canvas is
610   // hardware based, this will do a GPU-GPU texture copy.
611   // If the canvas is software based, the texture based bitmap will be
612   // readbacked to system memory then draw onto the canvas.
613   SkRect dest;
614   dest.set(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height);
615   SkPaint paint;
616   paint.setAlpha(alpha);
617   paint.setXfermodeMode(mode);
618   // It is not necessary to pass the dest into the drawBitmap call since all
619   // the context have been set up before calling paintCurrentFrameInContext.
620   canvas->drawBitmapRect(bitmap_, 0, dest, &paint);
621 }
622
623 bool WebMediaPlayerAndroid::copyVideoTextureToPlatformTexture(
624     blink::WebGraphicsContext3D* web_graphics_context,
625     unsigned int texture,
626     unsigned int level,
627     unsigned int internal_format,
628     unsigned int type,
629     bool premultiply_alpha,
630     bool flip_y) {
631   DCHECK(main_thread_checker_.CalledOnValidThread());
632   // Don't allow clients to copy an encrypted video frame.
633   if (needs_external_surface_)
634     return false;
635
636   scoped_refptr<VideoFrame> video_frame;
637   {
638     base::AutoLock auto_lock(current_frame_lock_);
639     video_frame = current_frame_;
640   }
641
642   if (!video_frame.get() ||
643       video_frame->format() != media::VideoFrame::NATIVE_TEXTURE)
644     return false;
645   const gpu::MailboxHolder* mailbox_holder = video_frame->mailbox_holder();
646   DCHECK((!is_remote_ &&
647           mailbox_holder->texture_target == GL_TEXTURE_EXTERNAL_OES) ||
648          (is_remote_ && mailbox_holder->texture_target == GL_TEXTURE_2D));
649
650   web_graphics_context->waitSyncPoint(mailbox_holder->sync_point);
651
652   // Ensure the target of texture is set before copyTextureCHROMIUM, otherwise
653   // an invalid texture target may be used for copy texture.
654   uint32 src_texture = web_graphics_context->createAndConsumeTextureCHROMIUM(
655       mailbox_holder->texture_target, mailbox_holder->mailbox.name);
656
657   // The video is stored in an unmultiplied format, so premultiply if
658   // necessary.
659   web_graphics_context->pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM,
660                                     premultiply_alpha);
661
662   // Application itself needs to take care of setting the right flip_y
663   // value down to get the expected result.
664   // flip_y==true means to reverse the video orientation while
665   // flip_y==false means to keep the intrinsic orientation.
666   web_graphics_context->pixelStorei(GL_UNPACK_FLIP_Y_CHROMIUM, flip_y);
667   web_graphics_context->copyTextureCHROMIUM(GL_TEXTURE_2D, src_texture,
668                                             texture, level, internal_format,
669                                             type);
670   web_graphics_context->pixelStorei(GL_UNPACK_FLIP_Y_CHROMIUM, false);
671   web_graphics_context->pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM,
672                                     false);
673
674   web_graphics_context->deleteTexture(src_texture);
675   web_graphics_context->flush();
676
677   SyncPointClientImpl client(web_graphics_context);
678   video_frame->UpdateReleaseSyncPoint(&client);
679   return true;
680 }
681
682 bool WebMediaPlayerAndroid::hasSingleSecurityOrigin() const {
683   DCHECK(main_thread_checker_.CalledOnValidThread());
684   if (player_type_ != MEDIA_PLAYER_TYPE_URL)
685     return true;
686
687   if (!info_loader_ || !info_loader_->HasSingleOrigin())
688     return false;
689
690   // TODO(qinmin): The url might be redirected when android media player
691   // requests the stream. As a result, we cannot guarantee there is only
692   // a single origin. Only if the HTTP request was made without credentials,
693   // we will honor the return value from  HasSingleSecurityOriginInternal()
694   // in pre-L android versions.
695   // Check http://crbug.com/334204.
696   if (!allow_stored_credentials_)
697     return true;
698
699   return base::android::BuildInfo::GetInstance()->sdk_int() >=
700       kSDKVersionToSupportSecurityOriginCheck;
701 }
702
703 bool WebMediaPlayerAndroid::didPassCORSAccessCheck() const {
704   DCHECK(main_thread_checker_.CalledOnValidThread());
705   if (info_loader_)
706     return info_loader_->DidPassCORSAccessCheck();
707   return false;
708 }
709
710 double WebMediaPlayerAndroid::mediaTimeForTimeValue(double timeValue) const {
711   return media::ConvertSecondsToTimestamp(timeValue).InSecondsF();
712 }
713
714 unsigned WebMediaPlayerAndroid::decodedFrameCount() const {
715   if (media_source_delegate_)
716     return media_source_delegate_->DecodedFrameCount();
717   NOTIMPLEMENTED();
718   return 0;
719 }
720
721 unsigned WebMediaPlayerAndroid::droppedFrameCount() const {
722   if (media_source_delegate_)
723     return media_source_delegate_->DroppedFrameCount();
724   NOTIMPLEMENTED();
725   return 0;
726 }
727
728 unsigned WebMediaPlayerAndroid::audioDecodedByteCount() const {
729   if (media_source_delegate_)
730     return media_source_delegate_->AudioDecodedByteCount();
731   NOTIMPLEMENTED();
732   return 0;
733 }
734
735 unsigned WebMediaPlayerAndroid::videoDecodedByteCount() const {
736   if (media_source_delegate_)
737     return media_source_delegate_->VideoDecodedByteCount();
738   NOTIMPLEMENTED();
739   return 0;
740 }
741
742 void WebMediaPlayerAndroid::OnMediaMetadataChanged(
743     const base::TimeDelta& duration, int width, int height, bool success) {
744   DCHECK(main_thread_checker_.CalledOnValidThread());
745   bool need_to_signal_duration_changed = false;
746
747   if (is_local_resource_ || url_.SchemeIs("app"))
748     UpdateNetworkState(WebMediaPlayer::NetworkStateLoaded);
749
750   // Update duration, if necessary, prior to ready state updates that may
751   // cause duration() query.
752   if (!ignore_metadata_duration_change_ && duration_ != duration) {
753     duration_ = duration;
754     if (is_local_resource_)
755       buffered_[0].end = duration_.InSecondsF();
756     // Client readyState transition from HAVE_NOTHING to HAVE_METADATA
757     // already triggers a durationchanged event. If this is a different
758     // transition, remember to signal durationchanged.
759     // Do not ever signal durationchanged on metadata change in MSE case
760     // because OnDurationChanged() handles this.
761     if (ready_state_ > WebMediaPlayer::ReadyStateHaveNothing &&
762         player_type_ != MEDIA_PLAYER_TYPE_MEDIA_SOURCE) {
763       need_to_signal_duration_changed = true;
764     }
765   }
766
767   if (ready_state_ != WebMediaPlayer::ReadyStateHaveEnoughData) {
768     UpdateReadyState(WebMediaPlayer::ReadyStateHaveMetadata);
769     UpdateReadyState(WebMediaPlayer::ReadyStateHaveEnoughData);
770   }
771
772   // TODO(wolenetz): Should we just abort early and set network state to an
773   // error if success == false? See http://crbug.com/248399
774   if (success)
775     OnVideoSizeChanged(width, height);
776
777   if (need_to_signal_duration_changed)
778     client_->durationChanged();
779 }
780
781 void WebMediaPlayerAndroid::OnPlaybackComplete() {
782   // When playback is about to finish, android media player often stops
783   // at a time which is smaller than the duration. This makes webkit never
784   // know that the playback has finished. To solve this, we set the
785   // current time to media duration when OnPlaybackComplete() get called.
786   interpolator_.SetBounds(duration_, duration_);
787   client_->timeChanged();
788
789   // If the loop attribute is set, timeChanged() will update the current time
790   // to 0. It will perform a seek to 0. Issue a command to the player to start
791   // playing after seek completes.
792   if (seeking_ && seek_time_ == base::TimeDelta())
793     player_manager_->Start(player_id_);
794 }
795
796 void WebMediaPlayerAndroid::OnBufferingUpdate(int percentage) {
797   buffered_[0].end = duration() * percentage / 100;
798   did_loading_progress_ = true;
799 }
800
801 void WebMediaPlayerAndroid::OnSeekRequest(const base::TimeDelta& time_to_seek) {
802   DCHECK(main_thread_checker_.CalledOnValidThread());
803   client_->requestSeek(time_to_seek.InSecondsF());
804 }
805
806 void WebMediaPlayerAndroid::OnSeekComplete(
807     const base::TimeDelta& current_time) {
808   DCHECK(main_thread_checker_.CalledOnValidThread());
809   seeking_ = false;
810   if (pending_seek_) {
811     pending_seek_ = false;
812     seek(pending_seek_time_.InSecondsF());
813     return;
814   }
815   interpolator_.SetBounds(current_time, current_time);
816
817   UpdateReadyState(WebMediaPlayer::ReadyStateHaveEnoughData);
818
819   client_->timeChanged();
820 }
821
822 void WebMediaPlayerAndroid::OnMediaError(int error_type) {
823   switch (error_type) {
824     case MediaPlayerAndroid::MEDIA_ERROR_FORMAT:
825       UpdateNetworkState(WebMediaPlayer::NetworkStateFormatError);
826       break;
827     case MediaPlayerAndroid::MEDIA_ERROR_DECODE:
828       UpdateNetworkState(WebMediaPlayer::NetworkStateDecodeError);
829       break;
830     case MediaPlayerAndroid::MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
831       UpdateNetworkState(WebMediaPlayer::NetworkStateFormatError);
832       break;
833     case MediaPlayerAndroid::MEDIA_ERROR_INVALID_CODE:
834       break;
835   }
836   client_->repaint();
837 }
838
839 void WebMediaPlayerAndroid::OnVideoSizeChanged(int width, int height) {
840   DCHECK(main_thread_checker_.CalledOnValidThread());
841   has_size_info_ = true;
842   if (natural_size_.width == width && natural_size_.height == height)
843     return;
844
845 #if defined(VIDEO_HOLE)
846   // Use H/W surface for encrypted video.
847   // TODO(qinmin): Change this so that only EME needs the H/W surface
848   if (force_use_overlay_embedded_video_ ||
849       (media_source_delegate_ && media_source_delegate_->IsVideoEncrypted() &&
850        player_manager_->ShouldUseVideoOverlayForEmbeddedEncryptedVideo())) {
851     needs_external_surface_ = true;
852     if (!paused() && !player_manager_->IsInFullscreen(frame_))
853       player_manager_->RequestExternalSurface(player_id_, last_computed_rect_);
854   } else if (stream_texture_proxy_ && !stream_id_) {
855     // Do deferred stream texture creation finally.
856     DoCreateStreamTexture();
857     SetNeedsEstablishPeer(true);
858   }
859 #endif  // defined(VIDEO_HOLE)
860   natural_size_.width = width;
861   natural_size_.height = height;
862
863   // When play() gets called, |natural_size_| may still be empty and
864   // EstablishSurfaceTexturePeer() will not get called. As a result, the video
865   // may play without a surface texture. When we finally get the valid video
866   // size here, we should call EstablishSurfaceTexturePeer() if it has not been
867   // previously called.
868   if (!paused() && needs_establish_peer_)
869     EstablishSurfaceTexturePeer();
870
871   ReallocateVideoFrame();
872
873   // For hidden video element (with style "display:none"), ensure the texture
874   // size is set.
875   if (!is_remote_ && cached_stream_texture_size_ != natural_size_) {
876     stream_texture_factory_->SetStreamTextureSize(
877         stream_id_, gfx::Size(natural_size_.width, natural_size_.height));
878     cached_stream_texture_size_ = natural_size_;
879   }
880
881   // Lazily allocate compositing layer.
882   if (!video_weblayer_) {
883     video_weblayer_.reset(new cc_blink::WebLayerImpl(
884         cc::VideoLayer::Create(this, media::VIDEO_ROTATION_0)));
885     client_->setWebLayer(video_weblayer_.get());
886   }
887
888   // TODO(qinmin): This is a hack. We need the media element to stop showing the
889   // poster image by forcing it to call setDisplayMode(video). Should move the
890   // logic into HTMLMediaElement.cpp.
891   client_->timeChanged();
892 }
893
894 void WebMediaPlayerAndroid::OnTimeUpdate(base::TimeDelta current_timestamp,
895                                          base::TimeTicks current_time_ticks) {
896   DCHECK(main_thread_checker_.CalledOnValidThread());
897   // Compensate the current_timestamp with the IPC latency.
898   base::TimeDelta lower_bound =
899       base::TimeTicks::Now() - current_time_ticks + current_timestamp;
900   base::TimeDelta upper_bound = lower_bound;
901   // We should get another time update in about |kTimeUpdateInterval|
902   // milliseconds.
903   if (is_playing_) {
904     upper_bound += base::TimeDelta::FromMilliseconds(
905         media::kTimeUpdateInterval);
906   }
907   // if the lower_bound is smaller than the current time, just use the current
908   // time so that the timer is always progressing.
909   lower_bound =
910       std::min(lower_bound, base::TimeDelta::FromSecondsD(currentTime()));
911   interpolator_.SetBounds(lower_bound, upper_bound);
912 }
913
914 void WebMediaPlayerAndroid::OnConnectedToRemoteDevice(
915     const std::string& remote_playback_message) {
916   DCHECK(main_thread_checker_.CalledOnValidThread());
917   DCHECK(!media_source_delegate_);
918   DrawRemotePlaybackText(remote_playback_message);
919   is_remote_ = true;
920   SetNeedsEstablishPeer(false);
921   client_->connectedToRemoteDevice();
922 }
923
924 void WebMediaPlayerAndroid::OnDisconnectedFromRemoteDevice() {
925   DCHECK(main_thread_checker_.CalledOnValidThread());
926   DCHECK(!media_source_delegate_);
927   SetNeedsEstablishPeer(true);
928   if (!paused())
929     EstablishSurfaceTexturePeer();
930   is_remote_ = false;
931   ReallocateVideoFrame();
932   client_->disconnectedFromRemoteDevice();
933 }
934
935 void WebMediaPlayerAndroid::OnDidEnterFullscreen() {
936   if (!player_manager_->IsInFullscreen(frame_))
937     player_manager_->DidEnterFullscreen(frame_);
938 }
939
940 void WebMediaPlayerAndroid::OnDidExitFullscreen() {
941   // |needs_external_surface_| is always false on non-TV devices.
942   if (!needs_external_surface_)
943     SetNeedsEstablishPeer(true);
944   // We had the fullscreen surface connected to Android MediaPlayer,
945   // so reconnect our surface texture for embedded playback.
946   if (!paused() && needs_establish_peer_)
947     EstablishSurfaceTexturePeer();
948
949 #if defined(VIDEO_HOLE)
950   if (!paused() && needs_external_surface_)
951     player_manager_->RequestExternalSurface(player_id_, last_computed_rect_);
952 #endif  // defined(VIDEO_HOLE)
953
954   player_manager_->DidExitFullscreen();
955   client_->repaint();
956 }
957
958 void WebMediaPlayerAndroid::OnMediaPlayerPlay() {
959   UpdatePlayingState(true);
960   client_->playbackStateChanged();
961 }
962
963 void WebMediaPlayerAndroid::OnMediaPlayerPause() {
964   UpdatePlayingState(false);
965   client_->playbackStateChanged();
966 }
967
968 void WebMediaPlayerAndroid::OnRequestFullscreen() {
969   client_->requestFullscreen();
970 }
971
972 void WebMediaPlayerAndroid::OnRemoteRouteAvailabilityChanged(
973     bool routes_available) {
974   client_->remoteRouteAvailabilityChanged(routes_available);
975 }
976
977 void WebMediaPlayerAndroid::OnDurationChanged(const base::TimeDelta& duration) {
978   DCHECK(main_thread_checker_.CalledOnValidThread());
979   // Only MSE |player_type_| registers this callback.
980   DCHECK_EQ(player_type_, MEDIA_PLAYER_TYPE_MEDIA_SOURCE);
981
982   // Cache the new duration value and trust it over any subsequent duration
983   // values received in OnMediaMetadataChanged().
984   duration_ = duration;
985   ignore_metadata_duration_change_ = true;
986
987   // Notify MediaPlayerClient that duration has changed, if > HAVE_NOTHING.
988   if (ready_state_ > WebMediaPlayer::ReadyStateHaveNothing)
989     client_->durationChanged();
990 }
991
992 void WebMediaPlayerAndroid::UpdateNetworkState(
993     WebMediaPlayer::NetworkState state) {
994   DCHECK(main_thread_checker_.CalledOnValidThread());
995   if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing &&
996       (state == WebMediaPlayer::NetworkStateNetworkError ||
997        state == WebMediaPlayer::NetworkStateDecodeError)) {
998     // Any error that occurs before reaching ReadyStateHaveMetadata should
999     // be considered a format error.
1000     network_state_ = WebMediaPlayer::NetworkStateFormatError;
1001   } else {
1002     network_state_ = state;
1003   }
1004   client_->networkStateChanged();
1005 }
1006
1007 void WebMediaPlayerAndroid::UpdateReadyState(
1008     WebMediaPlayer::ReadyState state) {
1009   ready_state_ = state;
1010   client_->readyStateChanged();
1011 }
1012
1013 void WebMediaPlayerAndroid::OnPlayerReleased() {
1014   // |needs_external_surface_| is always false on non-TV devices.
1015   if (!needs_external_surface_)
1016     needs_establish_peer_ = true;
1017
1018   if (is_playing_)
1019     OnMediaPlayerPause();
1020
1021 #if defined(VIDEO_HOLE)
1022   last_computed_rect_ = gfx::RectF();
1023 #endif  // defined(VIDEO_HOLE)
1024 }
1025
1026 void WebMediaPlayerAndroid::ReleaseMediaResources() {
1027   switch (network_state_) {
1028     // Pause the media player and inform WebKit if the player is in a good
1029     // shape.
1030     case WebMediaPlayer::NetworkStateIdle:
1031     case WebMediaPlayer::NetworkStateLoading:
1032     case WebMediaPlayer::NetworkStateLoaded:
1033       Pause(false);
1034       client_->playbackStateChanged();
1035       break;
1036     // If a WebMediaPlayer instance has entered into one of these states,
1037     // the internal network state in HTMLMediaElement could be set to empty.
1038     // And calling playbackStateChanged() could get this object deleted.
1039     case WebMediaPlayer::NetworkStateEmpty:
1040     case WebMediaPlayer::NetworkStateFormatError:
1041     case WebMediaPlayer::NetworkStateNetworkError:
1042     case WebMediaPlayer::NetworkStateDecodeError:
1043       break;
1044   }
1045   player_manager_->ReleaseResources(player_id_);
1046   if (!needs_external_surface_)
1047     SetNeedsEstablishPeer(true);
1048 }
1049
1050 void WebMediaPlayerAndroid::OnDestruct() {
1051   NOTREACHED() << "WebMediaPlayer should be destroyed before any "
1052                   "RenderFrameObserver::OnDestruct() gets called when "
1053                   "the RenderFrame goes away.";
1054 }
1055
1056 void WebMediaPlayerAndroid::InitializePlayer(
1057     const GURL& url,
1058     const GURL& first_party_for_cookies,
1059     bool allow_stored_credentials,
1060     int demuxer_client_id) {
1061   if (player_type_ == MEDIA_PLAYER_TYPE_URL) {
1062     UMA_HISTOGRAM_BOOLEAN("Media.Android.IsHttpLiveStreamingMedia",
1063                           IsHLSStream());
1064   }
1065   allow_stored_credentials_ = allow_stored_credentials;
1066   player_manager_->Initialize(
1067       player_type_, player_id_, url, first_party_for_cookies, demuxer_client_id,
1068       frame_->document().url(), allow_stored_credentials);
1069   if (player_manager_->ShouldEnterFullscreen(frame_))
1070     player_manager_->EnterFullscreen(player_id_, frame_);
1071 }
1072
1073 void WebMediaPlayerAndroid::Pause(bool is_media_related_action) {
1074   player_manager_->Pause(player_id_, is_media_related_action);
1075   UpdatePlayingState(false);
1076 }
1077
1078 void WebMediaPlayerAndroid::DrawRemotePlaybackText(
1079     const std::string& remote_playback_message) {
1080   DCHECK(main_thread_checker_.CalledOnValidThread());
1081   if (!video_weblayer_)
1082     return;
1083
1084   // TODO(johnme): Should redraw this frame if the layer bounds change; but
1085   // there seems no easy way to listen for the layer resizing (as opposed to
1086   // OnVideoSizeChanged, which is when the frame sizes of the video file
1087   // change). Perhaps have to poll (on main thread of course)?
1088   gfx::Size video_size_css_px = video_weblayer_->bounds();
1089   float device_scale_factor = frame_->view()->deviceScaleFactor();
1090   // canvas_size will be the size in device pixels when pageScaleFactor == 1
1091   gfx::Size canvas_size(
1092       static_cast<int>(video_size_css_px.width() * device_scale_factor),
1093       static_cast<int>(video_size_css_px.height() * device_scale_factor));
1094
1095   SkBitmap bitmap;
1096   bitmap.allocN32Pixels(canvas_size.width(), canvas_size.height());
1097
1098   // Create the canvas and draw the "Casting to <Chromecast>" text on it.
1099   SkCanvas canvas(bitmap);
1100   canvas.drawColor(SK_ColorBLACK);
1101
1102   const SkScalar kTextSize(40);
1103   const SkScalar kMinPadding(40);
1104
1105   SkPaint paint;
1106   paint.setAntiAlias(true);
1107   paint.setFilterLevel(SkPaint::kHigh_FilterLevel);
1108   paint.setColor(SK_ColorWHITE);
1109   paint.setTypeface(SkTypeface::CreateFromName("sans", SkTypeface::kBold));
1110   paint.setTextSize(kTextSize);
1111
1112   // Calculate the vertical margin from the top
1113   SkPaint::FontMetrics font_metrics;
1114   paint.getFontMetrics(&font_metrics);
1115   SkScalar sk_vertical_margin = kMinPadding - font_metrics.fAscent;
1116
1117   // Measure the width of the entire text to display
1118   size_t display_text_width = paint.measureText(
1119       remote_playback_message.c_str(), remote_playback_message.size());
1120   std::string display_text(remote_playback_message);
1121
1122   if (display_text_width + (kMinPadding * 2) > canvas_size.width()) {
1123     // The text is too long to fit in one line, truncate it and append ellipsis
1124     // to the end.
1125
1126     // First, figure out how much of the canvas the '...' will take up.
1127     const std::string kTruncationEllipsis("\xE2\x80\xA6");
1128     SkScalar sk_ellipse_width = paint.measureText(
1129         kTruncationEllipsis.c_str(), kTruncationEllipsis.size());
1130
1131     // Then calculate how much of the text can be drawn with the '...' appended
1132     // to the end of the string.
1133     SkScalar sk_max_original_text_width(
1134         canvas_size.width() - (kMinPadding * 2) - sk_ellipse_width);
1135     size_t sk_max_original_text_length = paint.breakText(
1136         remote_playback_message.c_str(),
1137         remote_playback_message.size(),
1138         sk_max_original_text_width);
1139
1140     // Remove the part of the string that doesn't fit and append '...'.
1141     display_text.erase(sk_max_original_text_length,
1142         remote_playback_message.size() - sk_max_original_text_length);
1143     display_text.append(kTruncationEllipsis);
1144     display_text_width = paint.measureText(
1145         display_text.c_str(), display_text.size());
1146   }
1147
1148   // Center the text horizontally.
1149   SkScalar sk_horizontal_margin =
1150       (canvas_size.width() - display_text_width) / 2.0;
1151   canvas.drawText(display_text.c_str(),
1152       display_text.size(),
1153       sk_horizontal_margin,
1154       sk_vertical_margin,
1155       paint);
1156
1157   GLES2Interface* gl = stream_texture_factory_->ContextGL();
1158   GLuint remote_playback_texture_id = 0;
1159   gl->GenTextures(1, &remote_playback_texture_id);
1160   GLuint texture_target = GL_TEXTURE_2D;
1161   gl->BindTexture(texture_target, remote_playback_texture_id);
1162   gl->TexParameteri(texture_target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1163   gl->TexParameteri(texture_target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1164   gl->TexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1165   gl->TexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1166
1167   {
1168     SkAutoLockPixels lock(bitmap);
1169     gl->TexImage2D(texture_target,
1170                    0 /* level */,
1171                    GL_RGBA /* internalformat */,
1172                    bitmap.width(),
1173                    bitmap.height(),
1174                    0 /* border */,
1175                    GL_RGBA /* format */,
1176                    GL_UNSIGNED_BYTE /* type */,
1177                    bitmap.getPixels());
1178   }
1179
1180   gpu::Mailbox texture_mailbox;
1181   gl->GenMailboxCHROMIUM(texture_mailbox.name);
1182   gl->ProduceTextureCHROMIUM(texture_target, texture_mailbox.name);
1183   gl->Flush();
1184   GLuint texture_mailbox_sync_point = gl->InsertSyncPointCHROMIUM();
1185
1186   scoped_refptr<VideoFrame> new_frame = VideoFrame::WrapNativeTexture(
1187       make_scoped_ptr(new gpu::MailboxHolder(
1188           texture_mailbox, texture_target, texture_mailbox_sync_point)),
1189       media::BindToCurrentLoop(base::Bind(&OnReleaseTexture,
1190                                           stream_texture_factory_,
1191                                           remote_playback_texture_id)),
1192       canvas_size /* coded_size */,
1193       gfx::Rect(canvas_size) /* visible_rect */,
1194       canvas_size /* natural_size */,
1195       base::TimeDelta() /* timestamp */,
1196       VideoFrame::ReadPixelsCB());
1197   SetCurrentFrameInternal(new_frame);
1198 }
1199
1200 void WebMediaPlayerAndroid::ReallocateVideoFrame() {
1201   DCHECK(main_thread_checker_.CalledOnValidThread());
1202   if (needs_external_surface_) {
1203     // VideoFrame::CreateHoleFrame is only defined under VIDEO_HOLE.
1204 #if defined(VIDEO_HOLE)
1205     if (!natural_size_.isEmpty()) {
1206       scoped_refptr<VideoFrame> new_frame =
1207           VideoFrame::CreateHoleFrame(natural_size_);
1208       SetCurrentFrameInternal(new_frame);
1209       // Force the client to grab the hole frame.
1210       client_->repaint();
1211     }
1212 #else
1213     NOTIMPLEMENTED() << "Hole punching not supported without VIDEO_HOLE flag";
1214 #endif  // defined(VIDEO_HOLE)
1215   } else if (!is_remote_ && texture_id_) {
1216     GLES2Interface* gl = stream_texture_factory_->ContextGL();
1217     GLuint texture_target = kGLTextureExternalOES;
1218     GLuint texture_id_ref = gl->CreateAndConsumeTextureCHROMIUM(
1219         texture_target, texture_mailbox_.name);
1220     gl->Flush();
1221     GLuint texture_mailbox_sync_point = gl->InsertSyncPointCHROMIUM();
1222
1223     scoped_refptr<VideoFrame> new_frame = VideoFrame::WrapNativeTexture(
1224         make_scoped_ptr(new gpu::MailboxHolder(
1225             texture_mailbox_, texture_target, texture_mailbox_sync_point)),
1226         media::BindToCurrentLoop(base::Bind(
1227             &OnReleaseTexture, stream_texture_factory_, texture_id_ref)),
1228         natural_size_,
1229         gfx::Rect(natural_size_),
1230         natural_size_,
1231         base::TimeDelta(),
1232         VideoFrame::ReadPixelsCB());
1233     SetCurrentFrameInternal(new_frame);
1234   }
1235 }
1236
1237 void WebMediaPlayerAndroid::SetVideoFrameProviderClient(
1238     cc::VideoFrameProvider::Client* client) {
1239   // This is called from both the main renderer thread and the compositor
1240   // thread (when the main thread is blocked).
1241
1242   // Set the callback target when a frame is produced. Need to do this before
1243   // StopUsingProvider to ensure we really stop using the client.
1244   if (stream_texture_proxy_)
1245     stream_texture_proxy_->BindToLoop(stream_id_, client, compositor_loop_);
1246
1247   if (video_frame_provider_client_ && video_frame_provider_client_ != client)
1248     video_frame_provider_client_->StopUsingProvider();
1249   video_frame_provider_client_ = client;
1250 }
1251
1252 void WebMediaPlayerAndroid::SetCurrentFrameInternal(
1253     scoped_refptr<media::VideoFrame>& video_frame) {
1254   DCHECK(main_thread_checker_.CalledOnValidThread());
1255   base::AutoLock auto_lock(current_frame_lock_);
1256   current_frame_ = video_frame;
1257 }
1258
1259 scoped_refptr<media::VideoFrame> WebMediaPlayerAndroid::GetCurrentFrame() {
1260   scoped_refptr<VideoFrame> video_frame;
1261   {
1262     base::AutoLock auto_lock(current_frame_lock_);
1263     video_frame = current_frame_;
1264   }
1265
1266   return video_frame;
1267 }
1268
1269 void WebMediaPlayerAndroid::PutCurrentFrame(
1270     const scoped_refptr<media::VideoFrame>& frame) {
1271 }
1272
1273 void WebMediaPlayerAndroid::ResetStreamTextureProxy() {
1274   DCHECK(main_thread_checker_.CalledOnValidThread());
1275
1276   if (stream_id_) {
1277     GLES2Interface* gl = stream_texture_factory_->ContextGL();
1278     gl->DeleteTextures(1, &texture_id_);
1279     texture_id_ = 0;
1280     texture_mailbox_ = gpu::Mailbox();
1281     stream_id_ = 0;
1282   }
1283   stream_texture_proxy_.reset();
1284   needs_establish_peer_ = !needs_external_surface_ && !is_remote_ &&
1285                           !player_manager_->IsInFullscreen(frame_) &&
1286                           (hasVideo() || IsHLSStream());
1287
1288   TryCreateStreamTextureProxyIfNeeded();
1289   if (needs_establish_peer_ && is_playing_)
1290     EstablishSurfaceTexturePeer();
1291 }
1292
1293 void WebMediaPlayerAndroid::TryCreateStreamTextureProxyIfNeeded() {
1294   DCHECK(main_thread_checker_.CalledOnValidThread());
1295   // Already created.
1296   if (stream_texture_proxy_)
1297     return;
1298
1299   // No factory to create proxy.
1300   if (!stream_texture_factory_.get())
1301     return;
1302
1303   // Not needed for hole punching.
1304   if (!needs_establish_peer_)
1305     return;
1306
1307   stream_texture_proxy_.reset(stream_texture_factory_->CreateProxy());
1308   if (stream_texture_proxy_) {
1309     DoCreateStreamTexture();
1310     ReallocateVideoFrame();
1311     if (video_frame_provider_client_) {
1312       stream_texture_proxy_->BindToLoop(
1313           stream_id_, video_frame_provider_client_, compositor_loop_);
1314     }
1315   }
1316 }
1317
1318 void WebMediaPlayerAndroid::EstablishSurfaceTexturePeer() {
1319   DCHECK(main_thread_checker_.CalledOnValidThread());
1320   if (!stream_texture_proxy_)
1321     return;
1322
1323   if (stream_texture_factory_.get() && stream_id_)
1324     stream_texture_factory_->EstablishPeer(stream_id_, player_id_);
1325
1326   // Set the deferred size because the size was changed in remote mode.
1327   if (!is_remote_ && cached_stream_texture_size_ != natural_size_) {
1328     stream_texture_factory_->SetStreamTextureSize(
1329         stream_id_, gfx::Size(natural_size_.width, natural_size_.height));
1330     cached_stream_texture_size_ = natural_size_;
1331   }
1332
1333   needs_establish_peer_ = false;
1334 }
1335
1336 void WebMediaPlayerAndroid::DoCreateStreamTexture() {
1337   DCHECK(main_thread_checker_.CalledOnValidThread());
1338   DCHECK(!stream_id_);
1339   DCHECK(!texture_id_);
1340   stream_id_ = stream_texture_factory_->CreateStreamTexture(
1341       kGLTextureExternalOES, &texture_id_, &texture_mailbox_);
1342 }
1343
1344 void WebMediaPlayerAndroid::SetNeedsEstablishPeer(bool needs_establish_peer) {
1345   needs_establish_peer_ = needs_establish_peer;
1346 }
1347
1348 void WebMediaPlayerAndroid::setPoster(const blink::WebURL& poster) {
1349   player_manager_->SetPoster(player_id_, poster);
1350 }
1351
1352 void WebMediaPlayerAndroid::UpdatePlayingState(bool is_playing) {
1353   if (is_playing == is_playing_)
1354     return;
1355
1356   is_playing_ = is_playing;
1357
1358   if (is_playing)
1359     interpolator_.StartInterpolating();
1360   else
1361     interpolator_.StopInterpolating();
1362
1363   if (delegate_) {
1364     if (is_playing)
1365       delegate_->DidPlay(this);
1366     else
1367       delegate_->DidPause(this);
1368   }
1369 }
1370
1371 #if defined(VIDEO_HOLE)
1372 bool WebMediaPlayerAndroid::UpdateBoundaryRectangle() {
1373   if (!video_weblayer_)
1374     return false;
1375
1376   // Compute the geometry of video frame layer.
1377   cc::Layer* layer = video_weblayer_->layer();
1378   gfx::RectF rect(layer->bounds());
1379   while (layer) {
1380     rect.Offset(layer->position().OffsetFromOrigin());
1381     layer = layer->parent();
1382   }
1383
1384   // Return false when the geometry hasn't been changed from the last time.
1385   if (last_computed_rect_ == rect)
1386     return false;
1387
1388   // Store the changed geometry information when it is actually changed.
1389   last_computed_rect_ = rect;
1390   return true;
1391 }
1392
1393 const gfx::RectF WebMediaPlayerAndroid::GetBoundaryRectangle() {
1394   return last_computed_rect_;
1395 }
1396 #endif
1397
1398 // The following EME related code is copied from WebMediaPlayerImpl.
1399 // TODO(xhwang): Remove duplicate code between WebMediaPlayerAndroid and
1400 // WebMediaPlayerImpl.
1401
1402 // Convert a WebString to ASCII, falling back on an empty string in the case
1403 // of a non-ASCII string.
1404 static std::string ToASCIIOrEmpty(const blink::WebString& string) {
1405   return base::IsStringASCII(string) ? base::UTF16ToASCII(string)
1406                                      : std::string();
1407 }
1408
1409 // Helper functions to report media EME related stats to UMA. They follow the
1410 // convention of more commonly used macros UMA_HISTOGRAM_ENUMERATION and
1411 // UMA_HISTOGRAM_COUNTS. The reason that we cannot use those macros directly is
1412 // that UMA_* macros require the names to be constant throughout the process'
1413 // lifetime.
1414
1415 static void EmeUMAHistogramEnumeration(const std::string& key_system,
1416                                        const std::string& method,
1417                                        int sample,
1418                                        int boundary_value) {
1419   base::LinearHistogram::FactoryGet(
1420       kMediaEme + KeySystemNameForUMA(key_system) + "." + method,
1421       1, boundary_value, boundary_value + 1,
1422       base::Histogram::kUmaTargetedHistogramFlag)->Add(sample);
1423 }
1424
1425 static void EmeUMAHistogramCounts(const std::string& key_system,
1426                                   const std::string& method,
1427                                   int sample) {
1428   // Use the same parameters as UMA_HISTOGRAM_COUNTS.
1429   base::Histogram::FactoryGet(
1430       kMediaEme + KeySystemNameForUMA(key_system) + "." + method,
1431       1, 1000000, 50, base::Histogram::kUmaTargetedHistogramFlag)->Add(sample);
1432 }
1433
1434 // Helper enum for reporting generateKeyRequest/addKey histograms.
1435 enum MediaKeyException {
1436   kUnknownResultId,
1437   kSuccess,
1438   kKeySystemNotSupported,
1439   kInvalidPlayerState,
1440   kMaxMediaKeyException
1441 };
1442
1443 static MediaKeyException MediaKeyExceptionForUMA(
1444     WebMediaPlayer::MediaKeyException e) {
1445   switch (e) {
1446     case WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported:
1447       return kKeySystemNotSupported;
1448     case WebMediaPlayer::MediaKeyExceptionInvalidPlayerState:
1449       return kInvalidPlayerState;
1450     case WebMediaPlayer::MediaKeyExceptionNoError:
1451       return kSuccess;
1452     default:
1453       return kUnknownResultId;
1454   }
1455 }
1456
1457 // Helper for converting |key_system| name and exception |e| to a pair of enum
1458 // values from above, for reporting to UMA.
1459 static void ReportMediaKeyExceptionToUMA(const std::string& method,
1460                                          const std::string& key_system,
1461                                          WebMediaPlayer::MediaKeyException e) {
1462   MediaKeyException result_id = MediaKeyExceptionForUMA(e);
1463   DCHECK_NE(result_id, kUnknownResultId) << e;
1464   EmeUMAHistogramEnumeration(
1465       key_system, method, result_id, kMaxMediaKeyException);
1466 }
1467
1468 bool WebMediaPlayerAndroid::IsKeySystemSupported(
1469     const std::string& key_system) {
1470   // On Android, EME only works with MSE.
1471   return player_type_ == MEDIA_PLAYER_TYPE_MEDIA_SOURCE &&
1472          IsConcreteSupportedKeySystem(key_system);
1473 }
1474
1475 WebMediaPlayer::MediaKeyException WebMediaPlayerAndroid::generateKeyRequest(
1476     const WebString& key_system,
1477     const unsigned char* init_data,
1478     unsigned init_data_length) {
1479   DVLOG(1) << "generateKeyRequest: " << base::string16(key_system) << ": "
1480            << std::string(reinterpret_cast<const char*>(init_data),
1481                           static_cast<size_t>(init_data_length));
1482
1483   std::string ascii_key_system =
1484       GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
1485
1486   WebMediaPlayer::MediaKeyException e =
1487       GenerateKeyRequestInternal(ascii_key_system, init_data, init_data_length);
1488   ReportMediaKeyExceptionToUMA("generateKeyRequest", ascii_key_system, e);
1489   return e;
1490 }
1491
1492 // Guess the type of |init_data|. This is only used to handle some corner cases
1493 // so we keep it as simple as possible without breaking major use cases.
1494 static std::string GuessInitDataType(const unsigned char* init_data,
1495                                      unsigned init_data_length) {
1496   // Most WebM files use KeyId of 16 bytes. CENC init data is always >16 bytes.
1497   if (init_data_length == 16)
1498     return "webm";
1499
1500   return "cenc";
1501 }
1502
1503 // TODO(xhwang): Report an error when there is encrypted stream but EME is
1504 // not enabled. Currently the player just doesn't start and waits for
1505 // ever.
1506 WebMediaPlayer::MediaKeyException
1507 WebMediaPlayerAndroid::GenerateKeyRequestInternal(
1508     const std::string& key_system,
1509     const unsigned char* init_data,
1510     unsigned init_data_length) {
1511   if (!IsKeySystemSupported(key_system))
1512     return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
1513
1514   // We do not support run-time switching between key systems for now.
1515   if (current_key_system_.empty()) {
1516     if (!proxy_decryptor_) {
1517       proxy_decryptor_.reset(new ProxyDecryptor(
1518           base::Bind(&WebMediaPlayerAndroid::OnKeyAdded,
1519                      weak_factory_.GetWeakPtr()),
1520           base::Bind(&WebMediaPlayerAndroid::OnKeyError,
1521                      weak_factory_.GetWeakPtr()),
1522           base::Bind(&WebMediaPlayerAndroid::OnKeyMessage,
1523                      weak_factory_.GetWeakPtr())));
1524     }
1525
1526     GURL security_origin(frame_->document().securityOrigin().toString());
1527     RenderCdmFactory cdm_factory(cdm_manager_);
1528     if (!proxy_decryptor_->InitializeCDM(&cdm_factory, key_system,
1529                                          security_origin)) {
1530       return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
1531     }
1532
1533     if (!decryptor_ready_cb_.is_null()) {
1534       base::ResetAndReturn(&decryptor_ready_cb_)
1535           .Run(proxy_decryptor_->GetDecryptor(), base::Bind(DoNothing));
1536     }
1537
1538     // Only browser CDMs have CDM ID. Render side CDMs (e.g. ClearKey CDM) do
1539     // not have a CDM ID and there is no need to call player_manager_->SetCdm().
1540     if (proxy_decryptor_->GetCdmId() != media::MediaKeys::kInvalidCdmId)
1541       player_manager_->SetCdm(player_id_, proxy_decryptor_->GetCdmId());
1542
1543     current_key_system_ = key_system;
1544   } else if (key_system != current_key_system_) {
1545     return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
1546   }
1547
1548   std::string init_data_type = init_data_type_;
1549   if (init_data_type.empty())
1550     init_data_type = GuessInitDataType(init_data, init_data_length);
1551
1552   // TODO(xhwang): We assume all streams are from the same container (thus have
1553   // the same "type") for now. In the future, the "type" should be passed down
1554   // from the application.
1555   if (!proxy_decryptor_->GenerateKeyRequest(
1556            init_data_type, init_data, init_data_length)) {
1557     current_key_system_.clear();
1558     return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
1559   }
1560
1561   return WebMediaPlayer::MediaKeyExceptionNoError;
1562 }
1563
1564 WebMediaPlayer::MediaKeyException WebMediaPlayerAndroid::addKey(
1565     const WebString& key_system,
1566     const unsigned char* key,
1567     unsigned key_length,
1568     const unsigned char* init_data,
1569     unsigned init_data_length,
1570     const WebString& session_id) {
1571   DVLOG(1) << "addKey: " << base::string16(key_system) << ": "
1572            << std::string(reinterpret_cast<const char*>(key),
1573                           static_cast<size_t>(key_length)) << ", "
1574            << std::string(reinterpret_cast<const char*>(init_data),
1575                           static_cast<size_t>(init_data_length)) << " ["
1576            << base::string16(session_id) << "]";
1577
1578   std::string ascii_key_system =
1579       GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
1580   std::string ascii_session_id = ToASCIIOrEmpty(session_id);
1581
1582   WebMediaPlayer::MediaKeyException e = AddKeyInternal(ascii_key_system,
1583                                                        key,
1584                                                        key_length,
1585                                                        init_data,
1586                                                        init_data_length,
1587                                                        ascii_session_id);
1588   ReportMediaKeyExceptionToUMA("addKey", ascii_key_system, e);
1589   return e;
1590 }
1591
1592 WebMediaPlayer::MediaKeyException WebMediaPlayerAndroid::AddKeyInternal(
1593     const std::string& key_system,
1594     const unsigned char* key,
1595     unsigned key_length,
1596     const unsigned char* init_data,
1597     unsigned init_data_length,
1598     const std::string& session_id) {
1599   DCHECK(key);
1600   DCHECK_GT(key_length, 0u);
1601
1602   if (!IsKeySystemSupported(key_system))
1603     return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
1604
1605   if (current_key_system_.empty() || key_system != current_key_system_)
1606     return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
1607
1608   proxy_decryptor_->AddKey(
1609       key, key_length, init_data, init_data_length, session_id);
1610   return WebMediaPlayer::MediaKeyExceptionNoError;
1611 }
1612
1613 WebMediaPlayer::MediaKeyException WebMediaPlayerAndroid::cancelKeyRequest(
1614     const WebString& key_system,
1615     const WebString& session_id) {
1616   DVLOG(1) << "cancelKeyRequest: " << base::string16(key_system) << ": "
1617            << " [" << base::string16(session_id) << "]";
1618
1619   std::string ascii_key_system =
1620       GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
1621   std::string ascii_session_id = ToASCIIOrEmpty(session_id);
1622
1623   WebMediaPlayer::MediaKeyException e =
1624       CancelKeyRequestInternal(ascii_key_system, ascii_session_id);
1625   ReportMediaKeyExceptionToUMA("cancelKeyRequest", ascii_key_system, e);
1626   return e;
1627 }
1628
1629 WebMediaPlayer::MediaKeyException
1630 WebMediaPlayerAndroid::CancelKeyRequestInternal(const std::string& key_system,
1631                                                 const std::string& session_id) {
1632   if (!IsKeySystemSupported(key_system))
1633     return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
1634
1635   if (current_key_system_.empty() || key_system != current_key_system_)
1636     return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
1637
1638   proxy_decryptor_->CancelKeyRequest(session_id);
1639   return WebMediaPlayer::MediaKeyExceptionNoError;
1640 }
1641
1642 void WebMediaPlayerAndroid::setContentDecryptionModule(
1643     blink::WebContentDecryptionModule* cdm) {
1644   DCHECK(main_thread_checker_.CalledOnValidThread());
1645
1646   // TODO(xhwang): Support setMediaKeys(0) if necessary: http://crbug.com/330324
1647   if (!cdm)
1648     return;
1649
1650   web_cdm_ = ToWebContentDecryptionModuleImpl(cdm);
1651   if (!web_cdm_)
1652     return;
1653
1654   if (!decryptor_ready_cb_.is_null()) {
1655     base::ResetAndReturn(&decryptor_ready_cb_)
1656         .Run(web_cdm_->GetDecryptor(), base::Bind(DoNothing));
1657   }
1658
1659   if (web_cdm_->GetCdmId() != media::MediaKeys::kInvalidCdmId)
1660     player_manager_->SetCdm(player_id_, web_cdm_->GetCdmId());
1661 }
1662
1663 void WebMediaPlayerAndroid::setContentDecryptionModule(
1664     blink::WebContentDecryptionModule* cdm,
1665     blink::WebContentDecryptionModuleResult result) {
1666   DCHECK(main_thread_checker_.CalledOnValidThread());
1667
1668   // TODO(xhwang): Support setMediaKeys(0) if necessary: http://crbug.com/330324
1669   if (!cdm) {
1670     result.completeWithError(
1671         blink::WebContentDecryptionModuleExceptionNotSupportedError,
1672         0,
1673         "Null MediaKeys object is not supported.");
1674     return;
1675   }
1676
1677   web_cdm_ = ToWebContentDecryptionModuleImpl(cdm);
1678   DCHECK(web_cdm_);
1679
1680   if (!decryptor_ready_cb_.is_null()) {
1681     base::ResetAndReturn(&decryptor_ready_cb_).Run(
1682         web_cdm_->GetDecryptor(),
1683         media::BindToCurrentLoop(
1684             base::Bind(&WebMediaPlayerAndroid::ContentDecryptionModuleAttached,
1685                        weak_factory_.GetWeakPtr(),
1686                        result)));
1687   } else {
1688     // No pipeline/decoder connected, so resolve the promise. When something
1689     // is connected, setting the CDM will happen in SetDecryptorReadyCB().
1690     ContentDecryptionModuleAttached(result, true);
1691   }
1692
1693   if (web_cdm_->GetCdmId() != media::MediaKeys::kInvalidCdmId)
1694     player_manager_->SetCdm(player_id_, web_cdm_->GetCdmId());
1695 }
1696
1697 void WebMediaPlayerAndroid::ContentDecryptionModuleAttached(
1698     blink::WebContentDecryptionModuleResult result,
1699     bool success) {
1700   if (success) {
1701     result.complete();
1702     return;
1703   }
1704
1705   result.completeWithError(
1706       blink::WebContentDecryptionModuleExceptionNotSupportedError,
1707       0,
1708       "Unable to set MediaKeys object");
1709 }
1710
1711 void WebMediaPlayerAndroid::OnKeyAdded(const std::string& session_id) {
1712   EmeUMAHistogramCounts(current_key_system_, "KeyAdded", 1);
1713
1714   client_->keyAdded(
1715       WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
1716       WebString::fromUTF8(session_id));
1717 }
1718
1719 void WebMediaPlayerAndroid::OnKeyError(const std::string& session_id,
1720                                        media::MediaKeys::KeyError error_code,
1721                                        uint32 system_code) {
1722   EmeUMAHistogramEnumeration(current_key_system_, "KeyError",
1723                              error_code, media::MediaKeys::kMaxKeyError);
1724
1725   unsigned short short_system_code = 0;
1726   if (system_code > std::numeric_limits<unsigned short>::max()) {
1727     LOG(WARNING) << "system_code exceeds unsigned short limit.";
1728     short_system_code = std::numeric_limits<unsigned short>::max();
1729   } else {
1730     short_system_code = static_cast<unsigned short>(system_code);
1731   }
1732
1733   client_->keyError(
1734       WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
1735       WebString::fromUTF8(session_id),
1736       static_cast<blink::WebMediaPlayerClient::MediaKeyErrorCode>(error_code),
1737       short_system_code);
1738 }
1739
1740 void WebMediaPlayerAndroid::OnKeyMessage(const std::string& session_id,
1741                                          const std::vector<uint8>& message,
1742                                          const GURL& destination_url) {
1743   DCHECK(destination_url.is_empty() || destination_url.is_valid());
1744
1745   client_->keyMessage(
1746       WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
1747       WebString::fromUTF8(session_id),
1748       message.empty() ? NULL : &message[0],
1749       message.size(),
1750       destination_url);
1751 }
1752
1753 void WebMediaPlayerAndroid::OnMediaSourceOpened(
1754     blink::WebMediaSource* web_media_source) {
1755   client_->mediaSourceOpened(web_media_source);
1756 }
1757
1758 void WebMediaPlayerAndroid::OnNeedKey(const std::string& type,
1759                                       const std::vector<uint8>& init_data) {
1760   DCHECK(main_thread_checker_.CalledOnValidThread());
1761
1762   // Do not fire NeedKey event if encrypted media is not enabled.
1763   if (!blink::WebRuntimeFeatures::isPrefixedEncryptedMediaEnabled() &&
1764       !blink::WebRuntimeFeatures::isEncryptedMediaEnabled()) {
1765     return;
1766   }
1767
1768   UMA_HISTOGRAM_COUNTS(kMediaEme + std::string("NeedKey"), 1);
1769
1770   DCHECK(init_data_type_.empty() || type.empty() || type == init_data_type_);
1771   if (init_data_type_.empty())
1772     init_data_type_ = type;
1773
1774   const uint8* init_data_ptr = init_data.empty() ? NULL : &init_data[0];
1775   client_->encrypted(
1776       WebString::fromUTF8(type), init_data_ptr, init_data.size());
1777 }
1778
1779 void WebMediaPlayerAndroid::SetDecryptorReadyCB(
1780     const media::DecryptorReadyCB& decryptor_ready_cb) {
1781   DCHECK(main_thread_checker_.CalledOnValidThread());
1782
1783   // Cancels the previous decryptor request.
1784   if (decryptor_ready_cb.is_null()) {
1785     if (!decryptor_ready_cb_.is_null()) {
1786       base::ResetAndReturn(&decryptor_ready_cb_)
1787           .Run(NULL, base::Bind(DoNothing));
1788     }
1789     return;
1790   }
1791
1792   // TODO(xhwang): Support multiple decryptor notification request (e.g. from
1793   // video and audio). The current implementation is okay for the current
1794   // media pipeline since we initialize audio and video decoders in sequence.
1795   // But WebMediaPlayerImpl should not depend on media pipeline's implementation
1796   // detail.
1797   DCHECK(decryptor_ready_cb_.is_null());
1798
1799   // Mixed use of prefixed and unprefixed EME APIs is disallowed by Blink.
1800   DCHECK(!proxy_decryptor_ || !web_cdm_);
1801
1802   if (proxy_decryptor_) {
1803     decryptor_ready_cb.Run(proxy_decryptor_->GetDecryptor(),
1804                            base::Bind(DoNothing));
1805     return;
1806   }
1807
1808   if (web_cdm_) {
1809     decryptor_ready_cb.Run(web_cdm_->GetDecryptor(), base::Bind(DoNothing));
1810     return;
1811   }
1812
1813   decryptor_ready_cb_ = decryptor_ready_cb;
1814 }
1815
1816 void WebMediaPlayerAndroid::enterFullscreen() {
1817   if (player_manager_->CanEnterFullscreen(frame_)) {
1818     player_manager_->EnterFullscreen(player_id_, frame_);
1819     SetNeedsEstablishPeer(false);
1820   }
1821 }
1822
1823 bool WebMediaPlayerAndroid::canEnterFullscreen() const {
1824   return player_manager_->CanEnterFullscreen(frame_);
1825 }
1826
1827 bool WebMediaPlayerAndroid::IsHLSStream() const {
1828   std::string mime;
1829   GURL url = redirected_url_.is_empty() ? url_ : redirected_url_;
1830   if (!net::GetMimeTypeFromFile(base::FilePath(url.path()), &mime))
1831     return false;
1832   return !mime.compare("application/x-mpegurl");
1833 }
1834
1835 }  // namespace content