-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
298 lines (229 loc) · 8.23 KB
/
Copy pathmain.cpp
File metadata and controls
298 lines (229 loc) · 8.23 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
#include <iostream>
#include <fstream>
#include <mmdeviceapi.h>
#include <Audioclient.h>
#include <Windows.h>
#include <winerror.h>
#include <vector>
#include <thread>
#include <string>
using namespace std;
bool RECORDING = false;
HHOOK hhook;
bool holds_alt = false;
bool holds_ctrl = false;
HDC screen;
vector<thread> recorders;
ofstream temp;
#define REFTIMES_PER_SEC 10000000
#define REFTIMES_PER_MILLISEC 10000
#define EXIT_ON_ERROR(hres) \
if (FAILED(hres)) { goto Exit; }
#define SAFE_RELEASE(punk) \
if ((punk) != NULL) \
{ (punk)->Release(); (punk) = NULL; }
const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
const IID IID_IAudioClient = __uuidof(IAudioClient);
const IID IID_IAudioCaptureClient = __uuidof(IAudioCaptureClient);
struct MyAudioSink {
vector<UINT8> pData;
HRESULT WriteWavData(WAVEFORMATEX* pwfx, string file_name) {
ofstream out(file_name, ios::binary);
UINT32 file_size = pData.size() + 36;
UINT32 bloc_size = 16;
UINT16 byte_per_bloc = pwfx->nChannels * pwfx->wBitsPerSample / 8;
// Write WAV header
temp.close();
ifstream in("temp", ios::binary);
while (in.get() != EOF)
file_size++;
in.close();
out.write("RIFF", 4);
out.write((const char*)&file_size, 4);
out.write("WAVE", 4);
out.write("fmt ", 4);
out.write((const char*)&bloc_size, 4);
out.write((const char*)&pwfx->wFormatTag, 2);
out.write((const char*)&pwfx->nChannels, 2);
out.write((const char*)&pwfx->nSamplesPerSec, 4);
out.write((const char*)&pwfx->nAvgBytesPerSec, 4);
out.write((const char*)&byte_per_bloc, 2);
out.write((const char*)&pwfx->wBitsPerSample, 2);
// Write data
out.write("data", 4);
int data_size = file_size - 36;
out.write((const char*)&data_size, 4);
in = ifstream("temp", ios::binary);
// process raw audio in blocks, instead of byte by byte
char block[256];
while (in.read(block, sizeof(block)))
out.write((const char*)block, in.gcount());
in.close();
system("del temp");
// write remaining data (left in the audio buffer)
out.write((const char*)pData.data(), pData.size());
out.close();
pData = vector<UINT8>(); // release the built up "music"
return 0;
}
};
void DumpAudio(MyAudioSink* pMySink) {
temp.write((const char*)pMySink->pData.data(), pMySink->pData.size());
pMySink->pData.clear();
}
HRESULT RecordAudioStream(MyAudioSink* pMySink, string file_name)
{
HRESULT hr;
REFERENCE_TIME hnsRequestedDuration = REFTIMES_PER_SEC;
REFERENCE_TIME hnsActualDuration;
UINT32 bufferFrameCount;
UINT32 numFramesAvailable;
IMMDeviceEnumerator* pEnumerator = NULL;
IMMDevice* pDevice = NULL;
IAudioClient* pAudioClient = NULL;
IAudioCaptureClient* pCaptureClient = NULL;
WAVEFORMATEX* pwfx = NULL;
UINT32 packetLength = 0;
BOOL bDone = FALSE;
BYTE* pData;
DWORD flags;
WAVEFORMATEXTENSIBLE* mixFormat;
temp = ofstream("temp", ios::binary | ios::app);
hr = CoInitialize(NULL);
EXIT_ON_ERROR(hr)
hr = CoCreateInstance(
CLSID_MMDeviceEnumerator, NULL,
CLSCTX_ALL, IID_IMMDeviceEnumerator,
(void**)&pEnumerator);
EXIT_ON_ERROR(hr)
hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &pDevice);
EXIT_ON_ERROR(hr)
hr = pDevice->Activate(IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient);
EXIT_ON_ERROR(hr)
hr = pAudioClient->GetMixFormat(&pwfx);
EXIT_ON_ERROR(hr)
hr = pAudioClient->Initialize(
AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_LOOPBACK,
hnsRequestedDuration,
0,
pwfx,
NULL);
EXIT_ON_ERROR(hr)
mixFormat = (WAVEFORMATEXTENSIBLE*)pwfx;
if (mixFormat->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {
pwfx->wFormatTag = 0x0003;
}
// Get the size of the allocated buffer.
hr = pAudioClient->GetBufferSize(&bufferFrameCount);
EXIT_ON_ERROR(hr)
hr = pAudioClient->GetService(IID_IAudioCaptureClient, (void**)&pCaptureClient);
EXIT_ON_ERROR(hr)
// Calculate the actual duration of the allocated buffer.
hnsActualDuration = (double)REFTIMES_PER_SEC * bufferFrameCount / pwfx->nSamplesPerSec;
hr = pAudioClient->Start(); // Start recording.
EXIT_ON_ERROR(hr)
while (RECORDING) {
// Sleep for 1/4 of the buffer duration.
Sleep(hnsActualDuration / REFTIMES_PER_MILLISEC / 4);
hr = pCaptureClient->GetNextPacketSize(&packetLength);
EXIT_ON_ERROR(hr)
while (packetLength != 0) {
// Get the available data in the shared buffer.
hr = pCaptureClient->GetBuffer(
&pData,
&numFramesAvailable,
&flags, NULL, NULL);
EXIT_ON_ERROR(hr)
// Copy the available capture data to the audio sink.
for (UINT32 i = 0; i < numFramesAvailable * pwfx->nBlockAlign; i++)
pMySink->pData.push_back(pData[i]);
// Avoid using too much memory
if (pMySink->pData.size() >= 1024 * 1024)
DumpAudio(pMySink);
hr = pCaptureClient->ReleaseBuffer(numFramesAvailable);
EXIT_ON_ERROR(hr)
hr = pCaptureClient->GetNextPacketSize(&packetLength);
EXIT_ON_ERROR(hr)
}
}
hr = pAudioClient->Stop(); // Stop recording.
EXIT_ON_ERROR(hr)
pMySink->WriteWavData(pwfx, file_name);
Exit:
CoTaskMemFree(pwfx);
SAFE_RELEASE(pEnumerator)
SAFE_RELEASE(pDevice)
SAFE_RELEASE(pAudioClient)
SAFE_RELEASE(pCaptureClient)
return hr;
}
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam);
string parseDate(char *date) {
string s = date;
s.pop_back(); // get rid of '\n'
for (int i = 0; i < s.size(); i++)
if (s[i] == ':')
s[i] = '_';
s += ".wav";
return s;
}
int main() {
hhook = SetWindowsHookExA(WH_KEYBOARD_LL, KeyboardProc, NULL, 0);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
for (thread& t : recorders)
t.join();
temp.close();
return 0;
}
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode < 0) {
return CallNextHookEx(hhook, nCode, wParam, lParam);
}
KBDLLHOOKSTRUCT* p = (KBDLLHOOKSTRUCT*)lParam;
if (nCode == HC_ACTION) {
if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
if (p->vkCode == VK_LCONTROL) {
holds_ctrl = true;
}
else if (p->vkCode == VK_LMENU) {
holds_alt = true;
}
else if (holds_alt && holds_ctrl) {
if (p->vkCode == 'R') {
RECORDING = !RECORDING;
if (RECORDING) {
printf("Recording started...\n");
auto ct = chrono::system_clock::now();
auto t = chrono::system_clock::to_time_t(ct);
// NOTE: curr_time is a pointer to static data (so DONT free)
char *curr_time = ctime(&t);
string file_name = parseDate(curr_time);
MyAudioSink* sink = new MyAudioSink;
recorders.push_back(std::thread(RecordAudioStream, sink, file_name));
} else {
printf("Recording stopped\n");
}
}
else if (p->vkCode == 'Q') {
PostQuitMessage(0);
}
}
}
else if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP) {
if (p->vkCode == VK_LCONTROL) {
holds_ctrl = false;
}
else if (p->vkCode == VK_LMENU) {
holds_alt = false;
}
}
}
return CallNextHookEx(hhook, nCode, wParam, lParam);
}