Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / media / audio / audio_manager_base.cc
blobdbe1b68a64e3567b4b63dbd52bb3dbc4bf9e930f
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 #include "media/audio/audio_manager_base.h"
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/command_line.h"
10 #include "base/single_thread_task_runner.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/thread_task_runner_handle.h"
13 #include "build/build_config.h"
14 #include "media/audio/audio_output_dispatcher_impl.h"
15 #include "media/audio/audio_output_proxy.h"
16 #include "media/audio/audio_output_resampler.h"
17 #include "media/audio/fake_audio_input_stream.h"
18 #include "media/audio/fake_audio_output_stream.h"
19 #include "media/base/media_switches.h"
21 namespace media {
23 static const int kStreamCloseDelaySeconds = 5;
25 // Default maximum number of output streams that can be open simultaneously
26 // for all platforms.
27 static const int kDefaultMaxOutputStreams = 16;
29 // Default maximum number of input streams that can be open simultaneously
30 // for all platforms.
31 static const int kDefaultMaxInputStreams = 16;
33 static const int kMaxInputChannels = 3;
35 const char AudioManagerBase::kDefaultDeviceName[] = "Default";
36 const char AudioManagerBase::kDefaultDeviceId[] = "default";
37 const char AudioManagerBase::kLoopbackInputDeviceId[] = "loopback";
39 struct AudioManagerBase::DispatcherParams {
40 DispatcherParams(const AudioParameters& input,
41 const AudioParameters& output,
42 const std::string& output_device_id)
43 : input_params(input),
44 output_params(output),
45 output_device_id(output_device_id) {}
46 ~DispatcherParams() {}
48 const AudioParameters input_params;
49 const AudioParameters output_params;
50 const std::string output_device_id;
51 scoped_refptr<AudioOutputDispatcher> dispatcher;
53 private:
54 DISALLOW_COPY_AND_ASSIGN(DispatcherParams);
57 class AudioManagerBase::CompareByParams {
58 public:
59 explicit CompareByParams(const DispatcherParams* dispatcher)
60 : dispatcher_(dispatcher) {}
61 bool operator()(DispatcherParams* dispatcher_in) const {
62 // We will reuse the existing dispatcher when:
63 // 1) Unified IO is not used, input_params and output_params of the
64 // existing dispatcher are the same as the requested dispatcher.
65 // 2) Unified IO is used, input_params and output_params of the existing
66 // dispatcher are the same as the request dispatcher.
67 return (dispatcher_->input_params.Equals(dispatcher_in->input_params) &&
68 dispatcher_->output_params.Equals(dispatcher_in->output_params) &&
69 dispatcher_->output_device_id == dispatcher_in->output_device_id);
72 private:
73 const DispatcherParams* dispatcher_;
76 AudioManagerBase::AudioManagerBase(AudioLogFactory* audio_log_factory)
77 : max_num_output_streams_(kDefaultMaxOutputStreams),
78 max_num_input_streams_(kDefaultMaxInputStreams),
79 num_output_streams_(0),
80 num_input_streams_(0),
81 // TODO(dalecurtis): Switch this to an ObserverListThreadSafe, so we don't
82 // block the UI thread when swapping devices.
83 output_listeners_(
84 ObserverList<AudioDeviceListener>::NOTIFY_EXISTING_ONLY),
85 audio_thread_("AudioThread"),
86 audio_log_factory_(audio_log_factory) {
87 #if defined(OS_WIN)
88 audio_thread_.init_com_with_mta(true);
89 #elif defined(OS_MACOSX)
90 // CoreAudio calls must occur on the main thread of the process, which in our
91 // case is sadly the browser UI thread. Failure to execute calls on the right
92 // thread leads to crashes and odd behavior. See http://crbug.com/158170.
93 // TODO(dalecurtis): We should require the message loop to be passed in.
94 if (base::MessageLoopForUI::IsCurrent()) {
95 task_runner_ = base::ThreadTaskRunnerHandle::Get();
96 return;
98 #endif
100 CHECK(audio_thread_.Start());
101 task_runner_ = audio_thread_.message_loop_proxy();
104 AudioManagerBase::~AudioManagerBase() {
105 // The platform specific AudioManager implementation must have already
106 // stopped the audio thread. Otherwise, we may destroy audio streams before
107 // stopping the thread, resulting an unexpected behavior.
108 // This way we make sure activities of the audio streams are all stopped
109 // before we destroy them.
110 CHECK(!audio_thread_.IsRunning());
111 // All the output streams should have been deleted.
112 DCHECK_EQ(0, num_output_streams_);
113 // All the input streams should have been deleted.
114 DCHECK_EQ(0, num_input_streams_);
117 base::string16 AudioManagerBase::GetAudioInputDeviceModel() {
118 return base::string16();
121 scoped_refptr<base::SingleThreadTaskRunner> AudioManagerBase::GetTaskRunner() {
122 return task_runner_;
125 scoped_refptr<base::SingleThreadTaskRunner>
126 AudioManagerBase::GetWorkerTaskRunner() {
127 // Lazily start the worker thread.
128 if (!audio_thread_.IsRunning())
129 CHECK(audio_thread_.Start());
131 return audio_thread_.message_loop_proxy();
134 AudioOutputStream* AudioManagerBase::MakeAudioOutputStream(
135 const AudioParameters& params,
136 const std::string& device_id) {
137 // TODO(miu): Fix ~50 call points across several unit test modules to call
138 // this method on the audio thread, then uncomment the following:
139 // DCHECK(task_runner_->BelongsToCurrentThread());
141 if (!params.IsValid()) {
142 DLOG(ERROR) << "Audio parameters are invalid";
143 return NULL;
146 // Limit the number of audio streams opened. This is to prevent using
147 // excessive resources for a large number of audio streams. More
148 // importantly it prevents instability on certain systems.
149 // See bug: http://crbug.com/30242.
150 if (num_output_streams_ >= max_num_output_streams_) {
151 DLOG(ERROR) << "Number of opened output audio streams "
152 << num_output_streams_
153 << " exceed the max allowed number "
154 << max_num_output_streams_;
155 return NULL;
158 AudioOutputStream* stream;
159 switch (params.format()) {
160 case AudioParameters::AUDIO_PCM_LINEAR:
161 DCHECK(device_id.empty())
162 << "AUDIO_PCM_LINEAR supports only the default device.";
163 stream = MakeLinearOutputStream(params);
164 break;
165 case AudioParameters::AUDIO_PCM_LOW_LATENCY:
166 stream = MakeLowLatencyOutputStream(params, device_id);
167 break;
168 case AudioParameters::AUDIO_FAKE:
169 stream = FakeAudioOutputStream::MakeFakeStream(this, params);
170 break;
171 default:
172 stream = NULL;
173 break;
176 if (stream) {
177 ++num_output_streams_;
180 return stream;
183 AudioInputStream* AudioManagerBase::MakeAudioInputStream(
184 const AudioParameters& params,
185 const std::string& device_id) {
186 // TODO(miu): Fix ~20 call points across several unit test modules to call
187 // this method on the audio thread, then uncomment the following:
188 // DCHECK(task_runner_->BelongsToCurrentThread());
190 if (!params.IsValid() || (params.channels() > kMaxInputChannels) ||
191 device_id.empty()) {
192 DLOG(ERROR) << "Audio parameters are invalid for device " << device_id;
193 return NULL;
196 if (num_input_streams_ >= max_num_input_streams_) {
197 DLOG(ERROR) << "Number of opened input audio streams "
198 << num_input_streams_
199 << " exceed the max allowed number " << max_num_input_streams_;
200 return NULL;
203 AudioInputStream* stream;
204 switch (params.format()) {
205 case AudioParameters::AUDIO_PCM_LINEAR:
206 stream = MakeLinearInputStream(params, device_id);
207 break;
208 case AudioParameters::AUDIO_PCM_LOW_LATENCY:
209 stream = MakeLowLatencyInputStream(params, device_id);
210 break;
211 case AudioParameters::AUDIO_FAKE:
212 stream = FakeAudioInputStream::MakeFakeStream(this, params);
213 break;
214 default:
215 stream = NULL;
216 break;
219 if (stream) {
220 ++num_input_streams_;
223 return stream;
226 AudioOutputStream* AudioManagerBase::MakeAudioOutputStreamProxy(
227 const AudioParameters& params,
228 const std::string& device_id) {
229 DCHECK(task_runner_->BelongsToCurrentThread());
231 // If the caller supplied an empty device id to select the default device,
232 // we fetch the actual device id of the default device so that the lookup
233 // will find the correct device regardless of whether it was opened as
234 // "default" or via the specific id.
235 // NOTE: Implementations that don't yet support opening non-default output
236 // devices may return an empty string from GetDefaultOutputDeviceID().
237 std::string output_device_id = device_id.empty() ?
238 GetDefaultOutputDeviceID() : device_id;
240 // If we're not using AudioOutputResampler our output parameters are the same
241 // as our input parameters.
242 AudioParameters output_params = params;
243 if (params.format() == AudioParameters::AUDIO_PCM_LOW_LATENCY) {
244 output_params =
245 GetPreferredOutputStreamParameters(output_device_id, params);
247 // Ensure we only pass on valid output parameters.
248 if (!output_params.IsValid()) {
249 // We've received invalid audio output parameters, so switch to a mock
250 // output device based on the input parameters. This may happen if the OS
251 // provided us junk values for the hardware configuration.
252 LOG(ERROR) << "Invalid audio output parameters received; using fake "
253 << "audio path. Channels: " << output_params.channels() << ", "
254 << "Sample Rate: " << output_params.sample_rate() << ", "
255 << "Bits Per Sample: " << output_params.bits_per_sample()
256 << ", Frames Per Buffer: "
257 << output_params.frames_per_buffer();
259 // Tell the AudioManager to create a fake output device.
260 output_params = AudioParameters(
261 AudioParameters::AUDIO_FAKE, params.channel_layout(),
262 params.sample_rate(), params.bits_per_sample(),
263 params.frames_per_buffer());
267 DispatcherParams* dispatcher_params =
268 new DispatcherParams(params, output_params, output_device_id);
270 AudioOutputDispatchers::iterator it =
271 std::find_if(output_dispatchers_.begin(), output_dispatchers_.end(),
272 CompareByParams(dispatcher_params));
273 if (it != output_dispatchers_.end()) {
274 delete dispatcher_params;
275 return new AudioOutputProxy((*it)->dispatcher.get());
278 const base::TimeDelta kCloseDelay =
279 base::TimeDelta::FromSeconds(kStreamCloseDelaySeconds);
280 scoped_refptr<AudioOutputDispatcher> dispatcher;
281 if (output_params.format() != AudioParameters::AUDIO_FAKE) {
282 dispatcher = new AudioOutputResampler(this, params, output_params,
283 output_device_id,
284 kCloseDelay);
285 } else {
286 dispatcher = new AudioOutputDispatcherImpl(this, output_params,
287 output_device_id,
288 kCloseDelay);
291 dispatcher_params->dispatcher = dispatcher;
292 output_dispatchers_.push_back(dispatcher_params);
293 return new AudioOutputProxy(dispatcher.get());
296 void AudioManagerBase::ShowAudioInputSettings() {
299 void AudioManagerBase::GetAudioInputDeviceNames(
300 AudioDeviceNames* device_names) {
303 void AudioManagerBase::GetAudioOutputDeviceNames(
304 AudioDeviceNames* device_names) {
307 void AudioManagerBase::ReleaseOutputStream(AudioOutputStream* stream) {
308 DCHECK(stream);
309 // TODO(xians) : Have a clearer destruction path for the AudioOutputStream.
310 // For example, pass the ownership to AudioManager so it can delete the
311 // streams.
312 --num_output_streams_;
313 delete stream;
316 void AudioManagerBase::ReleaseInputStream(AudioInputStream* stream) {
317 DCHECK(stream);
318 // TODO(xians) : Have a clearer destruction path for the AudioInputStream.
319 --num_input_streams_;
320 delete stream;
323 void AudioManagerBase::Shutdown() {
324 // Only true when we're sharing the UI message loop with the browser. The UI
325 // loop is no longer running at this time and browser destruction is imminent.
326 if (task_runner_->BelongsToCurrentThread()) {
327 ShutdownOnAudioThread();
328 } else {
329 task_runner_->PostTask(FROM_HERE, base::Bind(
330 &AudioManagerBase::ShutdownOnAudioThread, base::Unretained(this)));
333 // Stop() will wait for any posted messages to be processed first.
334 audio_thread_.Stop();
337 void AudioManagerBase::ShutdownOnAudioThread() {
338 DCHECK(task_runner_->BelongsToCurrentThread());
339 while (!output_dispatchers_.empty()) {
340 output_dispatchers_.back()->dispatcher->Shutdown();
341 output_dispatchers_.pop_back();
345 void AudioManagerBase::AddOutputDeviceChangeListener(
346 AudioDeviceListener* listener) {
347 DCHECK(task_runner_->BelongsToCurrentThread());
348 output_listeners_.AddObserver(listener);
351 void AudioManagerBase::RemoveOutputDeviceChangeListener(
352 AudioDeviceListener* listener) {
353 DCHECK(task_runner_->BelongsToCurrentThread());
354 output_listeners_.RemoveObserver(listener);
357 void AudioManagerBase::NotifyAllOutputDeviceChangeListeners() {
358 DCHECK(task_runner_->BelongsToCurrentThread());
359 DVLOG(1) << "Firing OnDeviceChange() notifications.";
360 FOR_EACH_OBSERVER(AudioDeviceListener, output_listeners_, OnDeviceChange());
363 AudioParameters AudioManagerBase::GetDefaultOutputStreamParameters() {
364 return GetPreferredOutputStreamParameters(GetDefaultOutputDeviceID(),
365 AudioParameters());
368 AudioParameters AudioManagerBase::GetOutputStreamParameters(
369 const std::string& device_id) {
370 return GetPreferredOutputStreamParameters(device_id,
371 AudioParameters());
374 AudioParameters AudioManagerBase::GetInputStreamParameters(
375 const std::string& device_id) {
376 NOTREACHED();
377 return AudioParameters();
380 std::string AudioManagerBase::GetAssociatedOutputDeviceID(
381 const std::string& input_device_id) {
382 return "";
385 std::string AudioManagerBase::GetDefaultOutputDeviceID() {
386 return "";
389 int AudioManagerBase::GetUserBufferSize() {
390 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
391 int buffer_size = 0;
392 std::string buffer_size_str(cmd_line->GetSwitchValueASCII(
393 switches::kAudioBufferSize));
394 if (base::StringToInt(buffer_size_str, &buffer_size) && buffer_size > 0)
395 return buffer_size;
397 return 0;
400 scoped_ptr<AudioLog> AudioManagerBase::CreateAudioLog(
401 AudioLogFactory::AudioComponent component) {
402 return audio_log_factory_->CreateAudioLog(component);
405 void AudioManagerBase::SetHasKeyboardMic() {
406 NOTREACHED();
409 } // namespace media