audio_manager_win.cc revision a93a17c8d99d686bd4a1511e5504e5e6cc9fcadf
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/files/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_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"
38
39// Libraries required for the SetupAPI and Wbem APIs used here.
40#pragma comment(lib, "setupapi.lib")
41
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
47DEFINE_GUID(AM_KSCATEGORY_AUDIO, 0x6994ad04, 0x93ef, 0x11d0,
48            0xa3, 0xcc, 0x00, 0xa0, 0xc9, 0x22, 0x31, 0x96);
49
50namespace media {
51
52// Maximum number of output streams that can be open simultaneously.
53static const int kMaxOutputStreams = 50;
54
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.
57static const int kWinMaxChannels = 8;
58
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.
64static const int kNumInputBuffers = 3;
65
66// Buffer size to use for input and output stream when a proper size can't be
67// determined from the system
68static const int kFallbackBufferSize = 2048;
69
70static int GetVersionPartAsInt(DWORDLONG num) {
71  return static_cast<int>(num & 0xffff);
72}
73
74// Returns a string containing the given device's description and installed
75// driver version.
76static 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);
88
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));
102    }
103    SetupDiDestroyDriverInfoList(device_info, device_data, SPDIT_COMPATDRIVER);
104  }
105
106  SetupDiSetDeviceInstallParams(device_info, device_data,
107                                &old_device_install_params);
108
109  return device_and_driver_info;
110}
111
112AudioManagerWin::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;
119  }
120
121  SetMaxOutputStreamsAllowed(kMaxOutputStreams);
122
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)));
127}
128
129AudioManagerWin::~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();
135}
136
137bool AudioManagerWin::HasAudioOutputDevices() {
138  return (::waveOutGetNumDevs() != 0);
139}
140
141bool AudioManagerWin::HasAudioInputDevices() {
142  return (::waveInGetNumDevs() != 0);
143}
144
145void 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)))));
153  }
154}
155
156void AudioManagerWin::DestroyDeviceListener() {
157  output_device_listener_.reset();
158}
159
160string16 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.
174
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));
182
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();
189
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;
203
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();
214
215    bool device_found = (device_interface_name == interface_detail->DevicePath);
216
217    if (device_found)
218      return GetDeviceAndDriverInfo(device_info, &device_data);
219  }
220
221  return string16();
222}
223
224void 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";
233  }
234
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);
241}
242
243void 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);
253  }
254
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);
261  }
262}
263
264AudioParameters 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;
275  }
276
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);
281}
282
283// Factory for the implementations of AudioOutputStream for AUDIO_PCM_LINEAR
284// mode.
285// - PCMWaveOutAudioOutputStream: Based on the waveOut API.
286AudioOutputStream* AudioManagerWin::MakeLinearOutputStream(
287    const AudioParameters& params) {
288  DCHECK_EQ(AudioParameters::AUDIO_PCM_LINEAR, params.format());
289  if (params.channels() > kWinMaxChannels)
290    return NULL;
291
292  return new PCMWaveOutAudioOutputStream(this,
293                                         params,
294                                         media::NumberOfWaveOutBuffers(),
295                                         WAVE_MAPPER);
296}
297
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.
303AudioOutputStream* AudioManagerWin::MakeLowLatencyOutputStream(
304    const AudioParameters& params) {
305  DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format());
306  if (params.channels() > kWinMaxChannels)
307    return NULL;
308
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);
314  }
315
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);
320  }
321
322  return new WASAPIAudioOutputStream(this, params, eConsole);
323}
324
325// Factory for the implementations of AudioInputStream for AUDIO_PCM_LINEAR
326// mode.
327AudioInputStream* 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);
331}
332
333// Factory for the implementations of AudioInputStream for
334// AUDIO_PCM_LOW_LATENCY mode.
335AudioInputStream* 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);
345  }
346
347  return stream;
348}
349
350AudioParameters 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();
374
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();
381
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;
388    }
389  }
390
391  if (input_params.IsValid()) {
392    if (CoreAudioUtil::IsSupported()) {
393      // Check if it is possible to open up at the specified input channel
394      // layout but avoid checking if the specified layout is the same as the
395      // hardware (preferred) layout. We do this extra check to avoid the
396      // CoreAudioUtil::IsChannelLayoutSupported() overhead in most cases.
397      if (input_params.channel_layout() != channel_layout) {
398        if (CoreAudioUtil::IsChannelLayoutSupported(
399                eRender, eConsole, input_params.channel_layout())) {
400          // Open up using the same channel layout as the source if it is
401          // supported by the hardware.
402          channel_layout = input_params.channel_layout();
403          VLOG(1) << "Hardware channel layout is not used; using same layout"
404                  << " as the source instead (" << channel_layout << ")";
405        }
406      }
407    }
408    input_channels = input_params.input_channels();
409    if (use_input_params) {
410      // If WASAPI isn't supported we'll fallback to WaveOut, which will take
411      // care of resampling and bits per sample changes.  By setting these
412      // equal to the input values, AudioOutputResampler will skip resampling
413      // and bit per sample differences (since the input parameters will match
414      // the output parameters).
415      sample_rate = input_params.sample_rate();
416      bits_per_sample = input_params.bits_per_sample();
417      channel_layout = input_params.channel_layout();
418      buffer_size = input_params.frames_per_buffer();
419    }
420  }
421
422  int user_buffer_size = GetUserBufferSize();
423  if (user_buffer_size)
424    buffer_size = user_buffer_size;
425
426  return AudioParameters(
427      AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, input_channels,
428      sample_rate, bits_per_sample, buffer_size);
429}
430
431AudioInputStream* AudioManagerWin::CreatePCMWaveInAudioInputStream(
432    const AudioParameters& params,
433    const std::string& device_id) {
434  std::string xp_device_id = device_id;
435  if (device_id != AudioManagerBase::kDefaultDeviceId &&
436      enumeration_type_ == kMMDeviceEnumeration) {
437    xp_device_id = media::ConvertToWinXPDeviceId(device_id);
438    if (xp_device_id.empty()) {
439      DLOG(ERROR) << "Cannot find a waveIn device which matches the device ID "
440                  << device_id;
441      return NULL;
442    }
443  }
444
445  return new PCMWaveInAudioInputStream(this, params, kNumInputBuffers,
446                                       xp_device_id);
447}
448
449/// static
450AudioManager* CreateAudioManager() {
451  return new AudioManagerWin();
452}
453
454}  // namespace media
455