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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  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. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  644. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  645. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  646. continue;
  647. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  648. continue;
  649. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  650. continue;
  651. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  652. continue;
  653. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  654. continue;
  655. // Fix bad note-off
  656. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  657. status = MIDI_STATUS_NOTE_OFF;
  658. // put back channel in data
  659. uint8_t midiData2[midiEvent.size];
  660. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  661. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  662. ysfx_midi_event_t yevent;
  663. yevent.bus = midiEvent.port;
  664. yevent.offset = event.time;
  665. yevent.size = midiEvent.size;
  666. yevent.data = midiData;
  667. ysfx_send_midi(fEffect, &yevent);
  668. if (status == MIDI_STATUS_NOTE_ON)
  669. {
  670. pData->postponeNoteOnRtEvent(true, event.channel, midiData[1], midiData[2]);
  671. }
  672. else if (status == MIDI_STATUS_NOTE_OFF)
  673. {
  674. pData->postponeNoteOffRtEvent(true, event.channel, midiData[1]);
  675. }
  676. } break;
  677. } // switch (event.type)
  678. }
  679. pData->postRtEvents.trySplice();
  680. } // End of Event Input and Processing
  681. // --------------------------------------------------------------------------------------------------------
  682. // Plugin processing
  683. const uint32_t numInputs = ysfx_get_num_inputs(fEffect);
  684. const uint32_t numOutputs = ysfx_get_num_outputs(fEffect);
  685. ysfx_process_float(fEffect, audioIn, audioOut, numInputs, numOutputs, frames);
  686. // End of Plugin processing (no events)
  687. // --------------------------------------------------------------------------------------------------------
  688. // MIDI Output
  689. if (pData->event.portOut != nullptr)
  690. {
  691. ysfx_midi_event_t event;
  692. while (ysfx_receive_midi(fEffect, &event))
  693. {
  694. CARLA_SAFE_ASSERT_BREAK(event.offset < frames);
  695. CARLA_SAFE_ASSERT_BREAK(event.size > 0);
  696. CARLA_SAFE_ASSERT_CONTINUE(event.size <= 0xff);
  697. if (! pData->event.portOut->writeMidiEvent(event.offset,
  698. static_cast<uint8_t>(event.size),
  699. event.data))
  700. break;
  701. }
  702. } // End of MIDI Output
  703. // --------------------------------------------------------------------------------------------------------
  704. // Control Output
  705. {
  706. uint64_t changes = ysfx_fetch_slider_changes(fEffect);
  707. uint64_t automations = ysfx_fetch_slider_automations(fEffect);
  708. if ((changes|automations) != 0)
  709. {
  710. for (uint32_t rindex = 0; rindex < ysfx_max_sliders; ++rindex)
  711. {
  712. uint64_t mask = (uint64_t)1 << rindex;
  713. //TODO: automations and changes are handled identically
  714. // refer to `sliderchange` vs `slider_automate`
  715. if (((changes|automations) & mask) != 0)
  716. {
  717. int32_t parameterIndex = fMapOfSliderToParameter[rindex];
  718. CARLA_SAFE_ASSERT_CONTINUE(parameterIndex != -1);
  719. const float newValue = static_cast<float>(ysfx_slider_get_value(fEffect, (uint32_t)parameterIndex));
  720. setParameterValueRT((uint32_t)parameterIndex, newValue, 0, true);
  721. }
  722. }
  723. }
  724. //TODO: slider visibility changes, if this feature can be supported
  725. }
  726. }
  727. // -------------------------------------------------------------------
  728. bool initJSFX(const CarlaPluginPtr plugin,
  729. const char* const filename, const char* name, const char* const label, const uint options)
  730. {
  731. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  732. // ---------------------------------------------------------------
  733. // first checks
  734. if (pData->client != nullptr)
  735. {
  736. pData->engine->setLastError("Plugin client is already registered");
  737. return false;
  738. }
  739. if ((filename == nullptr || filename[0] == '\0') &&
  740. (label == nullptr || label[0] == '\0'))
  741. {
  742. pData->engine->setLastError("null filename and label");
  743. return false;
  744. }
  745. // ---------------------------------------------------------------
  746. fUnit = CarlaJsfxUnit();
  747. {
  748. StringArray splitPaths;
  749. if (const char* paths = pData->engine->getOptions().pathJSFX)
  750. splitPaths = StringArray::fromTokens(CharPointer_UTF8(paths), CARLA_OS_SPLIT_STR, "");
  751. File file;
  752. if (filename && filename[0] != '\0')
  753. file = File(CharPointer_UTF8(filename));
  754. if (file.isNotNull() && file.existsAsFile())
  755. {
  756. // find which engine search path we're in, and use this as the root
  757. for (int i = 0; i < splitPaths.size() && !fUnit; ++i)
  758. {
  759. const File currentPath(splitPaths[i]);
  760. if (file.isAChildOf(currentPath))
  761. fUnit = CarlaJsfxUnit(currentPath, file);
  762. }
  763. // if not found in engine search paths, use parent directory as the root
  764. if (! fUnit)
  765. fUnit = CarlaJsfxUnit(file.getParentDirectory(), file);
  766. }
  767. else if (label && label[0] != '\0')
  768. {
  769. // search a matching file in plugin paths
  770. for (int i = 0; i < splitPaths.size() && !fUnit; ++i)
  771. {
  772. const File currentPath(splitPaths[i]);
  773. const File currentFile = currentPath.getChildFile(CharPointer_UTF8(label));
  774. const CarlaJsfxUnit currentUnit(currentPath, currentFile);
  775. if (File(currentUnit.getFilePath()).existsAsFile())
  776. fUnit = currentUnit;
  777. }
  778. }
  779. }
  780. if (! fUnit)
  781. {
  782. pData->engine->setLastError("Cannot locate the JSFX plugin");
  783. return false;
  784. }
  785. // ---------------------------------------------------------------
  786. ysfx_config_u config(ysfx_config_new());
  787. CARLA_SAFE_ASSERT_RETURN(config != nullptr, false);
  788. const water::String rootPath = fUnit.getRootPath();
  789. const water::String filePath = fUnit.getFilePath();
  790. ysfx_register_builtin_audio_formats(config.get());
  791. ysfx_set_import_root(config.get(), rootPath.toRawUTF8());
  792. ysfx_guess_file_roots(config.get(), filePath.toRawUTF8());
  793. ysfx_set_log_reporter(config.get(), &CarlaJsfxLogging::logAll);
  794. ysfx_set_user_data(config.get(), (intptr_t)this);
  795. fEffect = ysfx_new(config.get());
  796. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, false);
  797. // ---------------------------------------------------------------
  798. // get info
  799. {
  800. if (! ysfx_load_file(fEffect, filePath.toRawUTF8(), 0))
  801. {
  802. pData->engine->setLastError("Failed to load JSFX");
  803. return false;
  804. }
  805. // TODO(jsfx) adapt when implementing these features
  806. const int compileFlags = 0
  807. //| ysfx_compile_no_serialize
  808. | ysfx_compile_no_gfx
  809. ;
  810. if (! ysfx_compile(fEffect, compileFlags))
  811. {
  812. pData->engine->setLastError("Failed to compile JSFX");
  813. return false;
  814. }
  815. }
  816. if (name != nullptr && name[0] != '\0')
  817. {
  818. pData->name = pData->engine->getUniquePluginName(name);
  819. }
  820. else
  821. {
  822. pData->name = carla_strdup(ysfx_get_name(fEffect));
  823. }
  824. pData->filename = carla_strdup(filePath.toRawUTF8());
  825. // ---------------------------------------------------------------
  826. // register client
  827. pData->client = pData->engine->addClient(plugin);
  828. if (pData->client == nullptr || ! pData->client->isOk())
  829. {
  830. pData->engine->setLastError("Failed to register plugin client");
  831. return false;
  832. }
  833. // ---------------------------------------------------------------
  834. // set options
  835. pData->options = 0x0;
  836. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  837. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  838. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  839. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  840. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  841. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  842. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  843. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  844. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  845. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  846. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  847. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  848. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  849. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  850. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  851. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  852. return true;
  853. }
  854. private:
  855. ysfx_t* fEffect;
  856. ysfx_state_t* fEffectState;
  857. CarlaJsfxUnit fUnit;
  858. water::String fChunkText;
  859. ysfx_time_info_t fTransportValues;
  860. std::vector<int32_t> fMapOfSliderToParameter;
  861. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJSFX)
  862. };
  863. CARLA_BACKEND_END_NAMESPACE
  864. #endif // HAVE_YSFX
  865. CARLA_BACKEND_START_NAMESPACE
  866. // -------------------------------------------------------------------------------------------------------------------
  867. CarlaPluginPtr CarlaPlugin::newJSFX(const Initializer& init)
  868. {
  869. carla_debug("CarlaPlugin::newJSFX({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "})",
  870. init.engine, init.filename, init.name, init.label, init.uniqueId);
  871. #ifdef HAVE_YSFX
  872. std::shared_ptr<CarlaPluginJSFX> plugin(new CarlaPluginJSFX(init.engine, init.id));
  873. if (! plugin->initJSFX(plugin, init.filename, init.name, init.label, init.options))
  874. return nullptr;
  875. return plugin;
  876. #else
  877. init.engine->setLastError("JSFX support not available");
  878. return nullptr;
  879. #endif
  880. }
  881. // -------------------------------------------------------------------------------------------------------------------
  882. CARLA_BACKEND_END_NAMESPACE