Chromium Code Reviews| OLD | NEW |
|---|---|
| 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/command_line.h" |
| 10 #include "base/logging.h" | 10 #include "base/logging.h" |
| 11 #include "base/memory/scoped_ptr.h" | 11 #include "base/memory/scoped_ptr.h" |
| 12 #include "base/utf_string_conversions.h" | 12 #include "base/utf_string_conversions.h" |
| 13 #include "media/audio/audio_util.h" | 13 #include "media/audio/audio_util.h" |
| 14 #include "media/audio/win/audio_manager_win.h" | 14 #include "media/audio/win/audio_manager_win.h" |
| 15 #include "media/audio/win/avrt_wrapper_win.h" | 15 #include "media/audio/win/avrt_wrapper_win.h" |
| 16 #include "media/base/media_switches.h" | 16 #include "media/base/media_switches.h" |
| 17 | 17 |
| 18 using base::win::ScopedComPtr; | 18 using base::win::ScopedComPtr; |
| 19 using base::win::ScopedCOMInitializer; | 19 using base::win::ScopedCOMInitializer; |
| 20 using base::win::ScopedCoMem; | 20 using base::win::ScopedCoMem; |
| 21 | 21 |
| 22 namespace media { | 22 namespace media { |
| 23 | 23 |
| 24 typedef uint32 ChannelConfigMask; | |
| 25 | |
| 26 // Ensure that the alignment of members will be on a boundary that is a | |
| 27 // multiple of 1 byte. | |
| 28 #pragma pack(push) | |
| 29 #pragma pack(1) | |
| 30 | |
| 31 struct LayoutStereo_16bit { | |
| 32 int16 left; | |
| 33 int16 right; | |
| 34 }; | |
| 35 | |
| 36 struct Layout7_1_16bit { | |
| 37 int16 front_left; | |
| 38 int16 front_right; | |
| 39 int16 front_center; | |
| 40 int16 low_frequency; | |
| 41 int16 back_left; | |
| 42 int16 back_right; | |
| 43 int16 side_left; | |
| 44 int16 side_right; | |
| 45 }; | |
| 46 | |
| 47 #pragma pack(pop) | |
| 48 | |
| 49 // Retrieves the stream format that the audio engine uses for its internal | |
| 50 // processing/mixing of shared-mode streams. | |
| 51 HRESULT GetMixFormat(ERole device_role, WAVEFORMATEX** device_format) { | |
|
scherkus (not reviewing)
2012/08/02 00:41:57
static
henrika (OOO until Aug 14)
2012/08/02 09:01:16
Done. However, is it really needed when I am in th
| |
| 52 // Note that we are using the IAudioClient::GetMixFormat() API to get the | |
| 53 // device format in this function. It is in fact possible to be "more native", | |
| 54 // and ask the endpoint device directly for its properties. Given a reference | |
| 55 // to the IMMDevice interface of an endpoint object, a client can obtain a | |
| 56 // reference to the endpoint object's property store by calling the | |
| 57 // IMMDevice::OpenPropertyStore() method. However, I have not been able to | |
| 58 // access any valuable information using this method on my HP Z600 desktop, | |
| 59 // hence it feels more appropriate to use the IAudioClient::GetMixFormat() | |
| 60 // approach instead. | |
| 61 | |
| 62 // Calling this function only makes sense for shared mode streams, since | |
| 63 // if the device will be opened in exclusive mode, then the application | |
| 64 // specified format is used instead. However, the result of this method can | |
| 65 // be useful for testing purposes so we don't DCHECK here. | |
| 66 DLOG_IF(WARNING, WASAPIAudioOutputStream::GetShareMode() == | |
| 67 AUDCLNT_SHAREMODE_EXCLUSIVE) << | |
| 68 "The mixing sample rate will be ignored for exclusive-mode streams."; | |
| 69 | |
| 70 // It is assumed that this static method is called from a COM thread, i.e., | |
| 71 // CoInitializeEx() is not called here again to avoid STA/MTA conflicts. | |
| 72 ScopedComPtr<IMMDeviceEnumerator> enumerator; | |
| 73 HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), | |
| 74 NULL, | |
| 75 CLSCTX_INPROC_SERVER, | |
| 76 __uuidof(IMMDeviceEnumerator), | |
| 77 enumerator.ReceiveVoid()); | |
| 78 if (FAILED(hr)) { | |
| 79 NOTREACHED() << "error code: " << std::hex << hr; | |
| 80 return 0.0; | |
| 81 } | |
| 82 | |
| 83 ScopedComPtr<IMMDevice> endpoint_device; | |
| 84 hr = enumerator->GetDefaultAudioEndpoint(eRender, | |
| 85 device_role, | |
| 86 endpoint_device.Receive()); | |
| 87 if (FAILED(hr)) { | |
| 88 // This will happen if there's no audio output device found or available | |
| 89 // (e.g. some audio cards that have outputs will still report them as | |
| 90 // "not found" when no speaker is plugged into the output jack). | |
| 91 LOG(WARNING) << "No audio end point: " << std::hex << hr; | |
| 92 return 0.0; | |
| 93 } | |
| 94 | |
| 95 ScopedComPtr<IAudioClient> audio_client; | |
| 96 hr = endpoint_device->Activate(__uuidof(IAudioClient), | |
| 97 CLSCTX_INPROC_SERVER, | |
| 98 NULL, | |
| 99 audio_client.ReceiveVoid()); | |
| 100 DCHECK(SUCCEEDED(hr)) << "Failed to activate device: " << std::hex << hr; | |
| 101 if (SUCCEEDED(hr)) { | |
| 102 hr = audio_client->GetMixFormat(device_format); | |
| 103 DCHECK(SUCCEEDED(hr)) << "GetMixFormat: " << std::hex << hr; | |
| 104 } | |
| 105 | |
| 106 return hr; | |
| 107 } | |
| 108 | |
| 109 // Retrieves an integer mask which corresponds to the channel layout the | |
| 110 // audio engine uses for its internal processing/mixing of shared-mode | |
| 111 // streams. This mask indicates which channels are present in the multi- | |
| 112 // channel stream. The least significant bit corresponds with the Front Left | |
| 113 // speaker, the next least significant bit corresponds to the Front Right | |
| 114 // speaker, and so on, continuing in the order defined in KsMedia.h. | |
| 115 // See http://msdn.microsoft.com/en-us/library/windows/hardware/ff537083(v=vs.85 ).aspx | |
| 116 // for more details. | |
| 117 ChannelConfigMask ChannelConfig() { | |
|
scherkus (not reviewing)
2012/08/02 00:41:57
static
scherkus (not reviewing)
2012/08/02 00:41:57
ChannelConfig() isn't a terribly good message name
henrika (OOO until Aug 14)
2012/08/02 09:01:16
Done.
henrika (OOO until Aug 14)
2012/08/02 09:01:16
Done.
| |
| 118 // Use a WAVEFORMATEXTENSIBLE structure since it can specify both the | |
| 119 // number of channels and the mapping of channels to speakers for | |
| 120 // multichannel devices. | |
| 121 base::win::ScopedCoMem<WAVEFORMATPCMEX> format_ex; | |
| 122 HRESULT hr = GetMixFormat( | |
| 123 eConsole, reinterpret_cast<WAVEFORMATEX**>(&format_ex)); | |
| 124 if (FAILED(hr)) | |
| 125 return 0; | |
| 126 | |
| 127 // The dwChannelMask member specifies which channels are present in the | |
| 128 // multichannel stream. The least significant bit corresponds to the | |
| 129 // front left speaker, the next least significant bit corresponds to the | |
| 130 // front right speaker, and so on. | |
| 131 // See http://msdn.microsoft.com/en-us/library/windows/desktop/dd757714(v=vs.8 5).aspx | |
| 132 // for more details on the channel mapping. | |
| 133 DVLOG(2) << "dwChannelMask: 0x" << std::hex << format_ex->dwChannelMask; | |
| 134 | |
| 135 #if !defined(NDEBUG) | |
| 136 // See http://en.wikipedia.org/wiki/Surround_sound for more details on | |
| 137 // how to name various speaker configurations. The list below is not complete. | |
| 138 const char* speaker_config("Undefined"); | |
| 139 switch (format_ex->dwChannelMask) { | |
| 140 case KSAUDIO_SPEAKER_MONO: | |
| 141 speaker_config = "Mono"; | |
| 142 case KSAUDIO_SPEAKER_STEREO: | |
| 143 speaker_config = "Stereo"; | |
| 144 case KSAUDIO_SPEAKER_5POINT1_SURROUND: | |
| 145 speaker_config = "5.1 surround"; | |
| 146 case KSAUDIO_SPEAKER_5POINT1: | |
| 147 speaker_config = "5.1"; | |
| 148 case KSAUDIO_SPEAKER_7POINT1_SURROUND: | |
| 149 speaker_config = "7.1 surround"; | |
| 150 case KSAUDIO_SPEAKER_7POINT1: | |
| 151 speaker_config = "7.1"; | |
| 152 } | |
| 153 DVLOG(2) << "speaker configuration: " << speaker_config; | |
| 154 #endif | |
| 155 | |
| 156 return static_cast<ChannelConfigMask>(format_ex->dwChannelMask); | |
| 157 } | |
| 158 | |
| 159 // Converts Microsoft's channel configuration to Chrome's ChannelLayout. | |
| 160 // This mapping is not perfect but the best we can do given the current | |
| 161 // ChannelLayout enumerator and the Windows-specific speaker configurations | |
| 162 // defined in ksmedia.h. Don't assume that the channel ordering in | |
| 163 // ChannelLayout is exactly the same as the Windows specific configuration. | |
| 164 // As an example: KSAUDIO_SPEAKER_7POINT1_SURROUND is mapped to | |
| 165 // CHANNEL_LAYOUT_7_1 but the positions of Back L, Back R and Side L, Side R | |
| 166 // speakers are different in these two definitions. | |
| 167 ChannelLayout ChannelConfigToChromeChannelLayout(ChannelConfigMask config) { | |
|
scherkus (not reviewing)
2012/08/02 00:41:57
nit: drop the Chrome part from function name -- ha
henrika (OOO until Aug 14)
2012/08/02 09:01:16
Got it. Took it from FFmpeg ;-)
Removed Mask from
| |
| 168 switch (config) { | |
|
scherkus (not reviewing)
2012/08/02 00:41:57
fix indent
henrika (OOO until Aug 14)
2012/08/02 09:01:16
Done.
| |
| 169 case KSAUDIO_SPEAKER_DIRECTOUT: | |
| 170 return CHANNEL_LAYOUT_NONE; | |
| 171 case KSAUDIO_SPEAKER_MONO: | |
| 172 return CHANNEL_LAYOUT_MONO; | |
| 173 case KSAUDIO_SPEAKER_STEREO: | |
| 174 return CHANNEL_LAYOUT_STEREO; | |
| 175 case KSAUDIO_SPEAKER_QUAD: | |
| 176 return CHANNEL_LAYOUT_QUAD; | |
| 177 case KSAUDIO_SPEAKER_SURROUND: | |
| 178 return CHANNEL_LAYOUT_4_0; | |
| 179 case KSAUDIO_SPEAKER_5POINT1: | |
| 180 return CHANNEL_LAYOUT_5_1_BACK; | |
| 181 case KSAUDIO_SPEAKER_5POINT1_SURROUND: | |
| 182 return CHANNEL_LAYOUT_5_1; | |
| 183 case KSAUDIO_SPEAKER_7POINT1: | |
| 184 return CHANNEL_LAYOUT_7_1_WIDE; | |
| 185 case KSAUDIO_SPEAKER_7POINT1_SURROUND: | |
| 186 return CHANNEL_LAYOUT_7_1; | |
| 187 default: | |
| 188 DVLOG(1) << "Unsupported channel layout: " << config; | |
| 189 return CHANNEL_LAYOUT_UNSUPPORTED; | |
| 190 } | |
| 191 } | |
| 192 | |
| 193 // 2 -> N.1 up-mixing where N=out_channels-1. | |
| 194 // See http://www.w3.org/TR/webaudio/#UpMix-sub for details. | |
| 195 // TODO(henrika): improve comment and possible use ChannelLayout for channel | |
| 196 // parameters. | |
| 197 bool ChannelUpMix(void* input, | |
| 198 void* output, | |
| 199 int in_channels, | |
| 200 int out_channels, | |
| 201 size_t number_of_input_bytes) { | |
| 202 DCHECK(input); | |
|
scherkus (not reviewing)
2012/08/02 00:41:57
the DCHECKs for input/output aren't needed
henrika (OOO until Aug 14)
2012/08/02 09:01:16
Done.
| |
| 203 DCHECK(output); | |
| 204 DCHECK_GT(out_channels, in_channels); | |
| 205 | |
| 206 if (in_channels == 2 && out_channels == 8) { | |
| 207 LayoutStereo_16bit* in = reinterpret_cast<LayoutStereo_16bit*>(input); | |
| 208 Layout7_1_16bit* out = reinterpret_cast<Layout7_1_16bit*>(output); | |
| 209 int number_of_input_stereo_samples = (number_of_input_bytes >> 2); | |
| 210 | |
| 211 // Zero out all frames first. | |
| 212 memset(out, 0, number_of_input_stereo_samples * sizeof(out[0])); | |
| 213 | |
| 214 // Copy left and right input channels to the same output channels. | |
| 215 // TODO(henrika): can we do this in-place by processing the samples in | |
| 216 // reverse order when sizeof(out) > sizeof(in) (upmixing)? | |
| 217 for (int i = 0; i < number_of_input_stereo_samples; ++i) { | |
| 218 out->front_left = in->left; | |
| 219 out->front_right = in->right; | |
| 220 in++; | |
| 221 out++; | |
| 222 } | |
| 223 } else { | |
| 224 LOG(ERROR) << "Up-mixing is not supported."; | |
|
scherkus (not reviewing)
2012/08/02 00:41:57
document # of channels?
henrika (OOO until Aug 14)
2012/08/02 09:01:16
Done.
| |
| 225 return false; | |
| 226 } | |
| 227 return true; | |
| 228 } | |
| 229 | |
| 24 // static | 230 // static |
| 25 AUDCLNT_SHAREMODE WASAPIAudioOutputStream::GetShareMode() { | 231 AUDCLNT_SHAREMODE WASAPIAudioOutputStream::GetShareMode() { |
| 26 const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); | 232 const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); |
| 27 if (cmd_line->HasSwitch(switches::kEnableExclusiveAudio)) | 233 if (cmd_line->HasSwitch(switches::kEnableExclusiveAudio)) |
| 28 return AUDCLNT_SHAREMODE_EXCLUSIVE; | 234 return AUDCLNT_SHAREMODE_EXCLUSIVE; |
| 29 return AUDCLNT_SHAREMODE_SHARED; | 235 return AUDCLNT_SHAREMODE_SHARED; |
| 30 } | 236 } |
| 31 | 237 |
| 32 WASAPIAudioOutputStream::WASAPIAudioOutputStream(AudioManagerWin* manager, | 238 WASAPIAudioOutputStream::WASAPIAudioOutputStream(AudioManagerWin* manager, |
| 33 const AudioParameters& params, | 239 const AudioParameters& params, |
| 34 ERole device_role) | 240 ERole device_role) |
| 35 : com_init_(ScopedCOMInitializer::kMTA), | 241 : com_init_(ScopedCOMInitializer::kMTA), |
| 36 creating_thread_id_(base::PlatformThread::CurrentId()), | 242 creating_thread_id_(base::PlatformThread::CurrentId()), |
| 37 manager_(manager), | 243 manager_(manager), |
| 38 render_thread_(NULL), | 244 render_thread_(NULL), |
| 39 opened_(false), | 245 opened_(false), |
| 40 started_(false), | 246 started_(false), |
| 41 restart_rendering_mode_(false), | 247 restart_rendering_mode_(false), |
| 42 volume_(1.0), | 248 volume_(1.0), |
| 43 endpoint_buffer_size_frames_(0), | 249 endpoint_buffer_size_frames_(0), |
| 44 device_role_(device_role), | 250 device_role_(device_role), |
| 45 share_mode_(GetShareMode()), | 251 share_mode_(GetShareMode()), |
| 252 client_channel_count_(params.channels()), | |
| 46 num_written_frames_(0), | 253 num_written_frames_(0), |
| 47 source_(NULL) { | 254 source_(NULL) { |
| 48 CHECK(com_init_.succeeded()); | 255 CHECK(com_init_.succeeded()); |
| 49 DCHECK(manager_); | 256 DCHECK(manager_); |
| 50 | 257 |
| 51 // Load the Avrt DLL if not already loaded. Required to support MMCSS. | 258 // Load the Avrt DLL if not already loaded. Required to support MMCSS. |
| 52 bool avrt_init = avrt::Initialize(); | 259 bool avrt_init = avrt::Initialize(); |
| 53 DCHECK(avrt_init) << "Failed to load the avrt.dll"; | 260 DCHECK(avrt_init) << "Failed to load the avrt.dll"; |
| 54 | 261 |
| 55 if (share_mode() == AUDCLNT_SHAREMODE_EXCLUSIVE) { | 262 if (share_mode_ == AUDCLNT_SHAREMODE_EXCLUSIVE) { |
| 56 VLOG(1) << ">> Note that EXCLUSIVE MODE is enabled <<"; | 263 VLOG(1) << ">> Note that EXCLUSIVE MODE is enabled <<"; |
| 57 } | 264 } |
| 58 | 265 |
| 59 // Set up the desired render format specified by the client. | 266 // Set up the desired render format specified by the client. We use the |
| 60 format_.nSamplesPerSec = params.sample_rate(); | 267 // WAVE_FORMAT_EXTENSIBLE structure to ensure that multiple channel ordering |
| 61 format_.wFormatTag = WAVE_FORMAT_PCM; | 268 // and high precision data can be supported. |
| 62 format_.wBitsPerSample = params.bits_per_sample(); | 269 |
| 63 format_.nChannels = params.channels(); | 270 // Begin with the WAVEFORMATEX structure that specifies the basic format. |
| 64 format_.nBlockAlign = (format_.wBitsPerSample / 8) * format_.nChannels; | 271 WAVEFORMATEX* format = &format_.Format; |
| 65 format_.nAvgBytesPerSec = format_.nSamplesPerSec * format_.nBlockAlign; | 272 format->wFormatTag = WAVE_FORMAT_EXTENSIBLE; |
| 66 format_.cbSize = 0; | 273 format->nChannels = HardwareChannelCount(); |
| 274 format->nSamplesPerSec = params.sample_rate(); | |
| 275 format->wBitsPerSample = params.bits_per_sample(); | |
| 276 format->nBlockAlign = (format->wBitsPerSample / 8) * format->nChannels; | |
| 277 format->nAvgBytesPerSec = format->nSamplesPerSec * format->nBlockAlign; | |
| 278 format->cbSize = 22; | |
| 279 | |
| 280 // Add the parts which are unique to WAVE_FORMAT_EXTENSIBLE. | |
| 281 format_.Samples.wValidBitsPerSample = params.bits_per_sample(); | |
| 282 format_.dwChannelMask = ChannelConfig(); | |
| 283 format_.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; | |
| 67 | 284 |
| 68 // Size in bytes of each audio frame. | 285 // Size in bytes of each audio frame. |
| 69 frame_size_ = format_.nBlockAlign; | 286 frame_size_ = format->nBlockAlign; |
| 287 | |
| 288 // It is possible to set the number of channels in |params| to a lower value | |
| 289 // than we use as the internal number of audio channels when the audio stream | |
| 290 // is opened. If this mode (channel_factor_ > 1) is set, the native audio | |
| 291 // layer will expect a larger number of channels in the interleaved audio | |
| 292 // stream and a channel up-mix will be performed after the OnMoreData() | |
| 293 // callback to compensate for the lower number of channels provided by the | |
| 294 // audio source. | |
| 295 // Example: params.channels() is 2 and endpoint_channel_count() is 8 => | |
| 296 // the audio stream is opened up in 7.1 surround mode but the source only | |
| 297 // provides a stereo signal as input, i.e., a stereo up-mix (2 -> 7.1) will | |
| 298 // take place before sending the stream to the audio driver. | |
| 299 DCHECK_GE(channel_factor(), 1) << "Unsupported channel count."; | |
| 300 DVLOG(1) << "client channels: " << params.channels(); | |
| 301 DVLOG(1) << "channel factor: " << channel_factor(); | |
| 70 | 302 |
| 71 // Store size (in different units) of audio packets which we expect to | 303 // Store size (in different units) of audio packets which we expect to |
| 72 // get from the audio endpoint device in each render event. | 304 // get from the audio endpoint device in each render event. |
| 73 packet_size_frames_ = params.GetBytesPerBuffer() / format_.nBlockAlign; | 305 packet_size_frames_ = |
| 74 packet_size_bytes_ = params.GetBytesPerBuffer(); | 306 (channel_factor() * params.GetBytesPerBuffer()) / format->nBlockAlign; |
| 307 packet_size_bytes_ = channel_factor() * params.GetBytesPerBuffer(); | |
| 75 packet_size_ms_ = (1000.0 * packet_size_frames_) / params.sample_rate(); | 308 packet_size_ms_ = (1000.0 * packet_size_frames_) / params.sample_rate(); |
| 76 DVLOG(1) << "Number of bytes per audio frame : " << frame_size_; | 309 DVLOG(1) << "Number of bytes per audio frame : " << frame_size_; |
| 77 DVLOG(1) << "Number of audio frames per packet: " << packet_size_frames_; | 310 DVLOG(1) << "Number of audio frames per packet: " << packet_size_frames_; |
| 78 DVLOG(1) << "Number of milliseconds per packet: " << packet_size_ms_; | 311 DVLOG(1) << "Number of milliseconds per packet: " << packet_size_ms_; |
| 79 | 312 |
| 80 // All events are auto-reset events and non-signaled initially. | 313 // All events are auto-reset events and non-signaled initially. |
| 81 | 314 |
| 82 // Create the event which the audio engine will signal each time | 315 // Create the event which the audio engine will signal each time |
| 83 // a buffer becomes ready to be processed by the client. | 316 // a buffer becomes ready to be processed by the client. |
| 84 audio_samples_render_event_.Set(CreateEvent(NULL, FALSE, FALSE, NULL)); | 317 audio_samples_render_event_.Set(CreateEvent(NULL, FALSE, FALSE, NULL)); |
| (...skipping 153 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 238 hr = audio_client_->Reset(); | 471 hr = audio_client_->Reset(); |
| 239 if (FAILED(hr)) { | 472 if (FAILED(hr)) { |
| 240 DLOG_IF(ERROR, hr != AUDCLNT_E_NOT_INITIALIZED) | 473 DLOG_IF(ERROR, hr != AUDCLNT_E_NOT_INITIALIZED) |
| 241 << "Failed to reset streaming: " << std::hex << hr; | 474 << "Failed to reset streaming: " << std::hex << hr; |
| 242 } | 475 } |
| 243 | 476 |
| 244 // Extra safety check to ensure that the buffers are cleared. | 477 // Extra safety check to ensure that the buffers are cleared. |
| 245 // If the buffers are not cleared correctly, the next call to Start() | 478 // If the buffers are not cleared correctly, the next call to Start() |
| 246 // would fail with AUDCLNT_E_BUFFER_ERROR at IAudioRenderClient::GetBuffer(). | 479 // would fail with AUDCLNT_E_BUFFER_ERROR at IAudioRenderClient::GetBuffer(). |
| 247 // This check is is only needed for shared-mode streams. | 480 // This check is is only needed for shared-mode streams. |
| 248 if (share_mode() == AUDCLNT_SHAREMODE_SHARED) { | 481 if (share_mode_ == AUDCLNT_SHAREMODE_SHARED) { |
| 249 UINT32 num_queued_frames = 0; | 482 UINT32 num_queued_frames = 0; |
| 250 audio_client_->GetCurrentPadding(&num_queued_frames); | 483 audio_client_->GetCurrentPadding(&num_queued_frames); |
| 251 DCHECK_EQ(0u, num_queued_frames); | 484 DCHECK_EQ(0u, num_queued_frames); |
| 252 } | 485 } |
| 253 | 486 |
| 254 // Ensure that we don't quit the main thread loop immediately next | 487 // Ensure that we don't quit the main thread loop immediately next |
| 255 // time Start() is called. | 488 // time Start() is called. |
| 256 ResetEvent(stop_render_event_.Get()); | 489 ResetEvent(stop_render_event_.Get()); |
| 257 | 490 |
| 258 started_ = false; | 491 started_ = false; |
| (...skipping 27 matching lines...) Expand all Loading... | |
| 286 } | 519 } |
| 287 volume_ = volume_float; | 520 volume_ = volume_float; |
| 288 } | 521 } |
| 289 | 522 |
| 290 void WASAPIAudioOutputStream::GetVolume(double* volume) { | 523 void WASAPIAudioOutputStream::GetVolume(double* volume) { |
| 291 DVLOG(1) << "GetVolume()"; | 524 DVLOG(1) << "GetVolume()"; |
| 292 *volume = static_cast<double>(volume_); | 525 *volume = static_cast<double>(volume_); |
| 293 } | 526 } |
| 294 | 527 |
| 295 // static | 528 // static |
| 529 int WASAPIAudioOutputStream::HardwareChannelCount() { | |
| 530 // Use a WAVEFORMATEXTENSIBLE structure since it can specify both the | |
| 531 // number of channels and the mapping of channels to speakers for | |
| 532 // multichannel devices. | |
| 533 base::win::ScopedCoMem<WAVEFORMATPCMEX> format_ex; | |
| 534 HRESULT hr = GetMixFormat( | |
| 535 eConsole, reinterpret_cast<WAVEFORMATEX**>(&format_ex)); | |
| 536 if (FAILED(hr)) | |
| 537 return 0; | |
| 538 | |
| 539 // Number of channels in the stream. Corresponds to the number of bits | |
| 540 // set in the dwChannelMask. | |
| 541 DVLOG(2) << "endpoint channels: " << format_ex->Format.nChannels; | |
| 542 | |
| 543 return static_cast<int>(format_ex->Format.nChannels); | |
| 544 } | |
| 545 | |
| 546 // static | |
| 547 ChannelLayout WASAPIAudioOutputStream::HardwareChannelLayout() { | |
| 548 return ChannelConfigToChromeChannelLayout(ChannelConfig()); | |
| 549 } | |
| 550 | |
| 551 // static | |
| 296 int WASAPIAudioOutputStream::HardwareSampleRate(ERole device_role) { | 552 int WASAPIAudioOutputStream::HardwareSampleRate(ERole device_role) { |
| 297 // Calling this function only makes sense for shared mode streams, since | 553 base::win::ScopedCoMem<WAVEFORMATEX> format; |
| 298 // if the device will be opened in exclusive mode, then the application | 554 HRESULT hr = GetMixFormat(device_role, &format); |
| 299 // specified format is used instead. However, the result of this method can | 555 if (FAILED(hr)) |
| 300 // be useful for testing purposes so we don't DCHECK here. | 556 return 0; |
| 301 DLOG_IF(WARNING, GetShareMode() == AUDCLNT_SHAREMODE_EXCLUSIVE) << | |
| 302 "The mixing sample rate will be ignored for exclusive-mode streams."; | |
| 303 | 557 |
| 304 // It is assumed that this static method is called from a COM thread, i.e., | 558 DVLOG(2) << "nSamplesPerSec: " << format->nSamplesPerSec; |
| 305 // CoInitializeEx() is not called here again to avoid STA/MTA conflicts. | 559 return static_cast<int>(format->nSamplesPerSec); |
| 306 ScopedComPtr<IMMDeviceEnumerator> enumerator; | |
| 307 HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), | |
| 308 NULL, | |
| 309 CLSCTX_INPROC_SERVER, | |
| 310 __uuidof(IMMDeviceEnumerator), | |
| 311 enumerator.ReceiveVoid()); | |
| 312 if (FAILED(hr)) { | |
| 313 NOTREACHED() << "error code: " << std::hex << hr; | |
| 314 return 0.0; | |
| 315 } | |
| 316 | |
| 317 ScopedComPtr<IMMDevice> endpoint_device; | |
| 318 hr = enumerator->GetDefaultAudioEndpoint(eRender, | |
| 319 device_role, | |
| 320 endpoint_device.Receive()); | |
| 321 if (FAILED(hr)) { | |
| 322 // This will happen if there's no audio output device found or available | |
| 323 // (e.g. some audio cards that have outputs will still report them as | |
| 324 // "not found" when no speaker is plugged into the output jack). | |
| 325 LOG(WARNING) << "No audio end point: " << std::hex << hr; | |
| 326 return 0.0; | |
| 327 } | |
| 328 | |
| 329 ScopedComPtr<IAudioClient> audio_client; | |
| 330 hr = endpoint_device->Activate(__uuidof(IAudioClient), | |
| 331 CLSCTX_INPROC_SERVER, | |
| 332 NULL, | |
| 333 audio_client.ReceiveVoid()); | |
| 334 if (FAILED(hr)) { | |
| 335 NOTREACHED() << "error code: " << std::hex << hr; | |
| 336 return 0.0; | |
| 337 } | |
| 338 | |
| 339 // Retrieve the stream format that the audio engine uses for its internal | |
| 340 // processing of shared-mode streams. | |
| 341 base::win::ScopedCoMem<WAVEFORMATEX> audio_engine_mix_format; | |
| 342 hr = audio_client->GetMixFormat(&audio_engine_mix_format); | |
| 343 if (FAILED(hr)) { | |
| 344 NOTREACHED() << "error code: " << std::hex << hr; | |
| 345 return 0.0; | |
| 346 } | |
| 347 | |
| 348 return static_cast<int>(audio_engine_mix_format->nSamplesPerSec); | |
| 349 } | 560 } |
| 350 | 561 |
| 351 void WASAPIAudioOutputStream::Run() { | 562 void WASAPIAudioOutputStream::Run() { |
| 352 ScopedCOMInitializer com_init(ScopedCOMInitializer::kMTA); | 563 ScopedCOMInitializer com_init(ScopedCOMInitializer::kMTA); |
| 353 | 564 |
| 354 // Increase the thread priority. | 565 // Increase the thread priority. |
| 355 render_thread_->SetThreadPriority(base::kThreadPriority_RealtimeAudio); | 566 render_thread_->SetThreadPriority(base::kThreadPriority_RealtimeAudio); |
| 356 | 567 |
| 357 // Enable MMCSS to ensure that this thread receives prioritized access to | 568 // Enable MMCSS to ensure that this thread receives prioritized access to |
| 358 // CPU resources. | 569 // CPU resources. |
| (...skipping 60 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 419 { | 630 { |
| 420 // |audio_samples_render_event_| has been set. | 631 // |audio_samples_render_event_| has been set. |
| 421 UINT32 num_queued_frames = 0; | 632 UINT32 num_queued_frames = 0; |
| 422 uint8* audio_data = NULL; | 633 uint8* audio_data = NULL; |
| 423 | 634 |
| 424 // Contains how much new data we can write to the buffer without | 635 // Contains how much new data we can write to the buffer without |
| 425 // the risk of overwriting previously written data that the audio | 636 // the risk of overwriting previously written data that the audio |
| 426 // engine has not yet read from the buffer. | 637 // engine has not yet read from the buffer. |
| 427 size_t num_available_frames = 0; | 638 size_t num_available_frames = 0; |
| 428 | 639 |
| 429 if (share_mode() == AUDCLNT_SHAREMODE_SHARED) { | 640 if (share_mode_ == AUDCLNT_SHAREMODE_SHARED) { |
| 430 // Get the padding value which represents the amount of rendering | 641 // Get the padding value which represents the amount of rendering |
| 431 // data that is queued up to play in the endpoint buffer. | 642 // data that is queued up to play in the endpoint buffer. |
| 432 hr = audio_client_->GetCurrentPadding(&num_queued_frames); | 643 hr = audio_client_->GetCurrentPadding(&num_queued_frames); |
| 433 num_available_frames = | 644 num_available_frames = |
| 434 endpoint_buffer_size_frames_ - num_queued_frames; | 645 endpoint_buffer_size_frames_ - num_queued_frames; |
| 435 } else { | 646 } else { |
| 436 // While the stream is running, the system alternately sends one | 647 // While the stream is running, the system alternately sends one |
| 437 // buffer or the other to the client. This form of double buffering | 648 // buffer or the other to the client. This form of double buffering |
| 438 // is referred to as "ping-ponging". Each time the client receives | 649 // is referred to as "ping-ponging". Each time the client receives |
| 439 // a buffer from the system (triggers this event) the client must | 650 // a buffer from the system (triggers this event) the client must |
| (...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 471 // a render event and the time when the first audio sample in a | 682 // a render event and the time when the first audio sample in a |
| 472 // packet is played out through the speaker. This delay value | 683 // packet is played out through the speaker. This delay value |
| 473 // can typically be utilized by an acoustic echo-control (AEC) | 684 // can typically be utilized by an acoustic echo-control (AEC) |
| 474 // unit at the render side. | 685 // unit at the render side. |
| 475 UINT64 position = 0; | 686 UINT64 position = 0; |
| 476 int audio_delay_bytes = 0; | 687 int audio_delay_bytes = 0; |
| 477 hr = audio_clock->GetPosition(&position, NULL); | 688 hr = audio_clock->GetPosition(&position, NULL); |
| 478 if (SUCCEEDED(hr)) { | 689 if (SUCCEEDED(hr)) { |
| 479 // Stream position of the sample that is currently playing | 690 // Stream position of the sample that is currently playing |
| 480 // through the speaker. | 691 // through the speaker. |
| 481 double pos_sample_playing_frames = format_.nSamplesPerSec * | 692 double pos_sample_playing_frames = format_.Format.nSamplesPerSec * |
| 482 (static_cast<double>(position) / device_frequency); | 693 (static_cast<double>(position) / device_frequency); |
| 483 | 694 |
| 484 // Stream position of the last sample written to the endpoint | 695 // Stream position of the last sample written to the endpoint |
| 485 // buffer. Note that, the packet we are about to receive in | 696 // buffer. Note that, the packet we are about to receive in |
| 486 // the upcoming callback is also included. | 697 // the upcoming callback is also included. |
| 487 size_t pos_last_sample_written_frames = | 698 size_t pos_last_sample_written_frames = |
| 488 num_written_frames_ + packet_size_frames_; | 699 num_written_frames_ + packet_size_frames_; |
| 489 | 700 |
| 490 // Derive the actual delay value which will be fed to the | 701 // Derive the actual delay value which will be fed to the |
| 491 // render client using the OnMoreData() callback. | 702 // render client using the OnMoreData() callback. |
| 492 audio_delay_bytes = (pos_last_sample_written_frames - | 703 audio_delay_bytes = (pos_last_sample_written_frames - |
| 493 pos_sample_playing_frames) * frame_size_; | 704 pos_sample_playing_frames) * frame_size_; |
| 494 } | 705 } |
| 495 | 706 |
| 496 // Read a data packet from the registered client source and | 707 // Read a data packet from the registered client source and |
| 497 // deliver a delay estimate in the same callback to the client. | 708 // deliver a delay estimate in the same callback to the client. |
| 498 // A time stamp is also stored in the AudioBuffersState. This | 709 // A time stamp is also stored in the AudioBuffersState. This |
| 499 // time stamp can be used at the client side to compensate for | 710 // time stamp can be used at the client side to compensate for |
| 500 // the delay between the usage of the delay value and the time | 711 // the delay between the usage of the delay value and the time |
| 501 // of generation. | 712 // of generation. |
| 502 uint32 num_filled_bytes = source_->OnMoreData( | |
| 503 audio_data, packet_size_bytes_, | |
| 504 AudioBuffersState(0, audio_delay_bytes)); | |
| 505 | 713 |
| 506 // Perform in-place, software-volume adjustments. | 714 // TODO(henrika): improve comments about possible upmixing here... |
| 507 media::AdjustVolume(audio_data, | |
| 508 num_filled_bytes, | |
| 509 format_.nChannels, | |
| 510 format_.wBitsPerSample >> 3, | |
| 511 volume_); | |
| 512 | 715 |
| 513 // Zero out the part of the packet which has not been filled by | 716 uint32 num_filled_bytes = 0; |
| 514 // the client. Using silence is the least bad option in this | 717 |
| 515 // situation. | 718 if (channel_factor() == 1) { |
| 516 if (num_filled_bytes < packet_size_bytes_) { | 719 // Case I: no up-mixing. |
| 517 memset(&audio_data[num_filled_bytes], 0, | 720 num_filled_bytes = source_->OnMoreData( |
| 518 (packet_size_bytes_ - num_filled_bytes)); | 721 audio_data, packet_size_bytes_, |
| 722 AudioBuffersState(0, audio_delay_bytes)); | |
| 723 | |
| 724 // Perform in-place, software-volume adjustments. | |
| 725 media::AdjustVolume(audio_data, | |
| 726 num_filled_bytes, | |
| 727 format_.Format.nChannels, | |
| 728 format_.Format.wBitsPerSample >> 3, | |
| 729 volume_); | |
| 730 | |
| 731 // Zero out the part of the packet which has not been filled by | |
| 732 // the client. Using silence is the least bad option in this | |
| 733 // situation. | |
| 734 if (num_filled_bytes < packet_size_bytes_) { | |
| 735 memset(&audio_data[num_filled_bytes], 0, | |
| 736 (packet_size_bytes_ - num_filled_bytes)); | |
| 737 } | |
| 738 } else { | |
| 739 // Case II: up-mixing. | |
| 740 const int audio_source_size_bytes = | |
| 741 packet_size_bytes_ / channel_factor(); | |
| 742 scoped_array<uint8> buffer; | |
| 743 buffer.reset(new uint8[audio_source_size_bytes]); | |
| 744 | |
| 745 num_filled_bytes = source_->OnMoreData( | |
| 746 buffer.get(), audio_source_size_bytes, | |
| 747 AudioBuffersState(0, audio_delay_bytes)); | |
| 748 | |
| 749 ChannelUpMix(buffer.get(), | |
| 750 &audio_data[0], | |
| 751 client_channel_count_, | |
| 752 endpoint_channel_count(), | |
| 753 num_filled_bytes); | |
| 754 | |
| 755 // TODO(henrika): take care of zero-out for this case as well. | |
| 519 } | 756 } |
| 520 | 757 |
| 521 // Release the buffer space acquired in the GetBuffer() call. | 758 // Release the buffer space acquired in the GetBuffer() call. |
| 522 DWORD flags = 0; | 759 DWORD flags = 0; |
| 523 audio_render_client_->ReleaseBuffer(packet_size_frames_, | 760 audio_render_client_->ReleaseBuffer(packet_size_frames_, |
| 524 flags); | 761 flags); |
| 525 | 762 |
| 526 num_written_frames_ += packet_size_frames_; | 763 num_written_frames_ += packet_size_frames_; |
| 527 } | 764 } |
| 528 } | 765 } |
| (...skipping 69 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 598 // Creates and activates an IAudioClient COM object given the selected | 835 // Creates and activates an IAudioClient COM object given the selected |
| 599 // render endpoint device. | 836 // render endpoint device. |
| 600 HRESULT hr = endpoint_device_->Activate(__uuidof(IAudioClient), | 837 HRESULT hr = endpoint_device_->Activate(__uuidof(IAudioClient), |
| 601 CLSCTX_INPROC_SERVER, | 838 CLSCTX_INPROC_SERVER, |
| 602 NULL, | 839 NULL, |
| 603 audio_client.ReceiveVoid()); | 840 audio_client.ReceiveVoid()); |
| 604 if (SUCCEEDED(hr)) { | 841 if (SUCCEEDED(hr)) { |
| 605 // Retrieve the stream format that the audio engine uses for its internal | 842 // Retrieve the stream format that the audio engine uses for its internal |
| 606 // processing/mixing of shared-mode streams. | 843 // processing/mixing of shared-mode streams. |
| 607 audio_engine_mix_format_.Reset(NULL); | 844 audio_engine_mix_format_.Reset(NULL); |
| 608 hr = audio_client->GetMixFormat(&audio_engine_mix_format_); | 845 hr = audio_client->GetMixFormat( |
| 846 reinterpret_cast<WAVEFORMATEX**>(&audio_engine_mix_format_)); | |
| 609 | 847 |
| 610 if (SUCCEEDED(hr)) { | 848 if (SUCCEEDED(hr)) { |
| 611 audio_client_ = audio_client; | 849 audio_client_ = audio_client; |
| 612 } | 850 } |
| 613 } | 851 } |
| 614 | 852 |
| 615 return hr; | 853 return hr; |
| 616 } | 854 } |
| 617 | 855 |
| 618 bool WASAPIAudioOutputStream::DesiredFormatIsSupported() { | 856 bool WASAPIAudioOutputStream::DesiredFormatIsSupported() { |
| 619 // Determine, before calling IAudioClient::Initialize(), whether the audio | 857 // Determine, before calling IAudioClient::Initialize(), whether the audio |
| 620 // engine supports a particular stream format. | 858 // engine supports a particular stream format. |
| 621 // In shared mode, the audio engine always supports the mix format, | 859 // In shared mode, the audio engine always supports the mix format, |
| 622 // which is stored in the |audio_engine_mix_format_| member and it is also | 860 // which is stored in the |audio_engine_mix_format_| member and it is also |
| 623 // possible to receive a proposed (closest) format if the current format is | 861 // possible to receive a proposed (closest) format if the current format is |
| 624 // not supported. | 862 // not supported. |
| 625 base::win::ScopedCoMem<WAVEFORMATEX> closest_match; | 863 base::win::ScopedCoMem<WAVEFORMATEXTENSIBLE> closest_match; |
| 626 HRESULT hr = audio_client_->IsFormatSupported(share_mode(), | 864 HRESULT hr = audio_client_->IsFormatSupported( |
| 627 &format_, | 865 share_mode_, reinterpret_cast<WAVEFORMATEX*>(&format_), |
| 628 &closest_match); | 866 reinterpret_cast<WAVEFORMATEX**>(&closest_match)); |
| 629 | 867 |
| 630 // This log can only be triggered for shared mode. | 868 // This log can only be triggered for shared mode. |
| 631 DLOG_IF(ERROR, hr == S_FALSE) << "Format is not supported " | 869 DLOG_IF(ERROR, hr == S_FALSE) << "Format is not supported " |
| 632 << "but a closest match exists."; | 870 << "but a closest match exists."; |
| 633 // This log can be triggered both for shared and exclusive modes. | 871 // This log can be triggered both for shared and exclusive modes. |
| 634 DLOG_IF(ERROR, hr == AUDCLNT_E_UNSUPPORTED_FORMAT) << "Unsupported format."; | 872 DLOG_IF(ERROR, hr == AUDCLNT_E_UNSUPPORTED_FORMAT) << "Unsupported format."; |
| 635 if (hr == S_FALSE) { | 873 if (hr == S_FALSE) { |
| 636 DVLOG(1) << "wFormatTag : " << closest_match->wFormatTag; | 874 DVLOG(1) << "wFormatTag : " << closest_match->Format.wFormatTag; |
| 637 DVLOG(1) << "nChannels : " << closest_match->nChannels; | 875 DVLOG(1) << "nChannels : " << closest_match->Format.nChannels; |
| 638 DVLOG(1) << "nSamplesPerSec: " << closest_match->nSamplesPerSec; | 876 DVLOG(1) << "nSamplesPerSec: " << closest_match->Format.nSamplesPerSec; |
| 639 DVLOG(1) << "wBitsPerSample: " << closest_match->wBitsPerSample; | 877 DVLOG(1) << "wBitsPerSample: " << closest_match->Format.wBitsPerSample; |
| 640 } | 878 } |
| 641 | 879 |
| 642 return (hr == S_OK); | 880 return (hr == S_OK); |
| 643 } | 881 } |
| 644 | 882 |
| 645 HRESULT WASAPIAudioOutputStream::InitializeAudioEngine() { | 883 HRESULT WASAPIAudioOutputStream::InitializeAudioEngine() { |
| 646 #if !defined(NDEBUG) | 884 #if !defined(NDEBUG) |
| 647 // The period between processing passes by the audio engine is fixed for a | 885 // The period between processing passes by the audio engine is fixed for a |
| 648 // particular audio endpoint device and represents the smallest processing | 886 // particular audio endpoint device and represents the smallest processing |
| 649 // quantum for the audio engine. This period plus the stream latency between | 887 // quantum for the audio engine. This period plus the stream latency between |
| (...skipping 21 matching lines...) Expand all Loading... | |
| 671 DVLOG(1) << "stream latency: " << static_cast<double>(latency / 10000.0) | 909 DVLOG(1) << "stream latency: " << static_cast<double>(latency / 10000.0) |
| 672 << " [ms]"; | 910 << " [ms]"; |
| 673 } | 911 } |
| 674 } | 912 } |
| 675 #endif | 913 #endif |
| 676 | 914 |
| 677 HRESULT hr = S_FALSE; | 915 HRESULT hr = S_FALSE; |
| 678 | 916 |
| 679 // Perform different initialization depending on if the device shall be | 917 // Perform different initialization depending on if the device shall be |
| 680 // opened in shared mode or in exclusive mode. | 918 // opened in shared mode or in exclusive mode. |
| 681 hr = (share_mode() == AUDCLNT_SHAREMODE_SHARED) ? | 919 hr = (share_mode_ == AUDCLNT_SHAREMODE_SHARED) ? |
| 682 SharedModeInitialization() : ExclusiveModeInitialization(); | 920 SharedModeInitialization() : ExclusiveModeInitialization(); |
| 683 if (FAILED(hr)) { | 921 if (FAILED(hr)) { |
| 684 LOG(WARNING) << "IAudioClient::Initialize() failed: " << std::hex << hr; | 922 LOG(WARNING) << "IAudioClient::Initialize() failed: " << std::hex << hr; |
| 685 return hr; | 923 return hr; |
| 686 } | 924 } |
| 687 | 925 |
| 688 // Retrieve the length of the endpoint buffer. The buffer length represents | 926 // Retrieve the length of the endpoint buffer. The buffer length represents |
| 689 // the maximum amount of rendering data that the client can write to | 927 // the maximum amount of rendering data that the client can write to |
| 690 // the endpoint buffer during a single processing pass. | 928 // the endpoint buffer during a single processing pass. |
| 691 // A typical value is 960 audio frames <=> 20ms @ 48kHz sample rate. | 929 // A typical value is 960 audio frames <=> 20ms @ 48kHz sample rate. |
| 692 hr = audio_client_->GetBufferSize(&endpoint_buffer_size_frames_); | 930 hr = audio_client_->GetBufferSize(&endpoint_buffer_size_frames_); |
| 693 if (FAILED(hr)) | 931 if (FAILED(hr)) |
| 694 return hr; | 932 return hr; |
| 695 DVLOG(1) << "endpoint buffer size: " << endpoint_buffer_size_frames_ | 933 DVLOG(1) << "endpoint buffer size: " << endpoint_buffer_size_frames_ |
| 696 << " [frames]"; | 934 << " [frames]"; |
| 697 | 935 |
| 698 // The buffer scheme for exclusive mode streams is not designed for max | 936 // The buffer scheme for exclusive mode streams is not designed for max |
| 699 // flexibility. We only allow a "perfect match" between the packet size set | 937 // flexibility. We only allow a "perfect match" between the packet size set |
| 700 // by the user and the actual endpoint buffer size. | 938 // by the user and the actual endpoint buffer size. |
| 701 if (share_mode() == AUDCLNT_SHAREMODE_EXCLUSIVE && | 939 if (share_mode_ == AUDCLNT_SHAREMODE_EXCLUSIVE && |
| 702 endpoint_buffer_size_frames_ != packet_size_frames_) { | 940 endpoint_buffer_size_frames_ != packet_size_frames_) { |
| 703 hr = AUDCLNT_E_INVALID_SIZE; | 941 hr = AUDCLNT_E_INVALID_SIZE; |
| 704 DLOG(ERROR) << "AUDCLNT_E_INVALID_SIZE"; | 942 DLOG(ERROR) << "AUDCLNT_E_INVALID_SIZE"; |
| 705 return hr; | 943 return hr; |
| 706 } | 944 } |
| 707 | 945 |
| 708 // Set the event handle that the audio engine will signal each time | 946 // Set the event handle that the audio engine will signal each time |
| 709 // a buffer becomes ready to be processed by the client. | 947 // a buffer becomes ready to be processed by the client. |
| 710 hr = audio_client_->SetEventHandle(audio_samples_render_event_.Get()); | 948 hr = audio_client_->SetEventHandle(audio_samples_render_event_.Get()); |
| 711 if (FAILED(hr)) | 949 if (FAILED(hr)) |
| 712 return hr; | 950 return hr; |
| 713 | 951 |
| 714 // Get access to the IAudioRenderClient interface. This interface | 952 // Get access to the IAudioRenderClient interface. This interface |
| 715 // enables us to write output data to a rendering endpoint buffer. | 953 // enables us to write output data to a rendering endpoint buffer. |
| 716 // The methods in this interface manage the movement of data packets | 954 // The methods in this interface manage the movement of data packets |
| 717 // that contain audio-rendering data. | 955 // that contain audio-rendering data. |
| 718 hr = audio_client_->GetService(__uuidof(IAudioRenderClient), | 956 hr = audio_client_->GetService(__uuidof(IAudioRenderClient), |
| 719 audio_render_client_.ReceiveVoid()); | 957 audio_render_client_.ReceiveVoid()); |
| 720 return hr; | 958 return hr; |
| 721 } | 959 } |
| 722 | 960 |
| 723 HRESULT WASAPIAudioOutputStream::SharedModeInitialization() { | 961 HRESULT WASAPIAudioOutputStream::SharedModeInitialization() { |
| 724 DCHECK_EQ(share_mode(), AUDCLNT_SHAREMODE_SHARED); | 962 DCHECK_EQ(share_mode_, AUDCLNT_SHAREMODE_SHARED); |
| 725 | 963 |
| 726 // TODO(henrika): this buffer scheme is still under development. | 964 // TODO(henrika): this buffer scheme is still under development. |
| 727 // The exact details are yet to be determined based on tests with different | 965 // The exact details are yet to be determined based on tests with different |
| 728 // audio clients. | 966 // audio clients. |
| 729 int glitch_free_buffer_size_ms = static_cast<int>(packet_size_ms_ + 0.5); | 967 int glitch_free_buffer_size_ms = static_cast<int>(packet_size_ms_ + 0.5); |
| 730 if (audio_engine_mix_format_->nSamplesPerSec == 48000) { | 968 if (audio_engine_mix_format_->Format.nSamplesPerSec == 48000) { |
| 731 // Initial tests have shown that we have to add 10 ms extra to | 969 // Initial tests have shown that we have to add 10 ms extra to |
| 732 // ensure that we don't run empty for any packet size. | 970 // ensure that we don't run empty for any packet size. |
| 733 glitch_free_buffer_size_ms += 10; | 971 glitch_free_buffer_size_ms += 10; |
| 734 } else if (audio_engine_mix_format_->nSamplesPerSec == 44100) { | 972 } else if (audio_engine_mix_format_->Format.nSamplesPerSec == 44100) { |
| 735 // Initial tests have shown that we have to add 20 ms extra to | 973 // Initial tests have shown that we have to add 20 ms extra to |
| 736 // ensure that we don't run empty for any packet size. | 974 // ensure that we don't run empty for any packet size. |
| 737 glitch_free_buffer_size_ms += 20; | 975 glitch_free_buffer_size_ms += 20; |
| 738 } else { | 976 } else { |
| 739 glitch_free_buffer_size_ms += 20; | 977 glitch_free_buffer_size_ms += 20; |
| 740 } | 978 } |
| 741 DVLOG(1) << "glitch_free_buffer_size_ms: " << glitch_free_buffer_size_ms; | 979 DVLOG(1) << "glitch_free_buffer_size_ms: " << glitch_free_buffer_size_ms; |
| 742 REFERENCE_TIME requested_buffer_duration = | 980 REFERENCE_TIME requested_buffer_duration = |
| 743 static_cast<REFERENCE_TIME>(glitch_free_buffer_size_ms * 10000); | 981 static_cast<REFERENCE_TIME>(glitch_free_buffer_size_ms * 10000); |
| 744 | 982 |
| 745 // Initialize the audio stream between the client and the device. | 983 // Initialize the audio stream between the client and the device. |
| 746 // We connect indirectly through the audio engine by using shared mode | 984 // We connect indirectly through the audio engine by using shared mode |
| 747 // and WASAPI is initialized in an event driven mode. | 985 // and WASAPI is initialized in an event driven mode. |
| 748 // Note that this API ensures that the buffer is never smaller than the | 986 // Note that this API ensures that the buffer is never smaller than the |
| 749 // minimum buffer size needed to ensure glitch-free rendering. | 987 // minimum buffer size needed to ensure glitch-free rendering. |
| 750 // If we requests a buffer size that is smaller than the audio engine's | 988 // If we requests a buffer size that is smaller than the audio engine's |
| 751 // minimum required buffer size, the method sets the buffer size to this | 989 // minimum required buffer size, the method sets the buffer size to this |
| 752 // minimum buffer size rather than to the buffer size requested. | 990 // minimum buffer size rather than to the buffer size requested. |
| 753 HRESULT hr = audio_client_->Initialize(AUDCLNT_SHAREMODE_SHARED, | 991 HRESULT hr = audio_client_->Initialize(AUDCLNT_SHAREMODE_SHARED, |
| 754 AUDCLNT_STREAMFLAGS_EVENTCALLBACK | | 992 AUDCLNT_STREAMFLAGS_EVENTCALLBACK | |
| 755 AUDCLNT_STREAMFLAGS_NOPERSIST, | 993 AUDCLNT_STREAMFLAGS_NOPERSIST, |
| 756 requested_buffer_duration, | 994 requested_buffer_duration, |
| 757 0, | 995 0, |
| 758 &format_, | 996 reinterpret_cast<WAVEFORMATEX*>(&format _), |
| 759 NULL); | 997 NULL); |
| 760 return hr; | 998 return hr; |
| 761 } | 999 } |
| 762 | 1000 |
| 763 HRESULT WASAPIAudioOutputStream::ExclusiveModeInitialization() { | 1001 HRESULT WASAPIAudioOutputStream::ExclusiveModeInitialization() { |
| 764 DCHECK_EQ(share_mode(), AUDCLNT_SHAREMODE_EXCLUSIVE); | 1002 DCHECK_EQ(share_mode_, AUDCLNT_SHAREMODE_EXCLUSIVE); |
| 765 | 1003 |
| 766 float f = (1000.0 * packet_size_frames_) / format_.nSamplesPerSec; | 1004 float f = (1000.0 * packet_size_frames_) / format_.Format.nSamplesPerSec; |
| 767 REFERENCE_TIME requested_buffer_duration = | 1005 REFERENCE_TIME requested_buffer_duration = |
| 768 static_cast<REFERENCE_TIME>(f * 10000.0 + 0.5); | 1006 static_cast<REFERENCE_TIME>(f * 10000.0 + 0.5); |
| 769 | 1007 |
| 770 // Initialize the audio stream between the client and the device. | 1008 // Initialize the audio stream between the client and the device. |
| 771 // For an exclusive-mode stream that uses event-driven buffering, the | 1009 // For an exclusive-mode stream that uses event-driven buffering, the |
| 772 // caller must specify nonzero values for hnsPeriodicity and | 1010 // caller must specify nonzero values for hnsPeriodicity and |
| 773 // hnsBufferDuration, and the values of these two parameters must be equal. | 1011 // hnsBufferDuration, and the values of these two parameters must be equal. |
| 774 // The Initialize method allocates two buffers for the stream. Each buffer | 1012 // The Initialize method allocates two buffers for the stream. Each buffer |
| 775 // is equal in duration to the value of the hnsBufferDuration parameter. | 1013 // is equal in duration to the value of the hnsBufferDuration parameter. |
| 776 // Following the Initialize call for a rendering stream, the caller should | 1014 // Following the Initialize call for a rendering stream, the caller should |
| 777 // fill the first of the two buffers before starting the stream. | 1015 // fill the first of the two buffers before starting the stream. |
| 778 HRESULT hr = audio_client_->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, | 1016 HRESULT hr = audio_client_->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, |
| 779 AUDCLNT_STREAMFLAGS_EVENTCALLBACK | | 1017 AUDCLNT_STREAMFLAGS_EVENTCALLBACK | |
| 780 AUDCLNT_STREAMFLAGS_NOPERSIST, | 1018 AUDCLNT_STREAMFLAGS_NOPERSIST, |
| 781 requested_buffer_duration, | 1019 requested_buffer_duration, |
| 782 requested_buffer_duration, | 1020 requested_buffer_duration, |
| 783 &format_, | 1021 reinterpret_cast<WAVEFORMATEX*>(&format _), |
| 784 NULL); | 1022 NULL); |
| 785 if (FAILED(hr)) { | 1023 if (FAILED(hr)) { |
| 786 if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) { | 1024 if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) { |
| 787 LOG(ERROR) << "AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED"; | 1025 LOG(ERROR) << "AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED"; |
| 788 | 1026 |
| 789 UINT32 aligned_buffer_size = 0; | 1027 UINT32 aligned_buffer_size = 0; |
| 790 audio_client_->GetBufferSize(&aligned_buffer_size); | 1028 audio_client_->GetBufferSize(&aligned_buffer_size); |
| 791 DVLOG(1) << "Use aligned buffer size instead: " << aligned_buffer_size; | 1029 DVLOG(1) << "Use aligned buffer size instead: " << aligned_buffer_size; |
| 792 audio_client_.Release(); | 1030 audio_client_.Release(); |
| 793 | 1031 |
| 794 // Calculate new aligned periodicity. Each unit of reference time | 1032 // Calculate new aligned periodicity. Each unit of reference time |
| 795 // is 100 nanoseconds. | 1033 // is 100 nanoseconds. |
| 796 REFERENCE_TIME aligned_buffer_duration = static_cast<REFERENCE_TIME>( | 1034 REFERENCE_TIME aligned_buffer_duration = static_cast<REFERENCE_TIME>( |
| 797 (10000000.0 * aligned_buffer_size / format_.nSamplesPerSec) + 0.5); | 1035 (10000000.0 * aligned_buffer_size / format_.Format.nSamplesPerSec) |
| 1036 + 0.5); | |
| 798 | 1037 |
| 799 // It is possible to re-activate and re-initialize the audio client | 1038 // It is possible to re-activate and re-initialize the audio client |
| 800 // at this stage but we bail out with an error code instead and | 1039 // at this stage but we bail out with an error code instead and |
| 801 // combine it with a log message which informs about the suggested | 1040 // combine it with a log message which informs about the suggested |
| 802 // aligned buffer size which should be used instead. | 1041 // aligned buffer size which should be used instead. |
| 803 DVLOG(1) << "aligned_buffer_duration: " | 1042 DVLOG(1) << "aligned_buffer_duration: " |
| 804 << static_cast<double>(aligned_buffer_duration / 10000.0) | 1043 << static_cast<double>(aligned_buffer_duration / 10000.0) |
| 805 << " [ms]"; | 1044 << " [ms]"; |
| 806 } else if (hr == AUDCLNT_E_INVALID_DEVICE_PERIOD) { | 1045 } else if (hr == AUDCLNT_E_INVALID_DEVICE_PERIOD) { |
| 807 // We will get this error if we try to use a smaller buffer size than | 1046 // We will get this error if we try to use a smaller buffer size than |
| (...skipping 19 matching lines...) Expand all Loading... | |
| 827 NOTREACHED() << "IMMNotificationClient should not use this method."; | 1066 NOTREACHED() << "IMMNotificationClient should not use this method."; |
| 828 if (iid == IID_IUnknown || iid == __uuidof(IMMNotificationClient)) { | 1067 if (iid == IID_IUnknown || iid == __uuidof(IMMNotificationClient)) { |
| 829 *object = static_cast < IMMNotificationClient*>(this); | 1068 *object = static_cast < IMMNotificationClient*>(this); |
| 830 } else { | 1069 } else { |
| 831 return E_NOINTERFACE; | 1070 return E_NOINTERFACE; |
| 832 } | 1071 } |
| 833 return S_OK; | 1072 return S_OK; |
| 834 } | 1073 } |
| 835 | 1074 |
| 836 STDMETHODIMP WASAPIAudioOutputStream::OnDeviceStateChanged(LPCWSTR device_id, | 1075 STDMETHODIMP WASAPIAudioOutputStream::OnDeviceStateChanged(LPCWSTR device_id, |
| 837 DWORD new_state) { | 1076 DWORD new_state) { |
| 838 #ifndef NDEBUG | 1077 #ifndef NDEBUG |
| 839 std::string device_name = GetDeviceName(device_id); | 1078 std::string device_name = GetDeviceName(device_id); |
| 840 std::string device_state; | 1079 std::string device_state; |
| 841 | 1080 |
| 842 switch (new_state) { | 1081 switch (new_state) { |
| 843 case DEVICE_STATE_ACTIVE: | 1082 case DEVICE_STATE_ACTIVE: |
| 844 device_state = "ACTIVE"; | 1083 device_state = "ACTIVE"; |
| 845 break; | 1084 break; |
| 846 case DEVICE_STATE_DISABLED: | 1085 case DEVICE_STATE_DISABLED: |
| 847 device_state = "DISABLED"; | 1086 device_state = "DISABLED"; |
| (...skipping 123 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 971 // are now re-initiated and it is now possible to re-start audio rendering. | 1210 // are now re-initiated and it is now possible to re-start audio rendering. |
| 972 | 1211 |
| 973 // Start rendering again using the new default audio endpoint. | 1212 // Start rendering again using the new default audio endpoint. |
| 974 hr = audio_client_->Start(); | 1213 hr = audio_client_->Start(); |
| 975 | 1214 |
| 976 restart_rendering_mode_ = false; | 1215 restart_rendering_mode_ = false; |
| 977 return SUCCEEDED(hr); | 1216 return SUCCEEDED(hr); |
| 978 } | 1217 } |
| 979 | 1218 |
| 980 } // namespace media | 1219 } // namespace media |
| OLD | NEW |