/
clap-juce-wrapper.cpp
1102 lines (960 loc) · 37.3 KB
/
clap-juce-wrapper.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
/*
* BaconPaul's running todo
*
* - We always say we are an instrument....
* - midi out (try stochas perhaps?)
* - why does dexed not work?
* - Finish populating the desc
* - Cleanup and comment of course (including the CMake) including what's skipped
*/
#include <memory>
#include <unordered_map>
#include <unordered_set>
#define JUCE_GUI_BASICS_INCLUDE_XHEADERS 1
#include <juce_audio_processors/juce_audio_processors.h>
#include <juce_gui_basics/juce_gui_basics.h>
#include <juce_audio_processors/format_types/juce_LegacyAudioParameter.cpp>
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE("-Wunused-parameter", "-Wsign-conversion")
JUCE_BEGIN_IGNORE_WARNINGS_MSVC(4100 4127)
// Sigh - X11.h eventually does a #define None 0L which doesn't work
// with an enum in clap land being called None, so just undef it
// post the JUCE installs
#ifdef None
#undef None
#endif
#include <clap/helpers/checking-level.hh>
#include <clap/helpers/host-proxy.hh>
#include <clap/helpers/host-proxy.hxx>
#include <clap/helpers/plugin.hh>
#include <clap/helpers/plugin.hxx>
JUCE_END_IGNORE_WARNINGS_MSVC
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
#include <clap-juce-extensions/clap-juce-extensions.h>
#if JUCE_LINUX
#include <juce_audio_plugin_client/utility/juce_LinuxMessageThread.h>
#endif
#define FIXME(x) \
{ \
static bool onetime_ = false; \
if (!onetime_) \
{ \
std::ostringstream oss; \
oss << "FIXME: " << x << " @" << __LINE__; \
DBG(oss.str()); \
} \
jassert(onetime_); \
onetime_ = true; \
}
/*
* This is a utility lock free queue based on the JUCE abstract fifo
*/
template <typename T, int qSize = 4096> class PushPopQ
{
public:
PushPopQ() : af(qSize) {}
bool push(const T &ad)
{
auto ret = false;
int start1, size1, start2, size2;
af.prepareToWrite(1, start1, size1, start2, size2);
if (size1 > 0)
{
dq[start1] = ad;
ret = true;
}
af.finishedWrite(size1 + size2);
return ret;
}
bool pop(T &ad)
{
bool ret = false;
int start1, size1, start2, size2;
af.prepareToRead(1, start1, size1, start2, size2);
if (size1 > 0)
{
ad = dq[start1];
ret = true;
}
af.finishedRead(size1 + size2);
return ret;
}
juce::AbstractFifo af;
T dq[qSize];
};
/*
* These functions are the JUCE VST2/3 NSView attachment functions. We compile them into
* our clap dll by, on macos, also linking clap_juce_mac.mm
*/
namespace juce
{
extern JUCE_API void initialiseMacVST();
extern JUCE_API void *attachComponentToWindowRefVST(Component *, void *parentWindowOrView,
bool isNSView);
} // namespace juce
JUCE_BEGIN_IGNORE_WARNINGS_MSVC(4996) // allow strncpy
/*
* The ClapJuceWrapper is a class which immplements a collection
* of CLAP and JUCE APIs
*/
class ClapJuceWrapper : public clap::helpers::Plugin<clap::helpers::MisbehaviourHandler::Terminate,
clap::helpers::CheckingLevel::Minimal>,
public juce::AudioProcessorListener,
public juce::AudioPlayHead,
public juce::AudioProcessorParameter::Listener,
public juce::ComponentListener
{
public:
// this needs to be the very last thing to get deleted!
juce::ScopedJuceInitialiser_GUI libraryInitializer;
static clap_plugin_descriptor desc;
std::unique_ptr<juce::AudioProcessor> processor;
clap_juce_extensions::clap_properties *processorAsClapProperties{nullptr};
clap_juce_extensions::clap_extensions *processorAsClapExtensions{nullptr};
ClapJuceWrapper(const clap_host *host, juce::AudioProcessor *p)
: clap::helpers::Plugin<clap::helpers::MisbehaviourHandler::Terminate,
clap::helpers::CheckingLevel::Minimal>(&desc, host),
processor(p)
{
processor->setRateAndBufferSizeDetails(0, 0);
processor->setPlayHead(this);
processor->addListener(this);
processorAsClapProperties = dynamic_cast<clap_juce_extensions::clap_properties *>(p);
processorAsClapExtensions = dynamic_cast<clap_juce_extensions::clap_extensions *>(p);
const bool forceLegacyParamIDs = false;
juceParameters.update(*processor, forceLegacyParamIDs);
for (auto *juceParam :
#if JUCE_VERSION >= 0x060103
juceParameters
#else
juceParameters.params
#endif
)
{
uint32_t clap_id = generateClapIDForJuceParam(juceParam);
allClapIDs.insert(clap_id);
paramPtrByClapID[clap_id] = juceParam;
clapIDByParamPtr[juceParam] = clap_id;
}
}
~ClapJuceWrapper() override
{
processor->editorBeingDeleted(editor.get());
#if JUCE_LINUX
if (_host.canUseTimerSupport())
{
_host.timerSupportUnregister(idleTimer);
}
#endif
}
bool init() noexcept override
{
#if JUCE_LINUX
if (_host.canUseTimerSupport())
{
_host.timerSupportRegister(1000 / 50, &idleTimer);
}
#endif
return true;
}
public:
bool implementsTimerSupport() const noexcept override { return true; }
void onTimer(clap_id timerId) noexcept override
{
juce::ignoreUnused(timerId);
#if LINUX
juce::ScopedJuceInitialiser_GUI libraryInitialiser;
const juce::MessageManagerLock mmLock;
while (juce::dispatchNextMessageOnSystemQueue(true))
{
}
#endif
}
clap_id idleTimer{0};
uint32_t generateClapIDForJuceParam(juce::AudioProcessorParameter *param) const
{
auto juceParamID = juce::LegacyAudioParameter::getParamID(param, false);
auto clap_id = static_cast<uint32_t>(juceParamID.hashCode());
return clap_id;
}
#if JUCE_VERSION >= 0x060008
void audioProcessorChanged(juce::AudioProcessor *proc, const ChangeDetails &details) override
{
juce::ignoreUnused(proc);
if (details.latencyChanged)
{
runOnMainThread([this] {
if (isBeingDestroyed())
return;
_host.latencyChanged();
});
}
if (details.programChanged)
{
// At the moment, CLAP doesn't have a sense of programs (to my knowledge).
// (I think) what makes most sense is to tell the host to update the parameters
// as though a preset has been loaded.
runOnMainThread([this] {
if (isBeingDestroyed())
return;
_host.paramsRescan(CLAP_PARAM_RESCAN_VALUES);
});
}
#if JUCE_VERSION >= 0x060102
if (details.nonParameterStateChanged)
{
runOnMainThread([this] {
if (isBeingDestroyed())
return;
_host.stateMarkDirty();
});
}
#endif
if (details.parameterInfoChanged)
{
// JUCE documentations states that, `parameterInfoChanged` means
// "Indicates that some attributes of the AudioProcessor's parameters have changed."
// For now, I'm going to assume this means the parameter's name or value->text
// conversion has changed, and tell the clap host to rescan those.
//
// We could do CLAP_PARAM_RESCAN_ALL, but then the plugin would have to be deactivated.
runOnMainThread([this] {
if (isBeingDestroyed())
return;
_host.paramsRescan(CLAP_PARAM_RESCAN_VALUES | CLAP_PARAM_RESCAN_TEXT);
});
}
}
#else
void audioProcessorChanged(juce::AudioProcessor *proc) override {
/*
* Before 6.0.8 it was unclear what changed. For now make the approximating decision to just
* rescan values and text.
*/
runOnMainThread([this] {
if (isBeingDestroyed())
return;
_host.paramsRescan(CLAP_PARAM_RESCAN_VALUES | CLAP_PARAM_RESCAN_TEXT);
});
}
#endif
clap_id clapIdFromParameterIndex(int index)
{
auto pbi = juceParameters.getParamForIndex(index);
auto pf = clapIDByParamPtr.find(pbi);
if (pf != clapIDByParamPtr.end())
return pf->second;
auto id = generateClapIDForJuceParam(pbi); // a lookup obviously
return id;
}
void audioProcessorParameterChanged(juce::AudioProcessor *, int index, float newValue) override
{
auto id = clapIdFromParameterIndex(index);
uiParamChangeQ.push({CLAP_EVENT_PARAM_VALUE, 0, id, newValue});
}
void audioProcessorParameterChangeGestureBegin(juce::AudioProcessor *, int index) override
{
auto id = clapIdFromParameterIndex(index);
auto p = paramPtrByClapID[id];
uiParamChangeQ.push({CLAP_EVENT_PARAM_GESTURE_BEGIN, 0, id, p->getValue()});
}
void audioProcessorParameterChangeGestureEnd(juce::AudioProcessor *, int index) override
{
auto id = clapIdFromParameterIndex(index);
auto p = paramPtrByClapID[id];
uiParamChangeQ.push({CLAP_EVENT_PARAM_GESTURE_END, 0, id, p->getValue()});
}
/*
* According to the JUCE docs this is *only* called on the processing thread
*/
bool getCurrentPosition(juce::AudioPlayHead::CurrentPositionInfo &info) override
{
if (hasTransportInfo && transportInfo)
{
auto flags = transportInfo->flags;
if (flags & CLAP_TRANSPORT_HAS_TEMPO)
info.bpm = transportInfo->tempo;
if (flags & CLAP_TRANSPORT_HAS_TIME_SIGNATURE)
{
info.timeSigNumerator = transportInfo->tsig_num;
info.timeSigDenominator = transportInfo->tsig_denom;
}
if (flags & CLAP_TRANSPORT_HAS_BEATS_TIMELINE)
{
info.ppqPosition = 1.0 * transportInfo->song_pos_beats / CLAP_BEATTIME_FACTOR;
info.ppqPositionOfLastBarStart =
1.0 * transportInfo->bar_start / CLAP_BEATTIME_FACTOR;
}
if (flags & CLAP_TRANSPORT_HAS_SECONDS_TIMELINE)
{
info.timeInSeconds = 1.0 * transportInfo->song_pos_seconds / CLAP_SECTIME_FACTOR;
info.timeInSamples = (int64_t)(info.timeInSeconds * sampleRate());
}
info.isPlaying = flags & CLAP_TRANSPORT_IS_PLAYING;
info.isRecording = flags & CLAP_TRANSPORT_IS_RECORDING;
info.isLooping = flags & CLAP_TRANSPORT_IS_LOOP_ACTIVE;
}
return hasTransportInfo;
}
void parameterValueChanged(int, float newValue) override
{
juce::ignoreUnused(newValue);
FIXME("parameter value changed");
// this can only come from the bypass parameter
}
void parameterGestureChanged(int, bool) override { FIXME("parameter gesture changed"); }
bool activate(double sampleRate, uint32_t minFrameCount,
uint32_t maxFrameCount) noexcept override
{
juce::ignoreUnused(minFrameCount);
processor->setRateAndBufferSizeDetails(sampleRate, maxFrameCount);
processor->prepareToPlay(sampleRate, (int)maxFrameCount);
midiBuffer.ensureSize(2048);
midiBuffer.clear();
return true;
}
/* CLAP API */
bool implementsAudioPorts() const noexcept override { return true; }
uint32_t audioPortsCount(bool isInput) const noexcept override
{
return (uint32_t)processor->getBusCount(isInput);
}
bool audioPortsInfo(uint32_t index, bool isInput,
clap_audio_port_info *info) const noexcept override
{
// For now hardcode to stereo out. Fix this obviously.
auto bus = processor->getBus(isInput, (int)index);
auto clob = bus->getDefaultLayout();
// For now we only support stereo channels
jassert(clob.size() == 1 || clob.size() == 2);
jassert(clob.size() == 1 || (clob.getTypeOfChannel(0) == juce::AudioChannelSet::left &&
clob.getTypeOfChannel(1) == juce::AudioChannelSet::right));
// if (isInput || index != 0) return false;
info->id = (isInput ? 1 << 15 : 1) + index;
strncpy(info->name, bus->getName().toRawUTF8(), sizeof(info->name));
bool couldBeMain = true;
if (isInput && processorAsClapExtensions)
couldBeMain = processorAsClapExtensions->isInputMain(index);
if (index == 0 && couldBeMain)
{
info->flags = CLAP_AUDIO_PORT_IS_MAIN;
}
else
{
info->flags = 0;
}
info->in_place_pair = info->id;
info->channel_count = (uint32_t)clob.size();
if (clob.size() == 1)
info->port_type = CLAP_PORT_MONO;
else
info->port_type = CLAP_PORT_STEREO;
auto requested = processor->getBusesLayout();
if (clob.size() == 1)
requested.getChannelSet(isInput, (int)index) = juce::AudioChannelSet::mono();
if (clob.size() == 2)
requested.getChannelSet(isInput, (int)index) = juce::AudioChannelSet::stereo();
processor->setBusesLayoutWithoutEnabling(requested);
DBG("audioPortsInfo " << (isInput ? "INPUT " : "OUTPUT ") << (int)index << " '"
<< bus->getName()
<< "' isMain=" << ((index == 0 && couldBeMain) ? "T" : "F")
<< " sz=" << clob.size() << " enabled=" << (int)(bus->isEnabled()));
return true;
}
uint32_t audioPortsConfigCount() const noexcept override
{
DBG("audioPortsConfigCount CALLED - returning 0");
return 0;
}
bool audioPortsGetConfig(uint32_t /*index*/,
clap_audio_ports_config * /*config*/) const noexcept override
{
return false;
}
bool audioPortsSetConfig(clap_id /*configId*/) noexcept override { return false; }
bool implementsNotePorts() const noexcept override { return true; }
uint32_t notePortsCount(bool is_input) const noexcept override
{
if (is_input)
{
if (processor->acceptsMidi())
return 1;
}
else
{
if (processor->producesMidi())
return 1;
}
return 0;
}
bool notePortsInfo(uint32_t index, bool is_input,
clap_note_port_info *info) const noexcept override
{
juce::ignoreUnused(index);
if (is_input)
{
info->id = 1 << 5U;
info->supported_dialects = CLAP_NOTE_DIALECT_MIDI;
if (processor->supportsMPE())
info->supported_dialects |= CLAP_NOTE_DIALECT_MIDI_MPE;
info->preferred_dialect = CLAP_NOTE_DIALECT_MIDI;
if (processorAsClapExtensions)
{
if (processorAsClapExtensions->supportsNoteDialectClap(true))
{
info->supported_dialects |= CLAP_NOTE_DIALECT_CLAP;
}
if (processorAsClapExtensions->prefersNoteDialectClap(true))
{
info->preferred_dialect = CLAP_NOTE_DIALECT_CLAP;
}
}
strncpy(info->name, "JUCE Note Input", CLAP_NAME_SIZE);
}
else
{
info->id = 1 << 2U;
info->supported_dialects = CLAP_NOTE_DIALECT_MIDI;
if (processor->supportsMPE())
info->supported_dialects |= CLAP_NOTE_DIALECT_MIDI_MPE;
info->preferred_dialect = CLAP_NOTE_DIALECT_MIDI;
if (processorAsClapExtensions)
{
if (processorAsClapExtensions->supportsNoteDialectClap(false))
{
info->supported_dialects |= CLAP_NOTE_DIALECT_CLAP;
}
if (processorAsClapExtensions->prefersNoteDialectClap(false))
{
info->preferred_dialect = CLAP_NOTE_DIALECT_CLAP;
}
}
strncpy(info->name, "JUCE Note Output", CLAP_NAME_SIZE);
}
return true;
}
bool implementsVoiceInfo() const noexcept override
{
if (processorAsClapExtensions)
return processorAsClapExtensions->supportsVoiceInfo();
return false;
}
bool voiceInfoGet(clap_voice_info *info) noexcept override
{
if (processorAsClapExtensions)
return processorAsClapExtensions->voiceInfoGet(info);
return Plugin::voiceInfoGet(info);
}
public:
bool implementsParams() const noexcept override { return true; }
bool isValidParamId(clap_id paramId) const noexcept override
{
return allClapIDs.find(paramId) != allClapIDs.end();
}
uint32_t paramsCount() const noexcept override { return (uint32_t)allClapIDs.size(); }
bool paramsInfo(uint32_t paramIndex, clap_param_info *info) const noexcept override
{
auto pbi = juceParameters.getParamForIndex((int)paramIndex);
auto *parameterGroup = processor->getParameterTree().getGroupsForParameter(pbi).getLast();
juce::String group = "";
while (parameterGroup && parameterGroup->getParent() &&
parameterGroup->getParent()->getName().isNotEmpty())
{
group = parameterGroup->getName() + "/" + group;
parameterGroup = parameterGroup->getParent();
}
if (group.isNotEmpty())
group = "/" + group;
// Fixme - using parameter groups here would be lovely but until then
info->id = generateClapIDForJuceParam(pbi);
strncpy(info->name, (pbi->getName(CLAP_NAME_SIZE)).toRawUTF8(), CLAP_NAME_SIZE);
strncpy(info->module, group.toRawUTF8(), CLAP_NAME_SIZE);
info->min_value = 0; // FIXME
info->max_value = 1;
info->default_value = pbi->getDefaultValue();
info->cookie = pbi;
info->flags = 0;
if (pbi->isAutomatable())
info->flags = info->flags | CLAP_PARAM_IS_AUTOMATABLE;
if (pbi->isBoolean() || pbi->isDiscrete())
{
info->flags = info->flags | CLAP_PARAM_IS_STEPPED;
}
auto cpe = dynamic_cast<clap_juce_extensions::clap_param_extensions *>(pbi);
if (cpe)
{
if (cpe->supportsMonophonicModulation())
{
info->flags = info->flags | CLAP_PARAM_IS_MODULATABLE;
}
if (cpe->supportsPolyphonicModulation())
{
info->flags =
info->flags | CLAP_PARAM_IS_MODULATABLE |
CLAP_PARAM_IS_MODULATABLE_PER_CHANNEL | CLAP_PARAM_IS_MODULATABLE_PER_KEY |
CLAP_PARAM_IS_AUTOMATABLE_PER_NOTE_ID | CLAP_PARAM_IS_AUTOMATABLE_PER_PORT;
}
}
return true;
}
bool paramsValue(clap_id paramId, double *value) noexcept override
{
auto pbi = paramPtrByClapID[paramId];
*value = pbi->getValue();
return true;
}
bool paramsValueToText(clap_id paramId, double value, char *display,
uint32_t size) noexcept override
{
auto pbi = paramPtrByClapID[paramId];
auto res = pbi->getText(value, size);
strncpy(display, res.toStdString().c_str(), size);
return true;
}
bool paramsTextToValue(clap_id paramId, const char *display, double *value) noexcept override
{
auto pbi = paramPtrByClapID[paramId];
*value = pbi->getValueForText(display);
return true;
}
void paramSetValueAndNotifyIfChanged(juce::AudioProcessorParameter ¶m, float newValue)
{
if (param.getValue() == newValue)
return;
param.setValueNotifyingHost(newValue);
}
bool implementsLatency() const noexcept override { return true; }
uint32_t latencyGet() const noexcept override
{
return (uint32_t)processor->getLatencySamples();
}
bool implementsTail() const noexcept override { return true; }
uint32_t tailGet(const clap_plugin_t *) const noexcept override
{
return uint32_t(
juce::roundToIntAccurate((double)sampleRate() * processor->getTailLengthSeconds()));
}
juce::MidiBuffer midiBuffer;
clap_process_status process(const clap_process *process) noexcept override
{
// Since the playhead is *only* good inside juce audio processor process,
// we can just keep this little transient pointer here
if (process->transport)
{
hasTransportInfo = true;
transportInfo = process->transport;
}
else
{
hasTransportInfo = false;
transportInfo = nullptr;
}
if (processorAsClapProperties)
processorAsClapProperties->clap_transport = process->transport;
auto pc = ParamChange();
auto ov = process->out_events;
while (uiParamChangeQ.pop(pc))
{
if (pc.type == CLAP_EVENT_PARAM_VALUE)
{
auto evt = clap_event_param_value();
evt.header.size = sizeof(clap_event_param_value);
evt.header.type = (uint16_t)CLAP_EVENT_PARAM_VALUE;
evt.header.time = 0; // for now
evt.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
evt.header.flags = pc.flag;
evt.param_id = pc.id;
evt.value = pc.newval;
ov->try_push(ov, reinterpret_cast<const clap_event_header *>(&evt));
}
if (pc.type == CLAP_EVENT_PARAM_GESTURE_END ||
pc.type == CLAP_EVENT_PARAM_GESTURE_BEGIN)
{
auto evt = clap_event_param_gesture();
evt.header.size = sizeof(clap_event_param_gesture);
evt.header.type = (uint16_t)pc.type;
evt.header.time = 0; // for now
evt.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
evt.header.flags = pc.flag;
evt.param_id = pc.id;
ov->try_push(ov, reinterpret_cast<const clap_event_header *>(&evt));
}
}
if (processorAsClapExtensions && processorAsClapExtensions->supportsDirectProcess())
return processorAsClapExtensions->clap_direct_process(process);
auto ev = process->in_events;
auto sz = ev->size(ev);
if (sz != 0)
{
for (uint32_t i = 0; i < sz; ++i)
{
auto evt = ev->get(ev, i);
if (evt->space_id != CLAP_CORE_EVENT_SPACE_ID)
continue;
switch (evt->type)
{
case CLAP_EVENT_NOTE_ON:
{
auto nevt = reinterpret_cast<const clap_event_note *>(evt);
midiBuffer.addEvent(juce::MidiMessage::noteOn(nevt->channel + 1, nevt->key,
(float)nevt->velocity),
(int)nevt->header.time);
}
break;
case CLAP_EVENT_NOTE_OFF:
{
auto nevt = reinterpret_cast<const clap_event_note *>(evt);
midiBuffer.addEvent(juce::MidiMessage::noteOff(nevt->channel + 1, nevt->key,
(float)nevt->velocity),
(int)nevt->header.time);
}
break;
case CLAP_EVENT_MIDI:
{
auto mevt = reinterpret_cast<const clap_event_midi *>(evt);
midiBuffer.addEvent(juce::MidiMessage(mevt->data[0], mevt->data[1],
mevt->data[2], mevt->header.time),
(int)mevt->header.time);
}
break;
case CLAP_EVENT_TRANSPORT:
{
// handle this case
}
break;
case CLAP_EVENT_PARAM_VALUE:
{
auto pevt = reinterpret_cast<const clap_event_param_value *>(evt);
auto id = pevt->param_id;
auto nf = pevt->value;
jassert(pevt->cookie == paramPtrByClapID[id]);
auto jp = static_cast<juce::AudioProcessorParameter *>(pevt->cookie);
paramSetValueAndNotifyIfChanged(*jp, nf);
}
break;
case CLAP_EVENT_PARAM_MOD:
{
}
break;
case CLAP_EVENT_NOTE_END:
{
// Why do you send me this, Alex?
}
break;
default:
{
DBG("Unknown message type " << (int)evt->type);
// In theory I should never get this.
// jassertfalse
}
break;
}
}
}
// We process in place so
static constexpr uint32_t maxBuses = 128;
std::array<float *, maxBuses> busses{};
busses.fill(nullptr);
/*DBG("IO Configuration: I=" << (int)process->audio_inputs_count << " O="
<< (int)process->audio_outputs_count << " MX=" << (int)mx);
DBG("Plugin Configuration: IC=" << processor->getTotalNumInputChannels()
<< " OC=" << processor->getTotalNumOutputChannels());
*/
/*
* OK so here is what JUCE expects in its audio buffer. It *always* uses input as output
* buffer so we need to create a buffer where each channel is the channel of the associated
* output pointer (fine) and then the inputs need to either check they are the same or copy.
*/
/*
* So first lets load up with our outputs
*/
uint32_t ochans = 0;
for (uint32_t idx = 0; idx < process->audio_outputs_count && ochans < maxBuses; ++idx)
{
for (uint32_t ch = 0; ch < process->audio_outputs[idx].channel_count; ++ch)
{
busses[ochans] = process->audio_outputs[idx].data32[ch];
ochans++;
}
}
uint32_t ichans = 0;
for (uint32_t idx = 0; idx < process->audio_inputs_count && ichans < maxBuses; ++idx)
{
for (uint32_t ch = 0; ch < process->audio_inputs[idx].channel_count; ++ch)
{
auto *ic = process->audio_inputs[idx].data32[ch];
if (ichans < ochans)
{
if (ic == busses[ichans])
{
// The buffers overlap - no need to do anything
}
else
{
juce::FloatVectorOperations::copy(busses[ichans], ic,
(int)process->frames_count);
}
}
else
{
busses[ichans] = ic;
}
ichans++;
}
}
auto totalChans = std::max(ichans, ochans);
juce::AudioBuffer<float> buf(busses.data(), (int)totalChans, (int)process->frames_count);
FIXME("Handle bypass and deactivated states");
processor->processBlock(buf, midiBuffer);
if (processor->producesMidi())
{
for (auto meta : midiBuffer)
{
auto msg = meta.getMessage();
if (msg.getRawDataSize() == 3)
{
auto evt = clap_event_midi();
evt.header.size = sizeof(clap_event_midi);
evt.header.type = (uint16_t)CLAP_EVENT_MIDI;
evt.header.time = meta.samplePosition; // for now
evt.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
evt.header.flags = 0;
evt.port_index = 0;
memcpy(&evt.data, msg.getRawData(), 3 * sizeof(uint8_t));
ov->try_push(ov, reinterpret_cast<const clap_event_header *>(&evt));
}
}
}
if (!midiBuffer.isEmpty())
midiBuffer.clear();
return CLAP_PROCESS_CONTINUE;
}
void componentMovedOrResized(juce::Component &component, bool wasMoved,
bool wasResized) override
{
juce::ignoreUnused(wasMoved);
if (wasResized)
_host.guiRequestResize((uint32_t)component.getWidth(), (uint32_t)component.getHeight());
}
std::unique_ptr<juce::AudioProcessorEditor> editor;
bool implementsGui() const noexcept override { return processor->hasEditor(); }
bool guiCanResize() const noexcept override
{
if (editor)
return editor->isResizable();
return true;
}
bool guiAdjustSize(uint32_t *w, uint32_t *h) noexcept override
{
if (!editor)
return false;
if (!editor->isResizable())
return false;
editor->setSize(*w, *h);
return true;
}
bool guiIsApiSupported(const char *api, bool isFloating) noexcept override
{
if (isFloating)
return false;
if (strcmp(api, CLAP_WINDOW_API_WIN32) == 0 || strcmp(api, CLAP_WINDOW_API_COCOA) == 0 ||
strcmp(api, CLAP_WINDOW_API_X11) == 0)
return true;
return false;
}
bool guiCreate(const char *api, bool isFloating) noexcept override
{
juce::ignoreUnused(api);
// Should never happen
if (isFloating)
return false;
const juce::MessageManagerLock mmLock;
editor.reset(processor->createEditorIfNeeded());
editor->addComponentListener(this);
return editor != nullptr;
}
void guiDestroy() noexcept override
{
processor->editorBeingDeleted(editor.get());
editor.reset(nullptr);
}
bool guiSetParent(const clap_window *window) noexcept override
{
#if JUCE_MAC
return guiCocoaAttach(window->cocoa);
#elif JUCE_LINUX
return guiX11Attach(NULL, window->x11);
#elif JUCE_WINDOWS
return guiWin32Attach(window->win32);
#else
return false;
#endif
}
bool guiGetSize(uint32_t *width, uint32_t *height) noexcept override
{
const juce::MessageManagerLock mmLock;
if (editor)
{
auto b = editor->getBounds();
*width = (uint32_t)b.getWidth();
*height = (uint32_t)b.getHeight();
return true;
}
else
{
*width = 1000;
*height = 800;
}
return false;
}
protected:
juce::CriticalSection stateInformationLock;
juce::MemoryBlock chunkMemory;
public:
bool implementsState() const noexcept override { return true; }
bool stateSave(const clap_ostream *stream) noexcept override
{
if (processor == nullptr)
return false;
juce::ScopedLock lock(stateInformationLock);
chunkMemory.reset();
processor->getStateInformation(chunkMemory);
auto written = stream->write(stream, chunkMemory.getData(), chunkMemory.getSize());
return written == (int64_t)chunkMemory.getSize();
}
bool stateLoad(const clap_istream *stream) noexcept override
{
if (processor == nullptr)
return false;
juce::ScopedLock lock(stateInformationLock);
chunkMemory.reset();
// There must be a better way
char block[256];
int64_t rd;
while ((rd = stream->read(stream, block, 256)) > 0)
chunkMemory.append(block, (size_t)rd);
processor->setStateInformation(chunkMemory.getData(), (int)chunkMemory.getSize());
chunkMemory.reset();
return true;
}
public:
#if JUCE_MAC
bool guiCocoaAttach(void *nsView) noexcept
{
juce::initialiseMacVST();
auto hostWindow = juce::attachComponentToWindowRefVST(editor.get(), nsView, true);
juce::ignoreUnused(hostWindow);
return true;
}
#endif
#if JUCE_LINUX
bool guiX11Attach(const char *displayName, unsigned long window) noexcept
{
const juce::MessageManagerLock mmLock;
editor->setVisible(false);
editor->addToDesktop(0, (void *)window);
auto *display = juce::XWindowSystem::getInstance()->getDisplay();
juce::X11Symbols::getInstance()->xReparentWindow(display, (Window)editor->getWindowHandle(),
window, 0, 0);
editor->setVisible(true);
return true;
}
#endif
#if JUCE_WINDOWS
bool guiWin32Attach(clap_hwnd window) noexcept
{
editor->setVisible(false);
editor->setOpaque(true);
editor->setTopLeftPosition(0, 0);
editor->addToDesktop(0, (void *)window);
editor->setVisible(true);
return true;
}
#endif
private:
struct ParamChange
{