-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.cpp
More file actions
2547 lines (2149 loc) · 83.8 KB
/
main.cpp
File metadata and controls
2547 lines (2149 loc) · 83.8 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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define _CRT_SECURE_NO_WARNINGS
#define NOMINMAX
#include "gui/gui.h"
#include "Provider.h"
#include "user_config.h"
#include <cctype>
#include <deque>
#include<filesystem>
#include<mutex>
#include <ole2.h>
#include <shlobj_core.h>
#include <stacktrace>
#include <tlhelp32.h>
#define MINIAUDIO_IMPLEMENTATION
#include "miniaudio.h"
#include <comdef.h>
#include <chrono>
#include<fstream>
#include <iomanip>
#include<sstream>
#include<thread>
#include <vector>
#include <array>
#include <functional>
#include <optional>
#include <Windows.h>
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstring>
#include <exception>
#include <memory>
#include <string>
#include <condition_variable>
#include <string_view>
#include <audioclient.h>
#include <mmdeviceapi.h>
#include <audioclientactivationparams.h>
#include <mfapi.h>
template<typename T, typename Func, typename ...Args>
inline void safeCall(T* obj, Func func, Args... args) {
if (obj) {
(obj->*func)(args...);
}
else {
}
}
template<typename T, typename Func, typename ...Args>
inline void safeCall(T* obj, Func func, Args... args, std::function<void()> onNull) {
if (obj) {
(obj->*func)(args...);
}
else {
onNull();
}
}
template<typename T, typename R, typename Func, typename ...Args>
inline std::optional<R> safeCallVal(T* obj, Func func, Args ...args) {
if (obj) {
return (obj->*func)(args...);
}
else {
return std::nullopt;
}
}
using namespace gui;
enum EHotKey {
HOTKEY_STARTSTOP = 1,
HOTKEY_PAUSERESUME = 2,
HOTKEY_RESTART = 3,
HOTKEY_HIDESHOW = 4
};
static int g_Retcode = 0;
static bool g_Running = false;
template <class T>
class CSingleton {
public:
static T& GetInstance() {
static T instance;
return instance;
}
private:
CSingleton() = default;
~CSingleton() = default;
CSingleton(const CSingleton&) = delete;
CSingleton& operator=(const CSingleton&) = delete;
CSingleton(CSingleton&&) = delete;
CSingleton& operator=(CSingleton&&) = delete;
};
class CStringUtils {
public:
static std::string ToUpperCase(const std::string& str) {
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(),
[](unsigned char c) { return std::toupper(c); });
return result;
}
static std::string ToLowerCase(const std::string& str) {
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(),
[](unsigned char c) { return std::tolower(c); });
return result;
}
static bool UnicodeConvert(const std::string& input, std::wstring& output) {
int size_needed = MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, NULL, 0);
if (size_needed == 0) {
return false;
}
std::vector<wchar_t> wide_string(size_needed);
if (MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, &wide_string[0], size_needed) == 0) {
return false;
}
output.assign(wide_string.begin(), wide_string.end() - 1); // Remove null terminator
return true;
}
static bool UnicodeConvert(const std::wstring& input, std::string& output) {
int size_needed = WideCharToMultiByte(CP_UTF8, 0, input.c_str(), -1, NULL, 0, NULL, NULL);
if (size_needed == 0) {
return false;
}
std::vector<char> multi_byte_string(size_needed);
if (WideCharToMultiByte(CP_UTF8, 0, input.c_str(), -1, &multi_byte_string[0], size_needed, NULL, NULL) == 0) {
return false;
}
output.assign(multi_byte_string.begin(), multi_byte_string.end() - 1); // Remove null terminator
return true;
}
static bool _cdecl Replace(std::string& str, const std::string& from, const std::string& to, bool replace_all) {
if (from.empty()) {
return false; // Nothing to replace
}
size_t start_pos = 0;
bool replaced = false;
// Loop until no more occurrences are found
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Move past the replaced part
replaced = true;
// If not replacing all, break after the first replacement
if (!replace_all) {
break;
}
}
return replaced; // Return true if any replacement was made
}
static std::vector<std::string> Split(const std::string& delim, const std::string& str)
{
std::vector<std::string> array;
if (delim.empty()) {
array.push_back(str);
return array;
}
size_t pos = 0, prev = 0;
while ((pos = str.find(delim, prev)) != std::string::npos)
{
array.push_back(str.substr(prev, pos - prev));
prev = pos + delim.length();
}
array.push_back(str.substr(prev));
return array;
}
};
// Command line arguments
class COptionSet {
public:
bool start = false;
std::string filename = "";
bool useFilename = false;
bool exitAfterStop = false;
static bool ParseOptions(const wchar_t* lpCmdLine, std::vector<std::string>& options, std::vector<std::string>& values) {
std::string str;
CStringUtils::UnicodeConvert(lpCmdLine, str);
std::vector<std::string> parsed = CStringUtils::Split(" ", str);
if (parsed.empty()) return false;
for (std::string& arg : parsed) {
if (arg[0] == '-' || arg[0] == '/') {
arg.erase(arg.begin() + 0);
options.push_back(arg);
}
else {
values.push_back(arg);
}
}
return true;
}
};
static COptionSet g_CommandLineOptions;
LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS* exceptionInfo);
struct preset {
std::string name;
std::string command;
};
static preset g_CurrentPreset;
static std::vector<preset> g_Presets = {
{ "Default", "ffmpeg.exe -i %I %i.%f" },
{ "MP3 128k", "ffmpeg.exe -i %I -b:a 128k %i.mp3" },
{ "MP3 192k", "ffmpeg.exe -i %I -b:a 192k %i.mp3" },
{ "MP3 256k", "ffmpeg.exe -i %I -b:a 256k %i.mp3" },
{ "MP3 320k", "ffmpeg.exe -i %I -b:a 320k %i.mp3" },
{ "AAC 128k", "ffmpeg.exe -i %I -c:a aac -b:a 128k %i.m4a" },
{ "AAC 192k", "ffmpeg.exe -i %I -c:a aac -b:a 192k %i.m4a" },
{ "AAC 256k", "ffmpeg.exe -i %I -c:a aac -b:a 256k %i.m4a" },
{ "AAC 320k", "ffmpeg.exe -i %I -c:a aac -b:a 320k %i.m4a" },
{ "OGG Vorbis q5", "ffmpeg.exe -i %I -c:a libvorbis -qscale:a 5 %i.ogg" },
{ "OGG Vorbis q7", "ffmpeg.exe -i %I -c:a libvorbis -qscale:a 7 %i.ogg" },
{ "FLAC (Lossless)", "ffmpeg.exe -i %I -c:a flac %i.flac" }
};
static ma_uint32 sample_rate = 44100;
static ma_uint32 channels = 2;
static ma_uint32 buffer_size = 0;
static std::string filename_signature = "%Y %m %d %H %M %S";
static std::filesystem::path record_path = std::filesystem::current_path() / "recordings";
static std::string audio_format = "wav";
static ma_bool32 sound_events = MA_TRUE;
static ma_bool32 make_stems = MA_FALSE;
static ma_format buffer_format = ma_format_s16;
static constexpr ma_uint32 periods = 256;
static std::string hotkey_start_stop = "Windows+Shift+F1";
static std::string hotkey_pause_resume = "Windows+Shift+F2";
static std::string hotkey_restart = "Windows+Shift+F3";
static std::string hotkey_hide_show = "Windows+Shift+F4";
struct audio_device {
std::wstring name;
ma_device_id id;
};
enum SourceType {
DEVICE_CAPTURE,
DEVICE_LOOPBACK,
APP_LOOPBACK
};
struct application {
std::wstring name;
ma_uint32 id;
};
struct ConfiguredSource {
std::wstring custom_name;
SourceType type;
audio_device device;
application app;
};
static std::vector<ConfiguredSource> g_ConfiguredSources;
static std::string current_preset_name = g_Presets[0].name;
static user_config conf("fp.ini");
static inline std::string _cdecl get_now(bool filename = true) {
auto now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::tm tm = *std::localtime(&now_c);
std::stringstream oss;
oss << std::put_time(&tm, filename ? filename_signature.c_str() : "%Y-%m-%d %H:%M:%S");
return oss.str();
}
bool g_EnableLog = false;
class CLogger {
std::ofstream ofs;
public:
CLogger(const std::string& filename) {
if (g_EnableLog)
ofs.open(filename, std::ios::out | std::ios::app);
}
template <typename T>
CLogger& operator<<(const T& info) {
if (ofs.is_open()) {
ofs << get_now() << " - " << info;
}
return *this;
}
template <typename T>
CLogger& operator<<(T& info) {
if (ofs.is_open()) {
ofs << get_now() << " - " << info;
}
return *this;
}
~CLogger() {
if (ofs.is_open()) {
ofs.close();
}
}
};
static int ExecSystemCmd(const std::string& str, std::string& out)
{
// Convert the command to UTF16 to properly handle unicode path names
wchar_t bufUTF16[10000];
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, bufUTF16, 10000);
// Create a pipe to capture the stdout from the system command
HANDLE pipeRead, pipeWrite;
SECURITY_ATTRIBUTES secAttr = { 0 };
secAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
secAttr.bInheritHandle = TRUE;
secAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&pipeRead, &pipeWrite, &secAttr, 0))
return -1;
// Start the process for the system command, informing the pipe to
// capture stdout, and also to skip showing the command window
STARTUPINFOW si = { 0 };
si.cb = sizeof(STARTUPINFOW);
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.hStdOutput = pipeWrite;
si.hStdError = pipeWrite;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi = { 0 };
BOOL success = CreateProcessW(NULL, bufUTF16, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
if (!success)
{
CloseHandle(pipeWrite);
CloseHandle(pipeRead);
return -1;
}
// Run the command until the end, while capturing stdout
for (; g_Running;)
{
// Wait for a while to allow the process to work
wait(5);
DWORD ret = WaitForSingleObject(pi.hProcess, 50);
if (gui::try_close) {
int result = alert(L"FPWarning", L"You are attempting to close the program while it is converting a recording to another format. If the recording is lengthy, please wait a bit longer. If you believe the program has frozen and will not complete the conversion, click \"Yes\".", MB_YESNO | MB_ICONEXCLAMATION);
if (result == IDYES) {
g_Retcode = 0;
g_Running = false;
}
}
// Read from the stdout if there is any data
for (; g_Running;)
{
char buf[1024];
DWORD readCount = 0;
DWORD availCount = 0;
if (!::PeekNamedPipe(pipeRead, NULL, 0, NULL, &availCount, NULL))
break;
if (availCount == 0)
break;
if (!::ReadFile(pipeRead, buf, sizeof(buf) - 1 < availCount ? sizeof(buf) - 1 : availCount, &readCount, NULL) || !readCount)
break;
buf[readCount] = 0;
out += buf;
}
// End the loop if the process finished
if (ret == WAIT_OBJECT_0)
break;
}
// Get the return status from the process
DWORD status = 0;
GetExitCodeProcess(pi.hProcess, &status);
CloseHandle(pipeRead);
CloseHandle(pipeWrite);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return status;
}
static std::vector<std::wstring> WINAPI get_files(std::wstring path) {
std::vector<std::wstring> files;
try {
for (const auto& entry : std::filesystem::directory_iterator(path)) {
if (std::filesystem::is_regular_file(entry)) {
files.push_back(entry.path().filename().wstring());
}
}
}
catch (...) {
return files;
}
return files;
}
static constexpr std::string_view ma_result_to_string(ma_result result) {
switch (result) {
case MA_SUCCESS: return "Success.";
case MA_ERROR: return "A generic error occurred.";
case MA_INVALID_ARGS: return "Invalid arguments were provided.";
case MA_INVALID_OPERATION: return "The operation is not valid.";
case MA_OUT_OF_MEMORY: return "Out of memory.";
case MA_OUT_OF_RANGE: return "Value is out of range.";
case MA_ACCESS_DENIED: return "Access denied.";
case MA_DOES_NOT_EXIST: return "The specified item does not exist.";
case MA_ALREADY_EXISTS: return "The item already exists.";
case MA_TOO_MANY_OPEN_FILES: return "Too many open files.";
case MA_INVALID_FILE: return "Invalid file format.";
case MA_TOO_BIG: return "The item is too big.";
case MA_PATH_TOO_LONG: return "The path is too long.";
case MA_NAME_TOO_LONG: return "The name is too long.";
case MA_NOT_DIRECTORY: return "Not a directory.";
case MA_IS_DIRECTORY: return "Is a directory.";
case MA_DIRECTORY_NOT_EMPTY: return "Directory is not empty.";
case MA_AT_END: return "Reached the end of the file.";
case MA_NO_SPACE: return "No space left on device.";
case MA_BUSY: return "Resource is busy.";
case MA_IO_ERROR: return "An I/O error occurred.";
case MA_INTERRUPT: return "Operation was interrupted.";
case MA_UNAVAILABLE: return "Resource is unavailable.";
case MA_ALREADY_IN_USE: return "Resource is already in use.";
case MA_BAD_ADDRESS: return "Bad address.";
case MA_BAD_SEEK: return "Bad seek operation.";
case MA_BAD_PIPE: return "Bad pipe.";
case MA_DEADLOCK: return "Deadlock detected.";
case MA_TOO_MANY_LINKS: return "Too many links.";
case MA_NOT_IMPLEMENTED: return "Operation not implemented.";
case MA_NO_MESSAGE: return "No message available.";
case MA_BAD_MESSAGE: return "Bad message received.";
case MA_NO_DATA_AVAILABLE: return "No data available.";
case MA_INVALID_DATA: return "Invalid data received.";
case MA_TIMEOUT: return "Operation timed out.";
case MA_NO_NETWORK: return "No network available.";
case MA_NOT_UNIQUE: return "Not unique resource.";
case MA_NOT_SOCKET: return "Not a socket.";
case MA_NO_ADDRESS: return "No address found.";
case MA_BAD_PROTOCOL: return "Bad protocol specified.";
case MA_PROTOCOL_UNAVAILABLE: return "Protocol is unavailable.";
case MA_PROTOCOL_NOT_SUPPORTED: return "Protocol not supported.";
case MA_PROTOCOL_FAMILY_NOT_SUPPORTED: return "Protocol family not supported.";
case MA_ADDRESS_FAMILY_NOT_SUPPORTED: return "Address family not supported.";
case MA_SOCKET_NOT_SUPPORTED: return "Socket type not supported.";
case MA_CONNECTION_RESET: return "Connection was reset.";
case MA_ALREADY_CONNECTED: return "Already connected.";
case MA_NOT_CONNECTED: return "Not connected.";
case MA_CONNECTION_REFUSED: return "Connection refused.";
case MA_NO_HOST: return "No host found.";
case MA_IN_PROGRESS: return "Operation in progress.";
case MA_CANCELLED: return "Operation was cancelled.";
case MA_MEMORY_ALREADY_MAPPED: return "Memory is already mapped.";
/* General non-standard errors. */
case MA_CRC_MISMATCH: return "CRC mismatch error.";
/* General miniaudio-specific errors. */
case MA_FORMAT_NOT_SUPPORTED: return "Audio format not supported.";
case MA_DEVICE_TYPE_NOT_SUPPORTED: return "Device type not supported.";
case MA_SHARE_MODE_NOT_SUPPORTED: return "Share mode not supported for this device.";
case MA_NO_BACKEND: return "No backend available for audio playback.";
case MA_NO_DEVICE: return "No audio device available.";
case MA_API_NOT_FOUND: return "API not found for audio backend.";
case MA_INVALID_DEVICE_CONFIG: return "Invalid device configuration specified.";
case MA_LOOP: return "Looping detected in operation.";
case MA_BACKEND_NOT_ENABLED: return "Audio backend not enabled.";
/* State errors. */
case MA_DEVICE_NOT_INITIALIZED: return "Audio device has not been initialized.";
case MA_DEVICE_ALREADY_INITIALIZED: return "Audio device has already been initialized.";
case MA_DEVICE_NOT_STARTED: return "Audio device has not been started.";
case MA_DEVICE_NOT_STOPPED: return "Audio device has not been stopped.";
/* Operation errors. */
case MA_FAILED_TO_INIT_BACKEND: return "Failed to initialize audio backend.";
case MA_FAILED_TO_OPEN_BACKEND_DEVICE: return "Failed to open audio backend device.";
case MA_FAILED_TO_START_BACKEND_DEVICE: return "Failed to start audio backend device.";
case MA_FAILED_TO_STOP_BACKEND_DEVICE: return "Failed to stop audio backend device.";
default:
return "Unknown error code.";
}
return "";
}
static ma_result g_MaLastError = MA_SUCCESS;
static void CheckIfError(const ma_result& result) {
g_MaLastError = MA_SUCCESS;
if (result == MA_SUCCESS) {
return;
}
g_MaLastError = result;
std::wstring error_u;
std::stringstream ss;
std::stacktrace st = std::stacktrace::current();
ss << ma_result_to_string(result).data() << std::endl;
ss << st;
CStringUtils::UnicodeConvert(ss.str(), error_u);
alert(L"FPRuntimeError", error_u, MB_ICONERROR);
g_Retcode = result;
g_Running = false;
}
class MINIAUDIO_IMPLEMENTATION CAudioContext {
std::unique_ptr<ma_context> context;
public:
CAudioContext() : context(nullptr) {
context = std::make_unique<ma_context>();
CheckIfError(ma_context_init(NULL, 0, NULL, &*context));
}
~CAudioContext() {
ma_context_uninit(&*context);
context.reset();
}
inline operator ma_context* () {
return &*context;
}
};
#define g_AudioContext CSingleton<CAudioContext>::GetInstance()
class MINIAUDIO_IMPLEMENTATION CSoundStream {
std::unique_ptr<ma_engine> m_Engine;
std::unique_ptr<ma_sound> m_Player;
std::unique_ptr<ma_waveform> m_Waveform;
std::wstring current_file;
public:
enum ESoundEvent : std::int8_t {
SOUND_EVENT_NONE = 0,
SOUND_EVENT_START_RECORDING,
SOUND_EVENT_STOP_RECORDING,
SOUND_EVENT_PAUSE_RECORDING,
SOUND_EVENT_RESUME_RECORDING,
SOUND_EVENT_RESTART_RECORDING,
SOUND_EVENT_RECORD_MANAGER,
SOUND_EVENT_ERROR = -1,
};
CSoundStream() : m_Engine(nullptr), m_Player(nullptr), m_Waveform(nullptr) { Initialize(); }
~CSoundStream() {
Uninitialize();
}
bool Initialize() {
if (m_Engine) {
return true;
}
m_Engine = std::make_unique<ma_engine>();
ma_engine_config cfg = ma_engine_config_init();
cfg.sampleRate = sample_rate;
cfg.channels = channels;
CheckIfError(ma_engine_init(&cfg, &*m_Engine));
return g_MaLastError == MA_SUCCESS;
}
bool Uninitialize() {
Close();
if (m_Engine) {
ma_engine_uninit(&*m_Engine);
m_Engine.reset();
}
return true;
}
inline bool Reinitialize() {
return Uninitialize() && Initialize();
}
inline operator ma_sound* () {
return &*m_Player;
}
inline operator ma_engine* () {
return &*m_Engine;
}
bool Play(const std::wstring& filename) {
if (!Initialize()) {
return false;
}
if (filename == current_file and m_Player) {
return ma_sound_start(&*m_Player) == MA_SUCCESS;
}
Close();
if (!m_Player) {
m_Player = std::make_unique<ma_sound>();
g_MaLastError = ma_sound_init_from_file_w(&*m_Engine, filename.c_str(), MA_SOUND_FLAG_NO_SPATIALIZATION | MA_SOUND_FLAG_NO_PITCH, nullptr, nullptr, &*m_Player);
if (g_MaLastError == MA_SUCCESS) {
g_MaLastError = ma_sound_start(&*m_Player);
current_file = filename;
}
return g_MaLastError == MA_SUCCESS;
}
return false;
}
inline bool Play(const std::string& filename) {
std::wstring filename_u;
CStringUtils::UnicodeConvert(filename, filename_u);
return Play(filename_u);
}
bool PlayEvent(const CSoundStream::ESoundEvent& evt) {
if (!Initialize()) {
return false;
}
Close();
if (!m_Player) {
ma_waveform_config cfg = ma_waveform_config_init(ma_format_f32, ma_engine_get_channels(&*m_Engine), ma_engine_get_sample_rate(&*m_Engine), ma_waveform_type_sine, 0.3, 1200);
m_Waveform = std::make_unique<ma_waveform>();
g_MaLastError = ma_waveform_init(&cfg, &*m_Waveform);
if (g_MaLastError == MA_SUCCESS) {
m_Player = std::make_unique<ma_sound>();
g_MaLastError = ma_sound_init_from_data_source(&*m_Engine, (ma_data_source*)&*m_Waveform, MA_SOUND_FLAG_NO_SPATIALIZATION | MA_SOUND_FLAG_NO_PITCH, nullptr, &*m_Player);
if (g_MaLastError == MA_SUCCESS) {
g_MaLastError = ma_sound_start(&*m_Player);
}
}
gui::wait(20);
ma_sound_stop(&*m_Player);
gui::wait(20);
double freq = cfg.frequency;
switch (evt) {
case SOUND_EVENT_RECORD_MANAGER:
freq = freq + 50;
break;
case SOUND_EVENT_RESTART_RECORDING:
freq = freq != 0 ? freq / 2 : freq + 16 * 2;
break;
case SOUND_EVENT_RESUME_RECORDING:
case SOUND_EVENT_PAUSE_RECORDING:
freq = evt == SOUND_EVENT_RESUME_RECORDING ? freq + 130 : freq - 130;
break;
case SOUND_EVENT_START_RECORDING:
case SOUND_EVENT_STOP_RECORDING:
freq = evt == SOUND_EVENT_START_RECORDING ? freq + 200 : freq - 200;
break;
default:
freq = freq - 333;
break;
}
ma_waveform_set_frequency(&*m_Waveform, freq);
ma_sound_start(&*m_Player);
gui::wait(30);
Close();
return g_MaLastError == MA_SUCCESS;
}
return false;
}
void Close() {
if (m_Waveform) {
ma_waveform_uninit(&*m_Waveform);
m_Waveform.reset();
}
if (m_Player) {
ma_sound_uninit(&*m_Player);
m_Player.reset();
}
}
void Stop() {
if (m_Player) {
ma_sound_seek_to_pcm_frame(&*m_Player, 0);
ma_sound_stop(&*m_Player);
}
}
void Pause() {
if (m_Player) {
ma_sound_stop(&*m_Player);
}
}
bool Play() {
if (m_Player)
return ma_sound_start(&*m_Player) == MA_SUCCESS;
return false;
}
};
#define g_SoundStream CSingleton<CSoundStream>::GetInstance()
static bool ma_format_convert(const std::string& format, ma_format& value)
{
std::string str = CStringUtils::ToLowerCase(format);
if (str == "u8") {
value = ma_format_u8;
}
else if (str == "s16") {
value = ma_format_s16;
}
else if (str == "s24") {
value = ma_format_s24;
}
else if (str == "s32") {
value = ma_format_s32;
}
else if (str == "f32") {
value = ma_format_f32;
}
else {
return false;
}
return true;
}
static bool ma_format_convert(const ma_format& format, std::string& value) {
switch (format) {
case ma_format_u8:
value = "u8";
break;
case ma_format_s16:
value = "s16";
break;
case ma_format_s24:
value = "s24";
break;
case ma_format_s32:
value = "s32";
break;
case ma_format_f32:
value = "f32";
break;
default:
return false;
}
return true;
}
static bool ma_device_type_convert(const std::string& type, ma_device_type& value)
{
std::string str = CStringUtils::ToLowerCase(type);
if (str == "mic") {
value = ma_device_type_capture;
}
else if (str == "loopback") {
value = ma_device_type_loopback;
}
else {
return false;
}
return true;
}
static bool ma_device_type_convert(const ma_device_type& type, std::string& value) {
switch (type) {
case ma_device_type_capture:
value = "mic";
break;
case ma_device_type_loopback:
value = "loopback";
break;
default:
return false;
}
return true;
}
static inline std::optional<bool> str_to_bool(const std::string& val) {
std::string str = CStringUtils::ToLowerCase(val);
if (str == "0" || str == "false") {
return false;
}
else if (str == "1" || str == "true") {
return true;
}
return std::nullopt;
}
using namespace std;
bool g_Recording = false;
bool g_RecordingPaused = false;
static std::vector<application> WINAPI get_tasklist() {
std::vector<application> tasklist;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot != INVALID_HANDLE_VALUE) {
PROCESSENTRY32W pe32;
pe32.dwSize = sizeof(PROCESSENTRY32W);
if (Process32FirstW(hSnapshot, &pe32)) {
do {
application app;
app.name = pe32.szExeFile;
app.id = pe32.th32ProcessID;
tasklist.push_back(app);
} while (Process32NextW(hSnapshot, &pe32));
}
CloseHandle(hSnapshot);
}
return tasklist;
}
struct AudioData {
float* buffer;
ma_uint64 frameCount;
};
struct RecordingSource {
std::deque<AudioData> queue;
std::mutex mutex;
std::condition_variable condition;
std::wstring name;
};
struct CallbackUserData {
size_t sourceIndex;
};
static std::vector<std::unique_ptr<RecordingSource>> g_RecordingSources;
static std::vector<std::unique_ptr<CallbackUserData>> g_CallbackUserData;
static std::vector<audio_device> g_SelectedCaptureDevices;
static std::vector<audio_device> g_SelectedLoopbackDevices;
static std::atomic<bool> thread_shutdown = false;
static std::atomic<bool> paused = false;
class CompletionHandler : public IActivateAudioInterfaceCompletionHandler, public IAgileObject {
public:
CompletionHandler() : _refCount(1), activate_hr(E_FAIL), client(nullptr) {
event_finished = CreateEvent(nullptr, TRUE, FALSE, nullptr);
}
~CompletionHandler() {
if (event_finished) CloseHandle(event_finished);
if (client) client->Release();
}
// IUnknown
ULONG STDMETHODCALLTYPE AddRef() override { return InterlockedIncrement(&_refCount); }
ULONG STDMETHODCALLTYPE Release() override {
ULONG ulRef = InterlockedDecrement(&_refCount);
if (0 == ulRef) {
delete this;
}
return ulRef;
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject) override {
if (riid == IID_IUnknown || riid == __uuidof(IActivateAudioInterfaceCompletionHandler)) {
*ppvObject = this;
AddRef();
return S_OK;
}
else if (riid == __uuidof(IAgileObject)) {
*ppvObject = this;
AddRef();
return S_OK;
}
*ppvObject = nullptr;
return E_NOINTERFACE;
}
// IActivateAudioInterfaceCompletionHandler
STDMETHOD(ActivateCompleted)(IActivateAudioInterfaceAsyncOperation* operation) override {
if (operation) {
IUnknown* pUnknown = nullptr;
HRESULT hr_activate_result = E_FAIL;
operation->GetActivateResult(&hr_activate_result, &pUnknown);
activate_hr = hr_activate_result;
if (SUCCEEDED(activate_hr) && pUnknown) {
pUnknown->QueryInterface(IID_PPV_ARGS(&client));
pUnknown->Release();
}
}
SetEvent(event_finished);
return S_OK;
}
HRESULT activate_hr;
IAudioClient* client;
HANDLE event_finished;
private:
LONG _refCount;
};
class AppLoopbackCapture {
private:
std::thread m_thread;
std::atomic<bool> m_shutdown_flag{ false };
HANDLE m_shutdown_event = nullptr;
HANDLE m_packet_ready_event = nullptr;
DWORD m_pid;
RecordingSource* m_target_queue;
WAVEFORMATEX m_format;
IAudioClient* m_client = nullptr;
IAudioCaptureClient* m_capture_client = nullptr;
public:
AppLoopbackCapture(DWORD pid, RecordingSource* target_queue, ma_uint32 sampleRate, ma_uint32 numChannels)
: m_pid(pid), m_target_queue(target_queue) {
m_format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
m_format.nChannels = numChannels;
m_format.nSamplesPerSec = sampleRate;
m_format.wBitsPerSample = sizeof(float) * 8;
m_format.nBlockAlign = m_format.nChannels * sizeof(float);
m_format.nAvgBytesPerSec = m_format.nSamplesPerSec * m_format.nBlockAlign;
m_format.cbSize = 0;
m_shutdown_event = CreateEvent(nullptr, FALSE, FALSE, nullptr);
m_packet_ready_event = CreateEvent(nullptr, FALSE, FALSE, nullptr);
}
~AppLoopbackCapture() {
Stop();
if (m_shutdown_event) CloseHandle(m_shutdown_event);
if (m_packet_ready_event) CloseHandle(m_packet_ready_event);
}
void Start() {
m_shutdown_flag = false;
m_thread = std::thread(&AppLoopbackCapture::CaptureThread, this);
m_thread.detach();