Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / media / filters / audio_renderer_impl.h
blob4e8ad018252c6983e07bade839b269b46d417cbc
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 AudioBufferConverter;
41 class AudioBus;
42 class AudioClock;
43 class AudioHardwareConfig;
44 class AudioSplicer;
45 class DecryptingDemuxerStream;
47 class MEDIA_EXPORT AudioRendererImpl
48 : public AudioRenderer,
49 NON_EXPORTED_BASE(public AudioRendererSink::RenderCallback) {
50 public:
51 // |task_runner| is the thread on which AudioRendererImpl will execute.
53 // |sink| is used as the destination for the rendered audio.
55 // |decoders| contains the AudioDecoders to use when initializing.
57 // |set_decryptor_ready_cb| is fired when the audio decryptor is available
58 // (only applicable if the stream is encrypted and we have a decryptor).
59 AudioRendererImpl(
60 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
61 AudioRendererSink* sink,
62 ScopedVector<AudioDecoder> decoders,
63 const SetDecryptorReadyCB& set_decryptor_ready_cb,
64 AudioHardwareConfig* hardware_params);
65 virtual ~AudioRendererImpl();
67 // AudioRenderer implementation.
68 virtual void Initialize(DemuxerStream* stream,
69 const PipelineStatusCB& init_cb,
70 const StatisticsCB& statistics_cb,
71 const base::Closure& underflow_cb,
72 const TimeCB& time_cb,
73 const base::Closure& ended_cb,
74 const base::Closure& disabled_cb,
75 const PipelineStatusCB& error_cb) OVERRIDE;
76 virtual void Play(const base::Closure& callback) OVERRIDE;
77 virtual void Pause(const base::Closure& callback) OVERRIDE;
78 virtual void Flush(const base::Closure& callback) OVERRIDE;
79 virtual void Stop(const base::Closure& callback) OVERRIDE;
80 virtual void SetPlaybackRate(float rate) OVERRIDE;
81 virtual void Preroll(base::TimeDelta time,
82 const PipelineStatusCB& cb) OVERRIDE;
83 virtual void ResumeAfterUnderflow() OVERRIDE;
84 virtual void SetVolume(float volume) OVERRIDE;
86 // Disables underflow support. When used, |state_| will never transition to
87 // kUnderflow resulting in Render calls that underflow returning 0 frames
88 // instead of some number of silence frames. Must be called prior to
89 // Initialize().
90 void DisableUnderflowForTesting();
92 // Allows injection of a custom time callback for non-realtime testing.
93 typedef base::Callback<base::TimeTicks()> NowCB;
94 void set_now_cb_for_testing(const NowCB& now_cb) {
95 now_cb_ = now_cb;
98 private:
99 friend class AudioRendererImplTest;
101 // TODO(acolwell): Add a state machine graph.
102 enum State {
103 kUninitialized,
104 kInitializing,
105 kPaused,
106 kFlushing,
107 kPrerolling,
108 kPlaying,
109 kStopped,
110 kUnderflow,
111 kRebuffering,
114 // Callback from the audio decoder delivering decoded audio samples.
115 void DecodedAudioReady(AudioBufferStream::Status status,
116 const scoped_refptr<AudioBuffer>& buffer);
118 // Handles buffers that come out of |splicer_|.
119 // Returns true if more buffers are needed.
120 bool HandleSplicerBuffer(const scoped_refptr<AudioBuffer>& buffer);
122 // Helper functions for AudioDecoder::Status values passed to
123 // DecodedAudioReady().
124 void HandleAbortedReadOrDecodeError(bool is_decode_error);
126 // Estimate earliest time when current buffer can stop playing.
127 void UpdateEarliestEndTime_Locked(int frames_filled,
128 const base::TimeDelta& playback_delay,
129 const base::TimeTicks& time_now);
131 void DoPlay_Locked();
132 void DoPause_Locked();
134 // AudioRendererSink::RenderCallback implementation.
136 // NOTE: These are called on the audio callback thread!
138 // Render() fills the given buffer with audio data by delegating to its
139 // |algorithm_|. Render() also takes care of updating the clock.
140 // Returns the number of frames copied into |audio_bus|, which may be less
141 // than or equal to the initial number of frames in |audio_bus|
143 // If this method returns fewer frames than the initial number of frames in
144 // |audio_bus|, it could be a sign that the pipeline is stalled or unable to
145 // stream the data fast enough. In such scenarios, the callee should zero out
146 // unused portions of their buffer to play back silence.
148 // Render() updates the pipeline's playback timestamp. If Render() is
149 // not called at the same rate as audio samples are played, then the reported
150 // timestamp in the pipeline will be ahead of the actual audio playback. In
151 // this case |audio_delay_milliseconds| should be used to indicate when in the
152 // future should the filled buffer be played.
153 virtual int Render(AudioBus* audio_bus,
154 int audio_delay_milliseconds) OVERRIDE;
155 virtual void OnRenderError() OVERRIDE;
157 // Helper methods that schedule an asynchronous read from the decoder as long
158 // as there isn't a pending read.
160 // Must be called on |task_runner_|.
161 void AttemptRead();
162 void AttemptRead_Locked();
163 bool CanRead_Locked();
164 void ChangeState_Locked(State new_state);
166 // Returns true if the data in the buffer is all before
167 // |preroll_timestamp_|. This can only return true while
168 // in the kPrerolling state.
169 bool IsBeforePrerollTime(const scoped_refptr<AudioBuffer>& buffer);
171 // Called upon AudioBufferStream initialization, or failure thereof (indicated
172 // by the value of |success|).
173 void OnAudioBufferStreamInitialized(bool succes);
175 // Used to initiate the flush operation once all pending reads have
176 // completed.
177 void DoFlush_Locked();
179 // Calls |decoder_|.Reset() and arranges for ResetDecoderDone() to get
180 // called when the reset completes.
181 void ResetDecoder();
183 // Called when the |decoder_|.Reset() has completed.
184 void ResetDecoderDone();
186 // Called by the AudioBufferStream when a splice buffer is demuxed.
187 void OnNewSpliceBuffer(base::TimeDelta);
189 // Called by the AudioBufferStream when a config change occurs.
190 void OnConfigChange();
192 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
194 scoped_ptr<AudioSplicer> splicer_;
195 scoped_ptr<AudioBufferConverter> buffer_converter_;
197 // Whether or not we expect to handle config changes.
198 bool expecting_config_changes_;
200 // The sink (destination) for rendered audio. |sink_| must only be accessed
201 // on |task_runner_|. |sink_| must never be called under |lock_| or else we
202 // may deadlock between |task_runner_| and the audio callback thread.
203 scoped_refptr<media::AudioRendererSink> sink_;
205 AudioBufferStream audio_buffer_stream_;
207 // Interface to the hardware audio params.
208 const AudioHardwareConfig* const hardware_config_;
210 // Cached copy of hardware params from |hardware_config_|.
211 AudioParameters audio_parameters_;
213 // Callbacks provided during Initialize().
214 PipelineStatusCB init_cb_;
215 base::Closure underflow_cb_;
216 TimeCB time_cb_;
217 base::Closure ended_cb_;
218 base::Closure disabled_cb_;
219 PipelineStatusCB error_cb_;
221 // Callback provided to Flush().
222 base::Closure flush_cb_;
224 // Callback provided to Preroll().
225 PipelineStatusCB preroll_cb_;
227 // Typically calls base::TimeTicks::Now() but can be overridden by a test.
228 NowCB now_cb_;
230 // After Initialize() has completed, all variables below must be accessed
231 // under |lock_|. ------------------------------------------------------------
232 base::Lock lock_;
234 // Algorithm for scaling audio.
235 scoped_ptr<AudioRendererAlgorithm> algorithm_;
237 // Simple state tracking variable.
238 State state_;
240 // Keep track of whether or not the sink is playing.
241 bool sink_playing_;
243 // Keep track of our outstanding read to |decoder_|.
244 bool pending_read_;
246 // Keeps track of whether we received and rendered the end of stream buffer.
247 bool received_end_of_stream_;
248 bool rendered_end_of_stream_;
250 scoped_ptr<AudioClock> audio_clock_;
252 base::TimeDelta preroll_timestamp_;
254 // We're supposed to know amount of audio data OS or hardware buffered, but
255 // that is not always so -- on my Linux box
256 // AudioBuffersState::hardware_delay_bytes never reaches 0.
258 // As a result we cannot use it to find when stream ends. If we just ignore
259 // buffered data we will notify host that stream ended before it is actually
260 // did so, I've seen it done ~140ms too early when playing ~150ms file.
262 // Instead of trying to invent OS-specific solution for each and every OS we
263 // are supporting, use simple workaround: every time we fill the buffer we
264 // remember when it should stop playing, and do not assume that buffer is
265 // empty till that time. Workaround is not bulletproof, as we don't exactly
266 // know when that particular data would start playing, but it is much better
267 // than nothing.
268 base::TimeTicks earliest_end_time_;
269 size_t total_frames_filled_;
271 bool underflow_disabled_;
273 // True if the renderer receives a buffer with kAborted status during preroll,
274 // false otherwise. This flag is cleared on the next Preroll() call.
275 bool preroll_aborted_;
277 // End variables which must be accessed under |lock_|. ----------------------
279 // NOTE: Weak pointers must be invalidated before all other member variables.
280 base::WeakPtrFactory<AudioRendererImpl> weak_factory_;
282 DISALLOW_COPY_AND_ASSIGN(AudioRendererImpl);
285 } // namespace media
287 #endif // MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_