-
Notifications
You must be signed in to change notification settings - Fork 404
/
SurgeStorage.cpp
1496 lines (1312 loc) · 46.1 KB
/
SurgeStorage.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
//-------------------------------------------------------------------------------------------------------
// Copyright 2005-2006 Claes Johanson & Vember Audio
//-------------------------------------------------------------------------------------------------------
#include "DspUtilities.h"
#include "SurgeError.h"
#include "SurgeStorage.h"
#include "UserInteractions.h"
#include <set>
#include <numeric>
#include <cctype>
#include <map>
#include <queue>
#include <vt_dsp/vt_dsp_endian.h>
#if MAC
#include <cstdlib>
#include <sys/stat.h>
//#include <MoreFilesX.h>
//#include <MacErrorHandling.h>
#include <CoreFoundation/CFBundle.h>
#include <CoreServices/CoreServices.h>
#elif LINUX
#include <stdlib.h>
#include "ConfigurationXml.h"
#else
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#endif
#include <iostream>
#include <iomanip>
#include <sstream>
#include "UserDefaults.h"
#include "strnatcmp.h"
float sinctable alignas(16)[(FIRipol_M + 1) * FIRipol_N * 2];
float sinctable1X alignas(16)[(FIRipol_M + 1) * FIRipol_N];
short sinctableI16 alignas(16)[(FIRipol_M + 1) * FIRipolI16_N];
float table_dB alignas(16)[512],
table_envrate_lpf alignas(16)[512],
table_envrate_linear alignas(16)[512];
float waveshapers alignas(16)[8][1024];
float samplerate = 0, samplerate_inv;
double dsamplerate, dsamplerate_inv;
double dsamplerate_os, dsamplerate_os_inv;
using namespace std;
SurgeStorage::SurgeStorage(std::string suppliedDataPath)
{
_patch.reset(new SurgePatch(this));
float cutoff = 0.455f;
float cutoff1X = 0.85f;
float cutoffI16 = 1.0f;
int j;
for (j = 0; j < FIRipol_M + 1; j++)
{
for (int i = 0; i < FIRipol_N; i++)
{
double t = -double(i) + double(FIRipol_N / 2.0) + double(j) / double(FIRipol_M) - 1.0;
double val = (float)(symmetric_blackman(t, FIRipol_N) * cutoff * sincf(cutoff * t));
double val1X = (float)(symmetric_blackman(t, FIRipol_N) * cutoff1X * sincf(cutoff1X * t));
sinctable[j * FIRipol_N * 2 + i] = (float)val;
sinctable1X[j * FIRipol_N + i] = (float)val1X;
}
}
for (j = 0; j < FIRipol_M; j++)
{
for (int i = 0; i < FIRipol_N; i++)
{
sinctable[j * FIRipol_N * 2 + FIRipol_N + i] =
(float)((sinctable[(j + 1) * FIRipol_N * 2 + i] - sinctable[j * FIRipol_N * 2 + i]) /
65536.0);
}
}
for (j = 0; j < FIRipol_M + 1; j++)
{
for (int i = 0; i < FIRipolI16_N; i++)
{
double t = -double(i) + double(FIRipolI16_N / 2.0) + double(j) / double(FIRipol_M) - 1.0;
double val =
(float)(symmetric_blackman(t, FIRipolI16_N) * cutoffI16 * sincf(cutoffI16 * t));
sinctableI16[j * FIRipolI16_N + i] = (short)((float)val * 16384.f);
}
}
/*for(j=0; j<FIRipolI16_N; j++){
for(int i=0; i<FIRipol_N; i++){
sinctable[j*FIRipolI16_N*2 + FIRipolI16_N + i] = sinctable[(j+1)*FIRipolI16_N*2 +
i] - sinctable[j*FIRipolI16_N*2 + i]));
}
}*/
for (int s = 0; s < 2; s++)
for (int o = 0; o < n_oscs; o++)
for (int i = 0; i < max_mipmap_levels; i++)
for (int j = 0; j < max_subtables; j++)
{
getPatch().scene[s].osc[o].wt.TableF32WeakPointers[i][j] = 0;
getPatch().scene[s].osc[o].wt.TableI16WeakPointers[i][j] = 0;
}
init_tables();
pitch_bend = 0;
last_key[0] = 60;
last_key[1] = 60;
temposyncratio = 1.f;
temposyncratio_inv = 0.0f; // Use this as a sentinel (since it was not initialized prior to 1.6.5 this was the value at least win and mac had). #1444
songpos = 0;
for (int i = 0; i < n_customcontrollers; i++)
{
controllers[i] = 41 + i;
}
for (int i = 0; i < n_modsources; i++)
modsource_vu[i] = 0.f; // remove?
for (int s = 0; s < 2; s++)
for (int cc = 0; cc < 128; cc++)
poly_aftertouch[s][cc] = 0.f;
memset(&audio_in[0][0], 0, 2 * BLOCK_SIZE_OS * sizeof(float));
bool hasSuppliedDataPath = false;
if(suppliedDataPath.size() != 0)
{
hasSuppliedDataPath = true;
}
#if MAC || LINUX
const char* homePath = getenv("HOME");
if (!homePath)
throw Surge::Error("The environment variable HOME does not exist",
"Surge failed to initialize");
#endif
#if MAC
char path[1024];
if (!hasSuppliedDataPath)
{
FSRef foundRef;
OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &foundRef);
// or kUserDomain
FSRefMakePath(&foundRef, (UInt8*)path, 1024);
datapath = path;
datapath += "/Surge/";
auto cxmlpath = datapath + "configuration.xml";
// check if the directory exist in the user domain (if it doesn't, fall back to the local domain)
// See #863 where I chaned this to dir exists and contains config
CFStringRef testpathCF = CFStringCreateWithCString(0, cxmlpath.c_str(), kCFStringEncodingUTF8);
CFURLRef testCat = CFURLCreateWithFileSystemPath(0, testpathCF, kCFURLPOSIXPathStyle, true);
CFRelease(testpathCF);
FSRef myfsRef;
Boolean works = CFURLGetFSRef(testCat, &myfsRef);
CFRelease(testCat); // don't need it anymore?!?
if (!works)
{
OSErr err = FSFindFolder(kLocalDomain, kApplicationSupportFolderType, false, &foundRef);
FSRefMakePath(&foundRef, (UInt8*)path, 1024);
datapath = path;
datapath += "/Surge/";
}
}
else
{
datapath = suppliedDataPath;
}
// ~/Documents/Surge in full name
sprintf(path, "%s/Documents/Surge", homePath);
userDataPath = path;
#elif LINUX
if(!hasSuppliedDataPath)
{
const char* xdgDataPath = getenv("XDG_DATA_HOME");
if (xdgDataPath)
datapath = std::string(xdgDataPath) + "/Surge/";
else
datapath = std::string(homePath) + "/.local/share/Surge/";
/*
** If local directory doesn't exists - we probably came here through an installer -
** use /usr/share/Surge as our last guess
*/
if (! fs::is_directory(datapath))
{
datapath = "/usr/share/Surge/";
}
}
else
{
datapath = suppliedDataPath;
}
/*
** See the discussion in github issue #930. Basically
** if ~/Documents/Surge exists use that
** else if ~/.Surge exists use that
** else if ~/.Documents exists, use ~/Documents/Surge
** else use ~/.Surge
** Compensating for whether your distro makes you a ~/Documents or not
*/
std::string documentsSurge = std::string(homePath) + "/Documents/Surge";
std::string dotSurge = std::string(homePath) + "/.Surge";
std::string documents = std::string(homePath) + "/Documents/";
if( fs::is_directory(documentsSurge) )
{
userDataPath = documentsSurge;
}
else if( fs::is_directory(dotSurge) )
{
userDataPath = dotSurge;
}
else if( fs::is_directory(documents) )
{
userDataPath = documentsSurge;
}
else
{
userDataPath = dotSurge;
}
//std::cout << "DataPath is " << datapath << std::endl;
//std::cout << "UserDataPath is " << userDataPath << std::endl;
#elif WINDOWS
#if TARGET_RACK
datapath = suppliedDataPath;
#else
PWSTR localAppData;
if (!SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &localAppData))
{
CHAR path[4096];
wsprintf(path, "%S\\Surge\\", localAppData);
datapath = path;
}
PWSTR documentsFolder;
if (!SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &documentsFolder))
{
CHAR path[4096];
wsprintf(path, "%S\\Surge\\", documentsFolder);
userDataPath = path;
}
#endif
#endif
userDefaultFilePath = userDataPath;
std::string userSpecifiedDataPath = Surge::Storage::getUserDefaultValue(this, "userDataPath", "UNSPEC" );
if( userSpecifiedDataPath != "UNSPEC" )
{
userDataPath = userSpecifiedDataPath;
}
#if LINUX
if (!snapshotloader.Parse((const char*)&configurationXmlStart, 0,
TIXML_ENCODING_UTF8)) {
throw Surge::Error("Failed to parse the configuration",
"Surge failed to initialize");
}
#else
string snapshotmenupath = datapath + "configuration.xml";
if (!snapshotloader.LoadFile(snapshotmenupath.c_str())) // load snapshots (& config-stuff)
{
Surge::Error exc("Cannot find 'configuration.xml' in path '" + datapath + "'. Please reinstall surge.",
"Surge is not properly installed.");
Surge::UserInteractions::promptError(exc);
}
#endif
TiXmlElement* e = TINYXML_SAFE_TO_ELEMENT(snapshotloader.FirstChild("autometa"));
if (e)
{
defaultname = e->Attribute("name");
defaultsig = e->Attribute("comment");
}
load_midi_controllers();
#if !TARGET_RACK
bool loadWtAndPatch = true;
#if TARGET_LV2
// skip loading during export, it pops up an irrelevant error dialog
loadWtAndPatch = !skipLoadWtAndPatch;
#endif
if (loadWtAndPatch)
{
refresh_wtlist();
refresh_patchlist();
}
#endif
getPatch().scene[0].osc[0].wt.dt = 1.0f / 512.f;
load_wt(0, &getPatch().scene[0].osc[0].wt);
// WindowWT is a WaveTable which now has a constructor so don't do this
// memset(&WindowWT, 0, sizeof(WindowWT));
if( loadWtAndPatch && ! load_wt_wt(datapath + "windows.wt", &WindowWT) )
{
std::ostringstream oss;
oss << "Unable to load '" << datapath << "/windows.wt'. This file is required for surge to operate "
<< "properly. This occurs when Surge is mis-installed and shared resources are not in the "
<< "os-specific shared directory, which on your OS is a directory called 'Surge' in "
#if MAC
<< "the global or user local `Library/Application Support` directory."
#endif
#if WINDOWS
<< "your %LocalAppData% directory."
#endif
#if LINUX
<< "/usr/share or ~/.local/share."
#endif
<< " Please install shared assets correctly and restart.";
Surge::UserInteractions::promptError(oss.str(), "Unable to load windows.wt");
}
}
SurgePatch& SurgeStorage::getPatch()
{
return *_patch.get();
}
struct PEComparer
{
bool operator()(const Patch& a, const Patch& b)
{
return a.name.compare(b.name) < 0;
}
};
void SurgeStorage::refresh_patchlist()
{
patch_category.clear();
patch_list.clear();
refreshPatchlistAddDir(false, "patches_factory");
firstThirdPartyCategory = patch_category.size();
/*
** Do a quick sanity check here - if there are no patches in factory we are mis-installed
*/
int totalFactory = 0;
for(auto &cat : patch_category)
totalFactory += cat.numberOfPatchesInCatgory;
if(totalFactory == 0)
{
std::ostringstream ss;
ss << "Surge was unable to load factory patches from '" << datapath
<< "'. Surge found 0 factory patches. Please reinstall using the Surge installer.";
Surge::UserInteractions::promptError(ss.str(),
"Surge Installation Error");
}
refreshPatchlistAddDir(false, "patches_3rdparty");
firstUserCategory = patch_category.size();
refreshPatchlistAddDir(true, "");
patchOrdering = std::vector<int>(patch_list.size());
std::iota(patchOrdering.begin(), patchOrdering.end(), 0);
auto patchCompare =
[this](const int &i1, const int &i2) -> bool
{
return strnatcasecmp(patch_list[i1].name.c_str(),
patch_list[i2].name.c_str()) < 0;
};
std::sort(patchOrdering.begin(), patchOrdering.end(), patchCompare);
patchCategoryOrdering = std::vector<int>(patch_category.size());
std::iota(patchCategoryOrdering.begin(), patchCategoryOrdering.end(), 0);
for (int i = 0; i < patch_list.size(); i++)
patch_list[patchOrdering[i]].order = i;
auto categoryCompare =
[this](const int &i1, const int &i2) -> bool
{
return strnatcasecmp(patch_category[i1].name.c_str(),
patch_category[i2].name.c_str()) < 0;
};
int groups[4] = {0, firstThirdPartyCategory, firstUserCategory,
(int)patch_category.size()};
for (int i = 0; i < 3; i++)
std::sort(std::next(patchCategoryOrdering.begin(), groups[i]),
std::next(patchCategoryOrdering.begin(), groups[i + 1]),
categoryCompare);
for (int i = 0; i < patch_category.size(); i++)
patch_category[patchCategoryOrdering[i]].order = i;
}
void SurgeStorage::refreshPatchlistAddDir(bool userDir, string subdir)
{
refreshPatchOrWTListAddDir(
userDir, subdir, [](std::string s) -> bool { return _stricmp(s.c_str(), ".fxp") == 0; },
patch_list, patch_category);
}
void SurgeStorage::refreshPatchOrWTListAddDir(bool userDir,
string subdir,
std::function<bool(std::string)> filterOp,
std::vector<Patch>& items,
std::vector<PatchCategory>& categories)
{
int category = categories.size();
fs::path patchpath = (userDir ? userDataPath : datapath);
if (!subdir.empty())
patchpath.append(subdir);
if (!fs::is_directory(patchpath))
{
return;
}
/*
** std::filesystem has a recursive_directory_iterator, but between the
** hand rolled ipmmlementation on mac, expermiental on windows, and
** ostensibly standard on linux it isn't consistent enough to warrant
** using yet, so build my own recursive directory traversal with a simple
** stack
*/
std::vector<fs::path> alldirs;
std::deque<fs::path> workStack;
workStack.push_back( patchpath );
while (!workStack.empty())
{
auto top = workStack.front();
workStack.pop_front();
for (auto &d : fs::directory_iterator( top ))
{
if (fs::is_directory(d))
{
alldirs.push_back(d);
workStack.push_back(d);
}
}
}
/*
** We want to remove parent directory /user/foo or c:\\users\\bar\\
** with a substr in the main loop, so get the length once
*/
std::vector<PatchCategory> local_categories;
int patchpathSubstrLength= patchpath.generic_string().size() + 1;
if (patchpath.generic_string().back() == '/' || patchpath.generic_string().back() == '\\')
patchpathSubstrLength --;
for (auto &p : alldirs )
{
PatchCategory c;
#if WINDOWS && ! TARGET_RACK
/*
** Windows filesystem names are properly wstrings which, if we want them to
** display properly in vstgui, need to be converted to UTF8 using the
** windows widechar API. Linux and Mac do not require this.
*/
std::wstring str = p.wstring().substr(patchpathSubstrLength);
c.name = Surge::Storage::wstringToUTF8(str);
#else
c.name = p.generic_string().substr(patchpathSubstrLength);
#endif
c.internalid = category;
c.numberOfPatchesInCatgory = 0;
for (auto& f : fs::directory_iterator(p))
{
std::string xtn = f.path().extension().generic_string();
if (filterOp(xtn))
{
Patch e;
e.category = category;
e.path = f.path();
#if WINDOWS && ! TARGET_RACK
std::wstring str = f.path().filename().wstring();
str = str.substr(0, str.size() - xtn.length());
e.name = Surge::Storage::wstringToUTF8(str);
#else
e.name = f.path().filename().generic_string();
e.name = e.name.substr(0, e.name.size() - xtn.length());
#endif
items.push_back(e);
c.numberOfPatchesInCatgory ++;
}
}
c.numberOfPatchesInCategoryAndChildren = c.numberOfPatchesInCatgory;
local_categories.push_back(c);
category++;
}
/*
** Now establish parent child relationships between patch categories. Do this by
** scanning for names; setting the 'root' to everything without a slash
** and finding the parent in the name map for everything with a slash
*/
std::map<std::string,int> nameToLocalIndex;
int idx=0;
for (auto& pc : local_categories)
nameToLocalIndex[pc.name] = idx++;
std::string pathSep = "/";
#if WINDOWS
pathSep = "\\";
#endif
for (auto& pc : local_categories)
{
if (pc.name.find(pathSep) == std::string::npos)
{
pc.isRoot = true;
}
else
{
pc.isRoot = false;
std::string parent = pc.name.substr(0, pc.name.find_last_of(pathSep) );
local_categories[nameToLocalIndex[parent]].children.push_back(pc);
}
}
/*
** We need to sort the local patch category child to make sure subfolders remain
** sorted when displayed using the child data structure in the menu view.
*/
auto catCompare =
[this](const PatchCategory &c1, const PatchCategory &c2) -> bool
{
return strnatcasecmp(c1.name.c_str(),c2.name.c_str()) < 0;
};
for (auto& pc : local_categories)
{
std::sort(pc.children.begin(), pc.children.end(), catCompare);
}
/*
** Now we need to prune categories with nothing in their children.
** Start by updating the numberOfPatchesInCatgoryAndChildren from the root.
** This is complicated because the child list is a copy of values which
** I should fix one day. FIXME fix that to avoid this sort of double copy
** nonsense. But this keeps it consistent. At a price. Sorry!
*/
std::function<void(PatchCategory&)> recCorrect = [&recCorrect, &nameToLocalIndex,
&local_categories](PatchCategory& c) {
local_categories[nameToLocalIndex[c.name]].numberOfPatchesInCategoryAndChildren = c.numberOfPatchesInCatgory;
for (auto& ckid : c.children)
{
recCorrect(local_categories[nameToLocalIndex[ckid.name]]);
ckid.numberOfPatchesInCategoryAndChildren = local_categories[nameToLocalIndex[ckid.name]].numberOfPatchesInCategoryAndChildren;
local_categories[nameToLocalIndex[c.name]].numberOfPatchesInCategoryAndChildren +=
local_categories[nameToLocalIndex[ckid.name]].numberOfPatchesInCategoryAndChildren;
}
c.numberOfPatchesInCategoryAndChildren = local_categories[nameToLocalIndex[c.name]].numberOfPatchesInCategoryAndChildren;
};
for (auto& c : local_categories)
{
if (c.isRoot)
{
recCorrect(c);
}
}
/*
** Then copy our local patch category onto the member and be done
*/
for (auto& pc : local_categories)
{
categories.push_back(pc);
}
}
void SurgeStorage::refresh_wtlist()
{
wt_category.clear();
wt_list.clear();
refresh_wtlistAddDir(false, "wavetables");
if (wt_category.size() == 0 || wt_list.size() == 0)
{
std::ostringstream ss;
ss << "Surge was unable to load wavetables from '" << datapath
<< "'. The directory contains no wavetables. Please reinstall using the Surge installer.";
Surge::UserInteractions::promptError(ss.str(),
"Surge Installation Error" );
}
firstThirdPartyWTCategory = wt_category.size();
refresh_wtlistAddDir(false, "wavetables_3rdparty");
firstUserWTCategory = wt_category.size();
refresh_wtlistAddDir(true, "");
wtCategoryOrdering = std::vector<int>(wt_category.size());
std::iota(wtCategoryOrdering.begin(), wtCategoryOrdering.end(), 0);
// This nonsense deals with the fact that \ < ' ' but ' ' < / and we want "foo bar/h" and "foo/bar" to sort consistently on mac and win.
// See #1218
auto categoryCompare = [this](const int& i1, const int& i2) -> bool {
auto n1 = wt_category[i1].name;
for( auto i=0; i<n1.length(); ++i)
if( n1[i] == '\\' )
n1[i] = '/';
auto n2 = wt_category[i2].name;
for( auto i=0; i<n2.length(); ++i)
if( n2[i] == '\\' )
n2[i] = '/';
return strnatcasecmp(n1.c_str(), n2.c_str()) < 0;
};
int groups[4] = {0, firstThirdPartyWTCategory, firstUserWTCategory, (int)wt_category.size()};
for (int i = 0; i < 3; i++)
{
std::sort(std::next(wtCategoryOrdering.begin(), groups[i]),
std::next(wtCategoryOrdering.begin(), groups[i + 1]), categoryCompare);
}
for (int i = 0; i < wt_category.size(); i++)
wt_category[wtCategoryOrdering[i]].order = i;
wtOrdering = std::vector<int>();
auto wtCompare = [this](const int& i1, const int& i2) -> bool {
return strnatcasecmp(wt_list[i1].name.c_str(), wt_list[i2].name.c_str()) < 0;
};
// Sort wavetables per category in the category order.
for (auto c : wtCategoryOrdering)
{
int start = wtOrdering.size();
for (int i = 0; i < wt_list.size(); i++)
if (wt_list[i].category == c)
wtOrdering.push_back(i);
int end = wtOrdering.size();
std::sort(std::next(wtOrdering.begin(), start), std::next(wtOrdering.begin(), end),
wtCompare);
}
for (int i = 0; i < wt_list.size(); i++)
wt_list[wtOrdering[i]].order = i;
}
void SurgeStorage::refresh_wtlistAddDir(bool userDir, std::string subdir)
{
std::vector<std::string> supportedTableFileTypes;
supportedTableFileTypes.push_back(".wt");
supportedTableFileTypes.push_back(".wav");
refreshPatchOrWTListAddDir(
userDir, subdir,
[supportedTableFileTypes](std::string in) -> bool {
for (auto q : supportedTableFileTypes)
{
if (_stricmp(q.c_str(), in.c_str()) == 0)
return true;
}
return false;
},
wt_list, wt_category);
}
void SurgeStorage::perform_queued_wtloads()
{
SurgePatch& patch = getPatch(); //Change here is for performance and ease of debugging, simply not calling getPatch so many times. Code should behave identically.
for (int sc = 0; sc < 2; sc++)
{
for (int o = 0; o < n_oscs; o++)
{
if (patch.scene[sc].osc[o].wt.queue_id != -1)
{
load_wt(patch.scene[sc].osc[o].wt.queue_id, &patch.scene[sc].osc[o].wt);
patch.scene[sc].osc[o].wt.refresh_display = true;
}
else if (patch.scene[sc].osc[o].wt.queue_filename[0])
{
patch.scene[sc].osc[o].queue_type = ot_wavetable;
patch.scene[sc].osc[o].wt.current_id = -1;
load_wt(patch.scene[sc].osc[o].wt.queue_filename, &patch.scene[sc].osc[o].wt);
patch.scene[sc].osc[o].wt.refresh_display = true;
}
}
}
}
void SurgeStorage::load_wt(int id, Wavetable* wt)
{
wt->current_id = id;
wt->queue_id = -1;
if (id < 0)
return;
if (id >= wt_list.size())
return;
if (!wt)
return;
load_wt(wt_list[id].path.generic_string(), wt);
}
void SurgeStorage::load_wt(string filename, Wavetable* wt)
{
wt->queue_filename[0] = 0;
string extension = filename.substr(filename.find_last_of('.'), filename.npos);
for (unsigned int i = 0; i < extension.length(); i++)
extension[i] = tolower(extension[i]);
if (extension.compare(".wt") == 0)
load_wt_wt(filename, wt);
else if (extension.compare(".wav") == 0)
load_wt_wav_portable(filename, wt);
else
{
std::ostringstream oss;
oss << "Unable to load file with extension '" << extension << "'. Surge only supports .wav and .wt files";
Surge::UserInteractions::promptError(oss.str(), "load_wt error" );
}
}
bool SurgeStorage::load_wt_wt(string filename, Wavetable* wt)
{
FILE* f = fopen(filename.c_str(), "rb");
if (!f)
return false;
wt_header wh;
memset(&wh, 0, sizeof(wt_header));
size_t read = fread(&wh, sizeof(wt_header), 1, f);
// I'm not sure why this ever worked but it is checking the 4 bytes against vawt so...
// if (wh.tag != vt_read_int32BE('vawt'))
if (!(wh.tag[0] == 'v' && wh.tag[1] == 'a' && wh.tag[2] == 'w' && wh.tag[3] == 't'))
{
// SOME sort of error reporting is appropriate
fclose(f);
return false;
}
void* data;
size_t ds;
if (vt_read_int16LE(wh.flags) & wtf_int16)
ds = sizeof(short) * vt_read_int16LE(wh.n_tables) * vt_read_int32LE(wh.n_samples);
else
ds = sizeof(float) * vt_read_int16LE(wh.n_tables) * vt_read_int32LE(wh.n_samples);
data = malloc(ds);
fread(data, 1, ds, f);
CS_WaveTableData.enter();
bool wasBuilt = wt->BuildWT(data, wh, false);
CS_WaveTableData.leave();
free(data);
if (!wasBuilt)
{
std::ostringstream oss;
oss << "Your wavetable was unable to build. This often means that it has too many samples or tables."
<< " You provided " << wh.n_tables << " tables of size " << wh.n_samples << " vs max limits of "
<< max_subtables << " tables and " << max_wtable_size << " samples."
<< " In some cases, Surge detects this situation inconsistently leading to this message. Surge is now"
<< " in a potentially inconsistent state. We recommend you restart Surge and do not load the wavetable again."
<< " If you would like, please attach the wavetable which caused this message to a new github issue at "
<< " https://github.com/surge-synthesizer/surge/";
Surge::UserInteractions::promptError( oss.str(),
"Software Error on WT Load" );
fclose(f);
return false;
}
fclose(f);
return true;
}
int SurgeStorage::get_clipboard_type()
{
return clipboard_type;
}
int SurgeStorage::getAdjacentWaveTable(int id, bool nextPrev)
{
int n = wt_list.size();
if (!n)
return -1;
// See comment in SurgeSynthesizerIO::incrementPatch and #319
if( id < 0 || id > n-1 )
{
return wtOrdering[0];
}
else
{
int order = wt_list[id].order;
if (nextPrev)
order = (order >= (n - 1)) ? 0 : order + 1; // see comment in incrementPatch for that >= vs ==
else
order = (order <= 0) ? n - 1 : order - 1;
return wtOrdering[order];
}
}
void SurgeStorage::clipboard_copy(int type, int scene, int entry)
{
bool includemod = false, includeall = false;
if (type == cp_oscmod)
{
type = cp_osc;
includemod = true;
}
int cgroup = -1;
int cgroup_e = -1;
int id = -1;
clipboard_type = type;
switch (type)
{
case cp_osc:
cgroup = 2;
cgroup_e = entry;
id = getPatch().scene[scene].osc[entry].type.id; // first parameter id
if (uses_wavetabledata(getPatch().scene[scene].osc[entry].type.val.i))
{
clipboard_wt[0].Copy(&getPatch().scene[scene].osc[entry].wt);
}
break;
case cp_lfo:
cgroup = 6;
cgroup_e = entry + ms_lfo1;
id = getPatch().scene[scene].lfo[entry].shape.id;
if (getPatch().scene[scene].lfo[entry].shape.val.i == ls_stepseq)
memcpy(&clipboard_stepsequences[0], &getPatch().stepsequences[scene][entry],
sizeof(StepSequencerStorage));
break;
case cp_scene:
{
includemod = true;
includeall = true;
id = getPatch().scene[scene].octave.id;
for (int i = 0; i < n_lfos; i++)
memcpy(&clipboard_stepsequences[i], &getPatch().stepsequences[scene][i],
sizeof(StepSequencerStorage));
for (int i = 0; i < n_oscs; i++)
{
clipboard_wt[i].Copy(&getPatch().scene[scene].osc[i].wt);
}
}
break;
default:
return;
}
// CS ENTER
CS_ModRouting.enter();
{
clipboard_p.clear();
clipboard_modulation_scene.clear();
clipboard_modulation_voice.clear();
std::set<int> used_entries;
int n = getPatch().param_ptr.size();
for (int i = 0; i < n; i++)
{
Parameter p = *getPatch().param_ptr[i];
if (((p.ctrlgroup == cgroup) || (cgroup < 0)) &&
((p.ctrlgroup_entry == cgroup_e) || (cgroup_e < 0)) && (p.scene == (scene + 1)))
{
p.id = p.id - id;
used_entries.insert(p.id);
clipboard_p.push_back(p);
}
}
if (includemod)
{
int idoffset = 0;
if (!includeall)
idoffset = -id + n_global_params;
n = getPatch().scene[scene].modulation_voice.size();
for (int i = 0; i < n; i++)
{
ModulationRouting m;
m.source_id = getPatch().scene[scene].modulation_voice[i].source_id;
m.depth = getPatch().scene[scene].modulation_voice[i].depth;
m.destination_id =
getPatch().scene[scene].modulation_voice[i].destination_id + idoffset;
if (includeall || (used_entries.find(m.destination_id) != used_entries.end()))
clipboard_modulation_voice.push_back(m);
}
n = getPatch().scene[scene].modulation_scene.size();
for (int i = 0; i < n; i++)
{
ModulationRouting m;
m.source_id = getPatch().scene[scene].modulation_scene[i].source_id;
m.depth = getPatch().scene[scene].modulation_scene[i].depth;
m.destination_id =
getPatch().scene[scene].modulation_scene[i].destination_id + idoffset;
if (includeall || (used_entries.find(m.destination_id) != used_entries.end()))
clipboard_modulation_scene.push_back(m);
}
}
}
// CS LEAVE
CS_ModRouting.leave();
}
void SurgeStorage::clipboard_paste(int type, int scene, int entry)
{
assert(scene < 2);
if (type != clipboard_type)
return;
int cgroup = -1;
int cgroup_e = -1;
int id = -1;
int n = clipboard_p.size();
int start = 0;
if (!n)
return;
switch (type)
{
case cp_osc:
cgroup = 2;
cgroup_e = entry;
id = getPatch().scene[scene].osc[entry].type.id; // first parameter id
getPatch().scene[scene].osc[entry].type.val.i = clipboard_p[0].val.i;
start = 1;
getPatch().update_controls(false, &getPatch().scene[scene].osc[entry]);
break;
case cp_lfo:
cgroup = 6;
cgroup_e = entry + ms_lfo1;
id = getPatch().scene[scene].lfo[entry].shape.id;
break;
case cp_scene:
{
id = getPatch().scene[scene].octave.id;
for (int i = 0; i < n_lfos; i++)
memcpy(&getPatch().stepsequences[scene][i], &clipboard_stepsequences[i],
sizeof(StepSequencerStorage));
for (int i = 0; i < n_oscs; i++)
{
getPatch().scene[scene].osc[i].wt.Copy(&clipboard_wt[i]);
}
}
break;
default:
return;
}
// CS ENTER
CS_ModRouting.enter();
{
for (int i = start; i < n; i++)
{
Parameter p = clipboard_p[i];
int pid = p.id + id;
getPatch().param_ptr[pid]->val.i = p.val.i;
getPatch().param_ptr[pid]->temposync = p.temposync;
getPatch().param_ptr[pid]->extend_range = p.extend_range;
}
switch (type)
{
case cp_osc:
{
if (uses_wavetabledata(getPatch().scene[scene].osc[entry].type.val.i))
{
getPatch().scene[scene].osc[entry].wt.Copy(&clipboard_wt[0]);
}
// copy modroutings
n = clipboard_modulation_voice.size();
for (int i = 0; i < n; i++)
{
ModulationRouting m;
m.source_id = clipboard_modulation_voice[i].source_id;
m.depth = clipboard_modulation_voice[i].depth;
m.destination_id = clipboard_modulation_voice[i].destination_id + id - n_global_params;