Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / media / filters / audio_renderer_impl.h
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.
4
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.
14 //
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.
18
19 #ifndef MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_
20 #define MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_
21
22 #include <deque>
23
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"
33
34 namespace base {
35 class SingleThreadTaskRunner;
36 }
37
38 namespace media {
39
40 class AudioBus;
41 class AudioBufferConverter;
42 class AudioSplicer;
43 class DecryptingDemuxerStream;
44 class AudioHardwareConfig;
45
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.
51   //
52   // |sink| is used as the destination for the rendered audio.
53   //
54   // |decoders| contains the AudioDecoders to use when initializing.
55   //
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();
65
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;
84
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();
90
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;
95   }
96
97  private:
98   friend class AudioRendererImplTest;
99
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,
111   };
112
113   // Callback from the audio decoder delivering decoded audio samples.
114   void DecodedAudioReady(AudioBufferStream::Status status,
115                          const scoped_refptr<AudioBuffer>& buffer);
116
117   // Handles buffers that come out of |splicer_|.
118   // Returns true if more buffers are needed.
119   bool HandleSplicerBuffer(const scoped_refptr<AudioBuffer>& buffer);
120
121   // Helper functions for AudioDecoder::Status values passed to
122   // DecodedAudioReady().
123   void HandleAbortedReadOrDecodeError(bool is_decode_error);
124
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);
129
130   void DoPlay_Locked();
131   void DoPause_Locked();
132
133   // AudioRendererSink::RenderCallback implementation.
134   //
135   // NOTE: These are called on the audio callback thread!
136   //
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|
141   //
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.
146   //
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;
155
156   // Helper methods that schedule an asynchronous read from the decoder as long
157   // as there isn't a pending read.
158   //
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);
164
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);
169
170   // Called upon AudioBufferStream initialization, or failure thereof (indicated
171   // by the value of |success|).
172   void OnAudioBufferStreamInitialized(bool succes);
173
174   // Used to initiate the flush operation once all pending reads have
175   // completed.
176   void DoFlush_Locked();
177
178   // Calls |decoder_|.Reset() and arranges for ResetDecoderDone() to get
179   // called when the reset completes.
180   void ResetDecoder();
181
182   // Called when the |decoder_|.Reset() has completed.
183   void ResetDecoderDone();
184
185   // Called by the AudioBufferStream when a splice buffer is demuxed.
186   void OnNewSpliceBuffer(base::TimeDelta);
187
188   // Called by the AudioBufferStream when a config change occurs.
189   void OnConfigChange();
190
191   scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
192
193   scoped_ptr<AudioSplicer> splicer_;
194   scoped_ptr<AudioBufferConverter> buffer_converter_;
195
196   // Whether or not we expect to handle config changes.
197   bool expecting_config_changes_;
198
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_;
203
204   AudioBufferStream audio_buffer_stream_;
205
206   // Interface to the hardware audio params.
207   const AudioHardwareConfig* const hardware_config_;
208
209   // Cached copy of hardware params from |hardware_config_|.
210   AudioParameters audio_parameters_;
211
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_;
219
220   // Callback provided to Flush().
221   base::Closure flush_cb_;
222
223   // Callback provided to Preroll().
224   PipelineStatusCB preroll_cb_;
225
226   // Typically calls base::TimeTicks::Now() but can be overridden by a test.
227   NowCB now_cb_;
228
229   // After Initialize() has completed, all variables below must be accessed
230   // under |lock_|. ------------------------------------------------------------
231   base::Lock lock_;
232
233   // Algorithm for scaling audio.
234   scoped_ptr<AudioRendererAlgorithm> algorithm_;
235
236   // Simple state tracking variable.
237   State state_;
238
239   // Keep track of whether or not the sink is playing.
240   bool sink_playing_;
241
242   // Keep track of our outstanding read to |decoder_|.
243   bool pending_read_;
244
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_;
248
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_;
253
254   base::TimeDelta preroll_timestamp_;
255
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.
259   //
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.
263   //
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_;
272
273   bool underflow_disabled_;
274
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_;
278
279   // End variables which must be accessed under |lock_|. ----------------------
280
281   // NOTE: Weak pointers must be invalidated before all other member variables.
282   base::WeakPtrFactory<AudioRendererImpl> weak_factory_;
283
284   DISALLOW_COPY_AND_ASSIGN(AudioRendererImpl);
285 };
286
287 }  // namespace media
288
289 #endif  // MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_