Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(589)

Side by Side Diff: media/audio/win/audio_low_latency_output_win.cc

Issue 10575017: Adding experimental exclusive-mode streaming to WASAPIAudioOutputStream (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: nit Created 8 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "media/audio/win/audio_low_latency_output_win.h" 5 #include "media/audio/win/audio_low_latency_output_win.h"
6 6
7 #include <Functiondiscoverykeys_devpkey.h> 7 #include <Functiondiscoverykeys_devpkey.h>
8 8
9 #include "base/command_line.h"
9 #include "base/logging.h" 10 #include "base/logging.h"
10 #include "base/memory/scoped_ptr.h" 11 #include "base/memory/scoped_ptr.h"
11 #include "base/utf_string_conversions.h" 12 #include "base/utf_string_conversions.h"
12 #include "media/audio/audio_util.h" 13 #include "media/audio/audio_util.h"
13 #include "media/audio/win/audio_manager_win.h" 14 #include "media/audio/win/audio_manager_win.h"
14 #include "media/audio/win/avrt_wrapper_win.h" 15 #include "media/audio/win/avrt_wrapper_win.h"
16 #include "media/base/media_switches.h"
15 17
16 using base::win::ScopedComPtr; 18 using base::win::ScopedComPtr;
17 using base::win::ScopedCOMInitializer; 19 using base::win::ScopedCOMInitializer;
18 20
19 namespace media { 21 namespace media {
20 22
23 AUDCLNT_SHAREMODE GetShareModeImpl() {
24 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
25 if (cmd_line->HasSwitch(switches::kEnableExclusiveMode))
26 return AUDCLNT_SHAREMODE_EXCLUSIVE;
27 return AUDCLNT_SHAREMODE_SHARED;
28 }
29
30 // static
31 AUDCLNT_SHAREMODE WASAPIAudioOutputStream::GetShareMode() {
32 static const AUDCLNT_SHAREMODE kShareMode = GetShareModeImpl();
scherkus (not reviewing) 2012/07/25 23:44:44 don't worry about being crafty here with caching t
henrika (OOO until Aug 14) 2012/07/26 08:31:11 Might be overkill; hope it is OK to keep anyhow. D
33 return kShareMode;
34 }
35
21 WASAPIAudioOutputStream::WASAPIAudioOutputStream(AudioManagerWin* manager, 36 WASAPIAudioOutputStream::WASAPIAudioOutputStream(AudioManagerWin* manager,
22 const AudioParameters& params, 37 const AudioParameters& params,
23 ERole device_role) 38 ERole device_role)
24 : com_init_(ScopedCOMInitializer::kMTA), 39 : com_init_(ScopedCOMInitializer::kMTA),
25 creating_thread_id_(base::PlatformThread::CurrentId()), 40 creating_thread_id_(base::PlatformThread::CurrentId()),
26 manager_(manager), 41 manager_(manager),
27 render_thread_(NULL), 42 render_thread_(NULL),
28 opened_(false), 43 opened_(false),
29 started_(false), 44 started_(false),
30 restart_rendering_mode_(false), 45 restart_rendering_mode_(false),
31 volume_(1.0), 46 volume_(1.0),
32 endpoint_buffer_size_frames_(0), 47 endpoint_buffer_size_frames_(0),
33 device_role_(device_role), 48 device_role_(device_role),
49 share_mode_(GetShareMode()),
34 num_written_frames_(0), 50 num_written_frames_(0),
35 source_(NULL) { 51 source_(NULL) {
36 CHECK(com_init_.succeeded()); 52 CHECK(com_init_.succeeded());
37 DCHECK(manager_); 53 DCHECK(manager_);
38 54
39 // Load the Avrt DLL if not already loaded. Required to support MMCSS. 55 // Load the Avrt DLL if not already loaded. Required to support MMCSS.
40 bool avrt_init = avrt::Initialize(); 56 bool avrt_init = avrt::Initialize();
41 DCHECK(avrt_init) << "Failed to load the avrt.dll"; 57 DCHECK(avrt_init) << "Failed to load the avrt.dll";
42 58
59 if (AUDCLNT_SHAREMODE_EXCLUSIVE == share_mode()) {
scherkus (not reviewing) 2012/07/25 23:44:44 but constants on the right hand side of comparison
henrika (OOO until Aug 14) 2012/07/26 08:31:11 Done.
60 VLOG(1) << ">> Note that EXCLUSIVE MODE is enabled <<";
61 }
62
43 // Set up the desired render format specified by the client. 63 // Set up the desired render format specified by the client.
44 format_.nSamplesPerSec = params.sample_rate(); 64 format_.nSamplesPerSec = params.sample_rate();
45 format_.wFormatTag = WAVE_FORMAT_PCM; 65 format_.wFormatTag = WAVE_FORMAT_PCM;
46 format_.wBitsPerSample = params.bits_per_sample(); 66 format_.wBitsPerSample = params.bits_per_sample();
47 format_.nChannels = params.channels(); 67 format_.nChannels = params.channels();
48 format_.nBlockAlign = (format_.wBitsPerSample / 8) * format_.nChannels; 68 format_.nBlockAlign = (format_.wBitsPerSample / 8) * format_.nChannels;
49 format_.nAvgBytesPerSec = format_.nSamplesPerSec * format_.nBlockAlign; 69 format_.nAvgBytesPerSec = format_.nSamplesPerSec * format_.nBlockAlign;
50 format_.cbSize = 0; 70 format_.cbSize = 0;
51 71
52 // Size in bytes of each audio frame. 72 // Size in bytes of each audio frame.
(...skipping 27 matching lines...) Expand all
80 WASAPIAudioOutputStream::~WASAPIAudioOutputStream() {} 100 WASAPIAudioOutputStream::~WASAPIAudioOutputStream() {}
81 101
82 bool WASAPIAudioOutputStream::Open() { 102 bool WASAPIAudioOutputStream::Open() {
83 DCHECK_EQ(GetCurrentThreadId(), creating_thread_id_); 103 DCHECK_EQ(GetCurrentThreadId(), creating_thread_id_);
84 if (opened_) 104 if (opened_)
85 return true; 105 return true;
86 106
87 // Create an IMMDeviceEnumerator interface and obtain a reference to 107 // Create an IMMDeviceEnumerator interface and obtain a reference to
88 // the IMMDevice interface of the default rendering device with the 108 // the IMMDevice interface of the default rendering device with the
89 // specified role. 109 // specified role.
90 HRESULT hr = SetRenderDevice(device_role_); 110 HRESULT hr = SetRenderDevice();
91 if (FAILED(hr)) { 111 if (FAILED(hr)) {
92 return false; 112 return false;
93 } 113 }
94 114
95 // Obtain an IAudioClient interface which enables us to create and initialize 115 // Obtain an IAudioClient interface which enables us to create and initialize
96 // an audio stream between an audio application and the audio engine. 116 // an audio stream between an audio application and the audio engine.
97 hr = ActivateRenderDevice(); 117 hr = ActivateRenderDevice();
98 if (FAILED(hr)) { 118 if (FAILED(hr)) {
99 return false; 119 return false;
100 } 120 }
101 121
102 // Retrieve the stream format which the audio engine uses for its internal 122 // Retrieve the stream format which the audio engine uses for its internal
103 // processing/mixing of shared-mode streams. 123 // processing/mixing of shared-mode streams. The result of this method is
124 // ignored for shared mode streams.
104 hr = GetAudioEngineStreamFormat(); 125 hr = GetAudioEngineStreamFormat();
105 if (FAILED(hr)) { 126 if (FAILED(hr)) {
106 return false; 127 return false;
107 } 128 }
108 129
109 // Verify that the selected audio endpoint supports the specified format 130 // Verify that the selected audio endpoint supports the specified format
110 // set during construction. 131 // set during construction.
132 // In exclusive mode, the client can choose to open the stream in any audio
133 // format that the endpoint device supports. In shared mode, the client must
134 // open the stream in the mix format that is currently in use by the audio
135 // engine (or a format that is similar to the mix format). The audio engine's
136 // input streams and the output mix from the engine are all in this format.
111 if (!DesiredFormatIsSupported()) { 137 if (!DesiredFormatIsSupported()) {
112 return false; 138 return false;
113 } 139 }
114 140
115 // Initialize the audio stream between the client and the device using 141 // Initialize the audio stream between the client and the device using
116 // shared mode and a lowest possible glitch-free latency. 142 // shared or exclusive mode and a lowest possible glitch-free latency.
143 // We will enter different code paths depending on the specified share mode.
117 hr = InitializeAudioEngine(); 144 hr = InitializeAudioEngine();
118 if (FAILED(hr)) { 145 if (FAILED(hr)) {
119 return false; 146 return false;
120 } 147 }
121 148
122 // Register this client as an IMMNotificationClient implementation. 149 // Register this client as an IMMNotificationClient implementation.
123 // Only OnDefaultDeviceChanged() and OnDeviceStateChanged() and are 150 // Only OnDefaultDeviceChanged() and OnDeviceStateChanged() and are
124 // non-trivial. 151 // non-trivial.
125 hr = device_enumerator_->RegisterEndpointNotificationCallback(this); 152 hr = device_enumerator_->RegisterEndpointNotificationCallback(this);
126 153
(...skipping 95 matching lines...) Expand 10 before | Expand all | Expand 10 after
222 // Flush all pending data and reset the audio clock stream position to 0. 249 // Flush all pending data and reset the audio clock stream position to 0.
223 hr = audio_client_->Reset(); 250 hr = audio_client_->Reset();
224 if (FAILED(hr)) { 251 if (FAILED(hr)) {
225 DLOG_IF(ERROR, hr != AUDCLNT_E_NOT_INITIALIZED) 252 DLOG_IF(ERROR, hr != AUDCLNT_E_NOT_INITIALIZED)
226 << "Failed to reset streaming: " << std::hex << hr; 253 << "Failed to reset streaming: " << std::hex << hr;
227 } 254 }
228 255
229 // Extra safety check to ensure that the buffers are cleared. 256 // Extra safety check to ensure that the buffers are cleared.
230 // If the buffers are not cleared correctly, the next call to Start() 257 // If the buffers are not cleared correctly, the next call to Start()
231 // would fail with AUDCLNT_E_BUFFER_ERROR at IAudioRenderClient::GetBuffer(). 258 // would fail with AUDCLNT_E_BUFFER_ERROR at IAudioRenderClient::GetBuffer().
232 UINT32 num_queued_frames = 0; 259 // This check is is only needed for shared-mode streams.
233 audio_client_->GetCurrentPadding(&num_queued_frames); 260 if (share_mode() == AUDCLNT_SHAREMODE_SHARED) {
234 DCHECK_EQ(0u, num_queued_frames); 261 UINT32 num_queued_frames = 0;
262 audio_client_->GetCurrentPadding(&num_queued_frames);
263 DCHECK_EQ(0u, num_queued_frames);
264 }
235 265
236 // Ensure that we don't quit the main thread loop immediately next 266 // Ensure that we don't quit the main thread loop immediately next
237 // time Start() is called. 267 // time Start() is called.
238 ResetEvent(stop_render_event_.Get()); 268 ResetEvent(stop_render_event_.Get());
239 269
240 started_ = false; 270 started_ = false;
241 } 271 }
242 272
243 void WASAPIAudioOutputStream::Close() { 273 void WASAPIAudioOutputStream::Close() {
244 DCHECK_EQ(GetCurrentThreadId(), creating_thread_id_); 274 DCHECK_EQ(GetCurrentThreadId(), creating_thread_id_);
(...skipping 26 matching lines...) Expand all
271 301
272 void WASAPIAudioOutputStream::GetVolume(double* volume) { 302 void WASAPIAudioOutputStream::GetVolume(double* volume) {
273 DVLOG(1) << "GetVolume()"; 303 DVLOG(1) << "GetVolume()";
274 *volume = static_cast<double>(volume_); 304 *volume = static_cast<double>(volume_);
275 } 305 }
276 306
277 // static 307 // static
278 int WASAPIAudioOutputStream::HardwareSampleRate(ERole device_role) { 308 int WASAPIAudioOutputStream::HardwareSampleRate(ERole device_role) {
279 // It is assumed that this static method is called from a COM thread, i.e., 309 // It is assumed that this static method is called from a COM thread, i.e.,
280 // CoInitializeEx() is not called here again to avoid STA/MTA conflicts. 310 // CoInitializeEx() is not called here again to avoid STA/MTA conflicts.
311 // Note that, calling this function only makes sense for shared mode streams,
312 // since if the device will be opened in exclusive mode, then the application
313 // specified format is used instead.
281 ScopedComPtr<IMMDeviceEnumerator> enumerator; 314 ScopedComPtr<IMMDeviceEnumerator> enumerator;
282 HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), 315 HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),
283 NULL, 316 NULL,
284 CLSCTX_INPROC_SERVER, 317 CLSCTX_INPROC_SERVER,
285 __uuidof(IMMDeviceEnumerator), 318 __uuidof(IMMDeviceEnumerator),
286 enumerator.ReceiveVoid()); 319 enumerator.ReceiveVoid());
287 if (FAILED(hr)) { 320 if (FAILED(hr)) {
288 NOTREACHED() << "error code: " << std::hex << hr; 321 NOTREACHED() << "error code: " << std::hex << hr;
289 return 0.0; 322 return 0.0;
290 } 323 }
(...skipping 13 matching lines...) Expand all
304 ScopedComPtr<IAudioClient> audio_client; 337 ScopedComPtr<IAudioClient> audio_client;
305 hr = endpoint_device->Activate(__uuidof(IAudioClient), 338 hr = endpoint_device->Activate(__uuidof(IAudioClient),
306 CLSCTX_INPROC_SERVER, 339 CLSCTX_INPROC_SERVER,
307 NULL, 340 NULL,
308 audio_client.ReceiveVoid()); 341 audio_client.ReceiveVoid());
309 if (FAILED(hr)) { 342 if (FAILED(hr)) {
310 NOTREACHED() << "error code: " << std::hex << hr; 343 NOTREACHED() << "error code: " << std::hex << hr;
311 return 0.0; 344 return 0.0;
312 } 345 }
313 346
347 // Retrieve the stream format that the audio engine uses for its internal
348 // processing of shared-mode streams.
314 base::win::ScopedCoMem<WAVEFORMATEX> audio_engine_mix_format; 349 base::win::ScopedCoMem<WAVEFORMATEX> audio_engine_mix_format;
315 hr = audio_client->GetMixFormat(&audio_engine_mix_format); 350 hr = audio_client->GetMixFormat(&audio_engine_mix_format);
316 if (FAILED(hr)) { 351 if (FAILED(hr)) {
317 NOTREACHED() << "error code: " << std::hex << hr; 352 NOTREACHED() << "error code: " << std::hex << hr;
318 return 0.0; 353 return 0.0;
319 } 354 }
320 355
321 return static_cast<int>(audio_engine_mix_format->nSamplesPerSec); 356 return static_cast<int>(audio_engine_mix_format->nSamplesPerSec);
322 } 357 }
323 358
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
387 playing = false; 422 playing = false;
388 error = true; 423 error = true;
389 } 424 }
390 break; 425 break;
391 case WAIT_OBJECT_0 + 2: 426 case WAIT_OBJECT_0 + 2:
392 { 427 {
393 // |audio_samples_render_event_| has been set. 428 // |audio_samples_render_event_| has been set.
394 UINT32 num_queued_frames = 0; 429 UINT32 num_queued_frames = 0;
395 uint8* audio_data = NULL; 430 uint8* audio_data = NULL;
396 431
397 // Get the padding value which represents the amount of rendering 432 // Contains how much new data we can write to the buffer without
398 // data that is queued up to play in the endpoint buffer.
399 hr = audio_client_->GetCurrentPadding(&num_queued_frames);
400
401 // Determine how much new data we can write to the buffer without
402 // the risk of overwriting previously written data that the audio 433 // the risk of overwriting previously written data that the audio
403 // engine has not yet read from the buffer. 434 // engine has not yet read from the buffer.
404 size_t num_available_frames = 435 size_t num_available_frames = 0;
405 endpoint_buffer_size_frames_ - num_queued_frames; 436
437 if (share_mode() == AUDCLNT_SHAREMODE_SHARED) {
438 // Get the padding value which represents the amount of rendering
439 // data that is queued up to play in the endpoint buffer.
440 hr = audio_client_->GetCurrentPadding(&num_queued_frames);
441 num_available_frames =
442 endpoint_buffer_size_frames_ - num_queued_frames;
443 } else {
444 // While the stream is running, the system alternately sends one
445 // buffer or the other to the client. This form of double buffering
446 // is referred to as "ping-ponging". Each time the client receives
447 // a buffer from the system (triggers this event) the client must
448 // process the entire buffer. Calls to the GetCurrentPadding method
449 // are unnecessary because the packet size must always equal the
450 // buffer size. In contrast to the shared mode buffering scheme,
451 // the latency for an event-driven, exclusive-mode stream depends
452 // directly on the buffer size.
453 num_available_frames = endpoint_buffer_size_frames_;
454 }
406 455
407 // Check if there is enough available space to fit the packet size 456 // Check if there is enough available space to fit the packet size
408 // specified by the client. 457 // specified by the client.
409 if (FAILED(hr) || (num_available_frames < packet_size_frames_)) 458 if (FAILED(hr) || (num_available_frames < packet_size_frames_))
410 continue; 459 continue;
411 460
412 // Derive the number of packets we need get from the client to 461 // Derive the number of packets we need get from the client to
413 // fill up the available area in the endpoint buffer. 462 // fill up the available area in the endpoint buffer.
463 // |num_packets| will always be one for exclusive-mode streams.
414 size_t num_packets = (num_available_frames / packet_size_frames_); 464 size_t num_packets = (num_available_frames / packet_size_frames_);
415 465
416 // Get data from the client/source. 466 // Get data from the client/source.
417 for (size_t n = 0; n < num_packets; ++n) { 467 for (size_t n = 0; n < num_packets; ++n) {
418 // Grab all available space in the rendering endpoint buffer 468 // Grab all available space in the rendering endpoint buffer
419 // into which the client can write a data packet. 469 // into which the client can write a data packet.
420 hr = audio_render_client_->GetBuffer(packet_size_frames_, 470 hr = audio_render_client_->GetBuffer(packet_size_frames_,
421 &audio_data); 471 &audio_data);
422 if (FAILED(hr)) { 472 if (FAILED(hr)) {
423 DLOG(ERROR) << "Failed to use rendering audio buffer: " 473 DLOG(ERROR) << "Failed to use rendering audio buffer: "
(...skipping 80 matching lines...) Expand 10 before | Expand all | Expand 10 after
504 PLOG(WARNING) << "Failed to disable MMCSS"; 554 PLOG(WARNING) << "Failed to disable MMCSS";
505 } 555 }
506 } 556 }
507 557
508 void WASAPIAudioOutputStream::HandleError(HRESULT err) { 558 void WASAPIAudioOutputStream::HandleError(HRESULT err) {
509 NOTREACHED() << "Error code: " << std::hex << err; 559 NOTREACHED() << "Error code: " << std::hex << err;
510 if (source_) 560 if (source_)
511 source_->OnError(this, static_cast<int>(err)); 561 source_->OnError(this, static_cast<int>(err));
512 } 562 }
513 563
514 HRESULT WASAPIAudioOutputStream::SetRenderDevice(ERole device_role) { 564 HRESULT WASAPIAudioOutputStream::SetRenderDevice() {
515 // Create the IMMDeviceEnumerator interface. 565 // Create the IMMDeviceEnumerator interface.
516 HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), 566 HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),
517 NULL, 567 NULL,
518 CLSCTX_INPROC_SERVER, 568 CLSCTX_INPROC_SERVER,
519 __uuidof(IMMDeviceEnumerator), 569 __uuidof(IMMDeviceEnumerator),
520 device_enumerator_.ReceiveVoid()); 570 device_enumerator_.ReceiveVoid());
521 if (SUCCEEDED(hr)) { 571 if (SUCCEEDED(hr)) {
522 // Retrieve the default render audio endpoint for the specified role. 572 // Retrieve the default render audio endpoint for the specified role.
523 // Note that, in Windows Vista, the MMDevice API supports device roles 573 // Note that, in Windows Vista, the MMDevice API supports device roles
524 // but the system-supplied user interface programs do not. 574 // but the system-supplied user interface programs do not.
525 hr = device_enumerator_->GetDefaultAudioEndpoint( 575 hr = device_enumerator_->GetDefaultAudioEndpoint(
526 eRender, device_role, endpoint_device_.Receive()); 576 eRender, device_role_, endpoint_device_.Receive());
527 if (FAILED(hr)) 577 if (FAILED(hr))
528 return hr; 578 return hr;
529 579
530 // Verify that the audio endpoint device is active. That is, the audio 580 // Verify that the audio endpoint device is active. That is, the audio
531 // adapter that connects to the endpoint device is present and enabled. 581 // adapter that connects to the endpoint device is present and enabled.
532 DWORD state = DEVICE_STATE_DISABLED; 582 DWORD state = DEVICE_STATE_DISABLED;
533 hr = endpoint_device_->GetState(&state); 583 hr = endpoint_device_->GetState(&state);
534 if (SUCCEEDED(hr)) { 584 if (SUCCEEDED(hr)) {
535 if (!(state & DEVICE_STATE_ACTIVE)) { 585 if (!(state & DEVICE_STATE_ACTIVE)) {
536 DLOG(ERROR) << "Selected render device is not active."; 586 DLOG(ERROR) << "Selected render device is not active.";
(...skipping 15 matching lines...) Expand all
552 return hr; 602 return hr;
553 } 603 }
554 604
555 HRESULT WASAPIAudioOutputStream::GetAudioEngineStreamFormat() { 605 HRESULT WASAPIAudioOutputStream::GetAudioEngineStreamFormat() {
556 // Retrieve the stream format that the audio engine uses for its internal 606 // Retrieve the stream format that the audio engine uses for its internal
557 // processing/mixing of shared-mode streams. 607 // processing/mixing of shared-mode streams.
558 return audio_client_->GetMixFormat(&audio_engine_mix_format_); 608 return audio_client_->GetMixFormat(&audio_engine_mix_format_);
559 } 609 }
560 610
561 bool WASAPIAudioOutputStream::DesiredFormatIsSupported() { 611 bool WASAPIAudioOutputStream::DesiredFormatIsSupported() {
612 // Determine, before calling IAudioClient::Initialize(), whether the audio
613 // engine supports a particular stream format.
562 // In shared mode, the audio engine always supports the mix format, 614 // In shared mode, the audio engine always supports the mix format,
563 // which is stored in the |audio_engine_mix_format_| member. In addition, 615 // which is stored in the |audio_engine_mix_format_| member and it is also
564 // the audio engine *might* support similar formats that have the same 616 // possible to receive a proposed (closest) format if the current format is
565 // sample rate and number of channels as the mix format but differ in 617 // not supported.
566 // the representation of audio sample values.
567 base::win::ScopedCoMem<WAVEFORMATEX> closest_match; 618 base::win::ScopedCoMem<WAVEFORMATEX> closest_match;
568 HRESULT hr = audio_client_->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, 619 HRESULT hr = audio_client_->IsFormatSupported(share_mode(),
569 &format_, 620 &format_,
570 &closest_match); 621 &closest_match);
622
623 // This log can only be triggered for shared mode.
571 DLOG_IF(ERROR, hr == S_FALSE) << "Format is not supported " 624 DLOG_IF(ERROR, hr == S_FALSE) << "Format is not supported "
572 << "but a closest match exists."; 625 << "but a closest match exists.";
626 // This log can be triggered both for shared and exclusive modes.
627 DLOG_IF(ERROR, hr == AUDCLNT_E_UNSUPPORTED_FORMAT) << "Unsupported format.";
628 #ifndef NDEBUG
scherkus (not reviewing) 2012/07/25 23:44:44 #if !defined(NDEBUG)
henrika (OOO until Aug 14) 2012/07/26 08:31:11 Done.
629 if (hr == S_FALSE) {
630 DVLOG(1) << "wFormatTag : " << closest_match->wFormatTag;
631 DVLOG(1) << "nChannels : " << closest_match->nChannels;
632 DVLOG(1) << "nSamplesPerSec: " << closest_match->nSamplesPerSec;
633 DVLOG(1) << "wBitsPerSample: " << closest_match->wBitsPerSample;
634 }
635 #endif
636
573 return (hr == S_OK); 637 return (hr == S_OK);
574 } 638 }
575 639
576 HRESULT WASAPIAudioOutputStream::InitializeAudioEngine() { 640 HRESULT WASAPIAudioOutputStream::InitializeAudioEngine() {
577 // TODO(henrika): this buffer scheme is still under development.
578 // The exact details are yet to be determined based on tests with different
579 // audio clients.
580 int glitch_free_buffer_size_ms = static_cast<int>(packet_size_ms_ + 0.5);
581 if (audio_engine_mix_format_->nSamplesPerSec == 48000) {
582 // Initial tests have shown that we have to add 10 ms extra to
583 // ensure that we don't run empty for any packet size.
584 glitch_free_buffer_size_ms += 10;
585 } else if (audio_engine_mix_format_->nSamplesPerSec == 44100) {
586 // Initial tests have shown that we have to add 20 ms extra to
587 // ensure that we don't run empty for any packet size.
588 glitch_free_buffer_size_ms += 20;
589 } else {
590 glitch_free_buffer_size_ms += 20;
591 }
592 DVLOG(1) << "glitch_free_buffer_size_ms: " << glitch_free_buffer_size_ms;
593 REFERENCE_TIME requested_buffer_duration_hns =
594 static_cast<REFERENCE_TIME>(glitch_free_buffer_size_ms * 10000);
595
596 // Initialize the audio stream between the client and the device.
597 // We connect indirectly through the audio engine by using shared mode
598 // and WASAPI is initialized in an event driven mode.
599 // Note that this API ensures that the buffer is never smaller than the
600 // minimum buffer size needed to ensure glitch-free rendering.
601 // If we requests a buffer size that is smaller than the audio engine's
602 // minimum required buffer size, the method sets the buffer size to this
603 // minimum buffer size rather than to the buffer size requested.
604 HRESULT hr = audio_client_->Initialize(AUDCLNT_SHAREMODE_SHARED,
605 AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
606 AUDCLNT_STREAMFLAGS_NOPERSIST,
607 requested_buffer_duration_hns,
608 0,
609 &format_,
610 NULL);
611 if (FAILED(hr))
612 return hr;
613
614 // Retrieve the length of the endpoint buffer shared between the client
615 // and the audio engine. The buffer length the buffer length determines
616 // the maximum amount of rendering data that the client can write to
617 // the endpoint buffer during a single processing pass.
618 // A typical value is 960 audio frames <=> 20ms @ 48kHz sample rate.
619 hr = audio_client_->GetBufferSize(&endpoint_buffer_size_frames_);
620 if (FAILED(hr))
621 return hr;
622 DVLOG(1) << "endpoint buffer size: " << endpoint_buffer_size_frames_
623 << " [frames]";
624 #ifndef NDEBUG 641 #ifndef NDEBUG
625 // The period between processing passes by the audio engine is fixed for a 642 // The period between processing passes by the audio engine is fixed for a
626 // particular audio endpoint device and represents the smallest processing 643 // particular audio endpoint device and represents the smallest processing
627 // quantum for the audio engine. This period plus the stream latency between 644 // quantum for the audio engine. This period plus the stream latency between
628 // the buffer and endpoint device represents the minimum possible latency 645 // the buffer and endpoint device represents the minimum possible latency
629 // that an audio application can achieve in shared mode. 646 // that an audio application can achieve in shared mode.
630 REFERENCE_TIME default_device_period = 0; 647 REFERENCE_TIME default_device_period = 0;
631 REFERENCE_TIME minimum_device_period = 0; 648 REFERENCE_TIME minimum_device_period = 0;
632 HRESULT hr_dbg = audio_client_->GetDevicePeriod(&default_device_period, 649 HRESULT hr_dbg = audio_client_->GetDevicePeriod(&default_device_period,
633 &minimum_device_period); 650 &minimum_device_period);
634 if (SUCCEEDED(hr_dbg)) { 651 if (SUCCEEDED(hr_dbg)) {
635 // Shared mode device period. 652 // Shared mode device period.
636 DVLOG(1) << "default device period: " 653 DVLOG(1) << "shared mode (default) device period: "
637 << static_cast<double>(default_device_period / 10000.0) 654 << static_cast<double>(default_device_period / 10000.0)
638 << " [ms]"; 655 << " [ms]";
639 // Exclusive mode device period. 656 // Exclusive mode device period.
640 DVLOG(1) << "minimum device period: " 657 DVLOG(1) << "exclusive mode (minimum) device period: "
641 << static_cast<double>(minimum_device_period / 10000.0) 658 << static_cast<double>(minimum_device_period / 10000.0)
642 << " [ms]"; 659 << " [ms]";
643 } 660 }
644 661
645 REFERENCE_TIME latency = 0; 662 REFERENCE_TIME latency = 0;
646 hr_dbg = audio_client_->GetStreamLatency(&latency); 663 hr_dbg = audio_client_->GetStreamLatency(&latency);
647 if (SUCCEEDED(hr_dbg)) { 664 if (SUCCEEDED(hr_dbg)) {
648 DVLOG(1) << "stream latency: " << static_cast<double>(latency / 10000.0) 665 DVLOG(1) << "stream latency: " << static_cast<double>(latency / 10000.0)
649 << " [ms]"; 666 << " [ms]";
650 } 667 }
651 #endif 668 #endif
652 669
670 HRESULT hr = S_FALSE;
671
672 // Perform different initialization depending on if the device shall be
673 // opened in shared mode or in exclusive mode.
674 hr = (share_mode() == AUDCLNT_SHAREMODE_SHARED) ?
675 SharedModeInitialization() : ExclusiveModeInitialization();
676 if (FAILED(hr)) {
677 PLOG(WARNING) << "IAudioClient::Initialize() failed: " << std::hex << hr;
678 return hr;
679 }
680
681 // Retrieve the length of the endpoint buffer. The buffer length represents
682 // the maximum amount of rendering data that the client can write to
683 // the endpoint buffer during a single processing pass.
684 // A typical value is 960 audio frames <=> 20ms @ 48kHz sample rate.
685 hr = audio_client_->GetBufferSize(&endpoint_buffer_size_frames_);
686 if (FAILED(hr))
687 return hr;
688 DVLOG(1) << "endpoint buffer size: " << endpoint_buffer_size_frames_
689 << " [frames]";
690
691 // The buffer scheme for exclusive mode streams is not designed for max
692 // flexibility. We only allow a "perfect match" between the packet size set
693 // by the user and the actual endpoint buffer size.
694 if (share_mode() == AUDCLNT_SHAREMODE_EXCLUSIVE &&
695 endpoint_buffer_size_frames_ != packet_size_frames_) {
696 hr = AUDCLNT_E_INVALID_SIZE;
697 DLOG(ERROR) << "AUDCLNT_E_INVALID_SIZE";
698 return hr;
699 }
700
653 // Set the event handle that the audio engine will signal each time 701 // Set the event handle that the audio engine will signal each time
654 // a buffer becomes ready to be processed by the client. 702 // a buffer becomes ready to be processed by the client.
655 hr = audio_client_->SetEventHandle(audio_samples_render_event_.Get()); 703 hr = audio_client_->SetEventHandle(audio_samples_render_event_.Get());
656 if (FAILED(hr)) 704 if (FAILED(hr))
657 return hr; 705 return hr;
658 706
659 // Get access to the IAudioRenderClient interface. This interface 707 // Get access to the IAudioRenderClient interface. This interface
660 // enables us to write output data to a rendering endpoint buffer. 708 // enables us to write output data to a rendering endpoint buffer.
661 // The methods in this interface manage the movement of data packets 709 // The methods in this interface manage the movement of data packets
662 // that contain audio-rendering data. 710 // that contain audio-rendering data.
663 hr = audio_client_->GetService(__uuidof(IAudioRenderClient), 711 hr = audio_client_->GetService(__uuidof(IAudioRenderClient),
664 audio_render_client_.ReceiveVoid()); 712 audio_render_client_.ReceiveVoid());
665 return hr; 713 return hr;
666 } 714 }
667 715
716 HRESULT WASAPIAudioOutputStream::SharedModeInitialization() {
717 // TODO(henrika): this buffer scheme is still under development.
718 // The exact details are yet to be determined based on tests with different
719 // audio clients.
720 int glitch_free_buffer_size_ms = static_cast<int>(packet_size_ms_ + 0.5);
721 if (audio_engine_mix_format_->nSamplesPerSec == 48000) {
722 // Initial tests have shown that we have to add 10 ms extra to
723 // ensure that we don't run empty for any packet size.
724 glitch_free_buffer_size_ms += 10;
725 } else if (audio_engine_mix_format_->nSamplesPerSec == 44100) {
726 // Initial tests have shown that we have to add 20 ms extra to
727 // ensure that we don't run empty for any packet size.
728 glitch_free_buffer_size_ms += 20;
729 } else {
730 glitch_free_buffer_size_ms += 20;
731 }
732 DVLOG(1) << "glitch_free_buffer_size_ms: " << glitch_free_buffer_size_ms;
733 REFERENCE_TIME requested_buffer_duration =
734 static_cast<REFERENCE_TIME>(glitch_free_buffer_size_ms * 10000);
735
736 // Initialize the audio stream between the client and the device.
737 // We connect indirectly through the audio engine by using shared mode
738 // and WASAPI is initialized in an event driven mode.
739 // Note that this API ensures that the buffer is never smaller than the
740 // minimum buffer size needed to ensure glitch-free rendering.
741 // If we requests a buffer size that is smaller than the audio engine's
742 // minimum required buffer size, the method sets the buffer size to this
743 // minimum buffer size rather than to the buffer size requested.
744 HRESULT hr = audio_client_->Initialize(AUDCLNT_SHAREMODE_SHARED,
745 AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
746 AUDCLNT_STREAMFLAGS_NOPERSIST,
747 requested_buffer_duration,
748 0,
749 &format_,
750 NULL);
751 return hr;
752 }
753
754 HRESULT WASAPIAudioOutputStream::ExclusiveModeInitialization() {
755 float f = (1000.0 * packet_size_frames_) / format_.nSamplesPerSec;
756 REFERENCE_TIME requested_buffer_duration =
757 static_cast<REFERENCE_TIME>(f*10000.0 + 0.5);
scherkus (not reviewing) 2012/07/25 23:44:44 spaces around *
henrika (OOO until Aug 14) 2012/07/26 08:31:11 Done.
758
759 // Initialize the audio stream between the client and the device.
760 // For an exclusive-mode stream that uses event-driven buffering, the
761 // caller must specify nonzero values for hnsPeriodicity and
762 // hnsBufferDuration, and the values of these two parameters must be equal.
763 // The Initialize method allocates two buffers for the stream. Each buffer
764 // is equal in duration to the value of the hnsBufferDuration parameter.
765 // Following the Initialize call for a rendering stream, the caller should
766 // fill the first of the two buffers before starting the stream.
767 HRESULT hr = audio_client_->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE,
768 AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
769 AUDCLNT_STREAMFLAGS_NOPERSIST,
770 requested_buffer_duration,
771 requested_buffer_duration,
772 &format_,
773 NULL);
774 if (FAILED(hr)) {
775 if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) {
776 DLOG(ERROR) << "AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED";
777
778 UINT32 aligned_buffer_size = 0;
779 audio_client_->GetBufferSize(&aligned_buffer_size);
780 DVLOG(1) << "Use aligned buffer size instead: " << aligned_buffer_size;
781 audio_client_.Release();
782
783 // Calculate new aligned periodicity. Each unit of reference time
784 // is 100 nanoseconds.
785 REFERENCE_TIME aligned_buffer_duration = static_cast<REFERENCE_TIME>(
786 10000000.0 * aligned_buffer_size / format_.nSamplesPerSec + 0.5);
787
788 // It is possible to re-activate and re-initialize the audio client
789 // at this stage but we bail out with an error code instead and
790 // combine it with a log message which informs about the suggested
791 // aligned buffer size which should be used instead.
792 DVLOG(1) << "aligned_buffer_duration: "
793 << static_cast<double>(aligned_buffer_duration / 10000.0)
794 << " [ms]";
795 } else if (hr == AUDCLNT_E_INVALID_DEVICE_PERIOD) {
796 // We will get this error if we try to use a smaller buffer size than
797 // the minimum supported size (usually ~3ms on Windows 7).
798 DLOG(ERROR) << "AUDCLNT_E_INVALID_DEVICE_PERIOD";
799 }
800 }
801
802 return hr;
803 }
804
668 ULONG WASAPIAudioOutputStream::AddRef() { 805 ULONG WASAPIAudioOutputStream::AddRef() {
669 NOTREACHED() << "IMMNotificationClient should not use this method."; 806 NOTREACHED() << "IMMNotificationClient should not use this method.";
670 return 1; 807 return 1;
671 } 808 }
672 809
673 ULONG WASAPIAudioOutputStream::Release() { 810 ULONG WASAPIAudioOutputStream::Release() {
674 NOTREACHED() << "IMMNotificationClient should not use this method."; 811 NOTREACHED() << "IMMNotificationClient should not use this method.";
675 return 1; 812 return 1;
676 } 813 }
677 814
(...skipping 145 matching lines...) Expand 10 before | Expand all | Expand 10 after
823 // are now re-initiated and it is now possible to re-start audio rendering. 960 // are now re-initiated and it is now possible to re-start audio rendering.
824 961
825 // Start rendering again using the new default audio endpoint. 962 // Start rendering again using the new default audio endpoint.
826 hr = audio_client_->Start(); 963 hr = audio_client_->Start();
827 964
828 restart_rendering_mode_ = false; 965 restart_rendering_mode_ = false;
829 return SUCCEEDED(hr); 966 return SUCCEEDED(hr);
830 } 967 }
831 968
832 } // namespace media 969 } // namespace media
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698