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 "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"
41 class SingleThreadTaskRunner;
45 class WebContentDecryptionModule;
46 class WebContentDecryptionModuleResult;
61 class WebMediaPlayerDelegate;
65 class RendererCdmManager;
66 class RendererMediaPlayerManager;
67 class WebContentDecryptionModuleImpl;
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
73 class WebMediaPlayerAndroid : public blink::WebMediaPlayer,
74 public cc::VideoFrameProvider,
75 public RenderFrameObserver,
76 public StreamTextureFactoryContextObserver {
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();
96 // blink::WebMediaPlayer implementation.
97 virtual void enterFullscreen();
98 virtual bool canEnterFullscreen() const;
101 virtual void load(LoadType load_type,
102 const blink::WebURL& url,
105 // Playback controls.
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;
117 // Poster image, as defined in the <video> element.
118 virtual void setPoster(const blink::WebURL& poster) override;
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,
128 SkXfermode::Mode mode);
130 virtual bool copyVideoTextureToPlatformTexture(
131 blink::WebGraphicsContext3D* web_graphics_context,
132 unsigned int texture,
134 unsigned int internal_format,
136 bool premultiply_alpha,
139 // True if the loaded media has a playable video/audio track.
140 virtual bool hasVideo() const;
141 virtual bool hasAudio() const;
143 virtual bool isRemote() const;
145 // Dimensions of the video.
146 virtual blink::WebSize naturalSize() const;
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;
155 virtual bool didLoadingProgress();
157 // Internal states of loading and network.
158 virtual blink::WebMediaPlayer::NetworkState networkState() const;
159 virtual blink::WebMediaPlayer::ReadyState readyState() const;
161 virtual bool hasSingleSecurityOrigin() const;
162 virtual bool didPassCORSAccessCheck() const;
164 virtual double mediaTimeForTimeValue(double timeValue) const;
166 // Provide statistics.
167 virtual unsigned decodedFrameCount() const;
168 virtual unsigned droppedFrameCount() const;
169 virtual unsigned audioDecodedByteCount() const;
170 virtual unsigned videoDecodedByteCount() const;
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)
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);
191 // Called to update the current time.
192 void OnTimeUpdate(base::TimeDelta current_timestamp,
193 base::TimeTicks current_time_ticks);
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);
205 // StreamTextureFactoryContextObserver implementation.
206 virtual void ResetStreamTextureProxy() override;
208 // Called when the player is released.
209 virtual void OnPlayerReleased();
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();
216 // RenderFrameObserver implementation.
217 virtual void OnDestruct() override;
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();
225 const gfx::RectF GetBoundaryRectangle();
226 #endif // defined(VIDEO_HOLE)
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,
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
244 virtual void setContentDecryptionModule(
245 blink::WebContentDecryptionModule* cdm);
246 virtual void setContentDecryptionModule(
247 blink::WebContentDecryptionModule* cdm,
248 blink::WebContentDecryptionModuleResult result);
250 void OnKeyAdded(const std::string& session_id);
251 void OnKeyError(const std::string& session_id,
252 media::MediaKeys::KeyError error_code,
254 void OnKeyMessage(const std::string& session_id,
255 const std::vector<uint8>& message,
256 const GURL& destination_url);
258 void OnMediaSourceOpened(blink::WebMediaSource* web_media_source);
260 void OnNeedKey(const std::string& type,
261 const std::vector<uint8>& init_data);
263 // TODO(xhwang): Implement WebMediaPlayer::setContentDecryptionModule().
264 // See: http://crbug.com/224786
267 // Helper method to update the playing state.
268 void UpdatePlayingState(bool is_playing_);
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();
276 // Helper method to reestablish the surface texture peer for android
278 void EstablishSurfaceTexturePeer();
280 // Requesting whether the surface texture peer needs to be reestablished.
281 void SetNeedsEstablishPeer(bool needs_establish_peer);
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();
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,
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);
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,
325 bool EnsureTextureBackedSkBitmap(GrContext* gr, SkBitmap& bitmap,
326 const blink::WebSize& size,
327 GrSurfaceOrigin origin,
328 GrPixelConfig config);
330 bool IsHLSStream() const;
332 blink::WebFrame* const frame_;
334 blink::WebMediaPlayerClient* const client_;
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_;
343 // Save the list of buffered time ranges.
344 blink::WebTimeRanges buffered_;
346 // Size of the video.
347 blink::WebSize natural_size_;
349 // Size that has been sent to StreamTexture.
350 blink::WebSize cached_stream_texture_size_;
352 // The video frame object used for rendering by the compositor.
353 scoped_refptr<media::VideoFrame> current_frame_;
354 base::Lock current_frame_lock_;
356 base::ThreadChecker main_thread_checker_;
358 // Message loop for media thread.
359 const scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;
361 // URL of the media file to be fetched.
364 // URL of the media file after |media_info_loader_| resolves all the
366 GURL redirected_url_;
369 base::TimeDelta duration_;
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_;
376 // Seek gets pending if another seek is in progress. Only last pending seek
379 base::TimeDelta pending_seek_time_;
381 // Internal seek state.
383 base::TimeDelta seek_time_;
385 // Whether loading has progressed since the last call to didLoadingProgress.
386 bool did_loading_progress_;
388 // Manages this object and delegates player calls to the browser process.
389 // Owned by RenderFrameImpl.
390 RendererMediaPlayerManager* player_manager_;
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_;
397 // Player ID assigned by the |player_manager_|.
400 // Current player states.
401 blink::WebMediaPlayer::NetworkState network_state_;
402 blink::WebMediaPlayer::ReadyState ready_state_;
404 // GL texture ID allocated to the video.
405 unsigned int texture_id_;
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_;
411 // Stream texture ID allocated to the video.
412 unsigned int stream_id_;
414 // Whether the mediaplayer 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.
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
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 // 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
442 cc::VideoFrameProvider::Client* video_frame_provider_client_;
444 scoped_ptr<cc_blink::WebLayerImpl> video_weblayer_;
446 #if defined(VIDEO_HOLE)
447 // A rectangle represents the geometry of video frame, when computed last
449 gfx::RectF last_computed_rect_;
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)
456 MediaPlayerHostMsg_Initialize_Type player_type_;
458 // Whether the browser is currently connected to a remote media player.
461 scoped_refptr<media::MediaLog> media_log_;
463 scoped_ptr<MediaInfoLoader> info_loader_;
465 // The currently selected key system. Empty string means that no key system
466 // has been selected.
467 std::string current_key_system_;
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_;
473 // Manages decryption keys and decrypts encrypted frames.
474 scoped_ptr<ProxyDecryptor> proxy_decryptor_;
476 // Non-owned pointer to the CDM. Updated via calls to
477 // setContentDecryptionModule().
478 WebContentDecryptionModuleImpl* web_cdm_;
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_;
488 // Whether stored credentials are allowed to be passed to the server.
489 bool allow_stored_credentials_;
491 // Whether the resource is local.
492 bool is_local_resource_;
494 // base::TickClock used by |interpolator_|.
495 base::DefaultTickClock default_tick_clock_;
497 // Tracks the most recent media time update and provides interpolated values
498 // as playback progresses.
499 media::TimeDeltaInterpolator interpolator_;
501 scoped_ptr<MediaSourceDelegate> media_source_delegate_;
503 // NOTE: Weak pointers must be invalidated before all other member variables.
504 base::WeakPtrFactory<WebMediaPlayerAndroid> weak_factory_;
506 DISALLOW_COPY_AND_ASSIGN(WebMediaPlayerAndroid);
509 } // namespace content
511 #endif // CONTENT_RENDERER_MEDIA_ANDROID_WEBMEDIAPLAYER_ANDROID_H_