cc: Added inline to Tile::IsReadyToDraw
[chromium-blink-merge.git] / media / audio / win / audio_manager_win.cc
bloba753e554cb4c90713d893268163907e657b731d4
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_io.h"
7 #include <windows.h>
8 #include <objbase.h> // This has to be before initguid.h
9 #include <initguid.h>
10 #include <mmsystem.h>
11 #include <setupapi.h>
13 #include "base/bind.h"
14 #include "base/bind_helpers.h"
15 #include "base/command_line.h"
16 #include "base/files/file_path.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/path_service.h"
20 #include "base/process/launch.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_util.h"
23 #include "media/audio/audio_parameters.h"
24 #include "media/audio/audio_util.h"
25 #include "media/audio/win/audio_device_listener_win.h"
26 #include "media/audio/win/audio_low_latency_input_win.h"
27 #include "media/audio/win/audio_low_latency_output_win.h"
28 #include "media/audio/win/audio_manager_win.h"
29 #include "media/audio/win/audio_unified_win.h"
30 #include "media/audio/win/core_audio_util_win.h"
31 #include "media/audio/win/device_enumeration_win.h"
32 #include "media/audio/win/wavein_input_win.h"
33 #include "media/audio/win/waveout_output_win.h"
34 #include "media/base/bind_to_loop.h"
35 #include "media/base/channel_layout.h"
36 #include "media/base/limits.h"
37 #include "media/base/media_switches.h"
39 // Libraries required for the SetupAPI and Wbem APIs used here.
40 #pragma comment(lib, "setupapi.lib")
42 // The following are defined in various DDK headers, and we (re)define them here
43 // to avoid adding the DDK as a chrome dependency.
44 #define DRV_QUERYDEVICEINTERFACE 0x80c
45 #define DRVM_MAPPER_PREFERRED_GET 0x2015
46 #define DRV_QUERYDEVICEINTERFACESIZE 0x80d
47 DEFINE_GUID(AM_KSCATEGORY_AUDIO, 0x6994ad04, 0x93ef, 0x11d0,
48 0xa3, 0xcc, 0x00, 0xa0, 0xc9, 0x22, 0x31, 0x96);
50 namespace media {
52 // Maximum number of output streams that can be open simultaneously.
53 static const int kMaxOutputStreams = 50;
55 // Up to 8 channels can be passed to the driver. This should work, given the
56 // right drivers, but graceful error handling is needed.
57 static const int kWinMaxChannels = 8;
59 // We use 3 buffers for recording audio so that if a recording callback takes
60 // some time to return we won't lose audio. More buffers while recording are
61 // ok because they don't introduce any delay in recording, unlike in playback
62 // where you first need to fill in that number of buffers before starting to
63 // play.
64 static const int kNumInputBuffers = 3;
66 // Buffer size to use for input and output stream when a proper size can't be
67 // determined from the system
68 static const int kFallbackBufferSize = 2048;
70 static int GetVersionPartAsInt(DWORDLONG num) {
71 return static_cast<int>(num & 0xffff);
74 // Returns a string containing the given device's description and installed
75 // driver version.
76 static string16 GetDeviceAndDriverInfo(HDEVINFO device_info,
77 SP_DEVINFO_DATA* device_data) {
78 // Save the old install params setting and set a flag for the
79 // SetupDiBuildDriverInfoList below to return only the installed drivers.
80 SP_DEVINSTALL_PARAMS old_device_install_params;
81 old_device_install_params.cbSize = sizeof(old_device_install_params);
82 SetupDiGetDeviceInstallParams(device_info, device_data,
83 &old_device_install_params);
84 SP_DEVINSTALL_PARAMS device_install_params = old_device_install_params;
85 device_install_params.FlagsEx |= DI_FLAGSEX_INSTALLEDDRIVER;
86 SetupDiSetDeviceInstallParams(device_info, device_data,
87 &device_install_params);
89 SP_DRVINFO_DATA driver_data;
90 driver_data.cbSize = sizeof(driver_data);
91 string16 device_and_driver_info;
92 if (SetupDiBuildDriverInfoList(device_info, device_data,
93 SPDIT_COMPATDRIVER)) {
94 if (SetupDiEnumDriverInfo(device_info, device_data, SPDIT_COMPATDRIVER, 0,
95 &driver_data)) {
96 DWORDLONG version = driver_data.DriverVersion;
97 device_and_driver_info = string16(driver_data.Description) + L" v" +
98 base::IntToString16(GetVersionPartAsInt((version >> 48))) + L"." +
99 base::IntToString16(GetVersionPartAsInt((version >> 32))) + L"." +
100 base::IntToString16(GetVersionPartAsInt((version >> 16))) + L"." +
101 base::IntToString16(GetVersionPartAsInt(version));
103 SetupDiDestroyDriverInfoList(device_info, device_data, SPDIT_COMPATDRIVER);
106 SetupDiSetDeviceInstallParams(device_info, device_data,
107 &old_device_install_params);
109 return device_and_driver_info;
112 AudioManagerWin::AudioManagerWin() {
113 if (!CoreAudioUtil::IsSupported()) {
114 // Use the Wave API for device enumeration if XP or lower.
115 enumeration_type_ = kWaveEnumeration;
116 } else {
117 // Use the MMDevice API for device enumeration if Vista or higher.
118 enumeration_type_ = kMMDeviceEnumeration;
121 SetMaxOutputStreamsAllowed(kMaxOutputStreams);
123 // Task must be posted last to avoid races from handing out "this" to the
124 // audio thread.
125 GetMessageLoop()->PostTask(FROM_HERE, base::Bind(
126 &AudioManagerWin::CreateDeviceListener, base::Unretained(this)));
129 AudioManagerWin::~AudioManagerWin() {
130 // It's safe to post a task here since Shutdown() will wait for all tasks to
131 // complete before returning.
132 GetMessageLoop()->PostTask(FROM_HERE, base::Bind(
133 &AudioManagerWin::DestroyDeviceListener, base::Unretained(this)));
134 Shutdown();
137 bool AudioManagerWin::HasAudioOutputDevices() {
138 return (::waveOutGetNumDevs() != 0);
141 bool AudioManagerWin::HasAudioInputDevices() {
142 return (::waveInGetNumDevs() != 0);
145 void AudioManagerWin::CreateDeviceListener() {
146 // AudioDeviceListenerWin must be initialized on a COM thread and should only
147 // be used if WASAPI / Core Audio is supported.
148 if (CoreAudioUtil::IsSupported()) {
149 output_device_listener_.reset(new AudioDeviceListenerWin(BindToLoop(
150 GetMessageLoop(), base::Bind(
151 &AudioManagerWin::NotifyAllOutputDeviceChangeListeners,
152 base::Unretained(this)))));
156 void AudioManagerWin::DestroyDeviceListener() {
157 output_device_listener_.reset();
160 string16 AudioManagerWin::GetAudioInputDeviceModel() {
161 // Get the default audio capture device and its device interface name.
162 DWORD device_id = 0;
163 waveInMessage(reinterpret_cast<HWAVEIN>(WAVE_MAPPER),
164 DRVM_MAPPER_PREFERRED_GET,
165 reinterpret_cast<DWORD_PTR>(&device_id), NULL);
166 ULONG device_interface_name_size = 0;
167 waveInMessage(reinterpret_cast<HWAVEIN>(device_id),
168 DRV_QUERYDEVICEINTERFACESIZE,
169 reinterpret_cast<DWORD_PTR>(&device_interface_name_size), 0);
170 size_t bytes_in_char16 = sizeof(string16::value_type);
171 DCHECK_EQ(0u, device_interface_name_size % bytes_in_char16);
172 if (device_interface_name_size <= bytes_in_char16)
173 return string16(); // No audio capture device.
175 string16 device_interface_name;
176 string16::value_type* name_ptr = WriteInto(&device_interface_name,
177 device_interface_name_size / bytes_in_char16);
178 waveInMessage(reinterpret_cast<HWAVEIN>(device_id),
179 DRV_QUERYDEVICEINTERFACE,
180 reinterpret_cast<DWORD_PTR>(name_ptr),
181 static_cast<DWORD_PTR>(device_interface_name_size));
183 // Enumerate all audio devices and find the one matching the above device
184 // interface name.
185 HDEVINFO device_info = SetupDiGetClassDevs(
186 &AM_KSCATEGORY_AUDIO, 0, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
187 if (device_info == INVALID_HANDLE_VALUE)
188 return string16();
190 DWORD interface_index = 0;
191 SP_DEVICE_INTERFACE_DATA interface_data;
192 interface_data.cbSize = sizeof(interface_data);
193 while (SetupDiEnumDeviceInterfaces(device_info, 0, &AM_KSCATEGORY_AUDIO,
194 interface_index++, &interface_data)) {
195 // Query the size of the struct, allocate it and then query the data.
196 SP_DEVINFO_DATA device_data;
197 device_data.cbSize = sizeof(device_data);
198 DWORD interface_detail_size = 0;
199 SetupDiGetDeviceInterfaceDetail(device_info, &interface_data, 0, 0,
200 &interface_detail_size, &device_data);
201 if (!interface_detail_size)
202 continue;
204 scoped_ptr<char[]> interface_detail_buffer(new char[interface_detail_size]);
205 SP_DEVICE_INTERFACE_DETAIL_DATA* interface_detail =
206 reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA*>(
207 interface_detail_buffer.get());
208 interface_detail->cbSize = interface_detail_size;
209 if (!SetupDiGetDeviceInterfaceDetail(device_info, &interface_data,
210 interface_detail,
211 interface_detail_size, NULL,
212 &device_data))
213 return string16();
215 bool device_found = (device_interface_name == interface_detail->DevicePath);
217 if (device_found)
218 return GetDeviceAndDriverInfo(device_info, &device_data);
221 return string16();
224 void AudioManagerWin::ShowAudioInputSettings() {
225 std::wstring program;
226 std::string argument;
227 if (!CoreAudioUtil::IsSupported()) {
228 program = L"sndvol32.exe";
229 argument = "-R";
230 } else {
231 program = L"control.exe";
232 argument = "mmsys.cpl,,1";
235 base::FilePath path;
236 PathService::Get(base::DIR_SYSTEM, &path);
237 path = path.Append(program);
238 CommandLine command_line(path);
239 command_line.AppendArg(argument);
240 base::LaunchProcess(command_line, base::LaunchOptions(), NULL);
243 void AudioManagerWin::GetAudioInputDeviceNames(
244 media::AudioDeviceNames* device_names) {
245 DCHECK(enumeration_type() != kUninitializedEnumeration);
246 // Enumerate all active audio-endpoint capture devices.
247 if (enumeration_type() == kWaveEnumeration) {
248 // Utilize the Wave API for Windows XP.
249 media::GetInputDeviceNamesWinXP(device_names);
250 } else {
251 // Utilize the MMDevice API (part of Core Audio) for Vista and higher.
252 media::GetInputDeviceNamesWin(device_names);
255 // Always add default device parameters as first element.
256 if (!device_names->empty()) {
257 media::AudioDeviceName name;
258 name.device_name = AudioManagerBase::kDefaultDeviceName;
259 name.unique_id = AudioManagerBase::kDefaultDeviceId;
260 device_names->push_front(name);
264 AudioParameters AudioManagerWin::GetInputStreamParameters(
265 const std::string& device_id) {
266 int sample_rate = 48000;
267 ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
268 if (CoreAudioUtil::IsSupported()) {
269 int hw_sample_rate = WASAPIAudioInputStream::HardwareSampleRate(device_id);
270 if (hw_sample_rate)
271 sample_rate = hw_sample_rate;
272 channel_layout =
273 WASAPIAudioInputStream::HardwareChannelCount(device_id) == 1 ?
274 CHANNEL_LAYOUT_MONO : CHANNEL_LAYOUT_STEREO;
277 // TODO(Henrika): improve the default buffer size value for input stream.
278 return AudioParameters(
279 AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout,
280 sample_rate, 16, kFallbackBufferSize);
283 // Factory for the implementations of AudioOutputStream for AUDIO_PCM_LINEAR
284 // mode.
285 // - PCMWaveOutAudioOutputStream: Based on the waveOut API.
286 AudioOutputStream* AudioManagerWin::MakeLinearOutputStream(
287 const AudioParameters& params) {
288 DCHECK_EQ(AudioParameters::AUDIO_PCM_LINEAR, params.format());
289 if (params.channels() > kWinMaxChannels)
290 return NULL;
292 return new PCMWaveOutAudioOutputStream(this,
293 params,
294 media::NumberOfWaveOutBuffers(),
295 WAVE_MAPPER);
298 // Factory for the implementations of AudioOutputStream for
299 // AUDIO_PCM_LOW_LATENCY mode. Two implementations should suffice most
300 // windows user's needs.
301 // - PCMWaveOutAudioOutputStream: Based on the waveOut API.
302 // - WASAPIAudioOutputStream: Based on Core Audio (WASAPI) API.
303 AudioOutputStream* AudioManagerWin::MakeLowLatencyOutputStream(
304 const AudioParameters& params, const std::string& input_device_id) {
305 DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format());
306 if (params.channels() > kWinMaxChannels)
307 return NULL;
309 if (!CoreAudioUtil::IsSupported()) {
310 // Fall back to Windows Wave implementation on Windows XP or lower.
311 DVLOG(1) << "Using WaveOut since WASAPI requires at least Vista.";
312 return new PCMWaveOutAudioOutputStream(
313 this, params, media::NumberOfWaveOutBuffers(), WAVE_MAPPER);
316 // TODO(crogers): support more than stereo input.
317 if (params.input_channels() > 0) {
318 DVLOG(1) << "WASAPIUnifiedStream is created.";
319 return new WASAPIUnifiedStream(this, params, input_device_id);
322 return new WASAPIAudioOutputStream(this, params, eConsole);
325 // Factory for the implementations of AudioInputStream for AUDIO_PCM_LINEAR
326 // mode.
327 AudioInputStream* AudioManagerWin::MakeLinearInputStream(
328 const AudioParameters& params, const std::string& device_id) {
329 DCHECK_EQ(AudioParameters::AUDIO_PCM_LINEAR, params.format());
330 return CreatePCMWaveInAudioInputStream(params, device_id);
333 // Factory for the implementations of AudioInputStream for
334 // AUDIO_PCM_LOW_LATENCY mode.
335 AudioInputStream* AudioManagerWin::MakeLowLatencyInputStream(
336 const AudioParameters& params, const std::string& device_id) {
337 DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format());
338 AudioInputStream* stream = NULL;
339 if (!CoreAudioUtil::IsSupported()) {
340 // Fall back to Windows Wave implementation on Windows XP or lower.
341 DVLOG(1) << "Using WaveIn since WASAPI requires at least Vista.";
342 stream = CreatePCMWaveInAudioInputStream(params, device_id);
343 } else {
344 stream = new WASAPIAudioInputStream(this, params, device_id);
347 return stream;
350 AudioParameters AudioManagerWin::GetPreferredOutputStreamParameters(
351 const AudioParameters& input_params) {
352 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
353 ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
354 int sample_rate = 48000;
355 int buffer_size = kFallbackBufferSize;
356 int bits_per_sample = 16;
357 int input_channels = 0;
358 bool use_input_params = !CoreAudioUtil::IsSupported();
359 if (cmd_line->HasSwitch(switches::kEnableExclusiveAudio)) {
360 // TODO(crogers): tune these values for best possible WebAudio performance.
361 // WebRTC works well at 48kHz and a buffer size of 480 samples will be used
362 // for this case. Note that exclusive mode is experimental.
363 // This sample rate will be combined with a buffer size of 256 samples,
364 // which corresponds to an output delay of ~5.33ms.
365 sample_rate = 48000;
366 buffer_size = 256;
367 if (input_params.IsValid())
368 channel_layout = input_params.channel_layout();
369 } else if (!use_input_params) {
370 // Hardware sample-rate on Windows can be configured, so we must query.
371 // TODO(henrika): improve possibility to specify an audio endpoint.
372 // Use the default device (same as for Wave) for now to be compatible.
373 int hw_sample_rate = WASAPIAudioOutputStream::HardwareSampleRate();
375 AudioParameters params;
376 HRESULT hr = CoreAudioUtil::GetPreferredAudioParameters(eRender, eConsole,
377 &params);
378 int hw_buffer_size =
379 FAILED(hr) ? kFallbackBufferSize : params.frames_per_buffer();
380 channel_layout = WASAPIAudioOutputStream::HardwareChannelLayout();
382 // TODO(henrika): Figure out the right thing to do here.
383 if (hw_sample_rate && hw_buffer_size) {
384 sample_rate = hw_sample_rate;
385 buffer_size = hw_buffer_size;
386 } else {
387 use_input_params = true;
391 if (input_params.IsValid()) {
392 if (cmd_line->HasSwitch(switches::kTrySupportedChannelLayouts) &&
393 CoreAudioUtil::IsSupported()) {
394 // Check if it is possible to open up at the specified input channel
395 // layout but avoid checking if the specified layout is the same as the
396 // hardware (preferred) layout. We do this extra check to avoid the
397 // CoreAudioUtil::IsChannelLayoutSupported() overhead in most cases.
398 if (input_params.channel_layout() != channel_layout) {
399 if (CoreAudioUtil::IsChannelLayoutSupported(
400 eRender, eConsole, input_params.channel_layout())) {
401 // Open up using the same channel layout as the source if it is
402 // supported by the hardware.
403 channel_layout = input_params.channel_layout();
404 VLOG(1) << "Hardware channel layout is not used; using same layout"
405 << " as the source instead (" << channel_layout << ")";
409 input_channels = input_params.input_channels();
410 if (use_input_params) {
411 // If WASAPI isn't supported we'll fallback to WaveOut, which will take
412 // care of resampling and bits per sample changes. By setting these
413 // equal to the input values, AudioOutputResampler will skip resampling
414 // and bit per sample differences (since the input parameters will match
415 // the output parameters).
416 sample_rate = input_params.sample_rate();
417 bits_per_sample = input_params.bits_per_sample();
418 channel_layout = input_params.channel_layout();
419 buffer_size = input_params.frames_per_buffer();
423 int user_buffer_size = GetUserBufferSize();
424 if (user_buffer_size)
425 buffer_size = user_buffer_size;
427 return AudioParameters(
428 AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, input_channels,
429 sample_rate, bits_per_sample, buffer_size);
432 AudioInputStream* AudioManagerWin::CreatePCMWaveInAudioInputStream(
433 const AudioParameters& params,
434 const std::string& device_id) {
435 std::string xp_device_id = device_id;
436 if (device_id != AudioManagerBase::kDefaultDeviceId &&
437 enumeration_type_ == kMMDeviceEnumeration) {
438 xp_device_id = media::ConvertToWinXPDeviceId(device_id);
439 if (xp_device_id.empty()) {
440 DLOG(ERROR) << "Cannot find a waveIn device which matches the device ID "
441 << device_id;
442 return NULL;
446 return new PCMWaveInAudioInputStream(this, params, kNumInputBuffers,
447 xp_device_id);
450 /// static
451 AudioManager* CreateAudioManager() {
452 return new AudioManagerWin();
455 } // namespace media