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