Upstream version 11.39.244.0
[platform/framework/web/crosswalk.git] / src / media / audio / audio_output_controller.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 #ifndef MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_
6 #define MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_
7
8 #if defined(OS_TIZEN)
9 #include <string>
10 #endif
11
12 #include "base/atomic_ref_count.h"
13 #include "base/callback.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/timer/timer.h"
16 #include "build/build_config.h"
17 #include "media/audio/audio_io.h"
18 #include "media/audio/audio_manager.h"
19 #include "media/audio/audio_power_monitor.h"
20 #include "media/audio/audio_source_diverter.h"
21 #include "media/audio/simple_sources.h"
22 #include "media/base/media_export.h"
23
24 // An AudioOutputController controls an AudioOutputStream and provides data
25 // to this output stream. It has an important function that it executes
26 // audio operations like play, pause, stop, etc. on a separate thread,
27 // namely the audio manager thread.
28 //
29 // All the public methods of AudioOutputController are non-blocking.
30 // The actual operations are performed on the audio manager thread.
31 //
32 // Here is a state transition diagram for the AudioOutputController:
33 //
34 //   *[ Empty ]  -->  [ Created ]  -->  [ Playing ]  -------.
35 //        |                |               |    ^           |
36 //        |                |               |    |           |
37 //        |                |               |    |           v
38 //        |                |               |    `-----  [ Paused ]
39 //        |                |               |                |
40 //        |                v               v                |
41 //        `----------->  [      Closed       ]  <-----------'
42 //
43 // * Initial state
44 //
45 // At any time after reaching the Created state but before Closed, the
46 // AudioOutputController may be notified of a device change via
47 // OnDeviceChange().  As the OnDeviceChange() is processed, state transitions
48 // will occur, ultimately ending up in an equivalent pre-call state.  E.g., if
49 // the state was Paused, the new state will be Created, since these states are
50 // all functionally equivalent and require a Play() call to continue to the next
51 // state.
52 //
53 // The AudioOutputStream can request data from the AudioOutputController via the
54 // AudioSourceCallback interface. AudioOutputController uses the SyncReader
55 // passed to it via construction to synchronously fulfill this read request.
56 //
57
58 namespace media {
59
60 class MEDIA_EXPORT AudioOutputController
61     : public base::RefCountedThreadSafe<AudioOutputController>,
62       public AudioOutputStream::AudioSourceCallback,
63       public AudioSourceDiverter,
64       NON_EXPORTED_BASE(public AudioManager::AudioDeviceListener)  {
65  public:
66   // An event handler that receives events from the AudioOutputController. The
67   // following methods are called on the audio manager thread.
68   class MEDIA_EXPORT EventHandler {
69    public:
70     virtual void OnCreated() = 0;
71     virtual void OnPlaying() = 0;
72     virtual void OnPaused() = 0;
73     virtual void OnError() = 0;
74     virtual void OnDeviceChange(int new_buffer_size, int new_sample_rate) = 0;
75
76 #if defined(OS_TIZEN)
77     virtual std::string app_id() const = 0;
78     virtual std::string app_class() const = 0;
79 #endif
80
81    protected:
82     virtual ~EventHandler() {}
83   };
84
85   // A synchronous reader interface used by AudioOutputController for
86   // synchronous reading.
87   // TODO(crogers): find a better name for this class and the Read() method
88   // now that it can handle synchronized I/O.
89   class SyncReader {
90    public:
91     virtual ~SyncReader() {}
92
93     // Notify the synchronous reader the number of bytes in the
94     // AudioOutputController not yet played. This is used by SyncReader to
95     // prepare more data and perform synchronization.
96     virtual void UpdatePendingBytes(uint32 bytes) = 0;
97
98     // Attempts to completely fill |dest|, zeroing |dest| if the request can not
99     // be fulfilled (due to timeout).
100     virtual void Read(AudioBus* dest) = 0;
101
102     // Close this synchronous reader.
103     virtual void Close() = 0;
104   };
105
106   // Factory method for creating an AudioOutputController.
107   // This also creates and opens an AudioOutputStream on the audio manager
108   // thread, and if this is successful, the |event_handler| will receive an
109   // OnCreated() call from the same audio manager thread.  |audio_manager| must
110   // outlive AudioOutputController.
111   // The |output_device_id| can be either empty (default device) or specify a
112   // specific hardware device for audio output.
113   static scoped_refptr<AudioOutputController> Create(
114       AudioManager* audio_manager, EventHandler* event_handler,
115       const AudioParameters& params, const std::string& output_device_id,
116       SyncReader* sync_reader);
117
118   // Indicates whether audio power level analysis will be performed.  If false,
119   // ReadCurrentPowerAndClip() can not be called.
120   static bool will_monitor_audio_levels() {
121 #if defined(OS_ANDROID) || defined(OS_IOS)
122     return false;
123 #else
124     return true;
125 #endif
126   }
127
128   // Methods to control playback of the stream.
129
130   // Starts the playback of this audio output stream.
131   void Play();
132
133   // Pause this audio output stream.
134   void Pause();
135
136   // Closes the audio output stream. The state is changed and the resources
137   // are freed on the audio manager thread. closed_task is executed after that.
138   // Callbacks (EventHandler and SyncReader) must exist until closed_task is
139   // called.
140   //
141   // It is safe to call this method more than once. Calls after the first one
142   // will have no effect.
143   void Close(const base::Closure& closed_task);
144
145   // Sets the volume of the audio output stream.
146   void SetVolume(double volume);
147
148   // Calls |callback| (on the caller's thread) with the current output
149   // device ID.
150   void GetOutputDeviceId(
151       base::Callback<void(const std::string&)> callback) const;
152
153   // Changes which output device to use. If desired, you can provide a
154   // callback that will be notified (on the thread you called from)
155   // when the function has completed execution.
156   //
157   // Changing the output device causes the controller to go through
158   // the same state transition back to the current state as a call to
159   // OnDeviceChange (unless it is currently diverting, see
160   // Start/StopDiverting below, in which case the state transition
161   // will happen when StopDiverting is called).
162   void SwitchOutputDevice(const std::string& output_device_id,
163                           const base::Closure& callback);
164
165   // AudioSourceCallback implementation.
166   virtual int OnMoreData(AudioBus* dest,
167                          AudioBuffersState buffers_state) OVERRIDE;
168   virtual void OnError(AudioOutputStream* stream) OVERRIDE;
169
170   // AudioDeviceListener implementation.  When called AudioOutputController will
171   // shutdown the existing |stream_|, transition to the kRecreating state,
172   // create a new stream, and then transition back to an equivalent state prior
173   // to being called.
174   virtual void OnDeviceChange() OVERRIDE;
175
176   // AudioSourceDiverter implementation.
177   virtual const AudioParameters& GetAudioParameters() OVERRIDE;
178   virtual void StartDiverting(AudioOutputStream* to_stream) OVERRIDE;
179   virtual void StopDiverting() OVERRIDE;
180
181   // Accessor for AudioPowerMonitor::ReadCurrentPowerAndClip().  See comments in
182   // audio_power_monitor.h for usage.  This may be called on any thread.
183   std::pair<float, bool> ReadCurrentPowerAndClip();
184
185  protected:
186   // Internal state of the source.
187   enum State {
188     kEmpty,
189     kCreated,
190     kPlaying,
191     kPaused,
192     kClosed,
193     kError,
194   };
195
196   // Time constant for AudioPowerMonitor.  See AudioPowerMonitor ctor comments
197   // for semantics.  This value was arbitrarily chosen, but seems to work well.
198   enum { kPowerMeasurementTimeConstantMillis = 10 };
199
200   friend class base::RefCountedThreadSafe<AudioOutputController>;
201   virtual ~AudioOutputController();
202
203  private:
204   AudioOutputController(AudioManager* audio_manager, EventHandler* handler,
205                         const AudioParameters& params,
206                         const std::string& output_device_id,
207                         SyncReader* sync_reader);
208
209   // The following methods are executed on the audio manager thread.
210   void DoCreate(bool is_for_device_change);
211   void DoPlay();
212   void DoPause();
213   void DoClose();
214   void DoSetVolume(double volume);
215   std::string DoGetOutputDeviceId() const;
216   void DoSwitchOutputDevice(const std::string& output_device_id);
217   void DoReportError();
218   void DoStartDiverting(AudioOutputStream* to_stream);
219   void DoStopDiverting();
220
221   // Helper method that stops the physical stream.
222   void StopStream();
223
224   // Helper method that stops, closes, and NULLs |*stream_|.
225   void DoStopCloseAndClearStream();
226
227   // Checks if a stream was started successfully but never calls OnMoreData().
228   void WedgeCheck();
229
230   AudioManager* const audio_manager_;
231   const AudioParameters params_;
232   EventHandler* const handler_;
233
234   // Specifies the device id of the output device to open or empty for the
235   // default output device.
236   std::string output_device_id_;
237
238   AudioOutputStream* stream_;
239
240   // When non-NULL, audio is being diverted to this stream.
241   AudioOutputStream* diverting_to_stream_;
242
243   // The current volume of the audio stream.
244   double volume_;
245
246   // |state_| is written on the audio manager thread and is read on the
247   // hardware audio thread. These operations need to be locked. But lock
248   // is not required for reading on the audio manager thread.
249   State state_;
250
251   // SyncReader is used only in low latency mode for synchronous reading.
252   SyncReader* const sync_reader_;
253
254   // The message loop of audio manager thread that this object runs on.
255   const scoped_refptr<base::SingleThreadTaskRunner> message_loop_;
256
257   // Scans audio samples from OnMoreData() as input to compute power levels.
258   AudioPowerMonitor power_monitor_;
259
260   // Flags when we've asked for a stream to start but it never did.
261   base::AtomicRefCount on_more_io_data_called_;
262   scoped_ptr<base::OneShotTimer<AudioOutputController> > wedge_timer_;
263
264   DISALLOW_COPY_AND_ASSIGN(AudioOutputController);
265 };
266
267 }  // namespace media
268
269 #endif  // MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_