-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
juce_audio_plugin_client_LV2.cpp
1815 lines (1480 loc) · 66.2 KB
/
juce_audio_plugin_client_LV2.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
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
Agreement and JUCE Privacy Policy.
End User License Agreement: www.juce.com/juce-7-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#if JucePlugin_Build_LV2
#ifndef _SCL_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_WARNINGS
#endif
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#define JUCE_CORE_INCLUDE_NATIVE_HEADERS 1
#define JUCE_CORE_INCLUDE_OBJC_HELPERS 1
#define JUCE_GUI_BASICS_INCLUDE_XHEADERS 1
#include <juce_audio_plugin_client/juce_audio_plugin_client.h>
#include <juce_audio_plugin_client/detail/juce_CheckSettingMacros.h>
#include <juce_audio_plugin_client/detail/juce_PluginUtilities.h>
#include <juce_audio_plugin_client/detail/juce_LinuxMessageThread.h>
#include <juce_audio_processors/utilities/juce_FlagCache.h>
#include <juce_audio_processors/format_types/juce_LegacyAudioParameter.cpp>
#include "JuceLV2Defines.h"
#include <juce_audio_processors/format_types/juce_LV2Common.h>
#include <fstream>
#define JUCE_TURTLE_RECALL_URI "https://lv2-extensions.juce.com/turtle_recall"
#ifndef JucePlugin_LV2URI
#error "You need to define the JucePlugin_LV2URI value! If you're using the Projucer/CMake, the definition will be written into JuceLV2Defines.h automatically."
#endif
namespace juce
{
namespace lv2_client
{
constexpr auto uriSeparator = ":";
const auto JucePluginLV2UriUi = String (JucePlugin_LV2URI) + uriSeparator + "UI";
const auto JucePluginLV2UriState = String (JucePlugin_LV2URI) + uriSeparator + "StateString";
const auto JucePluginLV2UriProgram = String (JucePlugin_LV2URI) + uriSeparator + "Program";
static const LV2_Feature* findMatchingFeature (const LV2_Feature* const* features, const char* uri)
{
for (auto feature = features; *feature != nullptr; ++feature)
if (std::strcmp ((*feature)->URI, uri) == 0)
return *feature;
return nullptr;
}
static bool hasFeature (const LV2_Feature* const* features, const char* uri)
{
return findMatchingFeature (features, uri) != nullptr;
}
template <typename Data>
Data findMatchingFeatureData (const LV2_Feature* const* features, const char* uri)
{
if (const auto* feature = findMatchingFeature (features, uri))
return static_cast<Data> (feature->data);
return {};
}
static const LV2_Options_Option* findMatchingOption (const LV2_Options_Option* options, LV2_URID urid)
{
for (auto option = options; option->value != nullptr; ++option)
if (option->key == urid)
return option;
return nullptr;
}
class ParameterStorage : private AudioProcessorListener
{
public:
ParameterStorage (AudioProcessor& proc, LV2_URID_Map map)
: processor (proc),
mapFeature (map),
legacyParameters (proc, false)
{
processor.addListener (this);
}
~ParameterStorage() override
{
processor.removeListener (this);
}
/* This is the string that will be used to uniquely identify the parameter.
This string will be written into the plugin's manifest as an IRI, so it must be
syntactically valid.
We escape this string rather than writing the user-defined parameter ID directly to avoid
writing a malformed manifest in the case that user IDs contain spaces or other reserved
characters. This should allow users to keep the same param IDs for all plugin formats.
*/
static String getIri (const AudioProcessorParameter& param)
{
const auto urlSanitised = URL::addEscapeChars (LegacyAudioParameter::getParamID (¶m, false), true);
const auto ttlSanitised = lv2_shared::sanitiseStringAsTtlName (urlSanitised);
// If this is hit, the parameter ID could not be represented directly in the plugin ttl.
// We'll replace offending characters with '_'.
jassert (urlSanitised == ttlSanitised);
return ttlSanitised;
}
void setValueFromHost (LV2_URID urid, float value) noexcept
{
const auto it = uridToIndexMap.find (urid);
if (it == uridToIndexMap.end())
{
// No such parameter.
jassertfalse;
return;
}
if (auto* param = legacyParameters.getParamForIndex ((int) it->second))
{
const auto scaledValue = [&]
{
if (auto* rangedParam = dynamic_cast<RangedAudioParameter*> (param))
return rangedParam->convertTo0to1 (value);
return value;
}();
if (! approximatelyEqual (scaledValue, param->getValue()))
{
ScopedValueSetter<bool> scope (ignoreCallbacks, true);
param->setValueNotifyingHost (scaledValue);
}
}
}
struct Options
{
bool parameterValue, gestureBegin, gestureEnd;
};
static constexpr auto newClientValue = 1 << 0,
gestureBegan = 1 << 1,
gestureEnded = 1 << 2;
template <typename Callback>
void forEachChangedParameter (Callback&& callback)
{
stateCache.ifSet ([this, &callback] (size_t parameterIndex, float, uint32_t bits)
{
const Options options { (bits & newClientValue) != 0,
(bits & gestureBegan) != 0,
(bits & gestureEnded) != 0 };
callback (*legacyParameters.getParamForIndex ((int) parameterIndex),
indexToUridMap[parameterIndex],
options);
});
}
private:
void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float value) override
{
if (! ignoreCallbacks)
stateCache.setValueAndBits ((size_t) parameterIndex, value, newClientValue);
}
void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int parameterIndex) override
{
if (! ignoreCallbacks)
stateCache.setBits ((size_t) parameterIndex, gestureBegan);
}
void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int parameterIndex) override
{
if (! ignoreCallbacks)
stateCache.setBits ((size_t) parameterIndex, gestureEnded);
}
void audioProcessorChanged (AudioProcessor*, const ChangeDetails&) override {}
AudioProcessor& processor;
const LV2_URID_Map mapFeature;
const LegacyAudioParametersWrapper legacyParameters;
const std::vector<LV2_URID> indexToUridMap = [&]
{
std::vector<LV2_URID> result;
for (auto* param : legacyParameters)
{
jassert ((size_t) param->getParameterIndex() == result.size());
const auto uri = JucePlugin_LV2URI + String (uriSeparator) + getIri (*param);
const auto urid = mapFeature.map (mapFeature.handle, uri.toRawUTF8());
result.push_back (urid);
}
// If this is hit, some parameters have duplicate IDs.
// This may be because the IDs resolve to the same string when removing characters that
// are invalid in a TTL name.
jassert (std::set<LV2_URID> (result.begin(), result.end()).size() == result.size());
return result;
}();
const std::map<LV2_URID, size_t> uridToIndexMap = [&]
{
std::map<LV2_URID, size_t> result;
size_t index = 0;
for (const auto& urid : indexToUridMap)
result.emplace (urid, index++);
return result;
}();
FlaggedFloatCache<3> stateCache { (size_t) legacyParameters.getNumParameters() };
bool ignoreCallbacks = false;
JUCE_LEAK_DETECTOR (ParameterStorage)
};
enum class PortKind { seqInput, seqOutput, latencyOutput, freeWheelingInput, enabledInput };
struct PortIndices
{
PortIndices (int numInputsIn, int numOutputsIn)
: numInputs (numInputsIn), numOutputs (numOutputsIn) {}
int getPortIndexForAudioInput (int audioIndex) const noexcept
{
return audioIndex;
}
int getPortIndexForAudioOutput (int audioIndex) const noexcept
{
return audioIndex + numInputs;
}
int getPortIndexFor (PortKind p) const noexcept { return getMaxAudioPortIndex() + (int) p; }
// Audio ports are numbered from 0 to numInputs + numOutputs
int getMaxAudioPortIndex() const noexcept { return numInputs + numOutputs; }
int numInputs, numOutputs;
};
//==============================================================================
class PlayHead : public AudioPlayHead
{
public:
PlayHead (LV2_URID_Map mapFeatureIn, double sampleRateIn)
: parser (mapFeatureIn), sampleRate (sampleRateIn)
{
}
void invalidate() { info = nullopt; }
void readNewInfo (const LV2_Atom_Event* event)
{
if (event->body.type != mLV2_ATOM__Object && event->body.type != mLV2_ATOM__Blank)
return;
const auto* object = reinterpret_cast<const LV2_Atom_Object*> (&event->body);
if (object->body.otype != mLV2_TIME__Position)
return;
const LV2_Atom* atomFrame = nullptr;
const LV2_Atom* atomSpeed = nullptr;
const LV2_Atom* atomBar = nullptr;
const LV2_Atom* atomBeat = nullptr;
const LV2_Atom* atomBeatUnit = nullptr;
const LV2_Atom* atomBeatsPerBar = nullptr;
const LV2_Atom* atomBeatsPerMinute = nullptr;
LV2_Atom_Object_Query query[] { { mLV2_TIME__frame, &atomFrame },
{ mLV2_TIME__speed, &atomSpeed },
{ mLV2_TIME__bar, &atomBar },
{ mLV2_TIME__beat, &atomBeat },
{ mLV2_TIME__beatUnit, &atomBeatUnit },
{ mLV2_TIME__beatsPerBar, &atomBeatsPerBar },
{ mLV2_TIME__beatsPerMinute, &atomBeatsPerMinute },
LV2_ATOM_OBJECT_QUERY_END };
lv2_atom_object_query (object, query);
info.emplace();
// Carla always seems to give us an integral 'beat' even though I'd expect
// it to be a floating-point value
const auto numerator = parser.parseNumericAtom<float> (atomBeatsPerBar);
const auto denominator = parser.parseNumericAtom<int32_t> (atomBeatUnit);
if (numerator.hasValue() && denominator.hasValue())
info->setTimeSignature (TimeSignature { (int) *numerator, (int) *denominator });
info->setBpm (parser.parseNumericAtom<float> (atomBeatsPerMinute));
info->setPpqPosition (parser.parseNumericAtom<double> (atomBeat));
info->setIsPlaying (! approximatelyEqual (parser.parseNumericAtom<float> (atomSpeed).orFallback (0.0f), 0.0f));
info->setBarCount (parser.parseNumericAtom<int64_t> (atomBar));
if (const auto parsed = parser.parseNumericAtom<int64_t> (atomFrame))
{
info->setTimeInSamples (*parsed);
info->setTimeInSeconds ((double) *parsed / sampleRate);
}
}
Optional<PositionInfo> getPosition() const override
{
return info;
}
private:
lv2_shared::NumericAtomParser parser;
Optional<PositionInfo> info;
double sampleRate;
#define X(str) const LV2_URID m##str = parser.map (str);
X (LV2_ATOM__Blank)
X (LV2_ATOM__Object)
X (LV2_TIME__Position)
X (LV2_TIME__beat)
X (LV2_TIME__beatUnit)
X (LV2_TIME__beatsPerBar)
X (LV2_TIME__beatsPerMinute)
X (LV2_TIME__frame)
X (LV2_TIME__speed)
X (LV2_TIME__bar)
#undef X
JUCE_LEAK_DETECTOR (PlayHead)
};
//==============================================================================
class Ports
{
public:
Ports (LV2_URID_Map map, int numInputsIn, int numOutputsIn)
: forge (map),
indices (numInputsIn, numOutputsIn),
mLV2_ATOM__Sequence (map.map (map.handle, LV2_ATOM__Sequence))
{
audioBuffers.resize (static_cast<size_t> (numInputsIn + numOutputsIn), nullptr);
}
void connect (int port, void* data)
{
// The following is not UB _if_ data really points to an object with the expected type.
if (port == indices.getPortIndexFor (PortKind::seqInput))
{
inputData = static_cast<const LV2_Atom_Sequence*> (data);
}
else if (port == indices.getPortIndexFor (PortKind::seqOutput))
{
outputData = static_cast<LV2_Atom_Sequence*> (data);
}
else if (port == indices.getPortIndexFor (PortKind::latencyOutput))
{
latency = static_cast<float*> (data);
}
else if (port == indices.getPortIndexFor (PortKind::freeWheelingInput))
{
freeWheeling = static_cast<float*> (data);
}
else if (port == indices.getPortIndexFor (PortKind::enabledInput))
{
enabled = static_cast<float*> (data);
}
else if (isPositiveAndBelow (port, indices.getMaxAudioPortIndex()))
{
audioBuffers[(size_t) port] = static_cast<float*> (data);
}
else
{
// This port was not declared!
jassertfalse;
}
}
template <typename Callback>
void forEachInputEvent (Callback&& callback)
{
if (inputData != nullptr && inputData->atom.type == mLV2_ATOM__Sequence)
for (const auto* event : lv2_shared::SequenceIterator { lv2_shared::SequenceWithSize { inputData } })
callback (event);
}
void prepareToWrite()
{
// Note: Carla seems to have a bug (verified with the eg-fifths plugin) where
// the output buffer size is incorrect on alternate calls.
forge.setBuffer (reinterpret_cast<char*> (outputData), outputData->atom.size);
}
void writeLatency (int value)
{
if (latency != nullptr)
*latency = (float) value;
}
const float* getBufferForAudioInput (int index) const noexcept
{
return audioBuffers[(size_t) indices.getPortIndexForAudioInput (index)];
}
float* getBufferForAudioOutput (int index) const noexcept
{
return audioBuffers[(size_t) indices.getPortIndexForAudioOutput (index)];
}
bool isFreeWheeling() const noexcept
{
if (freeWheeling != nullptr)
return *freeWheeling > 0.5f;
return false;
}
bool isEnabled() const noexcept
{
if (enabled != nullptr)
return *enabled > 0.5f;
return true;
}
lv2_shared::AtomForge forge;
PortIndices indices;
private:
static constexpr auto numParamPorts = 3;
const LV2_Atom_Sequence* inputData = nullptr;
LV2_Atom_Sequence* outputData = nullptr;
float* latency = nullptr;
float* freeWheeling = nullptr;
float* enabled = nullptr;
std::vector<float*> audioBuffers;
const LV2_URID mLV2_ATOM__Sequence;
JUCE_LEAK_DETECTOR (Ports)
};
class LV2PluginInstance : private AudioProcessorListener
{
public:
LV2PluginInstance (double sampleRate,
int64_t maxBlockSize,
const char*,
LV2_URID_Map mapFeatureIn)
: mapFeature (mapFeatureIn),
playHead (mapFeature, sampleRate)
{
processor->addListener (this);
processor->setPlayHead (&playHead);
prepare (sampleRate, (int) maxBlockSize);
}
void connect (uint32_t port, void* data)
{
ports.connect ((int) port, data);
}
void activate() {}
template<typename UnaryFunction>
static void iterateAudioBuffer (AudioBuffer<float>& ab, UnaryFunction fn)
{
float* const* sampleData = ab.getArrayOfWritePointers();
for (int c = ab.getNumChannels(); --c >= 0;)
for (int s = ab.getNumSamples(); --s >= 0;)
fn (sampleData[c][s]);
}
static int countNaNs (AudioBuffer<float>& ab) noexcept
{
int count = 0;
iterateAudioBuffer (ab, [&count] (float s)
{
if (std::isnan (s))
++count;
});
return count;
}
void run (uint32_t numSteps)
{
// If this is hit, the host is trying to process more samples than it told us to prepare
jassert (static_cast<int> (numSteps) <= processor->getBlockSize());
midi.clear();
playHead.invalidate();
audio.setSize (audio.getNumChannels(), static_cast<int> (numSteps), true, false, true);
ports.forEachInputEvent ([&] (const LV2_Atom_Event* event)
{
struct Callback
{
explicit Callback (LV2PluginInstance& s) : self (s) {}
void setParameter (LV2_URID property, float value) const noexcept
{
self.parameters.setValueFromHost (property, value);
}
// The host probably shouldn't send us 'touched' messages.
void gesture (LV2_URID, bool) const noexcept {}
LV2PluginInstance& self;
};
patchSetHelper.processPatchSet (event, Callback { *this });
playHead.readNewInfo (event);
if (event->body.type == mLV2_MIDI__MidiEvent)
midi.addEvent (event + 1, static_cast<int> (event->body.size), static_cast<int> (event->time.frames));
});
processor->setNonRealtime (ports.isFreeWheeling());
for (auto i = 0, end = processor->getTotalNumInputChannels(); i < end; ++i)
audio.copyFrom (i, 0, ports.getBufferForAudioInput (i), audio.getNumSamples());
jassert (countNaNs (audio) == 0);
{
const ScopedLock lock { processor->getCallbackLock() };
if (processor->isSuspended())
{
for (auto i = 0, end = processor->getTotalNumOutputChannels(); i < end; ++i)
{
const auto ptr = ports.getBufferForAudioOutput (i);
std::fill (ptr, ptr + numSteps, 0.0f);
}
}
else
{
const auto isEnabled = ports.isEnabled();
if (auto* param = processor->getBypassParameter())
{
param->setValueNotifyingHost (isEnabled ? 0.0f : 1.0f);
processor->processBlock (audio, midi);
}
else if (isEnabled)
{
processor->processBlock (audio, midi);
}
else
{
processor->processBlockBypassed (audio, midi);
}
}
}
for (auto i = 0, end = processor->getTotalNumOutputChannels(); i < end; ++i)
{
const auto src = audio.getReadPointer (i);
const auto dst = ports.getBufferForAudioOutput (i);
if (dst != nullptr)
std::copy (src, src + numSteps, dst);
}
ports.prepareToWrite();
auto* forge = ports.forge.get();
lv2_shared::SequenceFrame sequence { forge, (uint32_t) 0 };
parameters.forEachChangedParameter ([&] (const AudioProcessorParameter& param,
LV2_URID paramUrid,
const ParameterStorage::Options& options)
{
const auto sendTouched = [&] (bool state)
{
// TODO Implement begin/end change gesture support once it's supported by LV2
ignoreUnused (state);
};
if (options.gestureBegin)
sendTouched (true);
if (options.parameterValue)
{
lv2_atom_forge_frame_time (forge, 0);
lv2_shared::ObjectFrame object { forge, (uint32_t) 0, patchSetHelper.mLV2_PATCH__Set };
lv2_atom_forge_key (forge, patchSetHelper.mLV2_PATCH__property);
lv2_atom_forge_urid (forge, paramUrid);
lv2_atom_forge_key (forge, patchSetHelper.mLV2_PATCH__value);
lv2_atom_forge_float (forge, [&]
{
if (auto* rangedParam = dynamic_cast<const RangedAudioParameter*> (¶m))
return rangedParam->convertFrom0to1 (rangedParam->getValue());
return param.getValue();
}());
}
if (options.gestureEnd)
sendTouched (false);
});
if (shouldSendStateChange.exchange (false))
{
lv2_atom_forge_frame_time (forge, 0);
lv2_shared::ObjectFrame { forge, (uint32_t) 0, mLV2_STATE__StateChanged };
}
for (const auto meta : midi)
{
const auto bytes = static_cast<uint32_t> (meta.numBytes);
lv2_atom_forge_frame_time (forge, meta.samplePosition);
lv2_atom_forge_atom (forge, bytes, mLV2_MIDI__MidiEvent);
lv2_atom_forge_write (forge, meta.data, bytes);
}
ports.writeLatency (processor->getLatencySamples());
}
void deactivate() {}
LV2_State_Status store (LV2_State_Store_Function storeFn,
LV2_State_Handle handle,
uint32_t,
const LV2_Feature* const*)
{
MemoryBlock block;
processor->getStateInformation (block);
const auto text = block.toBase64Encoding();
storeFn (handle,
mJucePluginLV2UriState,
text.toRawUTF8(),
text.getNumBytesAsUTF8() + 1,
mLV2_ATOM__String,
LV2_STATE_IS_POD | LV2_STATE_IS_PORTABLE);
return LV2_STATE_SUCCESS;
}
LV2_State_Status retrieve (LV2_State_Retrieve_Function retrieveFn,
LV2_State_Handle handle,
uint32_t,
const LV2_Feature* const*)
{
size_t size = 0;
uint32_t type = 0;
uint32_t dataFlags = 0;
// Try retrieving a port index (if this is a 'program' preset).
const auto* programData = retrieveFn (handle, mJucePluginLV2UriProgram, &size, &type, &dataFlags);
if (programData != nullptr && type == mLV2_ATOM__Int && size == sizeof (int32_t))
{
const auto programIndex = readUnaligned<int32_t> (programData);
processor->setCurrentProgram (programIndex);
return LV2_STATE_SUCCESS;
}
// This doesn't seem to be a 'program' preset, try setting the full state from a string instead.
const auto* data = retrieveFn (handle, mJucePluginLV2UriState, &size, &type, &dataFlags);
if (data == nullptr)
return LV2_STATE_ERR_NO_PROPERTY;
if (type != mLV2_ATOM__String)
return LV2_STATE_ERR_BAD_TYPE;
String text (static_cast<const char*> (data), (size_t) size);
MemoryBlock block;
block.fromBase64Encoding (text);
processor->setStateInformation (block.getData(), (int) block.getSize());
return LV2_STATE_SUCCESS;
}
std::unique_ptr<AudioProcessorEditor> createEditor()
{
return std::unique_ptr<AudioProcessorEditor> (processor->createEditorIfNeeded());
}
void editorBeingDeleted (AudioProcessorEditor* editor)
{
processor->editorBeingDeleted (editor);
}
static std::unique_ptr<AudioProcessor> createProcessorInstance()
{
auto result = createPluginFilterOfType (AudioProcessor::wrapperType_LV2);
#if defined (JucePlugin_PreferredChannelConfigurations)
constexpr short channelConfigurations[][2] { JucePlugin_PreferredChannelConfigurations };
static_assert (numElementsInArray (channelConfigurations) > 0,
"JucePlugin_PreferredChannelConfigurations must contain at least one entry");
static_assert (channelConfigurations[0][0] > 0 || channelConfigurations[0][1] > 0,
"JucePlugin_PreferredChannelConfigurations must have at least one input or output channel");
result->setPlayConfigDetails (channelConfigurations[0][0], channelConfigurations[0][1], 44100.0, 1024);
const auto desiredChannels = std::make_tuple (channelConfigurations[0][0], channelConfigurations[0][1]);
const auto actualChannels = std::make_tuple (result->getTotalNumInputChannels(), result->getTotalNumOutputChannels());
if (desiredChannels != actualChannels)
Logger::outputDebugString ("Failed to apply requested channel configuration!");
#else
result->enableAllBuses();
#endif
return result;
}
private:
void audioProcessorParameterChanged (AudioProcessor*, int, float) override {}
void audioProcessorChanged (AudioProcessor*, const ChangeDetails& details) override
{
// Only check for non-parameter state here because:
// - Latency is automatically written every block.
// - There's no way for an LV2 plugin to report an internal program change.
// - Parameter info is hard-coded in the plugin's turtle description.
if (details.nonParameterStateChanged)
shouldSendStateChange = true;
}
void prepare (double sampleRate, int maxBlockSize)
{
jassert (processor != nullptr);
processor->setRateAndBufferSizeDetails (sampleRate, maxBlockSize);
processor->prepareToPlay (sampleRate, maxBlockSize);
const auto numChannels = jmax (processor->getTotalNumInputChannels(),
processor->getTotalNumOutputChannels());
midi.ensureSize (8192);
audio.setSize (numChannels, maxBlockSize);
audio.clear();
}
LV2_URID map (StringRef uri) const { return mapFeature.map (mapFeature.handle, uri); }
ScopedJuceInitialiser_GUI scopedJuceInitialiser;
#if JUCE_LINUX || JUCE_BSD
SharedResourcePointer<detail::MessageThread> messageThread;
#endif
std::unique_ptr<AudioProcessor> processor = createProcessorInstance();
const LV2_URID_Map mapFeature;
ParameterStorage parameters { *processor, mapFeature };
Ports ports { mapFeature,
processor->getTotalNumInputChannels(),
processor->getTotalNumOutputChannels() };
lv2_shared::PatchSetHelper patchSetHelper { mapFeature, JucePlugin_LV2URI };
PlayHead playHead;
MidiBuffer midi;
AudioBuffer<float> audio;
std::atomic<bool> shouldSendStateChange { false };
#define X(str) const LV2_URID m##str = map (str);
X (JucePluginLV2UriProgram)
X (JucePluginLV2UriState)
X (LV2_ATOM__Int)
X (LV2_ATOM__String)
X (LV2_BUF_SIZE__maxBlockLength)
X (LV2_BUF_SIZE__sequenceSize)
X (LV2_MIDI__MidiEvent)
X (LV2_PATCH__Set)
X (LV2_STATE__StateChanged)
#undef X
JUCE_LEAK_DETECTOR (LV2PluginInstance)
};
//==============================================================================
struct RecallFeature
{
int (*doRecall) (const char*) = [] (const char* libraryPath) -> int
{
const ScopedJuceInitialiser_GUI scope;
const auto processor = LV2PluginInstance::createProcessorInstance();
const String pathString { CharPointer_UTF8 { libraryPath } };
const auto absolutePath = File::isAbsolutePath (pathString) ? File (pathString)
: File::getCurrentWorkingDirectory().getChildFile (pathString);
const auto writers = { writeManifestTtl, writeDspTtl, writeUiTtl };
const auto wroteSuccessfully = [&processor, &absolutePath] (auto* fn)
{
const auto result = fn (*processor, absolutePath);
if (! result.wasOk())
std::cerr << result.getErrorMessage() << '\n';
return result.wasOk();
};
return std::all_of (writers.begin(), writers.end(), wroteSuccessfully) ? 0 : 1;
};
private:
static String getPresetUri (int index)
{
return JucePlugin_LV2URI + String (uriSeparator) + "preset" + String (index + 1);
}
static FileOutputStream openStream (const File& libraryPath, StringRef name)
{
return FileOutputStream { libraryPath.getSiblingFile (name + ".ttl") };
}
static Result prepareStream (FileOutputStream& stream)
{
if (const auto result = stream.getStatus(); ! result)
return result;
stream.setPosition (0);
stream.truncate();
return Result::ok();
}
static Result writeManifestTtl (AudioProcessor& proc, const File& libraryPath)
{
auto os = openStream (libraryPath, "manifest");
if (const auto result = prepareStream (os); ! result)
return result;
os << "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
"@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n"
"@prefix state: <http://lv2plug.in/ns/ext/state#> .\n"
"@prefix ui: <http://lv2plug.in/ns/extensions/ui#> .\n"
"@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n"
"\n"
"<" JucePlugin_LV2URI ">\n"
"\ta lv2:Plugin ;\n"
"\tlv2:binary <" << URL::addEscapeChars (libraryPath.getFileName(), false) << "> ;\n"
"\trdfs:seeAlso <dsp.ttl> .\n";
if (proc.hasEditor())
{
#if JUCE_MAC
#define JUCE_LV2_UI_KIND "CocoaUI"
#elif JUCE_WINDOWS
#define JUCE_LV2_UI_KIND "WindowsUI"
#elif JUCE_LINUX || JUCE_BSD
#define JUCE_LV2_UI_KIND "X11UI"
#else
#error "LV2 UI is unsupported on this platform"
#endif
os << "\n"
"<" << JucePluginLV2UriUi << ">\n"
"\ta ui:" JUCE_LV2_UI_KIND " ;\n"
"\tlv2:binary <" << URL::addEscapeChars (libraryPath.getFileName(), false) << "> ;\n"
"\trdfs:seeAlso <ui.ttl> .\n"
"\n";
}
for (auto i = 0, end = proc.getNumPrograms(); i < end; ++i)
{
os << "<" << getPresetUri (i) << ">\n"
"\ta pset:Preset ;\n"
"\tlv2:appliesTo <" JucePlugin_LV2URI "> ;\n"
"\trdfs:label \"" << proc.getProgramName (i) << "\" ;\n"
"\tstate:state [ <" << JucePluginLV2UriProgram << "> \"" << i << "\"^^xsd:int ; ] .\n"
"\n";
}
return Result::ok();
}
static std::vector<const AudioProcessorParameterGroup*> findAllSubgroupsDepthFirst (const AudioProcessorParameterGroup& group,
std::vector<const AudioProcessorParameterGroup*> foundSoFar = {})
{
foundSoFar.push_back (&group);
for (auto* node : group)
{
if (auto* subgroup = node->getGroup())
foundSoFar = findAllSubgroupsDepthFirst (*subgroup, std::move (foundSoFar));
}
return foundSoFar;
}
using GroupSymbolMap = std::map<const AudioProcessorParameterGroup*, String>;
static String getFlattenedGroupSymbol (const AudioProcessorParameterGroup& group, String symbol = "")
{
if (auto* parent = group.getParent())
return getFlattenedGroupSymbol (*parent, group.getID() + (symbol.isEmpty() ? "" : group.getSeparator() + symbol));
return symbol;
}
static String getSymbolForGroup (const AudioProcessorParameterGroup& group)
{
const String allowedCharacters ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789");
const auto base = getFlattenedGroupSymbol (group);
if (base.isEmpty())
return {};
String copy;
for (const auto character : base)
copy << String::charToString (allowedCharacters.containsChar (character) ? character : (juce_wchar) '_');
return "paramgroup_" + copy;
}
static GroupSymbolMap getGroupsAndSymbols (const std::vector<const AudioProcessorParameterGroup*>& groups)
{
std::set<String> symbols;
GroupSymbolMap result;
for (const auto& group : groups)
{
const auto symbol = [&]
{
const auto idealSymbol = getSymbolForGroup (*group);
if (symbols.find (idealSymbol) == symbols.cend())
return idealSymbol;
for (auto i = 2; i < std::numeric_limits<int>::max(); ++i)
{
const auto toTest = idealSymbol + "_" + String (i);
if (symbols.find (toTest) == symbols.cend())
return toTest;
}
jassertfalse;
return String();
}();
symbols.insert (symbol);
result.emplace (group, symbol);
}
return result;
}
template <typename Fn>
static void visitAllParameters (const GroupSymbolMap& groups, Fn&& fn)
{
for (const auto& group : groups)
for (const auto* node : *group.first)
if (auto* param = node->getParameter())
fn (group.second, *param);
}
static Result writeDspTtl (AudioProcessor& proc, const File& libraryPath)
{
auto os = openStream (libraryPath, "dsp");
if (const auto result = prepareStream (os); ! result)
return result;
os << "@prefix atom: <http://lv2plug.in/ns/ext/atom#> .\n"