Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CarlaPluginJSFX.cpp 41KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. /*
  2. * Carla JSFX Plugin
  3. * Copyright (C) 2021 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. // TODO(jsfx) graphics section
  18. #include "CarlaPluginInternal.hpp"
  19. #include "CarlaEngine.hpp"
  20. #include "CarlaJsfxUtils.hpp"
  21. #include "CarlaBackendUtils.hpp"
  22. #include "CarlaUtils.hpp"
  23. #include "water/files/File.h"
  24. #include "water/text/StringArray.h"
  25. #include <algorithm>
  26. #include <cstdio>
  27. #include <cstring>
  28. using water::CharPointer_UTF8;
  29. using water::File;
  30. using water::String;
  31. using water::StringArray;
  32. CARLA_BACKEND_START_NAMESPACE
  33. // -------------------------------------------------------------------------------------------------------------------
  34. // Fallback data
  35. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  36. // -------------------------------------------------------------------------------------------------------------------
  37. class CarlaPluginJSFX : public CarlaPlugin
  38. {
  39. public:
  40. CarlaPluginJSFX(CarlaEngine* const engine, const uint id) noexcept
  41. : CarlaPlugin(engine, id),
  42. fEffect(nullptr),
  43. fEffectState(nullptr),
  44. fUnit(),
  45. fChunkText(),
  46. fTransportValues(),
  47. fMapOfSliderToParameter(ysfx_max_sliders, -1)
  48. {
  49. carla_debug("CarlaPluginJSFX::CarlaPluginJSFX(%p, %i)", engine, id);
  50. carla_zeroStruct(fTransportValues);
  51. }
  52. ~CarlaPluginJSFX() noexcept override
  53. {
  54. carla_debug("CarlaPluginJSFX::~CarlaPluginJSFX()");
  55. pData->singleMutex.lock();
  56. pData->masterMutex.lock();
  57. if (pData->client != nullptr && pData->client->isActive())
  58. pData->client->deactivate(true);
  59. if (pData->active)
  60. {
  61. deactivate();
  62. pData->active = false;
  63. }
  64. clearBuffers();
  65. ysfx_state_free(fEffectState);
  66. ysfx_free(fEffect);
  67. }
  68. // -------------------------------------------------------------------
  69. // Information (base)
  70. PluginType getType() const noexcept override
  71. {
  72. return PLUGIN_JSFX;
  73. }
  74. PluginCategory getCategory() const noexcept override
  75. {
  76. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, CarlaPlugin::getCategory());
  77. return CarlaJsfxCategories::getFromEffect(fEffect);
  78. }
  79. uint32_t getLatencyInFrames() const noexcept override
  80. {
  81. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0);
  82. ysfx_real sampleRate = ysfx_get_sample_rate(fEffect);
  83. ysfx_real latencyInSeconds = ysfx_get_pdc_delay(fEffect);
  84. //NOTE: `pdc_bot_ch` and `pdc_top_ch` channel range ignored
  85. int32_t latencyInFrames = water::roundToInt(latencyInSeconds * sampleRate);
  86. wassert(latencyInFrames >= 0);
  87. return (uint32_t)latencyInFrames;
  88. }
  89. // -------------------------------------------------------------------
  90. // Information (count)
  91. uint32_t getMidiInCount() const noexcept override
  92. {
  93. return 1;
  94. }
  95. uint32_t getMidiOutCount() const noexcept override
  96. {
  97. return 1;
  98. }
  99. uint32_t getParameterScalePointCount(const uint32_t parameterId) const noexcept override
  100. {
  101. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0);
  102. const uint32_t rindex = static_cast<uint32_t>(pData->param.data[parameterId].rindex);
  103. return ysfx_slider_get_enum_names(fEffect, rindex, nullptr, 0);;
  104. }
  105. // -------------------------------------------------------------------
  106. // Information (current data)
  107. std::size_t getChunkData(void** const dataPtr) noexcept override
  108. {
  109. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  110. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  111. ysfx_state_free(fEffectState);
  112. fEffectState = ysfx_save_state(fEffect);
  113. CARLA_SAFE_ASSERT_RETURN(fEffectState != nullptr, 0);
  114. *dataPtr = fEffectState->data;
  115. return fEffectState->data_size;
  116. }
  117. // -------------------------------------------------------------------
  118. // Information (per-plugin data)
  119. uint getOptionsAvailable() const noexcept override
  120. {
  121. uint options = 0x0;
  122. options |= PLUGIN_OPTION_USE_CHUNKS;
  123. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  124. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  125. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  126. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  127. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  128. options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  129. options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  130. return options;
  131. }
  132. float getParameterValue(const uint32_t parameterId) const noexcept override
  133. {
  134. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  135. const uint32_t rindex = static_cast<uint32_t>(pData->param.data[parameterId].rindex);
  136. return static_cast<float>(ysfx_slider_get_value(fEffect, rindex));
  137. }
  138. bool getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  139. {
  140. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, false);
  141. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  142. const uint32_t rindex = static_cast<uint32_t>(pData->param.data[parameterId].rindex);
  143. if (const char* const name = ysfx_slider_get_name(fEffect, rindex))
  144. {
  145. std::snprintf(strBuf, STR_MAX, "%s", name);
  146. return true;
  147. }
  148. return false;
  149. }
  150. float getParameterScalePointValue(const uint32_t parameterId, const uint32_t scalePointId) const noexcept override
  151. {
  152. CARLA_SAFE_ASSERT_RETURN(parameterId < getParameterCount(), 0.0f);
  153. CARLA_SAFE_ASSERT_RETURN(scalePointId < getParameterScalePointCount(parameterId), 0.0f);
  154. return (float)scalePointId;
  155. }
  156. bool getParameterScalePointLabel(const uint32_t parameterId, const uint32_t scalePointId, char* const strBuf) const noexcept override
  157. {
  158. CARLA_SAFE_ASSERT_RETURN(parameterId < getParameterCount(), false);
  159. const uint32_t rindex = static_cast<uint32_t>(pData->param.data[parameterId].rindex);
  160. const uint32_t enumCount = ysfx_slider_get_enum_names(fEffect, rindex, nullptr, 0);
  161. CARLA_SAFE_ASSERT_RETURN(scalePointId < enumCount, false);
  162. if (const char* const name = ysfx_slider_get_enum_name(fEffect, rindex, scalePointId))
  163. {
  164. std::snprintf(strBuf, STR_MAX, "%s", name);
  165. return true;
  166. }
  167. return false;
  168. }
  169. bool getLabel(char* const strBuf) const noexcept override
  170. {
  171. std::strncpy(strBuf, fUnit.getFileId().toRawUTF8(), STR_MAX);
  172. return true;
  173. }
  174. // -------------------------------------------------------------------
  175. // Set data (plugin-specific stuff)
  176. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  177. {
  178. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  179. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  180. const uint32_t rindex = static_cast<uint32_t>(pData->param.data[parameterId].rindex);
  181. ysfx_slider_set_value(fEffect, rindex, value);
  182. CarlaPlugin::setParameterValue(parameterId, value, sendGui, sendOsc, sendCallback);
  183. }
  184. void setParameterValueRT(const uint32_t parameterId, const float value, const uint32_t frameOffset, const bool sendCallbackLater) noexcept override
  185. {
  186. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  187. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  188. const uint32_t rindex = static_cast<uint32_t>(pData->param.data[parameterId].rindex);
  189. ysfx_slider_set_value(fEffect, rindex, value);
  190. CarlaPlugin::setParameterValueRT(parameterId, value, frameOffset, sendCallbackLater);
  191. }
  192. void setChunkData(const void* data, std::size_t dataSize) override
  193. {
  194. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  195. ysfx_state_t state;
  196. state.sliders = nullptr;
  197. state.slider_count = 0;
  198. state.data = static_cast<uint8_t*>(const_cast<void*>(data));
  199. state.data_size = dataSize;
  200. CARLA_SAFE_ASSERT(ysfx_load_state(fEffect, &state));
  201. }
  202. // -------------------------------------------------------------------
  203. // Plugin state
  204. void reload() override
  205. {
  206. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  207. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  208. carla_debug("CarlaPluginJSFX::reload()");
  209. const EngineProcessMode processMode(pData->engine->getProccessMode());
  210. // Safely disable plugin for reload
  211. const ScopedDisabler sd(this);
  212. if (pData->active)
  213. deactivate();
  214. clearBuffers();
  215. // ---------------------------------------------------------------
  216. // initialize the block size and sample rate
  217. // loading the chunk can invoke @slider which makes computations based on these
  218. ysfx_set_sample_rate(fEffect, pData->engine->getSampleRate());
  219. ysfx_set_block_size(fEffect, (uint32_t)pData->engine->getBufferSize());
  220. ysfx_init(fEffect);
  221. const uint32_t aIns = ysfx_get_num_inputs(fEffect);
  222. const uint32_t aOuts = ysfx_get_num_outputs(fEffect);
  223. // perhaps we obtained a latency value from @init
  224. pData->client->setLatency(getLatencyInFrames());
  225. if (aIns > 0)
  226. {
  227. pData->audioIn.createNew(aIns);
  228. }
  229. if (aOuts > 0)
  230. {
  231. pData->audioOut.createNew(aOuts);
  232. }
  233. // count the sliders and establish the mappings between parameter and slider
  234. uint32_t params = 0;
  235. uint32_t mapOfParameterToSlider[ysfx_max_sliders];
  236. for (uint32_t rindex = 0; rindex < ysfx_max_sliders; ++rindex)
  237. {
  238. if (ysfx_slider_exists(fEffect, rindex))
  239. {
  240. mapOfParameterToSlider[params] = rindex;
  241. fMapOfSliderToParameter[rindex] = (int32_t)params;
  242. ++params;
  243. }
  244. else
  245. {
  246. fMapOfSliderToParameter[rindex] = -1;
  247. }
  248. }
  249. if (params > 0)
  250. {
  251. pData->param.createNew(params, false);
  252. }
  253. const uint portNameSize = pData->engine->getMaxPortNameSize();
  254. CarlaString portName;
  255. // Audio Ins
  256. for (uint32_t j = 0; j < aIns; ++j)
  257. {
  258. portName.clear();
  259. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  260. {
  261. portName = pData->name;
  262. portName += ":";
  263. }
  264. const char* const inputName = ysfx_get_input_name(fEffect, j);
  265. if (inputName && inputName[0])
  266. {
  267. portName += inputName;
  268. }
  269. else if (aIns > 1)
  270. {
  271. portName += "input_";
  272. portName += CarlaString(j+1);
  273. }
  274. else
  275. portName += "input";
  276. portName.truncate(portNameSize);
  277. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  278. pData->audioIn.ports[j].rindex = j;
  279. }
  280. // Audio Outs
  281. for (uint32_t j = 0; j < aOuts; ++j)
  282. {
  283. portName.clear();
  284. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  285. {
  286. portName = pData->name;
  287. portName += ":";
  288. }
  289. const char* const outputName = ysfx_get_input_name(fEffect, j);
  290. if (outputName && outputName[0])
  291. {
  292. portName += outputName;
  293. }
  294. else if (aOuts > 1)
  295. {
  296. portName += "output_";
  297. portName += CarlaString(j+1);
  298. }
  299. else
  300. portName += "output";
  301. portName.truncate(portNameSize);
  302. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  303. pData->audioOut.ports[j].rindex = j;
  304. }
  305. // Parameters
  306. for (uint32_t j = 0; j < params; ++j)
  307. {
  308. const uint32_t rindex = mapOfParameterToSlider[j];
  309. pData->param.data[j].type = PARAMETER_INPUT;
  310. pData->param.data[j].index = (int32_t)j;
  311. pData->param.data[j].rindex = (int32_t)rindex;
  312. ysfx_slider_range_t range = {};
  313. ysfx_slider_get_range(fEffect, rindex, &range);
  314. float min = (float)range.min;
  315. float max = (float)range.max;
  316. float def = (float)range.def;
  317. float step = (float)range.inc;
  318. float stepSmall;
  319. float stepLarge;
  320. // only use values as integer if we have a proper range
  321. const bool isEnum = ysfx_slider_is_enum(fEffect, rindex) &&
  322. carla_isZero(min) &&
  323. max >= 0.0f &&
  324. carla_isEqual(max + 1.0f, static_cast<float>(ysfx_slider_get_enum_names(fEffect, rindex, nullptr, 0)));
  325. // NOTE: in case of incomplete slider specification without <min,max,step>;
  326. // these are usually output-only sliders.
  327. if (carla_isEqual(min, max))
  328. {
  329. // replace with a dummy range
  330. min = 0.0f;
  331. max = 1.0f;
  332. }
  333. if (min > max)
  334. std::swap(min, max);
  335. if (def < min)
  336. def = min;
  337. else if (def > max)
  338. def = max;
  339. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  340. if (isEnum)
  341. {
  342. step = 1.0f;
  343. stepSmall = 1.0f;
  344. stepLarge = 10.0f;
  345. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  346. pData->param.data[j].hints |= PARAMETER_USES_SCALEPOINTS;
  347. }
  348. else
  349. {
  350. stepSmall = step/10.0f;
  351. stepLarge = step*10.0f;
  352. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  353. }
  354. pData->param.ranges[j].min = min;
  355. pData->param.ranges[j].max = max;
  356. pData->param.ranges[j].def = def;
  357. pData->param.ranges[j].step = step;
  358. pData->param.ranges[j].stepSmall = stepSmall;
  359. pData->param.ranges[j].stepLarge = stepLarge;
  360. }
  361. //if (needsCtrlIn)
  362. {
  363. portName.clear();
  364. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  365. {
  366. portName = pData->name;
  367. portName += ":";
  368. }
  369. portName += "events-in";
  370. portName.truncate(portNameSize);
  371. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  372. }
  373. //if (needsCtrlOut)
  374. {
  375. portName.clear();
  376. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  377. {
  378. portName = pData->name;
  379. portName += ":";
  380. }
  381. portName += "events-out";
  382. portName.truncate(portNameSize);
  383. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  384. }
  385. }
  386. // -------------------------------------------------------------------
  387. // Plugin processing
  388. void activate() noexcept override
  389. {
  390. CARLA_SAFE_ASSERT_RETURN(fEffect,);
  391. ysfx_set_sample_rate(fEffect, pData->engine->getSampleRate());
  392. ysfx_set_block_size(fEffect, (uint32_t)pData->engine->getBufferSize());
  393. ysfx_init(fEffect);
  394. fTransportValues.tempo = 120;
  395. fTransportValues.playback_state = ysfx_playback_paused;
  396. fTransportValues.time_position = 0;
  397. fTransportValues.beat_position = 0;
  398. fTransportValues.time_signature[0] = 4;
  399. fTransportValues.time_signature[1] = 4;
  400. }
  401. void process(const float* const* const audioIn, float** const audioOut,
  402. const float* const* const, float**,
  403. const uint32_t frames) override
  404. {
  405. CARLA_SAFE_ASSERT_RETURN(fEffect,);
  406. // --------------------------------------------------------------------------------------------------------
  407. // Set TimeInfo
  408. const EngineTimeInfo timeInfo = pData->engine->getTimeInfo();
  409. const EngineTimeInfoBBT& bbt = timeInfo.bbt;
  410. fTransportValues.playback_state = timeInfo.playing ?
  411. ysfx_playback_playing : ysfx_playback_paused;
  412. fTransportValues.time_position = 1e-6*double(timeInfo.usecs);
  413. if (bbt.valid)
  414. {
  415. const double samplePos = double(timeInfo.frame);
  416. const double sampleRate = pData->engine->getSampleRate();
  417. fTransportValues.tempo = bbt.beatsPerMinute;
  418. fTransportValues.beat_position = samplePos / (sampleRate * 60 / bbt.beatsPerMinute);
  419. fTransportValues.time_signature[0] = (uint32_t)bbt.beatsPerBar;
  420. fTransportValues.time_signature[1] = (uint32_t)bbt.beatType;
  421. }
  422. ysfx_set_time_info(fEffect, &fTransportValues);
  423. // --------------------------------------------------------------------------------------------------------
  424. // Event Input and Processing
  425. if (pData->event.portIn != nullptr)
  426. {
  427. // ----------------------------------------------------------------------------------------------------
  428. // MIDI Input (External)
  429. if (pData->extNotes.mutex.tryLock())
  430. {
  431. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  432. {
  433. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  434. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  435. uint8_t midiData[3];
  436. midiData[0] = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  437. midiData[1] = note.note;
  438. midiData[2] = note.velo;
  439. ysfx_midi_event_t event;
  440. event.bus = 0;
  441. event.offset = 0;
  442. event.size = 3;
  443. event.data = midiData;
  444. ysfx_send_midi(fEffect, &event);
  445. }
  446. pData->extNotes.data.clear();
  447. pData->extNotes.mutex.unlock();
  448. } // End of MIDI Input (External)
  449. // ----------------------------------------------------------------------------------------------------
  450. // Event Input (System)
  451. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  452. bool allNotesOffSent = false;
  453. #endif
  454. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  455. {
  456. EngineEvent& event(pData->event.portIn->getEvent(i));
  457. if (event.time >= frames)
  458. continue;
  459. switch (event.type)
  460. {
  461. case kEngineEventTypeNull:
  462. break;
  463. case kEngineEventTypeControl: {
  464. EngineControlEvent& ctrlEvent(event.ctrl);
  465. switch (ctrlEvent.type)
  466. {
  467. case kEngineControlEventTypeNull:
  468. break;
  469. case kEngineControlEventTypeParameter: {
  470. float value;
  471. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  472. // non-midi
  473. if (event.channel == kEngineEventNonMidiChannel)
  474. {
  475. const uint32_t k = ctrlEvent.param;
  476. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  477. ctrlEvent.handled = true;
  478. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  479. setParameterValueRT(k, value, event.time, true);
  480. continue;
  481. }
  482. // Control backend stuff
  483. if (event.channel == pData->ctrlChannel)
  484. {
  485. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  486. {
  487. ctrlEvent.handled = true;
  488. value = ctrlEvent.normalizedValue;
  489. setDryWetRT(value, true);
  490. }
  491. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  492. {
  493. ctrlEvent.handled = true;
  494. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  495. setVolumeRT(value, true);
  496. }
  497. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  498. {
  499. float left, right;
  500. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  501. if (value < 0.0f)
  502. {
  503. left = -1.0f;
  504. right = (value*2.0f)+1.0f;
  505. }
  506. else if (value > 0.0f)
  507. {
  508. left = (value*2.0f)-1.0f;
  509. right = 1.0f;
  510. }
  511. else
  512. {
  513. left = -1.0f;
  514. right = 1.0f;
  515. }
  516. ctrlEvent.handled = true;
  517. setBalanceLeftRT(left, true);
  518. setBalanceRightRT(right, true);
  519. }
  520. }
  521. #endif
  522. // Control plugin parameters
  523. uint32_t k;
  524. for (k=0; k < pData->param.count; ++k)
  525. {
  526. if (pData->param.data[k].midiChannel != event.channel)
  527. continue;
  528. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  529. continue;
  530. if (pData->param.data[k].type != PARAMETER_INPUT)
  531. continue;
  532. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  533. continue;
  534. ctrlEvent.handled = true;
  535. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  536. setParameterValueRT(k, value, event.time, true);
  537. }
  538. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  539. {
  540. uint8_t midiData[3];
  541. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  542. midiData[1] = uint8_t(ctrlEvent.param);
  543. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f);
  544. ysfx_midi_event_t yevent;
  545. yevent.bus = 0;
  546. yevent.offset = event.time;
  547. yevent.size = 3;
  548. yevent.data = midiData;
  549. ysfx_send_midi(fEffect, &yevent);
  550. }
  551. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  552. if (! ctrlEvent.handled)
  553. checkForMidiLearn(event);
  554. #endif
  555. break;
  556. } // case kEngineControlEventTypeParameter
  557. case kEngineControlEventTypeMidiBank:
  558. if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  559. {
  560. uint8_t midiData[3];
  561. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  562. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  563. midiData[2] = 0;
  564. ysfx_midi_event_t yevent;
  565. yevent.bus = 0;
  566. yevent.offset = event.time;
  567. yevent.size = 3;
  568. yevent.data = midiData;
  569. ysfx_send_midi(fEffect, &yevent);
  570. midiData[1] = MIDI_CONTROL_BANK_SELECT__LSB;
  571. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f);
  572. yevent.bus = 0;
  573. yevent.offset = event.time;
  574. yevent.size = 3;
  575. yevent.data = midiData;
  576. ysfx_send_midi(fEffect, &yevent);
  577. }
  578. break;
  579. case kEngineControlEventTypeMidiProgram:
  580. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  581. {
  582. if (ctrlEvent.param < pData->prog.count)
  583. {
  584. setProgramRT(ctrlEvent.param, true);
  585. }
  586. }
  587. else if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  588. {
  589. uint8_t midiData[2];
  590. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  591. midiData[1] = uint8_t(ctrlEvent.normalizedValue*127.0f);
  592. ysfx_midi_event_t yevent;
  593. yevent.bus = 0;
  594. yevent.offset = event.time;
  595. yevent.size = 2;
  596. yevent.data = midiData;
  597. ysfx_send_midi(fEffect, &yevent);
  598. }
  599. break;
  600. case kEngineControlEventTypeAllSoundOff:
  601. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  602. {
  603. uint8_t midiData[3];
  604. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  605. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  606. midiData[2] = 0;
  607. ysfx_midi_event_t yevent;
  608. yevent.bus = 0;
  609. yevent.offset = event.time;
  610. yevent.size = 3;
  611. yevent.data = midiData;
  612. ysfx_send_midi(fEffect, &yevent);
  613. }
  614. break;
  615. case kEngineControlEventTypeAllNotesOff:
  616. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  617. {
  618. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  619. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  620. {
  621. allNotesOffSent = true;
  622. postponeRtAllNotesOff();
  623. }
  624. #endif
  625. uint8_t midiData[3];
  626. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  627. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  628. midiData[2] = 0;
  629. ysfx_midi_event_t yevent;
  630. yevent.bus = 0;
  631. yevent.offset = event.time;
  632. yevent.size = 3;
  633. yevent.data = midiData;
  634. ysfx_send_midi(fEffect, &yevent);
  635. }
  636. break;
  637. } // switch (ctrlEvent.type)
  638. break;
  639. } // case kEngineEventTypeControl
  640. case kEngineEventTypeMidi: {
  641. const EngineMidiEvent& midiEvent(event.midi);
  642. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  643. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  644. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  645. continue;
  646. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  647. continue;
  648. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  649. continue;
  650. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  651. continue;
  652. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  653. continue;
  654. // Fix bad note-off
  655. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  656. status = MIDI_STATUS_NOTE_OFF;
  657. // put back channel in data
  658. uint8_t midiData2[midiEvent.size];
  659. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  660. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  661. ysfx_midi_event_t yevent;
  662. yevent.bus = midiEvent.port;
  663. yevent.offset = event.time;
  664. yevent.size = midiEvent.size;
  665. yevent.data = midiData;
  666. ysfx_send_midi(fEffect, &yevent);
  667. if (status == MIDI_STATUS_NOTE_ON)
  668. {
  669. pData->postponeNoteOnRtEvent(true, event.channel, midiData[1], midiData[2]);
  670. }
  671. else if (status == MIDI_STATUS_NOTE_OFF)
  672. {
  673. pData->postponeNoteOffRtEvent(true, event.channel, midiData[1]);
  674. }
  675. } break;
  676. } // switch (event.type)
  677. }
  678. pData->postRtEvents.trySplice();
  679. } // End of Event Input and Processing
  680. // --------------------------------------------------------------------------------------------------------
  681. // Plugin processing
  682. const uint32_t numInputs = ysfx_get_num_inputs(fEffect);
  683. const uint32_t numOutputs = ysfx_get_num_outputs(fEffect);
  684. ysfx_process_float(fEffect, audioIn, audioOut, numInputs, numOutputs, frames);
  685. // End of Plugin processing (no events)
  686. // --------------------------------------------------------------------------------------------------------
  687. // MIDI Output
  688. if (pData->event.portOut != nullptr)
  689. {
  690. ysfx_midi_event_t event;
  691. while (ysfx_receive_midi(fEffect, &event))
  692. {
  693. CARLA_SAFE_ASSERT_BREAK(event.offset < frames);
  694. CARLA_SAFE_ASSERT_BREAK(event.size > 0);
  695. CARLA_SAFE_ASSERT_CONTINUE(event.size <= 0xff);
  696. if (! pData->event.portOut->writeMidiEvent(event.offset,
  697. static_cast<uint8_t>(event.size),
  698. event.data))
  699. break;
  700. }
  701. } // End of MIDI Output
  702. // --------------------------------------------------------------------------------------------------------
  703. // Control Output
  704. {
  705. uint64_t changes = ysfx_fetch_slider_changes(fEffect);
  706. uint64_t automations = ysfx_fetch_slider_automations(fEffect);
  707. if ((changes|automations) != 0)
  708. {
  709. for (uint32_t rindex = 0; rindex < ysfx_max_sliders; ++rindex)
  710. {
  711. uint64_t mask = (uint64_t)1 << rindex;
  712. //TODO: automations and changes are handled identically
  713. // refer to `sliderchange` vs `slider_automate`
  714. if (((changes|automations) & mask) != 0)
  715. {
  716. int32_t parameterIndex = fMapOfSliderToParameter[rindex];
  717. CARLA_SAFE_ASSERT_CONTINUE(parameterIndex != -1);
  718. const float newValue = static_cast<float>(ysfx_slider_get_value(fEffect, (uint32_t)parameterIndex));
  719. setParameterValueRT((uint32_t)parameterIndex, newValue, 0, true);
  720. }
  721. }
  722. }
  723. //TODO: slider visibility changes, if this feature can be supported
  724. }
  725. }
  726. // -------------------------------------------------------------------
  727. bool initJSFX(const CarlaPluginPtr plugin,
  728. const char* const filename, const char* name, const char* const label, const uint options)
  729. {
  730. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  731. // ---------------------------------------------------------------
  732. // first checks
  733. if (pData->client != nullptr)
  734. {
  735. pData->engine->setLastError("Plugin client is already registered");
  736. return false;
  737. }
  738. if ((filename == nullptr || filename[0] == '\0') &&
  739. (label == nullptr || label[0] == '\0'))
  740. {
  741. pData->engine->setLastError("null filename and label");
  742. return false;
  743. }
  744. // ---------------------------------------------------------------
  745. fUnit = CarlaJsfxUnit();
  746. {
  747. StringArray splitPaths;
  748. if (const char* paths = pData->engine->getOptions().pathJSFX)
  749. splitPaths = StringArray::fromTokens(CharPointer_UTF8(paths), CARLA_OS_SPLIT_STR, "");
  750. File file;
  751. if (filename && filename[0] != '\0')
  752. file = File(CharPointer_UTF8(filename));
  753. if (file.isNotNull() && file.existsAsFile())
  754. {
  755. // find which engine search path we're in, and use this as the root
  756. for (int i = 0; i < splitPaths.size() && !fUnit; ++i)
  757. {
  758. const File currentPath(splitPaths[i]);
  759. if (file.isAChildOf(currentPath))
  760. fUnit = CarlaJsfxUnit(currentPath, file);
  761. }
  762. // if not found in engine search paths, use parent directory as the root
  763. if (! fUnit)
  764. fUnit = CarlaJsfxUnit(file.getParentDirectory(), file);
  765. }
  766. else if (label && label[0] != '\0')
  767. {
  768. // search a matching file in plugin paths
  769. for (int i = 0; i < splitPaths.size() && !fUnit; ++i)
  770. {
  771. const File currentPath(splitPaths[i]);
  772. const File currentFile = currentPath.getChildFile(CharPointer_UTF8(label));
  773. const CarlaJsfxUnit currentUnit(currentPath, currentFile);
  774. if (File(currentUnit.getFilePath()).existsAsFile())
  775. fUnit = currentUnit;
  776. }
  777. }
  778. }
  779. if (! fUnit)
  780. {
  781. pData->engine->setLastError("Cannot locate the JSFX plugin");
  782. return false;
  783. }
  784. // ---------------------------------------------------------------
  785. ysfx_config_u config(ysfx_config_new());
  786. CARLA_SAFE_ASSERT_RETURN(config != nullptr, false);
  787. const water::String rootPath = fUnit.getRootPath();
  788. const water::String filePath = fUnit.getFilePath();
  789. ysfx_register_builtin_audio_formats(config.get());
  790. ysfx_set_import_root(config.get(), rootPath.toRawUTF8());
  791. ysfx_guess_file_roots(config.get(), filePath.toRawUTF8());
  792. ysfx_set_log_reporter(config.get(), &CarlaJsfxLogging::logAll);
  793. ysfx_set_user_data(config.get(), (intptr_t)this);
  794. fEffect = ysfx_new(config.get());
  795. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, false);
  796. // ---------------------------------------------------------------
  797. // get info
  798. {
  799. if (! ysfx_load_file(fEffect, filePath.toRawUTF8(), 0))
  800. {
  801. pData->engine->setLastError("Failed to load JSFX");
  802. return false;
  803. }
  804. // TODO(jsfx) adapt when implementing these features
  805. const int compileFlags = 0
  806. //| ysfx_compile_no_serialize
  807. | ysfx_compile_no_gfx
  808. ;
  809. if (! ysfx_compile(fEffect, compileFlags))
  810. {
  811. pData->engine->setLastError("Failed to compile JSFX");
  812. return false;
  813. }
  814. }
  815. if (name != nullptr && name[0] != '\0')
  816. {
  817. pData->name = pData->engine->getUniquePluginName(name);
  818. }
  819. else
  820. {
  821. pData->name = carla_strdup(ysfx_get_name(fEffect));
  822. }
  823. pData->filename = carla_strdup(filePath.toRawUTF8());
  824. // ---------------------------------------------------------------
  825. // register client
  826. pData->client = pData->engine->addClient(plugin);
  827. if (pData->client == nullptr || ! pData->client->isOk())
  828. {
  829. pData->engine->setLastError("Failed to register plugin client");
  830. return false;
  831. }
  832. // ---------------------------------------------------------------
  833. // set options
  834. pData->options = 0x0;
  835. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  836. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  837. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  838. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  839. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  840. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  841. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  842. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  843. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  844. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  845. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  846. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  847. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  848. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  849. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  850. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  851. return true;
  852. }
  853. private:
  854. ysfx_t* fEffect;
  855. ysfx_state_t* fEffectState;
  856. CarlaJsfxUnit fUnit;
  857. water::String fChunkText;
  858. ysfx_time_info_t fTransportValues;
  859. std::vector<int32_t> fMapOfSliderToParameter;
  860. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJSFX)
  861. };
  862. // -------------------------------------------------------------------------------------------------------------------
  863. CarlaPluginPtr CarlaPlugin::newJSFX(const Initializer& init)
  864. {
  865. carla_debug("CarlaPlugin::newJSFX({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "})",
  866. init.engine, init.filename, init.name, init.label, init.uniqueId);
  867. std::shared_ptr<CarlaPluginJSFX> plugin(new CarlaPluginJSFX(init.engine, init.id));
  868. if (! plugin->initJSFX(plugin, init.filename, init.name, init.label, init.options))
  869. return nullptr;
  870. return plugin;
  871. }
  872. // -------------------------------------------------------------------------------------------------------------------
  873. CARLA_BACKEND_END_NAMESPACE