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

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