Ozone: Keep the native pixmap alive till gl_image is destroyed
[chromium-blink-merge.git] / media / blink / webmediaplayer_impl.h
blob6fc7738e92167c2db24365a192fede8128ab2dd3
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 MEDIA_BLINK_WEBMEDIAPLAYER_IMPL_H_
6 #define MEDIA_BLINK_WEBMEDIAPLAYER_IMPL_H_
8 #include <string>
9 #include <vector>
11 #include "base/basictypes.h"
12 #include "base/compiler_specific.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.h"
17 #include "media/base/cdm_factory.h"
18 #include "media/base/media_export.h"
19 #include "media/base/pipeline.h"
20 #include "media/base/renderer_factory.h"
21 #include "media/base/text_track.h"
22 #include "media/blink/buffered_data_source.h"
23 #include "media/blink/buffered_data_source_host_impl.h"
24 #include "media/blink/encrypted_media_player_support.h"
25 #include "media/blink/skcanvas_video_renderer.h"
26 #include "media/blink/video_frame_compositor.h"
27 #include "media/blink/webmediaplayer_params.h"
28 #include "media/blink/webmediaplayer_util.h"
29 #include "third_party/WebKit/public/platform/WebAudioSourceProvider.h"
30 #include "third_party/WebKit/public/platform/WebContentDecryptionModuleResult.h"
31 #include "third_party/WebKit/public/platform/WebMediaPlayer.h"
32 #include "url/gurl.h"
34 namespace blink {
35 class WebGraphicsContext3D;
36 class WebLocalFrame;
37 class WebMediaPlayerClient;
38 class WebMediaPlayerEncryptedMediaClient;
41 namespace base {
42 class SingleThreadTaskRunner;
45 namespace cc_blink {
46 class WebLayerImpl;
49 namespace media {
51 class AudioHardwareConfig;
52 class ChunkDemuxer;
53 class GpuVideoAcceleratorFactories;
54 class MediaLog;
55 class VideoFrameCompositor;
56 class WebAudioSourceProviderImpl;
57 class WebMediaPlayerDelegate;
58 class WebTextTrackImpl;
60 // The canonical implementation of blink::WebMediaPlayer that's backed by
61 // Pipeline. Handles normal resource loading, Media Source, and
62 // Encrypted Media.
63 class MEDIA_EXPORT WebMediaPlayerImpl
64 : public NON_EXPORTED_BASE(blink::WebMediaPlayer),
65 public base::SupportsWeakPtr<WebMediaPlayerImpl> {
66 public:
67 // Constructs a WebMediaPlayer implementation using Chromium's media stack.
68 // |delegate| may be null. |renderer| may also be null, in which case an
69 // internal renderer will be created.
70 // TODO(xhwang): Drop the internal renderer path and always pass in a renderer
71 // here.
72 WebMediaPlayerImpl(
73 blink::WebLocalFrame* frame,
74 blink::WebMediaPlayerClient* client,
75 blink::WebMediaPlayerEncryptedMediaClient* encrypted_client,
76 base::WeakPtr<WebMediaPlayerDelegate> delegate,
77 scoped_ptr<RendererFactory> renderer_factory,
78 CdmFactory* cdm_factory,
79 const WebMediaPlayerParams& params);
80 virtual ~WebMediaPlayerImpl();
82 virtual void load(LoadType load_type,
83 const blink::WebURL& url,
84 CORSMode cors_mode);
86 // Playback controls.
87 virtual void play();
88 virtual void pause();
89 virtual bool supportsSave() const;
90 virtual void seek(double seconds);
91 virtual void setRate(double rate);
92 virtual void setVolume(double volume);
93 virtual void setSinkId(const blink::WebString& device_id,
94 WebSetSinkIdCB* web_callbacks);
95 virtual void setPreload(blink::WebMediaPlayer::Preload preload);
96 virtual blink::WebTimeRanges buffered() const;
97 virtual blink::WebTimeRanges seekable() const;
99 // Methods for painting.
100 virtual void paint(blink::WebCanvas* canvas,
101 const blink::WebRect& rect,
102 unsigned char alpha,
103 SkXfermode::Mode mode);
105 // True if the loaded media has a playable video/audio track.
106 virtual bool hasVideo() const;
107 virtual bool hasAudio() const;
109 // Dimensions of the video.
110 virtual blink::WebSize naturalSize() const;
112 // Getters of playback state.
113 virtual bool paused() const;
114 virtual bool seeking() const;
115 virtual double duration() const;
116 virtual double timelineOffset() const;
117 virtual double currentTime() const;
119 // Internal states of loading and network.
120 // TODO(hclam): Ask the pipeline about the state rather than having reading
121 // them from members which would cause race conditions.
122 virtual blink::WebMediaPlayer::NetworkState networkState() const;
123 virtual blink::WebMediaPlayer::ReadyState readyState() const;
125 virtual bool didLoadingProgress();
127 virtual bool hasSingleSecurityOrigin() const;
128 virtual bool didPassCORSAccessCheck() const;
130 virtual double mediaTimeForTimeValue(double timeValue) const;
132 virtual unsigned decodedFrameCount() const;
133 virtual unsigned droppedFrameCount() const;
134 virtual unsigned audioDecodedByteCount() const;
135 virtual unsigned videoDecodedByteCount() const;
137 bool copyVideoTextureToPlatformTexture(
138 blink::WebGraphicsContext3D* web_graphics_context,
139 unsigned int texture,
140 unsigned int internal_format,
141 unsigned int type,
142 bool premultiply_alpha,
143 bool flip_y) override;
145 virtual blink::WebAudioSourceProvider* audioSourceProvider();
147 virtual MediaKeyException generateKeyRequest(
148 const blink::WebString& key_system,
149 const unsigned char* init_data,
150 unsigned init_data_length);
152 virtual MediaKeyException addKey(const blink::WebString& key_system,
153 const unsigned char* key,
154 unsigned key_length,
155 const unsigned char* init_data,
156 unsigned init_data_length,
157 const blink::WebString& session_id);
159 virtual MediaKeyException cancelKeyRequest(
160 const blink::WebString& key_system,
161 const blink::WebString& session_id);
163 virtual void setContentDecryptionModule(
164 blink::WebContentDecryptionModule* cdm,
165 blink::WebContentDecryptionModuleResult result);
167 void OnPipelineSeeked(bool time_changed, PipelineStatus status);
168 void OnPipelineEnded();
169 void OnPipelineError(PipelineStatus error);
170 void OnPipelineMetadata(PipelineMetadata metadata);
171 void OnPipelineBufferingStateChanged(BufferingState buffering_state);
172 void OnDemuxerOpened();
173 void OnAddTextTrack(const TextTrackConfig& config,
174 const AddTextTrackDoneCB& done_cb);
176 private:
177 // Called after |defer_load_cb_| has decided to allow the load. If
178 // |defer_load_cb_| is null this is called immediately.
179 void DoLoad(LoadType load_type,
180 const blink::WebURL& url,
181 CORSMode cors_mode);
183 // Called after asynchronous initialization of a data source completed.
184 void DataSourceInitialized(bool success);
186 // Called when the data source is downloading or paused.
187 void NotifyDownloading(bool is_downloading);
189 // Creates a Renderer that will be used by the |pipeline_|.
190 scoped_ptr<Renderer> CreateRenderer();
192 // Finishes starting the pipeline due to a call to load().
193 void StartPipeline();
195 // Helpers that set the network/ready state and notifies the client if
196 // they've changed.
197 void SetNetworkState(blink::WebMediaPlayer::NetworkState state);
198 void SetReadyState(blink::WebMediaPlayer::ReadyState state);
200 // Gets the duration value reported by the pipeline.
201 double GetPipelineDuration() const;
203 // Callbacks from |pipeline_| that are forwarded to |client_|.
204 void OnDurationChanged();
205 void OnNaturalSizeChanged(gfx::Size size);
206 void OnOpacityChanged(bool opaque);
208 // Called by VideoRendererImpl on its internal thread with the new frame to be
209 // painted.
210 void FrameReady(const scoped_refptr<VideoFrame>& frame);
212 // Returns the current video frame from |compositor_|. Blocks until the
213 // compositor can return the frame.
214 scoped_refptr<VideoFrame> GetCurrentFrameFromCompositor();
216 // Called when the demuxer encounters encrypted streams.
217 void OnEncryptedMediaInitData(EmeInitDataType init_data_type,
218 const std::vector<uint8>& init_data);
220 // Called when a decoder detects that the key needed to decrypt the stream
221 // is not available.
222 void OnWaitingForDecryptionKey();
224 // Sets |cdm_context| on the pipeline and fires |cdm_attached_cb| when done.
225 // Parameter order is reversed for easy binding.
226 void SetCdm(const CdmAttachedCB& cdm_attached_cb, CdmContext* cdm_context);
228 // Called when a CDM has been attached to the |pipeline_|.
229 void OnCdmAttached(bool success);
231 // Updates |paused_time_| to the current media time with consideration for the
232 // |ended_| state by clamping current time to duration upon |ended_|.
233 void UpdatePausedTime();
235 blink::WebLocalFrame* frame_;
237 // TODO(hclam): get rid of these members and read from the pipeline directly.
238 blink::WebMediaPlayer::NetworkState network_state_;
239 blink::WebMediaPlayer::ReadyState ready_state_;
241 // Preload state for when |data_source_| is created after setPreload().
242 BufferedDataSource::Preload preload_;
244 // Task runner for posting tasks on Chrome's main thread. Also used
245 // for DCHECKs so methods calls won't execute in the wrong thread.
246 const scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
248 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;
249 scoped_refptr<MediaLog> media_log_;
250 Pipeline pipeline_;
252 // The LoadType passed in the |load_type| parameter of the load() call.
253 LoadType load_type_;
255 // Cache of metadata for answering hasAudio(), hasVideo(), and naturalSize().
256 PipelineMetadata pipeline_metadata_;
258 // Whether the video is known to be opaque or not.
259 bool opaque_;
261 // Playback state.
263 // TODO(scherkus): we have these because Pipeline favours the simplicity of a
264 // single "playback rate" over worrying about paused/stopped etc... It forces
265 // all clients to manage the pause+playback rate externally, but is that
266 // really a bad thing?
268 // TODO(scherkus): since SetPlaybackRate(0) is asynchronous and we don't want
269 // to hang the render thread during pause(), we record the time at the same
270 // time we pause and then return that value in currentTime(). Otherwise our
271 // clock can creep forward a little bit while the asynchronous
272 // SetPlaybackRate(0) is being executed.
273 double playback_rate_;
274 bool paused_;
275 base::TimeDelta paused_time_;
276 bool seeking_;
277 base::TimeDelta seek_time_; // Meaningless when |seeking_| is false.
279 // TODO(scherkus): Replace with an explicit ended signal to HTMLMediaElement,
280 // see http://crbug.com/409280
281 bool ended_;
283 // Seek gets pending if another seek is in progress. Only last pending seek
284 // will have effect.
285 bool pending_seek_;
286 // |pending_seek_time_| is meaningless when |pending_seek_| is false.
287 base::TimeDelta pending_seek_time_;
289 // Tracks whether to issue time changed notifications during buffering state
290 // changes.
291 bool should_notify_time_changed_;
293 blink::WebMediaPlayerClient* client_;
294 blink::WebMediaPlayerEncryptedMediaClient* encrypted_client_;
296 base::WeakPtr<WebMediaPlayerDelegate> delegate_;
298 WebMediaPlayerParams::DeferLoadCB defer_load_cb_;
299 WebMediaPlayerParams::Context3DCB context_3d_cb_;
301 // Routes audio playback to either AudioRendererSink or WebAudio.
302 scoped_refptr<WebAudioSourceProviderImpl> audio_source_provider_;
304 bool supports_save_;
306 // These two are mutually exclusive:
307 // |data_source_| is used for regular resource loads.
308 // |chunk_demuxer_| is used for Media Source resource loads.
310 // |demuxer_| will contain the appropriate demuxer based on which resource
311 // load strategy we're using.
312 scoped_ptr<BufferedDataSource> data_source_;
313 scoped_ptr<Demuxer> demuxer_;
314 ChunkDemuxer* chunk_demuxer_;
316 BufferedDataSourceHostImpl buffered_data_source_host_;
318 // Video rendering members.
319 scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner_;
320 VideoFrameCompositor* compositor_; // Deleted on |compositor_task_runner_|.
321 SkCanvasVideoRenderer skcanvas_video_renderer_;
323 // The compositor layer for displaying the video content when using composited
324 // playback.
325 scoped_ptr<cc_blink::WebLayerImpl> video_weblayer_;
327 EncryptedMediaPlayerSupport encrypted_media_support_;
329 scoped_ptr<blink::WebContentDecryptionModuleResult> set_cdm_result_;
331 scoped_ptr<RendererFactory> renderer_factory_;
333 DISALLOW_COPY_AND_ASSIGN(WebMediaPlayerImpl);
336 } // namespace media
338 #endif // MEDIA_BLINK_WEBMEDIAPLAYER_IMPL_H_