audio_manager_win.cc revision a1401311d1ab56c4ed0a474bd38c108f75cb0cd9
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/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 "base/win/windows_version.h"
24#include "media/audio/audio_parameters.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/core_audio_util_win.h"
30#include "media/audio/win/device_enumeration_win.h"
31#include "media/audio/win/wavein_input_win.h"
32#include "media/audio/win/waveout_output_win.h"
33#include "media/base/bind_to_current_loop.h"
34#include "media/base/channel_layout.h"
35#include "media/base/limits.h"
36#include "media/base/media_switches.h"
37
38// Libraries required for the SetupAPI and Wbem APIs used here.
39#pragma comment(lib, "setupapi.lib")
40
41// The following are defined in various DDK headers, and we (re)define them here
42// to avoid adding the DDK as a chrome dependency.
43#define DRV_QUERYDEVICEINTERFACE 0x80c
44#define DRVM_MAPPER_PREFERRED_GET 0x2015
45#define DRV_QUERYDEVICEINTERFACESIZE 0x80d
46DEFINE_GUID(AM_KSCATEGORY_AUDIO, 0x6994ad04, 0x93ef, 0x11d0,
47            0xa3, 0xcc, 0x00, 0xa0, 0xc9, 0x22, 0x31, 0x96);
48
49namespace media {
50
51// Maximum number of output streams that can be open simultaneously.
52static const int kMaxOutputStreams = 50;
53
54// Up to 8 channels can be passed to the driver.  This should work, given the
55// right drivers, but graceful error handling is needed.
56static const int kWinMaxChannels = 8;
57
58// We use 3 buffers for recording audio so that if a recording callback takes
59// some time to return we won't lose audio. More buffers while recording are
60// ok because they don't introduce any delay in recording, unlike in playback
61// where you first need to fill in that number of buffers before starting to
62// play.
63static const int kNumInputBuffers = 3;
64
65// Buffer size to use for input and output stream when a proper size can't be
66// determined from the system
67static const int kFallbackBufferSize = 2048;
68
69static int GetVersionPartAsInt(DWORDLONG num) {
70  return static_cast<int>(num & 0xffff);
71}
72
73// Returns a string containing the given device's description and installed
74// driver version.
75static base::string16 GetDeviceAndDriverInfo(HDEVINFO device_info,
76                                             SP_DEVINFO_DATA* device_data) {
77  // Save the old install params setting and set a flag for the
78  // SetupDiBuildDriverInfoList below to return only the installed drivers.
79  SP_DEVINSTALL_PARAMS old_device_install_params;
80  old_device_install_params.cbSize = sizeof(old_device_install_params);
81  SetupDiGetDeviceInstallParams(device_info, device_data,
82                                &old_device_install_params);
83  SP_DEVINSTALL_PARAMS device_install_params = old_device_install_params;
84  device_install_params.FlagsEx |= DI_FLAGSEX_INSTALLEDDRIVER;
85  SetupDiSetDeviceInstallParams(device_info, device_data,
86                                &device_install_params);
87
88  SP_DRVINFO_DATA driver_data;
89  driver_data.cbSize = sizeof(driver_data);
90  base::string16 device_and_driver_info;
91  if (SetupDiBuildDriverInfoList(device_info, device_data,
92                                 SPDIT_COMPATDRIVER)) {
93    if (SetupDiEnumDriverInfo(device_info, device_data, SPDIT_COMPATDRIVER, 0,
94                              &driver_data)) {
95      DWORDLONG version = driver_data.DriverVersion;
96      device_and_driver_info = base::string16(driver_data.Description) + L" v" +
97          base::IntToString16(GetVersionPartAsInt((version >> 48))) + L"." +
98          base::IntToString16(GetVersionPartAsInt((version >> 32))) + L"." +
99          base::IntToString16(GetVersionPartAsInt((version >> 16))) + L"." +
100          base::IntToString16(GetVersionPartAsInt(version));
101    }
102    SetupDiDestroyDriverInfoList(device_info, device_data, SPDIT_COMPATDRIVER);
103  }
104
105  SetupDiSetDeviceInstallParams(device_info, device_data,
106                                &old_device_install_params);
107
108  return device_and_driver_info;
109}
110
111static int NumberOfWaveOutBuffers() {
112  // Use the user provided buffer count if provided.
113  int buffers = 0;
114  std::string buffers_str(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
115      switches::kWaveOutBuffers));
116  if (base::StringToInt(buffers_str, &buffers) && buffers > 0) {
117    return buffers;
118  }
119
120  // Use 4 buffers for Vista, 3 for everyone else:
121  //  - The entire Windows audio stack was rewritten for Windows Vista and wave
122  //    out performance was degraded compared to XP.
123  //  - The regression was fixed in Windows 7 and most configurations will work
124  //    with 2, but some (e.g., some Sound Blasters) still need 3.
125  //  - Some XP configurations (even multi-processor ones) also need 3.
126  return (base::win::GetVersion() == base::win::VERSION_VISTA) ? 4 : 3;
127}
128
129AudioManagerWin::AudioManagerWin(AudioLogFactory* audio_log_factory)
130    : AudioManagerBase(audio_log_factory),
131      // |CoreAudioUtil::IsSupported()| uses static variables to avoid doing
132      // multiple initializations.  This is however not thread safe.
133      // So, here we call it explicitly before we kick off the audio thread
134      // or do any other work.
135      enumeration_type_(CoreAudioUtil::IsSupported() ?
136          kMMDeviceEnumeration : kWaveEnumeration) {
137  SetMaxOutputStreamsAllowed(kMaxOutputStreams);
138
139  // WARNING: This is executed on the UI loop, do not add any code here which
140  // loads libraries or attempts to call out into the OS.  Instead add such code
141  // to the InitializeOnAudioThread() method below.
142
143  // Task must be posted last to avoid races from handing out "this" to the
144  // audio thread.
145  GetTaskRunner()->PostTask(FROM_HERE, base::Bind(
146      &AudioManagerWin::InitializeOnAudioThread, base::Unretained(this)));
147}
148
149AudioManagerWin::~AudioManagerWin() {
150  // It's safe to post a task here since Shutdown() will wait for all tasks to
151  // complete before returning.
152  GetTaskRunner()->PostTask(FROM_HERE, base::Bind(
153      &AudioManagerWin::ShutdownOnAudioThread, base::Unretained(this)));
154  Shutdown();
155}
156
157bool AudioManagerWin::HasAudioOutputDevices() {
158  return (::waveOutGetNumDevs() != 0);
159}
160
161bool AudioManagerWin::HasAudioInputDevices() {
162  return (::waveInGetNumDevs() != 0);
163}
164
165void AudioManagerWin::InitializeOnAudioThread() {
166  DCHECK(GetTaskRunner()->BelongsToCurrentThread());
167
168  if (core_audio_supported()) {
169    // AudioDeviceListenerWin must be initialized on a COM thread and should
170    // only be used if WASAPI / Core Audio is supported.
171    output_device_listener_.reset(new AudioDeviceListenerWin(BindToCurrentLoop(
172        base::Bind(&AudioManagerWin::NotifyAllOutputDeviceChangeListeners,
173                   base::Unretained(this)))));
174  }
175}
176
177void AudioManagerWin::ShutdownOnAudioThread() {
178  DCHECK(GetTaskRunner()->BelongsToCurrentThread());
179  output_device_listener_.reset();
180}
181
182base::string16 AudioManagerWin::GetAudioInputDeviceModel() {
183  // Get the default audio capture device and its device interface name.
184  DWORD device_id = 0;
185  waveInMessage(reinterpret_cast<HWAVEIN>(WAVE_MAPPER),
186                DRVM_MAPPER_PREFERRED_GET,
187                reinterpret_cast<DWORD_PTR>(&device_id), NULL);
188  ULONG device_interface_name_size = 0;
189  waveInMessage(reinterpret_cast<HWAVEIN>(device_id),
190                DRV_QUERYDEVICEINTERFACESIZE,
191                reinterpret_cast<DWORD_PTR>(&device_interface_name_size), 0);
192  size_t bytes_in_char16 = sizeof(base::string16::value_type);
193  DCHECK_EQ(0u, device_interface_name_size % bytes_in_char16);
194  if (device_interface_name_size <= bytes_in_char16)
195    return base::string16();  // No audio capture device.
196
197  base::string16 device_interface_name;
198  base::string16::value_type* name_ptr = WriteInto(&device_interface_name,
199      device_interface_name_size / bytes_in_char16);
200  waveInMessage(reinterpret_cast<HWAVEIN>(device_id),
201                DRV_QUERYDEVICEINTERFACE,
202                reinterpret_cast<DWORD_PTR>(name_ptr),
203                static_cast<DWORD_PTR>(device_interface_name_size));
204
205  // Enumerate all audio devices and find the one matching the above device
206  // interface name.
207  HDEVINFO device_info = SetupDiGetClassDevs(
208      &AM_KSCATEGORY_AUDIO, 0, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
209  if (device_info == INVALID_HANDLE_VALUE)
210    return base::string16();
211
212  DWORD interface_index = 0;
213  SP_DEVICE_INTERFACE_DATA interface_data;
214  interface_data.cbSize = sizeof(interface_data);
215  while (SetupDiEnumDeviceInterfaces(device_info, 0, &AM_KSCATEGORY_AUDIO,
216                                     interface_index++, &interface_data)) {
217    // Query the size of the struct, allocate it and then query the data.
218    SP_DEVINFO_DATA device_data;
219    device_data.cbSize = sizeof(device_data);
220    DWORD interface_detail_size = 0;
221    SetupDiGetDeviceInterfaceDetail(device_info, &interface_data, 0, 0,
222                                    &interface_detail_size, &device_data);
223    if (!interface_detail_size)
224      continue;
225
226    scoped_ptr<char[]> interface_detail_buffer(new char[interface_detail_size]);
227    SP_DEVICE_INTERFACE_DETAIL_DATA* interface_detail =
228        reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA*>(
229            interface_detail_buffer.get());
230    interface_detail->cbSize = interface_detail_size;
231    if (!SetupDiGetDeviceInterfaceDetail(device_info, &interface_data,
232                                         interface_detail,
233                                         interface_detail_size, NULL,
234                                         &device_data))
235      return base::string16();
236
237    bool device_found = (device_interface_name == interface_detail->DevicePath);
238
239    if (device_found)
240      return GetDeviceAndDriverInfo(device_info, &device_data);
241  }
242
243  return base::string16();
244}
245
246void AudioManagerWin::ShowAudioInputSettings() {
247  std::wstring program;
248  std::string argument;
249  if (!core_audio_supported()) {
250    program = L"sndvol32.exe";
251    argument = "-R";
252  } else {
253    program = L"control.exe";
254    argument = "mmsys.cpl,,1";
255  }
256
257  base::FilePath path;
258  PathService::Get(base::DIR_SYSTEM, &path);
259  path = path.Append(program);
260  CommandLine command_line(path);
261  command_line.AppendArg(argument);
262  base::LaunchProcess(command_line, base::LaunchOptions(), NULL);
263}
264
265void AudioManagerWin::GetAudioDeviceNamesImpl(
266    bool input,
267    AudioDeviceNames* device_names) {
268  DCHECK(device_names->empty());
269  // Enumerate all active audio-endpoint capture devices.
270  if (enumeration_type() == kWaveEnumeration) {
271    // Utilize the Wave API for Windows XP.
272    if (input)
273      GetInputDeviceNamesWinXP(device_names);
274    else
275      GetOutputDeviceNamesWinXP(device_names);
276  } else {
277    // Utilize the MMDevice API (part of Core Audio) for Vista and higher.
278    if (input)
279      GetInputDeviceNamesWin(device_names);
280    else
281      GetOutputDeviceNamesWin(device_names);
282  }
283
284  // Always add default device parameters as first element.
285  if (!device_names->empty()) {
286    AudioDeviceName name;
287    name.device_name = AudioManagerBase::kDefaultDeviceName;
288    name.unique_id = AudioManagerBase::kDefaultDeviceId;
289    device_names->push_front(name);
290  }
291}
292
293void AudioManagerWin::GetAudioInputDeviceNames(AudioDeviceNames* device_names) {
294  GetAudioDeviceNamesImpl(true, device_names);
295}
296
297void AudioManagerWin::GetAudioOutputDeviceNames(
298    AudioDeviceNames* device_names) {
299  GetAudioDeviceNamesImpl(false, device_names);
300}
301
302AudioParameters AudioManagerWin::GetInputStreamParameters(
303    const std::string& device_id) {
304  if (!core_audio_supported()) {
305    return AudioParameters(
306        AudioParameters::AUDIO_PCM_LINEAR, CHANNEL_LAYOUT_STEREO, 0, 48000,
307        16, kFallbackBufferSize, AudioParameters::NO_EFFECTS);
308  }
309
310  return WASAPIAudioInputStream::GetInputStreamParameters(device_id);
311}
312
313std::string AudioManagerWin::GetAssociatedOutputDeviceID(
314    const std::string& input_device_id) {
315  if (!core_audio_supported()) {
316    NOTIMPLEMENTED()
317        << "GetAssociatedOutputDeviceID is not supported on this OS";
318    return std::string();
319  }
320  return CoreAudioUtil::GetMatchingOutputDeviceID(input_device_id);
321}
322
323// Factory for the implementations of AudioOutputStream for AUDIO_PCM_LINEAR
324// mode.
325// - PCMWaveOutAudioOutputStream: Based on the waveOut API.
326AudioOutputStream* AudioManagerWin::MakeLinearOutputStream(
327    const AudioParameters& params) {
328  DCHECK_EQ(AudioParameters::AUDIO_PCM_LINEAR, params.format());
329  if (params.channels() > kWinMaxChannels)
330    return NULL;
331
332  return new PCMWaveOutAudioOutputStream(this,
333                                         params,
334                                         NumberOfWaveOutBuffers(),
335                                         WAVE_MAPPER);
336}
337
338// Factory for the implementations of AudioOutputStream for
339// AUDIO_PCM_LOW_LATENCY mode. Two implementations should suffice most
340// windows user's needs.
341// - PCMWaveOutAudioOutputStream: Based on the waveOut API.
342// - WASAPIAudioOutputStream: Based on Core Audio (WASAPI) API.
343AudioOutputStream* AudioManagerWin::MakeLowLatencyOutputStream(
344    const AudioParameters& params,
345    const std::string& device_id) {
346  DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format());
347  if (params.channels() > kWinMaxChannels)
348    return NULL;
349
350  if (!core_audio_supported()) {
351    // Fall back to Windows Wave implementation on Windows XP or lower.
352    DLOG_IF(ERROR, !device_id.empty() &&
353        device_id != AudioManagerBase::kDefaultDeviceId)
354        << "Opening by device id not supported by PCMWaveOutAudioOutputStream";
355    DVLOG(1) << "Using WaveOut since WASAPI requires at least Vista.";
356    return new PCMWaveOutAudioOutputStream(
357        this, params, NumberOfWaveOutBuffers(), WAVE_MAPPER);
358  }
359
360  // Pass an empty string to indicate that we want the default device
361  // since we consistently only check for an empty string in
362  // WASAPIAudioOutputStream.
363  return new WASAPIAudioOutputStream(this,
364      device_id == AudioManagerBase::kDefaultDeviceId ?
365          std::string() : device_id,
366      params,
367      params.effects() & AudioParameters::DUCKING ? eCommunications : eConsole);
368}
369
370// Factory for the implementations of AudioInputStream for AUDIO_PCM_LINEAR
371// mode.
372AudioInputStream* AudioManagerWin::MakeLinearInputStream(
373    const AudioParameters& params, const std::string& device_id) {
374  DCHECK_EQ(AudioParameters::AUDIO_PCM_LINEAR, params.format());
375  return CreatePCMWaveInAudioInputStream(params, device_id);
376}
377
378// Factory for the implementations of AudioInputStream for
379// AUDIO_PCM_LOW_LATENCY mode.
380AudioInputStream* AudioManagerWin::MakeLowLatencyInputStream(
381    const AudioParameters& params, const std::string& device_id) {
382  DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format());
383  DVLOG(1) << "MakeLowLatencyInputStream: " << device_id;
384  AudioInputStream* stream = NULL;
385  if (!core_audio_supported()) {
386    // Fall back to Windows Wave implementation on Windows XP or lower.
387    DVLOG(1) << "Using WaveIn since WASAPI requires at least Vista.";
388    stream = CreatePCMWaveInAudioInputStream(params, device_id);
389  } else {
390    stream = new WASAPIAudioInputStream(this, params, device_id);
391  }
392
393  return stream;
394}
395
396std::string AudioManagerWin::GetDefaultOutputDeviceID() {
397  if (!core_audio_supported())
398    return std::string();
399  return CoreAudioUtil::GetDefaultOutputDeviceID();
400}
401
402AudioParameters AudioManagerWin::GetPreferredOutputStreamParameters(
403    const std::string& output_device_id,
404    const AudioParameters& input_params) {
405  DLOG_IF(ERROR, !core_audio_supported() && !output_device_id.empty())
406      << "CoreAudio is required to open non-default devices.";
407
408  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
409  ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
410  int sample_rate = 48000;
411  int buffer_size = kFallbackBufferSize;
412  int bits_per_sample = 16;
413  int input_channels = 0;
414  int effects = AudioParameters::NO_EFFECTS;
415  bool use_input_params = !core_audio_supported();
416  if (core_audio_supported()) {
417    if (cmd_line->HasSwitch(switches::kEnableExclusiveAudio)) {
418      // TODO(rtoy): tune these values for best possible WebAudio
419      // performance. WebRTC works well at 48kHz and a buffer size of 480
420      // samples will be used for this case. Note that exclusive mode is
421      // experimental. This sample rate will be combined with a buffer size of
422      // 256 samples, which corresponds to an output delay of ~5.33ms.
423      sample_rate = 48000;
424      buffer_size = 256;
425      if (input_params.IsValid())
426        channel_layout = input_params.channel_layout();
427    } else {
428      AudioParameters params;
429      HRESULT hr = CoreAudioUtil::GetPreferredAudioParameters(
430          output_device_id.empty() ?
431              GetDefaultOutputDeviceID() : output_device_id,
432          &params);
433      if (SUCCEEDED(hr)) {
434        bits_per_sample = params.bits_per_sample();
435        buffer_size = params.frames_per_buffer();
436        channel_layout = params.channel_layout();
437        sample_rate = params.sample_rate();
438        effects = params.effects();
439      } else {
440        // TODO(tommi): This should never happen really and I'm not sure that
441        // setting use_input_params is the right thing to do since WASAPI i
442        // definitely supported (see  core_audio_supported() above) and
443        // |use_input_params| is only for cases when it isn't supported.
444        DLOG(ERROR) << "GetPreferredAudioParameters failed: " << std::hex << hr;
445        use_input_params = true;
446      }
447    }
448  }
449
450  if (input_params.IsValid()) {
451    // If the user has enabled checking supported channel layouts or we don't
452    // have a valid channel layout yet, try to use the input layout.  See bugs
453    // http://crbug.com/259165 and http://crbug.com/311906 for more details.
454    if (core_audio_supported() &&
455        (cmd_line->HasSwitch(switches::kTrySupportedChannelLayouts) ||
456         channel_layout == CHANNEL_LAYOUT_UNSUPPORTED)) {
457      // Check if it is possible to open up at the specified input channel
458      // layout but avoid checking if the specified layout is the same as the
459      // hardware (preferred) layout. We do this extra check to avoid the
460      // CoreAudioUtil::IsChannelLayoutSupported() overhead in most cases.
461      if (input_params.channel_layout() != channel_layout) {
462        // TODO(henrika): Internally, IsChannelLayoutSupported does many of the
463        // operations that have already been done such as opening up a client
464        // and fetching the WAVEFORMATPCMEX format.  Ideally we should only do
465        // that once.  Then here, we can check the layout from the data we
466        // already hold.
467        if (CoreAudioUtil::IsChannelLayoutSupported(
468                output_device_id, eRender, eConsole,
469                input_params.channel_layout())) {
470          // Open up using the same channel layout as the source if it is
471          // supported by the hardware.
472          channel_layout = input_params.channel_layout();
473          VLOG(1) << "Hardware channel layout is not used; using same layout"
474                  << " as the source instead (" << channel_layout << ")";
475        }
476      }
477    }
478    input_channels = input_params.input_channels();
479    effects |= input_params.effects();
480    if (use_input_params) {
481      // If WASAPI isn't supported we'll fallback to WaveOut, which will take
482      // care of resampling and bits per sample changes.  By setting these
483      // equal to the input values, AudioOutputResampler will skip resampling
484      // and bit per sample differences (since the input parameters will match
485      // the output parameters).
486      bits_per_sample = input_params.bits_per_sample();
487      buffer_size = input_params.frames_per_buffer();
488      channel_layout = input_params.channel_layout();
489      sample_rate = input_params.sample_rate();
490    }
491  }
492
493  int user_buffer_size = GetUserBufferSize();
494  if (user_buffer_size)
495    buffer_size = user_buffer_size;
496
497  return AudioParameters(
498      AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, input_channels,
499      sample_rate, bits_per_sample, buffer_size, effects);
500}
501
502AudioInputStream* AudioManagerWin::CreatePCMWaveInAudioInputStream(
503    const AudioParameters& params,
504    const std::string& device_id) {
505  std::string xp_device_id = device_id;
506  if (device_id != AudioManagerBase::kDefaultDeviceId &&
507      enumeration_type_ == kMMDeviceEnumeration) {
508    xp_device_id = ConvertToWinXPInputDeviceId(device_id);
509    if (xp_device_id.empty()) {
510      DLOG(ERROR) << "Cannot find a waveIn device which matches the device ID "
511                  << device_id;
512      return NULL;
513    }
514  }
515
516  return new PCMWaveInAudioInputStream(this, params, kNumInputBuffers,
517                                       xp_device_id);
518}
519
520/// static
521AudioManager* CreateAudioManager(AudioLogFactory* audio_log_factory) {
522  return new AudioManagerWin(audio_log_factory);
523}
524
525}  // namespace media
526