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_
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"
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.
24 // All the public methods of AudioOutputController are non-blocking.
25 // The actual operations are performed on the audio manager thread.
27 // Here is a state transition diagram for the AudioOutputController:
29 // *[ Empty ] --> [ Created ] --> [ Playing ] -------.
33 // | | | `----- [ Paused ]
36 // `-----------> [ Closed ] <-----------'
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
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.
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
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 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;
78 virtual ~EventHandler() {}
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.
87 virtual ~SyncReader() {}
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;
94 // Attempt to completely fill |dest|, return the actual number of frames
95 // that could be read. |source| may optionally be provided for input data.
96 // If |block| is specified, the Read() will block until data is available
97 // or a timeout is reached.
98 virtual int Read(bool block
, const AudioBus
* source
, AudioBus
* dest
) = 0;
100 // Close this synchronous reader.
101 virtual void Close() = 0;
104 // Factory method for creating an AudioOutputController.
105 // This also creates and opens an AudioOutputStream on the audio manager
106 // thread, and if this is successful, the |event_handler| will receive an
107 // OnCreated() call from the same audio manager thread. |audio_manager| must
108 // outlive AudioOutputController.
109 // The |output_device_id| can be either empty (default device) or specify a
110 // specific hardware device for audio output. The |input_device_id| is
111 // used only for unified audio when opening up input and output at the same
112 // time (controlled by |params.input_channel_count()|).
113 static scoped_refptr
<AudioOutputController
> Create(
114 AudioManager
* audio_manager
, EventHandler
* event_handler
,
115 const AudioParameters
& params
, const std::string
& output_device_id
,
116 const std::string
& input_device_id
, SyncReader
* sync_reader
);
118 // Methods to control playback of the stream.
120 // Starts the playback of this audio output stream.
123 // Pause this audio output stream.
126 // Closes the audio output stream. The state is changed and the resources
127 // are freed on the audio manager thread. closed_task is executed after that.
128 // Callbacks (EventHandler and SyncReader) must exist until closed_task is
131 // It is safe to call this method more than once. Calls after the first one
132 // will have no effect.
133 void Close(const base::Closure
& closed_task
);
135 // Sets the volume of the audio output stream.
136 void SetVolume(double volume
);
138 // AudioSourceCallback implementation.
139 virtual int OnMoreData(AudioBus
* dest
,
140 AudioBuffersState buffers_state
) OVERRIDE
;
141 virtual int OnMoreIOData(AudioBus
* source
,
143 AudioBuffersState buffers_state
) OVERRIDE
;
144 virtual void OnError(AudioOutputStream
* stream
) OVERRIDE
;
146 // AudioDeviceListener implementation. When called AudioOutputController will
147 // shutdown the existing |stream_|, transition to the kRecreating state,
148 // create a new stream, and then transition back to an equivalent state prior
150 virtual void OnDeviceChange() OVERRIDE
;
152 // AudioSourceDiverter implementation.
153 virtual const AudioParameters
& GetAudioParameters() OVERRIDE
;
154 virtual void StartDiverting(AudioOutputStream
* to_stream
) OVERRIDE
;
155 virtual void StopDiverting() OVERRIDE
;
158 // Internal state of the source.
168 friend class base::RefCountedThreadSafe
<AudioOutputController
>;
169 virtual ~AudioOutputController();
172 // We are polling sync reader if data became available.
173 static const int kPollNumAttempts
;
174 static const int kPollPauseInMilliseconds
;
176 AudioOutputController(AudioManager
* audio_manager
, EventHandler
* handler
,
177 const AudioParameters
& params
,
178 const std::string
& output_device_id
,
179 const std::string
& input_device_id
,
180 SyncReader
* sync_reader
);
182 // The following methods are executed on the audio manager thread.
183 void DoCreate(bool is_for_device_change
);
187 void DoSetVolume(double volume
);
188 void DoReportError();
189 void DoStartDiverting(AudioOutputStream
* to_stream
);
190 void DoStopDiverting();
192 // Calls EventHandler::OnPowerMeasured() with the current power level and then
193 // schedules itself to be called again later.
194 void ReportPowerMeasurementPeriodically();
196 // Helper method that stops the physical stream.
199 // Helper method that stops, closes, and NULLs |*stream_|.
200 void DoStopCloseAndClearStream();
202 // Sanity-check that entry/exit to OnMoreIOData() by the hardware audio thread
203 // happens only between AudioOutputStream::Start() and Stop().
204 void AllowEntryToOnMoreIOData();
205 void DisallowEntryToOnMoreIOData();
207 AudioManager
* const audio_manager_
;
208 const AudioParameters params_
;
209 EventHandler
* const handler_
;
211 // Specifies the device id of the output device to open or empty for the
212 // default output device.
213 const std::string output_device_id_
;
215 // Used by the unified IO to open the correct input device.
216 const std::string input_device_id_
;
218 AudioOutputStream
* stream_
;
220 // When non-NULL, audio is being diverted to this stream.
221 AudioOutputStream
* diverting_to_stream_
;
223 // The current volume of the audio stream.
226 // |state_| is written on the audio manager thread and is read on the
227 // hardware audio thread. These operations need to be locked. But lock
228 // is not required for reading on the audio manager thread.
231 // Binary semaphore, used to ensure that only one thread enters the
232 // OnMoreIOData() method, and only when it is valid to do so. This is for
233 // sanity-checking the behavior of platform implementations of
234 // AudioOutputStream. In other words, multiple contention is not expected,
235 // nor in the design here.
236 base::AtomicRefCount num_allowed_io_
;
238 // SyncReader is used only in low latency mode for synchronous reading.
239 SyncReader
* const sync_reader_
;
241 // The message loop of audio manager thread that this object runs on.
242 const scoped_refptr
<base::MessageLoopProxy
> message_loop_
;
244 #if defined(AUDIO_POWER_MONITORING)
245 // Scans audio samples from OnMoreIOData() as input to compute power levels.
246 AudioPowerMonitor power_monitor_
;
248 // Periodic callback to report power levels during playback.
249 base::CancelableClosure power_poll_callback_
;
252 // When starting stream we wait for data to become available.
253 // Number of times left.
254 int number_polling_attempts_left_
;
256 DISALLOW_COPY_AND_ASSIGN(AudioOutputController
);
261 #endif // MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_