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