-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptForAudio.cpp
More file actions
346 lines (299 loc) · 10.4 KB
/
OptForAudio.cpp
File metadata and controls
346 lines (299 loc) · 10.4 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
/*
* OptForAudio
* License: UNLICENSE
*
* I (Sean Echevarria) wrote this to do repetitive system housekeeping necessary
* to run Amplitube on an old Dell laptop with significantly reduced audio
* dropouts and buffer underruns.
*
* It:
* Runs elevated
* Disables display power down
* Disables screensaver
* Disables Wi-Fi interface
* Disables CPU throttling
* Disables Microsoft ACPI-Compliant Control Method Battery (device ID ACPI\PNP0C0A\1)
* Launches a list of programs (not elevated by default)
* Waits for all of the programs to exit
* Restores all changes it made
*
* Let me know if you modify, extend or use this.
* My website: http://www.creepingfog.com/sean/
* Contact Sean: "fester" at the domain of my website
*/
#include <windows.h>
#include <string>
#include <vector>
#include <memory>
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi")
#include <powersetting.h>
#pragma comment(lib, "PowrProf")
bool gDisplayRequired = true;
bool gDisableScreensaver = true;
bool gDisableCPUThrottle = true;
bool gDisableWifi = true;
bool gDisableCoreAffinity = true;
bool gDisableAcpiDevice = true;
bool gRunUtilApps = false;
std::vector<std::wstring> gPrograms;
void ReportStatus(std::wstring msg);
HANDLE LaunchProgram(std::wstring cmdline, bool launchUsingShellToken = true);
int wmain(int argc, wchar_t* argv[], wchar_t* envp[])
{
// command line parameters to override default behavior
for (int i = 1; i < argc; i++)
{
if (_wcsicmp(argv[i], L"-xDisplay") == 0)
gDisplayRequired = false;
else if (_wcsicmp(argv[i], L"-xScreensaver") == 0)
gDisableScreensaver = false;
else if (_wcsicmp(argv[i], L"-xCpuThrottle") == 0)
gDisableCPUThrottle = false;
else if (_wcsicmp(argv[i], L"-xWifi") == 0)
gDisableWifi = false;
else if (_wcsicmp(argv[i], L"-xCoreAffinity") == 0)
gDisableCoreAffinity = false;
else if (_wcsicmp(argv[i], L"-xAcpi") == 0)
gDisableAcpiDevice = false;
else if (_wcsicmp(argv[i], L"-runUtils") == 0)
gRunUtilApps = true;
else if (_wcsicmp(argv[i], L"?") == 0 ||
_wcsicmp(argv[i], L"-?") == 0 ||
_wcsicmp(argv[i], L"/?") == 0 ||
_wcsicmp(argv[i], L"help") == 0 ||
_wcsicmp(argv[i], L"-help") == 0 ||
_wcsicmp(argv[i], L"/help") == 0)
{
std::wstring helpMsg =
L"Optional command arguments:\n\
-xDisplay prevent change to display power down\n\
-xScreensaver prevent change to screensaver timeout\n\
-xCpuThrottle prevent change to CPU throttling\n\
-xWifi prevent change to Wi-Fi interface\n\
-xCoreAffinity prevent change to CPU core affinity of launched programs\n\
-xAcpi prevent change to Microsoft ACPI-Compliant Control Method Battery\n\
-runUtils starts LatencyMon (if found at C:\\Program Files\\LatencyMon\\LatMon.exe)\n\
and Rightmark PPM Panel (if found at C:\\Program Files\\RightMark\\ppmpanel\\ppmpanel.exe)";
ReportStatus(helpMsg);
ReportStatus(L"pausing before exit...");
::Sleep(15000);
return 0;
}
else if (argv[i][0] == L'-')
{
ReportStatus(L"unrecognized command line parameter: ");
ReportStatus(argv[i]);
ReportStatus(L"Exiting...");
::Sleep(5000);
return -1;
}
else
{
// todo: check for semi-colon delimited program list; parse and add to gPrograms if is a file
}
}
// Change system settings before launching the program(s)
//
ReportStatus(L"Optimizing system for realtime audio...");
const EXECUTION_STATE prevExecState = gDisplayRequired ? ::SetThreadExecutionState(ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED | ES_CONTINUOUS) : 0;
UINT prevScreenSaverTimeout = 0;
if (gDisableScreensaver)
{
::SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT, 0, &prevScreenSaverTimeout, 0);
::SystemParametersInfo(SPI_SETSCREENSAVETIMEOUT, FALSE, nullptr, 0);
}
if (gDisableCPUThrottle)
{
// https ://learn.microsoft.com/en-us/windows/win32/api/powerbase/nf-powerbase-callntpowerinformation
// Changes made to the current system power policy using CallNtPowerInformation are immediate, but they are not persistent;
// https://learn.microsoft.com/en-us/windows/win32/power/processor-performance-control-policy-constants
// https://stackoverflow.com/questions/9721218/trying-to-disable-processor-idle-states-c-states-on-windows-pc
GUID *scheme;
::PowerGetActiveScheme(nullptr, &scheme);
::PowerWriteACValueIndex(nullptr, scheme, &GUID_PROCESSOR_SETTINGS_SUBGROUP, &GUID_PROCESSOR_IDLE_DISABLE, 1);
::PowerSetActiveScheme(nullptr, scheme);
}
if (gDisableWifi)
{
// run without waiting for command to complete since it is slow to run
::_wsystem(LR"(start /min %windir%\System32\netsh.exe interface set interface "Wi-Fi" disabled)");
}
if (gDisableAcpiDevice)
{
::_wsystem(LR"(%windir%\System32\pnputil.exe /disable-device ACPI\PNP0C0A\1)");
}
std::vector<HANDLE> processes;
// launch program(s), unelevated
//
if (gRunUtilApps)
{
std::vector<std::wstring> utilPrograms;
utilPrograms.emplace_back(LR"(C:\Program Files\RightMark\ppmpanel\ppmpanel.exe)");
utilPrograms.emplace_back(LR"(C:\Program Files\LatencyMon\LatMon.exe)");
ReportStatus(L"Starting util programs...");
for (const auto& it : utilPrograms)
{
if (::PathFileExists(it.c_str()))
{
HANDLE tmp = LaunchProgram(it);
if (tmp)
processes.push_back(tmp);
else
ReportStatus(L"Failed to launch: " + it);
}
else
ReportStatus(L"Program not found: " + it);
}
}
gPrograms.emplace_back(LR"(C:\Program Files\IK Multimedia\AmpliTube 5\AmpliTube 5.exe)");
gPrograms.emplace_back(LR"(C:\Program Files\Cakewalk\Cakewalk Core\Cakewalk.exe)");
gPrograms.emplace_back(LR"(C:\Program Files\Blue Cat Audio\Blue Cat's Axiom\Blue Cat's Axiom.exe)");
ReportStatus(L"Starting programs...");
for (const auto& it : gPrograms)
{
if (::PathFileExists(it.c_str()))
{
HANDLE tmp = LaunchProgram(it);
if (tmp)
{
ReportStatus(L"Started: " + it);
if (gDisableCoreAffinity)
{
DWORD_PTR procAffinityMask = 0, systemAffinityMask = 0;
::GetProcessAffinityMask(tmp, &procAffinityMask, &systemAffinityMask);
// disable core 0 and 1:
procAffinityMask &= 0xfffffffffffffffc;
if (!::SetProcessAffinityMask(tmp, procAffinityMask))
ReportStatus(L" process affinity fail");
}
processes.push_back(tmp);
}
else
ReportStatus(L"Failed to launch: " + it);
}
else
ReportStatus(L"Skipped/not present: " + it);
}
// Wait for all launched programs to exit
//
if (!processes.empty())
{
::Sleep(1000);
ReportStatus(L"Waiting for programs to exit...");
::WaitForMultipleObjects((DWORD)processes.size(), &processes[0], TRUE, INFINITE);
for (auto it : processes)
::CloseHandle(it);
processes.clear();
}
// restore all changed system states
//
ReportStatus(L"Restoring system settings...");
if (gDisableWifi)
{
// run without waiting for command to complete since it is slow to run
::_wsystem(LR"(start /min %windir%\System32\netsh.exe interface set interface "Wi-Fi" enabled)");
}
if (gDisableAcpiDevice)
{
::_wsystem(LR"(%windir%\System32\pnputil.exe /enable-device ACPI\PNP0C0A\1)");
}
if (gDisableCPUThrottle)
{
GUID *scheme;
::PowerGetActiveScheme(nullptr, &scheme);
::PowerWriteACValueIndex(nullptr, scheme, &GUID_PROCESSOR_SETTINGS_SUBGROUP, &GUID_PROCESSOR_IDLE_DISABLE, 0);
::PowerSetActiveScheme(nullptr, scheme);
}
if (gDisableScreensaver)
::SystemParametersInfo(SPI_SETSCREENSAVETIMEOUT, prevScreenSaverTimeout, nullptr, 0);
if (gDisplayRequired)
::SetThreadExecutionState(prevExecState);
ReportStatus(L"Completed, pausing before exit...");
::Sleep(5000);
return 0;
}
HANDLE
LaunchProgram(std::wstring inStr, bool launchUsingShellToken /*= true*/)
{
constexpr int kBufLen = 2048;
const std::unique_ptr<wchar_t[]> tmpVec(new wchar_t[kBufLen]);
wchar_t* tmp = &tmpVec[0];
::ExpandEnvironmentStringsW(inStr.c_str(), tmp, kBufLen);
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
STARTUPINFO si;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
if (launchUsingShellToken)
{
// unelevated launch
// assume we are running with elevation, so we need to launch the programs unelevated
// https://stackoverflow.com/questions/1173630/how-do-you-de-elevate-privileges-for-a-child-process
// https://devblogs.microsoft.com/oldnewthing/20190425-00/?p=102443https://devblogs.microsoft.com/oldnewthing/20190425-00/?p=102443
// https://stackoverflow.com/questions/17765568/how-to-start-a-process-unelevated/40687129#40687129
HWND hShellWnd = ::GetShellWindow();
if (!hShellWnd)
{
ReportStatus(L"GetShellWindow failed");
return nullptr;
}
DWORD shellProcessId = 0;
::GetWindowThreadProcessId(hShellWnd, &shellProcessId);
if (!shellProcessId)
{
ReportStatus(L"GetWindowThreadProcessId failed");
return nullptr;
}
HANDLE hShellProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION, false, shellProcessId);
if (!hShellProcess)
{
ReportStatus(L"OpenProcess failed");
return nullptr;
}
HANDLE hShellToken = nullptr;
if (!::OpenProcessToken(hShellProcess, TOKEN_DUPLICATE, &hShellToken))
{
ReportStatus(L"OpenProcessToken failed");
::CloseHandle(hShellProcess);
return nullptr;
}
::CloseHandle(hShellProcess);
hShellProcess = nullptr;
constexpr DWORD tokenAccess = TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID;
HANDLE hToken = nullptr;
if (!::DuplicateTokenEx(hShellToken, tokenAccess, nullptr, SecurityImpersonation, TokenPrimary, &hToken))
{
ReportStatus(L"DuplicateTokenEx failed");
return nullptr;
}
// https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createprocesswithtokenw
if (!::CreateProcessWithTokenW(hToken, 0, nullptr, tmp,
CREATE_NEW_PROCESS_GROUP | HIGH_PRIORITY_CLASS, nullptr, nullptr, &si, &pi))
{
(void)GetLastError();
// retry with normal CreateProcess -- maybe elevated assumption didn't apply (as when debugging)
}
::CloseHandle(hToken);
}
if (!launchUsingShellToken || !pi.hProcess)
{
// if launchUsingShellToken was true, then CreateProcessWithTokenW must have failed; retry this way
if (!::CreateProcess(tmp, nullptr, nullptr, nullptr, FALSE,
CREATE_NEW_PROCESS_GROUP | HIGH_PRIORITY_CLASS, nullptr, nullptr, &si, &pi))
{
(void)GetLastError();
ReportStatus(L"CreateProcess failed");
return nullptr;
}
}
::CloseHandle(pi.hThread);
return pi.hProcess;
}
void
ReportStatus(std::wstring msg)
{
msg = L"[OptForAudio] " + msg + L"\n";
::wprintf(msg.c_str());
::OutputDebugStringW(msg.c_str());
}