forked from VCVRack/Rack
-
Notifications
You must be signed in to change notification settings - Fork 28
/
vst2_main.cpp
2544 lines (2103 loc) · 76.4 KB
/
vst2_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
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
#ifdef USE_VST2
/// vst2_main.cpp
///
/// (c) 2018-2019 bsp. very loosely based on pongasoft's "hello, world" example plugin.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// created: 25Jun2018
/// changed: 26Jun2018, 27Jun2018, 29Jun2018, 01Jul2018, 02Jul2018, 06Jul2018, 13Jul2018
/// 26Jul2018, 04Aug2018, 05Aug2018, 06Aug2018, 07Aug2018, 09Aug2018, 11Aug2018
/// 18Aug2018, 19Aug2018, 05Sep2018, 06Sep2018, 10Oct2018, 26Oct2018, 10Mar2019
/// 12Mar2019, 07May2019, 19May2019
///
///
///
// #define DEBUG_PRINT_EVENTS defined
// #define DEBUG_PRINT_PARAMS defined
#define NUM_INPUTS ( 8) // must match AudioInterface.cpp:AUDIO_INPUTS
#define NUM_OUTPUTS ( 8) // must match AudioInterface.cpp:AUDIO_OUTPUTS
// (note) causes reason to shut down when console is freed (when plugin is deleted)
// #define USE_CONSOLE defined
// #define VST2_OPCODE_DEBUG defined
#undef RACK_HOST
#define Dprintf if(0);else printf
// #define Dprintf if(1);else printf
// #define Dprintf_idle if(0);else printf
#define Dprintf_idle if(1);else printf
#include <aeffect.h>
#include <aeffectx.h>
#include <stdio.h>
#ifdef HAVE_UNIX
#include <unistd.h>
#endif
#include "../dep/yac/yac.h"
#include "../dep/yac/yac_host.cpp"
YAC_Host *yac_host; // not actually used, just to satisfy the linker
#include "global_pre.hpp"
#include "global.hpp"
#include "global_ui.hpp"
#define EDITWIN_X 0
#define EDITWIN_Y 0
#define EDITWIN_W 1200
#define EDITWIN_H 800
#define Dfltequal(a, b) ( (((a)-(b)) < 0.0f) ? (((a)-(b)) > -0.0001f) : (((a)-(b)) < 0.0001f) )
typedef union cmemptr_u {
const sUI *u32;
const sF32 *f32;
const void *any;
} cmemptr_t;
typedef union mem_u {
sUI u32;
sF32 f32;
} mem_t;
extern int vst2_init (int argc, char* argv[], bool _bFX);
extern void vst2_exit (void);
namespace rack {
extern void vst2_editor_redraw (void);
}
extern void vst2_set_samplerate (sF32 _rate);
extern void vst2_engine_process (float *const*_in, float **_out, unsigned int _numFrames);
extern void vst2_process_midi_input_event (sU8 _a, sU8 _b, sU8 _c);
extern void vst2_queue_param (int uniqueParamId, float value, bool bNormalized);
extern void vst2_handle_queued_params (void);
extern float vst2_get_param (int uniqueParamId);
extern void vst2_get_param_name (int uniqueParamId, char *s, int sMaxLen);
extern void vst2_set_shared_plugin_tls_globals (void); // see plugin.cpp
#ifdef USE_BEGIN_REDRAW_FXN
extern void vst2_begin_shared_plugin_redraw (void); // see plugin.cpp
#endif // USE_BEGIN_REDRAW_FXN
extern "C" { extern int vst2_handle_effeditkeydown (unsigned int _vkey); }
void vst2_set_globals (void *_wrapper);
namespace rack {
extern bool b_touchkeyboard_enable;
extern void settingsLoad(std::string filename, bool bWindowSizeOnly);
}
#include "../include/window.hpp"
#include "../dep/include/osdialog.h"
#include "../include/app.hpp"
#include <speex/speex_resampler.h>
// using namespace rack;
// extern void rack::windowRun(void);
#if defined(_WIN32) || defined(_WIN64)
#define HAVE_WINDOWS defined
#define WIN32_LEAN_AND_MEAN defined
#include <windows.h>
#include <xmmintrin.h>
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
// Windows:
#define VST_EXPORT extern "C" __declspec(dllexport)
struct PluginMutex {
CRITICAL_SECTION handle;
PluginMutex(void) {
::InitializeCriticalSection( &handle );
}
~PluginMutex() {
::DeleteCriticalSection( &handle );
}
void lock(void) {
::EnterCriticalSection(&handle);
}
void unlock(void) {
::LeaveCriticalSection(&handle);
}
};
#else
// MacOSX, Linux:
#define HAVE_UNIX defined
#define VST_EXPORT extern
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <fenv.h> // fesetround()
#include <stdarg.h>
// #define USE_LOG_PRINTF defined
#ifdef USE_LOG_PRINTF
static FILE *logfile;
#undef Dprintf
#define Dprintf log_printf
void log_printf(const char *logData, ...) {
static char buf[16*1024];
va_list va;
va_start(va, logData);
vsprintf(buf, logData, va);
va_end(va);
printf(buf);
fputs(buf, logfile);
fflush(logfile);
}
#endif // USE_LOG_PRINTF
// #define _GNU_SOURCE
#include <dlfcn.h>
static pthread_mutex_t loc_pthread_mutex_t_init = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
//static pthread_mutex_t loc_pthread_mutex_t_init = PTHREAD_MUTEX_INITIALIZER;
struct PluginMutex {
pthread_mutex_t handle;
PluginMutex(void) {
::memcpy((void*)&handle, (const void*)&loc_pthread_mutex_t_init, sizeof(pthread_mutex_t));
}
~PluginMutex() {
}
void lock(void) {
::pthread_mutex_lock(&handle);
}
void unlock(void) {
::pthread_mutex_unlock(&handle);
}
};
#endif // _WIN32||_WIN64
// // extern "C" {
// // extern void glfwSetInstance(void *_glfw);
// // }
class PluginString : public YAC_String {
public:
static const sUI QUOT2 =(sUI)(1<<26); // \'\'
static const sUI STRFLQMASK = (QUOT | UTAG1 | QUOT2);
void safeFreeChars (void);
sSI _realloc (sSI _numChars);
sSI lastIndexOf (sChar _c, sUI _start) const;
void getDirName (PluginString *_r) const;
void replace (sChar _c, sChar _o);
};
void PluginString::safeFreeChars(void) {
if(bflags & PluginString::DEL)
{
// if(!(bflags & PluginString::LA))
{
Dyacfreechars(chars);
}
}
}
sSI PluginString::_realloc(sSI _numBytes) {
// Force alloc if a very big string is about to shrink a lot or there is simply not enough space available
if( ((buflen >= 1024) && ( (((sUI)_numBytes)<<3) < buflen )) ||
(NULL == chars) ||
(buflen < ((sUI)_numBytes))
) // xxx (!chars) hack added 180702
{
if(NULL != chars)
{
sUI l = length;
if(((sUI)_numBytes) < l)
{
l = _numBytes;
}
sU8 *nc = Dyacallocchars(_numBytes + 1);
sUI i = 0;
for(; i<l; i++)
{
nc[i] = chars[i];
}
nc[i] = 0;
safeFreeChars();
buflen = (_numBytes + 1);
bflags = PluginString::DEL | (bflags & PluginString::STRFLQMASK); // keep old stringflags
length = i + 1;
chars = nc;
key = YAC_LOSTKEY;
return YAC_TRUE;
}
else
{
return PluginString::alloc(_numBytes + 1);
}
}
else
{
key = YAC_LOSTKEY; // new 010208
return YAC_TRUE;
}
}
sSI PluginString::lastIndexOf(sChar _c, sUI _start) const {
sSI li = -1;
if(NULL != chars)
{
sUI i = _start;
for(; i<length; i++)
{
if(chars[i] == ((sChar)_c))
{
li = i;
}
}
}
return li;
}
void PluginString::replace(sChar _c, sChar _o) {
if(NULL != chars)
{
for(sUI i = 0; i < length; i++)
{
if(chars[i] == _c)
chars[i] = _o;
}
}
}
void PluginString::getDirName(PluginString *_r) const {
sSI idxSlash = lastIndexOf('/', 0);
sSI idxBackSlash = lastIndexOf('\\', 0);
sSI idxDrive = lastIndexOf(':', 0);
sSI idx = -1;
if(idxSlash > idxBackSlash)
{
idx = idxSlash;
}
else
{
idx = idxBackSlash;
}
if(idxDrive > idx)
{
idx = idxDrive;
}
if(-1 != idx)
{
_r->_realloc(idx + 2);
_r->length = idx + 2;
sSI i;
for(i=0; i<=idx; i++)
{
_r->chars[i] = chars[i];
}
_r->chars[i++] = 0;
_r->key = YAC_LOSTKEY;
}
else
{
_r->empty();
}
}
#define MAX_FLOATARRAYALLOCSIZE (1024*1024*64)
class PluginFloatArray : public YAC_FloatArray {
public:
sSI alloc (sSI _maxelements);
};
sSI PluginFloatArray::alloc(sSI _max_elements) {
if(((sUI)_max_elements)>MAX_FLOATARRAYALLOCSIZE)
{
printf("[---] FloatArray::insane array size (maxelements=%08x)\n", _max_elements);
return 0;
}
if(own_data)
{
if(elements)
{
delete [] elements;
elements = NULL;
}
}
if(_max_elements)
{
elements = new(std::nothrow) sF32[_max_elements];
if(elements)
{
max_elements = _max_elements;
num_elements = 0;
own_data = 1;
return 1;
}
}
num_elements = 0;
max_elements = 0;
return 0;
}
/*
* I find the naming a bit confusing so I decided to use more meaningful names instead.
*/
/**
* The VSTHostCallback is a function pointer so that the plugin can communicate with the host (not used in this small example)
*/
typedef audioMasterCallback VSTHostCallback;
/**
* The VSTPlugin structure (AEffect) contains information about the plugin (like version, number of inputs, ...) and
* callbacks so that the host can call the plugin to do its work. The primary callback will be `processReplacing` for
* single precision (float) sample processing (or `processDoubleReplacing` for double precision (double)).
*/
typedef AEffect VSTPlugin;
// Since the host is expecting a very specific API we need to make sure it has C linkage (not C++)
extern "C" {
/*
* This is the main entry point to the VST plugin.
*
* The host (DAW like Maschine, Ableton Live, Reason, ...) will look for this function with this exact API.
*
* It is the equivalent to `int main(int argc, char *argv[])` for a C executable.
*
* @param vstHostCallback is a callback so that the plugin can communicate with the host (not used in this small example)
* @return a pointer to the AEffect structure
*/
VST_EXPORT VSTPlugin *VSTPluginMain (VSTHostCallback vstHostCallback);
// note this looks like this without the type aliases (and is obviously 100% equivalent)
// extern AEffect *VSTPluginMain(audioMasterCallback audioMaster);
}
/*
* Constant for the version of the plugin. For example 1100 for version 1.1.0.0
*/
const VstInt32 PLUGIN_VERSION = 1000;
/**
* Encapsulates the plugin as a C++ class. It will keep both the host callback and the structure required by the
* host (VSTPlugin). This class will be stored in the `VSTPlugin.object` field (circular reference) so that it can
* be accessed when the host calls the plugin back (for example in `processDoubleReplacing`).
*/
class VSTPluginWrapper {
public:
static const uint32_t MIN_SAMPLE_RATE = 8192u;
static const uint32_t MAX_SAMPLE_RATE = 384000u;
static const uint32_t MIN_BLOCK_SIZE = 64u;
static const uint32_t MAX_BLOCK_SIZE = 16384u;
static const uint32_t MAX_OVERSAMPLE_FACTOR = 16u;
static const uint32_t IDLE_DETECT_NONE = 0u; // always active
static const uint32_t IDLE_DETECT_MIDI = 1u; // become idle when output is silence, reactivate when there's MIDI input activity
static const uint32_t IDLE_DETECT_AUDIO = 2u; // become idle when output is silence, reactivate when there's audio input activity
public:
rack::Global rack_global;
rack::GlobalUI rack_global_ui;
protected:
PluginString dllname;
PluginString cwd;
public:
struct {
float factor; // 1=no SR conversion, 2=oversample x2, 4=oversample x4, 0.5=undersample /2, ..
int quality; // SPEEX_RESAMPLER_QUALITY_xxx
float realtime_factor; // used during realtime rendering
int realtime_quality;
float offline_factor; // used during offline rendering (bounce)
int offline_quality; //
sUI num_in; // hack that limits oversampling to "n" input channels. default = NUM_INPUTS
sUI num_out; // hack that limits oversampling to "n" input channels. default = NUM_OUTPUTS
SpeexResamplerState *srs_in;
SpeexResamplerState *srs_out;
sF32 in_buffers[NUM_INPUTS * MAX_BLOCK_SIZE * MAX_OVERSAMPLE_FACTOR];
sF32 out_buffers[NUM_OUTPUTS * MAX_BLOCK_SIZE];
} oversample;
public:
float sample_rate; // e.g. 44100.0
protected:
uint32_t block_size; // e.g. 64
PluginMutex mtx_audio;
public:
PluginMutex mtx_mididev;
public:
bool b_open;
bool b_processing; // true=generate output, false=suspended
bool b_offline; // true=offline rendering (HQ)
bool b_check_offline; // true=ask host if it's in offline rendering mode
sUI idle_detect_mode;
sUI idle_detect_mode_fx;
sUI idle_detect_mode_instr;
sF32 idle_input_level_threshold;
sF32 idle_output_level_threshold;
sF32 idle_output_sec_threshold;
sUI idle_output_framecount;
sF32 idle_noteon_sec_grace; // grace period after note on
sUI idle_frames_since_noteon;
bool b_idle;
sBool b_fix_denorm; // true=fix denormalized floats + clip to -4..4. fixes broken audio in FLStudio and Reason.
ERect editor_rect;
sBool b_editor_open;
char *last_program_chunk_str;
static sSI instance_count;
sSI instance_id;
sF32 tmp_input_buffers[NUM_INPUTS * MAX_BLOCK_SIZE];
sUI redraw_ival_ms; // 0=use DAW timer (effEditIdle)
public:
VSTPluginWrapper(VSTHostCallback vstHostCallback,
VstInt32 vendorUniqueID,
VstInt32 vendorVersion,
VstInt32 numParams,
VstInt32 numPrograms,
VstInt32 numInputs,
VstInt32 numOutputs
);
~VSTPluginWrapper();
VSTPlugin *getVSTPlugin(void) {
return &_vstPlugin;
}
void setGlobals(void) {
rack::global = &rack_global;
rack::global_ui = &rack_global_ui;
}
sSI openEffect(void) {
Dprintf("xxx vstrack_plugin::openEffect\n");
// (todo) use mutex
instance_id = instance_count;
Dprintf("xxx vstrack_plugin::openEffect: instance_id=%d\n", instance_id);
rack_global.vst2.wrapper = this;
#ifdef USE_CONSOLE
AllocConsole();
freopen("CON", "w", stdout);
freopen("CON", "w", stderr);
freopen("CON", "r", stdin); // Note: "r", not "w".
#endif // USE_CONSOLE
setGlobals();
rack_global.init();
rack_global_ui.init();
rack::global->vst2.last_seen_instance_count = instance_count;
char oldCWD[1024];
char dllnameraw[1024];
char *dllnamerawp = dllnameraw;
#ifdef HAVE_WINDOWS
::GetCurrentDirectory(1024, (LPSTR) oldCWD);
// ::GetModuleFileNameA(NULL, dllnameraw, 1024); // returns executable name (not the dll pathname)
GetModuleFileNameA((HINSTANCE)&__ImageBase, dllnameraw, 1024);
#elif defined(HAVE_UNIX)
getcwd(oldCWD, 1024);
#if 0
// this does not work, it reports the path of the host, not the plugin
// (+the string is not NULL-terminated from the looks of it)
readlink("/proc/self/exe", dllnameraw, 1024);
#else
Dl_info dlInfo;
::dladdr((void*)VSTPluginMain, &dlInfo);
// // dllnamerawp = (char*)dlInfo.dli_fname;
if('/' != dlInfo.dli_fname[0])
{
// (note) 'dli_fname' can be a relative path (e.g. when loaded from vst2_debug_host)
sprintf(dllnameraw, "%s/%s", oldCWD, dlInfo.dli_fname);
}
else
{
// Absolute path (e.g. when loaded from Renoise host)
dllnamerawp = (char*)dlInfo.dli_fname;
}
#endif
#endif
Dprintf("xxx vstrack_plugin::openEffect: dllnamerawp=\"%s\"\n", dllnamerawp);
dllname.visit(dllnamerawp);
dllname.getDirName(&cwd);
rack::global->vst2.program_dir = (const char*)cwd.chars;
Dprintf("xxx vstrack_plugin::openEffect: cd to \"%s\"\n", (const char*)cwd.chars);
#ifdef HAVE_WINDOWS
::SetCurrentDirectory((const char*)cwd.chars);
#elif defined(HAVE_UNIX)
chdir((const char*)cwd.chars);
#endif
Dprintf("xxx vstrack_plugin::openEffect: cwd change done\n");
// cwd.replace('\\', '/');
int argc = 1;
char *argv[1];
//argv[0] = (char*)cwd.chars;
argv[0] = (char*)dllnamerawp;
Dprintf("xxx argv[0]=%p\n", argv[0]);
Dprintf("xxx vstrack_plugin::openEffect: dllname=\"%s\"\n", argv[0]);
(void)vst2_init(argc, argv,
#ifdef VST2_EFFECT
true/*bFX*/
#else
false/*bFX*/
#endif // VST2_EFFECT
);
Dprintf("xxx vstrack_plugin::openEffect: vst2_init() done\n");
vst2_set_shared_plugin_tls_globals();
Dprintf("xxx vstrack_plugin::openEffect: restore cwd=\"%s\"\n", oldCWD);
#ifdef HAVE_WINDOWS
::SetCurrentDirectory(oldCWD);
#elif defined(HAVE_UNIX)
chdir(oldCWD);
#endif
setSampleRate(sample_rate);
b_open = true;
b_editor_open = false;
Dprintf("xxx vstrack_plugin::openEffect: LEAVE\n");
return 1;
}
void setWindowSize(int _width, int _height) {
if(_width < 640)
_width = 640;
if(_height < 480)
_height = 480;
editor_rect.right = EDITWIN_X + _width;
editor_rect.bottom = EDITWIN_Y + _height;
(void)lglw_window_resize(rack_global_ui.window.lglw, _width, _height);
}
void setRefreshRate(float _hz) {
if(_hz < 15.0f)
{
redraw_ival_ms = 0u;
}
else
{
redraw_ival_ms = sUI(1000.0f / _hz);
}
if(b_editor_open)
{
lglw_timer_stop(rack_global_ui.window.lglw);
if(0u != redraw_ival_ms)
{
lglw_timer_start(rack_global_ui.window.lglw, redraw_ival_ms);
}
}
}
float getRefreshRate(void) {
if(redraw_ival_ms > 0u)
return (1000.0f / redraw_ival_ms);
else
return 0.0f;
}
void destroyResamplerStates(void) {
if(NULL != oversample.srs_in)
{
speex_resampler_destroy(oversample.srs_in);
oversample.srs_in = NULL;
}
if(NULL != oversample.srs_out)
{
speex_resampler_destroy(oversample.srs_out);
oversample.srs_out = NULL;
}
}
void openEditor(void *_hwnd) {
Dprintf("xxx vstrack_plugin: openEditor() parentHWND=%p\n", _hwnd);
setGlobals();
(void)lglw_window_open(rack_global_ui.window.lglw,
_hwnd,
0/*x*/, 0/*y*/,
(editor_rect.right - editor_rect.left),
(editor_rect.bottom - editor_rect.top)
);
if(0u != redraw_ival_ms)
{
lglw_timer_start(rack_global_ui.window.lglw, redraw_ival_ms);
}
b_editor_open = true;
rack::global_ui->param_info.placeholder_framecount = (30*30)-10;
rack::global_ui->param_info.last_param_widget = NULL;
}
void closeEditor(void) {
Dprintf("xxx vstrack_plugin: closeEditor() b_editor_open=%d\n", b_editor_open);
if(b_editor_open)
{
setGlobals();
lglw_timer_stop(rack_global_ui.window.lglw);
lglw_window_close(rack_global_ui.window.lglw);
b_editor_open = false;
}
}
void closeEffect(void) {
closeEditor();
// (todo) use mutex
Dprintf("xxx vstrack_plugin::closeEffect: last_program_chunk_str=%p\n", last_program_chunk_str);
if(NULL != last_program_chunk_str)
{
::free(last_program_chunk_str);
last_program_chunk_str = NULL;
}
Dprintf("xxx vstrack_plugin::closeEffect: b_open=%d\n", b_open);
if(b_open)
{
b_open = false;
setGlobals();
vst2_set_shared_plugin_tls_globals();
rack::global->vst2.last_seen_instance_count = instance_count;
Dprintf("xxx vstrack_plugin: call vst2_exit()\n");
vst2_exit();
Dprintf("xxx vstrack_plugin: vst2_exit() done\n");
destroyResamplerStates();
Dprintf("xxx vstrack_plugin: destroyResamplerStates() done\n");
#ifdef USE_CONSOLE
Sleep(5000);
// FreeConsole();
#endif // USE_CONSOLE
}
}
void lockAudio(void) {
mtx_audio.lock();
}
void unlockAudio(void) {
mtx_audio.unlock();
}
VstInt32 getNumInputs(void) const {
return _vstPlugin.numInputs;
}
VstInt32 getNumOutputs(void) const {
return _vstPlugin.numOutputs;
}
void setOversample(float _factor, int _quality, bool _bLock = true) {
oversample.factor = _factor;
oversample.quality = _quality;
setSampleRate(sample_rate, _bLock);
}
void setOversampleRealtime(float _factor, int _quality) {
Dprintf("xxx setOversampleRealtime 1\n");
if(_factor < 0.0f)
_factor = oversample.realtime_factor; // keep
if(_quality < 0)
_quality = oversample.realtime_quality; // keep
if(_factor < 0.001f)
_factor = 1.0f;
else if(_factor > float(MAX_OVERSAMPLE_FACTOR))
_factor = float(MAX_OVERSAMPLE_FACTOR);
if(_quality < SPEEX_RESAMPLER_QUALITY_MIN/*0*/)
_quality = SPEEX_RESAMPLER_QUALITY_MIN;
else if(_quality > SPEEX_RESAMPLER_QUALITY_MAX/*10*/)
_quality = SPEEX_RESAMPLER_QUALITY_MAX;
oversample.realtime_factor = _factor;
oversample.realtime_quality = _quality;
Dprintf("xxx setOversampleRealtime 2 b_offline=%d\n", b_offline);
if(!b_offline)
{
setOversample(oversample.realtime_factor, oversample.realtime_quality);
}
}
void setOversampleOffline(float _factor, int _quality) {
if(_factor < 0.0f)
_factor = oversample.offline_factor; // keep
if(_quality < 0)
_quality = oversample.offline_quality; // keep
if(_factor < 0.001f)
_factor = 1.0f;
else if(_factor > float(MAX_OVERSAMPLE_FACTOR))
_factor = float(MAX_OVERSAMPLE_FACTOR);
if(_quality < SPEEX_RESAMPLER_QUALITY_MIN/*0*/)
_quality = SPEEX_RESAMPLER_QUALITY_MIN;
else if(_quality > SPEEX_RESAMPLER_QUALITY_MAX/*10*/)
_quality = SPEEX_RESAMPLER_QUALITY_MAX;
oversample.offline_factor = _factor;
oversample.offline_quality = _quality;
if(b_offline)
{
setOversample(oversample.offline_factor, oversample.offline_quality);
}
}
void setOversampleChannels(int _numIn, int _numOut) {
if(_numIn < 0)
_numIn = int(oversample.num_in); // keep
if(_numOut < 0)
_numOut = int(oversample.num_out); // keep
if(_numIn < 0)
_numIn = 0;
else if(_numIn > NUM_INPUTS)
_numIn = NUM_INPUTS;
if(_numOut < 1)
_numOut = 1;
else if(_numOut > NUM_OUTPUTS)
_numOut = NUM_OUTPUTS;
// Dprintf("xxx setOversampleChannels: lockAudio\n");
lockAudio();
// Dprintf("xxx setOversampleChannels: lockAudio done\n");
oversample.num_in = sUI(_numIn);
oversample.num_out = sUI(_numOut);
// Dprintf("xxx setOversampleChannels: unlockAudio\n");
unlockAudio();
// Dprintf("xxx setOversampleChannels: unlockAudio done\n");
}
bool setSampleRate(float _rate, bool _bLock = true) {
bool r = false;
// Dprintf("xxx setSampleRate: ENTER bLock=%d\n", _bLock);
printf("xxx setSampleRate: 1\n"); fflush(stdout);
if((_rate >= float(MIN_SAMPLE_RATE)) && (_rate <= float(MAX_SAMPLE_RATE)))
{
if(_bLock)
{
setGlobals();
lockAudio();
}
sample_rate = _rate;
printf("xxx setSampleRate: 2\n"); fflush(stdout);
vst2_set_samplerate(sample_rate * oversample.factor); // see engine.cpp
printf("xxx setSampleRate: 3\n"); fflush(stdout);
destroyResamplerStates();
printf("xxx setSampleRate: 4\n"); fflush(stdout);
// Lazy-alloc resampler state
if(!Dfltequal(oversample.factor, 1.0f))
{
int err;
oversample.srs_in = speex_resampler_init(NUM_INPUTS,
sUI(sample_rate), // in rate
sUI(sample_rate * oversample.factor), // out rate
oversample.quality,
&err
);
oversample.srs_out = speex_resampler_init(NUM_OUTPUTS,
sUI(sample_rate * oversample.factor), // in rate
sUI(sample_rate), // out rate
oversample.quality,
&err
);
Dprintf("xxx vstrack_plugin: initialize speex resampler (rate=%f factor=%f quality=%d)\n", sample_rate, oversample.factor, oversample.quality);
}
printf("xxx setSampleRate: 5\n"); fflush(stdout);
if(_bLock)
{
unlockAudio();
}
printf("xxx setSampleRate: 6\n"); fflush(stdout);
r = true;
}
// Dprintf("xxx setSampleRate: LEAVE\n");
return r;
}
bool setBlockSize(uint32_t _blockSize) {
bool r = false;
if((_blockSize >= MIN_BLOCK_SIZE) && (_blockSize <= MAX_BLOCK_SIZE))
{
lockAudio();
block_size = _blockSize;
unlockAudio();
r = true;
}
return r;
}
void setEnableProcessingActive(bool _bEnable) {
lockAudio();
b_processing = _bEnable;
unlockAudio();
}
void checkOffline(void) {
// Called by VSTPluginProcessReplacingFloat32()
if(b_check_offline)
{
if(NULL != _vstHostCallback)
{
int level = (int)_vstHostCallback(&_vstPlugin, audioMasterGetCurrentProcessLevel, 0, 0/*value*/, NULL/*ptr*/, 0.0f/*opt*/);
// (note) Reason sets process level to kVstProcessLevelUser during "bounce in place"
bool bOffline = (kVstProcessLevelOffline == level) || (kVstProcessLevelUser == level);
#if 0
{
static int i = 0;
if(0 == (++i & 127))
{
Dprintf("xxx vstrack_plugin: audioMasterGetCurrentProcessLevel: level=%d\n", level);
}
}
#endif
if(b_offline ^ bOffline)
{
// Offline mode changed, update resampler
b_offline = bOffline;
if(bOffline)
{
Dprintf("xxx vstrack_plugin: enter OFFLINE mode. factor=%f quality=%d\n", oversample.offline_factor, oversample.offline_quality);
setOversample(oversample.offline_factor, oversample.offline_quality, false/*bLock*/);
}
else
{
Dprintf("xxx vstrack_plugin: enter REALTIME mode. factor=%f quality=%d\n", oversample.realtime_factor, oversample.realtime_quality);
setOversample(oversample.realtime_factor, oversample.realtime_quality, false/*bLock*/);
}
Dprintf("xxx vstrack_plugin: mode changed to %d\n", int(bOffline));
}
}
}
}