86#define DSPARK_PLUGIN_CLAP_INCLUDED 1
88#include "../DSParkPlugin.h"
93#pragma push_macro("min")
94#pragma push_macro("max")
126template <
size_t NumPerVoice>
146 static constexpr size_t kSlots = NumPerVoice == 0 ? 1 : NumPerVoice;
150 std::array<double, kSlots>
value {};
156 for (
auto& voice : voices_) voice.used =
false;
161 int start(
int channel,
int key, int32_t noteId)
noexcept
165 Voice& voice = voices_[
static_cast<size_t>(i)];
166 if (voice.
used)
continue;
167 voice.
channel =
static_cast<int16_t
>(channel);
168 voice.
key =
static_cast<int16_t
>(key);
170 voice.
serial = nextSerial_++;
173 if constexpr (NumPerVoice > 0)
177 auto&
params = params_[
static_cast<size_t>(i)];
178 params.modulated.fill(
false);
179 params.valued.fill(
false);
181 if (i >= end_) end_ = i + 1;
189 [[nodiscard]]
int oldest() const noexcept
192 bool bestHeld =
true;
193 uint32_t bestAge = 0;
194 for (
int i = 0; i < end_; ++i)
196 const Voice& voice = voices_[
static_cast<size_t>(i)];
197 if (!voice.
used)
continue;
198 const uint32_t age = nextSerial_ - voice.
serial;
199 if (best < 0 || (bestHeld && !voice.
held)
200 || (bestHeld == voice.
held && age > bestAge))
203 bestHeld = voice.
held;
211 [[nodiscard]]
int end() const noexcept {
return end_; }
215 template <
typename Fn>
216 void forEachMatching(
int port,
int channel,
int key, int32_t noteId, Fn&& fn)
noexcept
218 if (port > 0)
return;
219 for (
int i = 0; i < end_; ++i)
221 const Voice& voice = voices_[
static_cast<size_t>(i)];
223 || (channel >= 0 && voice.
channel != channel)
224 || (key >= 0 && voice.
key != key)
225 || (noteId >= 0 && voice.
noteId != noteId))
236 return params_[NumPerVoice > 0 ?
static_cast<size_t>(slot) : 0u];
242 voices_[
static_cast<size_t>(slot)].used =
false;
243 while (end_ > 0 && !voices_[
static_cast<size_t>(end_ - 1)].used) --end_;
247 std::array<Voice, kCapacity> voices_ {};
248 std::array<VoiceParams, (NumPerVoice > 0 ?
kCapacity : 1)> params_ {};
250 uint32_t nextSerial_ = 0;
261 "an Instrument has no audio inputs; remove the sidechain "
262 "processBlock or use Category::Fx");
264 "an Instrument needs handleMidiEvent (see HasMidi): it has "
265 "no audio input to process");
266 static_assert(paramIdsUnique<P>(),
267 "two parameter ids share a hash32 (or collide with the "
268 "reserved PRGM/BYPS/EDSW/EDSH state ids): automation and state "
269 "would cross-wire. Rename one id.");
273 "a perVoice() parameter needs handleMidiEvent (see HasMidi): "
274 "only a plugin with a note input has voices to modulate");
277 const clap_host_t*
host =
nullptr;
339#if defined(DSPARK_PLUGIN_WEBVIEW)
343 bool guiActive =
false;
344 double guiScale = 1.0;
345 int guiWidth = 0, guiHeight = 0;
347 const clap_host_gui_t* hostGui =
nullptr;
348#if defined(__linux__)
350 const clap_host_timer_support_t* hostTimer =
nullptr;
351 clap_id guiTimerId = CLAP_INVALID_ID;
354 enum : uint8_t { kUiGestureBegin = 0, kUiValue = 1, kUiGestureEnd = 2 };
361 static constexpr uint32_t kUiQueueSize = 256;
362 UiEvent uiQueue[kUiQueueSize] {};
363 std::atomic<uint32_t> uiHead { 0 }, uiTail { 0 };
370 std::memory_order_relaxed);
375 return static_cast<Plugin*
>(p->plugin_data);
381 double heardPlain(
int index,
double normalized)
const noexcept
383 const auto& spec = P::parameters[
static_cast<size_t>(index)];
384 const double value =
toPlain(spec, normalized);
385 const double mod =
modulation[
static_cast<size_t>(index)];
393 if (normalized != normalized)
return;
394 shadow[
static_cast<size_t>(index)].store(normalized, std::memory_order_relaxed);
395 user.setParameter(index,
static_cast<float>(
heardPlain(index, normalized)));
400 return paramIndexOf<P>(
id);
412 if (normalized != normalized)
return false;
413 if (
active.load(std::memory_order_acquire))
415 shadow[
static_cast<size_t>(index)].store(normalized, std::memory_order_relaxed);
427 i,
shadow[
static_cast<size_t>(i)].load(std::memory_order_relaxed))));
440 double amount)
const noexcept
442 const auto& spec = P::parameters[
static_cast<size_t>(index)];
443 const double base = valued
445 :
toPlain(spec,
shadow[
static_cast<size_t>(index)].load(std::memory_order_relaxed));
446 const double mod = modulated ? amount :
modulation[
static_cast<size_t>(index)];
452 template <
typename Params>
455 const auto s =
static_cast<size_t>(slot);
466 midi.channel =
static_cast<uint8_t
>(channel & 0x0F);
467 midi.note =
static_cast<uint8_t
>(key & 0x7F);
468 midi.noteId = noteId;
469 user.handleMidiEvent(midi);
490 const int slot = perVoiceSlotTable<P>[
static_cast<size_t>(index)];
491 if (slot < 0)
return;
492 const auto s =
static_cast<size_t>(slot);
493 const auto& spec = P::parameters[
static_cast<size_t>(index)];
495 const double globalValue =
496 toPlain(spec,
shadow[
static_cast<size_t>(index)].load(std::memory_order_relaxed));
497 const double globalAmount =
modulation[
static_cast<size_t>(index)];
500 midi.param =
static_cast<int16_t
>(index);
501 midi.sampleOffset = sampleOffset;
504 const auto& voice =
voices[v];
505 if (!voice.used)
continue;
507 const bool valued =
params.valued[s];
508 const bool modulated =
params.modulated[s];
509 if (modulationMoved ? (!valued || modulated) : (!modulated || valued))
continue;
510 const double base = valued ?
params.value[s] : globalValue;
511 const double amount = modulated ?
params.amount[s] : globalAmount;
520 (void) modulationMoved;
532 const auto& voice =
voices[slot];
549 if (
voices.
start(midi.channel, midi.note, midi.noteId) < 0)
553 (void)
voices.
start(midi.channel, midi.note, midi.noteId);
566 voices[slot].held =
false;
581 const int index = midi.param;
582 const int slot = isModulation ? perVoiceSlotTable<P>[
static_cast<size_t>(index)] : -1;
583 if (isModulation && slot < 0)
return;
584 const auto s =
static_cast<size_t>(slot < 0 ? 0 : slot);
585 bool delivered =
false;
587 ev.targetNoteId, [&](
int v) {
588 const auto& voice =
voices[v];
594 params.value[s] = ev.value;
599 params.amount[s] = ev.value;
600 params.modulated[s] =
true;
607 if (!delivered && ev.targetPort <= 0 && ev.targetChannel >= 0 && ev.targetKey >= 0)
610 midi.value =
static_cast<float>(ev.voiceValue
613 deliverToVoice(midi, ev.targetChannel, ev.targetKey, ev.targetNoteId);
623 for (
int v =
voices.
end() - 1; v >= 0; --v)
625 const auto& voice =
voices[v];
627 && !
static_cast<bool>(
user.isVoiceActive(voice.channel, voice.key,
639 for (
int i = 0; out !=
nullptr && out->try_push !=
nullptr && i <
endedCount; ++i)
641 clap_event_note_t ev {};
642 ev.header.size =
sizeof(ev);
643 ev.header.time = time;
644 ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
645 ev.header.type = CLAP_EVENT_NOTE_END;
651 out->try_push(out, &ev.header);
678 direct &=
applyFromUi(
static_cast<int>(i), presetNormalized<P>(idx, i));
694 const int now =
user.getLatency();
699 if (
host !=
nullptr &&
host->request_callback !=
nullptr)
711 if (ev ==
nullptr || ev->space_id != CLAP_CORE_EVENT_SPACE_ID)
return;
713 out.
offset =
static_cast<int32_t
>(ev->time);
714 if (numSamples > 0 && out.offset >=
static_cast<int32_t
>(numSamples))
715 out.offset =
static_cast<int32_t
>(numSamples) - 1;
716 if (out.offset < 0) out.offset = 0;
718 if (ev->type == CLAP_EVENT_PARAM_VALUE)
720 const auto* pv =
reinterpret_cast<const clap_event_param_value_t*
>(ev);
724 if (pv->value != pv->value)
return;
729 out.value = pv->value;
742 if (pv->note_id >= 0 || pv->key >= 0 || pv->channel >= 0)
746 if (P::parameters[
static_cast<size_t>(idx)].perVoice)
750 out.midi.param =
static_cast<int16_t
>(idx);
751 out.value = pv->value;
752 out.voiceValue =
true;
753 out.targetNoteId = pv->note_id;
754 out.targetPort = pv->port_index;
755 out.targetChannel = pv->channel;
756 out.targetKey = pv->key;
763 out.paramId = pv->param_id;
764 out.value =
toNormalized(P::parameters[
static_cast<size_t>(idx)],
768 else if (ev->type == CLAP_EVENT_PARAM_MOD)
775 const auto* pm =
reinterpret_cast<const clap_event_param_mod_t*
>(ev);
776 if (pm->amount != pm->amount)
return;
779 if (pm->note_id >= 0 || pm->key >= 0 || pm->channel >= 0 || pm->port_index >= 0)
783 if (!P::parameters[
static_cast<size_t>(idx)].perVoice)
return;
786 out.midi.param =
static_cast<int16_t
>(idx);
787 out.value = pm->amount;
788 out.targetNoteId = pm->note_id;
789 out.targetPort = pm->port_index;
790 out.targetChannel = pm->channel;
791 out.targetKey = pm->key;
797 out.paramId = pm->param_id;
798 out.value = pm->amount;
803 if (ev->type == CLAP_EVENT_NOTE_ON || ev->type == CLAP_EVENT_NOTE_OFF
804 || ev->type == CLAP_EVENT_NOTE_CHOKE)
806 const auto* note =
reinterpret_cast<const clap_event_note_t*
>(ev);
807 if (ev->type == CLAP_EVENT_NOTE_ON)
809 if ((note->key < 0) || (note->key > 127))
return;
810 const int ch = note->channel >= 0 ? (note->channel & 0x0F) : 0;
812 out.midi.channel =
static_cast<uint8_t
>(ch);
813 out.midi.note =
static_cast<uint8_t
>(note->key);
814 out.midi.value =
static_cast<float>(note->velocity);
815 out.midi.noteId = note->note_id >= 0 ? note->note_id : -1;
828 const bool choke = ev->type == CLAP_EVENT_NOTE_CHOKE;
829 const float velocity = choke ? 0.0f :
static_cast<float>(note->velocity);
830 out.midi.choke = choke;
831 const bool exact = note->channel >= 0 && note->key >= 0;
838 out.midi.channel =
static_cast<uint8_t
>(note->channel & 0x0F);
839 out.midi.note =
static_cast<uint8_t
>(note->key & 0x7F);
840 out.midi.value = velocity;
841 out.midi.noteId = note->note_id >= 0 ? note->note_id : -1;
850 off.
midi.
note =
static_cast<uint8_t
>(k);
859 else if (ev->type == CLAP_EVENT_NOTE_EXPRESSION)
864 const auto* ne =
reinterpret_cast<const clap_event_note_expression_t*
>(ev);
865 if ((ne->expression_id < CLAP_NOTE_EXPRESSION_VOLUME)
866 || (ne->expression_id > CLAP_NOTE_EXPRESSION_PRESSURE)
867 || ne->value != ne->value)
869 const auto expression =
872 if ((noteExpressionsOf<P>() &
expressionBit(expression)) == 0u)
return;
874 out.midi.expression = expression;
875 out.midi.value =
static_cast<float>(ne->value);
876 out.targetNoteId = ne->note_id;
877 out.targetPort = ne->port_index;
878 out.targetChannel = ne->channel;
879 out.targetKey = ne->key;
881 else if (ev->type == CLAP_EVENT_MIDI)
883 const auto* midi =
reinterpret_cast<const clap_event_midi_t*
>(ev);
884 const uint8_t status = midi->data[0] & 0xF0u;
885 const uint8_t channel = midi->data[0] & 0x0Fu;
886 const uint8_t d1 = midi->data[1] & 0x7Fu;
887 const uint8_t d2 = midi->data[2] & 0x7Fu;
888 out.midi.channel = channel;
895 out.midi.value =
static_cast<float>(d2) / 127.0f;
902 out.midi.value =
static_cast<float>(d2) / 127.0f;
908 out.midi.value =
static_cast<float>(d2) / 127.0f;
913 out.midi.value =
static_cast<float>(d2) / 127.0f;
917 out.midi.value =
static_cast<float>(d1) / 127.0f;
921 out.midi.value = (
static_cast<float>((d2 << 7) | d1) - 8192.0f)
943 if (in ==
nullptr)
return;
944 const uint32_t n = in->size(in);
945 for (uint32_t i = 0; i < n; ++i)
956 bypass.store(ev.value >= 0.5, std::memory_order_relaxed);
969 user.handleMidiEvent(midi);
977 modulation[
static_cast<size_t>(idx)] = ev.value;
979 idx,
shadow[
static_cast<size_t>(idx)].load(std::memory_order_relaxed))));
980 const int offset = ev.offset - blockStart;
990 const int offset = ev.offset - blockStart;
1003 if (t ==
nullptr)
return;
1004 constexpr double kBeatFactor =
static_cast<double>(CLAP_BEATTIME_FACTOR);
1006 info.
playing = (t->flags & CLAP_TRANSPORT_IS_PLAYING) != 0;
1007 info.recording = (t->flags & CLAP_TRANSPORT_IS_RECORDING) != 0;
1008 info.looping = (t->flags & CLAP_TRANSPORT_IS_LOOP_ACTIVE) != 0;
1009 if ((t->flags & CLAP_TRANSPORT_HAS_TEMPO) != 0)
1011 info.tempoBpm = t->tempo;
1012 info.tempoValid =
true;
1014 if ((t->flags & CLAP_TRANSPORT_HAS_BEATS_TIMELINE) != 0)
1016 info.ppqPosition =
static_cast<double>(t->song_pos_beats) / kBeatFactor;
1017 info.barStartPpq =
static_cast<double>(t->bar_start) / kBeatFactor;
1018 info.positionValid =
true;
1020 static_cast<double>(t->loop_start_beats) / kBeatFactor;
1021 info.loopEndPpq =
static_cast<double>(t->loop_end_beats) / kBeatFactor;
1022 info.loopValid =
true;
1024 if ((t->flags & CLAP_TRANSPORT_HAS_TIME_SIGNATURE) != 0)
1026 info.timeSigNumerator = t->tsig_num;
1027 info.timeSigDenominator = t->tsig_denom;
1028 info.timeSigValid =
true;
1030 user.setTransport(info);
1036#if defined(DSPARK_PLUGIN_WEBVIEW)
1039 void pushUiEvent(uint32_t paramId, uint8_t kind,
double value)
noexcept
1041 const uint32_t tail = uiTail.load(std::memory_order_relaxed);
1042 const uint32_t next = (tail + 1) & (kUiQueueSize - 1);
1043 if (next == uiHead.load(std::memory_order_acquire))
return;
1044 uiQueue[tail] = UiEvent { paramId, kind, value };
1045 uiTail.store(next, std::memory_order_release);
1048 void requestUiFlush() noexcept
1055 void drainUiEvents(
const clap_output_events_t* out)
noexcept
1057 if (out ==
nullptr)
return;
1058 uint32_t head = uiHead.load(std::memory_order_relaxed);
1059 const uint32_t tail = uiTail.load(std::memory_order_acquire);
1060 while (head != tail)
1062 const UiEvent& e = uiQueue[head];
1063 if (e.kind == kUiValue)
1065 clap_event_param_value_t ev {};
1066 ev.header.size =
sizeof(ev);
1067 ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
1068 ev.header.type = CLAP_EVENT_PARAM_VALUE;
1069 ev.param_id = e.paramId;
1075 out->try_push(out, &ev.header);
1079 clap_event_param_gesture_t ev {};
1080 ev.header.size =
sizeof(ev);
1081 ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
1082 ev.header.type =
static_cast<uint16_t
>(
1083 e.kind == kUiGestureBegin ? CLAP_EVENT_PARAM_GESTURE_BEGIN
1084 : CLAP_EVENT_PARAM_GESTURE_END);
1085 ev.param_id = e.paramId;
1086 out->try_push(out, &ev.header);
1088 head = (head + 1) & (kUiQueueSize - 1);
1090 uiHead.store(head, std::memory_order_release);
1096 static bool sInit(
const clap_plugin_t* p)
noexcept
1099 if (s->host !=
nullptr)
1101 s->hostParams =
static_cast<const clap_host_params_t*
>(
1102 s->host->get_extension(s->host, CLAP_EXT_PARAMS));
1103 s->hostLatency =
static_cast<const clap_host_latency_t*
>(
1104 s->host->get_extension(s->host, CLAP_EXT_LATENCY));
1106 s->hostPresetLoad =
static_cast<const clap_host_preset_load_t*
>(
1107 s->host->get_extension(s->host, CLAP_EXT_PRESET_LOAD));
1108#if defined(DSPARK_PLUGIN_WEBVIEW)
1110 s->hostGui =
static_cast<const clap_host_gui_t*
>(
1111 s->host->get_extension(s->host, CLAP_EXT_GUI));
1126 s->user.prepare(spec);
1128 s->user.setOfflineRendering(s->offlineRender);
1129 s->pending.drain([](
int) {});
1131 s->user.setParameter(
static_cast<int>(i),
1132 static_cast<float>(s->heardPlain(
static_cast<int>(i),
1133 s->shadow[i].load(std::memory_order_relaxed))));
1138 s->bypassMix = s->bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
1139 s->sounding.clear();
1144 const int latency = s->user.getLatency();
1145 s->cachedLatency.store(latency, std::memory_order_relaxed);
1150 s->latencyDirty.store(
false, std::memory_order_relaxed);
1151 if (latency != s->latencyAtActivate && s->hostLatency !=
nullptr
1152 && s->hostLatency->changed !=
nullptr)
1153 s->hostLatency->changed(s->host);
1154 s->latencyAtActivate = latency;
1157 s->active.store(
true, std::memory_order_release);
1164 s->active.store(
false, std::memory_order_release);
1180 static void sReset(
const clap_plugin_t* p)
noexcept
1185 s->dryDelay.reset();
1186 s->sounding.clear();
1189 s->bypassMix = s->bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
1194 void blendBypass(
float*
const* out,
float*
const* dry, uint32_t nCh,
int outStart,
1195 int dryStart,
int length)
noexcept
1197 const float target =
bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
1198 if (
bypassMix == target && target == 0.0f)
return;
1201 for (
int i = 0; i < length; ++i)
1203 mix += (target > mix) ? step : ((target < mix) ? -step : 0.0f);
1204 mix = mix < 0.0f ? 0.0f : (mix > 1.0f ? 1.0f : mix);
1205 for (uint32_t ch = 0; ch < nCh; ++ch)
1206 out[ch][outStart + i] += (dry[ch][dryStart + i] - out[ch][outStart + i]) * mix;
1211 static clap_process_status
sProcess(
const clap_plugin_t* p,
1212 const clap_process_t* process)
noexcept
1220#if defined(DSPARK_PLUGIN_WEBVIEW)
1221 s->drainUiEvents(process->out_events);
1224 const uint32_t n = process->frames_count;
1228 bool paramsChanged = s->drainPending();
1232 s->collectEvents(process->in_events, n, events);
1234 const int eventCount = events.
size();
1236 const clap_audio_buffer_t* outPort =
1237 process->audio_outputs_count >= 1 && process->audio_outputs !=
nullptr
1238 ? &process->audio_outputs[0] :
nullptr;
1239 float** out = outPort !=
nullptr ? outPort->data32 :
nullptr;
1240 const uint32_t width =
static_cast<uint32_t
>(s->currentChannels);
1241 uint32_t nCh = out ==
nullptr ? 0u
1242 : (outPort->channel_count < width ? outPort->channel_count : width);
1246 for (uint32_t ch = 0; ch < nCh; ++ch)
1247 if (out[ch] ==
nullptr)
1253 const bool canRender = n > 0 && s->prepared && nCh >= 1;
1256 for (
int i = 0; i < eventCount; ++i)
1257 paramsChanged |= s->applyBlockEvent(events[i], events[i].offset);
1258 if (paramsChanged) s->refreshLatency();
1259 s->flushEndedVoices(process->out_events, 0);
1260 return CLAP_PROCESS_CONTINUE;
1263 s->forwardTransport(process->transport);
1265 const bool haveIn = !
kIsInstrument && process->audio_inputs_count >= 1
1266 && process->audio_inputs !=
nullptr
1267 && process->audio_inputs[0].data32 !=
nullptr
1268 && process->audio_inputs[0].channel_count >= 1;
1269 float** in = haveIn ? process->audio_inputs[0].data32 :
nullptr;
1270 const uint32_t inCh = haveIn ? process->audio_inputs[0].channel_count : 0;
1273 float* scHost[2] = {
nullptr,
nullptr };
1276 if (process->audio_inputs_count >= 2
1277 && process->audio_inputs[1].data32 !=
nullptr)
1279 const auto& scPort = process->audio_inputs[1];
1280 const uint32_t scCh = scPort.channel_count < 2
1281 ? scPort.channel_count : 2;
1282 for (uint32_t ch = 0; ch < scCh; ++ch)
1283 scHost[ch] = scPort.data32[ch];
1285 scHost[1] = scPort.data32[0];
1292 const int total =
static_cast<int>(n);
1293 const int chunkMax =
static_cast<int>(s->dryL.size());
1294 if (chunkMax < 1)
return CLAP_PROCESS_CONTINUE;
1295 float* dry[2] = { s->dryL.data(), s->dryR.data() };
1298 for (
int c0 = 0; c0 < total; c0 += chunkMax)
1300 const int len = total - c0 < chunkMax ? total - c0 : chunkMax;
1301 const int cEnd = c0 + len;
1309 const size_t bytes =
sizeof(float) *
static_cast<size_t>(len);
1310 for (uint32_t ch = 0; ch < nCh; ++ch)
1312 const float* src =
nullptr;
1314 src = in[ch < inCh ? ch : inCh - 1];
1317 std::memset(out[ch] + c0, 0, bytes);
1321 std::memcpy(dry[ch], src + c0, bytes);
1323 std::memcpy(out[ch] + c0, src + c0, bytes);
1326 s->dryDelay.process(dry,
static_cast<int>(nCh), len,
1327 s->cachedLatency.load(std::memory_order_relaxed));
1329 float* scChunk[2] = {
nullptr,
nullptr };
1331 for (
int ch = 0; ch < 2; ++ch)
1332 scChunk[ch] = scHost[ch] !=
nullptr ? scHost[ch] + c0
1333 : s->silence.data();
1338 auto processSegment = [&](
int start,
int length)
noexcept {
1339 float* sub[2] = { out[0] + start,
1340 nCh > 1 ? out[1] + start : out[0] + start };
1345 float* scSub[2] = { scChunk[0] + (start - c0),
1346 scChunk[1] + (start - c0) };
1348 static_cast<int>(nCh), length);
1349 s->user.processBlock(view, scView);
1352 s->user.processBlock(view);
1356 s->blendBypass(out, dry, nCh, start, start - c0, length);
1359 if (!sampleAccurateOf<P>())
1361 for (; evIdx < eventCount && events[evIdx].offset < cEnd; ++evIdx)
1362 paramsChanged |= s->applyBlockEvent(events[evIdx], c0);
1363 processSegment(c0, len);
1370 while (evIdx < eventCount
1373 paramsChanged |= s->applyBlockEvent(events[evIdx++], pos);
1375 if (evIdx < eventCount)
1379 if (snapped < next) next = snapped;
1383 processSegment(pos, next - pos);
1388 for (; evIdx < eventCount; ++evIdx)
1389 paramsChanged |= s->applyBlockEvent(events[evIdx], total);
1391 if (paramsChanged) s->refreshLatency();
1393 s->flushEndedVoices(process->out_events, n - 1);
1394 return CLAP_PROCESS_CONTINUE;
1399 if (std::strcmp(
id, CLAP_EXT_AUDIO_PORTS) == 0)
return &
kAudioPorts;
1400 if (std::strcmp(
id, CLAP_EXT_PARAMS) == 0)
return &
kParams;
1401 if (std::strcmp(
id, CLAP_EXT_STATE) == 0)
return &
kState;
1402 if (std::strcmp(
id, CLAP_EXT_LATENCY) == 0)
return &
kLatency;
1403 if (std::strcmp(
id, CLAP_EXT_TAIL) == 0)
return &
kTail;
1406 if (std::strcmp(
id, CLAP_EXT_AUDIO_PORTS_CONFIG) == 0)
1408 if (std::strcmp(
id, CLAP_EXT_AUDIO_PORTS_CONFIG_INFO) == 0
1409 || std::strcmp(
id, CLAP_EXT_AUDIO_PORTS_CONFIG_INFO_COMPAT) == 0)
1413 if (std::strcmp(
id, CLAP_EXT_NOTE_PORTS) == 0)
return &
kNotePorts;
1415 if (std::strcmp(
id, CLAP_EXT_RENDER) == 0)
return &
kRender;
1417 if (std::strcmp(
id, CLAP_EXT_PRESET_LOAD) == 0
1418 || std::strcmp(
id, CLAP_EXT_PRESET_LOAD_COMPAT) == 0)
1420#if defined(DSPARK_PLUGIN_WEBVIEW)
1425#if defined(__linux__)
1427 && std::strcmp(
id, CLAP_EXT_TIMER_SUPPORT) == 0)
1445 if (!s->latencyDirty.exchange(
false, std::memory_order_acq_rel))
return;
1446 if (s->active.load(std::memory_order_acquire))
1448 if (s->host !=
nullptr && s->host->request_restart !=
nullptr)
1449 s->host->request_restart(s->host);
1456 static uint32_t
sPortCount(
const clap_plugin_t*,
bool isInput)
noexcept
1466 static bool sPortGet(
const clap_plugin_t* p, uint32_t index,
bool isInput,
1467 clap_audio_port_info_t* info)
noexcept
1469 if (info ==
nullptr || index >=
sPortCount(p, isInput))
return false;
1471 std::memset(info, 0,
sizeof(*info));
1472 if (isInput && index == 1)
1475 std::snprintf(info->name,
sizeof(info->name),
"Sidechain");
1477 info->channel_count =
static_cast<uint32_t
>(width);
1478 info->port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1479 info->in_place_pair = CLAP_INVALID_ID;
1482 info->id = isInput ? 0 : 1;
1483 std::snprintf(info->name,
sizeof(info->name),
"%s",
1484 isInput ?
"Input" :
"Output");
1485 info->flags = CLAP_AUDIO_PORT_IS_MAIN;
1486 info->channel_count =
static_cast<uint32_t
>(width);
1487 info->port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1489 : (isInput ? 1u : 0u);
1499 static void fillConfig(clap_audio_ports_config_t* config,
int width)
noexcept
1501 std::memset(config, 0,
sizeof(*config));
1502 config->id =
static_cast<clap_id
>(width);
1503 std::snprintf(config->name,
sizeof(config->name),
"%s",
1504 width == 1 ?
"Mono" :
"Stereo");
1505 config->input_port_count =
sPortCount(
nullptr,
true);
1506 config->output_port_count = 1;
1508 config->main_input_channel_count =
static_cast<uint32_t
>(width);
1509 config->main_input_port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1510 config->has_main_output =
true;
1511 config->main_output_channel_count =
static_cast<uint32_t
>(width);
1512 config->main_output_port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1516 clap_audio_ports_config_t* config)
noexcept
1518 if (config ==
nullptr || index >= 2)
return false;
1525 const int width =
static_cast<int>(configId);
1526 if (!supportsChannelCount<P>(width))
return false;
1541 uint32_t portIndex,
bool isInput,
1542 clap_audio_port_info_t* info)
noexcept
1544 const int width =
static_cast<int>(configId);
1545 if (info ==
nullptr || !supportsChannelCount<P>(width)
1549 std::memset(info, 0,
sizeof(*info));
1550 if (isInput && portIndex == 1)
1553 std::snprintf(info->name,
sizeof(info->name),
"Sidechain");
1554 info->channel_count =
static_cast<uint32_t
>(width);
1555 info->port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1556 info->in_place_pair = CLAP_INVALID_ID;
1559 info->id = isInput ? 0 : 1;
1560 std::snprintf(info->name,
sizeof(info->name),
"%s",
1561 isInput ?
"Input" :
"Output");
1562 info->flags = CLAP_AUDIO_PORT_IS_MAIN;
1563 info->channel_count =
static_cast<uint32_t
>(width);
1564 info->port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1566 : (isInput ? 1u : 0u);
1581 static bool sNotePortGet(
const clap_plugin_t*, uint32_t index,
bool isInput,
1582 clap_note_port_info_t* info)
noexcept
1584 if (info ==
nullptr || !isInput || index != 0 || !
HasMidi<P>)
return false;
1585 std::memset(info, 0,
sizeof(*info));
1587 info->supported_dialects = CLAP_NOTE_DIALECT_CLAP | CLAP_NOTE_DIALECT_MIDI;
1588 info->preferred_dialect = CLAP_NOTE_DIALECT_CLAP;
1589 std::snprintf(info->name,
sizeof(info->name),
"MIDI In");
1601 static bool sRenderSet(
const clap_plugin_t* p, clap_plugin_render_mode mode)
noexcept
1604 s->offlineRender = mode == CLAP_RENDER_OFFLINE;
1606 s->user.setOfflineRendering(s->offlineRender);
1610 inline static const clap_plugin_render_t
kRender = {
1617 const char* location,
const char* loadKey)
noexcept
1622 if (locationKind != CLAP_PRESET_DISCOVERY_LOCATION_PLUGIN
1623 || loadKey ==
nullptr)
1625 const int idx = std::atoi(loadKey);
1627 s->applyFactoryPresetIdx(idx);
1628 s->refreshLatency();
1629 if (s->hostParams !=
nullptr && s->hostParams->rescan !=
nullptr)
1630 s->hostParams->rescan(s->host, CLAP_PARAM_RESCAN_VALUES);
1631 if (s->hostPresetLoad !=
nullptr && s->hostPresetLoad->loaded !=
nullptr)
1632 s->hostPresetLoad->loaded(s->host, locationKind, location, loadKey);
1638 (void) locationKind;
1653 return static_cast<uint32_t
>(
kNumParams) + 1;
1661 auto whole = [](
double v) {
1662 const double r =
static_cast<double>(
static_cast<long long>(v < 0.0 ? v - 0.5
1664 return v - r < 1e-9 && r - v < 1e-9;
1666 const double step = (
static_cast<double>(spec.maxValue) - spec.minValue) / spec.steps;
1667 return whole(spec.minValue) && step > 1.0 - 1e-9 && step < 1.0 + 1e-9;
1671 clap_param_info_t* info)
noexcept
1673 if (info ==
nullptr || index >
kNumParams)
return false;
1674 std::memset(info, 0,
sizeof(*info));
1678 std::snprintf(info->name,
sizeof(info->name),
"Bypass");
1679 info->flags = CLAP_PARAM_IS_AUTOMATABLE | CLAP_PARAM_IS_STEPPED
1680 | CLAP_PARAM_IS_BYPASS;
1681 info->min_value = 0.0;
1682 info->max_value = 1.0;
1683 info->default_value = 0.0;
1686 const auto& spec = P::parameters[index];
1687 info->id =
hash32(spec.id);
1688 std::snprintf(info->name,
sizeof(info->name),
"%s", spec.name);
1689 info->flags = CLAP_PARAM_IS_AUTOMATABLE | CLAP_PARAM_IS_MODULATABLE;
1695 if (spec.steps > 0 &&
isIntegerGrid(spec)) info->flags |= CLAP_PARAM_IS_STEPPED;
1696 if (spec.labels !=
nullptr) info->flags |= CLAP_PARAM_IS_ENUM;
1703 info->flags |= CLAP_PARAM_IS_MODULATABLE_PER_NOTE_ID
1704 | CLAP_PARAM_IS_MODULATABLE_PER_KEY
1705 | CLAP_PARAM_IS_MODULATABLE_PER_CHANNEL
1706 | CLAP_PARAM_IS_MODULATABLE_PER_PORT
1707 | CLAP_PARAM_IS_AUTOMATABLE_PER_NOTE_ID
1708 | CLAP_PARAM_IS_AUTOMATABLE_PER_KEY
1709 | CLAP_PARAM_IS_AUTOMATABLE_PER_CHANNEL;
1710 info->min_value = spec.minValue;
1711 info->max_value = spec.maxValue;
1712 info->default_value = spec.defValue;
1716 static bool sParamValue(
const clap_plugin_t* p, clap_id
id,
double* out)
noexcept
1719 if (out ==
nullptr)
return false;
1722 *out = s->bypass.load(std::memory_order_relaxed) ? 1.0 : 0.0;
1726 if (idx < 0)
return false;
1727 *out =
toPlain(P::parameters[
static_cast<size_t>(idx)],
1728 s->shadow[
static_cast<size_t>(idx)].load(std::memory_order_relaxed));
1733 char* out, uint32_t size)
noexcept
1735 if (out ==
nullptr || size == 0)
return false;
1738 std::snprintf(out, size,
"%s", value >= 0.5 ?
"On" :
"Off");
1742 if (idx < 0)
return false;
1743 formatValue(P::parameters[
static_cast<size_t>(idx)], value, out,
1744 static_cast<int>(size));
1749 const char* text,
double* out)
noexcept
1751 if (text ==
nullptr || out ==
nullptr)
return false;
1756 : (std::strtod(text,
nullptr) >= 0.5 ? 1.0 : 0.0);
1760 if (idx < 0)
return false;
1763 return parseValue(P::parameters[
static_cast<size_t>(idx)], text, *out);
1766 static void sParamFlush(
const clap_plugin_t* p,
const clap_input_events_t* in,
1767 const clap_output_events_t* out)
noexcept
1773 bool paramsChanged = s->drainPending();
1776 s->collectEvents(in, 0, events);
1778 for (
int i = 0; i < events.
size(); ++i)
1779 paramsChanged |= s->applyBlockEvent(events[i], events[i].offset);
1780 if (paramsChanged) s->refreshLatency();
1781 s->flushEndedVoices(out, 0);
1782#if defined(DSPARK_PLUGIN_WEBVIEW)
1783 s->drainUiEvents(out);
1787 inline static const clap_plugin_params_t
kParams = {
1794 static bool sStateSave(
const clap_plugin_t* p,
const clap_ostream_t* stream)
noexcept
1799 norm[i] = s->shadow[i].load(std::memory_order_relaxed);
1801 const bool withSize = s->editorMemory.remembered(editorSize);
1802 const std::vector<uint8_t> blob =
buildState(
1804 kNumPresets > 0 ? s->currentProgram.load(std::memory_order_relaxed) : -1,
1805 s->bypass.load(std::memory_order_relaxed) ? 1 : 0,
1806 withSize ? &editorSize :
nullptr);
1808 while (pos < blob.size())
1810 const int64_t put = stream->write(stream, blob.data() + pos,
1812 if (put <= 0)
return false;
1813 pos +=
static_cast<size_t>(put);
1818 static bool sStateLoad(
const clap_plugin_t* p,
const clap_istream_t* stream)
noexcept
1821 std::vector<uint8_t> blob;
1822 uint8_t chunk[4096];
1825 const int64_t got = stream->read(stream, chunk,
sizeof(chunk));
1826 if (got < 0)
return false;
1827 if (got == 0)
break;
1828 blob.insert(blob.end(), chunk, chunk + got);
1836 loadDefaultNormalized<P>(norm);
1838 int bypassState = -1;
1840 if (!
applyState(s->user, blob.data(), blob.size(), norm, &program,
1841 &bypassState, &editorSize))
1845 direct &= s->applyFromUi(
static_cast<int>(i), norm[i]);
1847 s->currentProgram.store(program, std::memory_order_relaxed);
1848 if (bypassState >= 0)
1849 s->bypass.store(bypassState != 0, std::memory_order_relaxed);
1853 if (editorSize.width > 0)
1855 s->editorMemory.remember(editorSize.width, editorSize.height);
1856#if defined(DSPARK_PLUGIN_WEBVIEW)
1857 s->applyRememberedEditorSize();
1861 s->refreshLatency();
1863 s->requestParamFlush();
1873 return static_cast<uint32_t
>(
1879 static uint32_t
sTailGet(
const clap_plugin_t* p)
noexcept
1884 const double seconds = s->user.getTailSeconds();
1885 if (!(seconds > 0.0))
return 0;
1886 const double samples = seconds * s->sampleRate;
1889 if (samples >= 4294967295.0)
return 0xFFFFFFFFu;
1890 return static_cast<uint32_t
>(samples);
1901#if defined(DSPARK_PLUGIN_WEBVIEW)
1907 static const char* clapWindowApi() noexcept
1910 return CLAP_WINDOW_API_WIN32;
1911#elif defined(__APPLE__)
1912 return CLAP_WINDOW_API_COCOA;
1914 return CLAP_WINDOW_API_X11;
1923 void applyRememberedEditorSize() noexcept
1925 if (!guiActive)
return;
1931 if (w == guiWidth && h == guiHeight)
return;
1933 if (hostGui ==
nullptr || hostGui->request_resize ==
nullptr
1934 || !hostGui->request_resize(
host,
static_cast<uint32_t
>(w),
1935 static_cast<uint32_t
>(h)))
1942 static void cbGuiSetParam(
void* context,
int index,
double plain)
noexcept
1944 auto* s =
static_cast<Plugin*
>(context);
1945 const Param& spec = P::parameters[
static_cast<size_t>(index)];
1950 if (s->applyFromUi(index, normalized))
1951 s->refreshLatency();
1952 const double snapped =
toPlain(spec, normalized);
1953 const uint32_t
id =
hash32(spec.id);
1954 if (s->guiEditActive[
static_cast<size_t>(index)])
1955 s->pushUiEvent(
id, kUiValue, snapped);
1959 s->pushUiEvent(
id, kUiGestureBegin, 0.0);
1960 s->pushUiEvent(
id, kUiValue, snapped);
1961 s->pushUiEvent(
id, kUiGestureEnd, 0.0);
1963 s->requestUiFlush();
1966 static void cbGuiBeginEdit(
void* context,
int index)
noexcept
1968 auto* s =
static_cast<Plugin*
>(context);
1969 s->guiEditActive[
static_cast<size_t>(index)] =
true;
1970 s->pushUiEvent(
hash32(P::parameters[
static_cast<size_t>(index)].id),
1971 kUiGestureBegin, 0.0);
1972 s->requestUiFlush();
1975 static void cbGuiEndEdit(
void* context,
int index)
noexcept
1977 auto* s =
static_cast<Plugin*
>(context);
1978 s->guiEditActive[
static_cast<size_t>(index)] =
false;
1979 s->pushUiEvent(
hash32(P::parameters[
static_cast<size_t>(index)].id),
1980 kUiGestureEnd, 0.0);
1981 s->requestUiFlush();
1984 static bool sGuiIsApiSupported(
const clap_plugin_t*,
const char* api,
1985 bool isFloating)
noexcept
1987 return !isFloating && api !=
nullptr && std::strcmp(api, clapWindowApi()) == 0
1991 static bool sGuiGetPreferredApi(
const clap_plugin_t*,
const char** api,
1992 bool* isFloating)
noexcept
1994 if (api ==
nullptr || isFloating ==
nullptr)
return false;
1995 *api = clapWindowApi();
1996 *isFloating =
false;
2000 static bool sGuiCreate(
const clap_plugin_t* p,
const char* api,
2001 bool isFloating)
noexcept
2004 if (!sGuiIsApiSupported(p, api, isFloating))
return false;
2005#if defined(__linux__)
2008 s->hostTimer = s->host !=
nullptr
2009 ?
static_cast<const clap_host_timer_support_t*
>(
2010 s->host->get_extension(s->host, CLAP_EXT_TIMER_SUPPORT))
2012 if (s->hostTimer ==
nullptr || s->hostTimer->register_timer ==
nullptr
2013 || !s->hostTimer->register_timer(s->host, 33, &s->guiTimerId))
2016 s->hostTimer =
nullptr;
2017 s->guiTimerId = CLAP_INVALID_ID;
2023 const EditorSize logical = s->editorMemory.current();
2024 s->guiWidth =
toBoundedInt(logical.width * s->guiScale + 0.5,
2026 s->guiHeight =
toBoundedInt(logical.height * s->guiScale + 0.5,
2028 s->guiActive =
true;
2030 s->guiWidth, s->guiHeight, s->guiScale);
2034 static void sGuiDestroy(
const clap_plugin_t* p)
noexcept
2037#if defined(__linux__)
2038 if (s->hostTimer !=
nullptr && s->guiTimerId != CLAP_INVALID_ID)
2039 s->hostTimer->unregister_timer(s->host, s->guiTimerId);
2040 s->hostTimer =
nullptr;
2041 s->guiTimerId = CLAP_INVALID_ID;
2045 int parentW = 0, parentH = 0;
2046 if (s->guiEditor.created() && s->guiEditor.queryParentSize(parentW, parentH))
2050 constrainEditorSize<P>(w, h, s->guiScale);
2051 s->editorMemory.remember(w / s->guiScale, h / s->guiScale);
2053 s->guiEditor.destroy();
2054 s->guiActive =
false;
2057 static bool sGuiSetScale(
const clap_plugin_t* p,
double scale)
noexcept
2059#if defined(__APPLE__)
2060 (void) p; (void) scale;
2064 if (!(scale > 0.0))
return false;
2067 const double previous = s->guiScale;
2068 s->guiScale = scale;
2069 s->guiWidth =
toBoundedInt(s->guiWidth * (scale / previous) + 0.5,
2071 s->guiHeight =
toBoundedInt(s->guiHeight * (scale / previous) + 0.5,
2073 s->guiEditor.setBounds(s->guiWidth, s->guiHeight);
2078 static bool sGuiGetSize(
const clap_plugin_t* p, uint32_t* width,
2079 uint32_t* height)
noexcept
2082 if (width ==
nullptr || height ==
nullptr || !s->guiActive)
return false;
2083 *width =
static_cast<uint32_t
>(s->guiWidth);
2084 *height =
static_cast<uint32_t
>(s->guiHeight);
2088 static bool sGuiCanResize(
const clap_plugin_t*)
noexcept
2093 static bool sGuiGetResizeHints(
const clap_plugin_t*,
2094 clap_gui_resize_hints_t* hints)
noexcept
2096 if (hints ==
nullptr)
return false;
2098 const EditorSize logical = editorSizeOf<P>();
2102 hints->aspect_ratio_width =
static_cast<uint32_t
>(logical.width);
2103 hints->aspect_ratio_height =
static_cast<uint32_t
>(logical.height);
2107 static bool sGuiAdjustSize(
const clap_plugin_t* p, uint32_t* width,
2108 uint32_t* height)
noexcept
2111 if (width ==
nullptr || height ==
nullptr)
return false;
2114 constrainEditorSize<P>(w, h, s->guiScale);
2115 *width =
static_cast<uint32_t
>(
2117 *height =
static_cast<uint32_t
>(
2122 static bool sGuiSetSize(
const clap_plugin_t* p, uint32_t width,
2123 uint32_t height)
noexcept
2126 if (!s->guiActive)
return false;
2130 constrainEditorSize<P>(w, h, s->guiScale);
2134 s->guiEditor.setBounds(s->guiWidth, s->guiHeight);
2137 s->editorMemory.remember(s->guiWidth / s->guiScale, s->guiHeight / s->guiScale);
2141 static bool sGuiSetParent(
const clap_plugin_t* p,
2142 const clap_window_t* window)
noexcept
2145 if (window ==
nullptr || !s->guiActive)
return false;
2146#if defined(__linux__)
2148 void* parentHandle =
reinterpret_cast<void*
>(
2149 static_cast<std::uintptr_t
>(window->x11));
2151 void* parentHandle = window->ptr;
2154 parentHandle, s->guiWidth, s->guiHeight);
2155 const webview_ui::HostCallbacks callbacks {
2156 s, &cbGuiSetParam, &cbGuiBeginEdit, &cbGuiEndEdit
2158 if (!s->guiEditor.create(parentHandle, s->shadow, callbacks))
2162 int parentW = 0, parentH = 0;
2163 if (s->guiEditor.queryParentSize(parentW, parentH))
2165 s->guiWidth = parentW;
2166 s->guiHeight = parentH;
2168 s->guiEditor.setBounds(s->guiWidth, s->guiHeight);
2172 static bool sGuiSetTransient(
const clap_plugin_t*,
const clap_window_t*)
noexcept
2177 static void sGuiSuggestTitle(
const clap_plugin_t*,
const char*)
noexcept {}
2179 static bool sGuiShow(
const clap_plugin_t* p)
noexcept
2181 self(p)->guiEditor.setVisible(
true);
2185 static bool sGuiHide(
const clap_plugin_t* p)
noexcept
2187 self(p)->guiEditor.setVisible(
false);
2191 inline static const clap_plugin_gui_t kGui = {
2192 &sGuiIsApiSupported, &sGuiGetPreferredApi, &sGuiCreate, &sGuiDestroy,
2193 &sGuiSetScale, &sGuiGetSize, &sGuiCanResize, &sGuiGetResizeHints,
2194 &sGuiAdjustSize, &sGuiSetSize, &sGuiSetParent, &sGuiSetTransient,
2195 &sGuiSuggestTitle, &sGuiShow, &sGuiHide
2198#if defined(__linux__)
2202 static void sOnTimer(
const clap_plugin_t* p, clap_id)
noexcept
2204 self(p)->guiEditor.pump();
2207 inline static const clap_plugin_timer_support_t kTimer = { &sOnTimer };
2216 static const char* features[] = {
2218 : CLAP_PLUGIN_FEATURE_AUDIO_EFFECT,
2220 ? CLAP_PLUGIN_FEATURE_MONO : CLAP_PLUGIN_FEATURE_STEREO,
2223 static const clap_plugin_descriptor_t desc = {
2225 P::descriptor.productId,
2227 P::descriptor.vendor,
2231 P::descriptor.version,
2232 "Built with DSPark",
2238 static const clap_plugin_t*
create(
const clap_host_t*
host)
noexcept
2241 if (s ==
nullptr)
return nullptr;
2243 s->plugin.plugin_data = s;
2244 s->plugin.init = &
sInit;
2250 s->plugin.reset = &
sReset;
2258template <
typename P>
2261 static uint32_t
sCount(
const clap_plugin_factory_t*)
noexcept {
return 1; }
2263 static const clap_plugin_descriptor_t*
sDescriptor(
const clap_plugin_factory_t*,
2264 uint32_t index)
noexcept
2269 static const clap_plugin_t*
sCreate(
const clap_plugin_factory_t*,
2270 const clap_host_t* host,
2271 const char* pluginId)
noexcept
2273 if (pluginId ==
nullptr
2274 || std::strcmp(pluginId, P::descriptor.productId) != 0)
2295 static const std::array<char, 256>
id = [] {
2296 std::array<char, 256> buf {};
2297 std::snprintf(buf.data(), buf.size(),
"%s.presets",
2298 P::descriptor.productId);
2306 static const clap_preset_discovery_provider_descriptor_t desc = {
2307 CLAP_VERSION_INIT,
providerId(),
"DSPark Factory Presets",
2308 P::descriptor.vendor
2316 const clap_preset_discovery_indexer_t*
indexer =
nullptr;
2319 static bool sProviderInit(
const clap_preset_discovery_provider_t* provider)
noexcept
2321 const auto* state =
static_cast<const ProviderState*
>(provider->provider_data);
2322 if (state->indexer ==
nullptr || state->indexer->declare_location ==
nullptr)
2324 clap_preset_discovery_location_t location {};
2325 location.flags = CLAP_PRESET_DISCOVERY_IS_FACTORY_CONTENT;
2326 location.name =
"Factory Presets";
2327 location.kind = CLAP_PRESET_DISCOVERY_LOCATION_PLUGIN;
2328 location.location =
nullptr;
2329 return state->
indexer->declare_location(state->indexer, &location);
2334 delete static_cast<ProviderState*
>(provider->provider_data);
2338 uint32_t locationKind,
const char*,
2339 const clap_preset_discovery_metadata_receiver_t*
2344 if (locationKind != CLAP_PRESET_DISCOVERY_LOCATION_PLUGIN
2345 || receiver ==
nullptr)
2347 const clap_universal_plugin_id_t pluginId {
2348 "clap", P::descriptor.productId
2353 std::snprintf(key,
sizeof(key),
"%d", i);
2354 if (!receiver->begin_preset(receiver,
2355 P::factoryPresets[
static_cast<size_t>(i)].name, key))
2357 receiver->add_plugin_id(receiver, &pluginId);
2358 receiver->set_flags(receiver,
2359 CLAP_PRESET_DISCOVERY_IS_FACTORY_CONTENT);
2365 (void) locationKind;
2372 const char*)
noexcept
2379 const clap_preset_discovery_factory_t*, uint32_t index)
noexcept
2385 const clap_preset_discovery_factory_t*,
2386 const clap_preset_discovery_indexer_t* indexer,
2387 const char* providerIdAsked)
noexcept
2389 if (
kNumPresets == 0 || indexer ==
nullptr || providerIdAsked ==
nullptr
2390 || std::strcmp(providerIdAsked,
providerId()) != 0)
2393 if (state ==
nullptr)
return nullptr;
2396 state->provider.provider_data = state;
2401 return &state->provider;
2413 if (factoryId ==
nullptr)
return nullptr;
2414 if (std::strcmp(factoryId, CLAP_PLUGIN_FACTORY_ID) == 0)
2417 && (std::strcmp(factoryId, CLAP_PRESET_DISCOVERY_FACTORY_ID) == 0
2418 || std::strcmp(factoryId, CLAP_PRESET_DISCOVERY_FACTORY_ID_COMPAT) == 0))
2431#define DSPARK_CLAP_PLUGIN(PluginClass) \
2432 extern "C" CLAP_EXPORT const clap_plugin_entry_t clap_entry = { \
2433 CLAP_VERSION_INIT, \
2434 &dspark::plugin::clap_backend::Factory<PluginClass>::sEntryInit, \
2435 &dspark::plugin::clap_backend::Factory<PluginClass>::sEntryDeinit, \
2436 &dspark::plugin::clap_backend::Factory<PluginClass>::sEntryGetFactory \
2439#pragma pop_macro("max")
2440#pragma pop_macro("min")
Non-owning view over audio channel data.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
The notes a backend has delivered as sounding, per channel and key, with the host note id each starte...
void noteOn(int channel, int key, int32_t noteId) noexcept
void releaseMatching(int channel, int key, int32_t noteId, Off &&off) noexcept
int32_t noteIdOf(int channel, int key) const noexcept
void noteOff(int channel, int key) noexcept
The fixed-capacity, allocation-free event list one block of host events is collected into (a member o...
int size() const noexcept
The dry signal of the wrappers' soft bypass, delayed by the plugin's latency.
The editor size the user last left, in logical pixels, kept by each backend across editor re-opens an...
Parameter changes made OFF the audio thread, handed to it.
bool drain(Apply &&apply) noexcept
void mark(size_t index) noexcept
The voices this backend started (one per NoteOn it delivered), with the host's modulation amount of e...
static constexpr int kCapacity
VoiceParams & paramsOf(int slot) noexcept
int oldest() const noexcept
void release(int slot) noexcept
void forEachMatching(int port, int channel, int key, int32_t noteId, Fn &&fn) noexcept
int start(int channel, int key, int32_t noteId) noexcept
Voice & operator[](int slot) noexcept
One embedded WebView editor instance for plugin class P. Owned by the format backends (the VST3 IPlug...
static bool available() noexcept
void setBounds(int width, int height) noexcept
Custom-editor switch. With hasEditor = false (or absent) hosts show their generic parameter UI....
MIDI capability: void handleMidiEvent(const MidiEvent&) noexcept. Its presence grows a note/event inp...
Render-mode capability: void setOfflineRendering(bool) noexcept. The host flips it to true for non-re...
Sidechain capability. Implement the two-buffer process - the same shape DSPark's own dynamics take:
Transport capability: void setTransport(const TransportInfo&) noexcept. Called on the audio thread,...
Optional voice query: bool isVoiceActive(int channel, int key, int32_t noteId) const noexcept - true ...
constexpr int kBypassRampSamples
constexpr uint32_t kBypassParamId
void debugLog(const char *format,...) noexcept
constexpr std::array< Param, sizeof...(Ps)> params(Ps... ps) noexcept
Builds the parameter table (use inside static constexpr auto).
EditorResize
How the host may resize the editor window. Declare static constexpr EditorResize editorResize = ....
@ Fixed
The window is exactly editorSize; hosts cannot drag-resize it.
@ KeepAspect
Drag-resizable, locked to the declared width:height ratio.
@ Instrument
Audio generator (MIDI in -> audio out, no audio input).
constexpr double kEditorMaxPixels
Pixel ceiling for a negotiated editor size.
constexpr size_t kMaxStateBytes
Largest state a backend reads back (1 GiB). It only bounds a hostile, endless host stream: getState()...
constexpr Param toggle(const char *id, const char *name, bool defaultOn) noexcept
On/off parameter helper.
std::vector< uint8_t > buildState(const P &user, const double *normalized, size_t numParams, int programIndex=-1, int bypassState=-1, const EditorSize *editorSize=nullptr)
Serialises the plugin state: every parameter (normalized), the active factory preset (programIndex,...
constexpr int kDryDelayMinCapacity
Ring headroom of the bypass dry path: latencies up to this (or twice the latency at activation,...
constexpr uint32_t expressionBit(MidiEvent::ExpressionType type) noexcept
The bit of one ExpressionType in a note-expression mask.
constexpr double toNormalized(const Param &p, double plain) noexcept
Plain [min, max] -> normalized [0, 1] (steps snap on the way back).
constexpr double toPlain(const Param &p, double normalized) noexcept
Normalized [0, 1] -> plain [min, max], snapped for stepped params.
int parseToggleText(const char *text) noexcept
Case-insensitive "On"/"Off" recognition - the inverse of the toggle display below....
constexpr int kAutomationQuantum
Sub-block grain: automation/event splits snap to this many frames (bounds the per-call overhead; ~0....
constexpr uint32_t hash32(const char *s) noexcept
FNV-1a 32-bit over a C string - the per-parameter host id.
constexpr int kMaxBlockEvents
Capacity of the per-block event list. Past it the list merges rather than drops: an intermediate para...
bool applyState(P &user, const uint8_t *data, size_t size, double *normalized, int *programIndex=nullptr, int *bypassState=nullptr, EditorSize *editorSize=nullptr)
Parses a state blob; fills normalized (defaults pre-loaded by the caller, see loadDefaultNormalized),...
void formatValue(const Param &p, double plain, char *out, int outSize) noexcept
Formats a plain value for host display ("3.5 dB", "On", "Saw", "4").
@ MonoOnly
Strictly 1->1 (rare; metering/utility plugins).
@ MonoAndStereo
Negotiates 1->1 or 2->2 with the host (default).
constexpr int toBoundedInt(double value, int lo, int hi) noexcept
A floating value from outside converted to an integer, with the range settled BEFORE the conversion.
bool parseValue(const Param &p, const char *text, double &plain) noexcept
Host text -> plain value, the inverse of formatValue(): a choice's label (any case),...
Describes the audio environment for a DSP processor.
One timestamped in-block event, normalised across formats: a parameter point, a bypass point,...
int32_t offset
Frame position within the block.
MidiEvent midi
Kind::Midi payload.
Editor window size in logical pixels (physical = logical x host scale).
One incoming MIDI-ish event, normalised across formats.
ExpressionType
The per-voice expressions of Type::NoteExpression.
@ NoteOn
note = key, value = velocity 0..1.
@ NoteExpression
One voice: expression, value (see above).
@ PolyPressure
note = key, value = pressure 0..1.
@ NoteOff
note = key, value = release velocity 0..1.
@ NoteModulation
One voice: parameters[param] heard, plain units.
@ ControlChange
note = controller number, value = 0..1.
@ ChannelPressure
value = pressure 0..1 (note unused).
@ PitchBend
value = bend -1..+1 (note unused).
float value
Velocity / CC / pressure 0..1; bend -1..+1.
int sampleOffset
Frames into the NEXT processBlock call.
uint8_t note
Key 0..127, or controller number for CC.
int32_t noteId
Host voice id of the note (-1: none given).
One automatable parameter. Plain values run [min, max]; hosts see the normalized [0,...
Host transport snapshot, delivered once per audio block.
bool playing
Transport is rolling.
const clap_preset_discovery_indexer_t * indexer
clap_preset_discovery_provider_t provider
static bool sProviderInit(const clap_preset_discovery_provider_t *provider) noexcept
static const clap_preset_discovery_provider_descriptor_t * providerDescriptor() noexcept
static constexpr int kNumPresets
static const char * providerId() noexcept
static const void * sEntryGetFactory(const char *factoryId) noexcept
static const clap_preset_discovery_provider_t * sDiscoveryCreate(const clap_preset_discovery_factory_t *, const clap_preset_discovery_indexer_t *indexer, const char *providerIdAsked) noexcept
static void sEntryDeinit() noexcept
static uint32_t sDiscoveryCount(const clap_preset_discovery_factory_t *) noexcept
static uint32_t sCount(const clap_plugin_factory_t *) noexcept
static bool sProviderGetMetadata(const clap_preset_discovery_provider_t *, uint32_t locationKind, const char *, const clap_preset_discovery_metadata_receiver_t *receiver) noexcept
static void sProviderDestroy(const clap_preset_discovery_provider_t *provider) noexcept
static bool sEntryInit(const char *) noexcept
static const clap_preset_discovery_provider_descriptor_t * sDiscoveryDescriptor(const clap_preset_discovery_factory_t *, uint32_t index) noexcept
static const clap_plugin_factory_t kFactory
static const void * sProviderGetExtension(const clap_preset_discovery_provider_t *, const char *) noexcept
static const clap_preset_discovery_factory_t kDiscoveryFactory
static const clap_plugin_t * sCreate(const clap_plugin_factory_t *, const clap_host_t *host, const char *pluginId) noexcept
static const clap_plugin_descriptor_t * sDescriptor(const clap_plugin_factory_t *, uint32_t index) noexcept
static uint32_t sConfigCount(const clap_plugin_t *) noexcept
static void sStopProcessing(const clap_plugin_t *) noexcept
std::atomic< int > cachedLatency
const clap_host_params_t * hostParams
static void sReset(const clap_plugin_t *p) noexcept
std::atomic< int > currentProgram
static const clap_plugin_audio_ports_t kAudioPorts
static constexpr int kNumPresets
static bool sConfigSelect(const clap_plugin_t *p, clap_id configId) noexcept
static const clap_plugin_state_t kState
static Plugin * self(const clap_plugin_t *p) noexcept
EndedVoice endedVoices[kMaxEndedVoices]
const clap_host_preset_load_t * hostPresetLoad
static uint32_t sParamCount(const clap_plugin_t *) noexcept
static bool sParamValue(const clap_plugin_t *p, clap_id id, double *out) noexcept
void endVoice(int slot) noexcept
static uint32_t sNotePortCount(const clap_plugin_t *, bool isInput) noexcept
static bool sConfigInfoGet(const clap_plugin_t *p, clap_id configId, uint32_t portIndex, bool isInput, clap_audio_port_info_t *info) noexcept
static clap_process_status sProcess(const clap_plugin_t *p, const clap_process_t *process) noexcept
void forwardTransport(const clap_event_transport_t *t) noexcept
static bool sPortGet(const clap_plugin_t *p, uint32_t index, bool isInput, clap_audio_port_info_t *info) noexcept
std::vector< float > dryR
static const clap_plugin_latency_t kLatency
static bool sActivate(const clap_plugin_t *p, double sr, uint32_t, uint32_t maxFrames) noexcept
static constexpr int kMaxEndedVoices
void deliverToVoice(MidiEvent midi, int channel, int key, int32_t noteId) noexcept
static void sDeactivate(const clap_plugin_t *p) noexcept
Plugin(const clap_host_t *h) noexcept
static void sOnMainThread(const clap_plugin_t *p) noexcept
static bool sRenderSet(const clap_plugin_t *p, clap_plugin_render_mode mode) noexcept
static constexpr bool kIsInstrument
void applyFactoryPresetIdx(int idx) noexcept
std::vector< float > silence
static uint32_t sTailGet(const clap_plugin_t *p) noexcept
void refreshLatency() noexcept
static bool sNotePortGet(const clap_plugin_t *, uint32_t index, bool isInput, clap_note_port_info_t *info) noexcept
static clap_id sConfigCurrent(const clap_plugin_t *p) noexcept
static constexpr size_t kNumParams
static constexpr size_t kNumPerVoice
VoiceTable< kNumPerVoice > voices
The voices delivered so far, for per-voice events (audio thread).
BlockEventList blockEvents
const clap_host_latency_t * hostLatency
std::atomic< bool > bypass
double heardPlain(int index, double normalized) const noexcept
std::atomic< double > shadow[kNumParams==0 ? 1 :kNumParams]
void pollVoices() noexcept
void trackVoice(const MidiEvent &midi) noexcept
EditorSizeMemory< P > editorMemory
static bool sStateSave(const clap_plugin_t *p, const clap_ostream_t *stream) noexcept
bool drainPending() noexcept
static const clap_plugin_audio_ports_config_t kPortsConfig
static void sDestroy(const clap_plugin_t *p) noexcept
std::atomic< bool > latencyDirty
void requestParamFlush() noexcept
static bool sParamTextToValue(const clap_plugin_t *, clap_id id, const char *text, double *out) noexcept
std::vector< float > dryL
void applyVoiceEvent(const BlockEvent &ev, MidiEvent midi) noexcept
void applyNormalized(int index, double normalized) noexcept
static void sParamFlush(const clap_plugin_t *p, const clap_input_events_t *in, const clap_output_events_t *out) noexcept
static const clap_plugin_render_t kRender
double modulation[kNumParams==0 ? 1 :kNumParams]
Host modulation amount per parameter, plain units (audio thread).
static const clap_plugin_audio_ports_config_info_t kPortsConfigInfo
bool applyBlockEvent(const BlockEvent &ev, int blockStart) noexcept
double voiceHeardPlain(int index, int slot, const Params ¶ms) const noexcept
static bool sRenderHardRealtime(const clap_plugin_t *) noexcept
static const void * sGetExtension(const clap_plugin_t *, const char *id) noexcept
void collectEvents(const clap_input_events_t *in, uint32_t numSamples, BlockEventList &events) noexcept
static bool sPresetFromLocation(const clap_plugin_t *p, uint32_t locationKind, const char *location, const char *loadKey) noexcept
static bool sParamInfo(const clap_plugin_t *, uint32_t index, clap_param_info_t *info) noexcept
static const clap_plugin_descriptor_t * descriptor() noexcept
double voiceHeardPlain(int index, bool valued, double value, bool modulated, double amount) const noexcept
static bool sInit(const clap_plugin_t *p) noexcept
static bool sStartProcessing(const clap_plugin_t *p) noexcept
static const clap_plugin_t * create(const clap_host_t *host) noexcept
void flushEndedVoices(const clap_output_events_t *out, uint32_t time) noexcept
bool applyFromUi(int index, double normalized) noexcept
static int indexOfParamId(uint32_t id) noexcept
static uint32_t sLatencyGet(const clap_plugin_t *p) noexcept
static const clap_plugin_preset_load_t kPresetLoad
static constexpr bool isIntegerGrid(const Param &spec) noexcept
static const clap_plugin_params_t kParams
void collectEvent(const clap_event_header_t *ev, uint32_t numSamples, BlockEventList &events) noexcept
static const clap_plugin_tail_t kTail
static bool sStateLoad(const clap_plugin_t *p, const clap_istream_t *stream) noexcept
PendingParams< kNumParams > pending
void resendVoiceModulation(int index, int sampleOffset, bool modulationMoved) noexcept
static void fillConfig(clap_audio_ports_config_t *config, int width) noexcept
std::atomic< bool > active
static bool sParamValueToText(const clap_plugin_t *, clap_id id, double value, char *out, uint32_t size) noexcept
static bool sConfigGet(const clap_plugin_t *, uint32_t index, clap_audio_ports_config_t *config) noexcept
void blendBypass(float *const *out, float *const *dry, uint32_t nCh, int outStart, int dryStart, int length) noexcept
static uint32_t sPortCount(const clap_plugin_t *, bool isInput) noexcept
static const clap_plugin_note_ports_t kNotePorts
static constexpr bool kHasPerVoice
What the host set for each perVoice() parameter of one voice.
std::array< bool, kSlots > valued
std::array< bool, kSlots > modulated
std::array< double, kSlots > amount
static constexpr size_t kSlots
std::array< double, kSlots > value
Per-note automation: the voice's own plain value of the parameter.
A voice's identity (the part every scan reads; kept small).
bool held
false once its NoteOff arrived
uint32_t serial
start order, for choosing the oldest