Upstream version 9.38.198.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/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"
35
36 namespace base {
37 class SingleThreadTaskRunner;
38 }
39
40 namespace media {
41
42 class AudioBufferConverter;
43 class AudioBus;
44 class AudioClock;
45 class AudioHardwareConfig;
46 class AudioSplicer;
47 class DecryptingDemuxerStream;
48
49 class MEDIA_EXPORT AudioRendererImpl
50     : public AudioRenderer,
51       public TimeSource,
52       NON_EXPORTED_BASE(public AudioRendererSink::RenderCallback) {
53  public:
54   // |task_runner| is the thread on which AudioRendererImpl will execute.
55   //
56   // |sink| is used as the destination for the rendered audio.
57   //
58   // |decoders| contains the AudioDecoders to use when initializing.
59   //
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).
62   AudioRendererImpl(
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();
69
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;
76
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;
89
90  private:
91   friend class AudioRendererImplTest;
92
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().
96   //
97   //   kUninitialized
98   //         | Initialize()
99   //         |
100   //         V
101   //    kInitializing
102   //         | Decoders initialized
103   //         |
104   //         V            Decoders reset
105   //      kFlushed <------------------ kFlushing
106   //         | StartPlaying()             ^
107   //         |                            |
108   //         |                            | Flush()
109   //         `---------> kPlaying --------'
110   enum State {
111     kUninitialized,
112     kInitializing,
113     kFlushing,
114     kFlushed,
115     kPlaying
116   };
117
118   // Callback from the audio decoder delivering decoded audio samples.
119   void DecodedAudioReady(AudioBufferStream::Status status,
120                          const scoped_refptr<AudioBuffer>& buffer);
121
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);
125
126   // Helper functions for AudioDecoder::Status values passed to
127   // DecodedAudioReady().
128   void HandleAbortedReadOrDecodeError(bool is_decode_error);
129
130   void StartRendering_Locked();
131   void StopRendering_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 |start_timestamp_|.
166   // This can only return true while in the kPlaying state.
167   bool IsBeforeStartTime(const scoped_refptr<AudioBuffer>& buffer);
168
169   // Called upon AudioBufferStream initialization, or failure thereof (indicated
170   // by the value of |success|).
171   void OnAudioBufferStreamInitialized(bool succes);
172
173   // Used to initiate the flush operation once all pending reads have
174   // completed.
175   void DoFlush_Locked();
176
177   // Calls |decoder_|.Reset() and arranges for ResetDecoderDone() to get
178   // called when the reset completes.
179   void ResetDecoder();
180
181   // Called when the |decoder_|.Reset() has completed.
182   void ResetDecoderDone();
183
184   // Called by the AudioBufferStream when a splice buffer is demuxed.
185   void OnNewSpliceBuffer(base::TimeDelta);
186
187   // Called by the AudioBufferStream when a config change occurs.
188   void OnConfigChange();
189
190   // Updates |buffering_state_| and fires |buffering_state_cb_|.
191   void SetBufferingState_Locked(BufferingState buffering_state);
192
193   scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
194
195   scoped_ptr<AudioSplicer> splicer_;
196   scoped_ptr<AudioBufferConverter> buffer_converter_;
197
198   // Whether or not we expect to handle config changes.
199   bool expecting_config_changes_;
200
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_;
205
206   scoped_ptr<AudioBufferStream> audio_buffer_stream_;
207
208   // Interface to the hardware audio params.
209   const AudioHardwareConfig* const hardware_config_;
210
211   // Cached copy of hardware params from |hardware_config_|.
212   AudioParameters audio_parameters_;
213
214   // Callbacks provided during Initialize().
215   PipelineStatusCB init_cb_;
216   TimeCB time_cb_;
217   BufferingStateCB buffering_state_cb_;
218   base::Closure ended_cb_;
219   PipelineStatusCB error_cb_;
220
221   // Callback provided to Flush().
222   base::Closure flush_cb_;
223
224   // After Initialize() has completed, all variables below must be accessed
225   // under |lock_|. ------------------------------------------------------------
226   base::Lock lock_;
227
228   // Algorithm for scaling audio.
229   float playback_rate_;
230   scoped_ptr<AudioRendererAlgorithm> algorithm_;
231
232   // Simple state tracking variable.
233   State state_;
234
235   BufferingState buffering_state_;
236
237   // Keep track of whether or not the sink is playing and whether we should be
238   // rendering.
239   bool rendering_;
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   scoped_ptr<AudioClock> audio_clock_;
250
251   base::TimeDelta start_timestamp_;
252   base::TimeDelta last_timestamp_update_;
253
254   // End variables which must be accessed under |lock_|. ----------------------
255
256   // NOTE: Weak pointers must be invalidated before all other member variables.
257   base::WeakPtrFactory<AudioRendererImpl> weak_factory_;
258
259   DISALLOW_COPY_AND_ASSIGN(AudioRendererImpl);
260 };
261
262 }  // namespace media
263
264 #endif  // MEDIA_FILTERS_AUDIO_RENDERER_IMPL_H_