cleanup: pass string as const reference from c/b/extension
[chromium-blink-merge.git] / media / filters / audio_renderer_impl.h
blobf6f41f1ea5b3ec741a7706ce860f98f9bc51a4be
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 // Audio rendering unit utilizing an AudioRendererSink to output data.
6 //
7 // This class lives inside three threads during it's lifetime, namely:
8 // 1. Render thread
9 // Where the object is created.
10 // 2. Media thread (provided via constructor)
11 // All AudioDecoder methods are called on this thread.
12 // 3. Audio thread created by the AudioRendererSink.
13 // Render() is called here where audio data is decoded into raw PCM data.
15 // AudioRendererImpl talks to an AudioRendererAlgorithm that takes care of
16 // queueing audio data and stretching/shrinking audio data when playback rate !=
17 // 1.0 or 0.0.
19 #ifndef MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_
20 #define MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_
22 #include <deque>
24 #include "base/gtest_prod_util.h"
25 #include "base/memory/weak_ptr.h"
26 #include "base/synchronization/lock.h"
27 #include "media/base/audio_decoder.h"
28 #include "media/base/audio_renderer.h"
29 #include "media/base/audio_renderer_sink.h"
30 #include "media/base/decryptor.h"
31 #include "media/filters/audio_renderer_algorithm.h"
32 #include "media/filters/decoder_stream.h"
34 namespace base {
35 class SingleThreadTaskRunner;
38 namespace media {
40 class AudioBus;
41 class AudioBufferConverter;
42 class AudioSplicer;
43 class DecryptingDemuxerStream;
44 class AudioHardwareConfig;
46 class MEDIA_EXPORT AudioRendererImpl
47 : public AudioRenderer,
48 NON_EXPORTED_BASE(public AudioRendererSink::RenderCallback) {
49 public:
50 // |task_runner| is the thread on which AudioRendererImpl will execute.
52 // |sink| is used as the destination for the rendered audio.
54 // |decoders| contains the AudioDecoders to use when initializing.
56 // |set_decryptor_ready_cb| is fired when the audio decryptor is available
57 // (only applicable if the stream is encrypted and we have a decryptor).
58 AudioRendererImpl(
59 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
60 AudioRendererSink* sink,
61 ScopedVector<AudioDecoder> decoders,
62 const SetDecryptorReadyCB& set_decryptor_ready_cb,
63 AudioHardwareConfig* hardware_params);
64 virtual ~AudioRendererImpl();
66 // AudioRenderer implementation.
67 virtual void Initialize(DemuxerStream* stream,
68 const PipelineStatusCB& init_cb,
69 const StatisticsCB& statistics_cb,
70 const base::Closure& underflow_cb,
71 const TimeCB& time_cb,
72 const base::Closure& ended_cb,
73 const base::Closure& disabled_cb,
74 const PipelineStatusCB& error_cb) OVERRIDE;
75 virtual void Play(const base::Closure& callback) OVERRIDE;
76 virtual void Pause(const base::Closure& callback) OVERRIDE;
77 virtual void Flush(const base::Closure& callback) OVERRIDE;
78 virtual void Stop(const base::Closure& callback) OVERRIDE;
79 virtual void SetPlaybackRate(float rate) OVERRIDE;
80 virtual void Preroll(base::TimeDelta time,
81 const PipelineStatusCB& cb) OVERRIDE;
82 virtual void ResumeAfterUnderflow() OVERRIDE;
83 virtual void SetVolume(float volume) OVERRIDE;
85 // Disables underflow support. When used, |state_| will never transition to
86 // kUnderflow resulting in Render calls that underflow returning 0 frames
87 // instead of some number of silence frames. Must be called prior to
88 // Initialize().
89 void DisableUnderflowForTesting();
91 // Allows injection of a custom time callback for non-realtime testing.
92 typedef base::Callback<base::TimeTicks()> NowCB;
93 void set_now_cb_for_testing(const NowCB& now_cb) {
94 now_cb_ = now_cb;
97 private:
98 friend class AudioRendererImplTest;
100 // TODO(acolwell): Add a state machine graph.
101 enum State {
102 kUninitialized,
103 kInitializing,
104 kPaused,
105 kFlushing,
106 kPrerolling,
107 kPlaying,
108 kStopped,
109 kUnderflow,
110 kRebuffering,
113 // Callback from the audio decoder delivering decoded audio samples.
114 void DecodedAudioReady(AudioBufferStream::Status status,
115 const scoped_refptr<AudioBuffer>& buffer);
117 // Handles buffers that come out of |splicer_|.
118 // Returns true if more buffers are needed.
119 bool HandleSplicerBuffer(const scoped_refptr<AudioBuffer>& buffer);
121 // Helper functions for AudioDecoder::Status values passed to
122 // DecodedAudioReady().
123 void HandleAbortedReadOrDecodeError(bool is_decode_error);
125 // Estimate earliest time when current buffer can stop playing.
126 void UpdateEarliestEndTime_Locked(int frames_filled,
127 const base::TimeDelta& playback_delay,
128 const base::TimeTicks& time_now);
130 void DoPlay_Locked();
131 void DoPause_Locked();
133 // AudioRendererSink::RenderCallback implementation.
135 // NOTE: These are called on the audio callback thread!
137 // Render() fills the given buffer with audio data by delegating to its
138 // |algorithm_|. Render() also takes care of updating the clock.
139 // Returns the number of frames copied into |audio_bus|, which may be less
140 // than or equal to the initial number of frames in |audio_bus|
142 // If this method returns fewer frames than the initial number of frames in
143 // |audio_bus|, it could be a sign that the pipeline is stalled or unable to
144 // stream the data fast enough. In such scenarios, the callee should zero out
145 // unused portions of their buffer to play back silence.
147 // Render() updates the pipeline's playback timestamp. If Render() is
148 // not called at the same rate as audio samples are played, then the reported
149 // timestamp in the pipeline will be ahead of the actual audio playback. In
150 // this case |audio_delay_milliseconds| should be used to indicate when in the
151 // future should the filled buffer be played.
152 virtual int Render(AudioBus* audio_bus,
153 int audio_delay_milliseconds) OVERRIDE;
154 virtual void OnRenderError() OVERRIDE;
156 // Helper methods that schedule an asynchronous read from the decoder as long
157 // as there isn't a pending read.
159 // Must be called on |task_runner_|.
160 void AttemptRead();
161 void AttemptRead_Locked();
162 bool CanRead_Locked();
163 void ChangeState_Locked(State new_state);
165 // Returns true if the data in the buffer is all before
166 // |preroll_timestamp_|. This can only return true while
167 // in the kPrerolling state.
168 bool IsBeforePrerollTime(const scoped_refptr<AudioBuffer>& buffer);
170 // Called upon AudioBufferStream initialization, or failure thereof (indicated
171 // by the value of |success|).
172 void OnAudioBufferStreamInitialized(bool succes);
174 // Used to initiate the flush operation once all pending reads have
175 // completed.
176 void DoFlush_Locked();
178 // Calls |decoder_|.Reset() and arranges for ResetDecoderDone() to get
179 // called when the reset completes.
180 void ResetDecoder();
182 // Called when the |decoder_|.Reset() has completed.
183 void ResetDecoderDone();
185 // Called by the AudioBufferStream when a splice buffer is demuxed.
186 void OnNewSpliceBuffer(base::TimeDelta);
188 // Called by the AudioBufferStream when a config change occurs.
189 void OnConfigChange();
191 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
193 scoped_ptr<AudioSplicer> splicer_;
194 scoped_ptr<AudioBufferConverter> buffer_converter_;
196 // Whether or not we expect to handle config changes.
197 bool expecting_config_changes_;
199 // The sink (destination) for rendered audio. |sink_| must only be accessed
200 // on |task_runner_|. |sink_| must never be called under |lock_| or else we
201 // may deadlock between |task_runner_| and the audio callback thread.
202 scoped_refptr<media::AudioRendererSink> sink_;
204 AudioBufferStream audio_buffer_stream_;
206 // Interface to the hardware audio params.
207 const AudioHardwareConfig* const hardware_config_;
209 // Cached copy of hardware params from |hardware_config_|.
210 AudioParameters audio_parameters_;
212 // Callbacks provided during Initialize().
213 PipelineStatusCB init_cb_;
214 base::Closure underflow_cb_;
215 TimeCB time_cb_;
216 base::Closure ended_cb_;
217 base::Closure disabled_cb_;
218 PipelineStatusCB error_cb_;
220 // Callback provided to Flush().
221 base::Closure flush_cb_;
223 // Callback provided to Preroll().
224 PipelineStatusCB preroll_cb_;
226 // Typically calls base::TimeTicks::Now() but can be overridden by a test.
227 NowCB now_cb_;
229 // After Initialize() has completed, all variables below must be accessed
230 // under |lock_|. ------------------------------------------------------------
231 base::Lock lock_;
233 // Algorithm for scaling audio.
234 scoped_ptr<AudioRendererAlgorithm> algorithm_;
236 // Simple state tracking variable.
237 State state_;
239 // Keep track of whether or not the sink is playing.
240 bool sink_playing_;
242 // Keep track of our outstanding read to |decoder_|.
243 bool pending_read_;
245 // Keeps track of whether we received and rendered the end of stream buffer.
246 bool received_end_of_stream_;
247 bool rendered_end_of_stream_;
249 // The timestamp of the last frame (i.e. furthest in the future) buffered as
250 // well as the current time that takes current playback delay into account.
251 base::TimeDelta audio_time_buffered_;
252 base::TimeDelta current_time_;
254 base::TimeDelta preroll_timestamp_;
256 // We're supposed to know amount of audio data OS or hardware buffered, but
257 // that is not always so -- on my Linux box
258 // AudioBuffersState::hardware_delay_bytes never reaches 0.
260 // As a result we cannot use it to find when stream ends. If we just ignore
261 // buffered data we will notify host that stream ended before it is actually
262 // did so, I've seen it done ~140ms too early when playing ~150ms file.
264 // Instead of trying to invent OS-specific solution for each and every OS we
265 // are supporting, use simple workaround: every time we fill the buffer we
266 // remember when it should stop playing, and do not assume that buffer is
267 // empty till that time. Workaround is not bulletproof, as we don't exactly
268 // know when that particular data would start playing, but it is much better
269 // than nothing.
270 base::TimeTicks earliest_end_time_;
271 size_t total_frames_filled_;
273 bool underflow_disabled_;
275 // True if the renderer receives a buffer with kAborted status during preroll,
276 // false otherwise. This flag is cleared on the next Preroll() call.
277 bool preroll_aborted_;
279 // End variables which must be accessed under |lock_|. ----------------------
281 // NOTE: Weak pointers must be invalidated before all other member variables.
282 base::WeakPtrFactory<AudioRendererImpl> weak_factory_;
284 DISALLOW_COPY_AND_ASSIGN(AudioRendererImpl);
287 } // namespace media
289 #endif // MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_