audio_output_controller.h revision 1e9bf3e0803691d0a228da41fc608347b6db4340
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#include "base/atomic_ref_count.h"
9#include "base/callback.h"
10#include "base/cancelable_callback.h"
11#include "base/memory/ref_counted.h"
12#include "media/audio/audio_io.h"
13#include "media/audio/audio_manager.h"
14#include "media/audio/audio_power_monitor.h"
15#include "media/audio/audio_source_diverter.h"
16#include "media/audio/simple_sources.h"
17#include "media/base/media_export.h"
18
19// An AudioOutputController controls an AudioOutputStream and provides data
20// to this output stream. It has an important function that it executes
21// audio operations like play, pause, stop, etc. on a separate thread,
22// namely the audio manager thread.
23//
24// All the public methods of AudioOutputController are non-blocking.
25// The actual operations are performed on the audio manager thread.
26//
27// Here is a state transition diagram for the AudioOutputController:
28//
29//   *[ Empty ]  -->  [ Created ]  -->  [ Playing ]  -------.
30//        |                |               |    ^           |
31//        |                |               |    |           |
32//        |                |               |    |           v
33//        |                |               |    `-----  [ Paused ]
34//        |                |               |                |
35//        |                v               v                |
36//        `----------->  [      Closed       ]  <-----------'
37//
38// * Initial state
39//
40// At any time after reaching the Created state but before Closed, the
41// AudioOutputController may be notified of a device change via
42// OnDeviceChange().  As the OnDeviceChange() is processed, state transitions
43// will occur, ultimately ending up in an equivalent pre-call state.  E.g., if
44// the state was Paused, the new state will be Created, since these states are
45// all functionally equivalent and require a Play() call to continue to the next
46// state.
47//
48// The AudioOutputStream can request data from the AudioOutputController via the
49// AudioSourceCallback interface. AudioOutputController uses the SyncReader
50// passed to it via construction to synchronously fulfill this read request.
51//
52
53namespace media {
54
55// Only do power monitoring for non-mobile platforms that need it for the UI.
56#if !defined(OS_ANDROID) && !defined(OS_IOS)
57#define AUDIO_POWER_MONITORING
58#endif
59
60class 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 OnPowerMeasured(float power_dbfs, bool clipped) = 0;
73    virtual void OnPaused() = 0;
74    virtual void OnError() = 0;
75    virtual void OnDeviceChange(int new_buffer_size, int new_sample_rate) = 0;
76
77   protected:
78    virtual ~EventHandler() {}
79  };
80
81  // A synchronous reader interface used by AudioOutputController for
82  // synchronous reading.
83  // TODO(crogers): find a better name for this class and the Read() method
84  // now that it can handle synchronized I/O.
85  class SyncReader {
86   public:
87    virtual ~SyncReader() {}
88
89    // Notify the synchronous reader the number of bytes in the
90    // AudioOutputController not yet played. This is used by SyncReader to
91    // prepare more data and perform synchronization.
92    virtual void UpdatePendingBytes(uint32 bytes) = 0;
93
94    // Attempts to completely fill |dest|, zeroing |dest| if the request can not
95    // be fulfilled (due to timeout).  |source| may optionally be provided for
96    // input data.
97    virtual void Read(const AudioBus* source, AudioBus* dest) = 0;
98
99    // Close this synchronous reader.
100    virtual void Close() = 0;
101  };
102
103  // Factory method for creating an AudioOutputController.
104  // This also creates and opens an AudioOutputStream on the audio manager
105  // thread, and if this is successful, the |event_handler| will receive an
106  // OnCreated() call from the same audio manager thread.  |audio_manager| must
107  // outlive AudioOutputController.
108  // The |output_device_id| can be either empty (default device) or specify a
109  // specific hardware device for audio output.  The |input_device_id| is
110  // used only for unified audio when opening up input and output at the same
111  // time (controlled by |params.input_channel_count()|).
112  static scoped_refptr<AudioOutputController> Create(
113      AudioManager* audio_manager, EventHandler* event_handler,
114      const AudioParameters& params, const std::string& output_device_id,
115      const std::string& input_device_id, SyncReader* sync_reader);
116
117  // Methods to control playback of the stream.
118
119  // Starts the playback of this audio output stream.
120  void Play();
121
122  // Pause this audio output stream.
123  void Pause();
124
125  // Closes the audio output stream. The state is changed and the resources
126  // are freed on the audio manager thread. closed_task is executed after that.
127  // Callbacks (EventHandler and SyncReader) must exist until closed_task is
128  // called.
129  //
130  // It is safe to call this method more than once. Calls after the first one
131  // will have no effect.
132  void Close(const base::Closure& closed_task);
133
134  // Sets the volume of the audio output stream.
135  void SetVolume(double volume);
136
137  // Calls |callback| (on the caller's thread) with the current output
138  // device ID.
139  void GetOutputDeviceId(
140      base::Callback<void(const std::string&)> callback) const;
141
142  // Changes which output device to use. If desired, you can provide a
143  // callback that will be notified (on the thread you called from)
144  // when the function has completed execution.
145  //
146  // Changing the output device causes the controller to go through
147  // the same state transition back to the current state as a call to
148  // OnDeviceChange (unless it is currently diverting, see
149  // Start/StopDiverting below, in which case the state transition
150  // will happen when StopDiverting is called).
151  void SwitchOutputDevice(const std::string& output_device_id,
152                          const base::Closure& callback);
153
154  // AudioSourceCallback implementation.
155  virtual int OnMoreData(AudioBus* dest,
156                         AudioBuffersState buffers_state) OVERRIDE;
157  virtual int OnMoreIOData(AudioBus* source,
158                           AudioBus* dest,
159                           AudioBuffersState buffers_state) OVERRIDE;
160  virtual void OnError(AudioOutputStream* stream) OVERRIDE;
161
162  // AudioDeviceListener implementation.  When called AudioOutputController will
163  // shutdown the existing |stream_|, transition to the kRecreating state,
164  // create a new stream, and then transition back to an equivalent state prior
165  // to being called.
166  virtual void OnDeviceChange() OVERRIDE;
167
168  // AudioSourceDiverter implementation.
169  virtual const AudioParameters& GetAudioParameters() OVERRIDE;
170  virtual void StartDiverting(AudioOutputStream* to_stream) OVERRIDE;
171  virtual void StopDiverting() OVERRIDE;
172
173 protected:
174  // Internal state of the source.
175  enum State {
176    kEmpty,
177    kCreated,
178    kPlaying,
179    kPaused,
180    kClosed,
181    kError,
182  };
183
184  friend class base::RefCountedThreadSafe<AudioOutputController>;
185  virtual ~AudioOutputController();
186
187 private:
188  // We are polling sync reader if data became available.
189  static const int kPollNumAttempts;
190  static const int kPollPauseInMilliseconds;
191
192  AudioOutputController(AudioManager* audio_manager, EventHandler* handler,
193                        const AudioParameters& params,
194                        const std::string& output_device_id,
195                        const std::string& input_device_id,
196                        SyncReader* sync_reader);
197
198  // The following methods are executed on the audio manager thread.
199  void DoCreate(bool is_for_device_change);
200  void DoPlay();
201  void DoPause();
202  void DoClose();
203  void DoSetVolume(double volume);
204  std::string DoGetOutputDeviceId() const;
205  void DoSwitchOutputDevice(const std::string& output_device_id);
206  void DoReportError();
207  void DoStartDiverting(AudioOutputStream* to_stream);
208  void DoStopDiverting();
209
210  // Calls EventHandler::OnPowerMeasured() with the current power level and then
211  // schedules itself to be called again later.
212  void ReportPowerMeasurementPeriodically();
213
214  // Helper method that stops the physical stream.
215  void StopStream();
216
217  // Helper method that stops, closes, and NULLs |*stream_|.
218  void DoStopCloseAndClearStream();
219
220  // Sanity-check that entry/exit to OnMoreIOData() by the hardware audio thread
221  // happens only between AudioOutputStream::Start() and Stop().
222  void AllowEntryToOnMoreIOData();
223  void DisallowEntryToOnMoreIOData();
224
225  AudioManager* const audio_manager_;
226  const AudioParameters params_;
227  EventHandler* const handler_;
228
229  // Specifies the device id of the output device to open or empty for the
230  // default output device.
231  std::string output_device_id_;
232
233  // Used by the unified IO to open the correct input device.
234  const std::string input_device_id_;
235
236  AudioOutputStream* stream_;
237
238  // When non-NULL, audio is being diverted to this stream.
239  AudioOutputStream* diverting_to_stream_;
240
241  // The current volume of the audio stream.
242  double volume_;
243
244  // |state_| is written on the audio manager thread and is read on the
245  // hardware audio thread. These operations need to be locked. But lock
246  // is not required for reading on the audio manager thread.
247  State state_;
248
249  // Binary semaphore, used to ensure that only one thread enters the
250  // OnMoreIOData() method, and only when it is valid to do so.  This is for
251  // sanity-checking the behavior of platform implementations of
252  // AudioOutputStream.  In other words, multiple contention is not expected,
253  // nor in the design here.
254  base::AtomicRefCount num_allowed_io_;
255
256  // SyncReader is used only in low latency mode for synchronous reading.
257  SyncReader* const sync_reader_;
258
259  // The message loop of audio manager thread that this object runs on.
260  const scoped_refptr<base::MessageLoopProxy> message_loop_;
261
262#if defined(AUDIO_POWER_MONITORING)
263  // Scans audio samples from OnMoreIOData() as input to compute power levels.
264  AudioPowerMonitor power_monitor_;
265
266  // Periodic callback to report power levels during playback.
267  base::CancelableClosure power_poll_callback_;
268#endif
269
270  // When starting stream we wait for data to become available.
271  // Number of times left.
272  int number_polling_attempts_left_;
273
274  DISALLOW_COPY_AND_ASSIGN(AudioOutputController);
275};
276
277}  // namespace media
278
279#endif  // MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_
280