-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_loopback.cpp
More file actions
418 lines (358 loc) · 14.3 KB
/
Copy path_loopback.cpp
File metadata and controls
418 lines (358 loc) · 14.3 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
/**
* JUPITER Sound Booster — WASAPI Process Loopback Extension
*
* Captures ALL system audio EXCEPT our own process output.
* Uses ActivateAudioInterfaceAsync with PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE.
* Requires Windows 10 Build 20438+ (version 2004/20H1).
*
* Based on Microsoft's Application Loopback Audio Capture sample
* and ProcTap (MIT license, github.com/m96-chan/ProcTap).
*/
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <windows.h>
#include <mmdeviceapi.h>
#include <audioclient.h>
#include <audiopolicy.h>
#include <combaseapi.h>
#include <objidl.h>
#include <wrl/client.h>
#include <vector>
using Microsoft::WRL::ComPtr;
/* ── Constants & structs (may be missing from older SDK headers) ── */
#ifndef VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK
#define VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK L"VAD\\Process_Loopback"
#endif
enum AUDIOCLIENT_ACTIVATION_TYPE {
AUDIOCLIENT_ACTIVATION_TYPE_DEFAULT = 0,
AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK = 1
};
enum PROCESS_LOOPBACK_MODE {
PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE = 0,
PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE = 1
};
struct AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
DWORD TargetProcessId;
PROCESS_LOOPBACK_MODE ProcessLoopbackMode;
};
struct AUDIOCLIENT_ACTIVATION_PARAMS {
AUDIOCLIENT_ACTIVATION_TYPE ActivationType;
union {
AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS ProcessLoopbackParams;
};
};
typedef HRESULT(WINAPI* PFN_ActivateAudioInterfaceAsync)(
LPCWSTR deviceInterfacePath,
REFIID riid,
PROPVARIANT* activationParams,
IActivateAudioInterfaceCompletionHandler* completionHandler,
IActivateAudioInterfaceAsyncOperation** activationOperation
);
/* ── Async completion handler (COM callback) ── */
class ActivationHandler : public IActivateAudioInterfaceCompletionHandler,
public IAgileObject {
LONG m_ref;
HANDLE m_event;
HRESULT m_hr;
ComPtr<IUnknown> m_result;
public:
ActivationHandler() : m_ref(1), m_hr(E_FAIL) {
m_event = CreateEvent(nullptr, TRUE, FALSE, nullptr);
}
~ActivationHandler() { if (m_event) CloseHandle(m_event); }
STDMETHODIMP QueryInterface(REFIID riid, void** ppv) override {
if (riid == __uuidof(IUnknown) ||
riid == __uuidof(IActivateAudioInterfaceCompletionHandler)) {
*ppv = static_cast<IActivateAudioInterfaceCompletionHandler*>(this);
AddRef(); return S_OK;
}
if (riid == __uuidof(IAgileObject)) {
*ppv = static_cast<IAgileObject*>(this);
AddRef(); return S_OK;
}
*ppv = nullptr; return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG) AddRef() override { return InterlockedIncrement(&m_ref); }
STDMETHODIMP_(ULONG) Release() override {
LONG c = InterlockedDecrement(&m_ref);
if (c == 0) delete this;
return c;
}
STDMETHODIMP ActivateCompleted(IActivateAudioInterfaceAsyncOperation* op) override {
HRESULT hrResult = E_FAIL;
ComPtr<IUnknown> pUnk;
op->GetActivateResult(&hrResult, &pUnk);
m_hr = hrResult;
m_result = pUnk;
SetEvent(m_event);
return S_OK;
}
HRESULT Wait(DWORD ms = 10000) {
if (WaitForSingleObject(m_event, ms) != WAIT_OBJECT_0) return E_FAIL;
return m_hr;
}
ComPtr<IUnknown> GetResult() { return m_result; }
};
/* ── Main capture class ── */
class SystemLoopback {
ComPtr<IAudioClient> m_client;
ComPtr<IAudioCaptureClient> m_capture;
WAVEFORMATEX* m_fmt = nullptr;
bool m_running = false;
bool m_processSpecific = false;
std::vector<BYTE> m_buf;
CRITICAL_SECTION m_lock;
public:
SystemLoopback() { InitializeCriticalSection(&m_lock); }
~SystemLoopback() { Cleanup(); DeleteCriticalSection(&m_lock); }
/* Try process-specific loopback; fall back to system-wide */
HRESULT Init() {
HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
if (hr == RPC_E_CHANGED_MODE) hr = S_OK; /* already init'd */
if (FAILED(hr)) return hr;
hr = InitExcludeProcess();
if (SUCCEEDED(hr)) return hr;
/* Fallback: system-wide loopback (will include our output — echo cancel needed) */
return InitSystemWide();
}
HRESULT Start() {
if (m_running) return S_OK;
HRESULT hr = m_client->Start();
if (SUCCEEDED(hr)) m_running = true;
return hr;
}
void Stop() {
if (!m_running) return;
m_running = false;
if (m_client) m_client->Stop();
}
/* Drain WASAPI packets into internal buffer, return all buffered data */
PyObject* Read() {
if (!m_running || !m_capture) Py_RETURN_NONE;
/* Drain all available packets */
UINT32 pktLen = 0;
while (SUCCEEDED(m_capture->GetNextPacketSize(&pktLen)) && pktLen > 0) {
BYTE* pData = nullptr;
UINT32 frames = 0;
DWORD flags = 0;
if (FAILED(m_capture->GetBuffer(&pData, &frames, &flags, nullptr, nullptr)))
break;
UINT32 bytes = frames * m_fmt->nBlockAlign;
EnterCriticalSection(&m_lock);
size_t old = m_buf.size();
m_buf.resize(old + bytes);
if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
memset(m_buf.data() + old, 0, bytes);
else
memcpy(m_buf.data() + old, pData, bytes);
LeaveCriticalSection(&m_lock);
m_capture->ReleaseBuffer(frames);
}
EnterCriticalSection(&m_lock);
if (m_buf.empty()) {
LeaveCriticalSection(&m_lock);
return PyBytes_FromStringAndSize("", 0);
}
PyObject* result = PyBytes_FromStringAndSize(
(const char*)m_buf.data(), (Py_ssize_t)m_buf.size());
m_buf.clear();
LeaveCriticalSection(&m_lock);
return result;
}
PyObject* GetFormat() {
if (!m_fmt) Py_RETURN_NONE;
return Py_BuildValue("{s:i,s:i,s:i,s:i}",
"channels", (int)m_fmt->nChannels,
"sample_rate", (int)m_fmt->nSamplesPerSec,
"bits_per_sample",(int)m_fmt->wBitsPerSample,
"block_align", (int)m_fmt->nBlockAlign);
}
bool IsProcessSpecific() { return m_processSpecific; }
void Cleanup() {
Stop();
m_capture.Reset();
m_client.Reset();
if (m_fmt) { CoTaskMemFree(m_fmt); m_fmt = nullptr; }
EnterCriticalSection(&m_lock);
m_buf.clear();
LeaveCriticalSection(&m_lock);
}
private:
HRESULT InitExcludeProcess() {
/* Load ActivateAudioInterfaceAsync dynamically */
HMODULE hMod = LoadLibraryW(L"mmdevapi.dll");
if (!hMod) return E_FAIL;
auto pfn = (PFN_ActivateAudioInterfaceAsync)
GetProcAddress(hMod, "ActivateAudioInterfaceAsync");
if (!pfn) { FreeLibrary(hMod); return E_FAIL; }
/* Activation params: EXCLUDE our own process tree */
AUDIOCLIENT_ACTIVATION_PARAMS params = {};
params.ActivationType = AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK;
params.ProcessLoopbackParams.ProcessLoopbackMode =
PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE;
params.ProcessLoopbackParams.TargetProcessId = GetCurrentProcessId();
PROPVARIANT pv = {};
pv.vt = VT_BLOB;
pv.blob.cbSize = sizeof(params);
pv.blob.pBlobData = (BYTE*)¶ms;
auto* handler = new ActivationHandler();
ComPtr<IActivateAudioInterfaceAsyncOperation> asyncOp;
HRESULT hr = pfn(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK,
__uuidof(IAudioClient), &pv, handler, &asyncOp);
FreeLibrary(hMod);
if (FAILED(hr)) { handler->Release(); return hr; }
hr = handler->Wait(10000);
if (FAILED(hr)) { handler->Release(); return hr; }
ComPtr<IUnknown> pUnk = handler->GetResult();
handler->Release();
if (!pUnk) return E_FAIL;
hr = pUnk.As(&m_client);
if (FAILED(hr)) return hr;
m_processSpecific = true;
/* Process loopback: GetMixFormat may return E_NOTIMPL.
Use hardcoded 48kHz/float32/stereo (standard). */
m_fmt = (WAVEFORMATEX*)CoTaskMemAlloc(sizeof(WAVEFORMATEX));
if (!m_fmt) return E_OUTOFMEMORY;
m_fmt->wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
m_fmt->nChannels = 2;
m_fmt->nSamplesPerSec = 48000;
m_fmt->wBitsPerSample = 32;
m_fmt->nBlockAlign = m_fmt->nChannels * m_fmt->wBitsPerSample / 8;
m_fmt->nAvgBytesPerSec = m_fmt->nSamplesPerSec * m_fmt->nBlockAlign;
m_fmt->cbSize = 0;
hr = m_client->Initialize(AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_LOOPBACK,
10000000, 0, m_fmt, nullptr);
if (FAILED(hr)) {
/* Fallback: 44.1kHz int16 */
m_fmt->wFormatTag = WAVE_FORMAT_PCM;
m_fmt->nSamplesPerSec = 44100;
m_fmt->wBitsPerSample = 16;
m_fmt->nBlockAlign = m_fmt->nChannels * m_fmt->wBitsPerSample / 8;
m_fmt->nAvgBytesPerSec = m_fmt->nSamplesPerSec * m_fmt->nBlockAlign;
hr = m_client->Initialize(AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_LOOPBACK,
10000000, 0, m_fmt, nullptr);
if (FAILED(hr)) return hr;
}
/* Check if WASAPI changed the format */
WAVEFORMATEX* actual = nullptr;
if (SUCCEEDED(m_client->GetMixFormat(&actual)) && actual) {
if (actual->nSamplesPerSec != m_fmt->nSamplesPerSec ||
actual->wBitsPerSample != m_fmt->wBitsPerSample) {
CoTaskMemFree(m_fmt);
m_fmt = actual;
} else {
CoTaskMemFree(actual);
}
}
hr = m_client->GetService(__uuidof(IAudioCaptureClient), (void**)&m_capture);
return hr;
}
HRESULT InitSystemWide() {
m_processSpecific = false;
ComPtr<IMMDeviceEnumerator> pEnum;
HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,
CLSCTX_ALL, __uuidof(IMMDeviceEnumerator),
(void**)&pEnum);
if (FAILED(hr)) return hr;
ComPtr<IMMDevice> pDev;
hr = pEnum->GetDefaultAudioEndpoint(eRender, eConsole, &pDev);
if (FAILED(hr)) return hr;
hr = pDev->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
(void**)&m_client);
if (FAILED(hr)) return hr;
hr = m_client->GetMixFormat(&m_fmt);
if (FAILED(hr)) return hr;
hr = m_client->Initialize(AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_LOOPBACK |
AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
10000000, 0, m_fmt, nullptr);
if (FAILED(hr)) return hr;
hr = m_client->GetService(__uuidof(IAudioCaptureClient), (void**)&m_capture);
return hr;
}
};
/* ── Python type wrapper ── */
typedef struct {
PyObject_HEAD
SystemLoopback* cap;
} LoopbackObject;
static void Loopback_dealloc(LoopbackObject* self) {
if (self->cap) delete self->cap;
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject* Loopback_new(PyTypeObject* type, PyObject*, PyObject*) {
auto* self = (LoopbackObject*)type->tp_alloc(type, 0);
if (self) self->cap = new SystemLoopback();
return (PyObject*)self;
}
static int Loopback_init(LoopbackObject* self, PyObject*, PyObject*) {
HRESULT hr = self->cap->Init();
if (FAILED(hr)) {
char msg[128];
sprintf_s(msg, "WASAPI init failed (0x%08X). Need Win10 2004+.", hr);
PyErr_SetString(PyExc_RuntimeError, msg);
return -1;
}
return 0;
}
static PyObject* Loopback_start(LoopbackObject* self, PyObject*) {
HRESULT hr = self->cap->Start();
if (FAILED(hr)) {
PyErr_Format(PyExc_RuntimeError, "Start failed: 0x%08X", hr);
return nullptr;
}
Py_RETURN_NONE;
}
static PyObject* Loopback_stop(LoopbackObject* self, PyObject*) {
self->cap->Stop();
Py_RETURN_NONE;
}
static PyObject* Loopback_read(LoopbackObject* self, PyObject*) {
return self->cap->Read();
}
static PyObject* Loopback_get_format(LoopbackObject* self, PyObject*) {
return self->cap->GetFormat();
}
static PyObject* Loopback_is_excluding(LoopbackObject* self, PyObject*) {
return PyBool_FromLong(self->cap->IsProcessSpecific() ? 1 : 0);
}
static PyMethodDef Loopback_methods[] = {
{"start", (PyCFunction)Loopback_start, METH_NOARGS, "Start capture"},
{"stop", (PyCFunction)Loopback_stop, METH_NOARGS, "Stop capture"},
{"read", (PyCFunction)Loopback_read, METH_NOARGS, "Read captured PCM data"},
{"get_format", (PyCFunction)Loopback_get_format, METH_NOARGS, "Get audio format dict"},
{"is_excluding", (PyCFunction)Loopback_is_excluding, METH_NOARGS, "True if process-excluded capture"},
{nullptr}
};
static PyTypeObject LoopbackType = {
PyVarObject_HEAD_INIT(nullptr, 0)
"_loopback.SystemLoopback", /* tp_name */
sizeof(LoopbackObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)Loopback_dealloc, /* tp_dealloc */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Py_TPFLAGS_DEFAULT, /* tp_flags */
"WASAPI system loopback (excludes own process)", /* tp_doc */
0, 0, 0, 0, 0, 0,
Loopback_methods, /* tp_methods */
0, 0, 0, 0, 0, 0, 0,
(initproc)Loopback_init, /* tp_init */
0,
Loopback_new, /* tp_new */
};
static struct PyModuleDef module_def = {
PyModuleDef_HEAD_INIT,
"_loopback",
"WASAPI system loopback capture (excludes own process audio)",
-1, nullptr
};
PyMODINIT_FUNC PyInit__loopback(void) {
if (PyType_Ready(&LoopbackType) < 0) return nullptr;
PyObject* m = PyModule_Create(&module_def);
if (!m) return nullptr;
Py_INCREF(&LoopbackType);
PyModule_AddObject(m, "SystemLoopback", (PyObject*)&LoopbackType);
return m;
}