audio_low_latency_input_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/win/audio_low_latency_input_win.h"
6
7#include "base/logging.h"
8#include "base/memory/scoped_ptr.h"
9#include "base/utf_string_conversions.h"
10#include "media/audio/audio_util.h"
11#include "media/audio/win/audio_manager_win.h"
12#include "media/audio/win/avrt_wrapper_win.h"
13
14using base::win::ScopedComPtr;
15using base::win::ScopedCOMInitializer;
16
17namespace media {
18
19WASAPIAudioInputStream::WASAPIAudioInputStream(
20    AudioManagerWin* manager, const AudioParameters& params,
21    const std::string& device_id)
22    : manager_(manager),
23      capture_thread_(NULL),
24      opened_(false),
25      started_(false),
26      endpoint_buffer_size_frames_(0),
27      device_id_(device_id),
28      sink_(NULL) {
29  DCHECK(manager_);
30
31  // Load the Avrt DLL if not already loaded. Required to support MMCSS.
32  bool avrt_init = avrt::Initialize();
33  DCHECK(avrt_init) << "Failed to load the Avrt.dll";
34
35  // Set up the desired capture format specified by the client.
36  format_.nSamplesPerSec = params.sample_rate();
37  format_.wFormatTag = WAVE_FORMAT_PCM;
38  format_.wBitsPerSample = params.bits_per_sample();
39  format_.nChannels = params.channels();
40  format_.nBlockAlign = (format_.wBitsPerSample / 8) * format_.nChannels;
41  format_.nAvgBytesPerSec = format_.nSamplesPerSec * format_.nBlockAlign;
42  format_.cbSize = 0;
43
44  // Size in bytes of each audio frame.
45  frame_size_ = format_.nBlockAlign;
46  // Store size of audio packets which we expect to get from the audio
47  // endpoint device in each capture event.
48  packet_size_frames_ = params.GetBytesPerBuffer() / format_.nBlockAlign;
49  packet_size_bytes_ = params.GetBytesPerBuffer();
50  DVLOG(1) << "Number of bytes per audio frame  : " << frame_size_;
51  DVLOG(1) << "Number of audio frames per packet: " << packet_size_frames_;
52
53  // All events are auto-reset events and non-signaled initially.
54
55  // Create the event which the audio engine will signal each time
56  // a buffer becomes ready to be processed by the client.
57  audio_samples_ready_event_.Set(CreateEvent(NULL, FALSE, FALSE, NULL));
58  DCHECK(audio_samples_ready_event_.IsValid());
59
60  // Create the event which will be set in Stop() when capturing shall stop.
61  stop_capture_event_.Set(CreateEvent(NULL, FALSE, FALSE, NULL));
62  DCHECK(stop_capture_event_.IsValid());
63
64  ms_to_frame_count_ = static_cast<double>(params.sample_rate()) / 1000.0;
65
66  LARGE_INTEGER performance_frequency;
67  if (QueryPerformanceFrequency(&performance_frequency)) {
68    perf_count_to_100ns_units_ =
69        (10000000.0 / static_cast<double>(performance_frequency.QuadPart));
70  } else {
71    LOG(ERROR) <<  "High-resolution performance counters are not supported.";
72    perf_count_to_100ns_units_ = 0.0;
73  }
74}
75
76WASAPIAudioInputStream::~WASAPIAudioInputStream() {}
77
78bool WASAPIAudioInputStream::Open() {
79  DCHECK(CalledOnValidThread());
80  // Verify that we are not already opened.
81  if (opened_)
82    return false;
83
84  // Obtain a reference to the IMMDevice interface of the capturing
85  // device with the specified unique identifier or role which was
86  // set at construction.
87  HRESULT hr = SetCaptureDevice();
88  if (FAILED(hr))
89    return false;
90
91  // Obtain an IAudioClient interface which enables us to create and initialize
92  // an audio stream between an audio application and the audio engine.
93  hr = ActivateCaptureDevice();
94  if (FAILED(hr))
95    return false;
96
97  // Retrieve the stream format which the audio engine uses for its internal
98  // processing/mixing of shared-mode streams. This function call is for
99  // diagnostic purposes only and only in debug mode.
100#ifndef NDEBUG
101  hr = GetAudioEngineStreamFormat();
102#endif
103
104  // Verify that the selected audio endpoint supports the specified format
105  // set during construction.
106  if (!DesiredFormatIsSupported()) {
107    return false;
108  }
109
110  // Initialize the audio stream between the client and the device using
111  // shared mode and a lowest possible glitch-free latency.
112  hr = InitializeAudioEngine();
113
114  opened_ = SUCCEEDED(hr);
115  return opened_;
116}
117
118void WASAPIAudioInputStream::Start(AudioInputCallback* callback) {
119  DCHECK(CalledOnValidThread());
120  DCHECK(callback);
121  DLOG_IF(ERROR, !opened_) << "Open() has not been called successfully";
122  if (!opened_)
123    return;
124
125  if (started_)
126    return;
127
128  sink_ = callback;
129
130  // Create and start the thread that will drive the capturing by waiting for
131  // capture events.
132  capture_thread_ =
133      new base::DelegateSimpleThread(this, "wasapi_capture_thread");
134  capture_thread_->Start();
135
136  // Start streaming data between the endpoint buffer and the audio engine.
137  HRESULT hr = audio_client_->Start();
138  DLOG_IF(ERROR, FAILED(hr)) << "Failed to start input streaming.";
139
140  started_ = SUCCEEDED(hr);
141}
142
143void WASAPIAudioInputStream::Stop() {
144  DCHECK(CalledOnValidThread());
145  if (!started_)
146    return;
147
148  // Shut down the capture thread.
149  if (stop_capture_event_.IsValid()) {
150    SetEvent(stop_capture_event_.Get());
151  }
152
153  // Stop the input audio streaming.
154  HRESULT hr = audio_client_->Stop();
155  if (FAILED(hr)) {
156    LOG(ERROR) << "Failed to stop input streaming.";
157  }
158
159  // Wait until the thread completes and perform cleanup.
160  if (capture_thread_) {
161    SetEvent(stop_capture_event_.Get());
162    capture_thread_->Join();
163    capture_thread_ = NULL;
164  }
165
166  started_ = false;
167}
168
169void WASAPIAudioInputStream::Close() {
170  // It is valid to call Close() before calling open or Start().
171  // It is also valid to call Close() after Start() has been called.
172  Stop();
173  if (sink_) {
174    sink_->OnClose(this);
175    sink_ = NULL;
176  }
177
178  // Inform the audio manager that we have been closed. This will cause our
179  // destruction.
180  manager_->ReleaseInputStream(this);
181}
182
183double WASAPIAudioInputStream::GetMaxVolume() {
184  // Verify that Open() has been called succesfully, to ensure that an audio
185  // session exists and that an ISimpleAudioVolume interface has been created.
186  DLOG_IF(ERROR, !opened_) << "Open() has not been called successfully";
187  if (!opened_)
188    return 0.0;
189
190  // The effective volume value is always in the range 0.0 to 1.0, hence
191  // we can return a fixed value (=1.0) here.
192  return 1.0;
193}
194
195void WASAPIAudioInputStream::SetVolume(double volume) {
196  DVLOG(1) << "SetVolume(volume=" << volume << ")";
197  DCHECK(CalledOnValidThread());
198  DCHECK_GE(volume, 0.0);
199  DCHECK_LE(volume, 1.0);
200
201  DLOG_IF(ERROR, !opened_) << "Open() has not been called successfully";
202  if (!opened_)
203    return;
204
205  // Set a new master volume level. Valid volume levels are in the range
206  // 0.0 to 1.0. Ignore volume-change events.
207  HRESULT hr = simple_audio_volume_->SetMasterVolume(static_cast<float>(volume),
208      NULL);
209  DLOG_IF(WARNING, FAILED(hr)) << "Failed to set new input master volume.";
210
211  // Update the AGC volume level based on the last setting above. Note that,
212  // the volume-level resolution is not infinite and it is therefore not
213  // possible to assume that the volume provided as input parameter can be
214  // used directly. Instead, a new query to the audio hardware is required.
215  // This method does nothing if AGC is disabled.
216  UpdateAgcVolume();
217}
218
219double WASAPIAudioInputStream::GetVolume() {
220  DLOG_IF(ERROR, !opened_) << "Open() has not been called successfully";
221  if (!opened_)
222    return 0.0;
223
224  // Retrieve the current volume level. The value is in the range 0.0 to 1.0.
225  float level = 0.0f;
226  HRESULT hr = simple_audio_volume_->GetMasterVolume(&level);
227  DLOG_IF(WARNING, FAILED(hr)) << "Failed to get input master volume.";
228
229  return static_cast<double>(level);
230}
231
232// static
233int WASAPIAudioInputStream::HardwareSampleRate(
234    const std::string& device_id) {
235  base::win::ScopedCoMem<WAVEFORMATEX> audio_engine_mix_format;
236  HRESULT hr = GetMixFormat(device_id, &audio_engine_mix_format);
237  if (FAILED(hr))
238    return 0;
239
240  return static_cast<int>(audio_engine_mix_format->nSamplesPerSec);
241}
242
243// static
244uint32 WASAPIAudioInputStream::HardwareChannelCount(
245    const std::string& device_id) {
246  base::win::ScopedCoMem<WAVEFORMATEX> audio_engine_mix_format;
247  HRESULT hr = GetMixFormat(device_id, &audio_engine_mix_format);
248  if (FAILED(hr))
249    return 0;
250
251  return static_cast<uint32>(audio_engine_mix_format->nChannels);
252}
253
254// static
255HRESULT WASAPIAudioInputStream::GetMixFormat(const std::string& device_id,
256                                             WAVEFORMATEX** device_format) {
257  // It is assumed that this static method is called from a COM thread, i.e.,
258  // CoInitializeEx() is not called here to avoid STA/MTA conflicts.
259  ScopedComPtr<IMMDeviceEnumerator> enumerator;
260  HRESULT hr =  CoCreateInstance(__uuidof(MMDeviceEnumerator),
261                                 NULL,
262                                 CLSCTX_INPROC_SERVER,
263                                 __uuidof(IMMDeviceEnumerator),
264                                 enumerator.ReceiveVoid());
265  if (FAILED(hr))
266    return hr;
267
268  ScopedComPtr<IMMDevice> endpoint_device;
269  if (device_id == AudioManagerBase::kDefaultDeviceId) {
270    // Retrieve the default capture audio endpoint.
271    hr = enumerator->GetDefaultAudioEndpoint(eCapture, eConsole,
272                                             endpoint_device.Receive());
273  } else {
274    // Retrieve a capture endpoint device that is specified by an endpoint
275    // device-identification string.
276    hr = enumerator->GetDevice(UTF8ToUTF16(device_id).c_str(),
277                               endpoint_device.Receive());
278  }
279  if (FAILED(hr))
280    return hr;
281
282  ScopedComPtr<IAudioClient> audio_client;
283  hr = endpoint_device->Activate(__uuidof(IAudioClient),
284                                 CLSCTX_INPROC_SERVER,
285                                 NULL,
286                                 audio_client.ReceiveVoid());
287  return SUCCEEDED(hr) ? audio_client->GetMixFormat(device_format) : hr;
288}
289
290void WASAPIAudioInputStream::Run() {
291  ScopedCOMInitializer com_init(ScopedCOMInitializer::kMTA);
292
293  // Increase the thread priority.
294  capture_thread_->SetThreadPriority(base::kThreadPriority_RealtimeAudio);
295
296  // Enable MMCSS to ensure that this thread receives prioritized access to
297  // CPU resources.
298  DWORD task_index = 0;
299  HANDLE mm_task = avrt::AvSetMmThreadCharacteristics(L"Pro Audio",
300                                                      &task_index);
301  bool mmcss_is_ok =
302      (mm_task && avrt::AvSetMmThreadPriority(mm_task, AVRT_PRIORITY_CRITICAL));
303  if (!mmcss_is_ok) {
304    // Failed to enable MMCSS on this thread. It is not fatal but can lead
305    // to reduced QoS at high load.
306    DWORD err = GetLastError();
307    LOG(WARNING) << "Failed to enable MMCSS (error code=" << err << ").";
308  }
309
310  // Allocate a buffer with a size that enables us to take care of cases like:
311  // 1) The recorded buffer size is smaller, or does not match exactly with,
312  //    the selected packet size used in each callback.
313  // 2) The selected buffer size is larger than the recorded buffer size in
314  //    each event.
315  size_t buffer_frame_index = 0;
316  size_t capture_buffer_size = std::max(
317      2 * endpoint_buffer_size_frames_ * frame_size_,
318      2 * packet_size_frames_ * frame_size_);
319  scoped_array<uint8> capture_buffer(new uint8[capture_buffer_size]);
320
321  LARGE_INTEGER now_count;
322  bool recording = true;
323  bool error = false;
324  double volume = GetVolume();
325  HANDLE wait_array[2] = {stop_capture_event_, audio_samples_ready_event_};
326
327  while (recording && !error) {
328    HRESULT hr = S_FALSE;
329
330    // Wait for a close-down event or a new capture event.
331    DWORD wait_result = WaitForMultipleObjects(2, wait_array, FALSE, INFINITE);
332    switch (wait_result) {
333      case WAIT_FAILED:
334        error = true;
335        break;
336      case WAIT_OBJECT_0 + 0:
337        // |stop_capture_event_| has been set.
338        recording = false;
339        break;
340      case WAIT_OBJECT_0 + 1:
341        {
342          // |audio_samples_ready_event_| has been set.
343          BYTE* data_ptr = NULL;
344          UINT32 num_frames_to_read = 0;
345          DWORD flags = 0;
346          UINT64 device_position = 0;
347          UINT64 first_audio_frame_timestamp = 0;
348
349          // Retrieve the amount of data in the capture endpoint buffer,
350          // replace it with silence if required, create callbacks for each
351          // packet and store non-delivered data for the next event.
352          hr = audio_capture_client_->GetBuffer(&data_ptr,
353                                                &num_frames_to_read,
354                                                &flags,
355                                                &device_position,
356                                                &first_audio_frame_timestamp);
357          if (FAILED(hr)) {
358            DLOG(ERROR) << "Failed to get data from the capture buffer";
359            continue;
360          }
361
362          if (num_frames_to_read != 0) {
363            size_t pos = buffer_frame_index * frame_size_;
364            size_t num_bytes = num_frames_to_read * frame_size_;
365            DCHECK_GE(capture_buffer_size, pos + num_bytes);
366
367            if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
368              // Clear out the local buffer since silence is reported.
369              memset(&capture_buffer[pos], 0, num_bytes);
370            } else {
371              // Copy captured data from audio engine buffer to local buffer.
372              memcpy(&capture_buffer[pos], data_ptr, num_bytes);
373            }
374
375            buffer_frame_index += num_frames_to_read;
376          }
377
378          hr = audio_capture_client_->ReleaseBuffer(num_frames_to_read);
379          DLOG_IF(ERROR, FAILED(hr)) << "Failed to release capture buffer";
380
381          // Derive a delay estimate for the captured audio packet.
382          // The value contains two parts (A+B), where A is the delay of the
383          // first audio frame in the packet and B is the extra delay
384          // contained in any stored data. Unit is in audio frames.
385          QueryPerformanceCounter(&now_count);
386          double audio_delay_frames =
387              ((perf_count_to_100ns_units_ * now_count.QuadPart -
388                first_audio_frame_timestamp) / 10000.0) * ms_to_frame_count_ +
389                buffer_frame_index - num_frames_to_read;
390
391          // Update the AGC volume level once every second. Note that,
392          // |volume| is also updated each time SetVolume() is called
393          // through IPC by the render-side AGC.
394          QueryAgcVolume(&volume);
395
396          // Deliver captured data to the registered consumer using a packet
397          // size which was specified at construction.
398          uint32 delay_frames = static_cast<uint32>(audio_delay_frames + 0.5);
399          while (buffer_frame_index >= packet_size_frames_) {
400            uint8* audio_data =
401                reinterpret_cast<uint8*>(capture_buffer.get());
402
403            // Deliver data packet, delay estimation and volume level to
404            // the user.
405            sink_->OnData(this,
406                          audio_data,
407                          packet_size_bytes_,
408                          delay_frames * frame_size_,
409                          volume);
410
411            // Store parts of the recorded data which can't be delivered
412            // using the current packet size. The stored section will be used
413            // either in the next while-loop iteration or in the next
414            // capture event.
415            memmove(&capture_buffer[0],
416                    &capture_buffer[packet_size_bytes_],
417                    (buffer_frame_index - packet_size_frames_) * frame_size_);
418
419            buffer_frame_index -= packet_size_frames_;
420            delay_frames -= packet_size_frames_;
421          }
422        }
423        break;
424      default:
425        error = true;
426        break;
427    }
428  }
429
430  if (recording && error) {
431    // TODO(henrika): perhaps it worth improving the cleanup here by e.g.
432    // stopping the audio client, joining the thread etc.?
433    NOTREACHED() << "WASAPI capturing failed with error code "
434                 << GetLastError();
435  }
436
437  // Disable MMCSS.
438  if (mm_task && !avrt::AvRevertMmThreadCharacteristics(mm_task)) {
439    PLOG(WARNING) << "Failed to disable MMCSS";
440  }
441}
442
443void WASAPIAudioInputStream::HandleError(HRESULT err) {
444  NOTREACHED() << "Error code: " << err;
445  if (sink_)
446    sink_->OnError(this, static_cast<int>(err));
447}
448
449HRESULT WASAPIAudioInputStream::SetCaptureDevice() {
450  ScopedComPtr<IMMDeviceEnumerator> enumerator;
451  HRESULT hr =  CoCreateInstance(__uuidof(MMDeviceEnumerator),
452                                 NULL,
453                                 CLSCTX_INPROC_SERVER,
454                                 __uuidof(IMMDeviceEnumerator),
455                                 enumerator.ReceiveVoid());
456  if (SUCCEEDED(hr)) {
457    // Retrieve the IMMDevice by using the specified role or the specified
458    // unique endpoint device-identification string.
459    // TODO(henrika): possibly add support for the eCommunications as well.
460    if (device_id_ == AudioManagerBase::kDefaultDeviceId) {
461      // Retrieve the default capture audio endpoint for the specified role.
462      // Note that, in Windows Vista, the MMDevice API supports device roles
463      // but the system-supplied user interface programs do not.
464      hr = enumerator->GetDefaultAudioEndpoint(eCapture,
465                                               eConsole,
466                                               endpoint_device_.Receive());
467    } else {
468      // Retrieve a capture endpoint device that is specified by an endpoint
469      // device-identification string.
470      hr = enumerator->GetDevice(UTF8ToUTF16(device_id_).c_str(),
471                                 endpoint_device_.Receive());
472    }
473
474    if (FAILED(hr))
475      return hr;
476
477    // Verify that the audio endpoint device is active, i.e., the audio
478    // adapter that connects to the endpoint device is present and enabled.
479    DWORD state = DEVICE_STATE_DISABLED;
480    hr = endpoint_device_->GetState(&state);
481    if (SUCCEEDED(hr)) {
482      if (!(state & DEVICE_STATE_ACTIVE)) {
483        DLOG(ERROR) << "Selected capture device is not active.";
484        hr = E_ACCESSDENIED;
485      }
486    }
487  }
488
489  return hr;
490}
491
492HRESULT WASAPIAudioInputStream::ActivateCaptureDevice() {
493  // Creates and activates an IAudioClient COM object given the selected
494  // capture endpoint device.
495  HRESULT hr = endpoint_device_->Activate(__uuidof(IAudioClient),
496                                          CLSCTX_INPROC_SERVER,
497                                          NULL,
498                                          audio_client_.ReceiveVoid());
499  return hr;
500}
501
502HRESULT WASAPIAudioInputStream::GetAudioEngineStreamFormat() {
503  HRESULT hr = S_OK;
504#ifndef NDEBUG
505  // The GetMixFormat() method retrieves the stream format that the
506  // audio engine uses for its internal processing of shared-mode streams.
507  // The method always uses a WAVEFORMATEXTENSIBLE structure, instead
508  // of a stand-alone WAVEFORMATEX structure, to specify the format.
509  // An WAVEFORMATEXTENSIBLE structure can specify both the mapping of
510  // channels to speakers and the number of bits of precision in each sample.
511  base::win::ScopedCoMem<WAVEFORMATEXTENSIBLE> format_ex;
512  hr = audio_client_->GetMixFormat(
513      reinterpret_cast<WAVEFORMATEX**>(&format_ex));
514
515  // See http://msdn.microsoft.com/en-us/windows/hardware/gg463006#EFH
516  // for details on the WAVE file format.
517  WAVEFORMATEX format = format_ex->Format;
518  DVLOG(2) << "WAVEFORMATEX:";
519  DVLOG(2) << "  wFormatTags    : 0x" << std::hex << format.wFormatTag;
520  DVLOG(2) << "  nChannels      : " << format.nChannels;
521  DVLOG(2) << "  nSamplesPerSec : " << format.nSamplesPerSec;
522  DVLOG(2) << "  nAvgBytesPerSec: " << format.nAvgBytesPerSec;
523  DVLOG(2) << "  nBlockAlign    : " << format.nBlockAlign;
524  DVLOG(2) << "  wBitsPerSample : " << format.wBitsPerSample;
525  DVLOG(2) << "  cbSize         : " << format.cbSize;
526
527  DVLOG(2) << "WAVEFORMATEXTENSIBLE:";
528  DVLOG(2) << " wValidBitsPerSample: " <<
529      format_ex->Samples.wValidBitsPerSample;
530  DVLOG(2) << " dwChannelMask      : 0x" << std::hex <<
531      format_ex->dwChannelMask;
532  if (format_ex->SubFormat == KSDATAFORMAT_SUBTYPE_PCM)
533    DVLOG(2) << " SubFormat          : KSDATAFORMAT_SUBTYPE_PCM";
534  else if (format_ex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)
535    DVLOG(2) << " SubFormat          : KSDATAFORMAT_SUBTYPE_IEEE_FLOAT";
536  else if (format_ex->SubFormat == KSDATAFORMAT_SUBTYPE_WAVEFORMATEX)
537    DVLOG(2) << " SubFormat          : KSDATAFORMAT_SUBTYPE_WAVEFORMATEX";
538#endif
539  return hr;
540}
541
542bool WASAPIAudioInputStream::DesiredFormatIsSupported() {
543  // An application that uses WASAPI to manage shared-mode streams can rely
544  // on the audio engine to perform only limited format conversions. The audio
545  // engine can convert between a standard PCM sample size used by the
546  // application and the floating-point samples that the engine uses for its
547  // internal processing. However, the format for an application stream
548  // typically must have the same number of channels and the same sample
549  // rate as the stream format used by the device.
550  // Many audio devices support both PCM and non-PCM stream formats. However,
551  // the audio engine can mix only PCM streams.
552  base::win::ScopedCoMem<WAVEFORMATEX> closest_match;
553  HRESULT hr = audio_client_->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED,
554                                                &format_,
555                                                &closest_match);
556  DLOG_IF(ERROR, hr == S_FALSE) << "Format is not supported "
557                                << "but a closest match exists.";
558  return (hr == S_OK);
559}
560
561HRESULT WASAPIAudioInputStream::InitializeAudioEngine() {
562  // Initialize the audio stream between the client and the device.
563  // We connect indirectly through the audio engine by using shared mode
564  // and WASAPI is initialized in an event driven mode.
565  // Note that, |hnsBufferDuration| is set of 0, which ensures that the
566  // buffer is never smaller than the minimum buffer size needed to ensure
567  // that glitches do not occur between the periodic processing passes.
568  // This setting should lead to lowest possible latency.
569  HRESULT hr = audio_client_->Initialize(AUDCLNT_SHAREMODE_SHARED,
570                                         AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
571                                         AUDCLNT_STREAMFLAGS_NOPERSIST,
572                                         0,  // hnsBufferDuration
573                                         0,
574                                         &format_,
575                                         NULL);
576  if (FAILED(hr))
577    return hr;
578
579  // Retrieve the length of the endpoint buffer shared between the client
580  // and the audio engine. The buffer length determines the maximum amount
581  // of capture data that the audio engine can read from the endpoint buffer
582  // during a single processing pass.
583  // A typical value is 960 audio frames <=> 20ms @ 48kHz sample rate.
584  hr = audio_client_->GetBufferSize(&endpoint_buffer_size_frames_);
585  if (FAILED(hr))
586    return hr;
587  DVLOG(1) << "endpoint buffer size: " << endpoint_buffer_size_frames_
588           << " [frames]";
589
590#ifndef NDEBUG
591  // The period between processing passes by the audio engine is fixed for a
592  // particular audio endpoint device and represents the smallest processing
593  // quantum for the audio engine. This period plus the stream latency between
594  // the buffer and endpoint device represents the minimum possible latency
595  // that an audio application can achieve.
596  // TODO(henrika): possibly remove this section when all parts are ready.
597  REFERENCE_TIME device_period_shared_mode = 0;
598  REFERENCE_TIME device_period_exclusive_mode = 0;
599  HRESULT hr_dbg = audio_client_->GetDevicePeriod(
600      &device_period_shared_mode, &device_period_exclusive_mode);
601  if (SUCCEEDED(hr_dbg)) {
602    DVLOG(1) << "device period: "
603             << static_cast<double>(device_period_shared_mode / 10000.0)
604             << " [ms]";
605  }
606
607  REFERENCE_TIME latency = 0;
608  hr_dbg = audio_client_->GetStreamLatency(&latency);
609  if (SUCCEEDED(hr_dbg)) {
610    DVLOG(1) << "stream latency: " << static_cast<double>(latency / 10000.0)
611             << " [ms]";
612  }
613#endif
614
615  // Set the event handle that the audio engine will signal each time
616  // a buffer becomes ready to be processed by the client.
617  hr = audio_client_->SetEventHandle(audio_samples_ready_event_.Get());
618  if (FAILED(hr))
619    return hr;
620
621  // Get access to the IAudioCaptureClient interface. This interface
622  // enables us to read input data from the capture endpoint buffer.
623  hr = audio_client_->GetService(__uuidof(IAudioCaptureClient),
624                                 audio_capture_client_.ReceiveVoid());
625  if (FAILED(hr))
626    return hr;
627
628  // Obtain a reference to the ISimpleAudioVolume interface which enables
629  // us to control the master volume level of an audio session.
630  hr = audio_client_->GetService(__uuidof(ISimpleAudioVolume),
631                                 simple_audio_volume_.ReceiveVoid());
632  return hr;
633}
634
635}  // namespace media
636