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/demuxer.h"
16 #include "media/base/media_export.h"
17 #include "media/base/pipeline_status.h"
18 #include "media/base/ranges.h"
19 #include "media/base/serial_runner.h"
20 #include "media/base/text_track.h"
21 #include "media/base/video_rotation.h"
22 #include "ui/gfx/size.h"
25 class SingleThreadTaskRunner
;
34 class TextTrackConfig
;
35 class TimeDeltaInterpolator
;
38 // Metadata describing a pipeline once it has been initialized.
39 struct PipelineMetadata
{
41 : has_audio(false), has_video(false), video_rotation(VIDEO_ROTATION_0
) {}
45 gfx::Size natural_size
;
46 VideoRotation video_rotation
;
47 base::Time timeline_offset
;
50 typedef base::Callback
<void(PipelineMetadata
)> PipelineMetadataCB
;
52 // Pipeline runs the media pipeline. Filters are created and called on the
53 // task runner injected into this object. Pipeline works like a state
54 // machine to perform asynchronous initialization, pausing, seeking and playing.
56 // Here's a state diagram that describes the lifetime of this object.
58 // [ *Created ] [ Any State ]
59 // | Start() | Stop() / SetError()
61 // [ InitXXX (for each filter) ] [ Stopping ]
64 // [ Playing ] <-- [ Seeking ] [ Stopped ]
69 // Initialization is a series of state transitions from "Created" through each
70 // filter initialization state. When all filter initialization states have
71 // completed, we are implicitly in a "Paused" state. At that point we simulate
72 // a Seek() to the beginning of the media to give filters a chance to preroll.
73 // From then on the normal Seek() transitions are carried out and we start
76 // If any error ever happens, this object will transition to the "Error" state
77 // from any state. If Stop() is ever called, this object will transition to
79 class MEDIA_EXPORT Pipeline
: public DemuxerHost
{
81 // Used to paint VideoFrame.
82 typedef base::Callback
<void(const scoped_refptr
<VideoFrame
>&)> PaintCB
;
84 // Constructs a media pipeline that will execute on |task_runner|.
85 Pipeline(const scoped_refptr
<base::SingleThreadTaskRunner
>& task_runner
,
89 // Build a pipeline to using the given |demuxer| and |renderer| to construct
90 // a filter chain, executing |seek_cb| when the initial seek has completed.
92 // The following permanent callbacks will be executed as follows up until
93 // Stop() has completed:
94 // |ended_cb| will be executed whenever the media reaches the end.
95 // |error_cb| will be executed whenever an error occurs but hasn't been
96 // reported already through another callback.
97 // |metadata_cb| will be executed when the content duration, container video
98 // size, start time, and whether the content has audio and/or
99 // video in supported formats are known.
100 // |buffering_state_cb| will be executed whenever there are changes in the
101 // overall buffering state of the pipeline.
102 // |paint_cb| will be executed whenever there is a VideoFrame to be painted.
103 // It's safe to call this callback from any thread.
104 // |duration_change_cb| optional callback that will be executed whenever the
105 // presentation duration changes.
106 // |add_text_track_cb| will be executed whenever a text track is added.
107 // It is an error to call this method after the pipeline has already started.
108 void Start(Demuxer
* demuxer
,
109 scoped_ptr
<Renderer
> renderer
,
110 const base::Closure
& ended_cb
,
111 const PipelineStatusCB
& error_cb
,
112 const PipelineStatusCB
& seek_cb
,
113 const PipelineMetadataCB
& metadata_cb
,
114 const BufferingStateCB
& buffering_state_cb
,
115 const PaintCB
& paint_cb
,
116 const base::Closure
& duration_change_cb
,
117 const AddTextTrackCB
& add_text_track_cb
);
119 // Asynchronously stops the pipeline, executing |stop_cb| when the pipeline
120 // teardown has completed.
122 // Stop() must complete before destroying the pipeline. It it permissible to
123 // call Stop() at any point during the lifetime of the pipeline.
125 // It is safe to delete the pipeline during the execution of |stop_cb|.
126 void Stop(const base::Closure
& stop_cb
);
128 // Attempt to seek to the position specified by time. |seek_cb| will be
129 // executed when the all filters in the pipeline have processed the seek.
131 // Clients are expected to call GetMediaTime() to check whether the seek
134 // It is an error to call this method if the pipeline has not started.
135 void Seek(base::TimeDelta time
, const PipelineStatusCB
& seek_cb
);
137 // Returns true if the pipeline has been started via Start(). If IsRunning()
138 // returns true, it is expected that Stop() will be called before destroying
140 bool IsRunning() const;
142 // Gets the current playback rate of the pipeline. When the pipeline is
143 // started, the playback rate will be 0.0f. A rate of 1.0f indicates
144 // that the pipeline is rendering the media at the standard rate. Valid
145 // values for playback rate are >= 0.0f.
146 float GetPlaybackRate() const;
148 // Attempt to adjust the playback rate. Setting a playback rate of 0.0f pauses
149 // all rendering of the media. A rate of 1.0f indicates a normal playback
150 // rate. Values for the playback rate must be greater than or equal to 0.0f.
152 // TODO(scherkus): What about maximum rate? Does HTML5 specify a max?
153 void SetPlaybackRate(float playback_rate
);
155 // Gets the current volume setting being used by the audio renderer. When
156 // the pipeline is started, this value will be 1.0f. Valid values range
157 // from 0.0f to 1.0f.
158 float GetVolume() const;
160 // Attempt to set the volume of the audio renderer. Valid values for volume
161 // range from 0.0f (muted) to 1.0f (full volume). This value affects all
162 // channels proportionately for multi-channel audio streams.
163 void SetVolume(float volume
);
165 // Returns the current media playback time, which progresses from 0 until
166 // GetMediaDuration().
167 base::TimeDelta
GetMediaTime() const;
169 // Get approximate time ranges of buffered media.
170 Ranges
<base::TimeDelta
> GetBufferedTimeRanges() const;
172 // Get the duration of the media in microseconds. If the duration has not
173 // been determined yet, then returns 0.
174 base::TimeDelta
GetMediaDuration() const;
176 // Return true if loading progress has been made since the last time this
177 // method was called.
178 bool DidLoadingProgress();
180 // Gets the current pipeline statistics.
181 PipelineStatistics
GetStatistics() const;
183 void SetErrorForTesting(PipelineStatus status
);
184 bool HasWeakPtrsForTesting() const;
187 FRIEND_TEST_ALL_PREFIXES(PipelineTest
, GetBufferedTimeRanges
);
188 FRIEND_TEST_ALL_PREFIXES(PipelineTest
, EndedCallback
);
189 FRIEND_TEST_ALL_PREFIXES(PipelineTest
, AudioStreamShorterThanVideo
);
190 friend class MediaLog
;
192 // Pipeline states, as described above.
203 // Updates |state_|. All state transitions should use this call.
204 void SetState(State next_state
);
206 static const char* GetStateString(State state
);
207 State
GetNextState() const;
209 // Helper method that runs & resets |seek_cb_| and resets |seek_timestamp_|
210 // and |seek_pending_|.
213 // DemuxerHost implementaion.
214 void AddBufferedTimeRange(base::TimeDelta start
,
215 base::TimeDelta end
) override
;
216 void SetDuration(base::TimeDelta duration
) override
;
217 void OnDemuxerError(PipelineStatus error
) override
;
218 void AddTextStream(DemuxerStream
* text_stream
,
219 const TextTrackConfig
& config
) override
;
220 void RemoveTextStream(DemuxerStream
* text_stream
) override
;
222 // Callback executed when a rendering error happened, initiating the teardown
224 void OnError(PipelineStatus error
);
226 // Callback executed by filters to update statistics.
227 void OnUpdateStatistics(const PipelineStatistics
& stats
);
229 // The following "task" methods correspond to the public methods, but these
230 // methods are run as the result of posting a task to the Pipeline's
234 // Stops and destroys all filters, placing the pipeline in the kStopped state.
235 void StopTask(const base::Closure
& stop_cb
);
237 // Carries out stopping and destroying all filters, placing the pipeline in
238 // the kStopped state.
239 void ErrorChangedTask(PipelineStatus error
);
241 // Carries out notifying filters that the playback rate has changed.
242 void PlaybackRateChangedTask(float playback_rate
);
244 // Carries out notifying filters that the volume has changed.
245 void VolumeChangedTask(float volume
);
247 // Carries out notifying filters that we are seeking to a new timestamp.
248 void SeekTask(base::TimeDelta time
, const PipelineStatusCB
& seek_cb
);
250 // Callbacks executed when a renderer has ended.
251 void OnRendererEnded();
252 void OnTextRendererEnded();
253 void RunEndedCallbackIfNeeded();
255 scoped_ptr
<TextRenderer
> CreateTextRenderer();
257 // Carries out adding a new text stream to the text renderer.
258 void AddTextStreamTask(DemuxerStream
* text_stream
,
259 const TextTrackConfig
& config
);
261 // Carries out removing a text stream from the text renderer.
262 void RemoveTextStreamTask(DemuxerStream
* text_stream
);
264 // Callbacks executed when a text track is added.
265 void OnAddTextTrack(const TextTrackConfig
& config
,
266 const AddTextTrackDoneCB
& done_cb
);
268 // Kicks off initialization for each media object, executing |done_cb| with
269 // the result when completed.
270 void InitializeDemuxer(const PipelineStatusCB
& done_cb
);
271 void InitializeRenderer(const base::Closure
& done_cb
);
273 void OnStateTransition(PipelineStatus status
);
274 void StateTransitionTask(PipelineStatus status
);
276 // Initiates an asynchronous pause-flush-seek-preroll call sequence
277 // executing |done_cb| with the final status when completed.
278 void DoSeek(base::TimeDelta seek_timestamp
, const PipelineStatusCB
& done_cb
);
280 // Initiates an asynchronous pause-flush-stop call sequence executing
281 // |done_cb| when completed.
282 void DoStop(const PipelineStatusCB
& done_cb
);
283 void OnStopCompleted(PipelineStatus status
);
285 void ReportMetadata();
287 void BufferingStateChanged(BufferingState new_buffering_state
);
289 // Task runner used to execute pipeline tasks.
290 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
292 // MediaLog to which to log events.
293 scoped_refptr
<MediaLog
> media_log_
;
295 // Lock used to serialize access for the following data members.
296 mutable base::Lock lock_
;
298 // Whether or not the pipeline is running.
301 // Amount of available buffered data as reported by |demuxer_|.
302 Ranges
<base::TimeDelta
> buffered_time_ranges_
;
304 // True when AddBufferedTimeRange() has been called more recently than
305 // DidLoadingProgress().
306 bool did_loading_progress_
;
308 // Current volume level (from 0.0f to 1.0f). This value is set immediately
309 // via SetVolume() and a task is dispatched on the task runner to notify the
313 // Current playback rate (>= 0.0f). This value is set immediately via
314 // SetPlaybackRate() and a task is dispatched on the task runner to notify
316 float playback_rate_
;
318 // Current duration as reported by |demuxer_|.
319 base::TimeDelta duration_
;
321 // Status of the pipeline. Initialized to PIPELINE_OK which indicates that
322 // the pipeline is operating correctly. Any other value indicates that the
323 // pipeline is stopped or is stopping. Clients can call the Stop() method to
324 // reset the pipeline state, and restore this to PIPELINE_OK.
325 PipelineStatus status_
;
327 // The following data members are only accessed by tasks posted to
330 bool is_initialized_
;
332 // Member that tracks the current state.
335 // The timestamp to start playback from after starting/seeking has completed.
336 base::TimeDelta start_timestamp_
;
338 // Whether we've received the audio/video/text ended events.
339 bool renderer_ended_
;
340 bool text_renderer_ended_
;
342 // Temporary callback used for Start() and Seek().
343 PipelineStatusCB seek_cb_
;
345 // Temporary callback used for Stop().
346 base::Closure stop_cb_
;
348 // Permanent callbacks passed in via Start().
349 base::Closure ended_cb_
;
350 PipelineStatusCB error_cb_
;
351 PipelineMetadataCB metadata_cb_
;
352 BufferingStateCB buffering_state_cb_
;
354 base::Closure duration_change_cb_
;
355 AddTextTrackCB add_text_track_cb_
;
357 // Holds the initialized demuxer. Used for seeking. Owned by client.
360 // Holds the initialized renderers. Used for setting the volume,
361 // playback rate, and determining when playback has finished.
362 scoped_ptr
<Renderer
> renderer_
;
363 scoped_ptr
<TextRenderer
> text_renderer_
;
365 PipelineStatistics statistics_
;
367 scoped_ptr
<SerialRunner
> pending_callbacks_
;
369 base::ThreadChecker thread_checker_
;
371 // NOTE: Weak pointers must be invalidated before all other member variables.
372 base::WeakPtrFactory
<Pipeline
> weak_factory_
;
374 DISALLOW_COPY_AND_ASSIGN(Pipeline
);
379 #endif // MEDIA_BASE_PIPELINE_H_