Update To 11.40.268.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 blink::WebTimeRanges seekable() 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
130   virtual bool copyVideoTextureToPlatformTexture(
131       blink::WebGraphicsContext3D* web_graphics_context,
132       unsigned int texture,
133       unsigned int level,
134       unsigned int internal_format,
135       unsigned int type,
136       bool premultiply_alpha,
137       bool flip_y);
138
139   // True if the loaded media has a playable video/audio track.
140   virtual bool hasVideo() const;
141   virtual bool hasAudio() const;
142
143   virtual bool isRemote() const;
144
145   // Dimensions of the video.
146   virtual blink::WebSize naturalSize() const;
147
148   // Getters of playback state.
149   virtual bool paused() const;
150   virtual bool seeking() const;
151   virtual double duration() const;
152   virtual double timelineOffset() const;
153   virtual double currentTime() const;
154
155   virtual bool didLoadingProgress();
156
157   // Internal states of loading and network.
158   virtual blink::WebMediaPlayer::NetworkState networkState() const;
159   virtual blink::WebMediaPlayer::ReadyState readyState() const;
160
161   virtual bool hasSingleSecurityOrigin() const;
162   virtual bool didPassCORSAccessCheck() const;
163
164   virtual double mediaTimeForTimeValue(double timeValue) const;
165
166   // Provide statistics.
167   virtual unsigned decodedFrameCount() const;
168   virtual unsigned droppedFrameCount() const;
169   virtual unsigned audioDecodedByteCount() const;
170   virtual unsigned videoDecodedByteCount() const;
171
172   // cc::VideoFrameProvider implementation. These methods are running on the
173   // compositor thread.
174   virtual void SetVideoFrameProviderClient(
175       cc::VideoFrameProvider::Client* client) override;
176   virtual scoped_refptr<media::VideoFrame> GetCurrentFrame() override;
177   virtual void PutCurrentFrame(const scoped_refptr<media::VideoFrame>& frame)
178       override;
179
180   // Media player callback handlers.
181   void OnMediaMetadataChanged(const base::TimeDelta& duration, int width,
182                               int height, bool success);
183   void OnPlaybackComplete();
184   void OnBufferingUpdate(int percentage);
185   void OnSeekRequest(const base::TimeDelta& time_to_seek);
186   void OnSeekComplete(const base::TimeDelta& current_time);
187   void OnMediaError(int error_type);
188   void OnVideoSizeChanged(int width, int height);
189   void OnDurationChanged(const base::TimeDelta& duration);
190
191   // Called to update the current time.
192   void OnTimeUpdate(base::TimeDelta current_timestamp,
193                     base::TimeTicks current_time_ticks);
194
195   // Functions called when media player status changes.
196   void OnConnectedToRemoteDevice(const std::string& remote_playback_message);
197   void OnDisconnectedFromRemoteDevice();
198   void OnDidEnterFullscreen();
199   void OnDidExitFullscreen();
200   void OnMediaPlayerPlay();
201   void OnMediaPlayerPause();
202   void OnRequestFullscreen();
203   void OnRemoteRouteAvailabilityChanged(bool routes_available);
204
205   // StreamTextureFactoryContextObserver implementation.
206   virtual void ResetStreamTextureProxy() override;
207
208   // Called when the player is released.
209   virtual void OnPlayerReleased();
210
211   // This function is called by the RendererMediaPlayerManager to pause the
212   // video and release the media player and surface texture when we switch tabs.
213   // However, the actual GlTexture is not released to keep the video screenshot.
214   virtual void ReleaseMediaResources();
215
216   // RenderFrameObserver implementation.
217   virtual void OnDestruct() override;
218
219 #if defined(VIDEO_HOLE)
220   // Calculate the boundary rectangle of the media player (i.e. location and
221   // size of the video frame).
222   // Returns true if the geometry has been changed since the last call.
223   bool UpdateBoundaryRectangle();
224
225   const gfx::RectF GetBoundaryRectangle();
226 #endif  // defined(VIDEO_HOLE)
227
228   virtual MediaKeyException generateKeyRequest(
229       const blink::WebString& key_system,
230       const unsigned char* init_data,
231       unsigned init_data_length);
232   virtual MediaKeyException addKey(
233       const blink::WebString& key_system,
234       const unsigned char* key,
235       unsigned key_length,
236       const unsigned char* init_data,
237       unsigned init_data_length,
238       const blink::WebString& session_id);
239   virtual MediaKeyException cancelKeyRequest(
240       const blink::WebString& key_system,
241       const blink::WebString& session_id);
242   // TODO(jrummell): Remove this method once Blink updated to use the other
243   // two methods.
244   virtual void setContentDecryptionModule(
245       blink::WebContentDecryptionModule* cdm);
246   virtual void setContentDecryptionModule(
247       blink::WebContentDecryptionModule* cdm,
248       blink::WebContentDecryptionModuleResult result);
249
250   void OnKeyAdded(const std::string& session_id);
251   void OnKeyError(const std::string& session_id,
252                   media::MediaKeys::KeyError error_code,
253                   uint32 system_code);
254   void OnKeyMessage(const std::string& session_id,
255                     const std::vector<uint8>& message,
256                     const GURL& destination_url);
257
258   void OnMediaSourceOpened(blink::WebMediaSource* web_media_source);
259
260   void OnNeedKey(const std::string& type,
261                  const std::vector<uint8>& init_data);
262
263   // TODO(xhwang): Implement WebMediaPlayer::setContentDecryptionModule().
264   // See: http://crbug.com/224786
265
266  protected:
267   // Helper method to update the playing state.
268   void UpdatePlayingState(bool is_playing_);
269
270   // Helper methods for posting task for setting states and update WebKit.
271   void UpdateNetworkState(blink::WebMediaPlayer::NetworkState state);
272   void UpdateReadyState(blink::WebMediaPlayer::ReadyState state);
273   void TryCreateStreamTextureProxyIfNeeded();
274   void DoCreateStreamTexture();
275
276   // Helper method to reestablish the surface texture peer for android
277   // media player.
278   void EstablishSurfaceTexturePeer();
279
280   // Requesting whether the surface texture peer needs to be reestablished.
281   void SetNeedsEstablishPeer(bool needs_establish_peer);
282
283  private:
284   void InitializePlayer(const GURL& url,
285                         const GURL& first_party_for_cookies,
286                         bool allowed_stored_credentials,
287                         int demuxer_client_id);
288   void Pause(bool is_media_related_action);
289   void DrawRemotePlaybackText(const std::string& remote_playback_message);
290   void ReallocateVideoFrame();
291   void SetCurrentFrameInternal(scoped_refptr<media::VideoFrame>& frame);
292   void DidLoadMediaInfo(MediaInfoLoader::Status status,
293                         const GURL& redirected_url,
294                         const GURL& first_party_for_cookies,
295                         bool allow_stored_credentials);
296   bool IsKeySystemSupported(const std::string& key_system);
297   bool IsLocalResource();
298
299   // Actually do the work for generateKeyRequest/addKey so they can easily
300   // report results to UMA.
301   MediaKeyException GenerateKeyRequestInternal(const std::string& key_system,
302                                                const unsigned char* init_data,
303                                                unsigned init_data_length);
304   MediaKeyException AddKeyInternal(const std::string& key_system,
305                                    const unsigned char* key,
306                                    unsigned key_length,
307                                    const unsigned char* init_data,
308                                    unsigned init_data_length,
309                                    const std::string& session_id);
310   MediaKeyException CancelKeyRequestInternal(const std::string& key_system,
311                                              const std::string& session_id);
312
313   // Requests that this object notifies when a decryptor is ready through the
314   // |decryptor_ready_cb| provided.
315   // If |decryptor_ready_cb| is null, the existing callback will be fired with
316   // NULL immediately and reset.
317   void SetDecryptorReadyCB(const media::DecryptorReadyCB& decryptor_ready_cb);
318
319   // Called when the ContentDecryptionModule has been attached to the
320   // pipeline/decoders.
321   void ContentDecryptionModuleAttached(
322       blink::WebContentDecryptionModuleResult result,
323       bool success);
324
325   bool EnsureTextureBackedSkBitmap(GrContext* gr, SkBitmap& bitmap,
326                                    const blink::WebSize& size,
327                                    GrSurfaceOrigin origin,
328                                    GrPixelConfig config);
329
330   bool IsHLSStream() const;
331
332   blink::WebFrame* const frame_;
333
334   blink::WebMediaPlayerClient* const client_;
335
336   // |delegate_| is used to notify the browser process of the player status, so
337   // that the browser process can control screen locks.
338   // TODO(qinmin): Currently android mediaplayer takes care of the screen
339   // lock. So this is only used for media source. Will apply this to regular
340   // media tag once http://crbug.com/247892 is fixed.
341   base::WeakPtr<media::WebMediaPlayerDelegate> delegate_;
342
343   // Save the list of buffered time ranges.
344   blink::WebTimeRanges buffered_;
345
346   // Size of the video.
347   blink::WebSize natural_size_;
348
349   // Size that has been sent to StreamTexture.
350   blink::WebSize cached_stream_texture_size_;
351
352   // The video frame object used for rendering by the compositor.
353   scoped_refptr<media::VideoFrame> current_frame_;
354   base::Lock current_frame_lock_;
355
356   base::ThreadChecker main_thread_checker_;
357
358   // Message loop for media thread.
359   const scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;
360
361   // URL of the media file to be fetched.
362   GURL url_;
363
364   // URL of the media file after |media_info_loader_| resolves all the
365   // redirections.
366   GURL redirected_url_;
367
368   // Media duration.
369   base::TimeDelta duration_;
370
371   // Flag to remember if we have a trusted duration_ value provided by
372   // MediaSourceDelegate notifying OnDurationChanged(). In this case, ignore
373   // any subsequent duration value passed to OnMediaMetadataChange().
374   bool ignore_metadata_duration_change_;
375
376   // Seek gets pending if another seek is in progress. Only last pending seek
377   // will have effect.
378   bool pending_seek_;
379   base::TimeDelta pending_seek_time_;
380
381   // Internal seek state.
382   bool seeking_;
383   base::TimeDelta seek_time_;
384
385   // Whether loading has progressed since the last call to didLoadingProgress.
386   bool did_loading_progress_;
387
388   // Manages this object and delegates player calls to the browser process.
389   // Owned by RenderFrameImpl.
390   RendererMediaPlayerManager* player_manager_;
391
392   // Delegates EME calls to the browser process. Owned by RenderFrameImpl.
393   // TODO(xhwang): Remove |cdm_manager_| when prefixed EME is deprecated. See
394   // http://crbug.com/249976
395   RendererCdmManager* cdm_manager_;
396
397   // Player ID assigned by the |player_manager_|.
398   int player_id_;
399
400   // Current player states.
401   blink::WebMediaPlayer::NetworkState network_state_;
402   blink::WebMediaPlayer::ReadyState ready_state_;
403
404   // GL texture ID allocated to the video.
405   unsigned int texture_id_;
406
407   // GL texture mailbox for texture_id_ to provide in the VideoFrame, and sync
408   // point for when the mailbox was produced.
409   gpu::Mailbox texture_mailbox_;
410
411   // Stream texture ID allocated to the video.
412   unsigned int stream_id_;
413
414   // Whether the mediaplayer is playing.
415   bool is_playing_;
416
417   // Whether media player needs to re-establish the surface texture peer.
418   bool needs_establish_peer_;
419
420   // Whether the video size info is available.
421   bool has_size_info_;
422
423   const scoped_refptr<base::MessageLoopProxy> compositor_loop_;
424
425   // Object for allocating stream textures.
426   scoped_refptr<StreamTextureFactory> stream_texture_factory_;
427
428   // Object for calling back the compositor thread to repaint the video when a
429   // frame available. It should be initialized on the compositor thread.
430   // Accessed on main thread and on compositor thread when main thread is
431   // blocked.
432   ScopedStreamTextureProxy stream_texture_proxy_;
433
434   // Whether media player needs external surface.
435   // Only used for the VIDEO_HOLE logic.
436   bool needs_external_surface_;
437
438   // A pointer back to the compositor to inform it about state changes. This is
439   // not NULL while the compositor is actively using this webmediaplayer.
440   // Accessed on main thread and on compositor thread when main thread is
441   // blocked.
442   cc::VideoFrameProvider::Client* video_frame_provider_client_;
443
444   scoped_ptr<cc_blink::WebLayerImpl> video_weblayer_;
445
446 #if defined(VIDEO_HOLE)
447   // A rectangle represents the geometry of video frame, when computed last
448   // time.
449   gfx::RectF last_computed_rect_;
450
451   // Whether to use the video overlay for all embedded video.
452   // True only for testing.
453   bool force_use_overlay_embedded_video_;
454 #endif  // defined(VIDEO_HOLE)
455
456   MediaPlayerHostMsg_Initialize_Type player_type_;
457
458   // Whether the browser is currently connected to a remote media player.
459   bool is_remote_;
460
461   scoped_refptr<media::MediaLog> media_log_;
462
463   scoped_ptr<MediaInfoLoader> info_loader_;
464
465   // The currently selected key system. Empty string means that no key system
466   // has been selected.
467   std::string current_key_system_;
468
469   // Temporary for EME v0.1. In the future the init data type should be passed
470   // through GenerateKeyRequest() directly from WebKit.
471   std::string init_data_type_;
472
473   // Manages decryption keys and decrypts encrypted frames.
474   scoped_ptr<ProxyDecryptor> proxy_decryptor_;
475
476   // Non-owned pointer to the CDM. Updated via calls to
477   // setContentDecryptionModule().
478   WebContentDecryptionModuleImpl* web_cdm_;
479
480   // This is only Used by Clear Key key system implementation, where a renderer
481   // side CDM will be used. This is similar to WebMediaPlayerImpl. For other key
482   // systems, a browser side CDM will be used and we set CDM by calling
483   // player_manager_->SetCdm() directly.
484   media::DecryptorReadyCB decryptor_ready_cb_;
485
486   SkBitmap bitmap_;
487
488   // Whether stored credentials are allowed to be passed to the server.
489   bool allow_stored_credentials_;
490
491   // Whether the resource is local.
492   bool is_local_resource_;
493
494   // base::TickClock used by |interpolator_|.
495   base::DefaultTickClock default_tick_clock_;
496
497   // Tracks the most recent media time update and provides interpolated values
498   // as playback progresses.
499   media::TimeDeltaInterpolator interpolator_;
500
501   scoped_ptr<MediaSourceDelegate> media_source_delegate_;
502
503   // NOTE: Weak pointers must be invalidated before all other member variables.
504   base::WeakPtrFactory<WebMediaPlayerAndroid> weak_factory_;
505
506   DISALLOW_COPY_AND_ASSIGN(WebMediaPlayerAndroid);
507 };
508
509 }  // namespace content
510
511 #endif  // CONTENT_RENDERER_MEDIA_ANDROID_WEBMEDIAPLAYER_ANDROID_H_