iPlug2 - C++ Audio Plug-in Framework
Loading...
Searching...
No Matches
IPlugCLAP.cpp
1/*
2 ==============================================================================
3
4 This file is part of the iPlug 2 library. Copyright (C) the iPlug 2 developers.
5
6 See LICENSE.txt for more info.
7
8 ==============================================================================
9*/
10
11#include <algorithm>
12#include <cstdio>
13
14#include "IPlugCLAP.h"
15#include "IPlugPluginBase.h"
16#include "plugin.hxx"
17#include "host-proxy.hxx"
18
19// TODO - respond to situations in which parameters can't be pushed (search try_push)
20// Keep in the queue or discard?? - up to us?
21
22using namespace iplug;
23
24void ClapNameCopy(char* destination, const char* source)
25{
26 strncpy(destination, source, CLAP_NAME_SIZE);
27 destination[CLAP_NAME_SIZE - 1] = 0;
28}
29
30IPlugCLAP::IPlugCLAP(const InstanceInfo& info, const Config& config)
31 : IPlugAPIBase(config, kAPICLAP)
32 , IPlugProcessor(config, kAPICLAP)
33 , ClapPluginHelper(info.mDesc, info.mHost)
34{
35 Trace(TRACELOC, "%s", config.pluginName);
36
37 int version = 0;
38
39 if (CStringHasContents(info.mHost->version))
40 {
41 // TODO - check host version string
42 int ver, rmaj, rmin;
43 sscanf(info.mHost->version, "%d.%d.%d", &ver, &rmaj, &rmin);
44 version = (ver << 16) + (rmaj << 8) + rmin;
45 }
46
47 // Create space to store audio pointers
48 int nChans = RequiredChannels();
49 mAudioIO32.Resize(nChans);
50 mAudioIO64.Resize(nChans);
51
52 SetHost(info.mHost->name, version);
53 CreateTimer();
54}
55
56uint32_t IPlugCLAP::tailGet() const noexcept
57{
58 return GetTailIsInfinite() ? std::numeric_limits<uint32_t>::max() : GetTailSize();
59}
60
61void IPlugCLAP::FlushParamsIfNeeded()
62{
63 if (!isProcessing())
64 runOnMainThread([&](){ if (!isBeingDestroyed()) GetClapHost().paramsRequestFlush(); });
65}
66
68{
69 mParamValuesToHost.PushFromArgs(ParamToHost::Type::Begin, idx, 0.0);
70 FlushParamsIfNeeded();
71}
72
73void IPlugCLAP::InformHostOfParamChange(int idx, double normalizedValue)
74{
75 const IParam* pParam = GetParam(idx);
76 const bool isDoubleType = pParam->Type() == IParam::kTypeDouble;
77 const double value = isDoubleType ? normalizedValue : pParam->FromNormalized(normalizedValue);
78
79 mParamValuesToHost.PushFromArgs(ParamToHost::Type::Value, idx, value);
80 FlushParamsIfNeeded();
81}
82
84{
85 mParamValuesToHost.PushFromArgs(ParamToHost::Type::End, idx, 0.0);
86 FlushParamsIfNeeded();
87}
88
89bool IPlugCLAP::EditorResize(int viewWidth, int viewHeight)
90{
91 if (HasUI())
92 {
93 if (viewWidth != GetEditorWidth() || viewHeight != GetEditorHeight())
94 {
95 GetClapHost().guiRequestResize(viewWidth, viewHeight);
96 }
97
98 SetEditorSize(viewWidth, viewHeight);
99 }
100
101 return true;
102}
103
104// IPlugProcessor
105void IPlugCLAP::SetTailSize(int samples)
106{
108
109 if (GetClapHost().canUseTail())
110 mTailUpdate = true;
111}
112
113void IPlugCLAP::SetLatency(int samples)
114{
116
117 if (GetClapHost().canUseLatency())
118 {
119 // clap_host_latency::changed() may only be called from within activate(),
120 // so record the change and report it on the next activation, requesting a
121 // restart if the plugin is currently active.
122 mLatencyUpdate = true;
123 if (isActive())
124 runOnMainThread([&](){ if (!isBeingDestroyed()) GetClapHost().requestRestart(); });
125 }
126}
127
129{
130 mMidiToHost.Add(msg);
131 return true;
132}
133
135{
136 // TODO - don't copy the data
137 SysExData data(msg.mOffset, msg.mSize, msg.mData);
138 mSysExToHost.Add(data);
139 return true;
140}
141
142// clap_plugin
143bool IPlugCLAP::init() noexcept
144{
145 SetDefaultConfig();
146
147 return true;
148}
149
150bool IPlugCLAP::activate(double sampleRate, uint32_t minFrameCount, uint32_t maxFrameCount) noexcept
151{
152 SetBlockSize(maxFrameCount);
153 SetSampleRate(sampleRate);
154 OnActivate(true);
155 OnParamReset(kReset);
156 OnReset();
157
158 if (mLatencyUpdate)
159 {
160 GetClapHost().latencyChanged();
161 mLatencyUpdate = false;
162 }
163
164 mHostHasTail = GetClapHost().canUseTail();
165 mTailCount = 0;
166
167 return true;
168}
169
170void IPlugCLAP::deactivate() noexcept
171{
172 OnActivate(false);
173
174 // TODO - should we clear mTailUpdate here or elsewhere?
175}
176
177template <typename T>
178const T* ClapEventCast(const clap_event_header_t* event)
179{
180 return reinterpret_cast<const T*>(event);
181}
182
183template <typename T>
184bool InputIsSilent(const T* data, int nFrames)
185{
186 // For local tail processing find non-zero inputs
187 auto isZero = [](T x) { return x == T(0); };
188
189 return std::find_if_not(data, data + nFrames, isZero) == (data + nFrames);
190}
191
192clap_process_status IPlugCLAP::process(const clap_process* pProcess) noexcept
193{
194 IMidiMsg msg;
195 SysExData sysEx;
196
197 // Transport Info
198 if (pProcess->transport)
199 {
200 ITimeInfo timeInfo;
201
202 auto pTransport = pProcess->transport;
203
204 constexpr double beatFactor = static_cast<double>(CLAP_BEATTIME_FACTOR);
205 constexpr double secFactor = static_cast<double>(CLAP_SECTIME_FACTOR);
206
207 if (pTransport->flags & CLAP_TRANSPORT_HAS_TEMPO)
208 timeInfo.mTempo = pTransport->tempo;
209
210 // N.B. If there is no seconds timeline there is no way to get the sample position (the plugin one is not global)
211 if (pTransport->flags & CLAP_TRANSPORT_HAS_SECONDS_TIMELINE)
212 timeInfo.mSamplePos = (GetSampleRate() * static_cast<double>(pTransport->song_pos_seconds) / secFactor);
213
214 if (pTransport->flags & CLAP_TRANSPORT_HAS_BEATS_TIMELINE)
215 {
216 timeInfo.mPPQPos = static_cast<double>(pTransport->song_pos_beats) / beatFactor;
217 timeInfo.mLastBar = static_cast<double>(pTransport->bar_start) / beatFactor;
218 timeInfo.mCycleStart = static_cast<double>(pTransport->loop_start_beats) / beatFactor;
219 timeInfo.mCycleEnd = static_cast<double>(pTransport->loop_end_beats) / beatFactor;
220 }
221
222 if (pTransport->flags & CLAP_TRANSPORT_HAS_TIME_SIGNATURE)
223 {
224 timeInfo.mNumerator = static_cast<int>(pTransport->tsig_num);
225 timeInfo.mDenominator = static_cast<int>(pTransport->tsig_denom);
226 }
227
228 timeInfo.mTransportIsRunning = pTransport->flags & CLAP_TRANSPORT_IS_PLAYING;
229 timeInfo.mTransportLoopEnabled = pTransport->flags & CLAP_TRANSPORT_IS_LOOP_ACTIVE;
230
231 SetTimeInfo(timeInfo);
232 }
233
234 // Input Events
235 ProcessInputEvents(pProcess->in_events);
236
237 while (mMidiMsgsFromEditor.Pop(msg))
238 {
239 ProcessMidiMsg(msg);
240 }
241
242 while (mSysExDataFromEditor.Pop(sysEx))
243 {
244 SendSysEx(ISysEx(sysEx.mOffset, sysEx.mData, sysEx.mSize));
245 }
246
247 // Do Audio Processing!
248 int nIns = 0;
249 int nOuts = 0;
250 int nFrames = pProcess->frames_count;
251
252 // Local tail handling
253 bool localTail = !mHostHasTail && !GetTailIsInfinite() && GetTailSize();
254 bool insQuiet = true;
255
256 // Sum IO channels
257 for (uint32_t i = 0; i < pProcess->audio_inputs_count; i++)
258 nIns += static_cast<int>(pProcess->audio_inputs[i].channel_count);
259
260 for (uint32_t i = 0; i < pProcess->audio_outputs_count; i++)
261 nOuts += static_cast<int>(pProcess->audio_outputs[i].channel_count);
262
263 // Check the format
264 bool format64 = false;
265
266 if (pProcess->audio_inputs_count && pProcess->audio_inputs && pProcess->audio_inputs[0].channel_count)
267 format64 = pProcess->audio_inputs[0].data64;
268 else if (pProcess->audio_outputs_count && pProcess->audio_outputs && pProcess->audio_outputs[0].channel_count)
269 format64 = pProcess->audio_outputs[0].data64;
270
271 // Assert that all formats match
272#ifndef NDEBUG
273 for (uint32_t i = 0; i < pProcess->audio_inputs_count; i++)
274 {
275 auto bus = pProcess->audio_inputs[i];
276 assert(!bus.channel_count || format64 == static_cast<bool>(bus.data64));
277 }
278
279 for (uint32_t i = 0; i < pProcess->audio_outputs_count; i++)
280 {
281 auto bus = pProcess->audio_outputs[i];
282 assert(!bus.channel_count || format64 == static_cast<bool>(bus.data64));
283 }
284#endif
285
286 SetChannelConnections(ERoute::kInput, 0, MaxNChannels(ERoute::kInput), false);
287 SetChannelConnections(ERoute::kInput, 0, nIns, true);
288
289 if (nIns > 0)
290 {
291 // Copy and attach buffer pointers
292 if (format64)
293 {
294 for (uint32_t i = 0, k = 0; i < pProcess->audio_inputs_count; i++)
295 {
296 auto bus = pProcess->audio_inputs[i];
297
298 for (uint32_t j = 0; j < bus.channel_count; j++, k++)
299 {
300 mAudioIO64.Get()[k] = bus.data64[j];
301
302 // For local tail processing check for non-zero inputs
303
304 if (localTail && insQuiet)
305 insQuiet = InputIsSilent(bus.data64[j], nFrames);
306 }
307 }
308
309 AttachBuffers(ERoute::kInput, 0, nIns, mAudioIO64.Get(), nFrames);
310 }
311 else
312 {
313 for (uint32_t i = 0, k = 0; i < pProcess->audio_inputs_count; i++)
314 {
315 auto bus = pProcess->audio_inputs[i];
316
317 for (uint32_t j = 0; j < bus.channel_count; j++, k++)
318 {
319 mAudioIO32.Get()[k] = bus.data32[j];
320
321 // For local tail processing check for non-zero inputs
322 if (localTail && insQuiet)
323 insQuiet = InputIsSilent(bus.data32[j], nFrames);
324 }
325 }
326
327 AttachBuffers(ERoute::kInput, 0, nIns, mAudioIO32.Get(), nFrames);
328 }
329 }
330
331 SetChannelConnections(ERoute::kOutput, 0, MaxNChannels(ERoute::kOutput), false);
332 SetChannelConnections(ERoute::kOutput, 0, nOuts, true);
333
334 if (nOuts > 0)
335 {
336 // Copy and attach buffer pointers
337 if (format64)
338 {
339 for (uint32_t i = 0, k = 0; i < pProcess->audio_outputs_count; i++)
340 {
341 auto bus = pProcess->audio_outputs[i];
342 for (uint32_t j = 0; j < bus.channel_count; j++, k++)
343 mAudioIO64.Get()[k] = bus.data64[j];
344 }
345
346 AttachBuffers(ERoute::kOutput, 0, nOuts, mAudioIO64.Get(), nFrames);
347 }
348 else
349 {
350 for (uint32_t i = 0, k = 0; i < pProcess->audio_outputs_count; i++)
351 {
352 auto bus = pProcess->audio_outputs[i];
353 for (uint32_t j = 0; j < bus.channel_count; j++, k++)
354 mAudioIO32.Get()[k] = bus.data32[j];
355 }
356
357 AttachBuffers(ERoute::kOutput, 0, nOuts, mAudioIO32.Get(), nFrames);
358 }
359 }
360
361 if (format64)
362 ProcessBuffers(0.0, nFrames);
363 else
364 ProcessBuffers(0.f, nFrames);
365
366 // Send Events Out (Parameters and MIDI)
367 ProcessOutputEvents(pProcess->out_events, nFrames);
368
369 // Update tail if relevant
370 if (mTailUpdate)
371 {
372 GetClapHost().tailChanged();
373 mTailUpdate = false;
374 }
375
376 // Local tail handling
377 if (mHostHasTail)
378 return CLAP_PROCESS_TAIL;
379
380#if PLUG_TYPE == 0 // Only implement local tail for effects
381 // No tail
382 if (!GetTailSize())
383 return CLAP_PROCESS_CONTINUE_IF_NOT_QUIET;
384
385 // Infinite tail
386 if (GetTailIsInfinite())
387 return CLAP_PROCESS_CONTINUE;
388
389 // Finite tail
390 mTailCount = insQuiet ? std::min(mTailCount + nFrames, GetTailSize()) : 0;
391
392 return mTailCount < GetTailSize() ? CLAP_PROCESS_CONTINUE : CLAP_PROCESS_SLEEP;
393
394#else
395 return CLAP_PROCESS_CONTINUE;
396#endif
397}
398
399// clap_plugin_render
400bool IPlugCLAP::renderSetMode(clap_plugin_render_mode mode) noexcept
401{
402 SetRenderingOffline(mode == CLAP_RENDER_OFFLINE);
403 return true;
404}
405
406// clap_plugin_state
407bool IPlugCLAP::stateSave(const clap_ostream* pStream) noexcept
408{
409 IByteChunk chunk;
410
411 if (!SerializeState(chunk))
412 return false;
413
414 // clap_ostream::write() may perform a short write (like POSIX write()) --
415 // it isn't required to write the whole buffer in one call, so this must
416 // loop until every byte is written rather than checking a single call's
417 // return value against the full size.
418 const uint8_t* pData = chunk.GetData();
419 int64_t remaining = chunk.Size();
420
421 while (remaining > 0)
422 {
423 const int64_t written = pStream->write(pStream, pData, static_cast<uint64_t>(remaining));
424
425 if (written <= 0)
426 return false;
427
428 pData += written;
429 remaining -= written;
430 }
431
432 return true;
433}
434
435bool IPlugCLAP::stateLoad(const clap_istream* pStream) noexcept
436{
437 constexpr int bytesPerBlock = 256;
438 char buffer[bytesPerBlock];
439 int64_t bytesRead = 0;
440
441 IByteChunk chunk;
442
443 while ((bytesRead = pStream->read(pStream, buffer, bytesPerBlock)) > 0)
444 chunk.PutBytes(buffer, static_cast<int>(bytesRead));
445
446 if (bytesRead != 0)
447 return false;
448
449 bool restoredOK = UnserializeState(chunk, 0) >= 0;
450
451 if (restoredOK)
452 {
453 OnRestoreState();
454
455 if (GetClapHost().canUseParams())
456 GetClapHost().paramsRescan(CLAP_PARAM_RESCAN_VALUES);
457 }
458
459 return restoredOK;
460}
461
462// clap_plugin_params
463bool IPlugCLAP::paramsInfo(uint32_t paramIdx, clap_param_info* pInfo) const noexcept
464{
465 assert(MAX_PARAM_NAME_LEN <= CLAP_NAME_SIZE && "iPlug parameter name size exceeds CLAP maximum");
466 assert(MAX_PARAM_GROUP_LEN <= CLAP_PATH_SIZE && "iPlug group name size exceeds CLAP maximum");
467
468 const IParam* pParam = GetParam(paramIdx);
469 const bool isDoubleType = pParam->Type() == IParam::kTypeDouble;
470
471 clap_param_info_flags flags = CLAP_PARAM_REQUIRES_PROCESS; // TO DO - check this with Alex B
472
473 if (!isDoubleType)
474 flags |= CLAP_PARAM_IS_STEPPED;
475 if (pParam->GetCanAutomate())
476 flags |= CLAP_PARAM_IS_AUTOMATABLE;
477
478 pInfo->id = paramIdx;
479 pInfo->flags = flags;
480 pInfo->cookie = nullptr;
481
482 strcpy(pInfo->name, pParam->GetName());
483 strcpy(pInfo->module, pParam->GetGroup());
484
485 // Values
486 pInfo->min_value = isDoubleType ? 0.0 : pParam->GetMin();
487 pInfo->max_value = isDoubleType ? 1.0 : pParam->GetMax();
488 pInfo->default_value = pParam->GetDefault(isDoubleType);
489
490 return true;
491}
492
493bool IPlugCLAP::paramsValue(clap_id paramIdx, double* pValue) noexcept
494{
495 const IParam* pParam = GetParam(paramIdx);
496 const bool isDoubleType = pParam->Type() == IParam::kTypeDouble;
497 *pValue = isDoubleType ? pParam->GetNormalized() : pParam->Value();
498 return true;
499}
500
501bool IPlugCLAP::paramsValueToText(clap_id paramIdx, double value, char* display, uint32_t size) noexcept
502{
503 const IParam* pParam = GetParam(paramIdx);
504 const bool isDoubleType = pParam->Type() == IParam::kTypeDouble;
505
506 WDL_String str;
507
508 // Stepped parameters are exposed to CLAP with plain values, constrain so that display texts are found
509 const double plainValue = isDoubleType ? pParam->FromNormalized(value) : pParam->Constrain(value);
510
511 pParam->GetDisplay(plainValue, false, str);
512
513 // Add Label, unless the value has display text (which wouldn't map back to a value with the label added)
514 if (CStringHasContents(pParam->GetLabel()) && !CStringHasContents(pParam->GetDisplayText(plainValue)))
515 {
516 str.Append(" ");
517 str.Append(pParam->GetLabel());
518 }
519
520 // size includes the null terminator
521 if (size <= static_cast<uint32_t>(str.GetLength()))
522 return false;
523
524 strcpy(display, str.Get());
525 return true;
526}
527
528bool IPlugCLAP::paramsTextToValue(clap_id paramIdx, const char* display, double* pValue) noexcept
529{
530 const IParam* pParam = GetParam(paramIdx);
531 const bool isDoubleType = pParam->Type() == IParam::kTypeDouble;
532 const double paramValue = pParam->StringToValue(display);
533
534 *pValue = isDoubleType ? pParam->ToNormalized(paramValue) : paramValue;
535 return true;
536}
537
538void IPlugCLAP::paramsFlush(const clap_input_events* pInputParamChanges, const clap_output_events* pOutputParamChanges) noexcept
539{
540 ProcessInputEvents(pInputParamChanges);
541 ProcessOutputParams(pOutputParamChanges);
542}
543
544void IPlugCLAP::ProcessInputEvents(const clap_input_events* pInputEvents) noexcept
545{
546 IMidiMsg msg;
547
548 if (pInputEvents)
549 {
550 for (int i = 0; i < pInputEvents->size(pInputEvents); i++)
551 {
552 auto pEvent = pInputEvents->get(pInputEvents, i);
553
554 if (pEvent->space_id != CLAP_CORE_EVENT_SPACE_ID)
555 continue;
556
557 switch (pEvent->type)
558 {
559 case CLAP_EVENT_NOTE_ON:
560 {
561 // N.B. velocity stored 0-1
562 auto pNote = ClapEventCast<clap_event_note>(pEvent);
563 auto velocity = static_cast<int>(std::round(pNote->velocity * 127.0));
564 msg.MakeNoteOnMsg(pNote->key, velocity, pEvent->time, pNote->channel);
565 ProcessMidiMsg(msg);
566 mMidiMsgsFromProcessor.Push(msg);
567 break;
568 }
569
570 case CLAP_EVENT_NOTE_OFF:
571 {
572 auto pNote = ClapEventCast<clap_event_note>(pEvent);
573 msg.MakeNoteOffMsg(pNote->key, pEvent->time, pNote->channel);
574 ProcessMidiMsg(msg);
575 mMidiMsgsFromProcessor.Push(msg);
576 break;
577 }
578
579 case CLAP_EVENT_MIDI:
580 {
581 auto pMidiEvent = ClapEventCast<clap_event_midi>(pEvent);
582 msg = IMidiMsg(pEvent->time, pMidiEvent->data[0], pMidiEvent->data[1], pMidiEvent->data[2]);
583 ProcessMidiMsg(msg);
584 mMidiMsgsFromProcessor.Push(msg);
585 break;
586 }
587
588 case CLAP_EVENT_MIDI_SYSEX:
589 {
590 auto pSysexEvent = ClapEventCast<clap_event_midi_sysex>(pEvent);
591 ISysEx sysEx(pEvent->time, pSysexEvent->buffer, pSysexEvent->size);
592 ProcessSysEx(sysEx);
593 mSysExDataFromProcessor.PushFromArgs(sysEx.mOffset, sysEx.mSize, sysEx.mData);
594 break;
595 }
596
597 case CLAP_EVENT_PARAM_VALUE:
598 {
599 auto pParamValue = ClapEventCast<clap_event_param_value>(pEvent);
600
601 int paramIdx = pParamValue->param_id;
602 double value = pParamValue->value;
603
604 IParam* pParam = GetParam(paramIdx);
605 const bool isDoubleType = pParam->Type() == IParam::kTypeDouble;
606
607 if (isDoubleType)
608 pParam->SetNormalized(value);
609 else
610 pParam->Set(value);
611
612 SendParameterValueFromAPI(paramIdx, value, isDoubleType);
613 OnParamChange(paramIdx, EParamSource::kHost, pEvent->time);
614 break;
615 }
616
617 default:
618 break;
619 }
620 }
621 }
622}
623
624void IPlugCLAP::ProcessOutputParams(const clap_output_events* pOutputParamChanges) noexcept
625{
626 ParamToHost change;
627
628 while (mParamValuesToHost.Pop(change))
629 {
630 // Construct output stream
631 bool isValue = change.type() == CLAP_EVENT_PARAM_VALUE;
632
633 clap_event_header_t header;
634
635 // N.B. - paramaters output here almost certainly come from the UI
636 // They cannot be set with a sample offset (this is a limitation of the current IPlug2 API)
637
638 header.size = isValue ? sizeof(clap_event_param_value) : sizeof(clap_event_param_gesture);
639 header.time = 0;
640 header.space_id = CLAP_CORE_EVENT_SPACE_ID;
641 header.type = change.type();
642 header.flags = 0;
643
644 if (isValue)
645 {
646 clap_event_param_value event { header, change.idx(), nullptr, -1, -1, -1, -1, change.value() };
647 pOutputParamChanges->try_push(pOutputParamChanges, &event.header);
648 }
649 else
650 {
651 clap_event_param_gesture event { header, change.idx() };
652 pOutputParamChanges->try_push(pOutputParamChanges, &event.header);
653 }
654 }
655}
656
657void IPlugCLAP::ProcessOutputEvents(const clap_output_events* pOutputEvents, int nFrames) noexcept
658{
659 // N.B. Midi events and sysEx events are ordered by the respective queues
660 // Here we ensure correct ordering between the two queues
661 // Parameters can only be sent at the start of each block so are processed first
662
663 ProcessOutputParams(pOutputEvents);
664
665 if (pOutputEvents)
666 {
667 clap_event_header_t header;
668
669 while (mMidiToHost.ToDo() || mSysExToHost.ToDo())
670 {
671 int midiMsgOffset = nFrames;
672 int sysExOffset = nFrames;
673
674 // Look at the next two items to ensure correct ordering
675 if (mMidiToHost.ToDo())
676 midiMsgOffset = mMidiToHost.Peek().mOffset;
677
678 if (mSysExToHost.ToDo())
679 sysExOffset = mSysExToHost.Peek().mOffset;
680
681 // Don't move beyond the current frame
682 if (std::min(midiMsgOffset, sysExOffset) >= nFrames)
683 break;
684
685 if (sysExOffset <= midiMsgOffset)
686 {
687 auto data = mSysExToHost.Peek();
688
689 uint32_t dataSize = static_cast<uint32_t>(data.mSize);
690
691 header.size = sizeof(clap_event_midi_sysex);
692 header.time = data.mOffset;
693 header.space_id = CLAP_CORE_EVENT_SPACE_ID;
694 header.type = CLAP_EVENT_MIDI_SYSEX;
695 header.flags = 0;
696
697 clap_event_midi_sysex sysex_event { header, 0, data.mData, dataSize };
698
699 pOutputEvents->try_push(pOutputEvents, &sysex_event.header);
700
701 mSysExToHost.Remove();
702 }
703 else
704 {
705 auto msg = mMidiToHost.Peek();
706 auto status = msg.mStatus;
707
708 // Construct output stream
709 header.size = sizeof(clap_event_param_value);
710 header.time = msg.mOffset;
711 header.space_id = CLAP_CORE_EVENT_SPACE_ID;
712 header.type = CLAP_EVENT_MIDI;
713 header.flags = 0;
714
715 if (msg.StatusMsg() == IMidiMsg::kNoteOn)
716 header.type = CLAP_EVENT_NOTE_ON;
717
718 if (msg.StatusMsg() == IMidiMsg::kNoteOff)
719 header.type = CLAP_EVENT_NOTE_OFF;
720
721 if (header.type == CLAP_EVENT_NOTE_ON || header.type == CLAP_EVENT_NOTE_OFF)
722 {
723 int16_t channel = static_cast<int16_t>(msg.Channel());
724 clap_event_note note_event { header, -1, 0, channel, msg.mData1, static_cast<double>(msg.mData2) / 127.0};
725 pOutputEvents->try_push(pOutputEvents, &note_event.header);
726 }
727 else
728 {
729 clap_event_midi midi_event { header, 0, { status, msg.mData1, msg.mData2 } };
730 pOutputEvents->try_push(pOutputEvents, &midi_event.header);
731 }
732
733 mMidiToHost.Remove();
734 }
735 }
736
737 mMidiToHost.Flush(nFrames);
738 mSysExToHost.Flush(nFrames);
739 }
740}
741
742const char* ClapPortType(uint32_t nChans)
743{
744 // TODO - add support for surround/ambisonics or allow user setting?
745 return nChans == 2 ? CLAP_PORT_STEREO : (nChans == 1 ? CLAP_PORT_MONO : nullptr);
746}
747
748bool IPlugCLAP::implementsAudioPorts() const noexcept
749{
750 return MaxNBuses(ERoute::kInput) || MaxNBuses(ERoute::kOutput);
751}
752
753uint32_t IPlugCLAP::audioPortsCount(bool isInput) const noexcept
754{
755 return NBuses(isInput ? ERoute::kInput : ERoute::kOutput);
756}
757
758bool IPlugCLAP::audioPortsInfo(uint32_t index, bool isInput, clap_audio_port_info* pInfo) const noexcept
759{
760 // TODO - should we use in place pairs?
761 WDL_String busName;
762
763 const auto direction = isInput ? ERoute::kInput : ERoute::kOutput;
764 const auto nBuses = NBuses(direction);
765 const auto nChans = NChannels(direction, index);
766
767 GetBusName(direction, index, nBuses, busName);
768
769 constexpr uint32_t bitFlags = CLAP_AUDIO_PORT_SUPPORTS_64BITS
770 | CLAP_AUDIO_PORT_PREFERS_64BITS
771 | CLAP_AUDIO_PORT_REQUIRES_COMMON_SAMPLE_SIZE;
772
773 pInfo->id = index;
774 ClapNameCopy(pInfo->name, busName.Get());
775 pInfo->flags = !index ? bitFlags | CLAP_AUDIO_PORT_IS_MAIN : bitFlags;
776 pInfo->channel_count = nChans;
777 pInfo->port_type = ClapPortType(pInfo->channel_count);
778 pInfo->in_place_pair = CLAP_INVALID_ID;
779 return true;
780}
781
782bool IPlugCLAP::implementsAudioPortsConfig() const noexcept
783{
784 return audioPortsConfigCount();
785}
786
787uint32_t IPlugCLAP::audioPortsConfigCount() const noexcept
788{
789 return static_cast<uint32_t>(NIOConfigs());
790}
791
792bool IPlugCLAP::audioPortsGetConfig(uint32_t index, clap_audio_ports_config* pConfig) const noexcept
793{
794 if (index >= audioPortsConfigCount())
795 return false;
796
797 WDL_String configName;
798
799 // TODO - review naming or add option for names...
800 auto getNChans = [&](ERoute direction, int bus)
801 {
802 return static_cast<uint32_t>(NChannels(direction, static_cast<uint32_t>(bus), index));
803 };
804
805 auto getDirectionName = [&](ERoute direction)
806 {
807 // N.B. Configs in iPlug2 currently have no names so we reconstruct the strings...
808 configName.AppendFormatted(CLAP_NAME_SIZE, "%d", getNChans(direction, 0));
809
810 for (int i = 1; i < NBuses(direction, index); i++)
811 configName.AppendFormatted(CLAP_NAME_SIZE, ".%d", getNChans(direction, i));
812 };
813
814 getDirectionName(kInput);
815 configName.Append("-");
816 getDirectionName(kOutput);
817
818 pConfig->id = index;
819 ClapNameCopy(pConfig->name, configName.Get());
820
821 pConfig->input_port_count = static_cast<uint32_t>(NBuses(kInput, index));
822 pConfig->output_port_count = static_cast<uint32_t>(NBuses(kOutput, index));
823
824 // Bus 0 is the main port (see audioPortsInfo), so any bus in a direction means a main port
825 pConfig->has_main_input = pConfig->input_port_count > 0;
826 pConfig->main_input_channel_count = pConfig->has_main_input ? getNChans(kInput, 0) : 0;
827 pConfig->main_input_port_type = ClapPortType(pConfig->main_input_channel_count);
828
829 pConfig->has_main_output = pConfig->output_port_count > 0;
830 pConfig->main_output_channel_count = pConfig->has_main_output ? getNChans(kOutput, 0) : 0;
831 pConfig->main_output_port_type = ClapPortType(pConfig->main_output_channel_count);
832
833 return true;
834}
835
836bool IPlugCLAP::audioPortsSetConfig(clap_id configIdx) noexcept
837{
838 if (configIdx >= audioPortsConfigCount())
839 return false;
840
841 mConfigIdx = static_cast<int>(configIdx);
842
843 return true;
844}
845
846uint32_t IPlugCLAP::notePortsCount(bool isInput) const noexcept
847{
848 if (isInput)
849 return PLUG_DOES_MIDI_IN ? 1 : 0;
850 else
851 return PLUG_DOES_MIDI_OUT ? 1 : 0;
852}
853
854bool IPlugCLAP::notePortsInfo(uint32_t index, bool isInput, clap_note_port_info* pInfo) const noexcept
855{
856 if (isInput)
857 {
858 pInfo->id = index;
859 pInfo->supported_dialects = CLAP_NOTE_DIALECT_MIDI;
860 pInfo->preferred_dialect = CLAP_NOTE_DIALECT_MIDI;
861 ClapNameCopy(pInfo->name, "MIDI Input");
862 }
863 else
864 {
865 pInfo->id = index;
866 pInfo->supported_dialects = CLAP_NOTE_DIALECT_MIDI;
867 pInfo->preferred_dialect = CLAP_NOTE_DIALECT_MIDI;
868 ClapNameCopy(pInfo->name, "MIDI Output");
869 }
870 return true;
871}
872
873// clap_plugin_gui
874bool IPlugCLAP::guiIsApiSupported(const char* api, bool isFloating) noexcept
875{
876#if defined OS_MAC
877 return !isFloating && !strcmp(api, CLAP_WINDOW_API_COCOA);
878#elif defined OS_WIN
879 return !isFloating && !strcmp(api, CLAP_WINDOW_API_WIN32);
880#else
881#error Not Implemented!
882#endif
883}
884
885bool IPlugCLAP::guiSetParent(const clap_window* pWindow) noexcept
886{
887#if defined OS_MAC
888 return GUIWindowAttach(pWindow->cocoa);
889#elif defined OS_WIN
890 return GUIWindowAttach(pWindow->win32);
891#else
892#error Not Implemented!
893#endif
894}
895
896bool IPlugCLAP::implementsGui() const noexcept
897{
898 return HasUI();
899}
900
901bool IPlugCLAP::guiCreate(const char* api, bool isFloating) noexcept
902{
903 return HasUI();
904}
905
906void IPlugCLAP::guiDestroy() noexcept
907{
908 CloseWindow();
909 mGUIOpen = false;
910 mWindow = nullptr;
911}
912
913bool IPlugCLAP::guiShow() noexcept
914{
915 if (HasUI() && !mGUIOpen)
916 {
917 OpenWindow(mWindow);
918 return true;
919 }
920 else
921 {
922 return false;
923 }
924}
925
926bool IPlugCLAP::guiHide() noexcept
927{
928 if (HasUI())
929 {
930 CloseWindow();
931 mGUIOpen = false;
932 return true;
933 }
934 else
935 {
936 return false;
937 }
938}
939
940bool IPlugCLAP::guiCanResize() const noexcept
941{
942 return HasUI() && GetHostResizeEnabled();
943}
944
945bool IPlugCLAP::guiSetScale(double scale) noexcept
946{
947 if (HasUI())
948 {
949 SetScreenScale(static_cast<float>(scale));
950 return true;
951 }
952 else
953 {
954 return false;
955 }
956}
957
958bool IPlugCLAP::guiGetSize(uint32_t* pWidth, uint32_t* pHeight) noexcept
959{
960 TRACE
961
962 if (HasUI())
963 {
964 *pWidth = GetEditorWidth();
965 *pHeight = GetEditorHeight();
966
967 return true;
968 }
969 else
970 {
971 return false;
972 }
973}
974
975bool IPlugCLAP::GUIWindowAttach(void* pWindow) noexcept
976{
977 if (HasUI())
978 {
979 OpenWindow(pWindow);
980 mWindow = pWindow;
981 mGUIOpen = true;
982 return true;
983 }
984 else
985 {
986 return false;
987 }
988}
989
990bool IPlugCLAP::guiAdjustSize(uint32_t* pWidth, uint32_t* pHeight) noexcept
991{
992 Trace(TRACELOC, "width:%i height:%i\n", *pWidth, *pHeight);
993
994 if (HasUI())
995 {
996 int w = *pWidth;
997 int h = *pHeight;
998 ConstrainEditorResize(w, h);
999 *pWidth = w;
1000 *pHeight = h;
1001
1002 return true;
1003 }
1004 else
1005 {
1006 return false;
1007 }
1008}
1009
1010bool IPlugCLAP::guiSetSize(uint32_t width, uint32_t height) noexcept
1011{
1012 Trace(TRACELOC, "width:%i height:%i\n", width, height);
1013
1014 if (HasUI())
1015 {
1016 OnParentWindowResize(width, height);
1017 return true;
1018 }
1019 else
1020 {
1021 return false;
1022 }
1023}
1024
1025// TODO - wildcards (return as -1 chans...)
1026void IPlugCLAP::SetDefaultConfig()
1027{
1028 auto isMatch = [&](int idx, int chans)
1029 {
1030 if (NBuses(ERoute::kOutput, idx) >= 1 && NChannels(ERoute::kOutput, 0, idx) == chans)
1031 {
1032 int numBuses = NBuses(ERoute::kInput, idx);
1033
1034 // Instruments are allowed to match with no inputs
1035 if (IsInstrument() && (numBuses == 0 || NChannels(ERoute::kInput, 0, idx) == 0))
1036 return true;
1037
1038 // Otherwise IO must match
1039 return numBuses >= 1 && NChannels(ERoute::kInput, 0, idx) == chans;
1040 }
1041
1042 return false;
1043 };
1044
1045 auto testMatches = [&](int chans)
1046 {
1047 bool matched = false;
1048 int configNBusesI = 0;
1049 int configNBusesO = 0;
1050
1051 for (int i = 0; i < static_cast<int>(audioPortsConfigCount()); i++)
1052 {
1053 if (isMatch(i, chans))
1054 {
1055 const int nBusesI = NBuses(ERoute::kInput, i);
1056 const int nBusesO = NBuses(ERoute::kOutput, i);
1057
1058 const bool preferInput = nBusesO < configNBusesI;
1059 const bool preferOutput = nBusesI < configNBusesO;
1060
1061 if (!matched || preferOutput || (nBusesO == configNBusesO && preferInput))
1062 {
1063 matched = true;
1064 mConfigIdx = i;
1065 configNBusesI = NBuses(ERoute::kInput, i);
1066 configNBusesO = NBuses(ERoute::kOutput, i);
1067 }
1068 }
1069 }
1070
1071 return matched;
1072 };
1073
1074 mConfigIdx = 0;
1075
1076 // If there is track info available try to match
1077 if (GetClapHost().canUseTrackInfo())
1078 {
1079 clap_track_info info;
1080 GetClapHost().trackInfoGet(&info);
1081
1082 if (testMatches(info.audio_channel_count) || info.audio_channel_count == 2)
1083 return;
1084 }
1085
1086 // Default to stereo if nothing else has succeeded
1087 testMatches(2);
1088}
1089
1090int IPlugCLAP::RequiredChannels() const
1091{
1092 return std::max(MaxNChannels(kInput), MaxNChannels(kOutput));
1093}
1094
1095uint32_t IPlugCLAP::NBuses(ERoute direction, int configIdx) const
1096{
1097 return GetIOConfig(configIdx)->NBuses(direction);
1098}
1099
1100uint32_t IPlugCLAP::NChannels(ERoute direction, uint32_t bus, int configIdx) const
1101{
1102 return GetIOConfig(configIdx)->NChansOnBusSAFE(direction, static_cast<int>(bus));
1103}
1104
1105uint32_t IPlugCLAP::NBuses(ERoute direction) const
1106{
1107 return NBuses(direction, mConfigIdx);
1108}
1109
1110uint32_t IPlugCLAP::NChannels(ERoute direction, uint32_t bus) const
1111{
1112 return NChannels(direction, bus, mConfigIdx);
1113}
Manages a block of memory, for plug-in settings store/recall.
Definition: IPlugStructs.h:112
int PutBytes(const void *pSrc, int nBytesToCopy)
Copies data into the chunk, placing it at the end, resizing if necessary.
Definition: IPlugStructs.h:147
uint8_t * GetData()
Gets a ptr to the chunk data.
Definition: IPlugStructs.h:242
int Size() const
Returns the current size of the chunk.
Definition: IPlugStructs.h:221
IPlug's parameter class.
double GetDefault(bool normalized=false) const
Returns the parameter's default value.
EParamType Type() const
Get the parameter's type.
double ToNormalized(double nonNormalizedValue) const
Convert a real value to normalized value for this parameter.
bool GetCanAutomate() const
void GetDisplay(WDL_String &display, bool withDisplayText=true) const
Get the current textual display for the current parameter value.
double GetMin() const
Returns the parameter's minimum value.
void Set(double value)
Sets the parameter value.
const char * GetLabel() const
Returns the parameter's label.
double StringToValue(const char *str) const
Convert a textual representation of the parameter value to a double (real value)
void SetNormalized(double normalizedValue)
Sets the parameter value from a normalized range (usually coming from the linked IControl)
const char * GetName() const
Returns the parameter's name.
double FromNormalized(double normalizedValue) const
Convert a normalized value to real value for this parameter.
double GetNormalized() const
Returns the parameter's normalized value.
double Constrain(double value) const
Constrains the input value between mMin and mMax and apply stepping if relevant.
const char * GetDisplayText(double value) const
Get the display text for a particular value.
const char * GetGroup() const
Returns the parameter's group.
double Value() const
Gets a readable value of the parameter.
double GetMax() const
Returns the parameter's maximum value.
The base class of an IPlug plug-in, which interacts with the different plug-in APIs.
Definition: IPlugAPIBase.h:43
bool SendSysEx(const ISysEx &msg) override
Send a single MIDI System Exclusive (SysEx) message // TODO: info about what thread should this be ca...
Definition: IPlugCLAP.cpp:134
void InformHostOfParamChange(int idx, double normalizedValue) override
Implemented by the API class, called by the UI via SetParameterValue() with the value of a parameter ...
Definition: IPlugCLAP.cpp:73
void SetTailSize(int tailSize) override
Call this method if you need to update the tail size at runtime, for example if the decay time of you...
Definition: IPlugCLAP.cpp:105
void SetLatency(int samples) override
Call this if the latency of your plug-in changes after initialization (perhaps from OnReset() ) This ...
Definition: IPlugCLAP.cpp:113
bool EditorResize(int viewWidth, int viewHeight) override
Implementations call into the APIs resize hooks returns a bool to indicate whether the DAW or plugin ...
Definition: IPlugCLAP.cpp:89
void BeginInformHostOfParamChange(int idx) override
Implemented by the API class, called by the UI (or by a delegate) at the beginning of a parameter cha...
Definition: IPlugCLAP.cpp:67
bool SendMidiMsg(const IMidiMsg &msg) override
Send a single MIDI message // TODO: info about what thread should this be called on or not called on!
Definition: IPlugCLAP.cpp:128
void EndInformHostOfParamChange(int idx) override
Implemented by the API class, called by the UI (or by a delegate) at the end of a parameter change ge...
Definition: IPlugCLAP.cpp:83
The base class for IPlug Audio Processing.
bool GetTailIsInfinite() const
const IOConfig * GetIOConfig(int idx) const
int GetTailSize() const
virtual void SetTailSize(int tailSize)
Call this method if you need to update the tail size at runtime, for example if the decay time of you...
virtual void SetLatency(int latency)
Call this if the latency of your plug-in changes after initialization (perhaps from OnReset() ) This ...
bool IsInstrument() const
int MaxNBuses(ERoute direction, int *pConfigIdxWithTheMostBuses=nullptr) const
Used to determine the maximum number of input or output buses based on what was specified in the chan...
int NIOConfigs() const
int MaxNChannels(ERoute direction) const
virtual void OnActivate(bool active)
Override OnActivate() which should be called by the API class when a plug-in is "switched on" by the ...
bool PushFromArgs(Args ...args)
Constructs and adds an item to the queue in-place from arguments.
Definition: IPlugQueue.h:91
bool HasUI() const
bool GetHostResizeEnabled() const
ERoute
Used to identify whether a bus/channel connection is an input or an output.
Encapsulates information about the host transport state.
Definition: IPlugStructs.h:584
Encapsulates a MIDI message and provides helper functions.
Definition: IPlugMidi.h:31
void MakeNoteOnMsg(int noteNumber, int velocity, int offset, int channel=0)
Make a Note On message.
Definition: IPlugMidi.h:145
int Channel() const
Gets the channel of a MIDI message.
Definition: IPlugMidi.h:236
void MakeNoteOffMsg(int noteNumber, int offset, int channel=0)
Make a Note Off message.
Definition: IPlugMidi.h:158
EStatusMsg StatusMsg() const
Gets the MIDI Status message.
Definition: IPlugMidi.h:243
int NChansOnBusSAFE(ERoute direction, int index) const
Gets the number of channels on a bus with bounds checking.
Definition: IPlugStructs.h:535
int NBuses(ERoute direction) const
Gets the number of buses for a given direction.
Definition: IPlugStructs.h:548
A struct for dealing with SysEx messages.
Definition: IPlugMidi.h:539
This structure is used when queueing Sysex messages.
Definition: IPlugStructs.h:45