forked from projectM-visualizer/projectm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprojectM_SDL_main.cpp
865 lines (723 loc) · 26.7 KB
/
projectM_SDL_main.cpp
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
/**
* projectM -- Milkdrop-esque visualisation SDK
* Copyright (C)2003-2019 projectM Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* See 'LICENSE.txt' included within this release
*
* projectM-sdl
* This is an implementation of projectM using libSDL2
*
* main.cpp
* Authors: Created by Mischa Spiegelmock on 6/3/15.
*
*
* RobertPancoast77@gmail.com :
* experimental Stereoscopic SBS driver functionality
* WASAPI looback implementation
*
*
*/
#if defined _MSC_VER
# include <direct.h>
#endif
#include <fstream>
#include <iostream>
#include <string>
#include <memory>
#include "pmSDL.hpp"
//#include "httplib.h"
#define HTTPSERVER_IMPL
#include "httpserver.h"
//#include <CoreMIDI/MIDIServices.h>
//#include <CoreFoundation/CFRunLoop.h>
#if OGL_DEBUG
void DebugLog(GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam) {
/*if (type != GL_DEBUG_TYPE_OTHER)*/
{
std::cerr << " -- \n" << "Type: " <<
type << "; Source: " <<
source <<"; ID: " << id << "; Severity: " <<
severity << "\n" << message << "\n";
}
}
#endif
/*
MIDIPortRef gOutPort = NULL;
MIDIEndpointRef gDest = NULL;
int gChannel = 0;*/
/*
MIDIPortRef gOutPort = NULL;
MIDIEndpointRef gDest = NULL;
int gChannel = 0;
void MyReadProc(const MIDIPacketList *pktlist, void *refCon, void *connRefCon)
{
//if (gOutPort != NULL && gDest != NULL) {
MIDIPacket *packet = (MIDIPacket *)pktlist->packet; // remove const (!)
for (unsigned int j = 0; j < pktlist->numPackets; ++j) {
if (packet->data[2] > 1) {
if (packet->data[0] == 0x30)
printf("Switch to next\n");
(projectMSDL::pm2)->selectNext(true);
if (packet->data[0] == 0x31)
printf("Switch to previous\n");
//(projectMSDL::pm2)->selectPrevious(true);
//pm->selectPrevious(true);
}
for (int i = 0; i < packet->length; ++i) {
printf("%02X ", packet->data[i]);
// rechannelize status bytes
if (packet->data[i] >= 0x80 && packet->data[i] < 0xF0)
packet->data[i] = (packet->data[i] & 0xF0) | gChannel;
}
printf("\n");
packet = MIDIPacketNext(packet);
}
//MIDISend(gOutPort, gDest, pktlist);
//}
}
int miditest(int argc)
{
// create client and ports
MIDIClientRef client = NULL;
MIDIClientCreate(CFSTR("MIDI Echo"), NULL, NULL, &client);
MIDIPortRef inPort = NULL;
MIDIInputPortCreate(client, CFSTR("Input port"), MyReadProc, NULL, &inPort);
MIDIOutputPortCreate(client, CFSTR("Output port"), &gOutPort);
// enumerate devices (not really related to purpose of the echo program
// but shows how to get information about devices)
int i, n;
CFStringRef pname, pmanuf, pmodel;
char name[64], manuf[64], model[64];
n = MIDIGetNumberOfDevices();
for (i = 0; i < n; ++i) {
MIDIDeviceRef dev = MIDIGetDevice(i);
MIDIObjectGetStringProperty(dev, kMIDIPropertyName, &pname);
MIDIObjectGetStringProperty(dev, kMIDIPropertyManufacturer, &pmanuf);
MIDIObjectGetStringProperty(dev, kMIDIPropertyModel, &pmodel);
CFStringGetCString(pname, name, sizeof(name), 0);
CFStringGetCString(pmanuf, manuf, sizeof(manuf), 0);
CFStringGetCString(pmodel, model, sizeof(model), 0);
CFRelease(pname);
CFRelease(pmanuf);
CFRelease(pmodel);
printf("name=%s, manuf=%s, model=%s\n", name, manuf, model);
}
// open connections from all sources
n = MIDIGetNumberOfSources();
printf("%d sources\n", n);
for (i = 0; i < n; ++i) {
MIDIEndpointRef src = MIDIGetSource(i);
MIDIPortConnectSource(inPort, src, NULL);
}
// find the first destination
n = MIDIGetNumberOfDestinations();
if (n > 0)
gDest = MIDIGetDestination(2);
if (gDest != NULL) {
MIDIObjectGetStringProperty(gDest, kMIDIPropertyName, &pname);
CFStringGetCString(pname, name, sizeof(name), 0);
CFRelease(pname);
printf("Echoing to channel %d of %s\n", gChannel + 1, name);
} else {
printf("No MIDI destinations present\n");
}
//CFRunLoopRun();
// run until aborted with control-C
return 0;
}
*/
//projectMSDL *pm2;
static projectMSDL *pm;
struct http_server_s* server;
// return path to config file to use
std::string getConfigFilePath(std::string datadir_path) {
char* home = NULL;
std::string projectM_home;
std::string projectM_config = DATADIR_PATH;
projectM_config = datadir_path;
#ifdef _MSC_VER
home=getenv("USERPROFILE");
#else
home=getenv("PWD");
#endif
// Use config from local directory
projectM_home = std::string(home);
projectM_config = std::string(home);
//projectM_home += "/.projectM";
// Create the ~/.projectM directory. If it already exists, mkdir will do nothing
#if defined _MSC_VER
_mkdir(projectM_home.c_str());
#else
mkdir(projectM_home.c_str(), 0755);
#endif
projectM_home += "/config.inp";
projectM_config += "/config.inp";
std::ifstream f_home(projectM_home);
std::ifstream f_config(projectM_config);
if (f_config.good() && !f_home.good()) {
std::ifstream f_src;
std::ofstream f_dst;
f_src.open(projectM_config, std::ios::in | std::ios::binary);
f_dst.open(projectM_home, std::ios::out | std::ios::binary);
f_dst << f_src.rdbuf();
f_dst.close();
f_src.close();
return std::string(projectM_home);
} else if (f_home.good()) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "created ~/.projectM/config.inp successfully\n");
return std::string(projectM_home);
} else if (f_config.good()) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Cannot create ~/.projectM/config.inp, using default config file\n");
return std::string(projectM_config);
} else {
SDL_LogWarn(SDL_LOG_CATEGORY_ERROR, "Using implementation defaults, your system is really messed up, I'm surprised we even got this far\n");
return "";
}
}
// ref https://blogs.msdn.microsoft.com/matthew_van_eerde/2008/12/16/sample-wasapi-loopback-capture-record-what-you-hear/
#ifdef WASAPI_LOOPBACK
HRESULT get_default_device(IMMDevice **ppMMDevice) {
HRESULT hr = S_OK;
IMMDeviceEnumerator *pMMDeviceEnumerator;
// activate a device enumerator
hr = CoCreateInstance(
__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL,
__uuidof(IMMDeviceEnumerator),
(void**)&pMMDeviceEnumerator
);
if (FAILED(hr)) {
ERR(L"CoCreateInstance(IMMDeviceEnumerator) failed: hr = 0x%08x", hr);
return hr;
}
// get the default render endpoint
hr = pMMDeviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, ppMMDevice);
if (FAILED(hr)) {
ERR(L"IMMDeviceEnumerator::GetDefaultAudioEndpoint failed: hr = 0x%08x", hr);
return hr;
}
return S_OK;
}
#endif /** WASAPI_LOOPBACK */
int request_target_is(struct http_request_s* request, char const * target) {
/*http_string_t url = http_request_target(request);
int len = strlen(target);
return len == url.len && memcmp(url.buf, target, url.len) == 0;*/
}
// handle incoming request
#define RESPONSE "Hello, World!"
void handle_request(struct http_request_s* request) {
// init response
struct http_response_s* response = http_response_init();
std::string s_response(RESPONSE);
unsigned long size_response = sizeof(RESPONSE);
// check that we actually have a message body
if (request->stream.buf) {
//std::cout << request->stream.buf << "\n";
std::cout << request->stream.buf;
// cheap way to check what kind of request this is
// TODO: implement better solution
switch(request->stream.buf[5]) {
case 'n': // next
pm->selectNext(true);
break;
case 'p': // previous
pm->selectPrevious(true);
break;
case 'y': // next random
pm->selectRandom(true);
break;
case 't': { // requested test.html page
std::ifstream f_html("test.html");
s_response = std::string((std::istreambuf_iterator<char>(f_html)), std::istreambuf_iterator<char>());
size_t server_location = s_response.find("127.0.0.1");
s_response.replace(server_location, 9, pm->getServerIP());
size_t port_location = s_response.find("8800");
s_response.replace(port_location, 4, std::to_string(pm->getServerPort()));
std::cout << s_response ;
size_response = s_response.size();
f_html.close();
break;
}
case 'r': { // request current shader contents
// get the current preset
//std::string presetName = pm->getCurrentPreset();
//pm->projectM::renderer
unsigned int index = pm->getCurrentPreset();
std::string url_preset = pm->getPresetURL(index);
// read in file and save to response
std::ifstream f_preset;
f_preset.open(url_preset.c_str());
// if we're not able to open the file
if (!f_preset.is_open()) {
std::cout << "Could not find preset url : \n" << url_preset.c_str() << "\n";
} else {
// and if we are, we save it as the response
s_response = std::string((std::istreambuf_iterator<char>(f_preset)), std::istreambuf_iterator<char>());
size_response = s_response.size();
}
}
break;
case '/': { // template for POST request
http_string_t http_request = http_request_body(request);
std::string s_request = http_request.buf;
// print request
std::cout << "set request\n";
std::cout << s_request;
// save as file
std::string time_string = pm->getTimeString();
std::string filename = "" + time_string + ".milk";
// if we have actual content
if (s_request.size() > 0) {
// assume we have a valid file
std::ofstream output_preset;
output_preset.open("presets/" + filename, std::ios::out);
// if the file was opened
if (output_preset.is_open()) {
// write the requested shader to the file
output_preset << s_request;
output_preset.close();
std::cout << "\n\n" << TOTAL_RATING_TYPES << "\n\n";
std::vector<int> ratings(2);
// add the new perset to the PresetLoader
unsigned int new_index = pm->addPresetURL("presets/" + filename, time_string, ratings);
std::cout << "Added " << filename << " at index: " << new_index << "\n";
// set the new preset
pm->selectPreset(new_index);
// make sure to lock the preset so we don't immediately lose it
if (!pm->isPresetLocked())
pm->setPresetLock(true);
//pm->selectNext(true);
}
}
}
break;
default: // if invalid or none, respond with remote controller html page
std::ifstream f_html("remote.html");
s_response = std::string((std::istreambuf_iterator<char>(f_html)), std::istreambuf_iterator<char>());
size_t server_location = s_response.find("127.0.0.1");
s_response.replace(server_location, 9, pm->getServerIP());
size_t port_location = s_response.find("8800");
s_response.replace(port_location, 4, std::to_string(pm->getServerPort()));
std::cout << s_response ;
size_response = s_response.size();
f_html.close();
}
}
// begin http response
http_response_status(response, 200);
http_response_header(response, "Content-Type", "text/html");
http_response_header(response, "Access-Control-Allow-Origin", "*");
http_response_body(response, s_response.c_str(), size_response);
// send response
http_respond(request, response);
}
int main(int argc, char *argv[]) {
#ifndef WIN32
srand((int)(time(NULL)));
#endif
#ifdef WASAPI_LOOPBACK
HRESULT hr;
hr = CoInitialize(NULL);
if (FAILED(hr)) {
ERR(L"CoInitialize failed: hr = 0x%08x", hr);
}
IMMDevice *pMMDevice(NULL);
// open default device if not specified
if (NULL == pMMDevice) {
hr = get_default_device(&pMMDevice);
if (FAILED(hr)) {
return hr;
}
}
bool bInt16 = false;
UINT32 foo = 0;
PUINT32 pnFrames = &foo;
// activate an IAudioClient
IAudioClient *pAudioClient;
hr = pMMDevice->Activate(
__uuidof(IAudioClient),
CLSCTX_ALL, NULL,
(void**)&pAudioClient
);
if (FAILED(hr)) {
ERR(L"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)) {
ERR(L"IAudioClient::GetDevicePeriod failed: hr = 0x%08x", hr);
return hr;
}
// get the default device format
WAVEFORMATEX *pwfx;
hr = pAudioClient->GetMixFormat(&pwfx);
if (FAILED(hr)) {
ERR(L"IAudioClient::GetMixFormat failed: hr = 0x%08x", hr);
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 {
ERR(L"%s", L"Don't know how to coerce mix format to int-16");
return E_UNEXPECTED;
}
}
break;
default:
ERR(L"Don't know how to coerce WAVEFORMATEX with wFormatTag = 0x%08x to int-16", pwfx->wFormatTag);
return E_UNEXPECTED;
}
}
UINT32 nBlockAlign = pwfx->nBlockAlign;
*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)) {
ERR(L"pAudioClient->Initialize error");
return hr;
}
// activate an IAudioCaptureClient
IAudioCaptureClient *pAudioCaptureClient;
hr = pAudioClient->GetService(
__uuidof(IAudioCaptureClient),
(void**)&pAudioCaptureClient
);
if (FAILED(hr)) {
ERR(L"pAudioClient->GetService error");
return hr;
}
// call IAudioClient::Start
hr = pAudioClient->Start();
if (FAILED(hr)) {
ERR(L"pAudioClient->Start error");
return hr;
}
bool bDone = false;
bool bFirstPacket = true;
UINT32 nPasses = 0;
#endif /** WASAPI_LOOPBACK */
#if UNLOCK_FPS
setenv("vblank_mode", "0", 1);
#endif
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
if (! SDL_VERSION_ATLEAST(2, 0, 5)) {
SDL_Log("SDL version 2.0.5 or greater is required. You have %i.%i.%i", SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL);
return 1;
}
// default window size to usable bounds (e.g. minus menubar and dock)
SDL_Rect initialWindowBounds;
#if SDL_VERSION_ATLEAST(2, 0, 5)
// new and better
SDL_GetDisplayUsableBounds(0, &initialWindowBounds);
#else
SDL_GetDisplayBounds(0, &initialWindowBounds);
#endif
int width = initialWindowBounds.w;
int height = initialWindowBounds.h;
#ifdef USE_GLES
// use GLES 2.0 (this may need adjusting)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
#else
// Disabling compatibility profile
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#endif
SDL_Window *win = SDL_CreateWindow("projectM", 0, 0, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
SDL_GL_GetDrawableSize(win,&width,&height);
#if STEREOSCOPIC_SBS
// enable stereo
if (SDL_GL_SetAttribute(SDL_GL_STEREO, 1) == 0)
{
SDL_Log("SDL_GL_STEREO: true");
}
// requires fullscreen mode
SDL_ShowCursor(false);
SDL_SetWindowFullscreen(win, SDL_WINDOW_FULLSCREEN);
#endif
SDL_GLContext glCtx = SDL_GL_CreateContext(win);
SDL_Log("GL_VERSION: %s", glGetString(GL_VERSION));
SDL_Log("GL_SHADING_LANGUAGE_VERSION: %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
SDL_Log("GL_VENDOR: %s", glGetString(GL_VENDOR));
SDL_SetWindowTitle(win, "projectM Visualizer");
SDL_GL_MakeCurrent(win, glCtx); // associate GL context with main window
int avsync = SDL_GL_SetSwapInterval(-1); // try to enable adaptive vsync
if (avsync == -1) { // adaptive vsync not supported
SDL_GL_SetSwapInterval(1); // enable updates synchronized with vertical retrace
}
projectMSDL *app;
//httplib::Server server;
std::string base_path = DATADIR_PATH;
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Using data directory: %s\n", base_path.c_str());
// load configuration file
std::string configFilePath = getConfigFilePath(base_path);
if (! configFilePath.empty()) {
// found config file, use it
app = new projectMSDL(configFilePath, 0);
//miditest(2);
SDL_Log("Using config from %s", configFilePath.c_str());
} else {
base_path = SDL_GetBasePath();
SDL_Log("Config file not found, using built-in settings. Data directory=%s\n", base_path.c_str());
// Get max refresh rate from attached displays to use as built-in max FPS.
int i = 0;
int maxRefreshRate = 0;
SDL_DisplayMode current;
for (i = 0; i < SDL_GetNumVideoDisplays(); ++i)
{
if (SDL_GetCurrentDisplayMode(i, ¤t) == 0)
{
if (current.refresh_rate > maxRefreshRate) maxRefreshRate = current.refresh_rate;
}
}
if (maxRefreshRate <= 60) maxRefreshRate = 60;
float heightWidthRatio = (float)height / (float)width;
projectM::Settings settings;
settings.windowWidth = width;
settings.windowHeight = height;
settings.meshX = 64;
settings.meshY = settings.meshX * heightWidthRatio;
settings.fps = maxRefreshRate;
settings.smoothPresetDuration = 3; // seconds
settings.presetDuration = 22; // seconds
settings.hardcutEnabled = false;
settings.hardcutDuration = 60;
settings.hardcutSensitivity = 1.0;
settings.beatSensitivity = 1.0;
settings.aspectCorrection = 1;
settings.shuffleEnabled = 1;
settings.softCutRatingsEnabled = 1; // ???
// get path to our app, use CWD or resource dir for presets/fonts/etc
settings.presetURL = base_path + "presets";
// settings.presetURL = base_path + "presets/presets_shader_test";
settings.menuFontURL = base_path + "fonts/Vera.ttf";
settings.titleFontURL = base_path + "fonts/Vera.ttf";
// init with settings
app = new projectMSDL(settings, 0);
}
std::cout << "WIDTH = " << app->getWindowWidth() << "\n";
// If our config or hard-coded settings create a resolution smaller than the monitors, then resize the SDL window to match.
if (height > app->getWindowHeight() || width > app->getWindowWidth()) {
SDL_SetWindowSize(win, app->getWindowWidth(),app->getWindowHeight());
SDL_SetWindowPosition(win, (width / 2)-(app->getWindowWidth()/2), (height / 2)-(app->getWindowHeight()/2));
} else if (height < app->getWindowHeight() || width < app->getWindowWidth()) {
// If our config is larger than our monitors resolution then reduce it.
SDL_SetWindowSize(win, width, height);
SDL_SetWindowPosition(win, 0, 0);
}
// Create a help menu specific to SDL
std::string modKey = "CTRL";
#if __APPLE_
modKey = "CMD";
#endif
std::string sdlHelpMenu = "\n"
"F1: This help menu""\n"
"F3: Show preset name""\n"
"F4: Show details and statistics""\n"
"F5: Show FPS""\n"
"L or SPACE: Lock/Unlock Preset""\n"
"R: Random preset""\n"
"N: Next preset""\n"
"P: Previous preset""\n"
"UP: Increase Beat Sensitivity""\n"
"DOWN: Decrease Beat Sensitivity""\n"
"Left Click: Drop Random Waveform on Screen""\n"
"Right Click: Remove Random Waveform""\n" +
modKey + "+Right Click: Remove All Random Waveforms""\n" +
modKey + "+I: Audio Input (listen to next device)""\n" +
modKey + "+M: Change Monitor""\n" +
modKey + "+S: Stretch Monitors""\n" +
modKey + "+F: Fullscreen""\n" +
modKey + "+Q: Quit";
app->setHelpText(sdlHelpMenu.c_str());
app->init(win, &glCtx);
//pm2 = app;
//projectMSDL::pm2 = &app;
//miditest(2);
pm = app;
// initialize the server
printf("Server IP: %s\n", app->getServerIP().c_str());
printf("Server Port: %d\n", app->getServerPort());
server = http_server_init(app->getServerPort(), handle_request);
http_server_listen_poll(server);
#if STEREOSCOPIC_SBS
app->toggleFullScreen();
#endif
#if OGL_DEBUG && !USE_GLES
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(DebugLog, NULL);
#endif
#if !FAKE_AUDIO && !WASAPI_LOOPBACK
// get an audio input device
if (app->openAudioInput())
app->beginAudioCapture();
#endif
#ifdef WASAPI_LOOPBACK
// Default to WASAPI loopback if it was enabled at compilation.
app->wasapi = true;
// Notify that loopback capture was started.
SDL_Log("Opened audio capture loopback.");
#endif
#if TEST_ALL_PRESETS
uint buildErrors = 0;
for(unsigned int i = 0; i < app->getPlaylistSize(); i++) {
std::cout << i << "\t" << app->getPresetName(i) << std::endl;
app->selectPreset(i);
if (app->getErrorLoadingCurrentPreset()) {
buildErrors++;
}
}
if (app->getPlaylistSize()) {
fprintf(stdout, "Preset loading errors: %d/%d [%d%%]\n", buildErrors, app->getPlaylistSize(), (buildErrors*100) / app->getPlaylistSize());
}
delete app;
return PROJECTM_SUCCESS;
#endif
#if UNLOCK_FPS
int32_t frame_count = 0;
struct timespec now;
clock_gettime(CLOCK_MONOTONIC_RAW, &now);
int64_t start = ( ((int64_t)now.tv_sec * 1000L) + (now.tv_nsec / 1000000L) );
#endif
// standard main loop
//int fps = app->settings().fps;
// remove this
int fps = app->settings().fps;
printf("fps: %d\n", fps);
if (fps <= 0)
fps = 60;
const Uint32 frame_delay = 1000/fps;
Uint32 last_time = SDL_GetTicks();
while (! app->done) {
// poll server for any new packets
http_server_poll(server);
app->renderFrame();
#if FAKE_AUDIO
app->fakeAudio = true;
#endif
// fakeAudio can also be enabled dynamically.
if (app->fakeAudio )
{
app->addFakePCM();
}
#ifdef WASAPI_LOOPBACK
if (app->wasapi) {
// drain data while it is available
nPasses++;
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)) {
return hr;
}
LONG lBytesToWrite = nNumFramesToRead * nBlockAlign;
/** Add the waveform data */
app->pcm()->addPCMfloat((float *)pData, nNumFramesToRead);
*pnFrames += nNumFramesToRead;
hr = pAudioCaptureClient->ReleaseBuffer(nNumFramesToRead);
if (FAILED(hr)) {
return hr;
}
bFirstPacket = false;
}
if (FAILED(hr)) {
return hr;
}
}
#endif /** WASAPI_LOOPBACK */
#if UNLOCK_FPS
frame_count++;
clock_gettime(CLOCK_MONOTONIC_RAW, &now);
if (( ((int64_t)now.tv_sec * 1000L) + (now.tv_nsec / 1000000L) ) - start > 5000) {
SDL_GL_DeleteContext(glCtx);
delete(app);
fprintf(stdout, "Frames[%d]\n", frame_count);
exit(0);
}
#else
app->pollEvent();
Uint32 elapsed = SDL_GetTicks() - last_time;
if (elapsed < frame_delay)
SDL_Delay(frame_delay - elapsed);
last_time = SDL_GetTicks();
#endif
}
SDL_GL_DeleteContext(glCtx);
#if !FAKE_AUDIO
if (!app->wasapi) // not currently using WASAPI, so we need to endAudioCapture.
app->endAudioCapture();
#endif
/*
// Write back config with current app settings (if we loaded from a config file to begin with)
if (!configFilePath.empty()) {
projectM::writeConfig(configFilePath, app->settings());
}*/
delete app;
return PROJECTM_SUCCESS;
}