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_
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/blink/webmediaplayer_util.h"
32 #include "media/cdm/proxy_decryptor.h"
33 #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
34 #include "third_party/WebKit/public/platform/WebMediaPlayer.h"
35 #include "third_party/WebKit/public/platform/WebSize.h"
36 #include "third_party/WebKit/public/platform/WebURL.h"
37 #include "third_party/skia/include/core/SkBitmap.h"
38 #include "ui/gfx/geometry/rect_f.h"
41 class SingleThreadTaskRunner
;
45 class WebContentDecryptionModule
;
46 class WebContentDecryptionModuleResult
;
48 class WebMediaPlayerClient
;
64 class MediaPermission
;
65 class WebContentDecryptionModuleImpl
;
66 class WebMediaPlayerDelegate
;
71 class RendererCdmManager
;
72 class RendererMediaPlayerManager
;
74 // This class implements blink::WebMediaPlayer by keeping the android
75 // media player in the browser process. It listens to all the status changes
76 // sent from the browser process and sends playback controls to the media
78 class WebMediaPlayerAndroid
: public blink::WebMediaPlayer
,
79 public cc::VideoFrameProvider
,
80 public RenderFrameObserver
,
81 public StreamTextureFactoryContextObserver
{
83 // Construct a WebMediaPlayerAndroid object. This class communicates with the
84 // MediaPlayerAndroid object in the browser process through |proxy|.
85 // TODO(qinmin): |frame| argument is used to determine whether the current
86 // player can enter fullscreen. This logic should probably be moved into
87 // blink, so that enterFullscreen() will not be called if another video is
88 // already in fullscreen.
89 WebMediaPlayerAndroid(
90 blink::WebFrame
* frame
,
91 blink::WebMediaPlayerClient
* client
,
92 base::WeakPtr
<media::WebMediaPlayerDelegate
> delegate
,
93 RendererMediaPlayerManager
* player_manager
,
94 media::CdmFactory
* cdm_factory
,
95 media::MediaPermission
* media_permission
,
96 blink::WebContentDecryptionModule
* initial_cdm
,
97 scoped_refptr
<StreamTextureFactory
> factory
,
98 const scoped_refptr
<base::SingleThreadTaskRunner
>& task_runner
,
99 media::MediaLog
* media_log
);
100 virtual ~WebMediaPlayerAndroid();
102 // blink::WebMediaPlayer implementation.
103 virtual void enterFullscreen();
106 virtual void load(LoadType load_type
,
107 const blink::WebURL
& url
,
110 // Playback controls.
112 virtual void pause();
113 virtual void seek(double seconds
);
114 virtual bool supportsSave() const;
115 virtual void setRate(double rate
);
116 virtual void setVolume(double volume
);
117 virtual void setSinkId(const blink::WebString
& device_id
,
118 media::WebSetSinkIdCB
* raw_web_callbacks
);
119 virtual void requestRemotePlayback();
120 virtual void requestRemotePlaybackControl();
121 virtual blink::WebTimeRanges
buffered() const;
122 virtual blink::WebTimeRanges
seekable() const;
124 // Poster image, as defined in the <video> element.
125 virtual void setPoster(const blink::WebURL
& poster
) override
;
127 // Methods for painting.
128 // FIXME: This path "only works" on Android. It is a workaround for the
129 // issue that Skia could not handle Android's GL_TEXTURE_EXTERNAL_OES texture
130 // internally. It should be removed and replaced by the normal paint path.
131 // https://code.google.com/p/skia/issues/detail?id=1189
132 virtual void paint(blink::WebCanvas
* canvas
,
133 const blink::WebRect
& rect
,
135 SkXfermode::Mode mode
);
137 bool copyVideoTextureToPlatformTexture(
138 blink::WebGraphicsContext3D
* web_graphics_context
,
139 unsigned int texture
,
140 unsigned int internal_format
,
142 bool premultiply_alpha
,
143 bool flip_y
) override
;
145 // True if the loaded media has a playable video/audio track.
146 virtual bool hasVideo() const;
147 virtual bool hasAudio() const;
149 virtual bool isRemote() const;
151 // Dimensions of the video.
152 virtual blink::WebSize
naturalSize() const;
154 // Getters of playback state.
155 virtual bool paused() const;
156 virtual bool seeking() const;
157 virtual double duration() const;
158 virtual double timelineOffset() const;
159 virtual double currentTime() const;
161 virtual bool didLoadingProgress();
163 // Internal states of loading and network.
164 virtual blink::WebMediaPlayer::NetworkState
networkState() const;
165 virtual blink::WebMediaPlayer::ReadyState
readyState() const;
167 virtual bool hasSingleSecurityOrigin() const;
168 virtual bool didPassCORSAccessCheck() const;
170 virtual double mediaTimeForTimeValue(double timeValue
) const;
172 // Provide statistics.
173 virtual unsigned decodedFrameCount() const;
174 virtual unsigned droppedFrameCount() const;
175 virtual unsigned audioDecodedByteCount() const;
176 virtual unsigned videoDecodedByteCount() const;
178 // cc::VideoFrameProvider implementation. These methods are running on the
179 // compositor thread.
180 void SetVideoFrameProviderClient(
181 cc::VideoFrameProvider::Client
* client
) override
;
182 bool UpdateCurrentFrame(base::TimeTicks deadline_min
,
183 base::TimeTicks deadline_max
) override
;
184 bool HasCurrentFrame() override
;
185 scoped_refptr
<media::VideoFrame
> GetCurrentFrame() override
;
186 void PutCurrentFrame() override
;
188 // Media player callback handlers.
189 void OnMediaMetadataChanged(const base::TimeDelta
& duration
, int width
,
190 int height
, bool success
);
191 void OnPlaybackComplete();
192 void OnBufferingUpdate(int percentage
);
193 void OnSeekRequest(const base::TimeDelta
& time_to_seek
);
194 void OnSeekComplete(const base::TimeDelta
& current_time
);
195 void OnMediaError(int error_type
);
196 void OnVideoSizeChanged(int width
, int height
);
197 void OnDurationChanged(const base::TimeDelta
& duration
);
199 // Called to update the current time.
200 void OnTimeUpdate(base::TimeDelta current_timestamp
,
201 base::TimeTicks current_time_ticks
);
203 // Functions called when media player status changes.
204 void OnConnectedToRemoteDevice(const std::string
& remote_playback_message
);
205 void OnDisconnectedFromRemoteDevice();
206 void OnDidExitFullscreen();
207 void OnMediaPlayerPlay();
208 void OnMediaPlayerPause();
209 void OnRemoteRouteAvailabilityChanged(bool routes_available
);
211 // StreamTextureFactoryContextObserver implementation.
212 void ResetStreamTextureProxy() override
;
214 // Called when the player is released.
215 virtual void OnPlayerReleased();
217 // This function is called by the RendererMediaPlayerManager to pause the
218 // video and release the media player and surface texture when we switch tabs.
219 // However, the actual GlTexture is not released to keep the video screenshot.
220 virtual void ReleaseMediaResources();
222 // RenderFrameObserver implementation.
223 void OnDestruct() override
;
225 #if defined(VIDEO_HOLE)
226 // Calculate the boundary rectangle of the media player (i.e. location and
227 // size of the video frame).
228 // Returns true if the geometry has been changed since the last call.
229 bool UpdateBoundaryRectangle();
231 const gfx::RectF
GetBoundaryRectangle();
232 #endif // defined(VIDEO_HOLE)
234 virtual MediaKeyException
generateKeyRequest(
235 const blink::WebString
& key_system
,
236 const unsigned char* init_data
,
237 unsigned init_data_length
);
238 virtual MediaKeyException
addKey(
239 const blink::WebString
& key_system
,
240 const unsigned char* key
,
242 const unsigned char* init_data
,
243 unsigned init_data_length
,
244 const blink::WebString
& session_id
);
245 virtual MediaKeyException
cancelKeyRequest(
246 const blink::WebString
& key_system
,
247 const blink::WebString
& session_id
);
249 virtual void setContentDecryptionModule(
250 blink::WebContentDecryptionModule
* cdm
,
251 blink::WebContentDecryptionModuleResult result
);
253 void OnKeyAdded(const std::string
& session_id
);
254 void OnKeyError(const std::string
& session_id
,
255 media::MediaKeys::KeyError error_code
,
257 void OnKeyMessage(const std::string
& session_id
,
258 const std::vector
<uint8
>& message
,
259 const GURL
& destination_url
);
261 void OnMediaSourceOpened(blink::WebMediaSource
* web_media_source
);
263 void OnEncryptedMediaInitData(media::EmeInitDataType init_data_type
,
264 const std::vector
<uint8
>& init_data
);
266 // Called when a decoder detects that the key needed to decrypt the stream
268 void OnWaitingForDecryptionKey();
271 // Helper method to update the playing state.
272 void UpdatePlayingState(bool is_playing_
);
274 // Helper methods for posting task for setting states and update WebKit.
275 void UpdateNetworkState(blink::WebMediaPlayer::NetworkState state
);
276 void UpdateReadyState(blink::WebMediaPlayer::ReadyState state
);
277 void TryCreateStreamTextureProxyIfNeeded();
278 void DoCreateStreamTexture();
280 // Helper method to reestablish the surface texture peer for android
282 void EstablishSurfaceTexturePeer();
284 // Requesting whether the surface texture peer needs to be reestablished.
285 void SetNeedsEstablishPeer(bool needs_establish_peer
);
288 void InitializePlayer(const GURL
& url
,
289 const GURL
& first_party_for_cookies
,
290 bool allowed_stored_credentials
,
291 int demuxer_client_id
);
292 void Pause(bool is_media_related_action
);
293 void DrawRemotePlaybackText(const std::string
& remote_playback_message
);
294 void ReallocateVideoFrame();
295 void SetCurrentFrameInternal(scoped_refptr
<media::VideoFrame
>& frame
);
296 void RemoveSurfaceTextureAndProxy();
297 void DidLoadMediaInfo(MediaInfoLoader::Status status
,
298 const GURL
& redirected_url
,
299 const GURL
& first_party_for_cookies
,
300 bool allow_stored_credentials
);
301 bool IsKeySystemSupported(const std::string
& key_system
);
302 bool IsLocalResource();
304 // Actually do the work for generateKeyRequest/addKey so they can easily
305 // report results to UMA.
306 MediaKeyException
GenerateKeyRequestInternal(const std::string
& key_system
,
307 const unsigned char* init_data
,
308 unsigned init_data_length
);
309 MediaKeyException
AddKeyInternal(const std::string
& key_system
,
310 const unsigned char* key
,
312 const unsigned char* init_data
,
313 unsigned init_data_length
,
314 const std::string
& session_id
);
315 MediaKeyException
CancelKeyRequestInternal(const std::string
& key_system
,
316 const std::string
& session_id
);
318 // Called when |cdm_context| is ready.
319 void OnCdmContextReady(media::CdmContext
* cdm_context
);
321 // Sets the CDM. Should only be called when |is_player_initialized_| is true
322 // and a new non-null |cdm_context_| is available. Fires |cdm_attached_cb_|
323 // with the result after the CDM is attached.
324 void SetCdmInternal(const media::CdmAttachedCB
& cdm_attached_cb
);
326 // Requests that this object notifies when a decryptor is ready through the
327 // |decryptor_ready_cb| provided.
328 // If |decryptor_ready_cb| is null, the existing callback will be fired with
329 // NULL immediately and reset.
330 void SetDecryptorReadyCB(const media::DecryptorReadyCB
& decryptor_ready_cb
);
332 // Called when the ContentDecryptionModule has been attached to the
333 // pipeline/decoders.
334 void ContentDecryptionModuleAttached(
335 blink::WebContentDecryptionModuleResult result
,
338 bool IsHLSStream() const;
340 blink::WebFrame
* const frame_
;
342 blink::WebMediaPlayerClient
* const client_
;
344 // |delegate_| is used to notify the browser process of the player status, so
345 // that the browser process can control screen locks.
346 // TODO(qinmin): Currently android mediaplayer takes care of the screen
347 // lock. So this is only used for media source. Will apply this to regular
348 // media tag once http://crbug.com/247892 is fixed.
349 base::WeakPtr
<media::WebMediaPlayerDelegate
> delegate_
;
351 // Save the list of buffered time ranges.
352 blink::WebTimeRanges buffered_
;
354 // Size of the video.
355 blink::WebSize natural_size_
;
357 // Size that has been sent to StreamTexture.
358 blink::WebSize cached_stream_texture_size_
;
360 // The video frame object used for rendering by the compositor.
361 scoped_refptr
<media::VideoFrame
> current_frame_
;
362 base::Lock current_frame_lock_
;
364 base::ThreadChecker main_thread_checker_
;
366 // Message loop for media thread.
367 const scoped_refptr
<base::SingleThreadTaskRunner
> media_task_runner_
;
369 // URL of the media file to be fetched.
372 // URL of the media file after |media_info_loader_| resolves all the
374 GURL redirected_url_
;
377 base::TimeDelta duration_
;
379 // Flag to remember if we have a trusted duration_ value provided by
380 // MediaSourceDelegate notifying OnDurationChanged(). In this case, ignore
381 // any subsequent duration value passed to OnMediaMetadataChange().
382 bool ignore_metadata_duration_change_
;
384 // Seek gets pending if another seek is in progress. Only last pending seek
387 base::TimeDelta pending_seek_time_
;
389 // Internal seek state.
391 base::TimeDelta seek_time_
;
393 // Whether loading has progressed since the last call to didLoadingProgress.
394 bool did_loading_progress_
;
396 // Manages this object and delegates player calls to the browser process.
397 // Owned by RenderFrameImpl.
398 RendererMediaPlayerManager
* const player_manager_
;
400 // TODO(xhwang): Remove |cdm_factory_| when prefixed EME is deprecated. See
401 // http://crbug.com/249976
402 media::CdmFactory
* const cdm_factory_
;
404 media::MediaPermission
* media_permission_
;
406 // Player ID assigned by the |player_manager_|.
409 // Current player states.
410 blink::WebMediaPlayer::NetworkState network_state_
;
411 blink::WebMediaPlayer::ReadyState ready_state_
;
413 // GL texture ID allocated to the video.
414 unsigned int texture_id_
;
416 // GL texture mailbox for texture_id_ to provide in the VideoFrame, and sync
417 // point for when the mailbox was produced.
418 gpu::Mailbox texture_mailbox_
;
420 // Stream texture ID allocated to the video.
421 unsigned int stream_id_
;
423 // Whether the media player has been initialized.
424 bool is_player_initialized_
;
426 // Whether the media player is playing.
429 // Whether media player needs to re-establish the surface texture peer.
430 bool needs_establish_peer_
;
432 // Whether the video size info is available.
435 const scoped_refptr
<base::SingleThreadTaskRunner
> compositor_loop_
;
437 // Object for allocating stream textures.
438 scoped_refptr
<StreamTextureFactory
> stream_texture_factory_
;
440 // Object for calling back the compositor thread to repaint the video when a
441 // frame available. It should be initialized on the compositor thread.
442 // Accessed on main thread and on compositor thread when main thread is
444 ScopedStreamTextureProxy stream_texture_proxy_
;
446 // Whether media player needs external surface.
447 // Only used for the VIDEO_HOLE logic.
448 bool needs_external_surface_
;
450 // Whether the player is in fullscreen.
453 // A pointer back to the compositor to inform it about state changes. This is
454 // not NULL while the compositor is actively using this webmediaplayer.
455 // Accessed on main thread and on compositor thread when main thread is
457 cc::VideoFrameProvider::Client
* video_frame_provider_client_
;
459 scoped_ptr
<cc_blink::WebLayerImpl
> video_weblayer_
;
461 #if defined(VIDEO_HOLE)
462 // A rectangle represents the geometry of video frame, when computed last
464 gfx::RectF last_computed_rect_
;
466 // Whether to use the video overlay for all embedded video.
467 // True only for testing.
468 bool force_use_overlay_embedded_video_
;
469 #endif // defined(VIDEO_HOLE)
471 MediaPlayerHostMsg_Initialize_Type player_type_
;
473 // Whether the browser is currently connected to a remote media player.
476 scoped_refptr
<media::MediaLog
> media_log_
;
478 scoped_ptr
<MediaInfoLoader
> info_loader_
;
480 // The currently selected key system. Empty string means that no key system
481 // has been selected.
482 std::string current_key_system_
;
484 // Temporary for EME v0.1. Not needed for unprefixed EME, and can be removed
485 // when prefixed EME is removed.
486 media::EmeInitDataType init_data_type_
;
488 // Manages decryption keys and decrypts encrypted frames.
489 scoped_ptr
<media::ProxyDecryptor
> proxy_decryptor_
;
491 // Non-owned pointer to the CdmContext. Updated in the constructor,
492 // generateKeyRequest() or setContentDecryptionModule().
493 media::CdmContext
* cdm_context_
;
495 // This is only Used by Clear Key key system implementation, where a renderer
496 // side CDM will be used. This is similar to WebMediaPlayerImpl. For other key
497 // systems, a browser side CDM will be used and we set CDM by calling
498 // player_manager_->SetCdm() directly.
499 media::DecryptorReadyCB decryptor_ready_cb_
;
503 // Whether stored credentials are allowed to be passed to the server.
504 bool allow_stored_credentials_
;
506 // Whether the resource is local.
507 bool is_local_resource_
;
509 // base::TickClock used by |interpolator_|.
510 base::DefaultTickClock default_tick_clock_
;
512 // Tracks the most recent media time update and provides interpolated values
513 // as playback progresses.
514 media::TimeDeltaInterpolator interpolator_
;
516 scoped_ptr
<MediaSourceDelegate
> media_source_delegate_
;
518 // NOTE: Weak pointers must be invalidated before all other member variables.
519 base::WeakPtrFactory
<WebMediaPlayerAndroid
> weak_factory_
;
521 DISALLOW_COPY_AND_ASSIGN(WebMediaPlayerAndroid
);
524 } // namespace content
526 #endif // CONTENT_RENDERER_MEDIA_ANDROID_WEBMEDIAPLAYER_ANDROID_H_