audio_low_latency_output_win.cc revision cedac228d2dd51db4b79ea1e72c7f249408ee061
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_output_win.h" 6 7#include <Functiondiscoverykeys_devpkey.h> 8 9#include "base/command_line.h" 10#include "base/debug/trace_event.h" 11#include "base/logging.h" 12#include "base/memory/scoped_ptr.h" 13#include "base/metrics/histogram.h" 14#include "base/strings/utf_string_conversions.h" 15#include "base/win/scoped_propvariant.h" 16#include "media/audio/win/audio_manager_win.h" 17#include "media/audio/win/avrt_wrapper_win.h" 18#include "media/audio/win/core_audio_util_win.h" 19#include "media/base/limits.h" 20#include "media/base/media_switches.h" 21 22using base::win::ScopedComPtr; 23using base::win::ScopedCOMInitializer; 24using base::win::ScopedCoMem; 25 26namespace media { 27 28// static 29AUDCLNT_SHAREMODE WASAPIAudioOutputStream::GetShareMode() { 30 const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); 31 if (cmd_line->HasSwitch(switches::kEnableExclusiveAudio)) 32 return AUDCLNT_SHAREMODE_EXCLUSIVE; 33 return AUDCLNT_SHAREMODE_SHARED; 34} 35 36// static 37int WASAPIAudioOutputStream::HardwareSampleRate(const std::string& device_id) { 38 WAVEFORMATPCMEX format; 39 ScopedComPtr<IAudioClient> client; 40 if (device_id.empty()) { 41 client = CoreAudioUtil::CreateDefaultClient(eRender, eConsole); 42 } else { 43 ScopedComPtr<IMMDevice> device(CoreAudioUtil::CreateDevice(device_id)); 44 if (!device) 45 return 0; 46 client = CoreAudioUtil::CreateClient(device); 47 } 48 49 if (!client || FAILED(CoreAudioUtil::GetSharedModeMixFormat(client, &format))) 50 return 0; 51 52 return static_cast<int>(format.Format.nSamplesPerSec); 53} 54 55WASAPIAudioOutputStream::WASAPIAudioOutputStream(AudioManagerWin* manager, 56 const std::string& device_id, 57 const AudioParameters& params, 58 ERole device_role) 59 : creating_thread_id_(base::PlatformThread::CurrentId()), 60 manager_(manager), 61 format_(), 62 opened_(false), 63 volume_(1.0), 64 packet_size_frames_(0), 65 packet_size_bytes_(0), 66 endpoint_buffer_size_frames_(0), 67 device_id_(device_id), 68 device_role_(device_role), 69 share_mode_(GetShareMode()), 70 num_written_frames_(0), 71 source_(NULL), 72 audio_bus_(AudioBus::Create(params)) { 73 DCHECK(manager_); 74 VLOG(1) << "WASAPIAudioOutputStream::WASAPIAudioOutputStream()"; 75 VLOG_IF(1, share_mode_ == AUDCLNT_SHAREMODE_EXCLUSIVE) 76 << "Core Audio (WASAPI) EXCLUSIVE MODE is enabled."; 77 78 // Load the Avrt DLL if not already loaded. Required to support MMCSS. 79 bool avrt_init = avrt::Initialize(); 80 DCHECK(avrt_init) << "Failed to load the avrt.dll"; 81 82 // Set up the desired render format specified by the client. We use the 83 // WAVE_FORMAT_EXTENSIBLE structure to ensure that multiple channel ordering 84 // and high precision data can be supported. 85 86 // Begin with the WAVEFORMATEX structure that specifies the basic format. 87 WAVEFORMATEX* format = &format_.Format; 88 format->wFormatTag = WAVE_FORMAT_EXTENSIBLE; 89 format->nChannels = params.channels(); 90 format->nSamplesPerSec = params.sample_rate(); 91 format->wBitsPerSample = params.bits_per_sample(); 92 format->nBlockAlign = (format->wBitsPerSample / 8) * format->nChannels; 93 format->nAvgBytesPerSec = format->nSamplesPerSec * format->nBlockAlign; 94 format->cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); 95 96 // Add the parts which are unique to WAVE_FORMAT_EXTENSIBLE. 97 format_.Samples.wValidBitsPerSample = params.bits_per_sample(); 98 format_.dwChannelMask = CoreAudioUtil::GetChannelConfig(device_id, eRender); 99 format_.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; 100 101 // Store size (in different units) of audio packets which we expect to 102 // get from the audio endpoint device in each render event. 103 packet_size_frames_ = params.frames_per_buffer(); 104 packet_size_bytes_ = params.GetBytesPerBuffer(); 105 VLOG(1) << "Number of bytes per audio frame : " << format->nBlockAlign; 106 VLOG(1) << "Number of audio frames per packet: " << packet_size_frames_; 107 VLOG(1) << "Number of bytes per packet : " << packet_size_bytes_; 108 VLOG(1) << "Number of milliseconds per packet: " 109 << params.GetBufferDuration().InMillisecondsF(); 110 111 // All events are auto-reset events and non-signaled initially. 112 113 // Create the event which the audio engine will signal each time 114 // a buffer becomes ready to be processed by the client. 115 audio_samples_render_event_.Set(CreateEvent(NULL, FALSE, FALSE, NULL)); 116 DCHECK(audio_samples_render_event_.IsValid()); 117 118 // Create the event which will be set in Stop() when capturing shall stop. 119 stop_render_event_.Set(CreateEvent(NULL, FALSE, FALSE, NULL)); 120 DCHECK(stop_render_event_.IsValid()); 121} 122 123WASAPIAudioOutputStream::~WASAPIAudioOutputStream() {} 124 125bool WASAPIAudioOutputStream::Open() { 126 VLOG(1) << "WASAPIAudioOutputStream::Open()"; 127 DCHECK_EQ(GetCurrentThreadId(), creating_thread_id_); 128 if (opened_) 129 return true; 130 131 // Create an IAudioClient interface for the default rendering IMMDevice. 132 ScopedComPtr<IAudioClient> audio_client; 133 if (device_id_.empty() || 134 CoreAudioUtil::DeviceIsDefault(eRender, device_role_, device_id_)) { 135 audio_client = CoreAudioUtil::CreateDefaultClient(eRender, device_role_); 136 } else { 137 ScopedComPtr<IMMDevice> device(CoreAudioUtil::CreateDevice(device_id_)); 138 DLOG_IF(ERROR, !device) << "Failed to open device: " << device_id_; 139 if (device) 140 audio_client = CoreAudioUtil::CreateClient(device); 141 } 142 143 if (!audio_client) 144 return false; 145 146 // Extra sanity to ensure that the provided device format is still valid. 147 if (!CoreAudioUtil::IsFormatSupported(audio_client, 148 share_mode_, 149 &format_)) { 150 LOG(ERROR) << "Audio parameters are not supported."; 151 return false; 152 } 153 154 HRESULT hr = S_FALSE; 155 if (share_mode_ == AUDCLNT_SHAREMODE_SHARED) { 156 // Initialize the audio stream between the client and the device in shared 157 // mode and using event-driven buffer handling. 158 hr = CoreAudioUtil::SharedModeInitialize( 159 audio_client, &format_, audio_samples_render_event_.Get(), 160 &endpoint_buffer_size_frames_); 161 if (FAILED(hr)) 162 return false; 163 164 // We know from experience that the best possible callback sequence is 165 // achieved when the packet size (given by the native device period) 166 // is an even divisor of the endpoint buffer size. 167 // Examples: 48kHz => 960 % 480, 44.1kHz => 896 % 448 or 882 % 441. 168 if (endpoint_buffer_size_frames_ % packet_size_frames_ != 0) { 169 LOG(ERROR) 170 << "Bailing out due to non-perfect timing. Buffer size of " 171 << packet_size_frames_ << " is not an even divisor of " 172 << endpoint_buffer_size_frames_; 173 return false; 174 } 175 } else { 176 // TODO(henrika): break out to CoreAudioUtil::ExclusiveModeInitialize() 177 // when removing the enable-exclusive-audio flag. 178 hr = ExclusiveModeInitialization(audio_client, 179 audio_samples_render_event_.Get(), 180 &endpoint_buffer_size_frames_); 181 if (FAILED(hr)) 182 return false; 183 184 // The buffer scheme for exclusive mode streams is not designed for max 185 // flexibility. We only allow a "perfect match" between the packet size set 186 // by the user and the actual endpoint buffer size. 187 if (endpoint_buffer_size_frames_ != packet_size_frames_) { 188 LOG(ERROR) << "Bailing out due to non-perfect timing."; 189 return false; 190 } 191 } 192 193 // Create an IAudioRenderClient client for an initialized IAudioClient. 194 // The IAudioRenderClient interface enables us to write output data to 195 // a rendering endpoint buffer. 196 ScopedComPtr<IAudioRenderClient> audio_render_client = 197 CoreAudioUtil::CreateRenderClient(audio_client); 198 if (!audio_render_client) 199 return false; 200 201 // Store valid COM interfaces. 202 audio_client_ = audio_client; 203 audio_render_client_ = audio_render_client; 204 205 hr = audio_client_->GetService(__uuidof(IAudioClock), 206 audio_clock_.ReceiveVoid()); 207 if (FAILED(hr)) { 208 LOG(ERROR) << "Failed to get IAudioClock service."; 209 return false; 210 } 211 212 opened_ = true; 213 return true; 214} 215 216void WASAPIAudioOutputStream::Start(AudioSourceCallback* callback) { 217 VLOG(1) << "WASAPIAudioOutputStream::Start()"; 218 DCHECK_EQ(GetCurrentThreadId(), creating_thread_id_); 219 CHECK(callback); 220 CHECK(opened_); 221 222 if (render_thread_) { 223 CHECK_EQ(callback, source_); 224 return; 225 } 226 227 source_ = callback; 228 229 // Ensure that the endpoint buffer is prepared with silence. 230 if (share_mode_ == AUDCLNT_SHAREMODE_SHARED) { 231 if (!CoreAudioUtil::FillRenderEndpointBufferWithSilence( 232 audio_client_, audio_render_client_)) { 233 LOG(ERROR) << "Failed to prepare endpoint buffers with silence."; 234 callback->OnError(this); 235 return; 236 } 237 } 238 num_written_frames_ = endpoint_buffer_size_frames_; 239 240 // Create and start the thread that will drive the rendering by waiting for 241 // render events. 242 render_thread_.reset( 243 new base::DelegateSimpleThread(this, "wasapi_render_thread")); 244 render_thread_->Start(); 245 if (!render_thread_->HasBeenStarted()) { 246 LOG(ERROR) << "Failed to start WASAPI render thread."; 247 StopThread(); 248 callback->OnError(this); 249 return; 250 } 251 252 // Start streaming data between the endpoint buffer and the audio engine. 253 HRESULT hr = audio_client_->Start(); 254 if (FAILED(hr)) { 255 PLOG(ERROR) << "Failed to start output streaming: " << std::hex << hr; 256 StopThread(); 257 callback->OnError(this); 258 } 259} 260 261void WASAPIAudioOutputStream::Stop() { 262 VLOG(1) << "WASAPIAudioOutputStream::Stop()"; 263 DCHECK_EQ(GetCurrentThreadId(), creating_thread_id_); 264 if (!render_thread_) 265 return; 266 267 // Stop output audio streaming. 268 HRESULT hr = audio_client_->Stop(); 269 if (FAILED(hr)) { 270 PLOG(ERROR) << "Failed to stop output streaming: " << std::hex << hr; 271 source_->OnError(this); 272 } 273 274 // Make a local copy of |source_| since StopThread() will clear it. 275 AudioSourceCallback* callback = source_; 276 StopThread(); 277 278 // Flush all pending data and reset the audio clock stream position to 0. 279 hr = audio_client_->Reset(); 280 if (FAILED(hr)) { 281 PLOG(ERROR) << "Failed to reset streaming: " << std::hex << hr; 282 callback->OnError(this); 283 } 284 285 // Extra safety check to ensure that the buffers are cleared. 286 // If the buffers are not cleared correctly, the next call to Start() 287 // would fail with AUDCLNT_E_BUFFER_ERROR at IAudioRenderClient::GetBuffer(). 288 // This check is is only needed for shared-mode streams. 289 if (share_mode_ == AUDCLNT_SHAREMODE_SHARED) { 290 UINT32 num_queued_frames = 0; 291 audio_client_->GetCurrentPadding(&num_queued_frames); 292 DCHECK_EQ(0u, num_queued_frames); 293 } 294} 295 296void WASAPIAudioOutputStream::Close() { 297 VLOG(1) << "WASAPIAudioOutputStream::Close()"; 298 DCHECK_EQ(GetCurrentThreadId(), creating_thread_id_); 299 300 // It is valid to call Close() before calling open or Start(). 301 // It is also valid to call Close() after Start() has been called. 302 Stop(); 303 304 // Inform the audio manager that we have been closed. This will cause our 305 // destruction. 306 manager_->ReleaseOutputStream(this); 307} 308 309void WASAPIAudioOutputStream::SetVolume(double volume) { 310 VLOG(1) << "SetVolume(volume=" << volume << ")"; 311 float volume_float = static_cast<float>(volume); 312 if (volume_float < 0.0f || volume_float > 1.0f) { 313 return; 314 } 315 volume_ = volume_float; 316} 317 318void WASAPIAudioOutputStream::GetVolume(double* volume) { 319 VLOG(1) << "GetVolume()"; 320 *volume = static_cast<double>(volume_); 321} 322 323void WASAPIAudioOutputStream::Run() { 324 ScopedCOMInitializer com_init(ScopedCOMInitializer::kMTA); 325 326 // Increase the thread priority. 327 render_thread_->SetThreadPriority(base::kThreadPriority_RealtimeAudio); 328 329 // Enable MMCSS to ensure that this thread receives prioritized access to 330 // CPU resources. 331 DWORD task_index = 0; 332 HANDLE mm_task = avrt::AvSetMmThreadCharacteristics(L"Pro Audio", 333 &task_index); 334 bool mmcss_is_ok = 335 (mm_task && avrt::AvSetMmThreadPriority(mm_task, AVRT_PRIORITY_CRITICAL)); 336 if (!mmcss_is_ok) { 337 // Failed to enable MMCSS on this thread. It is not fatal but can lead 338 // to reduced QoS at high load. 339 DWORD err = GetLastError(); 340 LOG(WARNING) << "Failed to enable MMCSS (error code=" << err << ")."; 341 } 342 343 HRESULT hr = S_FALSE; 344 345 bool playing = true; 346 bool error = false; 347 HANDLE wait_array[] = { stop_render_event_, 348 audio_samples_render_event_ }; 349 UINT64 device_frequency = 0; 350 351 // The device frequency is the frequency generated by the hardware clock in 352 // the audio device. The GetFrequency() method reports a constant frequency. 353 hr = audio_clock_->GetFrequency(&device_frequency); 354 error = FAILED(hr); 355 PLOG_IF(ERROR, error) << "Failed to acquire IAudioClock interface: " 356 << std::hex << hr; 357 358 // Keep rendering audio until the stop event or the stream-switch event 359 // is signaled. An error event can also break the main thread loop. 360 while (playing && !error) { 361 // Wait for a close-down event, stream-switch event or a new render event. 362 DWORD wait_result = WaitForMultipleObjects(arraysize(wait_array), 363 wait_array, 364 FALSE, 365 INFINITE); 366 367 switch (wait_result) { 368 case WAIT_OBJECT_0 + 0: 369 // |stop_render_event_| has been set. 370 playing = false; 371 break; 372 case WAIT_OBJECT_0 + 1: 373 // |audio_samples_render_event_| has been set. 374 error = !RenderAudioFromSource(device_frequency); 375 break; 376 default: 377 error = true; 378 break; 379 } 380 } 381 382 if (playing && error) { 383 // Stop audio rendering since something has gone wrong in our main thread 384 // loop. Note that, we are still in a "started" state, hence a Stop() call 385 // is required to join the thread properly. 386 audio_client_->Stop(); 387 PLOG(ERROR) << "WASAPI rendering failed."; 388 } 389 390 // Disable MMCSS. 391 if (mm_task && !avrt::AvRevertMmThreadCharacteristics(mm_task)) { 392 PLOG(WARNING) << "Failed to disable MMCSS"; 393 } 394} 395 396bool WASAPIAudioOutputStream::RenderAudioFromSource(UINT64 device_frequency) { 397 TRACE_EVENT0("audio", "RenderAudioFromSource"); 398 399 HRESULT hr = S_FALSE; 400 UINT32 num_queued_frames = 0; 401 uint8* audio_data = NULL; 402 403 // Contains how much new data we can write to the buffer without 404 // the risk of overwriting previously written data that the audio 405 // engine has not yet read from the buffer. 406 size_t num_available_frames = 0; 407 408 if (share_mode_ == AUDCLNT_SHAREMODE_SHARED) { 409 // Get the padding value which represents the amount of rendering 410 // data that is queued up to play in the endpoint buffer. 411 hr = audio_client_->GetCurrentPadding(&num_queued_frames); 412 num_available_frames = 413 endpoint_buffer_size_frames_ - num_queued_frames; 414 if (FAILED(hr)) { 415 DLOG(ERROR) << "Failed to retrieve amount of available space: " 416 << std::hex << hr; 417 return false; 418 } 419 } else { 420 // While the stream is running, the system alternately sends one 421 // buffer or the other to the client. This form of double buffering 422 // is referred to as "ping-ponging". Each time the client receives 423 // a buffer from the system (triggers this event) the client must 424 // process the entire buffer. Calls to the GetCurrentPadding method 425 // are unnecessary because the packet size must always equal the 426 // buffer size. In contrast to the shared mode buffering scheme, 427 // the latency for an event-driven, exclusive-mode stream depends 428 // directly on the buffer size. 429 num_available_frames = endpoint_buffer_size_frames_; 430 } 431 432 // Check if there is enough available space to fit the packet size 433 // specified by the client. 434 if (num_available_frames < packet_size_frames_) 435 return true; 436 437 DLOG_IF(ERROR, num_available_frames % packet_size_frames_ != 0) 438 << "Non-perfect timing detected (num_available_frames=" 439 << num_available_frames << ", packet_size_frames=" 440 << packet_size_frames_ << ")"; 441 442 // Derive the number of packets we need to get from the client to 443 // fill up the available area in the endpoint buffer. 444 // |num_packets| will always be one for exclusive-mode streams and 445 // will be one in most cases for shared mode streams as well. 446 // However, we have found that two packets can sometimes be 447 // required. 448 size_t num_packets = (num_available_frames / packet_size_frames_); 449 450 for (size_t n = 0; n < num_packets; ++n) { 451 // Grab all available space in the rendering endpoint buffer 452 // into which the client can write a data packet. 453 hr = audio_render_client_->GetBuffer(packet_size_frames_, 454 &audio_data); 455 if (FAILED(hr)) { 456 DLOG(ERROR) << "Failed to use rendering audio buffer: " 457 << std::hex << hr; 458 return false; 459 } 460 461 // Derive the audio delay which corresponds to the delay between 462 // a render event and the time when the first audio sample in a 463 // packet is played out through the speaker. This delay value 464 // can typically be utilized by an acoustic echo-control (AEC) 465 // unit at the render side. 466 UINT64 position = 0; 467 int audio_delay_bytes = 0; 468 hr = audio_clock_->GetPosition(&position, NULL); 469 if (SUCCEEDED(hr)) { 470 // Stream position of the sample that is currently playing 471 // through the speaker. 472 double pos_sample_playing_frames = format_.Format.nSamplesPerSec * 473 (static_cast<double>(position) / device_frequency); 474 475 // Stream position of the last sample written to the endpoint 476 // buffer. Note that, the packet we are about to receive in 477 // the upcoming callback is also included. 478 size_t pos_last_sample_written_frames = 479 num_written_frames_ + packet_size_frames_; 480 481 // Derive the actual delay value which will be fed to the 482 // render client using the OnMoreData() callback. 483 audio_delay_bytes = (pos_last_sample_written_frames - 484 pos_sample_playing_frames) * format_.Format.nBlockAlign; 485 } 486 487 // Read a data packet from the registered client source and 488 // deliver a delay estimate in the same callback to the client. 489 // A time stamp is also stored in the AudioBuffersState. This 490 // time stamp can be used at the client side to compensate for 491 // the delay between the usage of the delay value and the time 492 // of generation. 493 494 int frames_filled = source_->OnMoreData( 495 audio_bus_.get(), AudioBuffersState(0, audio_delay_bytes)); 496 uint32 num_filled_bytes = frames_filled * format_.Format.nBlockAlign; 497 DCHECK_LE(num_filled_bytes, packet_size_bytes_); 498 499 // Note: If this ever changes to output raw float the data must be 500 // clipped and sanitized since it may come from an untrusted 501 // source such as NaCl. 502 const int bytes_per_sample = format_.Format.wBitsPerSample >> 3; 503 audio_bus_->Scale(volume_); 504 audio_bus_->ToInterleaved( 505 frames_filled, bytes_per_sample, audio_data); 506 507 508 // Release the buffer space acquired in the GetBuffer() call. 509 // Render silence if we were not able to fill up the buffer totally. 510 DWORD flags = (num_filled_bytes < packet_size_bytes_) ? 511 AUDCLNT_BUFFERFLAGS_SILENT : 0; 512 audio_render_client_->ReleaseBuffer(packet_size_frames_, flags); 513 514 num_written_frames_ += packet_size_frames_; 515 } 516 517 return true; 518} 519 520HRESULT WASAPIAudioOutputStream::ExclusiveModeInitialization( 521 IAudioClient* client, HANDLE event_handle, uint32* endpoint_buffer_size) { 522 DCHECK_EQ(share_mode_, AUDCLNT_SHAREMODE_EXCLUSIVE); 523 524 float f = (1000.0 * packet_size_frames_) / format_.Format.nSamplesPerSec; 525 REFERENCE_TIME requested_buffer_duration = 526 static_cast<REFERENCE_TIME>(f * 10000.0 + 0.5); 527 528 DWORD stream_flags = AUDCLNT_STREAMFLAGS_NOPERSIST; 529 bool use_event = (event_handle != NULL && 530 event_handle != INVALID_HANDLE_VALUE); 531 if (use_event) 532 stream_flags |= AUDCLNT_STREAMFLAGS_EVENTCALLBACK; 533 VLOG(2) << "stream_flags: 0x" << std::hex << stream_flags; 534 535 // Initialize the audio stream between the client and the device. 536 // For an exclusive-mode stream that uses event-driven buffering, the 537 // caller must specify nonzero values for hnsPeriodicity and 538 // hnsBufferDuration, and the values of these two parameters must be equal. 539 // The Initialize method allocates two buffers for the stream. Each buffer 540 // is equal in duration to the value of the hnsBufferDuration parameter. 541 // Following the Initialize call for a rendering stream, the caller should 542 // fill the first of the two buffers before starting the stream. 543 HRESULT hr = S_FALSE; 544 hr = client->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, 545 stream_flags, 546 requested_buffer_duration, 547 requested_buffer_duration, 548 reinterpret_cast<WAVEFORMATEX*>(&format_), 549 NULL); 550 if (FAILED(hr)) { 551 if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) { 552 LOG(ERROR) << "AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED"; 553 554 UINT32 aligned_buffer_size = 0; 555 client->GetBufferSize(&aligned_buffer_size); 556 VLOG(1) << "Use aligned buffer size instead: " << aligned_buffer_size; 557 558 // Calculate new aligned periodicity. Each unit of reference time 559 // is 100 nanoseconds. 560 REFERENCE_TIME aligned_buffer_duration = static_cast<REFERENCE_TIME>( 561 (10000000.0 * aligned_buffer_size / format_.Format.nSamplesPerSec) 562 + 0.5); 563 564 // It is possible to re-activate and re-initialize the audio client 565 // at this stage but we bail out with an error code instead and 566 // combine it with a log message which informs about the suggested 567 // aligned buffer size which should be used instead. 568 VLOG(1) << "aligned_buffer_duration: " 569 << static_cast<double>(aligned_buffer_duration / 10000.0) 570 << " [ms]"; 571 } else if (hr == AUDCLNT_E_INVALID_DEVICE_PERIOD) { 572 // We will get this error if we try to use a smaller buffer size than 573 // the minimum supported size (usually ~3ms on Windows 7). 574 LOG(ERROR) << "AUDCLNT_E_INVALID_DEVICE_PERIOD"; 575 } 576 return hr; 577 } 578 579 if (use_event) { 580 hr = client->SetEventHandle(event_handle); 581 if (FAILED(hr)) { 582 VLOG(1) << "IAudioClient::SetEventHandle: " << std::hex << hr; 583 return hr; 584 } 585 } 586 587 UINT32 buffer_size_in_frames = 0; 588 hr = client->GetBufferSize(&buffer_size_in_frames); 589 if (FAILED(hr)) { 590 VLOG(1) << "IAudioClient::GetBufferSize: " << std::hex << hr; 591 return hr; 592 } 593 594 *endpoint_buffer_size = buffer_size_in_frames; 595 VLOG(2) << "endpoint buffer size: " << buffer_size_in_frames; 596 return hr; 597} 598 599void WASAPIAudioOutputStream::StopThread() { 600 if (render_thread_ ) { 601 if (render_thread_->HasBeenStarted()) { 602 // Wait until the thread completes and perform cleanup. 603 SetEvent(stop_render_event_.Get()); 604 render_thread_->Join(); 605 } 606 607 render_thread_.reset(); 608 609 // Ensure that we don't quit the main thread loop immediately next 610 // time Start() is called. 611 ResetEvent(stop_render_event_.Get()); 612 } 613 614 source_ = NULL; 615} 616 617} // namespace media 618