audio_output_controller.h revision 58537e28ecd584eab876aee8be7156509866d23a
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
55class MEDIA_EXPORT AudioOutputController
56    : public base::RefCountedThreadSafe<AudioOutputController>,
57      public AudioOutputStream::AudioSourceCallback,
58      public AudioSourceDiverter,
59      NON_EXPORTED_BASE(public AudioManager::AudioDeviceListener)  {
60 public:
61  // An event handler that receives events from the AudioOutputController. The
62  // following methods are called on the audio manager thread.
63  class MEDIA_EXPORT EventHandler {
64   public:
65    virtual void OnCreated() = 0;
66    virtual void OnPlaying() = 0;
67    virtual void OnPowerMeasured(float power_dbfs, bool clipped) = 0;
68    virtual void OnPaused() = 0;
69    virtual void OnError() = 0;
70    virtual void OnDeviceChange(int new_buffer_size, int new_sample_rate) = 0;
71
72   protected:
73    virtual ~EventHandler() {}
74  };
75
76  // A synchronous reader interface used by AudioOutputController for
77  // synchronous reading.
78  // TODO(crogers): find a better name for this class and the Read() method
79  // now that it can handle synchronized I/O.
80  class SyncReader {
81   public:
82    virtual ~SyncReader() {}
83
84    // Notify the synchronous reader the number of bytes in the
85    // AudioOutputController not yet played. This is used by SyncReader to
86    // prepare more data and perform synchronization.
87    virtual void UpdatePendingBytes(uint32 bytes) = 0;
88
89    // Attempt to completely fill |dest|, return the actual number of frames
90    // that could be read.  |source| may optionally be provided for input data.
91    // If |block| is specified, the Read() will block until data is available
92    // or a timeout is reached.
93    virtual int Read(bool block, const AudioBus* source, AudioBus* dest) = 0;
94
95    // Close this synchronous reader.
96    virtual void Close() = 0;
97  };
98
99  // Factory method for creating an AudioOutputController.
100  // This also creates and opens an AudioOutputStream on the audio manager
101  // thread, and if this is successful, the |event_handler| will receive an
102  // OnCreated() call from the same audio manager thread.  |audio_manager| must
103  // outlive AudioOutputController.
104  // The |output_device_id| can be either empty (default device) or specify a
105  // specific hardware device for audio output.  The |input_device_id| is
106  // used only for unified audio when opening up input and output at the same
107  // time (controlled by |params.input_channel_count()|).
108  static scoped_refptr<AudioOutputController> Create(
109      AudioManager* audio_manager, EventHandler* event_handler,
110      const AudioParameters& params, const std::string& output_device_id,
111      const std::string& input_device_id, SyncReader* sync_reader);
112
113  // Methods to control playback of the stream.
114
115  // Starts the playback of this audio output stream.
116  void Play();
117
118  // Pause this audio output stream.
119  void Pause();
120
121  // Closes the audio output stream. The state is changed and the resources
122  // are freed on the audio manager thread. closed_task is executed after that.
123  // Callbacks (EventHandler and SyncReader) must exist until closed_task is
124  // called.
125  //
126  // It is safe to call this method more than once. Calls after the first one
127  // will have no effect.
128  void Close(const base::Closure& closed_task);
129
130  // Sets the volume of the audio output stream.
131  void SetVolume(double volume);
132
133  // AudioSourceCallback implementation.
134  virtual int OnMoreData(AudioBus* dest,
135                         AudioBuffersState buffers_state) OVERRIDE;
136  virtual int OnMoreIOData(AudioBus* source,
137                           AudioBus* dest,
138                           AudioBuffersState buffers_state) OVERRIDE;
139  virtual void OnError(AudioOutputStream* stream) OVERRIDE;
140
141  // AudioDeviceListener implementation.  When called AudioOutputController will
142  // shutdown the existing |stream_|, transition to the kRecreating state,
143  // create a new stream, and then transition back to an equivalent state prior
144  // to being called.
145  virtual void OnDeviceChange() OVERRIDE;
146
147  // AudioSourceDiverter implementation.
148  virtual const AudioParameters& GetAudioParameters() OVERRIDE;
149  virtual void StartDiverting(AudioOutputStream* to_stream) OVERRIDE;
150  virtual void StopDiverting() OVERRIDE;
151
152 protected:
153  // Internal state of the source.
154  enum State {
155    kEmpty,
156    kCreated,
157    kPlaying,
158    kPaused,
159    kClosed,
160    kError,
161  };
162
163  friend class base::RefCountedThreadSafe<AudioOutputController>;
164  virtual ~AudioOutputController();
165
166 private:
167  // We are polling sync reader if data became available.
168  static const int kPollNumAttempts;
169  static const int kPollPauseInMilliseconds;
170
171  AudioOutputController(AudioManager* audio_manager, EventHandler* handler,
172                        const AudioParameters& params,
173                        const std::string& output_device_id,
174                        const std::string& input_device_id,
175                        SyncReader* sync_reader);
176
177  // The following methods are executed on the audio manager thread.
178  void DoCreate(bool is_for_device_change);
179  void DoPlay();
180  void DoPause();
181  void DoClose();
182  void DoSetVolume(double volume);
183  void DoReportError();
184  void DoStartDiverting(AudioOutputStream* to_stream);
185  void DoStopDiverting();
186
187  // Calls EventHandler::OnPowerMeasured() with the current power level and then
188  // schedules itself to be called again later.
189  void ReportPowerMeasurementPeriodically();
190
191  // Helper method that stops the physical stream.
192  void StopStream();
193
194  // Helper method that stops, closes, and NULLs |*stream_|.
195  void DoStopCloseAndClearStream();
196
197  // Sanity-check that entry/exit to OnMoreIOData() by the hardware audio thread
198  // happens only between AudioOutputStream::Start() and Stop().
199  void AllowEntryToOnMoreIOData();
200  void DisallowEntryToOnMoreIOData();
201
202  AudioManager* const audio_manager_;
203  const AudioParameters params_;
204  EventHandler* const handler_;
205
206  // Specifies the device id of the output device to open or empty for the
207  // default output device.
208  const std::string output_device_id_;
209
210  // Used by the unified IO to open the correct input device.
211  const std::string input_device_id_;
212
213  AudioOutputStream* stream_;
214
215  // When non-NULL, audio is being diverted to this stream.
216  AudioOutputStream* diverting_to_stream_;
217
218  // The current volume of the audio stream.
219  double volume_;
220
221  // |state_| is written on the audio manager thread and is read on the
222  // hardware audio thread. These operations need to be locked. But lock
223  // is not required for reading on the audio manager thread.
224  State state_;
225
226  // Binary semaphore, used to ensure that only one thread enters the
227  // OnMoreIOData() method, and only when it is valid to do so.  This is for
228  // sanity-checking the behavior of platform implementations of
229  // AudioOutputStream.  In other words, multiple contention is not expected,
230  // nor in the design here.
231  base::AtomicRefCount num_allowed_io_;
232
233  // SyncReader is used only in low latency mode for synchronous reading.
234  SyncReader* const sync_reader_;
235
236  // The message loop of audio manager thread that this object runs on.
237  const scoped_refptr<base::MessageLoopProxy> message_loop_;
238
239  // When starting stream we wait for data to become available.
240  // Number of times left.
241  int number_polling_attempts_left_;
242
243  // Scans audio samples from OnMoreIOData() as input to compute power levels.
244  AudioPowerMonitor power_monitor_;
245
246  // Periodic callback to report power levels during playback.
247  base::CancelableClosure power_poll_callback_;
248
249  DISALLOW_COPY_AND_ASSIGN(AudioOutputController);
250};
251
252}  // namespace media
253
254#endif  // MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_
255