-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathacmx.cpp
More file actions
2374 lines (2162 loc) · 93.9 KB
/
acmx.cpp
File metadata and controls
2374 lines (2162 loc) · 93.9 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
#include "version_info.hpp"
#include <mx.hpp>
#include <argz.hpp>
#include <gl.hpp>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>
#include <tuple>
#include <unordered_map>
#include <opencv2/opencv.hpp>
#include <filesystem>
#include <chrono>
#include <thread>
#include <ctime>
#include <optional>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <atomic>
#include <iomanip>
#include <ctime>
#include <sstream>
#include <deque>
#include <mxwrite.hpp>
#ifdef AUDIO_ENABLED
#include "audio.hpp"
#endif
#include<string_view>
#include <deque>
#include <opencv2/opencv.hpp>
#include <model.hpp>
#include <glm/gtc/matrix_transform.hpp>
void transfer_audio(std::string_view, std::string_view);
class SnapshotThreadPool {
public:
SnapshotThreadPool(size_t threads) : stop(false) {
for(size_t i = 0; i < threads; ++i)
workers.emplace_back([this] {
for(;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); });
if(this->stop) {
return;
}
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
template<class F>
void enqueue(F&& f) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
if(stop) throw std::runtime_error("enqueue on stopped SnapshotThreadPool");
tasks.emplace(std::forward<F>(f));
}
condition.notify_one();
}
~SnapshotThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
class FrameCache {
public:
explicit FrameCache(std::size_t num)
: num_frames(num) {
}
~FrameCache() = default;
void push(cv::Mat&& frame) {
if (frames.size() < num_frames) {
frames.emplace_back(std::move(frame));
} else {
frames.pop_front();
frames.emplace_back(std::move(frame));
}
}
cv::Mat& at(std::size_t index) {
return frames.at(index);
}
cv::Mat& operator[](std::size_t index) { return frames[index]; }
std::size_t size() const {
return frames.size();
}
bool isFull() {
if(size() == num_frames)
return true;
return false;
}
void fill(cv::Mat &frame) {
for(size_t i = 0; i < num_frames; ++i) {
if(frames.size() < num_frames)
frames.push_back(frame);
}
}
private:
std::size_t num_frames;
std::deque<cv::Mat> frames;
};
class ShaderLibrary {
float alpha = 1.0;
float time_f = 1.0;
bool time_active = true;
bool is3d = false;
public:
ShaderLibrary() = default;
~ShaderLibrary() {}
void loadProgram(gl::GLWindow *win, const std::string text) {
programs.push_back(std::make_unique<gl::ShaderProgram>());
if(is3d == true) {
if(!programs.back()->loadProgram(win->util.getFilePath("data/vertex.glsl"), text)) {
throw mx::Exception("Error loading shader program: " + text);
}
} else {
if(!programs.back()->loadProgram(win->util.getFilePath("data/vert.glsl"), text)) {
throw mx::Exception("Error loading shader program: " + text);
}
}
GLenum error;
error = glGetError();
if(error != GL_NO_ERROR){
throw mx::Exception("OpenGL Error: on ShaderLibary::loadProgram: " + std::to_string(error));
}
programs.back()->useProgram();
GLint loc = glGetUniformLocation(programs.back()->id(), "iResolution");
glUniform2f(loc, win->w, win->h);
error = glGetError();
if(error != GL_NO_ERROR) {
throw mx::Exception("setUniform");
}
mx::system_out << "acmx2: Compiled Shader 0: " << text << "\n";
std::filesystem::path file_path(text);
std::string name = file_path.stem().string();
if(!name.empty()) {
size_t pos = programs.size()-1;
program_names[pos].name = name;
program_names[pos].loc = glGetUniformLocation(programs.back()->id(), "alpha");
program_names[pos].iTime = glGetUniformLocation(programs.back()->id(), "iTime");
program_names[pos].iMouse = glGetUniformLocation(programs.back()->id(), "iMouse");
program_names[pos].time_f = glGetUniformLocation(programs.back()->id(), "time_f");
program_names[pos].iResolution = glGetUniformLocation(programs.back()->id(), "iResolution");
program_names[pos].iFrame = glGetUniformLocation(programs.back()->id(), "iFrame");
program_names[pos].iTimeDelta = glGetUniformLocation(programs.back()->id(), "iTimeDelta");
program_names[pos].iDate = glGetUniformLocation(programs.back()->id(), "iDate");
program_names[pos].iFrameRate = glGetUniformLocation(programs.back()->id(), "iFrameRate");
program_names[pos].iMouseClick = glGetUniformLocation(programs.back()->id(), "iMouseClick");
for(int i = 0; i < 4; ++i) {
std::string channelTime = "iChannelTime[" + std::to_string(i) + "]";
std::string channelRes = "iChannelResolution[" + std::to_string(i) + "]";
program_names[pos].iChannelTime[i] = glGetUniformLocation(programs.back()->id(), channelTime.c_str());
program_names[pos].iChannelResolution[i] = glGetUniformLocation(programs.back()->id(), channelRes.c_str());
}
if(name.find("cache") != std::string::npos) {
for(int i = 0; i < 4; ++i) {
program_names[pos].texture_cache_loc[i] = glGetUniformLocation(programs.back()->id(), std::string("samp" + std::to_string(i+1)).c_str());
}
}
#ifdef AUDIO_ENABLED
program_names[pos].amp = glGetUniformLocation(programs.back()->id(), "amp");
program_names[pos].amp_untouched = glGetUniformLocation(programs.back()->id(), "uamp");
program_names[pos].iSampleRate = glGetUniformLocation(programs.back()->id(), "iSampleRate");
#endif
}
}
void setFPS(float fps_value) {
GLuint iFrameRateLoc = program_names[index()].iFrameRate;
if(iFrameRateLoc != GL_INVALID_INDEX) {
glUniform1f(iFrameRateLoc, fps_value);
}
}
void setUniform(const std::string &name, int value) {
glUniform1i(program_names[index()].texture_cache_loc[value], value+1);
}
void is3D(bool is3d) {
this->is3d = is3d;
}
void toggleBypass() {
shader_bypass = !shader_bypass;
std::string state = shader_bypass ? "disabled" : "enabled";
mx::system_out << "acmx2: Shader processing " << state << "\n";
fflush(stdout);
}
bool isBypassed() const {
return shader_bypass;
}
void loadPrograms(gl::GLWindow *win, const std::string &text) {
std::fstream file;
file.open(text + "/index.txt", std::ios::in);
if(!file.is_open()) {
throw mx::Exception("acmx2: Could not load index.txt at shader path: " + text);
}
size_t index = 0;
GLenum error;
while(!file.eof()) {
std::string line_data;
std::getline(file, line_data);
if(file && !line_data.empty() && std::filesystem::exists(text + "/" + line_data) && line_data.find("material") == std::string::npos) {
programs.push_back(std::make_unique<gl::ShaderProgram>());
mx::system_out << "acmx2: Compiling Shader: " << index++ << ": [" << line_data << "]\n";
fflush(stdout);
fflush(stderr);
try {
if(is3d == true) {
if(!programs.back()->loadProgram(win->util.getFilePath("data/vertex.glsl"), text + "/" + line_data)) {
throw mx::Exception("acmx2: Error could not load shader: " + line_data);
}
} else {
if(!programs.back()->loadProgram(win->util.getFilePath("data/vert.glsl"), text + "/" + line_data)) {
throw mx::Exception("acmx2: Error could not load shader: " + line_data);
}
}
} catch(mx::Exception &e) {
mx::system_err << "\n";
fflush(stdout);
fflush(stderr);
throw;
}
error = glGetError();
if(error != GL_NO_ERROR) {
throw mx::Exception("OpenGL Error loading shader program");
}
programs.back()->useProgram();
//programs.back()->setUniform("proj_matrix", glm::mat4(1.0f));
//programs.back()->setUniform("mv_matrix", glm::mat4(1.0f));
GLint loc = glGetUniformLocation(programs.back()->id(), "iResolution");
glUniform2f(loc, win->w, win->h);
error = glGetError();
if(error != GL_NO_ERROR) {
throw mx::Exception("setUniform");
}
fflush(stdout);
fflush(stderr);
std::filesystem::path file_path(line_data);
std::string name = file_path.stem().string();
if(!name.empty()) {
size_t pos = programs.size()-1;
program_names[pos].name = name;
program_names[pos].loc = glGetUniformLocation(programs.back()->id(), "alpha");
program_names[pos].iTime = glGetUniformLocation(programs.back()->id(), "iTime");
program_names[pos].iMouse = glGetUniformLocation(programs.back()->id(), "iMouse");
program_names[pos].time_f = glGetUniformLocation(programs.back()->id(), "time_f");
program_names[pos].iResolution = glGetUniformLocation(programs.back()->id(), "iResolution");
program_names[pos].iFrame = glGetUniformLocation(programs.back()->id(), "iFrame");
program_names[pos].iTimeDelta = glGetUniformLocation(programs.back()->id(), "iTimeDelta");
program_names[pos].iDate = glGetUniformLocation(programs.back()->id(), "iDate");
program_names[pos].iFrameRate = glGetUniformLocation(programs.back()->id(), "iFrameRate");
program_names[pos].iMouseClick = glGetUniformLocation(programs.back()->id(), "iMouseClick");
for(int i = 0; i < 4; ++i) {
std::string channelTime = "iChannelTime[" + std::to_string(i) + "]";
std::string channelRes = "iChannelResolution[" + std::to_string(i) + "]";
program_names[pos].iChannelTime[i] = glGetUniformLocation(programs.back()->id(), channelTime.c_str());
program_names[pos].iChannelResolution[i] = glGetUniformLocation(programs.back()->id(), channelRes.c_str());
}
if(name.find("cache") != std::string::npos) {
for(int i = 0; i < 4; ++i) {
program_names[pos].texture_cache_loc[i] = glGetUniformLocation(programs.back()->id(), std::string("samp" + std::to_string(i+1)).c_str());
}
}
#ifdef AUDIO_ENABLED
program_names[pos].amp = glGetUniformLocation(programs.back()->id(), "amp");
program_names[pos].amp_untouched = glGetUniformLocation(programs.back()->id(), "uamp");
program_names[pos].iSampleRate = glGetUniformLocation(programs.back()->id(), "iSampleRate");
#endif
}
}
}
file.close();
}
bool isCache() {
if(library_index < program_names.size() && program_names[library_index].name.find("cache") != std::string::npos)
return true;
return false;
}
void setIndex(size_t i) {
if(i < programs.size()) {
library_index = i;
mx::system_out << "acmx2: Set Shader to Index: " << i << " [" << program_names[i].name << "]\n";
fflush(stdout);
}
}
void inc() {
if(library_index+1 < programs.size())
setIndex(library_index+1);
}
void dec() {
if(library_index > 0)
setIndex(library_index-1);
}
size_t index() { return library_index; }
size_t size() { return programs.size(); }
void useProgram() {
programs[index()]->useProgram();
}
gl::ShaderProgram *shader() { return programs[index()].get(); }
gl::ShaderProgram *getShader(size_t idx) {
if(idx < programs.size()) {
return programs[idx].get();
}
return nullptr;
}
std::string getFullShaderName() {
if(program_names.find(library_index) != program_names.end()) {
return std::to_string(library_index) + ": " + program_names[library_index].name;
}
return std::to_string(library_index);
}
std::string getFullShaderName(const std::vector<int> &pass_list) {
std::string name = getFullShaderName();
if(!pass_list.empty()) {
name += " [";
for(size_t i = 0; i < pass_list.size(); ++i) {
int idx = pass_list[i];
if(program_names.find(idx) != program_names.end()) {
name += program_names[idx].name;
} else {
name += std::to_string(idx);
}
if(i + 1 < pass_list.size()) {
name += ", ";
}
}
name += "]";
}
return name;
}
void updateShaderUniforms(gl::GLWindow *win, size_t idx) {
if(idx >= programs.size()) return;
if(program_names.find(idx) == program_names.end()) return;
static Uint64 start_time = SDL_GetPerformanceCounter();
static Uint64 last_frame_time = start_time;
static uint64_t frame_counter = 0;
Uint64 now_time = SDL_GetPerformanceCounter();
double elapsed_time = (double)(now_time - start_time) / SDL_GetPerformanceFrequency();
double delta_time = (double)(now_time - last_frame_time) / SDL_GetPerformanceFrequency();
last_frame_time = now_time;
frame_counter++;
auto &n = program_names[idx];
programs[idx]->useProgram();
glUniform1f(n.loc, alpha);
glUniform1f(n.iTime, static_cast<float>(elapsed_time));
glUniform1f(n.time_f, time_f);
glUniform1i(n.iFrame, static_cast<int>(frame_counter % INT_MAX));
glUniform1f(n.iTimeDelta, static_cast<float>(delta_time));
auto now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::tm *localTime = std::localtime(&now_c);
float year = static_cast<float>(localTime->tm_year + 1900);
float month = static_cast<float>(localTime->tm_mon + 1);
float day = static_cast<float>(localTime->tm_mday);
float seconds = static_cast<float>(localTime->tm_hour * 3600 +
localTime->tm_min * 60 +
localTime->tm_sec);
glUniform4f(n.iDate, year, month, day, seconds);
if(n.iFrameRate != GL_INVALID_INDEX) {
glUniform1f(n.iFrameRate, 24.0f);
}
int mouseX = 0, mouseY = 0;
SDL_GetMouseState(&mouseX, &mouseY);
float currentY = static_cast<float>(win->h - mouseY);
float currentX = static_cast<float>(mouseX);
glUniform4f(n.iMouse, currentX, currentY, 0.0f, 0.0f);
if(n.iMouseClick != GL_INVALID_INDEX) {
glUniform2f(n.iMouseClick, currentX, currentY);
}
glUniform2f(n.iResolution, static_cast<float>(win->w), static_cast<float>(win->h));
}
void update(gl::GLWindow *win) {
static Uint64 start_time = SDL_GetPerformanceCounter();
static Uint64 last_frame_time = start_time;
static uint64_t frame_counter = 0;
Uint64 now_time = SDL_GetPerformanceCounter();
double elapsed_time = (double)(now_time - start_time) / SDL_GetPerformanceFrequency();
double delta_time = (double)(now_time - last_frame_time) / SDL_GetPerformanceFrequency();
last_frame_time = now_time;
frame_counter++;
if(time_audio == false && time_active) {
time_f = static_cast<float>(elapsed_time);
} else {
#ifdef AUDIO_ENABLED
if(time_audio) {
time_f += (get_amp() * get_sense());
}
#endif
}
if(std::isnan(time_f) || std::isinf(time_f))
time_f = 1.0;
GLuint time_f_loc = program_names[index()].time_f;
glUniform1f(time_f_loc, time_f);
GLint loc = program_names[index()].loc;
glUniform1f(loc, alpha);
GLuint iTimeLoc = program_names[index()].iTime;
double currentTime = (double)SDL_GetTicks64() / 1000.0f;
glUniform1f(iTimeLoc, currentTime);
GLuint iFrameLoc = program_names[index()].iFrame;
glUniform1i(iFrameLoc, static_cast<int>(frame_counter % INT_MAX));
GLuint iTimeDeltaLoc = program_names[index()].iTimeDelta;
glUniform1f(iTimeDeltaLoc, static_cast<float>(delta_time));
GLuint iDateLoc = program_names[index()].iDate;
auto now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::tm* localTime = std::localtime(&now_c);
float year = static_cast<float>(localTime->tm_year + 1900);
float month = static_cast<float>(localTime->tm_mon + 1);
float day = static_cast<float>(localTime->tm_mday);
float seconds = static_cast<float>(localTime->tm_hour * 3600 +
localTime->tm_min * 60 +
localTime->tm_sec);
glUniform4f(iDateLoc, year, month, day, seconds);
GLuint iFrameRateLoc = program_names[index()].iFrameRate;
if(iFrameRateLoc != GL_INVALID_INDEX) {
glUniform1f(iFrameRateLoc, 24.0f);
}
static bool isDragging = false;
static bool wasClicked = false;
static float clickStartX = 0.0f;
static float clickStartY = 0.0f;
static float lastClickX = 0.0f;
static float lastClickY = 0.0f;
GLuint iMouseLoc = program_names[index()].iMouse;
GLuint iMouseClickLoc = program_names[index()].iMouseClick;
int mouseX = 0, mouseY = 0;
Uint32 mouseState = SDL_GetMouseState(&mouseX, &mouseY);
float currentY = static_cast<float>(win->h - mouseY);
float currentX = static_cast<float>(mouseX);
if (mouseState & SDL_BUTTON(SDL_BUTTON_LEFT)) {
if (!isDragging) {
clickStartX = currentX;
clickStartY = currentY;
lastClickX = currentX;
lastClickY = currentY;
isDragging = true;
wasClicked = true;
}
} else {
isDragging = false;
}
if (isDragging) {
glUniform4f(iMouseLoc, currentX, currentY, clickStartX, clickStartY);
} else {
glUniform4f(iMouseLoc, currentX, currentY, 0.0f, 0.0f);
}
if(wasClicked && iMouseClickLoc != GL_INVALID_INDEX) {
glUniform2f(iMouseClickLoc, lastClickX, lastClickY);
}
GLuint iResolution = program_names[index()].iResolution;
glUniform2f(iResolution, win->w, win->h);
#ifdef AUDIO_ENABLED
GLuint amp_i = program_names[index()].amp;
static float amplitude = 1.0;
float new_amp = amplitude + (get_amp() * get_sense());
if (std::isnan(new_amp) || std::isinf(new_amp) || new_amp > 1e6f) {
amplitude = 1.0f;
} else {
amplitude = new_amp;
}
glUniform1f(amp_i, amplitude);
GLuint amp_u = program_names[index()].amp_untouched;
glUniform1f(amp_u, get_amp());
GLuint iSampleRateLoc = program_names[index()].iSampleRate;
if(iSampleRateLoc != GL_INVALID_INDEX) {
glUniform1f(iSampleRateLoc, 44100.0f);
}
#endif
}
void incTime(float value) {
if(!time_active) {
time_f += value;
mx::system_out << "acmx2: Time step forward: " << time_f << "\n";
fflush(stdout);
}
}
void decTime(float value) {
if(!time_active) {
if(time_f - value > 1.0) {
time_f -= value;
mx::system_out << "acmx2: Time step back: " << time_f << "\n";
} else {
time_f = 1.0f;
mx::system_out << "acmx2: Time reset to: " << time_f << "\n";
}
fflush(stdout);
}
}
void activeTime(bool t) {
time_active = t;
std::string enabled = ((t == true) ? "on" : "off");
mx::system_out << "acmx2: active time: " << enabled << "\n";
fflush(stdout);
}
void audioTime(bool t) {
time_audio = t;
std::string enabled = ((t == true) ? "on" : "off");
mx::system_out << "acmx2: audio time: " << enabled << "\n";
fflush(stdout);
}
#ifdef AUDIO_ENABLED
bool timeActive() const { return time_active; }
bool timeAudio() const { return time_audio; }
#endif
void event(SDL_Event &e) { }
private:
size_t library_index = 0;
std::vector<std::unique_ptr<gl::ShaderProgram>> programs;
struct ProgramData {
std::string name;
GLuint loc, iTime, iMouse, time_f, iResolution;
#ifdef AUDIO_ENABLED
GLuint amp, amp_untouched;
#endif
GLuint texture_cache_loc[4];
GLuint iFrame;
GLuint iTimeDelta;
GLuint iDate;
GLuint iChannelTime[4];
GLuint iChannelResolution[4];
GLuint iSampleRate;
GLuint iFrameRate;
GLuint iMouseClick;
};
bool time_audio = false;
std::unordered_map<int, ProgramData> program_names;
bool shader_bypass = false;
};
struct MXArguments {
std::string path, filename, ofilename;
std::string graphic_file;
int audio_input = -1, audio_output = -1;
int tw = 1280, th = 720;
std::string crf = "23";
int camera_device = 0;
std::string library = "./filters";
std::string fragment = "./frag.glsl";
std::string prefix_path = ".";
std::string model_file = "cube.mxmod.z";
int mode = 0;
int shader_index = 0;
std::optional<cv::Size> sizev = std::nullopt;
std::optional<cv::Size> csize = std::nullopt;
double fps_value = 24.0;
bool repeat = false;
std::tuple<int, std::string, int> slib;
bool full = false;
bool cache = false;
int cache_delay = 1;
bool copy_audio = false;
bool is3d = false;
#ifdef AUDIO_ENABLED
bool audio_enabled = false;
unsigned int audio_channels = 2;
float audio_sensitivty = 0.25f;
#endif
std::vector<int> shader_pass_list;
bool shader_pass_enabled = false;
};
struct FrameData {
std::vector<unsigned char> pixels;
int width = 0;
int height = 0;
bool isSnapshot = false;
};
class ACView : public gl::GLObject {
#ifdef AUDIO_ENABLED
bool audio_is_enabled = false;
int audio_input_device;
int audio_output_device;
#endif
bool isPaused = false;
bool isFrozen = false;
GLuint pboIds[2] = {0, 0};
int pboIndex = 0;
int pboNextIndex = 1;
SnapshotThreadPool snapshot_pool{2};
public:
ACView(const MXArguments &args)
: crf{args.crf},
prefix_path{args.prefix_path},
filename{args.filename},
ofilename{args.ofilename},
graphic{args.graphic_file},
camera_index{args.camera_device},
flib{args.slib},
sizev{args.sizev},
sizec{args.csize},
fps{args.fps_value},
repeat{args.repeat},
full{args.full},
frame_cache{4},
texture_cache{args.cache},
cache_delay{args.cache_delay},
copy_audio{args.copy_audio} {
#ifdef AUDIO_ENABLED
audio_input_device = args.audio_input;
audio_output_device = args.audio_output;
if(args.audio_enabled) {
if(init_audio(args.audio_channels, args.audio_sensitivty, audio_input_device, audio_output_device) != 0) {
mx::system_err << "acmx2: Error could not initalize audio\n";
} else {
audio_is_enabled = true;
}
}
#endif
library.is3D(args.is3d);
is3d_enabled = args.is3d;
m_file = args.model_file;
if(args.shader_pass_enabled && !args.shader_pass_list.empty()) {
shader_pass_list = args.shader_pass_list;
shader_pass_enabled = true;
mx::system_out << "acmx2: Shader pass list enabled with " << shader_pass_list.size() << " shader(s)\n";
fflush(stdout);
}
}
bool is3d_enabled = false;
std::vector<int> shader_pass_list;
bool shader_pass_enabled = false;
std::string cached_shader_name;
void updateShaderNameCache() {
cached_shader_name = shader_pass_enabled
? library.getFullShaderName(shader_pass_list)
: library.getFullShaderName();
}
~ACView() override {
#ifdef AUDIO_ENABLED
if(audio_is_enabled) {
close_audio();
}
#endif
stopCaptureThread();
if (pboIds[0] && writer.is_open() && win_w > 0 && win_h > 0) {
for (int i = 0; i < 2; i++) {
glBindBuffer(GL_PIXEL_PACK_BUFFER, pboIds[i]);
GLubyte* src = (GLubyte*)glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);
if (src) {
std::vector<unsigned char> pixels(win_w * win_h * 4);
std::memcpy(pixels.data(), src, pixels.size());
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
std::vector<unsigned char> flipped_pixels(win_w * win_h * 4);
for (int y = 0; y < win_h; ++y) {
int src_row_start = y * win_w * 4;
int dest_row_start = (win_h - 1 - y) * win_w * 4;
std::copy(pixels.begin() + src_row_start,
pixels.begin() + src_row_start + (win_w * 4),
flipped_pixels.begin() + dest_row_start);
}
FrameData fd;
fd.pixels = std::move(flipped_pixels);
fd.width = win_w;
fd.height = win_h;
fd.isSnapshot = false;
{
std::lock_guard<std::mutex> lock(queueMutex);
frameQueue.push(std::move(fd));
}
queueCondVar.notify_one();
}
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
stopWriterThread();
if (pboIds[0]) {
glDeleteBuffers(2, pboIds);
pboIds[0] = pboIds[1] = 0;
}
if (captureFBO) {
glDeleteFramebuffers(1, &captureFBO);
captureFBO = 0;
}
if (fboTexture) {
glDeleteTextures(1, &fboTexture);
fboTexture = 0;
}
for(int p = 0; p < 2; ++p) {
if(passFBO[p]) {
glDeleteFramebuffers(1, &passFBO[p]);
passFBO[p] = 0;
}
if(passTexture[p]) {
glDeleteTextures(1, &passTexture[p]);
passTexture[p] = 0;
}
}
if (depthBuffer) {
glDeleteRenderbuffers(1, &depthBuffer);
depthBuffer = 0;
}
if(camera_texture) {
glDeleteTextures(1, &camera_texture);
camera_texture = 0;
}
if(texture_cache) {
glDeleteTextures(4, cache_textures);
for(int i = 0; i < 4; i++) {
cache_textures[i] = 0;
}
}
if(cap.isOpened())
cap.release();
}
mx::Model cube;
gl::ShaderProgram fshader, fshader3d;
std::string m_file;
virtual void load(gl::GLWindow *win) override {
frame_counter = 0;
sessionStartTime = std::chrono::steady_clock::now();
fpsLastTime = sessionStartTime;
fpsFrameCount = 0;
displayFPS = 0.0;
overlayFont.tryLoadFont(win->util.getFilePath("data/font.ttf"), 24);
library.is3D(is3d_enabled);
if(std::get<0>(flib) == 1)
library.loadPrograms(win, std::get<1>(flib));
else
library.loadProgram(win, std::get<1>(flib));
library.setIndex(std::get<2>(flib));
updateShaderNameCache();
std::string m_file_path;
if(std::filesystem::exists(m_file)) {
m_file_path = m_file;
} else {
m_file_path = win->util.getFilePath("data/" + m_file);
}
if(is3d_enabled && !cube.openModel(m_file_path)) {
throw mx::Exception("Could not open model: cube.mxmod.z");
}
cube.setShaderProgram(library.shader(), "samp");
if(!fshader.loadProgram(win->util.getFilePath("data/vert.glsl"), win->util.getFilePath("data/framebuffer.glsl"))) {
throw mx::Exception("Error loading shader");
}
if(!fshader3d.loadProgram(win->util.getFilePath("data/vertex.glsl"), win->util.getFilePath("data/framebuffer.glsl"))) {
throw mx::Exception("Error loading shader");
}
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
throw mx::Exception("OpenGL error occurred: GL Error: " + std::to_string(error));
}
int w = 1280, h = 720;
int frame_w = w, frame_h = h;
if(!graphic.empty()) {
graphic_frame = cv::imread(graphic);
if(graphic_frame.empty()) {
throw mx::Exception("Graphics file not found: " + graphic);
}
w = graphic_frame.cols;
h = graphic_frame.rows;
frame_w = w;
frame_h = h;
mx::system_out << "acmx2: Graphics file loaded: " << w << "x" << h << " at FPS: " << fps << "\n";
fflush(stdout);
fflush(stderr);
if(sizev.has_value()) {
w = sizev.value().width;
h = sizev.value().height;
mx::system_out << "acmx2: Resolution stretched to: " << w << "x" << h << "\n";
fflush(stdout);
fflush(stderr);
}
win->setWindowSize(w, h);
win->w = w;
win->h = h;
SDL_SetWindowPosition(win->getWindow(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
if(!ofilename.empty()) {
if(writer.open(ofilename, w, h, fps, crf.c_str())) {
mx::system_out << "acmx2: Opened: " << ofilename
<< " for writing at: " << crf
<< " CRF FPS: " << fps <<"\n";
fflush(stdout);
fflush(stderr);
} else {
throw mx::Exception("Could not open output video file: " + ofilename);
}
}
} else if(filename.empty()) {
#ifdef _WIN32
cap.open(camera_index, cv::CAP_DSHOW);
#else
cap.open(camera_index);
#endif
if(!cap.isOpened()) {
throw mx::Exception("Could not open camera index: " + std::to_string(camera_index));
}
cap.set(cv::CAP_PROP_BUFFERSIZE, 1);
if(sizec.has_value()) {
cap.set(cv::CAP_PROP_FRAME_WIDTH, sizec.value().width);
cap.set(cv::CAP_PROP_FRAME_HEIGHT, sizec.value().height);
} else {
cap.set(cv::CAP_PROP_FRAME_WIDTH, win->w);
cap.set(cv::CAP_PROP_FRAME_HEIGHT, win->h);
}
cap.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M','J','P','G'));
cap.set(cv::CAP_PROP_FPS, fps);
w = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_WIDTH));
h = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_HEIGHT));
fps = cap.get(cv::CAP_PROP_FPS);
frame_w = w;
frame_h = h;
mx::system_out << "acmx2: Camera opened: " << w << "x" << h << " at FPS: " << fps << "\n";
fflush(stderr);
fflush(stdout);
if(sizev.has_value()) {
w = sizev.value().width;
h = sizev.value().height;
mx::system_out << "acmx2: Resolution stretched to: " << w << "x" << h << "\n";
}
win->setWindowSize(w, h);
win->w = w;
win->h = h;
SDL_SetWindowPosition(win->getWindow(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
if(!ofilename.empty()) {
if(writer.open_ts(ofilename, w, h, fps, crf.c_str())) {
mx::system_out << "acmx2: Opened: " << ofilename
<< " for writing at: " << crf
<< " CRF FPS: " << fps <<"\n";
} else {
throw mx::Exception("Could not open output video file: " + ofilename);
}
}
}
else if(!filename.empty() && graphic.empty()) {
cap.open(filename);
if(!cap.isOpened()) {
throw mx::Exception("Could not open video file: " + filename);
}
w = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_WIDTH));
h = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_HEIGHT));
fps = cap.get(cv::CAP_PROP_FPS);
totalFrames = cap.get(cv::CAP_PROP_FRAME_COUNT);
frame_w = w;
frame_h = h;
mx::system_out << "acmx2: Video opened: " << w << "x" << h
<< " at FPS: " << fps
<< " Total Frames: " << totalFrames << "\n";
fflush(stdout);
fflush(stderr);
if(sizev.has_value()) {
w = sizev.value().width;
h = sizev.value().height;
mx::system_out << "acmx2: Resolution stretched to: "
<< w << "x" << h << "\n";
fflush(stdout);
fflush(stderr);
}
win->setWindowSize(w, h);
win->w = w;
win->h = h;
SDL_SetWindowPosition(win->getWindow(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
if(!ofilename.empty()) {
if(writer.open(ofilename, w, h, fps, crf.c_str())) {
mx::system_out << "acmx2: Opened: " << ofilename
<< " for writing at: " << crf << " CRF\n";
fflush(stdout);
fflush(stderr);
} else {
throw mx::Exception("Could not open output video file: " + ofilename);
}
}
} else if(graphic.empty() && filename.empty()) {
throw mx::Exception("Requires input from a file, or camera.");
}
library.useProgram();
if(texture_cache) {
cv::Mat blankMat = cv::Mat::zeros(frame_h, frame_w, CV_8UC3);
for(int i = 0; i < 4; ++i) {
cache_textures[i] = loadTexture(blankMat);
}
frame_cache.fill(blankMat);
mx::system_out << "acmx2: Texture cache initalized.\n";
fflush(stdout);
}
sprite.initSize(win->w, win->h);
cv::Mat blankMat = cv::Mat::zeros(frame_h, frame_w, CV_8UC3);
camera_texture = loadTexture(blankMat);
sprite.setName("samp");
sprite.initWithTexture(library.shader(), camera_texture, 0, 0, blankMat.cols, blankMat.rows);
setupCaptureFBO(win->w, win->h);
glGenBuffers(2, pboIds);
size_t pboSize = win->w * win->h * 4;
for (int i = 0; i < 2; i++) {
glBindBuffer(GL_PIXEL_PACK_BUFFER, pboIds[i]);
glBufferData(GL_PIXEL_PACK_BUFFER, pboSize, nullptr, GL_STREAM_READ);
}
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
if(!graphic.empty())