forked from ozsun88/SynchronousAudioRouter
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmmwrapper.cpp
More file actions
460 lines (366 loc) · 13 KB
/
mmwrapper.cpp
File metadata and controls
460 lines (366 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
// SynchronousAudioRouter
// Copyright (C) 2015 Mackenzie Straight
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SynchronousAudioRouter. If not, see <http://www.gnu.org/licenses/>.
#include "stdafx.h"
#include "mmwrapper.h"
#include "utility.h"
#include <DbgHelp.h>
#pragma comment(lib, "dbghelp.lib")
namespace Sar {
typedef HRESULT STDAPICALLTYPE DllGetClassObjectFn(
REFCLSID rclsid, REFIID riid, LPVOID *ppv);
#define MMDEVAPI_PATH "%SystemRoot%\\System32\\MMDevApi.dll"
const PROPERTYKEY PKEY_SynchronousAudioRouter_EndpointId =
{
{ 0xf4b15b6f, 0x8c3f, 0x48b6,
{ 0xa1, 0x15, 0x42, 0xfd, 0xe1, 0x9e, 0xf0, 0x5b } },
0
};
// There's an undocumented device property that gives the actual path to the
// kernel streaming device, which is what ActivateAudioInterfaceAsync expects.
// TODO: find a better way to get this from IMMDevice.
const PROPERTYKEY PKEY_Unknown_DevicePath =
{
{ 0x9c119480, 0xddc2, 0x4954,
{ 0xa1, 0x50, 0x5b, 0xd2, 0x40, 0xd4, 0x54, 0xad } },
1
};
static HRESULT CreateMMDevAPIObject(
REFCLSID rclsid, REFIID riid, LPVOID *ppvObject)
{
char buf[256] = {};
DllGetClassObjectFn *fn_DllGetClassObject;
CComPtr<IClassFactory> cf;
HMODULE lib, dummy;
HRESULT hr;
// Our registry filter has replaced the registration for the
// MMDeviceEnumerator with our wrapper object, but we need to instantiate
// the original coclass. Unfortunately, we can't just bypass the registry
// filter to get the original registration back, as CoCreateInstance uses
// an internal class cache and won't re-load the registration. So we hack
// job it and instantiate the object directly using the DLL's
// DllGetClassObject export. In order for this to be safe, the wrapper
// object must use the same threading model as the underlying one.
if (!ExpandEnvironmentStringsA(MMDEVAPI_PATH, buf, sizeof(buf))) {
LOG(ERROR) << "Failed to get MMDEVAPI_PATH";
return E_FAIL;
}
lib = LoadLibraryA(buf);
if (!lib) {
LOG(ERROR) << "Failed to load MMDevAPI";
return E_FAIL;
}
fn_DllGetClassObject =
(DllGetClassObjectFn *)GetProcAddress(lib, "DllGetClassObject");
if (!fn_DllGetClassObject) {
LOG(ERROR) << "Failed to get DllClassObject from MMDevAPI";
FreeLibrary(lib);
return E_FAIL;
}
// Because of the nasty way we're loading the underlying COM object outside
// of CoCreateInstance, we need to make sure that both our dll and the
// MMDevAPI dll never unload for the lifetime of the process, so we pin them
// here.
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,
(LPCTSTR)fn_DllGetClassObject, &dummy);
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,
(LPCTSTR)DllGetClassObject, &dummy);
// It probably doesn't matter since we've pinned the library anyway, but
// balance the LoadLibraryA call above.
FreeLibrary(lib);
if (!SUCCEEDED(hr = fn_DllGetClassObject(
rclsid, IID_IClassFactory, (LPVOID *)&cf))) {
LOG(ERROR) << "Failed to instantiate class factory";
return hr;
}
return cf->CreateInstance(0, riid, ppvObject);
}
SarMMDeviceEnumerator::SarMMDeviceEnumerator()
{
LOG(INFO) << "Initializing SarMMDeviceEnumerator.";
HRESULT hr;
_config = DriverConfig::fromFile(ConfigurationPath("default.json"));
hr = CreateMMDevAPIObject(
__uuidof(MMDeviceEnumerator), __uuidof(IMMDeviceEnumerator),
(LPVOID *)&_innerEnumerator);
if (!SUCCEEDED(hr)) {
LOG(ERROR) << "Failed to instantiate MMDeviceEnumerator";
}
LOG(INFO) << "Initialized SarMMDeviceEnumerator.";
}
SarMMDeviceEnumerator::~SarMMDeviceEnumerator()
{
_innerEnumerator = nullptr;
}
HRESULT STDMETHODCALLTYPE SarMMDeviceEnumerator::EnumAudioEndpoints(
_In_ EDataFlow dataFlow,
_In_ DWORD dwStateMask,
_Out_ IMMDeviceCollection **ppDevices)
{
if (!_innerEnumerator) {
return E_FAIL;
}
LOG(INFO) << "SarMMDeviceEnumerator::EnumAudioEndpoints";
CComPtr<IMMDeviceCollection> innerCollection;
CComPtr<IMMDeviceCollection> outerCollection;
std::vector<CComPtr<IMMDevice>> devices;
auto hr = _innerEnumerator->EnumAudioEndpoints(
dataFlow, dwStateMask, &innerCollection);
if (!SUCCEEDED(hr)) {
return hr;
}
UINT numDevices;
hr = innerCollection->GetCount(&numDevices);
if (!SUCCEEDED(hr)) {
return hr;
}
for (UINT i = 0; i < numDevices; ++i) {
CComPtr<IMMDevice> device;
hr = innerCollection->Item(i, &device);
if (!SUCCEEDED(hr)) {
continue;
}
devices.emplace_back(device);
}
hr = SarMMDeviceCollection::CreateInstance(&outerCollection);
if (!SUCCEEDED(hr)) {
return hr;
}
CComQIPtr<ISarMMDeviceCollectionInit> ocInit(outerCollection);
ocInit->Initialize(devices);
return outerCollection.CopyTo(ppDevices);
}
HRESULT STDMETHODCALLTYPE SarMMDeviceEnumerator::GetDefaultAudioEndpoint(
_In_ EDataFlow dataFlow,
_In_ ERole role,
_Out_ IMMDevice **ppEndpoint)
{
LOG(INFO) << "SarMMDeviceEnumerator::GetDefaultAudioEndpoint";
if (!_innerEnumerator) {
return E_FAIL;
}
if (!_config.enableApplicationRouting) {
return _innerEnumerator->GetDefaultAudioEndpoint(
dataFlow, role, ppEndpoint);
}
CComPtr<IMMDeviceCollection> devices;
CComPtr<IMMDevice> foundDevice;
UINT deviceCount;
WCHAR processNameWide[512] = {};
ApplicationConfig *appConfig = nullptr;
GetModuleFileName(nullptr, processNameWide, sizeof(processNameWide));
auto processName = TCHARToUTF8(processNameWide);
for (auto& candidateApp : _config.applications) {
if (std::regex_search(processName, candidateApp.pattern)) {
appConfig = &candidateApp;
break;
}
}
if (!appConfig) {
return _innerEnumerator->GetDefaultAudioEndpoint(
dataFlow, role, ppEndpoint);
}
if (!SUCCEEDED(_innerEnumerator->EnumAudioEndpoints(
dataFlow, DEVICE_STATE_ACTIVE, &devices))) {
return E_FAIL;
}
if (!SUCCEEDED(devices->GetCount(&deviceCount))) {
return E_FAIL;
}
for (UINT i = 0; i < deviceCount && !foundDevice; ++i) {
CComPtr<IMMDevice> device;
CComPtr<IPropertyStore> ps;
PROPVARIANT pvalue = {};
if (!SUCCEEDED(devices->Item(i, &device))) {
continue;
}
if (!SUCCEEDED(device->OpenPropertyStore(STGM_READ, &ps))) {
continue;
}
if (!SUCCEEDED(ps->GetValue(
PKEY_SynchronousAudioRouter_EndpointId, &pvalue))) {
continue;
}
if (pvalue.vt == VT_LPWSTR) {
auto candidateId = TCHARToUTF8(pvalue.pwszVal);
for (auto& defaultEndpoint : appConfig->defaults) {
if (role == defaultEndpoint.role &&
dataFlow == defaultEndpoint.type &&
candidateId == defaultEndpoint.id) {
foundDevice = device;
break;
}
}
}
PropVariantClear(&pvalue);
}
if (foundDevice) {
*ppEndpoint = foundDevice.Detach();
return S_OK;
}
return _innerEnumerator->GetDefaultAudioEndpoint(
dataFlow, role, ppEndpoint);
}
HRESULT STDMETHODCALLTYPE SarMMDeviceEnumerator::GetDevice(
_In_ LPCWSTR pwstrId,
_Out_ IMMDevice **ppDevice)
{
if (!_innerEnumerator) {
return E_FAIL;
}
auto deviceId = TCHARToUTF8(pwstrId);
LOG(INFO) << "SarMMDeviceEnumerator::GetDevice("
<< deviceId << ")";
return _innerEnumerator->GetDevice(pwstrId, ppDevice);
}
HRESULT STDMETHODCALLTYPE
SarMMDeviceEnumerator::RegisterEndpointNotificationCallback(
_In_ IMMNotificationClient *pClient)
{
if (!_innerEnumerator) {
return E_FAIL;
}
LOG(INFO) << "SarMMDeviceEnumerator::RegisterEndpointNotificationCallback";
return _innerEnumerator->RegisterEndpointNotificationCallback(pClient);
}
HRESULT STDMETHODCALLTYPE
SarMMDeviceEnumerator::UnregisterEndpointNotificationCallback(
_In_ IMMNotificationClient *pClient)
{
if (!_innerEnumerator) {
return E_FAIL;
}
LOG(INFO)
<< "SarMMDeviceEnumerator::UnregisterEndpointNotificationCallback";
return _innerEnumerator->UnregisterEndpointNotificationCallback(
pClient);
}
HRESULT SarMMDeviceCollection::Initialize(
const std::vector<CComPtr<IMMDevice>> &items)
{
_items = items;
return S_OK;
}
HRESULT STDMETHODCALLTYPE SarMMDeviceCollection::GetCount(
_Out_ UINT *pcDevices)
{
if (!pcDevices) {
return E_POINTER;
}
*pcDevices = (UINT)_items.size();
return S_OK;
}
HRESULT STDMETHODCALLTYPE SarMMDeviceCollection::Item(
_In_ UINT nDevice, _Out_ IMMDevice **ppDevice)
{
if (nDevice >= _items.size()) {
return E_INVALIDARG;
}
LOG(INFO) << "Getting enumerated device at index " << nDevice;
return _items[nDevice].CopyTo(ppDevice);
}
SarActivateAudioInterfaceWorker::SarActivateAudioInterfaceWorker()
{
HRESULT hr;
hr = CreateMMDevAPIObject(
__uuidof(SarActivateAudioInterfaceWorker),
__uuidof(IActivateAudioInterfaceWorker),
(LPVOID *)&_innerWorker);
if (!SUCCEEDED(hr)) {
LOG(ERROR)
<< "Failed to initialize inner ActivateAudioInterfaceWorker.";
}
}
HRESULT STDMETHODCALLTYPE SarActivateAudioInterfaceWorker::Initialize(
LPCWSTR deviceInterfacePath,
REFIID riid,
PROPVARIANT *activationParams,
IActivateAudioInterfaceCompletionHandler *completionHandler,
UINT threadId)
{
if (!_innerWorker) {
return E_FAIL;
}
auto path = TCHARToUTF8(deviceInterfacePath);
LPOLESTR riidStr;
HRESULT hr;
CComPtr<IMMDeviceEnumerator> mmEnum;
CComPtr<IMMDevice> mmDevice;
std::wstring defaultDevicePath = deviceInterfacePath;
hr = CoCreateInstance(
__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,
__uuidof(IMMDeviceEnumerator), (LPVOID *)&mmEnum);
if (!SUCCEEDED(hr)) {
LOG(ERROR) << "Failed to create device enumerator.";
return hr;
}
StringFromCLSID(riid, &riidStr);
LOG(INFO) << "SarActivateAudioInterfaceWorker::Initialize("
<< TCHARToUTF8(deviceInterfacePath) << ", "
<< TCHARToUTF8(riidStr) << ", "
<< "activationParams, "
<< std::hex << completionHandler << ", " << threadId << "), thread id "
<< std::hex << GetCurrentThreadId() << std::dec;
CoTaskMemFree(riidStr);
hr = S_OK;
if (path == "{E6327CAD-DCEC-4949-AE8A-991E976A79D2}") {
LOG(INFO) << "Caller is trying to initialize default render interface.";
hr = mmEnum->GetDefaultAudioEndpoint(eRender, eConsole, &mmDevice);
}
if (path == "{2EEF81BE-33FA-4800-9670-1CD474972C3F}") {
LOG(INFO) << "Caller is trying to initialize default record interface.";
hr = mmEnum->GetDefaultAudioEndpoint(eCapture, eConsole, &mmDevice);
}
if (SUCCEEDED(hr) && mmDevice) {
do {
CComPtr<IPropertyStore> ps;
PROPVARIANT pvalue = {};
if (!SUCCEEDED(mmDevice->OpenPropertyStore(STGM_READ, &ps))) {
break;
}
if (!SUCCEEDED(ps->GetValue(PKEY_Unknown_DevicePath, &pvalue))) {
break;
}
defaultDevicePath = pvalue.pwszVal;
PropVariantClear(&pvalue);
} while(0);
}
LOG(INFO) << "Using device " << TCHARToUTF8(defaultDevicePath.c_str());
return _innerWorker->Initialize(
defaultDevicePath.c_str(),
riid, activationParams, completionHandler, threadId);
}
HRESULT STDMETHODCALLTYPE SarActivateAudioInterfaceWorker::GetActivateResult(
_Out_ HRESULT *activateResult,
_Outptr_result_maybenull_ IUnknown **activatedInterface)
{
// This wrapper is never actually called by the implementation of the worker
// but ActivateAudioInterfaceAsync does a QueryInterface on us to make sure
// that it's actually present.
LOG(INFO) << "SarActivateAudioInterfaceWorker::GetActivateResult";
if (!_innerWorker) {
return E_FAIL;
}
CComQIPtr<IActivateAudioInterfaceAsyncOperation>
innerOperation(_innerWorker);
if (!innerOperation) {
return E_FAIL;
}
return innerOperation->GetActivateResult(
activateResult, activatedInterface);
}
} // namespace Sar