Debian Codegraph @

Source/Core/AudioCommon/WASAPIStream.cpp

raw symbols SCIP
1 // Copyright 2018 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "AudioCommon/WASAPIStream.h"
5
6 #ifdef _WIN32
7
8 // clang-format off
9 #include <initguid.h>
10 #include <Audioclient.h>
11 #include <mmdeviceapi.h>
12 #include <functiondiscoverykeys_devpkey.h>
13 #include <wil/resource.h>
14 // clang-format on
15
16 #include <thread>
17
18 #include "Common/Assert.h"
19 #include "Common/HRWrap.h"
20 #include "Common/Logging/Log.h"
21 #include "Common/StringUtil.h"
22 #include "Common/Thread.h"
23 #include "Core/Config/MainSettings.h"
24 #include "VideoCommon/OnScreenDisplay.h"
25
26 using Microsoft::WRL::ComPtr;
27
28 WASAPIStream::WASAPIStream()
29 {
30 if (SUCCEEDED(CoInitializeEx(nullptr, COINIT_MULTITHREADED)))
31 m_coinitialize.activate();
32
33 m_format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
34 m_format.Format.nChannels = 2;
35 m_format.Format.nSamplesPerSec = GetMixer()->GetSampleRate();
36 m_format.Format.nAvgBytesPerSec = m_format.Format.nSamplesPerSec * 4;
37 m_format.Format.nBlockAlign = 4;
38 m_format.Format.wBitsPerSample = 16;
39 m_format.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
40 m_format.Samples.wValidBitsPerSample = m_format.Format.wBitsPerSample;
41 m_format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
42 m_format.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
43 }
44
45 WASAPIStream::~WASAPIStream()
46 {
47 m_running.store(false, std::memory_order_relaxed);
48 if (m_thread.joinable())
49 m_thread.join();
50 }
51
52 bool WASAPIStream::IsValid()
53 {
54 return true;
55 }
56
57 static bool HandleWinAPI(std::string_view message, HRESULT result)
58 {
59 if (FAILED(result))
60 {
61 std::string error;
62
63 switch (result)
64 {
65 case AUDCLNT_E_DEVICE_IN_USE:
66 error = "Audio endpoint already in use!";
67 break;
68 default:
69 error = Common::GetHResultMessage(result);
70 break;
71 }
72
73 ERROR_LOG_FMT(AUDIO, "WASAPI: {}: {} ({:08x})", message, error, result);
74 }
75
76 return SUCCEEDED(result);
77 }
78
79 static void ForEachNamedDevice(const std::function<bool(ComPtr<IMMDevice>, std::string)>& callback)
80 {
81 HRESULT result = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
82 // RPC_E_CHANGED_MODE means that thread has COM already initialized with a different threading
83 // model. We don't necessarily need multithreaded model here, so don't treat this as an error
84 if (result != RPC_E_CHANGED_MODE && !HandleWinAPI("Failed to call CoInitialize", result))
85 return;
86
87 wil::unique_couninitialize_call cleanup;
88 if (FAILED(result))
89 cleanup.release(); // CoUninitialize must be matched with each successful CoInitialize call, so
90 // don't call it if initialize fails
91
92 ComPtr<IMMDeviceEnumerator> enumerator;
93
94 result = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC_SERVER,
95 IID_PPV_ARGS(&enumerator));
96
97 if (!HandleWinAPI("Failed to create MMDeviceEnumerator", result))
98 return;
99
100 ComPtr<IMMDeviceCollection> devices;
101 result = enumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &devices);
102
103 if (!HandleWinAPI("Failed to get available devices", result))
104 return;
105
106 UINT count;
107 devices->GetCount(&count);
108
109 for (u32 i = 0; i < count; i++)
110 {
111 ComPtr<IMMDevice> device;
112 devices->Item(i, &device);
113 if (!HandleWinAPI("Failed to get device " + std::to_string(i), result))
114 continue;
115
116 ComPtr<IPropertyStore> device_properties;
117
118 result = device->OpenPropertyStore(STGM_READ, &device_properties);
119
120 if (!HandleWinAPI("Failed to initialize IPropertyStore", result))
121 continue;
122
123 wil::unique_prop_variant device_name;
124 device_properties->GetValue(PKEY_Device_FriendlyName, device_name.addressof());
125
126 if (!callback(std::move(device), TStrToUTF8(device_name.pwszVal)))
127 break;
128 }
129 }
130
131 std::vector<std::string> WASAPIStream::GetAvailableDevices()
132 {
133 std::vector<std::string> device_names;
134
135 ForEachNamedDevice([&device_names](ComPtr<IMMDevice>, std::string n) {
136 device_names.push_back(std::move(n));
137 return true;
138 });
139
140 return device_names;
141 }
142
143 ComPtr<IMMDevice> WASAPIStream::GetDeviceByName(std::string_view name)
144 {
145 ComPtr<IMMDevice> device;
146
147 ForEachNamedDevice([&device, &name](ComPtr<IMMDevice> d, std::string n) {
148 if (n == name)
149 {
150 device = std::move(d);
151 return false;
152 }
153 return true;
154 });
155
156 return device;
157 }
158
159 bool WASAPIStream::Init()
160 {
161 ASSERT(m_enumerator == nullptr);
162 const HRESULT result = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,
163 CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_enumerator));
164
165 if (!HandleWinAPI("Failed to create MMDeviceEnumerator", result))
166 return false;
167
168 return true;
169 }
170
171 bool WASAPIStream::SetRunning(bool running)
172 {
173 if (running)
174 {
175 ComPtr<IMMDevice> device;
176
177 HRESULT result;
178
179 if (Config::IsDefaultValue(Config::MAIN_WASAPI_DEVICE))
180 {
181 result = m_enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device);
182 }
183 else
184 {
185 result = S_OK;
186 device = GetDeviceByName(Config::Get(Config::MAIN_WASAPI_DEVICE));
187
188 if (!device)
189 {
190 ERROR_LOG_FMT(AUDIO, "Can't find device '{}', falling back to default",
191 Config::Get(Config::MAIN_WASAPI_DEVICE));
192 result = m_enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device);
193 }
194 }
195
196 if (!HandleWinAPI("Failed to obtain default endpoint", result))
197 return false;
198
199 // Show a friendly name in the log
200 ComPtr<IPropertyStore> device_properties;
201
202 result = device->OpenPropertyStore(STGM_READ, &device_properties);
203
204 if (!HandleWinAPI("Failed to initialize IPropertyStore", result))
205 return false;
206
207 wil::unique_prop_variant device_name;
208 device_properties->GetValue(PKEY_Device_FriendlyName, device_name.addressof());
209
210 INFO_LOG_FMT(AUDIO, "Using audio endpoint '{}'", TStrToUTF8(device_name.pwszVal));
211
212 ComPtr<IAudioClient> audio_client;
213
214 // Get IAudioDevice
215 result = device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, nullptr, &audio_client);
216
217 if (!HandleWinAPI("Failed to activate IAudioClient", result))
218 return false;
219
220 REFERENCE_TIME device_period = 0;
221
222 result = audio_client->GetDevicePeriod(nullptr, &device_period);
223
224 device_period += Config::Get(Config::MAIN_AUDIO_LATENCY) * (10000 / m_format.Format.nChannels);
225 INFO_LOG_FMT(AUDIO, "Audio period set to {}", device_period);
226
227 if (!HandleWinAPI("Failed to obtain device period", result))
228 return false;
229
230 result = audio_client->Initialize(
231 AUDCLNT_SHAREMODE_EXCLUSIVE,
232 AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST, device_period,
233 device_period, reinterpret_cast<WAVEFORMATEX*>(&m_format), nullptr);
234
235 if (result == AUDCLNT_E_UNSUPPORTED_FORMAT)
236 {
237 OSD::AddMessage("Your current audio device doesn't support 16-bit 48000 hz PCM audio. WASAPI "
238 "exclusive mode won't work.",
239 6000U);
240 return false;
241 }
242
243 if (result == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED)
244 {
245 result = audio_client->GetBufferSize(&m_frames_in_buffer);
246
247 if (!HandleWinAPI("Failed to get aligned buffer size", result))
248 return false;
249
250 // Get IAudioDevice
251 result =
252 device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, nullptr, &audio_client);
253
254 if (!HandleWinAPI("Failed to reactivate IAudioClient", result))
255 return false;
256
257 device_period =
258 static_cast<REFERENCE_TIME>(
259 10000.0 * 1000 * m_frames_in_buffer / m_format.Format.nSamplesPerSec + 0.5) +
260 Config::Get(Config::MAIN_AUDIO_LATENCY) * 10000;
261
262 result = audio_client->Initialize(
263 AUDCLNT_SHAREMODE_EXCLUSIVE,
264 AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST, device_period,
265 device_period, reinterpret_cast<WAVEFORMATEX*>(&m_format), nullptr);
266 }
267
268 if (!HandleWinAPI("Failed to initialize IAudioClient", result))
269 return false;
270
271 result = audio_client->GetBufferSize(&m_frames_in_buffer);
272
273 if (!HandleWinAPI("Failed to get buffer size from IAudioClient", result))
274 return false;
275
276 ComPtr<IAudioRenderClient> audio_renderer;
277
278 result = audio_client->GetService(IID_PPV_ARGS(&audio_renderer));
279
280 if (!HandleWinAPI("Failed to get IAudioRenderClient from IAudioClient", result))
281 return false;
282
283 wil::unique_event_nothrow need_data_event;
284 need_data_event.create();
285
286 audio_client->SetEventHandle(need_data_event.get());
287
288 result = audio_client->Start();
289
290 if (!HandleWinAPI("Failed to get IAudioRenderClient from IAudioClient", result))
291 return false;
292
293 INFO_LOG_FMT(AUDIO, "WASAPI: Successfully initialized!");
294
295 // "Commit" audio client and audio renderer now
296 m_audio_client = std::move(audio_client);
297 m_audio_renderer = std::move(audio_renderer);
298 m_need_data_event = std::move(need_data_event);
299
300 m_running.store(true, std::memory_order_relaxed);
301 m_thread = std::thread(&WASAPIStream::SoundLoop, this);
302 }
303 else
304 {
305 m_running.store(false, std::memory_order_relaxed);
306
307 if (m_thread.joinable())
308 m_thread.join();
309
310 m_need_data_event.reset();
311 m_audio_renderer.Reset();
312 m_audio_client.Reset();
313 }
314
315 return true;
316 }
317
318 void WASAPIStream::SoundLoop()
319 {
320 Common::SetCurrentThreadName("WASAPI Handler");
321 BYTE* data;
322
323 HRESULT getbuffer_result = m_audio_renderer->GetBuffer(m_frames_in_buffer, &data);
324 if (getbuffer_result != S_OK)
325 {
326 m_running.store(false, std::memory_order_relaxed);
327 return;
328 }
329 m_audio_renderer->ReleaseBuffer(m_frames_in_buffer, AUDCLNT_BUFFERFLAGS_SILENT);
330
331 while (m_running.load(std::memory_order_relaxed))
332 {
333 WaitForSingleObject(m_need_data_event.get(), 1000);
334
335 getbuffer_result = m_audio_renderer->GetBuffer(m_frames_in_buffer, &data);
336 if (getbuffer_result != S_OK)
337 {
338 m_running.store(false, std::memory_order_relaxed);
339 return;
340 }
341
342 s16* audio_data = reinterpret_cast<s16*>(data);
343 GetMixer()->Mix(audio_data, m_frames_in_buffer);
344
345 const bool is_muted =
346 Config::Get(Config::MAIN_AUDIO_MUTED) || Config::Get(Config::MAIN_AUDIO_VOLUME) == 0;
347 const bool need_volume_adjustment = Config::Get(Config::MAIN_AUDIO_VOLUME) != 100 && !is_muted;
348
349 if (need_volume_adjustment)
350 {
351 const float volume = Config::Get(Config::MAIN_AUDIO_VOLUME) / 100.0f;
352
353 for (u32 i = 0; i < m_frames_in_buffer * 2; i++)
354 *audio_data++ *= volume;
355 }
356
357 m_audio_renderer->ReleaseBuffer(m_frames_in_buffer, is_muted ? AUDCLNT_BUFFERFLAGS_SILENT : 0);
358 }
359 }
360
361 #endif // _WIN32