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