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