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.
7 // This class lives inside three threads during it's lifetime, namely:
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 !=
19 #ifndef MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_
20 #define MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_
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"
34 class MessageLoopProxy
;
40 class AudioDecoderSelector
;
42 class DecryptingDemuxerStream
;
44 class MEDIA_EXPORT AudioRendererImpl
45 : public AudioRenderer
,
46 NON_EXPORTED_BASE(public AudioRendererSink::RenderCallback
) {
48 // |message_loop| is the thread on which AudioRendererImpl will execute.
50 // |sink| is used as the destination for the rendered audio.
52 // |decoders| contains the AudioDecoders to use when initializing.
54 // |set_decryptor_ready_cb| is fired when the audio decryptor is available
55 // (only applicable if the stream is encrypted and we have a decryptor).
57 // |increase_preroll_on_underflow| Set to true if the preroll duration
58 // should be increased when ResumeAfterUnderflow() is called.
59 AudioRendererImpl(const scoped_refptr
<base::MessageLoopProxy
>& message_loop
,
60 AudioRendererSink
* sink
,
61 ScopedVector
<AudioDecoder
> decoders
,
62 const SetDecryptorReadyCB
& set_decryptor_ready_cb
,
63 bool increase_preroll_on_underflow
);
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
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
) {
98 friend class AudioRendererImplTest
;
110 // Callback from the audio decoder delivering decoded audio samples.
111 void DecodedAudioReady(AudioDecoder::Status status
,
112 const scoped_refptr
<AudioBuffer
>& buffer
);
114 // Handles buffers that come out of |splicer_|.
115 // Returns true if more buffers are needed.
116 bool HandleSplicerBuffer(const scoped_refptr
<AudioBuffer
>& buffer
);
118 // Helper functions for AudioDecoder::Status values passed to
119 // DecodedAudioReady().
120 void HandleAbortedReadOrDecodeError(bool is_decode_error
);
122 // Estimate earliest time when current buffer can stop playing.
123 void UpdateEarliestEndTime_Locked(int frames_filled
,
124 const base::TimeDelta
& playback_delay
,
125 const base::TimeTicks
& time_now
);
127 void DoPlay_Locked();
128 void DoPause_Locked();
130 // AudioRendererSink::RenderCallback implementation.
132 // NOTE: These are called on the audio callback thread!
134 // Render() fills the given buffer with audio data by delegating to its
135 // |algorithm_|. Render() also takes care of updating the clock.
136 // Returns the number of frames copied into |audio_bus|, which may be less
137 // than or equal to the initial number of frames in |audio_bus|
139 // If this method returns fewer frames than the initial number of frames in
140 // |audio_bus|, it could be a sign that the pipeline is stalled or unable to
141 // stream the data fast enough. In such scenarios, the callee should zero out
142 // unused portions of their buffer to play back silence.
144 // Render() updates the pipeline's playback timestamp. If Render() is
145 // not called at the same rate as audio samples are played, then the reported
146 // timestamp in the pipeline will be ahead of the actual audio playback. In
147 // this case |audio_delay_milliseconds| should be used to indicate when in the
148 // future should the filled buffer be played.
149 virtual int Render(AudioBus
* audio_bus
,
150 int audio_delay_milliseconds
) OVERRIDE
;
151 virtual void OnRenderError() OVERRIDE
;
153 // Helper methods that schedule an asynchronous read from the decoder as long
154 // as there isn't a pending read.
156 // Must be called on |message_loop_|.
158 void AttemptRead_Locked();
159 bool CanRead_Locked();
160 void ChangeState_Locked(State new_state
);
162 // Returns true if the data in the buffer is all before
163 // |preroll_timestamp_|. This can only return true while
164 // in the kPrerolling state.
165 bool IsBeforePrerollTime(const scoped_refptr
<AudioBuffer
>& buffer
);
167 // Called when |decoder_selector_| has selected |decoder| or is null if no
168 // decoder could be selected.
170 // |decrypting_demuxer_stream| is non-null if a DecryptingDemuxerStream was
171 // created to help decrypt the encrypted stream.
172 void OnDecoderSelected(
173 scoped_ptr
<AudioDecoder
> decoder
,
174 scoped_ptr
<DecryptingDemuxerStream
> decrypting_demuxer_stream
);
176 void ResetDecoder(const base::Closure
& callback
);
178 scoped_refptr
<base::MessageLoopProxy
> message_loop_
;
179 base::WeakPtrFactory
<AudioRendererImpl
> weak_factory_
;
180 base::WeakPtr
<AudioRendererImpl
> weak_this_
;
182 scoped_ptr
<AudioSplicer
> splicer_
;
184 // The sink (destination) for rendered audio. |sink_| must only be accessed
185 // on |message_loop_|. |sink_| must never be called under |lock_| or else we
186 // may deadlock between |message_loop_| and the audio callback thread.
187 scoped_refptr
<media::AudioRendererSink
> sink_
;
189 scoped_ptr
<AudioDecoderSelector
> decoder_selector_
;
191 // These two will be set by AudioDecoderSelector::SelectAudioDecoder().
192 scoped_ptr
<AudioDecoder
> decoder_
;
193 scoped_ptr
<DecryptingDemuxerStream
> decrypting_demuxer_stream_
;
195 // AudioParameters constructed during Initialize() based on |decoder_|.
196 AudioParameters audio_parameters_
;
198 // Callbacks provided during Initialize().
199 PipelineStatusCB init_cb_
;
200 StatisticsCB statistics_cb_
;
201 base::Closure underflow_cb_
;
203 base::Closure ended_cb_
;
204 base::Closure disabled_cb_
;
205 PipelineStatusCB error_cb_
;
207 // Callback provided to Pause().
208 base::Closure pause_cb_
;
210 // Callback provided to Preroll().
211 PipelineStatusCB preroll_cb_
;
213 // Typically calls base::TimeTicks::Now() but can be overridden by a test.
216 // After Initialize() has completed, all variables below must be accessed
217 // under |lock_|. ------------------------------------------------------------
220 // Algorithm for scaling audio.
221 scoped_ptr
<AudioRendererAlgorithm
> algorithm_
;
223 // Simple state tracking variable.
226 // Keep track of whether or not the sink is playing.
229 // Keep track of our outstanding read to |decoder_|.
232 // Keeps track of whether we received and rendered the end of stream buffer.
233 bool received_end_of_stream_
;
234 bool rendered_end_of_stream_
;
236 // The timestamp of the last frame (i.e. furthest in the future) buffered as
237 // well as the current time that takes current playback delay into account.
238 base::TimeDelta audio_time_buffered_
;
239 base::TimeDelta current_time_
;
241 base::TimeDelta preroll_timestamp_
;
243 // We're supposed to know amount of audio data OS or hardware buffered, but
244 // that is not always so -- on my Linux box
245 // AudioBuffersState::hardware_delay_bytes never reaches 0.
247 // As a result we cannot use it to find when stream ends. If we just ignore
248 // buffered data we will notify host that stream ended before it is actually
249 // did so, I've seen it done ~140ms too early when playing ~150ms file.
251 // Instead of trying to invent OS-specific solution for each and every OS we
252 // are supporting, use simple workaround: every time we fill the buffer we
253 // remember when it should stop playing, and do not assume that buffer is
254 // empty till that time. Workaround is not bulletproof, as we don't exactly
255 // know when that particular data would start playing, but it is much better
257 base::TimeTicks earliest_end_time_
;
258 size_t total_frames_filled_
;
260 bool underflow_disabled_
;
261 bool increase_preroll_on_underflow_
;
263 // True if the renderer receives a buffer with kAborted status during preroll,
264 // false otherwise. This flag is cleared on the next Preroll() call.
265 bool preroll_aborted_
;
267 // End variables which must be accessed under |lock_|. ----------------------
269 DISALLOW_COPY_AND_ASSIGN(AudioRendererImpl
);
274 #endif // MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_