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_
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 "third_party/WebKit/public/platform/WebMediaPlayerClient.h"
36 class WebGraphicsContext3D
;
41 class SingleThreadTaskRunner
;
50 class AudioHardwareConfig
;
52 class GpuVideoAcceleratorFactories
;
54 class VideoFrameCompositor
;
55 class WebAudioSourceProviderImpl
;
56 class WebMediaPlayerDelegate
;
57 class WebTextTrackImpl
;
59 // The canonical implementation of blink::WebMediaPlayer that's backed by
60 // Pipeline. Handles normal resource loading, Media Source, and
62 class MEDIA_EXPORT WebMediaPlayerImpl
63 : public NON_EXPORTED_BASE(blink::WebMediaPlayer
),
64 public base::SupportsWeakPtr
<WebMediaPlayerImpl
> {
66 // Constructs a WebMediaPlayer implementation using Chromium's media stack.
67 // |delegate| may be null. |renderer| may also be null, in which case an
68 // internal renderer will be created.
69 // TODO(xhwang): Drop the internal renderer path and always pass in a renderer
71 WebMediaPlayerImpl(blink::WebLocalFrame
* frame
,
72 blink::WebMediaPlayerClient
* client
,
73 base::WeakPtr
<WebMediaPlayerDelegate
> delegate
,
74 scoped_ptr
<RendererFactory
> renderer_factory
,
75 CdmFactory
* cdm_factory
,
76 const WebMediaPlayerParams
& params
);
77 virtual ~WebMediaPlayerImpl();
79 virtual void load(LoadType load_type
,
80 const blink::WebURL
& url
,
86 virtual bool supportsSave() const;
87 virtual void seek(double seconds
);
88 virtual void setRate(double rate
);
89 virtual void setVolume(double volume
);
90 virtual void setSinkId(const blink::WebString
& device_id
,
91 WebSetSinkIdCB
* web_callbacks
);
92 virtual void setPreload(blink::WebMediaPlayer::Preload preload
);
93 virtual blink::WebTimeRanges
buffered() const;
94 virtual blink::WebTimeRanges
seekable() const;
96 // Methods for painting.
97 virtual void paint(blink::WebCanvas
* canvas
,
98 const blink::WebRect
& rect
,
100 SkXfermode::Mode mode
);
102 // True if the loaded media has a playable video/audio track.
103 virtual bool hasVideo() const;
104 virtual bool hasAudio() const;
106 // Dimensions of the video.
107 virtual blink::WebSize
naturalSize() const;
109 // Getters of playback state.
110 virtual bool paused() const;
111 virtual bool seeking() const;
112 virtual double duration() const;
113 virtual double timelineOffset() const;
114 virtual double currentTime() const;
116 // Internal states of loading and network.
117 // TODO(hclam): Ask the pipeline about the state rather than having reading
118 // them from members which would cause race conditions.
119 virtual blink::WebMediaPlayer::NetworkState
networkState() const;
120 virtual blink::WebMediaPlayer::ReadyState
readyState() const;
122 virtual bool didLoadingProgress();
124 virtual bool hasSingleSecurityOrigin() const;
125 virtual bool didPassCORSAccessCheck() const;
127 virtual double mediaTimeForTimeValue(double timeValue
) const;
129 virtual unsigned decodedFrameCount() const;
130 virtual unsigned droppedFrameCount() const;
131 virtual unsigned audioDecodedByteCount() const;
132 virtual unsigned videoDecodedByteCount() const;
134 bool copyVideoTextureToPlatformTexture(
135 blink::WebGraphicsContext3D
* web_graphics_context
,
136 unsigned int texture
,
137 unsigned int internal_format
,
139 bool premultiply_alpha
,
140 bool flip_y
) override
;
142 virtual blink::WebAudioSourceProvider
* audioSourceProvider();
144 virtual MediaKeyException
generateKeyRequest(
145 const blink::WebString
& key_system
,
146 const unsigned char* init_data
,
147 unsigned init_data_length
);
149 virtual MediaKeyException
addKey(const blink::WebString
& key_system
,
150 const unsigned char* key
,
152 const unsigned char* init_data
,
153 unsigned init_data_length
,
154 const blink::WebString
& session_id
);
156 virtual MediaKeyException
cancelKeyRequest(
157 const blink::WebString
& key_system
,
158 const blink::WebString
& session_id
);
160 virtual void setContentDecryptionModule(
161 blink::WebContentDecryptionModule
* cdm
,
162 blink::WebContentDecryptionModuleResult result
);
164 void OnPipelineSeeked(bool time_changed
, PipelineStatus status
);
165 void OnPipelineEnded();
166 void OnPipelineError(PipelineStatus error
);
167 void OnPipelineMetadata(PipelineMetadata metadata
);
168 void OnPipelineBufferingStateChanged(BufferingState buffering_state
);
169 void OnDemuxerOpened();
170 void OnAddTextTrack(const TextTrackConfig
& config
,
171 const AddTextTrackDoneCB
& done_cb
);
174 // Called after |defer_load_cb_| has decided to allow the load. If
175 // |defer_load_cb_| is null this is called immediately.
176 void DoLoad(LoadType load_type
,
177 const blink::WebURL
& url
,
180 // Called after asynchronous initialization of a data source completed.
181 void DataSourceInitialized(bool success
);
183 // Called when the data source is downloading or paused.
184 void NotifyDownloading(bool is_downloading
);
186 // Creates a Renderer that will be used by the |pipeline_|.
187 scoped_ptr
<Renderer
> CreateRenderer();
189 // Finishes starting the pipeline due to a call to load().
190 void StartPipeline();
192 // Helpers that set the network/ready state and notifies the client if
194 void SetNetworkState(blink::WebMediaPlayer::NetworkState state
);
195 void SetReadyState(blink::WebMediaPlayer::ReadyState state
);
197 // Gets the duration value reported by the pipeline.
198 double GetPipelineDuration() const;
200 // Callbacks from |pipeline_| that are forwarded to |client_|.
201 void OnDurationChanged();
202 void OnNaturalSizeChanged(gfx::Size size
);
203 void OnOpacityChanged(bool opaque
);
205 // Called by VideoRendererImpl on its internal thread with the new frame to be
207 void FrameReady(const scoped_refptr
<VideoFrame
>& frame
);
209 // Returns the current video frame from |compositor_|. Blocks until the
210 // compositor can return the frame.
211 scoped_refptr
<VideoFrame
> GetCurrentFrameFromCompositor();
213 // Called when the demuxer encounters encrypted streams.
214 void OnEncryptedMediaInitData(EmeInitDataType init_data_type
,
215 const std::vector
<uint8
>& init_data
);
217 // Called when a decoder detects that the key needed to decrypt the stream
219 void OnWaitingForDecryptionKey();
221 // Sets |cdm_context| on the pipeline and fires |cdm_attached_cb| when done.
222 // Parameter order is reversed for easy binding.
223 void SetCdm(const CdmAttachedCB
& cdm_attached_cb
, CdmContext
* cdm_context
);
225 // Called when a CDM has been attached to the |pipeline_|.
226 void OnCdmAttached(blink::WebContentDecryptionModuleResult result
,
229 // Updates |paused_time_| to the current media time with consideration for the
230 // |ended_| state by clamping current time to duration upon |ended_|.
231 void UpdatePausedTime();
233 blink::WebLocalFrame
* frame_
;
235 // TODO(hclam): get rid of these members and read from the pipeline directly.
236 blink::WebMediaPlayer::NetworkState network_state_
;
237 blink::WebMediaPlayer::ReadyState ready_state_
;
239 // Preload state for when |data_source_| is created after setPreload().
240 BufferedDataSource::Preload preload_
;
242 // Task runner for posting tasks on Chrome's main thread. Also used
243 // for DCHECKs so methods calls won't execute in the wrong thread.
244 const scoped_refptr
<base::SingleThreadTaskRunner
> main_task_runner_
;
246 scoped_refptr
<base::SingleThreadTaskRunner
> media_task_runner_
;
247 scoped_refptr
<MediaLog
> media_log_
;
250 // The LoadType passed in the |load_type| parameter of the load() call.
253 // Cache of metadata for answering hasAudio(), hasVideo(), and naturalSize().
254 PipelineMetadata pipeline_metadata_
;
256 // Whether the video is known to be opaque or not.
261 // TODO(scherkus): we have these because Pipeline favours the simplicity of a
262 // single "playback rate" over worrying about paused/stopped etc... It forces
263 // all clients to manage the pause+playback rate externally, but is that
264 // really a bad thing?
266 // TODO(scherkus): since SetPlaybackRate(0) is asynchronous and we don't want
267 // to hang the render thread during pause(), we record the time at the same
268 // time we pause and then return that value in currentTime(). Otherwise our
269 // clock can creep forward a little bit while the asynchronous
270 // SetPlaybackRate(0) is being executed.
271 double playback_rate_
;
273 base::TimeDelta paused_time_
;
275 base::TimeDelta seek_time_
; // Meaningless when |seeking_| is false.
277 // TODO(scherkus): Replace with an explicit ended signal to HTMLMediaElement,
278 // see http://crbug.com/409280
281 // Seek gets pending if another seek is in progress. Only last pending seek
284 // |pending_seek_time_| is meaningless when |pending_seek_| is false.
285 base::TimeDelta pending_seek_time_
;
287 // Tracks whether to issue time changed notifications during buffering state
289 bool should_notify_time_changed_
;
291 blink::WebMediaPlayerClient
* client_
;
293 base::WeakPtr
<WebMediaPlayerDelegate
> delegate_
;
295 WebMediaPlayerParams::DeferLoadCB defer_load_cb_
;
296 WebMediaPlayerParams::Context3DCB context_3d_cb_
;
298 // Routes audio playback to either AudioRendererSink or WebAudio.
299 scoped_refptr
<WebAudioSourceProviderImpl
> audio_source_provider_
;
303 // These two are mutually exclusive:
304 // |data_source_| is used for regular resource loads.
305 // |chunk_demuxer_| is used for Media Source resource loads.
307 // |demuxer_| will contain the appropriate demuxer based on which resource
308 // load strategy we're using.
309 scoped_ptr
<BufferedDataSource
> data_source_
;
310 scoped_ptr
<Demuxer
> demuxer_
;
311 ChunkDemuxer
* chunk_demuxer_
;
313 BufferedDataSourceHostImpl buffered_data_source_host_
;
315 // Video rendering members.
316 scoped_refptr
<base::SingleThreadTaskRunner
> compositor_task_runner_
;
317 VideoFrameCompositor
* compositor_
; // Deleted on |compositor_task_runner_|.
318 SkCanvasVideoRenderer skcanvas_video_renderer_
;
320 // The compositor layer for displaying the video content when using composited
322 scoped_ptr
<cc_blink::WebLayerImpl
> video_weblayer_
;
324 EncryptedMediaPlayerSupport encrypted_media_support_
;
326 scoped_ptr
<RendererFactory
> renderer_factory_
;
328 DISALLOW_COPY_AND_ASSIGN(WebMediaPlayerImpl
);
333 #endif // MEDIA_BLINK_WEBMEDIAPLAYER_IMPL_H_