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.
5 #ifndef MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_
6 #define MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_
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"
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.
29 // All the public methods of AudioOutputController are non-blocking.
30 // The actual operations are performed on the audio manager thread.
32 // Here is a state transition diagram for the AudioOutputController:
34 // *[ Empty ] --> [ Created ] --> [ Playing ] -------.
38 // | | | `----- [ Paused ]
41 // `-----------> [ Closed ] <-----------'
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
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.
60 class MEDIA_EXPORT AudioOutputController
61 : public base::RefCountedThreadSafe<AudioOutputController>,
62 public AudioOutputStream::AudioSourceCallback,
63 public AudioSourceDiverter,
64 NON_EXPORTED_BASE(public AudioManager::AudioDeviceListener) {
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 {
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;
77 virtual std::string app_id() const = 0;
78 virtual std::string app_class() const = 0;
82 virtual ~EventHandler() {}
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.
91 virtual ~SyncReader() {}
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;
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;
102 // Close this synchronous reader.
103 virtual void Close() = 0;
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);
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)
128 // Methods to control playback of the stream.
130 // Starts the playback of this audio output stream.
133 // Pause this audio output stream.
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
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);
145 // Sets the volume of the audio output stream.
146 void SetVolume(double volume);
148 // Calls |callback| (on the caller's thread) with the current output
150 void GetOutputDeviceId(
151 base::Callback<void(const std::string&)> callback) const;
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.
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);
165 // AudioSourceCallback implementation.
166 virtual int OnMoreData(AudioBus* dest,
167 AudioBuffersState buffers_state) OVERRIDE;
168 virtual void OnError(AudioOutputStream* stream) OVERRIDE;
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
174 virtual void OnDeviceChange() OVERRIDE;
176 // AudioSourceDiverter implementation.
177 virtual const AudioParameters& GetAudioParameters() OVERRIDE;
178 virtual void StartDiverting(AudioOutputStream* to_stream) OVERRIDE;
179 virtual void StopDiverting() OVERRIDE;
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();
186 // Internal state of the source.
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 };
200 friend class base::RefCountedThreadSafe<AudioOutputController>;
201 virtual ~AudioOutputController();
204 AudioOutputController(AudioManager* audio_manager, EventHandler* handler,
205 const AudioParameters& params,
206 const std::string& output_device_id,
207 SyncReader* sync_reader);
209 // The following methods are executed on the audio manager thread.
210 void DoCreate(bool is_for_device_change);
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();
221 // Helper method that stops the physical stream.
224 // Helper method that stops, closes, and NULLs |*stream_|.
225 void DoStopCloseAndClearStream();
227 // Checks if a stream was started successfully but never calls OnMoreData().
230 AudioManager* const audio_manager_;
231 const AudioParameters params_;
232 EventHandler* const handler_;
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_;
238 AudioOutputStream* stream_;
240 // When non-NULL, audio is being diverted to this stream.
241 AudioOutputStream* diverting_to_stream_;
243 // The current volume of the audio stream.
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.
251 // SyncReader is used only in low latency mode for synchronous reading.
252 SyncReader* const sync_reader_;
254 // The message loop of audio manager thread that this object runs on.
255 const scoped_refptr<base::SingleThreadTaskRunner> message_loop_;
257 // Scans audio samples from OnMoreData() as input to compute power levels.
258 AudioPowerMonitor power_monitor_;
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_;
264 DISALLOW_COPY_AND_ASSIGN(AudioOutputController);
269 #endif // MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_