-
Notifications
You must be signed in to change notification settings - Fork 7
/
dfxsettings.cpp
1653 lines (1481 loc) · 60.4 KB
/
dfxsettings.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
/*------------------------------------------------------------------------
Destroy FX Library is a collection of foundation code
for creating audio processing plug-ins.
Copyright (C) 2002-2023 Sophia Poirier
This file is part of the Destroy FX Library (version 1.0).
Destroy FX Library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
Destroy FX 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with Destroy FX Library. If not, see <http:https://www.gnu.org/licenses/>.
To contact the author, use the contact form at http:https://destroyfx.org
Destroy FX is a sovereign entity comprised of Sophia Poirier and Tom Murphy 7.
Welcome to our settings persistence mess.
------------------------------------------------------------------------*/
#include "dfxsettings.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <optional>
#include <stdexcept>
#include <string_view>
#include <type_traits>
#include <vector>
#include "dfxmath.h"
#include "dfxmidi.h"
#include "dfxmisc.h"
#include "dfxplugin.h"
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#pragma mark -
#pragma mark init / destroy
#pragma mark -
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//-----------------------------------------------------------------------------
DfxSettings::DfxSettings(uint32_t inMagic, DfxPlugin& inPlugin, size_t inSizeofExtendedData)
: mPlugin(inPlugin),
// TODO C++23: integer literal suffix UZ
mNumParameters(std::max(inPlugin.getnumparameters(), size_t(1))), // we need at least one parameter
mNumPresets(std::max(inPlugin.getnumpresets(), size_t(1))), // we need at least one set of parameters
mSizeOfExtendedData(inSizeofExtendedData),
mParameterIDMap(mNumParameters, dfx::kParameterID_Invalid),
mParameterAssignments(mNumParameters)
{
// default to each parameter having its ID equal its index
std::iota(mParameterIDMap.begin(), mParameterIDMap.end(), 0);
// calculate some data sizes that are useful to know
mSizeOfPreset = sizeOfGenPreset(mNumParameters);
mSizeOfParameterIDs = sizeof(mParameterIDMap.front()) * mNumParameters;
mSizeOfPresetChunk = mSizeOfPreset // 1 preset
+ sizeof(SettingsInfo) // the special data header info
+ mSizeOfParameterIDs // the table of parameter IDs
+ (sizeof(dfx::ParameterAssignment) * mNumParameters) // the MIDI events assignment array
+ inSizeofExtendedData;
mSizeOfChunk = (mSizeOfPreset * mNumPresets) // all of the presets
+ sizeof(SettingsInfo) // the special data header info
+ mSizeOfParameterIDs // the table of parameter IDs
+ (sizeof(dfx::ParameterAssignment) * mNumParameters) // the MIDI events assignment array
+ inSizeofExtendedData;
// set all of the header infos
mSettingsInfo.mMagic = inMagic;
mSettingsInfo.mVersion = mPlugin.getpluginversion();
mSettingsInfo.mLowestLoadableVersion = 0;
mSettingsInfo.mStoredHeaderSize = sizeof(SettingsInfo);
mSettingsInfo.mNumStoredParameters = static_cast<uint32_t>(mNumParameters);
mSettingsInfo.mNumStoredPresets = static_cast<uint32_t>(mNumPresets);
mSettingsInfo.mStoredParameterAssignmentSize = sizeof(dfx::ParameterAssignment);
mSettingsInfo.mStoredExtendedDataSize = static_cast<uint32_t>(inSizeofExtendedData);
clearAssignments(); // initialize all of the parameters to have no MIDI event assignments
// allow for further constructor stuff, if necessary
mPlugin.settings_init();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#pragma mark -
#pragma mark settings
#pragma mark -
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//-----------------------------------------------------------------------------
template <typename FromT, typename ToT>
requires (!std::is_const_v<ToT>)
using CopyConstT = std::conditional_t<std::is_const_v<FromT>, std::add_const_t<ToT>, ToT>;
//-----------------------------------------------------------------------------
template <typename T>
T* OffsetAddress(T* inAddress, ptrdiff_t inOffset) noexcept
{
return reinterpret_cast<T*>(reinterpret_cast<CopyConstT<T, std::byte>*>(inAddress) + inOffset);
}
//-----------------------------------------------------------------------------
template <typename T>
T* OffsetAddressToType(CopyConstT<T, void>* inAddress, ptrdiff_t inOffset) noexcept
{
return static_cast<T*>(OffsetAddress(inAddress, inOffset));
}
//-----------------------------------------------------------------------------
template <dfx::TriviallySerializable T>
class SerializedObject
{
public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using reference = T&;
using iterator_category = std::input_iterator_tag;
template <typename ToT>
using CopyConstT = CopyConstT<T, ToT>;
explicit SerializedObject(CopyConstT<void>* inData) noexcept
: mData(static_cast<T*>(inData))
{
}
auto operator*() const noexcept
requires (!std::is_const_v<T>)
{
return AssignmentWrapper(mData);
}
auto operator*() const noexcept
requires std::is_const_v<T>
{
return dfx::Enliven(mData);
}
auto operator[](std::size_t inIndex) const noexcept
requires (!std::is_const_v<T>)
{
return AssignmentWrapper(mData + inIndex);
}
[[nodiscard]] T operator[](std::size_t inIndex) const noexcept
requires std::is_const_v<T>
{
return dfx::Enliven(mData + inIndex);
}
SerializedObject begin() const noexcept
{
return *this;
}
SerializedObject& operator++() noexcept
{
this->offsetAddress(sizeof(T));
return *this;
}
SerializedObject operator++(int) noexcept
{
auto const entrySelf = *this;
operator++();
return entrySelf;
}
auto getByteAddress() const noexcept
{
return reinterpret_cast<CopyConstT<std::byte>*>(mData);
}
void offsetAddress(ptrdiff_t inOffset) noexcept
{
mData = OffsetAddress(mData, inOffset);
}
static constexpr auto sizeOfType() noexcept
{
return sizeof(T);
}
private:
class AssignmentWrapper
{
public:
explicit AssignmentWrapper(T* inData) noexcept
requires (!std::is_const_v<T>)
: mData(inData)
{
}
AssignmentWrapper& operator=(T const& inOther) noexcept
{
dfx::MemCpyObject(inOther, mData);
return *this;
}
private:
T* const mData;
};
T* mData;
};
#define GET_SERIALIZED_HEADER_FIELD(inData, inMemberName) \
dfx::Enliven(OffsetAddressToType<decltype(SettingsInfo::inMemberName)>(inData, offsetof(SettingsInfo, inMemberName)))
//-----------------------------------------------------------------------------
// this gets called when the host wants to save settings data,
// like when saving a session document or preset files
std::vector<std::byte> DfxSettings::save(bool inIsPreset) const
{
std::vector<std::byte> data(inIsPreset ? mSizeOfPresetChunk : mSizeOfChunk, std::byte{0});
SerializedObject<SettingsInfo> const sharedHeader(data.data());
// and a few references to elements within that data, just for ease of use
SerializedObject<uint32_t> const sharedParameterIDs(data.data() + sizeof(SettingsInfo));
auto const firstSharedPresetByteAddress = sharedParameterIDs.getByteAddress() + mSizeOfParameterIDs;
auto sharedPresetName = reinterpret_cast<GenPresetNameElementT*>(firstSharedPresetByteAddress + offsetof(GenPreset, mName));
SerializedObject<GenPresetParameterValueT> sharedPresetParameterValues(firstSharedPresetByteAddress + offsetof(GenPreset, mParameterValues));
// TODO C++23: integer literal suffix UZ
auto const savePresetCount = inIsPreset ? size_t(1) : mNumPresets;
SerializedObject<dfx::ParameterAssignment> const sharedParameterAssignments(firstSharedPresetByteAddress + (mSizeOfPreset * savePresetCount));
// first store the special chunk infos
auto settingsInfoWithAdjustedPresetCount = mSettingsInfo;
if (inIsPreset)
{
settingsInfoWithAdjustedPresetCount.mNumStoredPresets = 1;
}
*sharedHeader = settingsInfoWithAdjustedPresetCount;
// store the parameters' IDs
std::copy(mParameterIDMap.cbegin(), mParameterIDMap.cend(), sharedParameterIDs.begin());
// store only one preset setting if inIsPreset is true
if (inIsPreset)
{
dfx::StrLCpy(sharedPresetName, mPlugin.getpresetname(mPlugin.getcurrentpresetnum()), std::extent_v<GenPresetNameT>);
for (dfx::ParameterID i = 0; i < mNumParameters; i++)
{
sharedPresetParameterValues[i] = mPlugin.getparameter_f(i);
}
}
// otherwise store the entire bank of presets and the MIDI event assignments
else
{
for (size_t j = 0; j < mNumPresets; j++)
{
// copy the preset name to the chunk
dfx::StrLCpy(sharedPresetName, mPlugin.getpresetname(j), std::extent_v<GenPresetNameT>);
// copy all of the parameters for this preset to the chunk
for (dfx::ParameterID i = 0; i < mNumParameters; i++)
{
sharedPresetParameterValues[i] = mPlugin.getpresetparameter_f(j, i);
}
// point to the next preset in the data array for the host
sharedPresetName = OffsetAddress(sharedPresetName, mSizeOfPreset);
sharedPresetParameterValues.offsetAddress(mSizeOfPreset);
}
}
// store the parameters' MIDI event assignments
std::copy(mParameterAssignments.cbegin(), mParameterAssignments.cend(), sharedParameterAssignments.begin());
// reverse the order of bytes in the data being sent to the host, if necessary
[[maybe_unused]] auto const endianSuccess = correctEndian(data.data(), data.size() - mSizeOfExtendedData, false, inIsPreset);
assert(endianSuccess);
// allow for the storage of extra data
if (mSizeOfExtendedData > 0)
{
mPlugin.settings_saveExtendedData(data.data() + data.size() - mSizeOfExtendedData, inIsPreset);
}
return data;
}
#ifdef DFX_SUPPORT_OLD_VST_SETTINGS
//-----------------------------------------------------------------------------
// for backwerds compaxibilitee
inline bool DFX_IsOldVstVersionNumber(uint32_t inVersion) noexcept
{
return (inVersion < 0x00010000);
}
constexpr size_t kDfxOldPresetNameMaxLength = 32;
#endif
//-----------------------------------------------------------------------------
// this gets called when the host wants to load settings data,
// like when restoring settings while opening a song,
// or loading a preset file
bool DfxSettings::restore(void const* inData, size_t const inDataSize, bool inIsPreset)
try
{
static_assert(std::numeric_limits<float>::is_iec559, "floating point values cannot be deserialized if the representation is inconsistent");
auto const require = [](bool condition)
{
if (!condition)
{
throw std::invalid_argument("bad data");
}
};
constexpr auto kMinimumHeaderSize = offsetof(SettingsInfo, mGlobalBehaviorFlags);
require(inDataSize >= kMinimumHeaderSize);
// create our own copy of the data before we muck with it (e.g. reversing endianness, etc.)
auto const incomingData_copy = dfx::MakeUniqueMemoryBlock<void>(inDataSize);
require(incomingData_copy.get());
std::memcpy(incomingData_copy.get(), inData, inDataSize);
// un-reverse the order of bytes in the received data, if necessary
require(correctEndian(incomingData_copy.get(), inDataSize, true, inIsPreset));
auto const validateRange = [&incomingData_copy, inDataSize, this](void const* address, size_t length, char const* name)
{
this->validateRange(incomingData_copy.get(), inDataSize, address, length, name);
};
// the start of the chunk data: the SettingsInfo header
auto const storedHeaderSize = GET_SERIALIZED_HEADER_FIELD(incomingData_copy.get(), mStoredHeaderSize);
validateRange(incomingData_copy.get(), storedHeaderSize, "header");
require(storedHeaderSize >= kMinimumHeaderSize);
auto const storedMagic = GET_SERIALIZED_HEADER_FIELD(incomingData_copy.get(), mMagic);
auto const storedVersion = GET_SERIALIZED_HEADER_FIELD(incomingData_copy.get(), mVersion);
auto const storedLowestLoadableVersion = GET_SERIALIZED_HEADER_FIELD(incomingData_copy.get(), mLowestLoadableVersion);
auto const numStoredParameters = GET_SERIALIZED_HEADER_FIELD(incomingData_copy.get(), mNumStoredParameters);
auto const numStoredPresets = GET_SERIALIZED_HEADER_FIELD(incomingData_copy.get(), mNumStoredPresets);
auto const storedParameterAssignmentSize = GET_SERIALIZED_HEADER_FIELD(incomingData_copy.get(), mStoredParameterAssignmentSize);
auto const storedExtendedDataSize = GET_SERIALIZED_HEADER_FIELD(incomingData_copy.get(), mStoredExtendedDataSize);
std::optional<decltype(SettingsInfo::mGlobalBehaviorFlags)> storedGlobalBehaviorFlags;
// check for availability of later extensions to the header
if (storedHeaderSize >= (offsetof(SettingsInfo, mGlobalBehaviorFlags) + sizeof(SettingsInfo::mGlobalBehaviorFlags)))
{
storedGlobalBehaviorFlags = GET_SERIALIZED_HEADER_FIELD(incomingData_copy.get(), mGlobalBehaviorFlags);
}
// The following situations are basically considered to be
// irrecoverable "crisis" situations. Regardless of what
// crisis behavior has been chosen, any of the following errors
// will prompt an unsuccessful exit because these are big problems.
// Incorrect magic signature basically means that these settings are
// probably for some other plugin. And the whole point of setting a
// lowest loadable version value is that it should be taken seriously.
require(storedMagic == mSettingsInfo.mMagic);
require((storedVersion >= mSettingsInfo.mLowestLoadableVersion) &&
(mSettingsInfo.mVersion >= storedLowestLoadableVersion)); // TODO: does this second test make sense?
#ifdef DFX_SUPPORT_OLD_VST_SETTINGS
// we started using hex format versions (like below) with the advent
// of the glorious DfxPlugin
// versions lower than 0x00010000 indicate inferior settings
auto const oldVST = DFX_IsOldVstVersionNumber(storedVersion);
#endif
// figure out how many presets we should try to load
// if the incoming chunk doesn't match what we're expecting
// TODO C++23: integer literal suffix UZ
auto const copyPresets = std::min(static_cast<size_t>(numStoredPresets), inIsPreset ? size_t(1) : mNumPresets);
// figure out how much of the dfx::ParameterAssignment structure we can import
auto const copyParameterAssignmentSize = std::min(storedParameterAssignmentSize, mSettingsInfo.mStoredParameterAssignmentSize);
// check for conflicts and keep track of them
CrisisReasonFlags crisisFlags = kCrisisReasonFlag_None;
if (storedVersion < mSettingsInfo.mVersion)
{
crisisFlags = crisisFlags | kCrisisReasonFlag_LowerVersion;
}
else if (storedVersion > mSettingsInfo.mVersion)
{
crisisFlags = crisisFlags | kCrisisReasonFlag_HigherVersion;
}
if (numStoredParameters < mNumParameters)
{
crisisFlags = crisisFlags | kCrisisReasonFlag_FewerParameters;
}
else if (numStoredParameters > mNumParameters)
{
crisisFlags = crisisFlags | kCrisisReasonFlag_MoreParameters;
}
if (inIsPreset)
{
if (inDataSize < mSizeOfPresetChunk)
{
crisisFlags = crisisFlags | kCrisisReasonFlag_SmallerByteSize;
}
else if (inDataSize > mSizeOfPresetChunk)
{
crisisFlags = crisisFlags | kCrisisReasonFlag_LargerByteSize;
}
}
else
{
if (inDataSize < mSizeOfChunk)
{
crisisFlags = crisisFlags | kCrisisReasonFlag_SmallerByteSize;
}
else if (inDataSize > mSizeOfChunk)
{
crisisFlags = crisisFlags | kCrisisReasonFlag_LargerByteSize;
}
if (numStoredPresets < mNumPresets)
{
crisisFlags = crisisFlags | kCrisisReasonFlag_FewerPresets;
}
else if (numStoredPresets > mNumPresets)
{
crisisFlags = crisisFlags | kCrisisReasonFlag_MorePresets;
}
}
// handle the crisis situations (if any) and stop trying to load if we're told to
require(handleCrisis(crisisFlags) != CrisisError::QuitError);
if (storedGlobalBehaviorFlags)
{
setUseChannel(*storedGlobalBehaviorFlags & kGlobalBehaviorFlag_UseChannel);
setSteal(*storedGlobalBehaviorFlags & kGlobalBehaviorFlag_StealAssignments);
}
// point to the next data element after the chunk header: the first parameter ID
SerializedObject<uint32_t const> const newParameterIDs(OffsetAddress(incomingData_copy.get(), storedHeaderSize));
size_t const sizeOfStoredParameterIDs = newParameterIDs.sizeOfType() * numStoredParameters;
validateRange(newParameterIDs.getByteAddress(), sizeOfStoredParameterIDs, "parameter IDs");
// XXX plain contiguous data container copy required for passing to getParameterIndexFromMap
std::vector<uint32_t> newParameterIDs_copy(numStoredParameters, dfx::kParameterID_Invalid);
std::copy_n(newParameterIDs.begin(), numStoredParameters, newParameterIDs_copy.begin());
// create a mapping table for corresponding the incoming parameters to the
// destination parameters (in case the parameter IDs don't all match up)
// [ the index of parameterMap is the same as our parameter tag/index and the value
// is the tag/index of the incoming parameter that corresponds, if any ]
std::vector<dfx::ParameterID> parameterMap(mNumParameters, dfx::kParameterID_Invalid);
for (size_t i = 0; i < mParameterIDMap.size(); i++)
{
parameterMap[i] = getParameterIndexFromMap(mParameterIDMap[i], newParameterIDs_copy);
}
// point to the next data element after the parameter IDs: the first preset name
auto const firstNewPresetByteAddress = newParameterIDs.getByteAddress() + sizeOfStoredParameterIDs;
auto newPresetName = reinterpret_cast<GenPresetNameElementT const*>(firstNewPresetByteAddress + offsetof(GenPreset, mName));
SerializedObject<GenPresetParameterValueT const> newPresetParameterValues(firstNewPresetByteAddress + offsetof(GenPreset, mParameterValues));
#ifdef DFX_SUPPORT_OLD_VST_SETTINGS
if (oldVST)
{
newPresetParameterValues.offsetAddress(dfx::math::ToSigned(kDfxOldPresetNameMaxLength) - dfx::math::ToSigned(dfx::kPresetNameMaxLength));
}
size_t const sizeOfStoredPreset = sizeOfGenPreset(numStoredParameters) + (oldVST ? kDfxOldPresetNameMaxLength : 0) - (oldVST ? dfx::kPresetNameMaxLength : 0);
#else
auto const sizeOfStoredPreset = sizeOfGenPreset(numStoredParameters);
#endif
validateRange(firstNewPresetByteAddress, sizeOfStoredPreset * numStoredPresets, "presets");
constexpr auto getPresetNameWithFallback = [](std::string_view presetName) -> std::string_view
{
return presetName.empty() ? "(unnamed)" : presetName;
};
// the chunk being received only contains one preset
if (inIsPreset)
{
// in Audio Unit, this is handled already in AUBase::RestoreState,
// and we are not really loading a "preset,"
// we are restoring the last user state
#ifndef TARGET_API_AUDIOUNIT
// copy the preset name from the chunk
mPlugin.setpresetname(mPlugin.getcurrentpresetnum(), getPresetNameWithFallback(newPresetName));
#endif
// copy all of the parameters that we can for this preset from the chunk
for (dfx::ParameterID i = 0; i < parameterMap.size(); i++)
{
auto const mappedParameterID = parameterMap[i];
if ((mappedParameterID != dfx::kParameterID_Invalid) && (mappedParameterID < numStoredParameters))
{
#ifdef DFX_SUPPORT_OLD_VST_SETTINGS
// handle old-style generic VST 0-to-1 normalized parameter values
if (oldVST)
{
mPlugin.setparameter_gen(i, newPresetParameterValues[mappedParameterID]);
}
else
#endif
{
mPlugin.setparameter_f(i, newPresetParameterValues[mappedParameterID]);
}
// allow for additional tweaking of the stored parameter setting
mPlugin.settings_doChunkRestoreSetParameterStuff(i, newPresetParameterValues[mappedParameterID], storedVersion, {});
}
}
// point past the preset
newPresetName = OffsetAddress(newPresetName, sizeOfStoredPreset);
newPresetParameterValues.offsetAddress(sizeOfStoredPreset);
}
// the chunk being received has all of the presets plus the MIDI event assignments
else
{
// we're loading an entire bank of presets plus the MIDI event assignments,
// so cycle through all of the presets and load them up, as many as we can
for (size_t j = 0; j < copyPresets; j++)
{
// copy the preset name from the chunk
mPlugin.setpresetname(j, getPresetNameWithFallback(newPresetName));
// copy all of the parameters that we can for this preset from the chunk
for (dfx::ParameterID i = 0; i < parameterMap.size(); i++)
{
auto const mappedParameterID = parameterMap[i];
if ((mappedParameterID != dfx::kParameterID_Invalid) && (mappedParameterID < numStoredParameters))
{
#ifdef DFX_SUPPORT_OLD_VST_SETTINGS
// handle old-style generic VST 0-to-1 normalized parameter values
if (oldVST)
{
mPlugin.setpresetparameter_gen(j, i, newPresetParameterValues[mappedParameterID]);
}
else
#endif
{
mPlugin.setpresetparameter_f(j, i, newPresetParameterValues[mappedParameterID]);
}
// allow for additional tweaking of the stored parameter setting
mPlugin.settings_doChunkRestoreSetParameterStuff(i, newPresetParameterValues[mappedParameterID], storedVersion, j);
}
}
// point to the next preset in the received data array
newPresetName = OffsetAddress(newPresetName, sizeOfStoredPreset);
newPresetParameterValues.offsetAddress(sizeOfStoredPreset);
}
}
// point to the last chunk data element, the MIDI event assignment array
// (offset by the number of stored presets that were skipped, if any)
auto const newParameterAssignments = firstNewPresetByteAddress + (numStoredPresets * sizeOfStoredPreset);
size_t sizeOfStoredParameterAssignments = 0; // until we establish that they are present
#ifdef DFX_SUPPORT_OLD_VST_SETTINGS
if (!(oldVST && inIsPreset))
#endif
{
// completely clear our table of parameter assignments before loading the new
// table since the new one might not have all of the data members
clearAssignments();
sizeOfStoredParameterAssignments = storedParameterAssignmentSize * numStoredParameters;
validateRange(newParameterAssignments, sizeOfStoredParameterAssignments, "parameter assignments");
// and load up as many of them as we can
for (size_t i = 0; i < std::min(parameterMap.size(), mParameterAssignments.size()); i++)
{
auto const mappedParameterID = parameterMap[i];
if ((mappedParameterID != dfx::kParameterID_Invalid) && (mappedParameterID < numStoredParameters))
{
mParameterAssignments[i] = {};
std::memcpy(&(mParameterAssignments[i]),
newParameterAssignments + (mappedParameterID * storedParameterAssignmentSize),
copyParameterAssignmentSize);
}
}
}
// allow for the retrieval of extra data
if (storedExtendedDataSize > 0)
{
auto const newExtendedData = newParameterAssignments + sizeOfStoredParameterAssignments;
validateRange(newExtendedData, storedExtendedDataSize, "extended data");
mPlugin.settings_restoreExtendedData(newExtendedData, storedExtendedDataSize, storedVersion, inIsPreset);
}
return true;
}
catch (...)
{
return false;
}
//-----------------------------------------------------------------------------
bool DfxSettings::minimalValidate(void const* inData, size_t inDataSize) const noexcept
{
SettingsInfo settingsInfo;
if (!inData || (inDataSize < sizeof(settingsInfo)))
{
return false;
}
std::memcpy(&settingsInfo, inData, sizeof(settingsInfo));
if constexpr (!serializationIsNativeEndian())
{
dfx::ReverseBytes(settingsInfo.mMagic);
dfx::ReverseBytes(settingsInfo.mVersion);
dfx::ReverseBytes(settingsInfo.mStoredHeaderSize);
}
return (settingsInfo.mMagic == mSettingsInfo.mMagic) && (settingsInfo.mVersion == mSettingsInfo.mVersion) && (settingsInfo.mStoredHeaderSize == mSettingsInfo.mStoredHeaderSize);
}
//-----------------------------------------------------------------------------
// this function, if called for the non-reference endian architecture,
// will reverse the order of bytes in each variable/value of the data
// to correct endian differences and make a uniform data chunk
bool DfxSettings::correctEndian(void* const ioData, size_t const inDataSize, bool inIsReversed, bool inIsPreset) const
try
{
/*
// XXX another idea...
void blah(long long x)
{
int n = sizeof(x);
while (n--)
{
write(f, x & 0xFF, 1);
x >>= 8;
}
}
*/
if constexpr (serializationIsNativeEndian())
{
return true;
}
// start by looking at the header info
auto const dataHeaderAddress = ioData;
// we need to know how big the header is before dealing with it
auto storedVersion = GET_SERIALIZED_HEADER_FIELD(dataHeaderAddress, mVersion);
auto storedHeaderSize = GET_SERIALIZED_HEADER_FIELD(dataHeaderAddress, mStoredHeaderSize);
auto numStoredParameters = GET_SERIALIZED_HEADER_FIELD(dataHeaderAddress, mNumStoredParameters);
auto numStoredPresets = GET_SERIALIZED_HEADER_FIELD(dataHeaderAddress, mNumStoredPresets);
auto storedParameterAssignmentSize = GET_SERIALIZED_HEADER_FIELD(dataHeaderAddress, mStoredParameterAssignmentSize);
// correct the values' endian byte order order if the data was received byte-swapped
if (inIsReversed)
{
dfx::ReverseBytes(storedVersion);
dfx::ReverseBytes(storedHeaderSize);
dfx::ReverseBytes(numStoredParameters);
dfx::ReverseBytes(numStoredPresets);
dfx::ReverseBytes(storedParameterAssignmentSize);
}
auto const validateRange = [ioData, inDataSize, this](void const* address, size_t length, char const* name)
{
this->validateRange(ioData, inDataSize, address, length, name);
};
// reverse the order of bytes of the header values
validateRange(dataHeaderAddress, storedHeaderSize, "header");
constexpr auto headerItemSize = sizeof(SettingsInfo::mMagic);
if ((storedHeaderSize % headerItemSize) != 0)
{
debugAlertCorruptData("header divisibility", storedHeaderSize, inDataSize);
return false;
}
dfx::ReverseBytes(dataHeaderAddress, headerItemSize, storedHeaderSize / headerItemSize);
// reverse the byte order for each of the parameter IDs
auto const dataParameterIDs = OffsetAddressToType<uint32_t>(dataHeaderAddress, storedHeaderSize);
validateRange(dataParameterIDs, sizeof(*dataParameterIDs) * numStoredParameters, "parameter IDs");
dfx::ReverseBytes(dataParameterIDs, numStoredParameters);
// reverse the order of bytes for each parameter value,
// but no need to mess with the preset names since they are char arrays
auto dataPresets = OffsetAddressToType<GenPreset>(dataParameterIDs, sizeof(*dataParameterIDs) * numStoredParameters);
auto sizeOfStoredPreset = sizeOfGenPreset(numStoredParameters);
#ifdef DFX_SUPPORT_OLD_VST_SETTINGS
if (DFX_IsOldVstVersionNumber(storedVersion))
{
// back up the pointer to account for shorter preset names
dataPresets = OffsetAddress(dataPresets, dfx::math::ToSigned(kDfxOldPresetNameMaxLength) - dfx::math::ToSigned(dfx::kPresetNameMaxLength));
// and shrink the size to account for shorter preset names
if (sizeOfStoredPreset < dfx::kPresetNameMaxLength)
{
debugAlertCorruptData("old VST presets", sizeOfStoredPreset, inDataSize);
return false;
}
sizeOfStoredPreset += kDfxOldPresetNameMaxLength;
sizeOfStoredPreset -= dfx::kPresetNameMaxLength;
}
#endif
validateRange(dataPresets, sizeOfStoredPreset * numStoredPresets, "presets");
for (uint32_t i = 0; i < numStoredPresets; i++)
{
dfx::ReverseBytes(dataPresets->mParameterValues, numStoredParameters);
// point to the next preset in the data array
dataPresets = OffsetAddress(dataPresets, sizeOfStoredPreset);
}
#ifdef DFX_SUPPORT_OLD_VST_SETTINGS
if (DFX_IsOldVstVersionNumber(storedVersion))
{
// advance the pointer to compensate for backing up earlier
dataPresets = OffsetAddress(dataPresets, dfx::math::ToSigned(dfx::kPresetNameMaxLength) - dfx::math::ToSigned(kDfxOldPresetNameMaxLength));
}
#endif
#ifdef DFX_SUPPORT_OLD_VST_SETTINGS
if (!(DFX_IsOldVstVersionNumber(storedVersion) && inIsPreset))
#endif
{
// and reverse the byte order of each event assignment
auto dataParameterAssignment = reinterpret_cast<dfx::ParameterAssignment*>(dataPresets);
validateRange(dataParameterAssignment, storedParameterAssignmentSize * numStoredParameters, "parameter assignments");
auto const copyParameterAssignmentSize = std::min(storedParameterAssignmentSize, mSettingsInfo.mStoredParameterAssignmentSize);
for (uint32_t i = 0; i < numStoredParameters; ++i)
{
dfx::ParameterAssignment pa;
std::memcpy(&pa, dataParameterAssignment, copyParameterAssignmentSize);
dfx::ReverseBytes(pa.mEventType);
dfx::ReverseBytes(pa.mEventChannel);
dfx::ReverseBytes(pa.mEventNum);
dfx::ReverseBytes(pa.mEventNum2);
dfx::ReverseBytes(pa.mEventBehaviorFlags);
dfx::ReverseBytes(pa.mDataInt1);
dfx::ReverseBytes(pa.mDataInt2);
dfx::ReverseBytes(pa.mDataFloat1);
dfx::ReverseBytes(pa.mDataFloat2);
std::memcpy(dataParameterAssignment, &pa, copyParameterAssignmentSize);
dataParameterAssignment = OffsetAddress(dataParameterAssignment, storedParameterAssignmentSize);
}
}
return true;
}
catch (...)
{
return false;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#pragma mark -
#pragma mark Audio Unit -specific stuff
#pragma mark -
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#ifdef TARGET_API_AUDIOUNIT
static CFStringRef const kDfxSettings_ParameterIDKey = CFSTR("parameter ID");
static CFStringRef const kDfxSettings_MidiAssignmentsKey = CFSTR("DFX! MIDI assignments");
static CFStringRef const kDfxSettings_MidiAssignment_mEventTypeKey = CFSTR("event type");
static CFStringRef const kDfxSettings_MidiAssignment_mEventChannelKey = CFSTR("event channel");
static CFStringRef const kDfxSettings_MidiAssignment_mEventNumKey = CFSTR("event number");
static CFStringRef const kDfxSettings_MidiAssignment_mEventNum2Key = CFSTR("event number 2");
static CFStringRef const kDfxSettings_MidiAssignment_mEventBehaviorFlagsKey = CFSTR("event behavior flags");
static CFStringRef const kDfxSettings_MidiAssignment_mDataInt1Key = CFSTR("integer data 1");
static CFStringRef const kDfxSettings_MidiAssignment_mDataInt2Key = CFSTR("integer data 2");
static CFStringRef const kDfxSettings_MidiAssignment_mDataFloat1Key = CFSTR("float data 1");
static CFStringRef const kDfxSettings_MidiAssignment_mDataFloat2Key = CFSTR("float data 2");
namespace
{
//-----------------------------------------------------------------------------------------
bool DFX_AddNumberToCFDictionary(void const* inNumber, CFNumberType inType, CFMutableDictionaryRef inDictionary, void const* inDictionaryKey)
{
if (!inNumber || !inDictionary || !inDictionaryKey)
{
return false;
}
auto const cfNumber = dfx::MakeUniqueCFType(CFNumberCreate(kCFAllocatorDefault, inType, inNumber));
if (cfNumber)
{
CFDictionarySetValue(inDictionary, inDictionaryKey, cfNumber.get());
return true;
}
return false;
}
//-----------------------------------------------------------------------------------------
bool DFX_AddNumberToCFDictionary_i(SInt64 inNumber, CFMutableDictionaryRef inDictionary, void const* inDictionaryKey)
{
return DFX_AddNumberToCFDictionary(&inNumber, kCFNumberSInt64Type, inDictionary, inDictionaryKey);
}
//-----------------------------------------------------------------------------------------
bool DFX_AddNumberToCFDictionary_f(Float64 inNumber, CFMutableDictionaryRef inDictionary, void const* inDictionaryKey)
{
return DFX_AddNumberToCFDictionary(&inNumber, kCFNumberFloat64Type, inDictionary, inDictionaryKey);
}
} // namespace
//-----------------------------------------------------------------------------------------
std::optional<SInt64> DFX_GetNumberFromCFDictionary_i(CFDictionaryRef inDictionary, void const* inDictionaryKey)
{
constexpr CFNumberType numberType = kCFNumberSInt64Type;
if (!inDictionary || !inDictionaryKey)
{
return {};
}
auto const cfNumber = static_cast<CFNumberRef>(CFDictionaryGetValue(inDictionary, inDictionaryKey));
if (cfNumber && (CFGetTypeID(cfNumber) == CFNumberGetTypeID()))
{
if (CFNumberGetType(cfNumber) == numberType)
{
SInt64 resultNumber {};
if (CFNumberGetValue(cfNumber, numberType, &resultNumber))
{
return resultNumber;
}
}
}
return {};
}
//-----------------------------------------------------------------------------------------
std::optional<Float64> DFX_GetNumberFromCFDictionary_f(CFDictionaryRef inDictionary, void const* inDictionaryKey)
{
constexpr CFNumberType numberType = kCFNumberFloat64Type;
if (!inDictionary || !inDictionaryKey)
{
return {};
}
auto const cfNumber = static_cast<CFNumberRef>(CFDictionaryGetValue(inDictionary, inDictionaryKey));
if (cfNumber && (CFGetTypeID(cfNumber) == CFNumberGetTypeID()))
{
if (CFNumberGetType(cfNumber) == numberType)
{
Float64 resultNumber {};
if (CFNumberGetValue(cfNumber, numberType, &resultNumber))
{
return resultNumber;
}
}
}
return {};
}
//-----------------------------------------------------------------------------------------
bool DfxSettings::saveMidiAssignmentsToDictionary(CFMutableDictionaryRef inDictionary) const
{
if (!inDictionary)
{
return false;
}
size_t assignmentsFoundCount = 0;
for (dfx::ParameterID i = 0; i < mNumParameters; i++)
{
if (getParameterAssignmentType(i) != dfx::MidiEventType::None)
{
assignmentsFoundCount++;
}
}
// nothing to do
if (assignmentsFoundCount == 0)
{
return true;
}
auto const assignmentsCFArray = dfx::MakeUniqueCFType(CFArrayCreateMutable(kCFAllocatorDefault, mNumParameters, &kCFTypeArrayCallBacks));
if (!assignmentsCFArray)
{
return false;
}
for (dfx::ParameterID i = 0; i < mNumParameters; i++)
{
auto const assignmentCFDictionary = dfx::MakeUniqueCFType(CFDictionaryCreateMutable(kCFAllocatorDefault, 10, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
if (assignmentCFDictionary)
{
if (getMappedParameterID(i) == dfx::kParameterID_Invalid)
{
continue;
}
DFX_AddNumberToCFDictionary_i(getMappedParameterID(i), assignmentCFDictionary.get(), kDfxSettings_ParameterIDKey);
DFX_AddNumberToCFDictionary_i(static_cast<SInt64>(mParameterAssignments[i].mEventType),
assignmentCFDictionary.get(), kDfxSettings_MidiAssignment_mEventTypeKey);
#define ADD_ASSIGNMENT_VALUE_TO_DICT(inMember, inTypeSuffix) \
DFX_AddNumberToCFDictionary_##inTypeSuffix(mParameterAssignments[i].inMember, assignmentCFDictionary.get(), kDfxSettings_MidiAssignment_##inMember##Key);
ADD_ASSIGNMENT_VALUE_TO_DICT(mEventChannel, i)
ADD_ASSIGNMENT_VALUE_TO_DICT(mEventNum, i)
ADD_ASSIGNMENT_VALUE_TO_DICT(mEventNum2, i)
ADD_ASSIGNMENT_VALUE_TO_DICT(mEventBehaviorFlags, i)
ADD_ASSIGNMENT_VALUE_TO_DICT(mDataInt1, i)
ADD_ASSIGNMENT_VALUE_TO_DICT(mDataInt2, i)
ADD_ASSIGNMENT_VALUE_TO_DICT(mDataFloat1, f)
ADD_ASSIGNMENT_VALUE_TO_DICT(mDataFloat2, f)
#undef ADD_ASSIGNMENT_VALUE_TO_DICT
CFArraySetValueAtIndex(assignmentsCFArray.get(), i, assignmentCFDictionary.get());
}
}
auto const arraySize = CFArrayGetCount(assignmentsCFArray.get());
if (arraySize > 0)
{
CFDictionarySetValue(inDictionary, kDfxSettings_MidiAssignmentsKey, assignmentsCFArray.get());
}
return (dfx::math::ToUnsigned(arraySize) == assignmentsFoundCount);
}
//-----------------------------------------------------------------------------------------
bool DfxSettings::restoreMidiAssignmentsFromDictionary(CFDictionaryRef inDictionary)
{
if (!inDictionary)
{
return false;
}
auto const assignmentsCFArray = static_cast<CFArrayRef>(CFDictionaryGetValue(inDictionary, kDfxSettings_MidiAssignmentsKey));
// nothing to do
if (!assignmentsCFArray)
{
return true;
}
if (CFGetTypeID(assignmentsCFArray) != CFArrayGetTypeID())
{
return false;
}
// completely clear our table of parameter assignments before loading the new
// table since the new one might not have all of the data members
clearAssignments();
auto const arraySize = CFArrayGetCount(assignmentsCFArray);
for (CFIndex i = 0; i < arraySize; i++)
{
auto const assignmentCFDictionary = static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(assignmentsCFArray, i));
if (assignmentCFDictionary)
{
auto const parameterID_optional = DFX_GetNumberFromCFDictionary_i(assignmentCFDictionary, kDfxSettings_ParameterIDKey);
if (!parameterID_optional || (*parameterID_optional < 0))
{
continue;
}
auto const parameterID = getParameterIndexFromMap(static_cast<dfx::ParameterID>(*parameterID_optional));
if (!isValidParameterID(parameterID))
{
continue;
}
#define GET_ASSIGNMENT_VALUE_FROM_DICT(inMember, inTypeSuffix) \
{ \
auto const optionalValue = DFX_GetNumberFromCFDictionary_##inTypeSuffix(assignmentCFDictionary, kDfxSettings_MidiAssignment_##inMember##Key); \
mParameterAssignments[parameterID].inMember = static_cast<decltype(mParameterAssignments[parameterID].inMember)>(optionalValue.value_or(0)); \
numberSuccess = optionalValue.has_value(); \
}
bool numberSuccess = false;
GET_ASSIGNMENT_VALUE_FROM_DICT(mEventType, i)
if (!numberSuccess)
{
unassignParameter(parameterID);
continue;
}
GET_ASSIGNMENT_VALUE_FROM_DICT(mEventChannel, i)
GET_ASSIGNMENT_VALUE_FROM_DICT(mEventNum, i)
GET_ASSIGNMENT_VALUE_FROM_DICT(mEventNum2, i)
GET_ASSIGNMENT_VALUE_FROM_DICT(mEventBehaviorFlags, i)
GET_ASSIGNMENT_VALUE_FROM_DICT(mDataInt1, i)
GET_ASSIGNMENT_VALUE_FROM_DICT(mDataInt2, i)
GET_ASSIGNMENT_VALUE_FROM_DICT(mDataFloat1, f)
GET_ASSIGNMENT_VALUE_FROM_DICT(mDataFloat2, f)
#undef GET_ASSIGNMENT_VALUE_FROM_DICT
}
}
// this seems like a good enough sign that we at least partially succeeded
return (arraySize > 0);
}
#endif // TARGET_API_AUDIOUNIT
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#pragma mark -
#pragma mark MIDI learn
#pragma mark -
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//-----------------------------------------------------------------------------------------
void DfxSettings::handleCC(int inMidiChannel, int inControllerNumber, int inValue, size_t inOffsetFrames)
{
// don't allow the "all notes off" CC because almost every sequencer uses that when playback stops
if (inControllerNumber == DfxMidi::kCC_AllNotesOff)
{
return;
}
handleMidi_assignParameter(dfx::MidiEventType::CC, inMidiChannel, inControllerNumber, inOffsetFrames);
handleMidi_automateParameters(dfx::MidiEventType::CC, inMidiChannel, inControllerNumber, inValue, inOffsetFrames);
}
//-----------------------------------------------------------------------------------------
void DfxSettings::handleChannelAftertouch(int inMidiChannel, int inValue, size_t inOffsetFrames)
{
if (!mAllowChannelAftertouchEvents)
{