audio_manager_win.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
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#include "media/audio/audio_io.h" 6 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> 12 13#include "base/bind.h" 14#include "base/bind_helpers.h" 15#include "base/command_line.h" 16#include "base/file_path.h" 17#include "base/memory/scoped_ptr.h" 18#include "base/message_loop.h" 19#include "base/path_service.h" 20#include "base/process_util.h" 21#include "base/string_number_conversions.h" 22#include "base/string_util.h" 23#include "media/audio/audio_util.h" 24#include "media/audio/win/audio_device_listener_win.h" 25#include "media/audio/win/audio_low_latency_input_win.h" 26#include "media/audio/win/audio_low_latency_output_win.h" 27#include "media/audio/win/audio_manager_win.h" 28#include "media/audio/win/audio_unified_win.h" 29#include "media/audio/win/device_enumeration_win.h" 30#include "media/audio/win/wavein_input_win.h" 31#include "media/audio/win/waveout_output_win.h" 32#include "media/base/bind_to_loop.h" 33#include "media/base/limits.h" 34#include "media/base/media_switches.h" 35 36// Libraries required for the SetupAPI and Wbem APIs used here. 37#pragma comment(lib, "setupapi.lib") 38 39// The following are defined in various DDK headers, and we (re)define them 40// here to avoid adding the DDK as a chrome dependency. 41#define DRV_QUERYDEVICEINTERFACE 0x80c 42#define DRVM_MAPPER_PREFERRED_GET 0x2015 43#define DRV_QUERYDEVICEINTERFACESIZE 0x80d 44DEFINE_GUID(AM_KSCATEGORY_AUDIO, 0x6994ad04, 0x93ef, 0x11d0, 45 0xa3, 0xcc, 0x00, 0xa0, 0xc9, 0x22, 0x31, 0x96); 46 47namespace media { 48 49// Maximum number of output streams that can be open simultaneously. 50static const int kMaxOutputStreams = 50; 51 52// Up to 8 channels can be passed to the driver. 53// This should work, given the right drivers, but graceful error handling is 54// needed. 55static const int kWinMaxChannels = 8; 56 57// We use 3 buffers for recording audio so that if a recording callback takes 58// some time to return we won't lose audio. More buffers while recording are 59// ok because they don't introduce any delay in recording, unlike in playback 60// where you first need to fill in that number of buffers before starting to 61// play. 62static const int kNumInputBuffers = 3; 63 64static int GetVersionPartAsInt(DWORDLONG num) { 65 return static_cast<int>(num & 0xffff); 66} 67 68// Returns a string containing the given device's description and installed 69// driver version. 70static string16 GetDeviceAndDriverInfo(HDEVINFO device_info, 71 SP_DEVINFO_DATA* device_data) { 72 // Save the old install params setting and set a flag for the 73 // SetupDiBuildDriverInfoList below to return only the installed drivers. 74 SP_DEVINSTALL_PARAMS old_device_install_params; 75 old_device_install_params.cbSize = sizeof(old_device_install_params); 76 SetupDiGetDeviceInstallParams(device_info, device_data, 77 &old_device_install_params); 78 SP_DEVINSTALL_PARAMS device_install_params = old_device_install_params; 79 device_install_params.FlagsEx |= DI_FLAGSEX_INSTALLEDDRIVER; 80 SetupDiSetDeviceInstallParams(device_info, device_data, 81 &device_install_params); 82 83 SP_DRVINFO_DATA driver_data; 84 driver_data.cbSize = sizeof(driver_data); 85 string16 device_and_driver_info; 86 if (SetupDiBuildDriverInfoList(device_info, device_data, 87 SPDIT_COMPATDRIVER)) { 88 if (SetupDiEnumDriverInfo(device_info, device_data, SPDIT_COMPATDRIVER, 0, 89 &driver_data)) { 90 DWORDLONG version = driver_data.DriverVersion; 91 device_and_driver_info = string16(driver_data.Description) + L" v" + 92 base::IntToString16(GetVersionPartAsInt((version >> 48))) + L"." + 93 base::IntToString16(GetVersionPartAsInt((version >> 32))) + L"." + 94 base::IntToString16(GetVersionPartAsInt((version >> 16))) + L"." + 95 base::IntToString16(GetVersionPartAsInt(version)); 96 } 97 SetupDiDestroyDriverInfoList(device_info, device_data, SPDIT_COMPATDRIVER); 98 } 99 100 SetupDiSetDeviceInstallParams(device_info, device_data, 101 &old_device_install_params); 102 103 return device_and_driver_info; 104} 105 106AudioManagerWin::AudioManagerWin() { 107 if (!media::IsWASAPISupported()) { 108 // Use the Wave API for device enumeration if XP or lower. 109 enumeration_type_ = kWaveEnumeration; 110 } else { 111 // Use the MMDevice API for device enumeration if Vista or higher. 112 enumeration_type_ = kMMDeviceEnumeration; 113 } 114 115 SetMaxOutputStreamsAllowed(kMaxOutputStreams); 116 117 // Task must be posted last to avoid races from handing out "this" to the 118 // audio thread. 119 GetMessageLoop()->PostTask(FROM_HERE, base::Bind( 120 &AudioManagerWin::CreateDeviceListener, base::Unretained(this))); 121} 122 123AudioManagerWin::~AudioManagerWin() { 124 // It's safe to post a task here since Shutdown() will wait for all tasks to 125 // complete before returning. 126 GetMessageLoop()->PostTask(FROM_HERE, base::Bind( 127 &AudioManagerWin::DestroyDeviceListener, base::Unretained(this))); 128 Shutdown(); 129} 130 131bool AudioManagerWin::HasAudioOutputDevices() { 132 return (::waveOutGetNumDevs() != 0); 133} 134 135bool AudioManagerWin::HasAudioInputDevices() { 136 return (::waveInGetNumDevs() != 0); 137} 138 139void AudioManagerWin::CreateDeviceListener() { 140 // AudioDeviceListenerWin must be initialized on a COM thread and should only 141 // be used if WASAPI / Core Audio is supported. 142 if (media::IsWASAPISupported()) { 143 output_device_listener_.reset(new AudioDeviceListenerWin(BindToLoop( 144 GetMessageLoop(), base::Bind( 145 &AudioManagerWin::NotifyAllOutputDeviceChangeListeners, 146 base::Unretained(this))))); 147 } 148} 149 150void AudioManagerWin::DestroyDeviceListener() { 151 output_device_listener_.reset(); 152} 153 154string16 AudioManagerWin::GetAudioInputDeviceModel() { 155 // Get the default audio capture device and its device interface name. 156 DWORD device_id = 0; 157 waveInMessage(reinterpret_cast<HWAVEIN>(WAVE_MAPPER), 158 DRVM_MAPPER_PREFERRED_GET, 159 reinterpret_cast<DWORD_PTR>(&device_id), NULL); 160 ULONG device_interface_name_size = 0; 161 waveInMessage(reinterpret_cast<HWAVEIN>(device_id), 162 DRV_QUERYDEVICEINTERFACESIZE, 163 reinterpret_cast<DWORD_PTR>(&device_interface_name_size), 0); 164 size_t bytes_in_char16 = sizeof(string16::value_type); 165 DCHECK_EQ(0u, device_interface_name_size % bytes_in_char16); 166 if (device_interface_name_size <= bytes_in_char16) 167 return string16(); // No audio capture device. 168 169 string16 device_interface_name; 170 string16::value_type* name_ptr = WriteInto(&device_interface_name, 171 device_interface_name_size / bytes_in_char16); 172 waveInMessage(reinterpret_cast<HWAVEIN>(device_id), 173 DRV_QUERYDEVICEINTERFACE, 174 reinterpret_cast<DWORD_PTR>(name_ptr), 175 static_cast<DWORD_PTR>(device_interface_name_size)); 176 177 // Enumerate all audio devices and find the one matching the above device 178 // interface name. 179 HDEVINFO device_info = SetupDiGetClassDevs( 180 &AM_KSCATEGORY_AUDIO, 0, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); 181 if (device_info == INVALID_HANDLE_VALUE) 182 return string16(); 183 184 DWORD interface_index = 0; 185 SP_DEVICE_INTERFACE_DATA interface_data; 186 interface_data.cbSize = sizeof(interface_data); 187 while (SetupDiEnumDeviceInterfaces(device_info, 0, &AM_KSCATEGORY_AUDIO, 188 interface_index++, &interface_data)) { 189 // Query the size of the struct, allocate it and then query the data. 190 SP_DEVINFO_DATA device_data; 191 device_data.cbSize = sizeof(device_data); 192 DWORD interface_detail_size = 0; 193 SetupDiGetDeviceInterfaceDetail(device_info, &interface_data, 0, 0, 194 &interface_detail_size, &device_data); 195 if (!interface_detail_size) 196 continue; 197 198 scoped_array<char> interface_detail_buffer(new char[interface_detail_size]); 199 SP_DEVICE_INTERFACE_DETAIL_DATA* interface_detail = 200 reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA*>( 201 interface_detail_buffer.get()); 202 interface_detail->cbSize = interface_detail_size; 203 if (!SetupDiGetDeviceInterfaceDetail(device_info, &interface_data, 204 interface_detail, 205 interface_detail_size, NULL, 206 &device_data)) 207 return string16(); 208 209 bool device_found = (device_interface_name == interface_detail->DevicePath); 210 211 if (device_found) 212 return GetDeviceAndDriverInfo(device_info, &device_data); 213 } 214 215 return string16(); 216} 217 218bool AudioManagerWin::CanShowAudioInputSettings() { 219 return true; 220} 221 222void AudioManagerWin::ShowAudioInputSettings() { 223 std::wstring program; 224 std::string argument; 225 if (!media::IsWASAPISupported()) { 226 program = L"sndvol32.exe"; 227 argument = "-R"; 228 } else { 229 program = L"control.exe"; 230 argument = "mmsys.cpl,,1"; 231 } 232 233 FilePath path; 234 PathService::Get(base::DIR_SYSTEM, &path); 235 path = path.Append(program); 236 CommandLine command_line(path); 237 command_line.AppendArg(argument); 238 base::LaunchProcess(command_line, base::LaunchOptions(), NULL); 239} 240 241void AudioManagerWin::GetAudioInputDeviceNames( 242 media::AudioDeviceNames* device_names) { 243 DCHECK(enumeration_type() != kUninitializedEnumeration); 244 // Enumerate all active audio-endpoint capture devices. 245 if (enumeration_type() == kWaveEnumeration) { 246 // Utilize the Wave API for Windows XP. 247 media::GetInputDeviceNamesWinXP(device_names); 248 } else { 249 // Utilize the MMDevice API (part of Core Audio) for Vista and higher. 250 media::GetInputDeviceNamesWin(device_names); 251 } 252 253 // Always add default device parameters as first element. 254 if (!device_names->empty()) { 255 media::AudioDeviceName name; 256 name.device_name = AudioManagerBase::kDefaultDeviceName; 257 name.unique_id = AudioManagerBase::kDefaultDeviceId; 258 device_names->push_front(name); 259 } 260} 261 262// Factory for the implementations of AudioOutputStream for AUDIO_PCM_LINEAR 263// mode. 264// - PCMWaveOutAudioOutputStream: Based on the waveOut API. 265AudioOutputStream* AudioManagerWin::MakeLinearOutputStream( 266 const AudioParameters& params) { 267 DCHECK_EQ(AudioParameters::AUDIO_PCM_LINEAR, params.format()); 268 if (params.channels() > kWinMaxChannels) 269 return NULL; 270 271 return new PCMWaveOutAudioOutputStream(this, 272 params, 273 media::NumberOfWaveOutBuffers(), 274 WAVE_MAPPER); 275} 276 277// Factory for the implementations of AudioOutputStream for 278// AUDIO_PCM_LOW_LATENCY mode. Two implementations should suffice most 279// windows user's needs. 280// - PCMWaveOutAudioOutputStream: Based on the waveOut API. 281// - WASAPIAudioOutputStream: Based on Core Audio (WASAPI) API. 282AudioOutputStream* AudioManagerWin::MakeLowLatencyOutputStream( 283 const AudioParameters& params) { 284 DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format()); 285 if (params.channels() > kWinMaxChannels) 286 return NULL; 287 288 if (!media::IsWASAPISupported()) { 289 // Fall back to Windows Wave implementation on Windows XP or lower. 290 DVLOG(1) << "Using WaveOut since WASAPI requires at least Vista."; 291 return new PCMWaveOutAudioOutputStream(this, params, 2, WAVE_MAPPER); 292 } 293 294 // TODO(henrika): remove once we properly handle input device selection. 295 if (CommandLine::ForCurrentProcess()->HasSwitch( 296 switches::kEnableWebAudioInput)) { 297 if (WASAPIUnifiedStream::HasUnifiedDefaultIO()) { 298 DVLOG(1) << "WASAPIUnifiedStream is created."; 299 return new WASAPIUnifiedStream(this, params); 300 } 301 LOG(WARNING) << "Unified audio I/O is not supported."; 302 } 303 304 return new WASAPIAudioOutputStream(this, params, eConsole); 305} 306 307// Factory for the implementations of AudioInputStream for AUDIO_PCM_LINEAR 308// mode. 309AudioInputStream* AudioManagerWin::MakeLinearInputStream( 310 const AudioParameters& params, const std::string& device_id) { 311 DCHECK_EQ(AudioParameters::AUDIO_PCM_LINEAR, params.format()); 312 return CreatePCMWaveInAudioInputStream(params, device_id); 313} 314 315// Factory for the implementations of AudioInputStream for 316// AUDIO_PCM_LOW_LATENCY mode. 317AudioInputStream* AudioManagerWin::MakeLowLatencyInputStream( 318 const AudioParameters& params, const std::string& device_id) { 319 DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format()); 320 AudioInputStream* stream = NULL; 321 if (!media::IsWASAPISupported()) { 322 // Fall back to Windows Wave implementation on Windows XP or lower. 323 DVLOG(1) << "Using WaveIn since WASAPI requires at least Vista."; 324 stream = CreatePCMWaveInAudioInputStream(params, device_id); 325 } else { 326 stream = new WASAPIAudioInputStream(this, params, device_id); 327 } 328 329 return stream; 330} 331 332AudioInputStream* AudioManagerWin::CreatePCMWaveInAudioInputStream( 333 const AudioParameters& params, 334 const std::string& device_id) { 335 std::string xp_device_id = device_id; 336 if (device_id != AudioManagerBase::kDefaultDeviceId && 337 enumeration_type_ == kMMDeviceEnumeration) { 338 xp_device_id = media::ConvertToWinXPDeviceId(device_id); 339 if (xp_device_id.empty()) { 340 DLOG(ERROR) << "Cannot find a waveIn device which matches the device ID " 341 << device_id; 342 return NULL; 343 } 344 } 345 346 return new PCMWaveInAudioInputStream(this, params, kNumInputBuffers, 347 xp_device_id); 348} 349 350/// static 351AudioManager* CreateAudioManager() { 352 return new AudioManagerWin(); 353} 354 355AudioParameters AudioManagerWin::GetPreferredLowLatencyOutputStreamParameters( 356 const AudioParameters& input_params) { 357 // If WASAPI isn't supported we'll fallback to WaveOut, which will take care 358 // of resampling and bits per sample changes. By setting these equal to the 359 // input values, AudioOutputResampler will skip resampling and bit per sample 360 // differences (since the input parameters will match the output parameters). 361 int sample_rate = input_params.sample_rate(); 362 int bits_per_sample = input_params.bits_per_sample(); 363 ChannelLayout channel_layout = input_params.channel_layout(); 364 if (IsWASAPISupported()) { 365 sample_rate = GetAudioHardwareSampleRate(); 366 bits_per_sample = 16; 367 channel_layout = WASAPIAudioOutputStream::HardwareChannelLayout(); 368 } 369 370 // TODO(dalecurtis): This should include hardware bits per channel eventually. 371 return AudioParameters( 372 AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, 373 sample_rate, bits_per_sample, GetAudioHardwareBufferSize()); 374} 375 376} // namespace media 377