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_RENDERERS_AUDIO_RENDERER_IMPL_H_
20 #define MEDIA_RENDERERS_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/media_log.h"
33 #include "media/base/time_source.h"
34 #include "media/filters/audio_renderer_algorithm.h"
35 #include "media/filters/decoder_stream.h"
38 class SingleThreadTaskRunner
;
43 class AudioBufferConverter
;
46 class AudioHardwareConfig
;
48 class DecryptingDemuxerStream
;
50 class MEDIA_EXPORT AudioRendererImpl
51 : public AudioRenderer
,
53 NON_EXPORTED_BASE(public AudioRendererSink::RenderCallback
) {
55 // |task_runner| is the thread on which AudioRendererImpl will execute.
57 // |sink| is used as the destination for the rendered audio.
59 // |decoders| contains the AudioDecoders to use when initializing.
61 const scoped_refptr
<base::SingleThreadTaskRunner
>& task_runner
,
62 AudioRendererSink
* sink
,
63 ScopedVector
<AudioDecoder
> decoders
,
64 const AudioHardwareConfig
& hardware_config
,
65 const scoped_refptr
<MediaLog
>& media_log
);
66 ~AudioRendererImpl() override
;
68 // TimeSource implementation.
69 void StartTicking() override
;
70 void StopTicking() override
;
71 void SetPlaybackRate(float rate
) override
;
72 void SetMediaTime(base::TimeDelta time
) override
;
73 base::TimeDelta
CurrentMediaTime() override
;
74 base::TimeTicks
GetWallClockTime(base::TimeDelta time
) override
;
76 // AudioRenderer implementation.
77 void Initialize(DemuxerStream
* stream
,
78 const PipelineStatusCB
& init_cb
,
79 const SetDecryptorReadyCB
& set_decryptor_ready_cb
,
80 const StatisticsCB
& statistics_cb
,
81 const BufferingStateCB
& buffering_state_cb
,
82 const base::Closure
& ended_cb
,
83 const PipelineStatusCB
& error_cb
,
84 const base::Closure
& waiting_for_decryption_key_cb
) override
;
85 TimeSource
* GetTimeSource() override
;
86 void Flush(const base::Closure
& callback
) override
;
87 void StartPlaying() override
;
88 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 int Render(AudioBus
* audio_bus
, int audio_delay_milliseconds
) override
;
153 void OnRenderError() override
;
155 // Helper methods that schedule an asynchronous read from the decoder as long
156 // as there isn't a pending read.
158 // Must be called on |task_runner_|.
160 void AttemptRead_Locked();
161 bool CanRead_Locked();
162 void ChangeState_Locked(State new_state
);
164 // Returns true if the data in the buffer is all before |start_timestamp_|.
165 // This can only return true while in the kPlaying state.
166 bool IsBeforeStartTime(const scoped_refptr
<AudioBuffer
>& buffer
);
168 // Called upon AudioBufferStream initialization, or failure thereof (indicated
169 // by the value of |success|).
170 void OnAudioBufferStreamInitialized(bool succes
);
172 // Used to initiate the flush operation once all pending reads have
174 void DoFlush_Locked();
176 // Calls |decoder_|.Reset() and arranges for ResetDecoderDone() to get
177 // called when the reset completes.
180 // Called when the |decoder_|.Reset() has completed.
181 void ResetDecoderDone();
183 // Called by the AudioBufferStream when a splice buffer is demuxed.
184 void OnNewSpliceBuffer(base::TimeDelta
);
186 // Called by the AudioBufferStream when a config change occurs.
187 void OnConfigChange();
189 // Updates |buffering_state_| and fires |buffering_state_cb_|.
190 void SetBufferingState_Locked(BufferingState buffering_state
);
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 scoped_ptr
<AudioBufferStream
> audio_buffer_stream_
;
207 // Interface to the hardware audio params.
208 const AudioHardwareConfig
& 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 BufferingStateCB buffering_state_cb_
;
216 base::Closure ended_cb_
;
217 PipelineStatusCB error_cb_
;
219 // Callback provided to Flush().
220 base::Closure flush_cb_
;
222 // After Initialize() has completed, all variables below must be accessed
223 // under |lock_|. ------------------------------------------------------------
226 // Algorithm for scaling audio.
227 float playback_rate_
;
228 scoped_ptr
<AudioRendererAlgorithm
> algorithm_
;
230 // Simple state tracking variable.
233 BufferingState buffering_state_
;
235 // Keep track of whether or not the sink is playing and whether we should be
240 // Keep track of our outstanding read to |decoder_|.
243 // Keeps track of whether we received and rendered the end of stream buffer.
244 bool received_end_of_stream_
;
245 bool rendered_end_of_stream_
;
247 scoped_ptr
<AudioClock
> audio_clock_
;
249 // The media timestamp to begin playback at after seeking. Set via
251 base::TimeDelta start_timestamp_
;
253 // The media timestamp to signal end of audio playback. Determined during
254 // Render() when writing the final frames of decoded audio data.
255 base::TimeDelta ended_timestamp_
;
257 // Set every Render() and used to provide an interpolated time value to
258 // CurrentMediaTimeForSyncingVideo().
259 base::TimeTicks last_render_ticks_
;
261 // Set upon receipt of the first decoded buffer after a StartPlayingFrom().
262 // Used to determine how long to delay playback.
263 base::TimeDelta first_packet_timestamp_
;
265 // End variables which must be accessed under |lock_|. ----------------------
267 // NOTE: Weak pointers must be invalidated before all other member variables.
268 base::WeakPtrFactory
<AudioRendererImpl
> weak_factory_
;
270 DISALLOW_COPY_AND_ASSIGN(AudioRendererImpl
);
275 #endif // MEDIA_RENDERERS_AUDIO_RENDERER_IMPL_H_