Update V8 to version 4.7.56.
[chromium-blink-merge.git] / media / base / pipeline.h
blobb63be0093bfe5f525cedbf2f74c220362f9df736
1 // Copyright (c) 2012 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_BASE_PIPELINE_H_
6 #define MEDIA_BASE_PIPELINE_H_
8 #include "base/gtest_prod_util.h"
9 #include "base/memory/ref_counted.h"
10 #include "base/memory/weak_ptr.h"
11 #include "base/synchronization/lock.h"
12 #include "base/threading/thread_checker.h"
13 #include "base/time/default_tick_clock.h"
14 #include "media/base/buffering_state.h"
15 #include "media/base/cdm_context.h"
16 #include "media/base/demuxer.h"
17 #include "media/base/media_export.h"
18 #include "media/base/pipeline_status.h"
19 #include "media/base/ranges.h"
20 #include "media/base/serial_runner.h"
21 #include "media/base/text_track.h"
22 #include "media/base/video_rotation.h"
23 #include "ui/gfx/geometry/size.h"
25 namespace base {
26 class SingleThreadTaskRunner;
27 class TimeDelta;
30 namespace media {
32 class MediaLog;
33 class Renderer;
34 class TextRenderer;
35 class TextTrackConfig;
36 class TimeDeltaInterpolator;
37 class VideoFrame;
39 // Metadata describing a pipeline once it has been initialized.
40 struct PipelineMetadata {
41 PipelineMetadata()
42 : has_audio(false), has_video(false), video_rotation(VIDEO_ROTATION_0) {}
44 bool has_audio;
45 bool has_video;
46 gfx::Size natural_size;
47 VideoRotation video_rotation;
48 base::Time timeline_offset;
51 typedef base::Callback<void(PipelineMetadata)> PipelineMetadataCB;
53 // Pipeline runs the media pipeline. Filters are created and called on the
54 // task runner injected into this object. Pipeline works like a state
55 // machine to perform asynchronous initialization, pausing, seeking and playing.
57 // Here's a state diagram that describes the lifetime of this object.
59 // [ *Created ] [ Any State ]
60 // | Start() | Stop() / SetError()
61 // V V
62 // [ InitXXX (for each filter) ] [ Stopping ]
63 // | |
64 // V V
65 // [ Playing ] <-- [ Seeking ] [ Stopped ]
66 // | ^
67 // `---------------'
68 // Seek()
70 // Initialization is a series of state transitions from "Created" through each
71 // filter initialization state. When all filter initialization states have
72 // completed, we are implicitly in a "Paused" state. At that point we simulate
73 // a Seek() to the beginning of the media to give filters a chance to preroll.
74 // From then on the normal Seek() transitions are carried out and we start
75 // playing the media.
77 // If any error ever happens, this object will transition to the "Error" state
78 // from any state. If Stop() is ever called, this object will transition to
79 // "Stopped" state.
80 class MEDIA_EXPORT Pipeline : public DemuxerHost {
81 public:
82 // Used to paint VideoFrame.
83 typedef base::Callback<void(const scoped_refptr<VideoFrame>&)> PaintCB;
85 // Constructs a media pipeline that will execute on |task_runner|.
86 Pipeline(const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
87 MediaLog* media_log);
88 ~Pipeline() override;
90 // Build a pipeline to using the given |demuxer| and |renderer| to construct
91 // a filter chain, executing |seek_cb| when the initial seek has completed.
93 // The following permanent callbacks will be executed as follows up until
94 // Stop() has completed:
95 // |ended_cb| will be executed whenever the media reaches the end.
96 // |error_cb| will be executed whenever an error occurs but hasn't been
97 // reported already through another callback.
98 // |metadata_cb| will be executed when the content duration, container video
99 // size, start time, and whether the content has audio and/or
100 // video in supported formats are known.
101 // |buffering_state_cb| will be executed whenever there are changes in the
102 // overall buffering state of the pipeline.
103 // |duration_change_cb| optional callback that will be executed whenever the
104 // presentation duration changes.
105 // |add_text_track_cb| will be executed whenever a text track is added.
106 // |waiting_for_decryption_key_cb| will be executed whenever the key needed
107 // to decrypt the stream is not available.
108 // It is an error to call this method after the pipeline has already started.
109 void Start(Demuxer* demuxer,
110 scoped_ptr<Renderer> renderer,
111 const base::Closure& ended_cb,
112 const PipelineStatusCB& error_cb,
113 const PipelineStatusCB& seek_cb,
114 const PipelineMetadataCB& metadata_cb,
115 const BufferingStateCB& buffering_state_cb,
116 const base::Closure& duration_change_cb,
117 const AddTextTrackCB& add_text_track_cb,
118 const base::Closure& waiting_for_decryption_key_cb);
120 // Asynchronously stops the pipeline, executing |stop_cb| when the pipeline
121 // teardown has completed.
123 // Stop() must complete before destroying the pipeline. It it permissible to
124 // call Stop() at any point during the lifetime of the pipeline.
126 // It is safe to delete the pipeline during the execution of |stop_cb|.
127 void Stop(const base::Closure& stop_cb);
129 // Attempt to seek to the position specified by time. |seek_cb| will be
130 // executed when the all filters in the pipeline have processed the seek.
132 // Clients are expected to call GetMediaTime() to check whether the seek
133 // succeeded.
135 // It is an error to call this method if the pipeline has not started.
136 void Seek(base::TimeDelta time, const PipelineStatusCB& seek_cb);
138 // Returns true if the pipeline has been started via Start(). If IsRunning()
139 // returns true, it is expected that Stop() will be called before destroying
140 // the pipeline.
141 bool IsRunning() const;
143 // Gets the current playback rate of the pipeline. When the pipeline is
144 // started, the playback rate will be 0.0. A rate of 1.0 indicates
145 // that the pipeline is rendering the media at the standard rate. Valid
146 // values for playback rate are >= 0.0.
147 double GetPlaybackRate() const;
149 // Attempt to adjust the playback rate. Setting a playback rate of 0.0 pauses
150 // all rendering of the media. A rate of 1.0 indicates a normal playback
151 // rate. Values for the playback rate must be greater than or equal to 0.0.
153 // TODO(scherkus): What about maximum rate? Does HTML5 specify a max?
154 void SetPlaybackRate(double playback_rate);
156 // Gets the current volume setting being used by the audio renderer. When
157 // the pipeline is started, this value will be 1.0f. Valid values range
158 // from 0.0f to 1.0f.
159 float GetVolume() const;
161 // Attempt to set the volume of the audio renderer. Valid values for volume
162 // range from 0.0f (muted) to 1.0f (full volume). This value affects all
163 // channels proportionately for multi-channel audio streams.
164 void SetVolume(float volume);
166 // Returns the current media playback time, which progresses from 0 until
167 // GetMediaDuration().
168 base::TimeDelta GetMediaTime() const;
170 // Get approximate time ranges of buffered media.
171 Ranges<base::TimeDelta> GetBufferedTimeRanges() const;
173 // Get the duration of the media in microseconds. If the duration has not
174 // been determined yet, then returns 0.
175 base::TimeDelta GetMediaDuration() const;
177 // Return true if loading progress has been made since the last time this
178 // method was called.
179 bool DidLoadingProgress();
181 // Gets the current pipeline statistics.
182 PipelineStatistics GetStatistics() const;
184 void SetCdm(CdmContext* cdm_context, const CdmAttachedCB& cdm_attached_cb);
186 void SetErrorForTesting(PipelineStatus status);
187 bool HasWeakPtrsForTesting() const;
189 private:
190 FRIEND_TEST_ALL_PREFIXES(PipelineTest, GetBufferedTimeRanges);
191 FRIEND_TEST_ALL_PREFIXES(PipelineTest, EndedCallback);
192 FRIEND_TEST_ALL_PREFIXES(PipelineTest, AudioStreamShorterThanVideo);
193 friend class MediaLog;
195 // Pipeline states, as described above.
196 enum State {
197 kCreated,
198 kInitDemuxer,
199 kInitRenderer,
200 kSeeking,
201 kPlaying,
202 kStopping,
203 kStopped,
206 // Updates |state_|. All state transitions should use this call.
207 void SetState(State next_state);
209 static const char* GetStateString(State state);
210 State GetNextState() const;
212 // Helper method that runs & resets |seek_cb_| and resets |seek_timestamp_|
213 // and |seek_pending_|.
214 void FinishSeek();
216 // DemuxerHost implementaion.
217 void AddBufferedTimeRange(base::TimeDelta start,
218 base::TimeDelta end) override;
219 void SetDuration(base::TimeDelta duration) override;
220 void OnDemuxerError(PipelineStatus error) override;
221 void AddTextStream(DemuxerStream* text_stream,
222 const TextTrackConfig& config) override;
223 void RemoveTextStream(DemuxerStream* text_stream) override;
225 // Callback executed when a rendering error happened, initiating the teardown
226 // sequence.
227 void OnError(PipelineStatus error);
229 // Callback executed by filters to update statistics.
230 void OnUpdateStatistics(const PipelineStatistics& stats);
232 // The following "task" methods correspond to the public methods, but these
233 // methods are run as the result of posting a task to the Pipeline's
234 // task runner.
235 void StartTask();
237 // Stops and destroys all filters, placing the pipeline in the kStopped state.
238 void StopTask(const base::Closure& stop_cb);
240 // Carries out stopping and destroying all filters, placing the pipeline in
241 // the kStopped state.
242 void ErrorChangedTask(PipelineStatus error);
244 // Carries out notifying filters that the playback rate has changed.
245 void PlaybackRateChangedTask(double playback_rate);
247 // Carries out notifying filters that the volume has changed.
248 void VolumeChangedTask(float volume);
250 // Carries out notifying filters that we are seeking to a new timestamp.
251 void SeekTask(base::TimeDelta time, const PipelineStatusCB& seek_cb);
253 // Carries out setting the |cdm_context| in |renderer_|, and then fires
254 // |cdm_attached_cb| with the result. If |renderer_| is null,
255 // |cdm_attached_cb| will be fired immediately with true, and |cdm_context|
256 // will be set in |renderer_| later when |renderer_| is created.
257 void SetCdmTask(CdmContext* cdm_context,
258 const CdmAttachedCB& cdm_attached_cb);
260 // Callbacks executed when a renderer has ended.
261 void OnRendererEnded();
262 void OnTextRendererEnded();
263 void RunEndedCallbackIfNeeded();
265 scoped_ptr<TextRenderer> CreateTextRenderer();
267 // Carries out adding a new text stream to the text renderer.
268 void AddTextStreamTask(DemuxerStream* text_stream,
269 const TextTrackConfig& config);
271 // Carries out removing a text stream from the text renderer.
272 void RemoveTextStreamTask(DemuxerStream* text_stream);
274 // Callbacks executed when a text track is added.
275 void OnAddTextTrack(const TextTrackConfig& config,
276 const AddTextTrackDoneCB& done_cb);
278 // Kicks off initialization for each media object, executing |done_cb| with
279 // the result when completed.
280 void InitializeDemuxer(const PipelineStatusCB& done_cb);
281 void InitializeRenderer(const PipelineStatusCB& done_cb);
283 void StateTransitionTask(PipelineStatus status);
285 // Initiates an asynchronous pause-flush-seek-preroll call sequence
286 // executing |done_cb| with the final status when completed.
287 void DoSeek(base::TimeDelta seek_timestamp, const PipelineStatusCB& done_cb);
289 // Initiates an asynchronous pause-flush-stop call sequence executing
290 // |done_cb| when completed.
291 void DoStop(const PipelineStatusCB& done_cb);
292 void OnStopCompleted(PipelineStatus status);
294 void ReportMetadata();
296 void BufferingStateChanged(BufferingState new_buffering_state);
298 // Task runner used to execute pipeline tasks.
299 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
301 // MediaLog to which to log events.
302 scoped_refptr<MediaLog> media_log_;
304 // Lock used to serialize access for the following data members.
305 mutable base::Lock lock_;
307 // Whether or not the pipeline is running.
308 bool running_;
310 // Amount of available buffered data as reported by |demuxer_|.
311 Ranges<base::TimeDelta> buffered_time_ranges_;
313 // True when AddBufferedTimeRange() has been called more recently than
314 // DidLoadingProgress().
315 bool did_loading_progress_;
317 // Current volume level (from 0.0f to 1.0f). This value is set immediately
318 // via SetVolume() and a task is dispatched on the task runner to notify the
319 // filters.
320 float volume_;
322 // Current playback rate (>= 0.0). This value is set immediately via
323 // SetPlaybackRate() and a task is dispatched on the task runner to notify
324 // the filters.
325 double playback_rate_;
327 // Current duration as reported by |demuxer_|.
328 base::TimeDelta duration_;
330 // Status of the pipeline. Initialized to PIPELINE_OK which indicates that
331 // the pipeline is operating correctly. Any other value indicates that the
332 // pipeline is stopped or is stopping. Clients can call the Stop() method to
333 // reset the pipeline state, and restore this to PIPELINE_OK.
334 PipelineStatus status_;
336 // The following data members are only accessed by tasks posted to
337 // |task_runner_|.
339 // Member that tracks the current state.
340 State state_;
342 // The timestamp to start playback from after starting/seeking has completed.
343 base::TimeDelta start_timestamp_;
345 // Whether we've received the audio/video/text ended events.
346 bool renderer_ended_;
347 bool text_renderer_ended_;
349 // Temporary callback used for Start() and Seek().
350 PipelineStatusCB seek_cb_;
352 // Temporary callback used for Stop().
353 base::Closure stop_cb_;
355 // Permanent callbacks passed in via Start().
356 base::Closure ended_cb_;
357 PipelineStatusCB error_cb_;
358 PipelineMetadataCB metadata_cb_;
359 BufferingStateCB buffering_state_cb_;
360 base::Closure duration_change_cb_;
361 AddTextTrackCB add_text_track_cb_;
362 base::Closure waiting_for_decryption_key_cb_;
364 // Holds the initialized demuxer. Used for seeking. Owned by client.
365 Demuxer* demuxer_;
367 // Holds the initialized renderers. Used for setting the volume,
368 // playback rate, and determining when playback has finished.
369 scoped_ptr<Renderer> renderer_;
370 scoped_ptr<TextRenderer> text_renderer_;
372 PipelineStatistics statistics_;
374 scoped_ptr<SerialRunner> pending_callbacks_;
376 // CdmContext to be used to decrypt (and decode) encrypted stream in this
377 // pipeline. Non-null only when SetCdm() is called and the pipeline has not
378 // been started. Then during Start(), this value will be set on |renderer_|.
379 CdmContext* pending_cdm_context_;
381 base::ThreadChecker thread_checker_;
383 // NOTE: Weak pointers must be invalidated before all other member variables.
384 base::WeakPtrFactory<Pipeline> weak_factory_;
386 DISALLOW_COPY_AND_ASSIGN(Pipeline);
389 } // namespace media
391 #endif // MEDIA_BASE_PIPELINE_H_