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