Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / content / renderer / media / android / webmediaplayer_android.h
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 #ifndef CONTENT_RENDERER_MEDIA_ANDROID_WEBMEDIAPLAYER_ANDROID_H_
6 #define CONTENT_RENDERER_MEDIA_ANDROID_WEBMEDIAPLAYER_ANDROID_H_
7
8 #include <jni.h>
9 #include <string>
10 #include <vector>
11
12 #include "base/basictypes.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/threading/thread_checker.h"
17 #include "base/time/default_tick_clock.h"
18 #include "base/time/time.h"
19 #include "cc/layers/video_frame_provider.h"
20 #include "content/common/media/media_player_messages_enums_android.h"
21 #include "content/public/renderer/render_frame_observer.h"
22 #include "content/renderer/media/android/media_info_loader.h"
23 #include "content/renderer/media/android/media_source_delegate.h"
24 #include "content/renderer/media/android/stream_texture_factory.h"
25 #include "content/renderer/media/crypto/proxy_decryptor.h"
26 #include "gpu/command_buffer/common/mailbox.h"
27 #include "media/base/android/media_player_android.h"
28 #include "media/base/demuxer_stream.h"
29 #include "media/base/media_keys.h"
30 #include "media/base/time_delta_interpolator.h"
31 #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
32 #include "third_party/WebKit/public/platform/WebMediaPlayer.h"
33 #include "third_party/WebKit/public/platform/WebSize.h"
34 #include "third_party/WebKit/public/platform/WebURL.h"
35 #include "third_party/skia/include/core/SkBitmap.h"
36 #include "third_party/skia/include/gpu/GrContext.h"
37 #include "third_party/skia/include/gpu/SkGrPixelRef.h"
38 #include "ui/gfx/rect_f.h"
39
40 namespace base {
41 class SingleThreadTaskRunner;
42 }
43
44 namespace blink {
45 class WebContentDecryptionModule;
46 class WebContentDecryptionModuleResult;
47 class WebFrame;
48 class WebURL;
49 }
50
51 namespace cc_blink {
52 class WebLayerImpl;
53 }
54
55 namespace gpu {
56 struct MailboxHolder;
57 }
58
59 namespace media {
60 class MediaLog;
61 class WebMediaPlayerDelegate;
62 }
63
64 namespace content {
65 class RendererCdmManager;
66 class RendererMediaPlayerManager;
67 class WebContentDecryptionModuleImpl;
68
69 // This class implements blink::WebMediaPlayer by keeping the android
70 // media player in the browser process. It listens to all the status changes
71 // sent from the browser process and sends playback controls to the media
72 // player.
73 class WebMediaPlayerAndroid : public blink::WebMediaPlayer,
74                               public cc::VideoFrameProvider,
75                               public RenderFrameObserver,
76                               public StreamTextureFactoryContextObserver {
77  public:
78   // Construct a WebMediaPlayerAndroid object. This class communicates with the
79   // MediaPlayerAndroid object in the browser process through |proxy|.
80   // TODO(qinmin): |frame| argument is used to determine whether the current
81   // player can enter fullscreen. This logic should probably be moved into
82   // blink, so that enterFullscreen() will not be called if another video is
83   // already in fullscreen.
84   WebMediaPlayerAndroid(
85       blink::WebFrame* frame,
86       blink::WebMediaPlayerClient* client,
87       base::WeakPtr<media::WebMediaPlayerDelegate> delegate,
88       RendererMediaPlayerManager* player_manager,
89       RendererCdmManager* cdm_manager,
90       blink::WebContentDecryptionModule* initial_cdm,
91       scoped_refptr<StreamTextureFactory> factory,
92       const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
93       media::MediaLog* media_log);
94   virtual ~WebMediaPlayerAndroid();
95
96   // blink::WebMediaPlayer implementation.
97   virtual void enterFullscreen();
98   virtual bool canEnterFullscreen() const;
99
100   // Resource loading.
101   virtual void load(LoadType load_type,
102                     const blink::WebURL& url,
103                     CORSMode cors_mode);
104
105   // Playback controls.
106   virtual void play();
107   virtual void pause();
108   virtual void seek(double seconds);
109   virtual bool supportsSave() const;
110   virtual void setRate(double rate);
111   virtual void setVolume(double volume);
112   virtual void requestRemotePlayback();
113   virtual void requestRemotePlaybackControl();
114   virtual blink::WebTimeRanges buffered() const;
115   virtual double maxTimeSeekable() const;
116
117   // Poster image, as defined in the <video> element.
118   virtual void setPoster(const blink::WebURL& poster) OVERRIDE;
119
120   // Methods for painting.
121   // FIXME: This path "only works" on Android. It is a workaround for the
122   // issue that Skia could not handle Android's GL_TEXTURE_EXTERNAL_OES texture
123   // internally. It should be removed and replaced by the normal paint path.
124   // https://code.google.com/p/skia/issues/detail?id=1189
125   virtual void paint(blink::WebCanvas* canvas,
126                      const blink::WebRect& rect,
127                      unsigned char alpha,
128                      SkXfermode::Mode mode);
129   // TODO(dshwang): remove it because above method replaces. crbug.com/401027
130   virtual void paint(blink::WebCanvas* canvas,
131                      const blink::WebRect& rect,
132                      unsigned char alpha);
133
134   virtual bool copyVideoTextureToPlatformTexture(
135       blink::WebGraphicsContext3D* web_graphics_context,
136       unsigned int texture,
137       unsigned int level,
138       unsigned int internal_format,
139       unsigned int type,
140       bool premultiply_alpha,
141       bool flip_y);
142
143   // True if the loaded media has a playable video/audio track.
144   virtual bool hasVideo() const;
145   virtual bool hasAudio() const;
146
147   // Dimensions of the video.
148   virtual blink::WebSize naturalSize() const;
149
150   // Getters of playback state.
151   virtual bool paused() const;
152   virtual bool seeking() const;
153   virtual double duration() const;
154   virtual double timelineOffset() const;
155   virtual double currentTime() const;
156
157   virtual bool didLoadingProgress();
158
159   // Internal states of loading and network.
160   virtual blink::WebMediaPlayer::NetworkState networkState() const;
161   virtual blink::WebMediaPlayer::ReadyState readyState() const;
162
163   virtual bool hasSingleSecurityOrigin() const;
164   virtual bool didPassCORSAccessCheck() const;
165
166   virtual double mediaTimeForTimeValue(double timeValue) const;
167
168   // Provide statistics.
169   virtual unsigned decodedFrameCount() const;
170   virtual unsigned droppedFrameCount() const;
171   virtual unsigned audioDecodedByteCount() const;
172   virtual unsigned videoDecodedByteCount() const;
173
174   // cc::VideoFrameProvider implementation. These methods are running on the
175   // compositor thread.
176   virtual void SetVideoFrameProviderClient(
177       cc::VideoFrameProvider::Client* client) OVERRIDE;
178   virtual scoped_refptr<media::VideoFrame> GetCurrentFrame() OVERRIDE;
179   virtual void PutCurrentFrame(const scoped_refptr<media::VideoFrame>& frame)
180       OVERRIDE;
181
182   // Media player callback handlers.
183   void OnMediaMetadataChanged(const base::TimeDelta& duration, int width,
184                               int height, bool success);
185   void OnPlaybackComplete();
186   void OnBufferingUpdate(int percentage);
187   void OnSeekRequest(const base::TimeDelta& time_to_seek);
188   void OnSeekComplete(const base::TimeDelta& current_time);
189   void OnMediaError(int error_type);
190   void OnVideoSizeChanged(int width, int height);
191   void OnDurationChanged(const base::TimeDelta& duration);
192
193   // Called to update the current time.
194   void OnTimeUpdate(base::TimeDelta current_timestamp,
195                     base::TimeTicks current_time_ticks);
196
197   // Functions called when media player status changes.
198   void OnConnectedToRemoteDevice(const std::string& remote_playback_message);
199   void OnDisconnectedFromRemoteDevice();
200   void OnDidEnterFullscreen();
201   void OnDidExitFullscreen();
202   void OnMediaPlayerPlay();
203   void OnMediaPlayerPause();
204   void OnRequestFullscreen();
205   void OnRemoteRouteAvailabilityChanged(bool routes_available);
206
207   // StreamTextureFactoryContextObserver implementation.
208   virtual void ResetStreamTextureProxy() OVERRIDE;
209
210   // Called when the player is released.
211   virtual void OnPlayerReleased();
212
213   // This function is called by the RendererMediaPlayerManager to pause the
214   // video and release the media player and surface texture when we switch tabs.
215   // However, the actual GlTexture is not released to keep the video screenshot.
216   virtual void ReleaseMediaResources();
217
218   // RenderFrameObserver implementation.
219   virtual void OnDestruct() OVERRIDE;
220
221 #if defined(VIDEO_HOLE)
222   // Calculate the boundary rectangle of the media player (i.e. location and
223   // size of the video frame).
224   // Returns true if the geometry has been changed since the last call.
225   bool UpdateBoundaryRectangle();
226
227   const gfx::RectF GetBoundaryRectangle();
228 #endif  // defined(VIDEO_HOLE)
229
230   virtual MediaKeyException generateKeyRequest(
231       const blink::WebString& key_system,
232       const unsigned char* init_data,
233       unsigned init_data_length);
234   virtual MediaKeyException addKey(
235       const blink::WebString& key_system,
236       const unsigned char* key,
237       unsigned key_length,
238       const unsigned char* init_data,
239       unsigned init_data_length,
240       const blink::WebString& session_id);
241   virtual MediaKeyException cancelKeyRequest(
242       const blink::WebString& key_system,
243       const blink::WebString& session_id);
244   // TODO(jrummell): Remove this method once Blink updated to use the other
245   // two methods.
246   virtual void setContentDecryptionModule(
247       blink::WebContentDecryptionModule* cdm);
248   virtual void setContentDecryptionModule(
249       blink::WebContentDecryptionModule* cdm,
250       blink::WebContentDecryptionModuleResult result);
251
252   void OnKeyAdded(const std::string& session_id);
253   void OnKeyError(const std::string& session_id,
254                   media::MediaKeys::KeyError error_code,
255                   uint32 system_code);
256   void OnKeyMessage(const std::string& session_id,
257                     const std::vector<uint8>& message,
258                     const GURL& destination_url);
259
260   void OnMediaSourceOpened(blink::WebMediaSource* web_media_source);
261
262   void OnNeedKey(const std::string& type,
263                  const std::vector<uint8>& init_data);
264
265   // TODO(xhwang): Implement WebMediaPlayer::setContentDecryptionModule().
266   // See: http://crbug.com/224786
267
268  protected:
269   // Helper method to update the playing state.
270   void UpdatePlayingState(bool is_playing_);
271
272   // Helper methods for posting task for setting states and update WebKit.
273   void UpdateNetworkState(blink::WebMediaPlayer::NetworkState state);
274   void UpdateReadyState(blink::WebMediaPlayer::ReadyState state);
275   void TryCreateStreamTextureProxyIfNeeded();
276   void DoCreateStreamTexture();
277
278   // Helper method to reestablish the surface texture peer for android
279   // media player.
280   void EstablishSurfaceTexturePeer();
281
282   // Requesting whether the surface texture peer needs to be reestablished.
283   void SetNeedsEstablishPeer(bool needs_establish_peer);
284
285  private:
286   void InitializePlayer(const GURL& url,
287                         const GURL& first_party_for_cookies,
288                         bool allowed_stored_credentials,
289                         int demuxer_client_id);
290   void Pause(bool is_media_related_action);
291   void DrawRemotePlaybackText(const std::string& remote_playback_message);
292   void ReallocateVideoFrame();
293   void SetCurrentFrameInternal(scoped_refptr<media::VideoFrame>& frame);
294   void DidLoadMediaInfo(MediaInfoLoader::Status status,
295                         const GURL& redirected_url,
296                         const GURL& first_party_for_cookies,
297                         bool allow_stored_credentials);
298   bool IsKeySystemSupported(const std::string& key_system);
299   bool IsLocalResource();
300
301   // Actually do the work for generateKeyRequest/addKey so they can easily
302   // report results to UMA.
303   MediaKeyException GenerateKeyRequestInternal(const std::string& key_system,
304                                                const unsigned char* init_data,
305                                                unsigned init_data_length);
306   MediaKeyException AddKeyInternal(const std::string& key_system,
307                                    const unsigned char* key,
308                                    unsigned key_length,
309                                    const unsigned char* init_data,
310                                    unsigned init_data_length,
311                                    const std::string& session_id);
312   MediaKeyException CancelKeyRequestInternal(const std::string& key_system,
313                                              const std::string& session_id);
314
315   // Requests that this object notifies when a decryptor is ready through the
316   // |decryptor_ready_cb| provided.
317   // If |decryptor_ready_cb| is null, the existing callback will be fired with
318   // NULL immediately and reset.
319   void SetDecryptorReadyCB(const media::DecryptorReadyCB& decryptor_ready_cb);
320
321   // Called when the ContentDecryptionModule has been attached to the
322   // pipeline/decoders.
323   void ContentDecryptionModuleAttached(
324       blink::WebContentDecryptionModuleResult result,
325       bool success);
326
327   bool EnsureTextureBackedSkBitmap(GrContext* gr, SkBitmap& bitmap,
328                                    const blink::WebSize& size,
329                                    GrSurfaceOrigin origin,
330                                    GrPixelConfig config);
331
332   bool IsHLSStream() const;
333
334   blink::WebFrame* const frame_;
335
336   blink::WebMediaPlayerClient* const client_;
337
338   // |delegate_| is used to notify the browser process of the player status, so
339   // that the browser process can control screen locks.
340   // TODO(qinmin): Currently android mediaplayer takes care of the screen
341   // lock. So this is only used for media source. Will apply this to regular
342   // media tag once http://crbug.com/247892 is fixed.
343   base::WeakPtr<media::WebMediaPlayerDelegate> delegate_;
344
345   // Save the list of buffered time ranges.
346   blink::WebTimeRanges buffered_;
347
348   // Size of the video.
349   blink::WebSize natural_size_;
350
351   // Size that has been sent to StreamTexture.
352   blink::WebSize cached_stream_texture_size_;
353
354   // The video frame object used for rendering by the compositor.
355   scoped_refptr<media::VideoFrame> current_frame_;
356   base::Lock current_frame_lock_;
357
358   base::ThreadChecker main_thread_checker_;
359
360   // Message loop for media thread.
361   const scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;
362
363   // URL of the media file to be fetched.
364   GURL url_;
365
366   // URL of the media file after |media_info_loader_| resolves all the
367   // redirections.
368   GURL redirected_url_;
369
370   // Media duration.
371   base::TimeDelta duration_;
372
373   // Flag to remember if we have a trusted duration_ value provided by
374   // MediaSourceDelegate notifying OnDurationChanged(). In this case, ignore
375   // any subsequent duration value passed to OnMediaMetadataChange().
376   bool ignore_metadata_duration_change_;
377
378   // Seek gets pending if another seek is in progress. Only last pending seek
379   // will have effect.
380   bool pending_seek_;
381   base::TimeDelta pending_seek_time_;
382
383   // Internal seek state.
384   bool seeking_;
385   base::TimeDelta seek_time_;
386
387   // Whether loading has progressed since the last call to didLoadingProgress.
388   bool did_loading_progress_;
389
390   // Manages this object and delegates player calls to the browser process.
391   // Owned by RenderFrameImpl.
392   RendererMediaPlayerManager* player_manager_;
393
394   // Delegates EME calls to the browser process. Owned by RenderFrameImpl.
395   // TODO(xhwang): Remove |cdm_manager_| when prefixed EME is deprecated. See
396   // http://crbug.com/249976
397   RendererCdmManager* cdm_manager_;
398
399   // Player ID assigned by the |player_manager_|.
400   int player_id_;
401
402   // Current player states.
403   blink::WebMediaPlayer::NetworkState network_state_;
404   blink::WebMediaPlayer::ReadyState ready_state_;
405
406   // GL texture ID allocated to the video.
407   unsigned int texture_id_;
408
409   // GL texture mailbox for texture_id_ to provide in the VideoFrame, and sync
410   // point for when the mailbox was produced.
411   gpu::Mailbox texture_mailbox_;
412
413   // Stream texture ID allocated to the video.
414   unsigned int stream_id_;
415
416   // Whether the mediaplayer is playing.
417   bool is_playing_;
418
419   // Whether media player needs to re-establish the surface texture peer.
420   bool needs_establish_peer_;
421
422   // Whether the video size info is available.
423   bool has_size_info_;
424
425   const scoped_refptr<base::MessageLoopProxy> compositor_loop_;
426
427   // Object for allocating stream textures.
428   scoped_refptr<StreamTextureFactory> stream_texture_factory_;
429
430   // Object for calling back the compositor thread to repaint the video when a
431   // frame available. It should be initialized on the compositor thread.
432   // Accessed on main thread and on compositor thread when main thread is
433   // blocked.
434   ScopedStreamTextureProxy stream_texture_proxy_;
435
436   // Whether media player needs external surface.
437   // Only used for the VIDEO_HOLE logic.
438   bool needs_external_surface_;
439
440   // A pointer back to the compositor to inform it about state changes. This is
441   // not NULL while the compositor is actively using this webmediaplayer.
442   // Accessed on main thread and on compositor thread when main thread is
443   // blocked.
444   cc::VideoFrameProvider::Client* video_frame_provider_client_;
445
446   scoped_ptr<cc_blink::WebLayerImpl> video_weblayer_;
447
448 #if defined(VIDEO_HOLE)
449   // A rectangle represents the geometry of video frame, when computed last
450   // time.
451   gfx::RectF last_computed_rect_;
452
453   // Whether to use the video overlay for all embedded video.
454   // True only for testing.
455   bool force_use_overlay_embedded_video_;
456 #endif  // defined(VIDEO_HOLE)
457
458   MediaPlayerHostMsg_Initialize_Type player_type_;
459
460   // Whether the browser is currently connected to a remote media player.
461   bool is_remote_;
462
463   scoped_refptr<media::MediaLog> media_log_;
464
465   scoped_ptr<MediaInfoLoader> info_loader_;
466
467   // The currently selected key system. Empty string means that no key system
468   // has been selected.
469   std::string current_key_system_;
470
471   // Temporary for EME v0.1. In the future the init data type should be passed
472   // through GenerateKeyRequest() directly from WebKit.
473   std::string init_data_type_;
474
475   // Manages decryption keys and decrypts encrypted frames.
476   scoped_ptr<ProxyDecryptor> proxy_decryptor_;
477
478   // Non-owned pointer to the CDM. Updated via calls to
479   // setContentDecryptionModule().
480   WebContentDecryptionModuleImpl* web_cdm_;
481
482   // This is only Used by Clear Key key system implementation, where a renderer
483   // side CDM will be used. This is similar to WebMediaPlayerImpl. For other key
484   // systems, a browser side CDM will be used and we set CDM by calling
485   // player_manager_->SetCdm() directly.
486   media::DecryptorReadyCB decryptor_ready_cb_;
487
488   SkBitmap bitmap_;
489
490   // Whether stored credentials are allowed to be passed to the server.
491   bool allow_stored_credentials_;
492
493   // Whether the resource is local.
494   bool is_local_resource_;
495
496   // base::TickClock used by |interpolator_|.
497   base::DefaultTickClock default_tick_clock_;
498
499   // Tracks the most recent media time update and provides interpolated values
500   // as playback progresses.
501   media::TimeDeltaInterpolator interpolator_;
502
503   scoped_ptr<MediaSourceDelegate> media_source_delegate_;
504
505   // NOTE: Weak pointers must be invalidated before all other member variables.
506   base::WeakPtrFactory<WebMediaPlayerAndroid> weak_factory_;
507
508   DISALLOW_COPY_AND_ASSIGN(WebMediaPlayerAndroid);
509 };
510
511 }  // namespace content
512
513 #endif  // CONTENT_RENDERER_MEDIA_ANDROID_WEBMEDIAPLAYER_ANDROID_H_