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/scoped_ptr.h"
26 #include "base/memory/weak_ptr.h"
27 #include "base/synchronization/lock.h"
28 #include "media/base/audio_decoder.h"
29 #include "media/base/audio_renderer.h"
30 #include "media/base/audio_renderer_sink.h"
31 #include "media/base/decryptor.h"
32 #include "media/base/time_source.h"
33 #include "media/filters/audio_renderer_algorithm.h"
34 #include "media/filters/decoder_stream.h"
37 class SingleThreadTaskRunner;
42 class AudioBufferConverter;
45 class AudioHardwareConfig;
47 class DecryptingDemuxerStream;
49 class MEDIA_EXPORT AudioRendererImpl
50 : public AudioRenderer,
52 NON_EXPORTED_BASE(public AudioRendererSink::RenderCallback) {
54 // |task_runner| is the thread on which AudioRendererImpl will execute.
56 // |sink| is used as the destination for the rendered audio.
58 // |decoders| contains the AudioDecoders to use when initializing.
60 // |set_decryptor_ready_cb| is fired when the audio decryptor is available
61 // (only applicable if the stream is encrypted and we have a decryptor).
63 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
64 AudioRendererSink* sink,
65 ScopedVector<AudioDecoder> decoders,
66 const SetDecryptorReadyCB& set_decryptor_ready_cb,
67 AudioHardwareConfig* hardware_params);
68 virtual ~AudioRendererImpl();
70 // TimeSource implementation.
71 virtual void StartTicking() OVERRIDE;
72 virtual void StopTicking() OVERRIDE;
73 virtual void SetPlaybackRate(float rate) OVERRIDE;
74 virtual void SetMediaTime(base::TimeDelta time) OVERRIDE;
75 virtual base::TimeDelta CurrentMediaTime() OVERRIDE;
77 // AudioRenderer implementation.
78 virtual void Initialize(DemuxerStream* stream,
79 const PipelineStatusCB& init_cb,
80 const StatisticsCB& statistics_cb,
81 const TimeCB& time_cb,
82 const BufferingStateCB& buffering_state_cb,
83 const base::Closure& ended_cb,
84 const PipelineStatusCB& error_cb) OVERRIDE;
85 virtual TimeSource* GetTimeSource() OVERRIDE;
86 virtual void Flush(const base::Closure& callback) OVERRIDE;
87 virtual void StartPlaying() OVERRIDE;
88 virtual void SetVolume(float volume) OVERRIDE;
91 friend class AudioRendererImplTest;
93 // Important detail: being in kPlaying doesn't imply that audio is being
94 // rendered. Rather, it means that the renderer is ready to go. The actual
95 // rendering of audio is controlled via Start/StopRendering().
102 // | Decoders initialized
105 // kFlushed <------------------ kFlushing
106 // | StartPlaying() ^
109 // `---------> kPlaying --------'
118 // Callback from the audio decoder delivering decoded audio samples.
119 void DecodedAudioReady(AudioBufferStream::Status status,
120 const scoped_refptr<AudioBuffer>& buffer);
122 // Handles buffers that come out of |splicer_|.
123 // Returns true if more buffers are needed.
124 bool HandleSplicerBuffer_Locked(const scoped_refptr<AudioBuffer>& buffer);
126 // Helper functions for AudioDecoder::Status values passed to
127 // DecodedAudioReady().
128 void HandleAbortedReadOrDecodeError(bool is_decode_error);
130 void StartRendering_Locked();
131 void StopRendering_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_|.
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 |start_timestamp_|.
166 // This can only return true while in the kPlaying state.
167 bool IsBeforeStartTime(const scoped_refptr<AudioBuffer>& buffer);
169 // Called upon AudioBufferStream initialization, or failure thereof (indicated
170 // by the value of |success|).
171 void OnAudioBufferStreamInitialized(bool succes);
173 // Used to initiate the flush operation once all pending reads have
175 void DoFlush_Locked();
177 // Calls |decoder_|.Reset() and arranges for ResetDecoderDone() to get
178 // called when the reset completes.
181 // Called when the |decoder_|.Reset() has completed.
182 void ResetDecoderDone();
184 // Called by the AudioBufferStream when a splice buffer is demuxed.
185 void OnNewSpliceBuffer(base::TimeDelta);
187 // Called by the AudioBufferStream when a config change occurs.
188 void OnConfigChange();
190 // Updates |buffering_state_| and fires |buffering_state_cb_|.
191 void SetBufferingState_Locked(BufferingState buffering_state);
193 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
195 scoped_ptr<AudioSplicer> splicer_;
196 scoped_ptr<AudioBufferConverter> buffer_converter_;
198 // Whether or not we expect to handle config changes.
199 bool expecting_config_changes_;
201 // The sink (destination) for rendered audio. |sink_| must only be accessed
202 // on |task_runner_|. |sink_| must never be called under |lock_| or else we
203 // may deadlock between |task_runner_| and the audio callback thread.
204 scoped_refptr<media::AudioRendererSink> sink_;
206 scoped_ptr<AudioBufferStream> audio_buffer_stream_;
208 // Interface to the hardware audio params.
209 const AudioHardwareConfig* const hardware_config_;
211 // Cached copy of hardware params from |hardware_config_|.
212 AudioParameters audio_parameters_;
214 // Callbacks provided during Initialize().
215 PipelineStatusCB init_cb_;
217 BufferingStateCB buffering_state_cb_;
218 base::Closure ended_cb_;
219 PipelineStatusCB error_cb_;
221 // Callback provided to Flush().
222 base::Closure flush_cb_;
224 // After Initialize() has completed, all variables below must be accessed
225 // under |lock_|. ------------------------------------------------------------
228 // Algorithm for scaling audio.
229 float playback_rate_;
230 scoped_ptr<AudioRendererAlgorithm> algorithm_;
232 // Simple state tracking variable.
235 BufferingState buffering_state_;
237 // Keep track of whether or not the sink is playing and whether we should be
242 // Keep track of our outstanding read to |decoder_|.
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 scoped_ptr<AudioClock> audio_clock_;
251 base::TimeDelta start_timestamp_;
252 base::TimeDelta last_timestamp_update_;
254 // End variables which must be accessed under |lock_|. ----------------------
256 // NOTE: Weak pointers must be invalidated before all other member variables.
257 base::WeakPtrFactory<AudioRendererImpl> weak_factory_;
259 DISALLOW_COPY_AND_ASSIGN(AudioRendererImpl);
264 #endif // MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_