-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathloopback-capture.cpp
More file actions
371 lines (330 loc) · 12.2 KB
/
Copy pathloopback-capture.cpp
File metadata and controls
371 lines (330 loc) · 12.2 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
/*
Copyright (C) 2014 kaytat
Originally derived from the example posted here:
http://blogs.msdn.com/b/matthew_van_eerde/archive/2014/11/05/draining-the-wasapi-capture-buffer-fully.aspx
Since there is no explict license, the Microsoft LPL applies:
http://msdn.microsoft.com/en-us/cc300389.aspx
*/
// loopback-capture.cpp
#include <windows.h>
#include <mmsystem.h>
#include <mmdeviceapi.h>
#include <audioclient.h>
#include <stdio.h>
#include <avrt.h>
#include "loopback-capture.h"
#include "simpletcpserver.h"
HRESULT LoopbackCapture(
IMMDevice *pMMDevice,
bool bInt16,
HANDLE hStartedEvent,
HANDLE hStopEvent,
PUINT32 pnFrames,
bool bMono,
INT32 iSampleRateDivisor
);
DWORD WINAPI LoopbackCaptureThreadFunction(LPVOID pContext) {
LoopbackCaptureThreadFunctionArguments *pArgs =
(LoopbackCaptureThreadFunctionArguments*)pContext;
pArgs->hr = CoInitialize(NULL);
if (FAILED(pArgs->hr)) {
printf("CoInitialize failed: hr = 0x%08x\n", pArgs->hr);
return 0;
}
pArgs->hr = LoopbackCapture(
pArgs->pMMDevice,
pArgs->bInt16,
pArgs->hStartedEvent,
pArgs->hStopEvent,
&pArgs->nFrames,
pArgs->bMono,
pArgs->iSampleRateDivisor
);
CoUninitialize();
return 0;
}
HRESULT LoopbackCapture(
IMMDevice *pMMDevice,
bool bInt16,
HANDLE hStartedEvent,
HANDLE hStopEvent,
PUINT32 pnFrames,
bool bMono,
INT32 iSampleRateDivisor
) {
HRESULT hr;
SimpleTcpServer server;
// Wait for client connection before attempting any audio capture
server.setup();
server.waitForClient();
// activate an IAudioClient
IAudioClient *pAudioClient;
hr = pMMDevice->Activate(
__uuidof(IAudioClient),
CLSCTX_ALL, NULL,
(void**)&pAudioClient
);
if (FAILED(hr)) {
printf("IMMDevice::Activate(IAudioClient) failed: hr = 0x%08x", hr);
return hr;
}
// get the default device periodicity
REFERENCE_TIME hnsDefaultDevicePeriod;
hr = pAudioClient->GetDevicePeriod(&hnsDefaultDevicePeriod, NULL);
if (FAILED(hr)) {
printf("IAudioClient::GetDevicePeriod failed: hr = 0x%08x\n", hr);
pAudioClient->Release();
return hr;
}
// get the default device format
WAVEFORMATEX *pwfx;
hr = pAudioClient->GetMixFormat(&pwfx);
if (FAILED(hr)) {
printf("IAudioClient::GetMixFormat failed: hr = 0x%08x\n", hr);
CoTaskMemFree(pwfx);
pAudioClient->Release();
return hr;
}
if (bInt16) {
// coerce int-16 wave format
// can do this in-place since we're not changing the size of the format
// also, the engine will auto-convert from float to int for us
switch (pwfx->wFormatTag) {
case WAVE_FORMAT_IEEE_FLOAT:
pwfx->wFormatTag = WAVE_FORMAT_PCM;
pwfx->wBitsPerSample = 16;
pwfx->nBlockAlign = pwfx->nChannels * pwfx->wBitsPerSample / 8;
pwfx->nAvgBytesPerSec = pwfx->nBlockAlign * pwfx->nSamplesPerSec;
break;
case WAVE_FORMAT_EXTENSIBLE:
{
// naked scope for case-local variable
PWAVEFORMATEXTENSIBLE pEx = reinterpret_cast<PWAVEFORMATEXTENSIBLE>(pwfx);
if (IsEqualGUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, pEx->SubFormat)) {
pEx->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
pEx->Samples.wValidBitsPerSample = 16;
pwfx->wBitsPerSample = 16;
pwfx->nBlockAlign = pwfx->nChannels * pwfx->wBitsPerSample / 8;
pwfx->nAvgBytesPerSec = pwfx->nBlockAlign * pwfx->nSamplesPerSec;
} else {
printf("Don't know how to coerce mix format to int-16\n");
CoTaskMemFree(pwfx);
pAudioClient->Release();
return E_UNEXPECTED;
}
}
break;
default:
printf("Don't know how to coerce WAVEFORMATEX with wFormatTag = 0x%08x to int-16\n", pwfx->wFormatTag);
CoTaskMemFree(pwfx);
pAudioClient->Release();
return E_UNEXPECTED;
}
}
// create a periodic waitable timer
HANDLE hWakeUp = CreateWaitableTimer(NULL, FALSE, NULL);
if (NULL == hWakeUp) {
DWORD dwErr = GetLastError();
printf("CreateWaitableTimer failed: last error = %u\n", dwErr);
CoTaskMemFree(pwfx);
pAudioClient->Release();
return HRESULT_FROM_WIN32(dwErr);
}
UINT32 nBlockAlign = pwfx->nBlockAlign;
UINT32 nBufferSize;
*pnFrames = 0;
// call IAudioClient::Initialize
// note that AUDCLNT_STREAMFLAGS_LOOPBACK and AUDCLNT_STREAMFLAGS_EVENTCALLBACK
// do not work together...
// the "data ready" event never gets set
// so we're going to do a timer-driven loop
hr = pAudioClient->Initialize(
AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_LOOPBACK,
0, 0, pwfx, 0
);
if (FAILED(hr)) {
printf("IAudioClient::Initialize failed: hr = 0x%08x\n", hr);
CloseHandle(hWakeUp);
pAudioClient->Release();
return hr;
}
CoTaskMemFree(pwfx);
// Get the buffer size
hr = pAudioClient->GetBufferSize(&nBufferSize);
if (FAILED(hr)) {
printf("IAudioClient::GetBufferSize failed: hr = 0x%08x\n", hr);
CloseHandle(hWakeUp);
pAudioClient->Release();
return hr;
}
// Configure the server. The buffer size returned is in frames
// so assume stereo, 16 bits per sample to convert from frames to bytes
server.configure(
bMono,
iSampleRateDivisor,
nBufferSize * 2 * 2);
// activate an IAudioCaptureClient
IAudioCaptureClient *pAudioCaptureClient;
hr = pAudioClient->GetService(
__uuidof(IAudioCaptureClient),
(void**)&pAudioCaptureClient
);
if (FAILED(hr)) {
printf("IAudioClient::GetService(IAudioCaptureClient) failed: hr 0x%08x\n", hr);
CloseHandle(hWakeUp);
pAudioClient->Release();
return hr;
}
// register with MMCSS
DWORD nTaskIndex = 0;
HANDLE hTask = AvSetMmThreadCharacteristics(L"Capture", &nTaskIndex);
if (NULL == hTask) {
DWORD dwErr = GetLastError();
printf("AvSetMmThreadCharacteristics failed: last error = %u\n", dwErr);
pAudioCaptureClient->Release();
CloseHandle(hWakeUp);
pAudioClient->Release();
return HRESULT_FROM_WIN32(dwErr);
}
// set the waitable timer
LARGE_INTEGER liFirstFire;
liFirstFire.QuadPart = -hnsDefaultDevicePeriod / 2; // negative means relative time
LONG lTimeBetweenFires = (LONG)hnsDefaultDevicePeriod / 2 / (10 * 1000); // convert to milliseconds
BOOL bOK = SetWaitableTimer(
hWakeUp,
&liFirstFire,
lTimeBetweenFires,
NULL, NULL, FALSE
);
if (!bOK) {
DWORD dwErr = GetLastError();
printf("SetWaitableTimer failed: last error = %u\n", dwErr);
AvRevertMmThreadCharacteristics(hTask);
pAudioCaptureClient->Release();
CloseHandle(hWakeUp);
pAudioClient->Release();
return HRESULT_FROM_WIN32(dwErr);
}
// call IAudioClient::Start
hr = pAudioClient->Start();
if (FAILED(hr)) {
printf("IAudioClient::Start failed: hr = 0x%08x\n", hr);
AvRevertMmThreadCharacteristics(hTask);
pAudioCaptureClient->Release();
CloseHandle(hWakeUp);
pAudioClient->Release();
return hr;
}
SetEvent(hStartedEvent);
// loopback capture loop
HANDLE waitArray[2] = { hStopEvent, hWakeUp };
DWORD dwWaitResult;
bool bDone = false;
for (UINT32 nPasses = 0; !bDone; nPasses++) {
// drain data while it is available
UINT32 nNextPacketSize;
for (
hr = pAudioCaptureClient->GetNextPacketSize(&nNextPacketSize);
SUCCEEDED(hr) && nNextPacketSize > 0;
hr = pAudioCaptureClient->GetNextPacketSize(&nNextPacketSize)
) {
// get the captured data
BYTE *pData;
UINT32 nNumFramesToRead;
DWORD dwFlags;
hr = pAudioCaptureClient->GetBuffer(
&pData,
&nNumFramesToRead,
&dwFlags,
NULL,
NULL
);
if (FAILED(hr)) {
printf("IAudioCaptureClient::GetBuffer failed on pass %u after %u frames: hr = 0x%08x\n", nPasses, *pnFrames, hr);
pAudioClient->Stop();
CancelWaitableTimer(hWakeUp);
AvRevertMmThreadCharacteristics(hTask);
pAudioCaptureClient->Release();
CloseHandle(hWakeUp);
pAudioClient->Release();
return hr;
}
#ifdef _DEBUG
if (0 != dwFlags) {
printf("[ignoring] IAudioCaptureClient::GetBuffer set flags to 0x%08x on pass %u after %u frames\n", dwFlags, nPasses, *pnFrames);
}
#endif
if (0 == nNumFramesToRead) {
printf("IAudioCaptureClient::GetBuffer said to read 0 frames on pass %u after %u frames\n", nPasses, *pnFrames);
pAudioClient->Stop();
CancelWaitableTimer(hWakeUp);
AvRevertMmThreadCharacteristics(hTask);
pAudioCaptureClient->Release();
CloseHandle(hWakeUp);
pAudioClient->Release();
return E_UNEXPECTED;
}
LONG lBytesToWrite = nNumFramesToRead * nBlockAlign;
if (server.sendData(reinterpret_cast<const char*>(pData), lBytesToWrite) != 0) {
printf("Error sending data to peer\n");
pAudioClient->Stop();
CancelWaitableTimer(hWakeUp);
AvRevertMmThreadCharacteristics(hTask);
pAudioCaptureClient->Release();
CloseHandle(hWakeUp);
pAudioClient->Release();
return E_UNEXPECTED;
}
*pnFrames += nNumFramesToRead;
hr = pAudioCaptureClient->ReleaseBuffer(nNumFramesToRead);
if (FAILED(hr)) {
printf("IAudioCaptureClient::ReleaseBuffer failed on pass %u after %u frames: hr = 0x%08x\n", nPasses, *pnFrames, hr);
pAudioClient->Stop();
CancelWaitableTimer(hWakeUp);
AvRevertMmThreadCharacteristics(hTask);
pAudioCaptureClient->Release();
CloseHandle(hWakeUp);
pAudioClient->Release();
return hr;
}
}
if (FAILED(hr)) {
printf("IAudioCaptureClient::GetNextPacketSize failed on pass %u after %u frames: hr = 0x%08x\n", nPasses, *pnFrames, hr);
pAudioClient->Stop();
CancelWaitableTimer(hWakeUp);
AvRevertMmThreadCharacteristics(hTask);
pAudioCaptureClient->Release();
CloseHandle(hWakeUp);
pAudioClient->Release();
return hr;
}
dwWaitResult = WaitForMultipleObjects(
ARRAYSIZE(waitArray), waitArray,
FALSE, INFINITE
);
if (WAIT_OBJECT_0 == dwWaitResult) {
printf("Received stop event after %u passes and %u frames\n", nPasses, *pnFrames);
bDone = true;
continue; // exits loop
}
if (WAIT_OBJECT_0 + 1 != dwWaitResult) {
printf("Unexpected WaitForMultipleObjects return value %u on pass %u after %u frames\n", dwWaitResult, nPasses, *pnFrames);
pAudioClient->Stop();
CancelWaitableTimer(hWakeUp);
AvRevertMmThreadCharacteristics(hTask);
pAudioCaptureClient->Release();
CloseHandle(hWakeUp);
pAudioClient->Release();
return E_UNEXPECTED;
}
} // capture loop
pAudioClient->Stop();
CancelWaitableTimer(hWakeUp);
AvRevertMmThreadCharacteristics(hTask);
pAudioCaptureClient->Release();
CloseHandle(hWakeUp);
pAudioClient->Release();
server.shutdown();
return hr;
}