audio_output_controller.h revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
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/memory/ref_counted.h"
11#include "base/memory/weak_ptr.h"
12#include "media/audio/audio_buffers_state.h"
13#include "media/audio/audio_io.h"
14#include "media/audio/audio_manager.h"
15#include "media/audio/audio_source_diverter.h"
16#include "media/audio/simple_sources.h"
17#include "media/base/media_export.h"
18
19class MessageLoop;
20
21// An AudioOutputController controls an AudioOutputStream and provides data
22// to this output stream. It has an important function that it executes
23// audio operations like play, pause, stop, etc. on a separate thread,
24// namely the audio manager thread.
25//
26// All the public methods of AudioOutputController are non-blocking.
27// The actual operations are performed on the audio manager thread.
28//
29// Here is a state transition diagram for the AudioOutputController:
30//
31//   *[ Empty ]  -->  [ Created ]  -->  [ Starting ]  -->  [ Playing ]  --.
32//        |                |               |    ^               |         |
33//        |                |               |    |               |         |
34//        |                |               |    |               v         |
35//        |                |               |    `---------  [ Paused ]    |
36//        |                |               |                    |         |
37//        |                v               v                    |         |
38//        `----------->  [      Closed       ]  <-------------------------'
39//
40// * Initial state
41//
42// At any time after reaching the Created state but before Closed, the
43// AudioOutputController may be notified of a device change via
44// OnDeviceChange().  As the OnDeviceChange() is processed, state transitions
45// will occur, ultimately ending up in an equivalent pre-call state.  E.g., if
46// the state was Paused, the new state will be Created, since these states are
47// all functionally equivalent and require a Play() call to continue to the next
48// state.
49//
50// The AudioOutputStream can request data from the AudioOutputController via the
51// AudioSourceCallback interface. AudioOutputController uses the SyncReader
52// passed to it via construction to synchronously fulfill this read request.
53//
54// Since AudioOutputController uses AudioManager's message loop the controller
55// uses WeakPtr to allow safe cancellation of pending tasks.
56//
57
58namespace media {
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(AudioOutputController* controller) = 0;
71    virtual void OnPlaying(AudioOutputController* controller) = 0;
72    virtual void OnPaused(AudioOutputController* controller) = 0;
73    virtual void OnError(AudioOutputController* controller) = 0;
74    virtual void OnDeviceChange(AudioOutputController* controller,
75                                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    // Attempt to completely fill |dest|, return the actual number of
95    // frames that could be read.
96    // |source| may optionally be provided for input data.
97    virtual int Read(AudioBus* source, AudioBus* dest) = 0;
98
99    // Close this synchronous reader.
100    virtual void Close() = 0;
101
102    // Check if data is ready.
103    virtual bool DataReady() = 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  static scoped_refptr<AudioOutputController> Create(
112      AudioManager* audio_manager, EventHandler* event_handler,
113      const AudioParameters& params, SyncReader* sync_reader);
114
115  // Methods to control playback of the stream.
116
117  // Starts the playback of this audio output stream.
118  void Play();
119
120  // Pause this audio output stream.
121  void Pause();
122
123  // Discard all audio data buffered in this output stream. This method only
124  // has effect when the stream is paused.
125  void Flush();
126
127  // Closes the audio output stream. The state is changed and the resources
128  // are freed on the audio manager thread. closed_task is executed after that.
129  // Callbacks (EventHandler and SyncReader) must exist until closed_task is
130  // called.
131  //
132  // It is safe to call this method more than once. Calls after the first one
133  // will have no effect.
134  void Close(const base::Closure& closed_task);
135
136  // Sets the volume of the audio output stream.
137  void SetVolume(double volume);
138
139  // AudioSourceCallback implementation.
140  virtual int OnMoreData(AudioBus* dest,
141                         AudioBuffersState buffers_state) OVERRIDE;
142  virtual int OnMoreIOData(AudioBus* source,
143                           AudioBus* dest,
144                           AudioBuffersState buffers_state) OVERRIDE;
145  virtual void OnError(AudioOutputStream* stream) OVERRIDE;
146  // Deprecated: Currently only used for starting audio playback and for audio
147  // mirroring.
148  virtual void WaitTillDataReady() OVERRIDE;
149
150  // AudioDeviceListener implementation.  When called AudioOutputController will
151  // shutdown the existing |stream_|, transition to the kRecreating state,
152  // create a new stream, and then transition back to an equivalent state prior
153  // to being called.
154  virtual void OnDeviceChange() OVERRIDE;
155
156  // AudioSourceDiverter implementation.
157  virtual const AudioParameters& GetAudioParameters() OVERRIDE;
158  virtual void StartDiverting(AudioOutputStream* to_stream) OVERRIDE;
159  virtual void StopDiverting() OVERRIDE;
160
161 protected:
162  // Internal state of the source.
163  enum State {
164    kEmpty,
165    kCreated,
166    kStarting,
167    kPlaying,
168    kPaused,
169    kClosed,
170    kError,
171  };
172
173  friend class base::RefCountedThreadSafe<AudioOutputController>;
174  virtual ~AudioOutputController();
175
176 private:
177  // We are polling sync reader if data became available.
178  static const int kPollNumAttempts;
179  static const int kPollPauseInMilliseconds;
180
181  AudioOutputController(AudioManager* audio_manager, EventHandler* handler,
182                        const AudioParameters& params, SyncReader* sync_reader);
183
184  // The following methods are executed on the audio manager thread.
185  void DoCreate(bool is_for_device_change);
186  void DoPlay();
187  void PollAndStartIfDataReady();
188  void DoPause();
189  void DoFlush();
190  void DoClose();
191  void DoSetVolume(double volume);
192  void DoReportError();
193  void DoStartDiverting(AudioOutputStream* to_stream);
194  void DoStopDiverting();
195
196  // Helper methods that start/stop physical stream.
197  void StartStream();
198  void StopStream();
199
200  // Helper method that stops, closes, and NULLs |*stream_|.
201  void DoStopCloseAndClearStream();
202
203  // Sanity-check that entry/exit to OnMoreIOData() by the hardware audio thread
204  // happens only between AudioOutputStream::Start() and Stop().
205  void AllowEntryToOnMoreIOData();
206  void DisallowEntryToOnMoreIOData();
207
208  AudioManager* const audio_manager_;
209  const AudioParameters params_;
210  EventHandler* const handler_;
211
212  // Note: It's important to invalidate the weak pointers whenever stream_ is
213  // changed.  See comment for weak_this_.
214  AudioOutputStream* stream_;
215
216  // When non-NULL, audio is being diverted to this stream.
217  AudioOutputStream* diverting_to_stream_;
218
219  // The current volume of the audio stream.
220  double volume_;
221
222  // |state_| is written on the audio manager thread and is read on the
223  // hardware audio thread. These operations need to be locked. But lock
224  // is not required for reading on the audio manager thread.
225  State state_;
226
227  // Binary semaphore, used to ensure that only one thread enters the
228  // OnMoreIOData() method, and only when it is valid to do so.  This is for
229  // sanity-checking the behavior of platform implementations of
230  // AudioOutputStream.  In other words, multiple contention is not expected,
231  // nor in the design here.
232  base::AtomicRefCount num_allowed_io_;
233
234  // SyncReader is used only in low latency mode for synchronous reading.
235  SyncReader* const sync_reader_;
236
237  // The message loop of audio manager thread that this object runs on.
238  const scoped_refptr<base::MessageLoopProxy> message_loop_;
239
240  // When starting stream we wait for data to become available.
241  // Number of times left.
242  int number_polling_attempts_left_;
243
244  // Used to auto-cancel the delayed tasks that are created to poll for data
245  // (when starting-up a stream).
246  base::WeakPtrFactory<AudioOutputController> weak_this_;
247
248  DISALLOW_COPY_AND_ASSIGN(AudioOutputController);
249};
250
251}  // namespace media
252
253#endif  // MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_
254