- add sources.
[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/message_loop/message_loop.h"
17 #include "base/time/time.h"
18 #include "cc/layers/video_frame_provider.h"
19 #include "content/common/media/media_player_messages_enums_android.h"
20 #include "content/renderer/media/android/media_info_loader.h"
21 #include "content/renderer/media/android/media_source_delegate.h"
22 #include "content/renderer/media/android/stream_texture_factory_android.h"
23 #include "content/renderer/media/crypto/proxy_decryptor.h"
24 #include "gpu/command_buffer/common/mailbox.h"
25 #include "media/base/android/media_player_android.h"
26 #include "media/base/demuxer_stream.h"
27 #include "media/base/media_keys.h"
28 #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
29 #include "third_party/WebKit/public/platform/WebSize.h"
30 #include "third_party/WebKit/public/platform/WebURL.h"
31 #include "third_party/WebKit/public/web/WebMediaPlayer.h"
32 #include "ui/gfx/rect_f.h"
33
34 namespace media {
35 class Demuxer;
36 class MediaLog;
37 }
38
39 namespace WebKit {
40 class WebFrame;
41 }
42
43 namespace webkit {
44 class WebLayerImpl;
45 }
46
47 namespace content {
48 class WebMediaPlayerDelegate;
49 class RendererMediaPlayerManager;
50
51 #if defined(GOOGLE_TV)
52 class MediaStreamAudioRenderer;
53 class MediaStreamClient;
54 #endif
55
56 // This class implements WebKit::WebMediaPlayer by keeping the android
57 // media player in the browser process. It listens to all the status changes
58 // sent from the browser process and sends playback controls to the media
59 // player.
60 class WebMediaPlayerAndroid
61     : public WebKit::WebMediaPlayer,
62       public cc::VideoFrameProvider,
63       public base::MessageLoop::DestructionObserver,
64       public base::SupportsWeakPtr<WebMediaPlayerAndroid> {
65  public:
66   // Construct a WebMediaPlayerAndroid object. This class communicates
67   // with the MediaPlayerAndroid object in the browser process through
68   // |proxy|.
69   // TODO(qinmin): |frame| argument is used to determine whether the current
70   // player can enter fullscreen. This logic should probably be moved into
71   // blink, so that enterFullscreen() will not be called if another video is
72   // already in fullscreen.
73   WebMediaPlayerAndroid(
74       WebKit::WebFrame* frame,
75       WebKit::WebMediaPlayerClient* client,
76       base::WeakPtr<WebMediaPlayerDelegate> delegate,
77       RendererMediaPlayerManager* manager,
78       StreamTextureFactory* factory,
79       const scoped_refptr<base::MessageLoopProxy>& media_loop,
80       media::MediaLog* media_log);
81   virtual ~WebMediaPlayerAndroid();
82
83   // WebKit::WebMediaPlayer implementation.
84   virtual void enterFullscreen();
85   virtual void exitFullscreen();
86   virtual bool canEnterFullscreen() const;
87
88   // Resource loading.
89   virtual void load(LoadType load_type,
90                     const WebKit::WebURL& url,
91                     CORSMode cors_mode) OVERRIDE;
92
93   // Playback controls.
94   virtual void play();
95   virtual void pause();
96   virtual void pause(bool is_media_related_action);
97   virtual void seek(double seconds);
98   virtual bool supportsFullscreen() const;
99   virtual bool supportsSave() const;
100   virtual void setRate(double rate);
101   virtual void setVolume(double volume);
102   virtual const WebKit::WebTimeRanges& buffered();
103   virtual double maxTimeSeekable() const;
104
105   // Methods for painting.
106   virtual void paint(WebKit::WebCanvas* canvas,
107                      const WebKit::WebRect& rect,
108                      unsigned char alpha);
109
110   virtual bool copyVideoTextureToPlatformTexture(
111       WebKit::WebGraphicsContext3D* web_graphics_context,
112       unsigned int texture,
113       unsigned int level,
114       unsigned int internal_format,
115       unsigned int type,
116       bool premultiply_alpha,
117       bool flip_y);
118
119   // True if the loaded media has a playable video/audio track.
120   virtual bool hasVideo() const;
121   virtual bool hasAudio() const;
122
123   // Dimensions of the video.
124   virtual WebKit::WebSize naturalSize() const;
125
126   // Getters of playback state.
127   virtual bool paused() const;
128   virtual bool seeking() const;
129   virtual double duration() const;
130   virtual double currentTime() const;
131
132   virtual bool didLoadingProgress() const;
133
134   // Internal states of loading and network.
135   virtual WebKit::WebMediaPlayer::NetworkState networkState() const;
136   virtual WebKit::WebMediaPlayer::ReadyState readyState() const;
137
138   virtual bool hasSingleSecurityOrigin() const;
139   virtual bool didPassCORSAccessCheck() const;
140
141   virtual double mediaTimeForTimeValue(double timeValue) const;
142
143   // Provide statistics.
144   virtual unsigned decodedFrameCount() const;
145   virtual unsigned droppedFrameCount() const;
146   virtual unsigned audioDecodedByteCount() const;
147   virtual unsigned videoDecodedByteCount() const;
148
149   // cc::VideoFrameProvider implementation. These methods are running on the
150   // compositor thread.
151   virtual void SetVideoFrameProviderClient(
152       cc::VideoFrameProvider::Client* client) OVERRIDE;
153   virtual scoped_refptr<media::VideoFrame> GetCurrentFrame() OVERRIDE;
154   virtual void PutCurrentFrame(const scoped_refptr<media::VideoFrame>& frame)
155       OVERRIDE;
156
157   // Media player callback handlers.
158   void OnMediaMetadataChanged(const base::TimeDelta& duration, int width,
159                               int height, bool success);
160   void OnPlaybackComplete();
161   void OnBufferingUpdate(int percentage);
162   void OnSeekRequest(const base::TimeDelta& time_to_seek);
163   void OnSeekComplete(const base::TimeDelta& current_time);
164   void OnMediaError(int error_type);
165   void OnVideoSizeChanged(int width, int height);
166   void OnDurationChanged(const base::TimeDelta& duration);
167
168   // Called to update the current time.
169   void OnTimeUpdate(const base::TimeDelta& current_time);
170
171   // Functions called when media player status changes.
172   void OnConnectedToRemoteDevice();
173   void OnDisconnectedFromRemoteDevice();
174   void OnDidEnterFullscreen();
175   void OnDidExitFullscreen();
176   void OnMediaPlayerPlay();
177   void OnMediaPlayerPause();
178
179   // Called when the player is released.
180   virtual void OnPlayerReleased();
181
182   // This function is called by the RendererMediaPlayerManager to pause the
183   // video and release the media player and surface texture when we switch tabs.
184   // However, the actual GlTexture is not released to keep the video screenshot.
185   virtual void ReleaseMediaResources();
186
187   // Method inherited from DestructionObserver.
188   virtual void WillDestroyCurrentMessageLoop() OVERRIDE;
189
190   // Detach the player from its manager.
191   void Detach();
192
193 #if defined(GOOGLE_TV)
194   // Retrieve geometry of the media player (i.e. location and size of the video
195   // frame) if changed. Returns true only if the geometry has been changed since
196   // the last call.
197   bool RetrieveGeometryChange(gfx::RectF* rect);
198 #endif
199
200   virtual MediaKeyException generateKeyRequest(
201       const WebKit::WebString& key_system,
202       const unsigned char* init_data,
203       unsigned init_data_length) OVERRIDE;
204   virtual MediaKeyException addKey(
205       const WebKit::WebString& key_system,
206       const unsigned char* key,
207       unsigned key_length,
208       const unsigned char* init_data,
209       unsigned init_data_length,
210       const WebKit::WebString& session_id) OVERRIDE;
211   virtual MediaKeyException cancelKeyRequest(
212       const WebKit::WebString& key_system,
213       const WebKit::WebString& session_id) OVERRIDE;
214
215   void OnKeyAdded(const std::string& session_id);
216   void OnKeyError(const std::string& session_id,
217                   media::MediaKeys::KeyError error_code,
218                   int system_code);
219   void OnKeyMessage(const std::string& session_id,
220                     const std::vector<uint8>& message,
221                     const std::string& destination_url);
222
223   void OnMediaSourceOpened(WebKit::WebMediaSource* web_media_source);
224
225   void OnNeedKey(const std::string& type,
226                  const std::vector<uint8>& init_data);
227
228 #if defined(GOOGLE_TV)
229   bool InjectMediaStream(MediaStreamClient* media_stream_client,
230                          media::Demuxer* demuxer,
231                          const base::Closure& destroy_demuxer_cb);
232 #endif
233
234   // Can be called on any thread.
235   static void OnReleaseRemotePlaybackTexture(
236       const scoped_refptr<base::MessageLoopProxy>& main_loop,
237       const base::WeakPtr<WebMediaPlayerAndroid>& player,
238       uint32 sync_point);
239
240  protected:
241   // Helper method to update the playing state.
242   void UpdatePlayingState(bool is_playing_);
243
244   // Helper methods for posting task for setting states and update WebKit.
245   void UpdateNetworkState(WebKit::WebMediaPlayer::NetworkState state);
246   void UpdateReadyState(WebKit::WebMediaPlayer::ReadyState state);
247   void TryCreateStreamTextureProxyIfNeeded();
248   void DoCreateStreamTexture();
249
250
251   // Helper method to reestablish the surface texture peer for android
252   // media player.
253   void EstablishSurfaceTexturePeer();
254
255   // Requesting whether the surface texture peer needs to be reestablished.
256   void SetNeedsEstablishPeer(bool needs_establish_peer);
257
258 #if defined(GOOGLE_TV)
259   // Request external surface for out-of-band composition.
260   void RequestExternalSurface();
261 #endif
262
263  private:
264   void DrawRemotePlaybackIcon();
265   void ReallocateVideoFrame();
266   void SetCurrentFrameInternal(scoped_refptr<media::VideoFrame>& frame);
267   void DidLoadMediaInfo(MediaInfoLoader::Status status);
268   void DoReleaseRemotePlaybackTexture(uint32 sync_point);
269
270   // Actually do the work for generateKeyRequest/addKey so they can easily
271   // report results to UMA.
272   MediaKeyException GenerateKeyRequestInternal(
273       const WebKit::WebString& key_system,
274       const unsigned char* init_data,
275       unsigned init_data_length);
276   MediaKeyException AddKeyInternal(const WebKit::WebString& key_system,
277                                    const unsigned char* key,
278                                    unsigned key_length,
279                                    const unsigned char* init_data,
280                                    unsigned init_data_length,
281                                    const WebKit::WebString& session_id);
282   MediaKeyException CancelKeyRequestInternal(
283       const WebKit::WebString& key_system,
284       const WebKit::WebString& session_id);
285
286   WebKit::WebFrame* const frame_;
287
288   WebKit::WebMediaPlayerClient* const client_;
289
290   // |delegate_| is used to notify the browser process of the player status, so
291   // that the browser process can control screen locks.
292   // TODO(qinmin): Currently android mediaplayer takes care of the screen
293   // lock. So this is only used for media source. Will apply this to regular
294   // media tag once http://crbug.com/247892 is fixed.
295   base::WeakPtr<WebMediaPlayerDelegate> delegate_;
296
297   // Save the list of buffered time ranges.
298   WebKit::WebTimeRanges buffered_;
299
300   // Size of the video.
301   WebKit::WebSize natural_size_;
302
303   // Size that has been sent to StreamTexture.
304   WebKit::WebSize cached_stream_texture_size_;
305
306   // The video frame object used for rendering by the compositor.
307   scoped_refptr<media::VideoFrame> current_frame_;
308   base::Lock current_frame_lock_;
309
310   base::ThreadChecker main_thread_checker_;
311
312   // Message loop for main renderer thread.
313   const scoped_refptr<base::MessageLoopProxy> main_loop_;
314
315   // Message loop for media thread.
316   const scoped_refptr<base::MessageLoopProxy> media_loop_;
317
318   // URL of the media file to be fetched.
319   GURL url_;
320
321   // Media duration.
322   base::TimeDelta duration_;
323
324   // Flag to remember if we have a trusted duration_ value provided by
325   // MediaSourceDelegate notifying OnDurationChanged(). In this case, ignore
326   // any subsequent duration value passed to OnMediaMetadataChange().
327   bool ignore_metadata_duration_change_;
328
329   // Seek gets pending if another seek is in progress. Only last pending seek
330   // will have effect.
331   bool pending_seek_;
332   base::TimeDelta pending_seek_time_;
333
334   // Internal seek state.
335   bool seeking_;
336   base::TimeDelta seek_time_;
337
338   // Whether loading has progressed since the last call to didLoadingProgress.
339   mutable bool did_loading_progress_;
340
341   // Manager for managing this object and for delegating method calls on
342   // Render Thread.
343   RendererMediaPlayerManager* manager_;
344
345   // Player ID assigned by the |manager_|.
346   int player_id_;
347
348   // Current player states.
349   WebKit::WebMediaPlayer::NetworkState network_state_;
350   WebKit::WebMediaPlayer::ReadyState ready_state_;
351
352   // GL texture ID used to show the remote playback icon.
353   unsigned int remote_playback_texture_id_;
354
355   // GL texture ID allocated to the video.
356   unsigned int texture_id_;
357
358   // GL texture mailbox for texture_id_ to provide in the VideoFrame, and sync
359   // point for when the mailbox was produced.
360   gpu::Mailbox texture_mailbox_;
361   unsigned int texture_mailbox_sync_point_;
362
363   // Stream texture ID allocated to the video.
364   unsigned int stream_id_;
365
366   // Whether the mediaplayer is playing.
367   bool is_playing_;
368
369   // Whether the mediaplayer has already started playing.
370   bool playing_started_;
371
372   // Whether media player needs to re-establish the surface texture peer.
373   bool needs_establish_peer_;
374
375   // Whether |stream_texture_proxy_| is initialized.
376   bool stream_texture_proxy_initialized_;
377
378   // Whether the video size info is available.
379   bool has_size_info_;
380
381   // Whether the video metadata and info are available.
382   bool has_media_metadata_;
383   bool has_media_info_;
384
385   // Object for allocating stream textures.
386   scoped_ptr<StreamTextureFactory> stream_texture_factory_;
387
388   // Object for calling back the compositor thread to repaint the video when a
389   // frame available. It should be initialized on the compositor thread.
390   ScopedStreamTextureProxy stream_texture_proxy_;
391
392   // Whether media player needs external surface.
393   bool needs_external_surface_;
394
395   // A pointer back to the compositor to inform it about state changes. This is
396   // not NULL while the compositor is actively using this webmediaplayer.
397   cc::VideoFrameProvider::Client* video_frame_provider_client_;
398
399   scoped_ptr<webkit::WebLayerImpl> video_weblayer_;
400
401 #if defined(GOOGLE_TV)
402   // Pixel threshold for external surface usage. Negative value means that the
403   // threshold is not defined, so that external surface is never used.
404   int external_surface_threshold_;
405
406   // A rectangle represents the geometry of video frame, when computed last
407   // time.
408   gfx::RectF last_computed_rect_;
409
410   // Media Stream related fields.
411   media::Demuxer* demuxer_;
412   base::Closure destroy_demuxer_cb_;
413   scoped_refptr<MediaStreamAudioRenderer> audio_renderer_;
414   MediaStreamClient* media_stream_client_;
415 #endif
416
417   scoped_ptr<MediaSourceDelegate,
418              MediaSourceDelegate::Destroyer> media_source_delegate_;
419
420   // Internal pending playback state.
421   // Store a playback request that cannot be started immediately.
422   bool pending_playback_;
423
424   MediaPlayerHostMsg_Initialize_Type player_type_;
425
426   // The current playing time. Because the media player is in the browser
427   // process, it will regularly update the |current_time_| by calling
428   // OnTimeUpdate().
429   double current_time_;
430
431   // Whether the browser is currently connected to a remote media player.
432   bool is_remote_;
433
434   media::MediaLog* media_log_;
435
436   scoped_ptr<MediaInfoLoader> info_loader_;
437
438   // The currently selected key system. Empty string means that no key system
439   // has been selected.
440   WebKit::WebString current_key_system_;
441
442   // Temporary for EME v0.1. In the future the init data type should be passed
443   // through GenerateKeyRequest() directly from WebKit.
444   std::string init_data_type_;
445
446   // The decryptor that manages decryption keys and decrypts encrypted frames.
447   scoped_ptr<ProxyDecryptor> decryptor_;
448
449   base::WeakPtrFactory<WebMediaPlayerAndroid> weak_factory_;
450
451   DISALLOW_COPY_AND_ASSIGN(WebMediaPlayerAndroid);
452 };
453
454 }  // namespace content
455
456 #endif  // CONTENT_RENDERER_MEDIA_ANDROID_WEBMEDIAPLAYER_ANDROID_H_