[ServiceWorker] Implement WebServiceWorkerContextClient::openWindow().
[chromium-blink-merge.git] / content / renderer / media / android / webmediaplayer_android.h
blob314d7ee56bee498e3910f9629aae4b57542d205d
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.
5 #ifndef CONTENT_RENDERER_MEDIA_ANDROID_WEBMEDIAPLAYER_ANDROID_H_
6 #define CONTENT_RENDERER_MEDIA_ANDROID_WEBMEDIAPLAYER_ANDROID_H_
8 #include <jni.h>
9 #include <string>
10 #include <vector>
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 "gpu/command_buffer/common/mailbox.h"
26 #include "media/base/android/media_player_android.h"
27 #include "media/base/cdm_context.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 "media/cdm/proxy_decryptor.h"
32 #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
33 #include "third_party/WebKit/public/platform/WebMediaPlayer.h"
34 #include "third_party/WebKit/public/platform/WebSize.h"
35 #include "third_party/WebKit/public/platform/WebURL.h"
36 #include "third_party/skia/include/core/SkBitmap.h"
37 #include "ui/gfx/geometry/rect_f.h"
39 namespace base {
40 class SingleThreadTaskRunner;
43 namespace blink {
44 class WebContentDecryptionModule;
45 class WebContentDecryptionModuleResult;
46 class WebFrame;
47 class WebMediaPlayerClient;
48 class WebURL;
51 namespace cc_blink {
52 class WebLayerImpl;
55 namespace gpu {
56 struct MailboxHolder;
59 namespace media {
60 class CdmContext;
61 class MediaLog;
62 class MediaPermission;
63 class WebContentDecryptionModuleImpl;
64 class WebMediaPlayerDelegate;
67 namespace content {
69 class RendererCdmManager;
70 class RendererMediaPlayerManager;
72 // This class implements blink::WebMediaPlayer by keeping the android
73 // media player in the browser process. It listens to all the status changes
74 // sent from the browser process and sends playback controls to the media
75 // player.
76 class WebMediaPlayerAndroid : public blink::WebMediaPlayer,
77 public cc::VideoFrameProvider,
78 public RenderFrameObserver,
79 public StreamTextureFactoryContextObserver {
80 public:
81 // Construct a WebMediaPlayerAndroid object. This class communicates with the
82 // MediaPlayerAndroid object in the browser process through |proxy|.
83 // TODO(qinmin): |frame| argument is used to determine whether the current
84 // player can enter fullscreen. This logic should probably be moved into
85 // blink, so that enterFullscreen() will not be called if another video is
86 // already in fullscreen.
87 WebMediaPlayerAndroid(
88 blink::WebFrame* frame,
89 blink::WebMediaPlayerClient* client,
90 base::WeakPtr<media::WebMediaPlayerDelegate> delegate,
91 RendererMediaPlayerManager* player_manager,
92 RendererCdmManager* cdm_manager,
93 media::MediaPermission* media_permission,
94 blink::WebContentDecryptionModule* initial_cdm,
95 scoped_refptr<StreamTextureFactory> factory,
96 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
97 media::MediaLog* media_log);
98 virtual ~WebMediaPlayerAndroid();
100 // blink::WebMediaPlayer implementation.
101 virtual void enterFullscreen();
103 // Resource loading.
104 virtual void load(LoadType load_type,
105 const blink::WebURL& url,
106 CORSMode cors_mode);
108 // Playback controls.
109 virtual void play();
110 virtual void pause();
111 virtual void seek(double seconds);
112 virtual bool supportsSave() const;
113 virtual void setRate(double rate);
114 virtual void setVolume(double volume);
115 virtual void requestRemotePlayback();
116 virtual void requestRemotePlaybackControl();
117 virtual blink::WebTimeRanges buffered() const;
118 virtual blink::WebTimeRanges seekable() const;
120 // Poster image, as defined in the <video> element.
121 virtual void setPoster(const blink::WebURL& poster) override;
123 // Methods for painting.
124 // FIXME: This path "only works" on Android. It is a workaround for the
125 // issue that Skia could not handle Android's GL_TEXTURE_EXTERNAL_OES texture
126 // internally. It should be removed and replaced by the normal paint path.
127 // https://code.google.com/p/skia/issues/detail?id=1189
128 virtual void paint(blink::WebCanvas* canvas,
129 const blink::WebRect& rect,
130 unsigned char alpha,
131 SkXfermode::Mode mode);
133 virtual bool copyVideoTextureToPlatformTexture(
134 blink::WebGraphicsContext3D* web_graphics_context,
135 unsigned int texture,
136 unsigned int level,
137 unsigned int internal_format,
138 unsigned int type,
139 bool premultiply_alpha,
140 bool flip_y);
142 // True if the loaded media has a playable video/audio track.
143 virtual bool hasVideo() const;
144 virtual bool hasAudio() const;
146 virtual bool isRemote() const;
148 // Dimensions of the video.
149 virtual blink::WebSize naturalSize() const;
151 // Getters of playback state.
152 virtual bool paused() const;
153 virtual bool seeking() const;
154 virtual double duration() const;
155 virtual double timelineOffset() const;
156 virtual double currentTime() const;
158 virtual bool didLoadingProgress();
160 // Internal states of loading and network.
161 virtual blink::WebMediaPlayer::NetworkState networkState() const;
162 virtual blink::WebMediaPlayer::ReadyState readyState() const;
164 virtual bool hasSingleSecurityOrigin() const;
165 virtual bool didPassCORSAccessCheck() const;
167 virtual double mediaTimeForTimeValue(double timeValue) const;
169 // Provide statistics.
170 virtual unsigned decodedFrameCount() const;
171 virtual unsigned droppedFrameCount() const;
172 virtual unsigned audioDecodedByteCount() const;
173 virtual unsigned videoDecodedByteCount() const;
175 // cc::VideoFrameProvider implementation. These methods are running on the
176 // compositor thread.
177 void SetVideoFrameProviderClient(
178 cc::VideoFrameProvider::Client* client) override;
179 scoped_refptr<media::VideoFrame> GetCurrentFrame() override;
180 void PutCurrentFrame(const scoped_refptr<media::VideoFrame>& frame) override;
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);
193 // Called to update the current time.
194 void OnTimeUpdate(base::TimeDelta current_timestamp,
195 base::TimeTicks current_time_ticks);
197 // Functions called when media player status changes.
198 void OnConnectedToRemoteDevice(const std::string& remote_playback_message);
199 void OnDisconnectedFromRemoteDevice();
200 void OnDidExitFullscreen();
201 void OnMediaPlayerPlay();
202 void OnMediaPlayerPause();
203 void OnRequestFullscreen();
204 void OnRemoteRouteAvailabilityChanged(bool routes_available);
206 // StreamTextureFactoryContextObserver implementation.
207 void ResetStreamTextureProxy() override;
209 // Called when the player is released.
210 virtual void OnPlayerReleased();
212 // This function is called by the RendererMediaPlayerManager to pause the
213 // video and release the media player and surface texture when we switch tabs.
214 // However, the actual GlTexture is not released to keep the video screenshot.
215 virtual void ReleaseMediaResources();
217 // RenderFrameObserver implementation.
218 void OnDestruct() override;
220 #if defined(VIDEO_HOLE)
221 // Calculate the boundary rectangle of the media player (i.e. location and
222 // size of the video frame).
223 // Returns true if the geometry has been changed since the last call.
224 bool UpdateBoundaryRectangle();
226 const gfx::RectF GetBoundaryRectangle();
227 #endif // defined(VIDEO_HOLE)
229 virtual MediaKeyException generateKeyRequest(
230 const blink::WebString& key_system,
231 const unsigned char* init_data,
232 unsigned init_data_length);
233 virtual MediaKeyException addKey(
234 const blink::WebString& key_system,
235 const unsigned char* key,
236 unsigned key_length,
237 const unsigned char* init_data,
238 unsigned init_data_length,
239 const blink::WebString& session_id);
240 virtual MediaKeyException cancelKeyRequest(
241 const blink::WebString& key_system,
242 const blink::WebString& session_id);
244 virtual void setContentDecryptionModule(
245 blink::WebContentDecryptionModule* cdm,
246 blink::WebContentDecryptionModuleResult result);
248 void OnKeyAdded(const std::string& session_id);
249 void OnKeyError(const std::string& session_id,
250 media::MediaKeys::KeyError error_code,
251 uint32 system_code);
252 void OnKeyMessage(const std::string& session_id,
253 const std::vector<uint8>& message,
254 const GURL& destination_url);
256 void OnMediaSourceOpened(blink::WebMediaSource* web_media_source);
258 void OnEncryptedMediaInitData(const std::string& init_data_type,
259 const std::vector<uint8>& init_data);
261 protected:
262 // Helper method to update the playing state.
263 void UpdatePlayingState(bool is_playing_);
265 // Helper methods for posting task for setting states and update WebKit.
266 void UpdateNetworkState(blink::WebMediaPlayer::NetworkState state);
267 void UpdateReadyState(blink::WebMediaPlayer::ReadyState state);
268 void TryCreateStreamTextureProxyIfNeeded();
269 void DoCreateStreamTexture();
271 // Helper method to reestablish the surface texture peer for android
272 // media player.
273 void EstablishSurfaceTexturePeer();
275 // Requesting whether the surface texture peer needs to be reestablished.
276 void SetNeedsEstablishPeer(bool needs_establish_peer);
278 private:
279 void InitializePlayer(const GURL& url,
280 const GURL& first_party_for_cookies,
281 bool allowed_stored_credentials,
282 int demuxer_client_id);
283 void Pause(bool is_media_related_action);
284 void DrawRemotePlaybackText(const std::string& remote_playback_message);
285 void ReallocateVideoFrame();
286 void SetCurrentFrameInternal(scoped_refptr<media::VideoFrame>& frame);
287 void DidLoadMediaInfo(MediaInfoLoader::Status status,
288 const GURL& redirected_url,
289 const GURL& first_party_for_cookies,
290 bool allow_stored_credentials);
291 bool IsKeySystemSupported(const std::string& key_system);
292 bool IsLocalResource();
294 // Actually do the work for generateKeyRequest/addKey so they can easily
295 // report results to UMA.
296 MediaKeyException GenerateKeyRequestInternal(const std::string& key_system,
297 const unsigned char* init_data,
298 unsigned init_data_length);
299 MediaKeyException AddKeyInternal(const std::string& key_system,
300 const unsigned char* key,
301 unsigned key_length,
302 const unsigned char* init_data,
303 unsigned init_data_length,
304 const std::string& session_id);
305 MediaKeyException CancelKeyRequestInternal(const std::string& key_system,
306 const std::string& session_id);
308 // Sets the CDM. Should only be called when |is_player_initialized_| is true
309 // and a new non-null |cdm_context_| is available. Fires |cdm_attached_cb_|
310 // with the result after the CDM is attached.
311 void SetCdmInternal(const media::CdmAttachedCB& cdm_attached_cb);
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);
319 // Called when the ContentDecryptionModule has been attached to the
320 // pipeline/decoders.
321 void ContentDecryptionModuleAttached(
322 blink::WebContentDecryptionModuleResult result,
323 bool success);
325 bool IsHLSStream() const;
327 blink::WebFrame* const frame_;
329 blink::WebMediaPlayerClient* const client_;
331 // |delegate_| is used to notify the browser process of the player status, so
332 // that the browser process can control screen locks.
333 // TODO(qinmin): Currently android mediaplayer takes care of the screen
334 // lock. So this is only used for media source. Will apply this to regular
335 // media tag once http://crbug.com/247892 is fixed.
336 base::WeakPtr<media::WebMediaPlayerDelegate> delegate_;
338 // Save the list of buffered time ranges.
339 blink::WebTimeRanges buffered_;
341 // Size of the video.
342 blink::WebSize natural_size_;
344 // Size that has been sent to StreamTexture.
345 blink::WebSize cached_stream_texture_size_;
347 // The video frame object used for rendering by the compositor.
348 scoped_refptr<media::VideoFrame> current_frame_;
349 base::Lock current_frame_lock_;
351 base::ThreadChecker main_thread_checker_;
353 // Message loop for media thread.
354 const scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;
356 // URL of the media file to be fetched.
357 GURL url_;
359 // URL of the media file after |media_info_loader_| resolves all the
360 // redirections.
361 GURL redirected_url_;
363 // Media duration.
364 base::TimeDelta duration_;
366 // Flag to remember if we have a trusted duration_ value provided by
367 // MediaSourceDelegate notifying OnDurationChanged(). In this case, ignore
368 // any subsequent duration value passed to OnMediaMetadataChange().
369 bool ignore_metadata_duration_change_;
371 // Seek gets pending if another seek is in progress. Only last pending seek
372 // will have effect.
373 bool pending_seek_;
374 base::TimeDelta pending_seek_time_;
376 // Internal seek state.
377 bool seeking_;
378 base::TimeDelta seek_time_;
380 // Whether loading has progressed since the last call to didLoadingProgress.
381 bool did_loading_progress_;
383 // Manages this object and delegates player calls to the browser process.
384 // Owned by RenderFrameImpl.
385 RendererMediaPlayerManager* const player_manager_;
387 // Delegates EME calls to the browser process. Owned by RenderFrameImpl.
388 // TODO(xhwang): Remove |cdm_manager_| when prefixed EME is deprecated. See
389 // http://crbug.com/249976
390 RendererCdmManager* const cdm_manager_;
392 media::MediaPermission* media_permission_;
394 // Player ID assigned by the |player_manager_|.
395 int player_id_;
397 // Current player states.
398 blink::WebMediaPlayer::NetworkState network_state_;
399 blink::WebMediaPlayer::ReadyState ready_state_;
401 // GL texture ID allocated to the video.
402 unsigned int texture_id_;
404 // GL texture mailbox for texture_id_ to provide in the VideoFrame, and sync
405 // point for when the mailbox was produced.
406 gpu::Mailbox texture_mailbox_;
408 // Stream texture ID allocated to the video.
409 unsigned int stream_id_;
411 // Whether the media player has been initialized.
412 bool is_player_initialized_;
414 // Whether the media player is playing.
415 bool is_playing_;
417 // Whether media player needs to re-establish the surface texture peer.
418 bool needs_establish_peer_;
420 // Whether the video size info is available.
421 bool has_size_info_;
423 const scoped_refptr<base::MessageLoopProxy> compositor_loop_;
425 // Object for allocating stream textures.
426 scoped_refptr<StreamTextureFactory> stream_texture_factory_;
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_;
434 // Whether media player needs external surface.
435 // Only used for the VIDEO_HOLE logic.
436 bool needs_external_surface_;
438 // Whether the player is in fullscreen.
439 bool is_fullscreen_;
441 // A pointer back to the compositor to inform it about state changes. This is
442 // not NULL while the compositor is actively using this webmediaplayer.
443 // Accessed on main thread and on compositor thread when main thread is
444 // blocked.
445 cc::VideoFrameProvider::Client* video_frame_provider_client_;
447 scoped_ptr<cc_blink::WebLayerImpl> video_weblayer_;
449 #if defined(VIDEO_HOLE)
450 // A rectangle represents the geometry of video frame, when computed last
451 // time.
452 gfx::RectF last_computed_rect_;
454 // Whether to use the video overlay for all embedded video.
455 // True only for testing.
456 bool force_use_overlay_embedded_video_;
457 #endif // defined(VIDEO_HOLE)
459 MediaPlayerHostMsg_Initialize_Type player_type_;
461 // Whether the browser is currently connected to a remote media player.
462 bool is_remote_;
464 scoped_refptr<media::MediaLog> media_log_;
466 scoped_ptr<MediaInfoLoader> info_loader_;
468 // The currently selected key system. Empty string means that no key system
469 // has been selected.
470 std::string current_key_system_;
472 // Temporary for EME v0.1. In the future the init data type should be passed
473 // through GenerateKeyRequest() directly from WebKit.
474 std::string init_data_type_;
476 // Manages decryption keys and decrypts encrypted frames.
477 scoped_ptr<media::ProxyDecryptor> proxy_decryptor_;
479 // Non-owned pointer to the CdmContext. Updated in the constructor,
480 // generateKeyRequest() or setContentDecryptionModule().
481 media::CdmContext* cdm_context_;
483 // This is only Used by Clear Key key system implementation, where a renderer
484 // side CDM will be used. This is similar to WebMediaPlayerImpl. For other key
485 // systems, a browser side CDM will be used and we set CDM by calling
486 // player_manager_->SetCdm() directly.
487 media::DecryptorReadyCB decryptor_ready_cb_;
489 SkBitmap bitmap_;
491 // Whether stored credentials are allowed to be passed to the server.
492 bool allow_stored_credentials_;
494 // Whether the resource is local.
495 bool is_local_resource_;
497 // base::TickClock used by |interpolator_|.
498 base::DefaultTickClock default_tick_clock_;
500 // Tracks the most recent media time update and provides interpolated values
501 // as playback progresses.
502 media::TimeDeltaInterpolator interpolator_;
504 scoped_ptr<MediaSourceDelegate> media_source_delegate_;
506 // NOTE: Weak pointers must be invalidated before all other member variables.
507 base::WeakPtrFactory<WebMediaPlayerAndroid> weak_factory_;
509 DISALLOW_COPY_AND_ASSIGN(WebMediaPlayerAndroid);
512 } // namespace content
514 #endif // CONTENT_RENDERER_MEDIA_ANDROID_WEBMEDIAPLAYER_ANDROID_H_