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.

2827 lines
101KB

  1. /*
  2. * Carla DSSI Plugin
  3. * Copyright (C) 2011-2014 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: set fUsesCustomData and latency index before init finishes
  18. // TODO: common laterncy code
  19. #include "CarlaPluginInternal.hpp"
  20. #include "CarlaEngineUtils.hpp"
  21. #include "CarlaDssiUtils.hpp"
  22. #include "CarlaMathUtils.hpp"
  23. #ifdef HAVE_LIBLO
  24. # include "CarlaOscUtils.hpp"
  25. # include "CarlaThread.hpp"
  26. #endif
  27. using juce::ChildProcess;
  28. using juce::ScopedPointer;
  29. using juce::String;
  30. using juce::StringArray;
  31. #define CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(/* argc, types, */ argcToCompare, typesToCompare) \
  32. /* check argument count */ \
  33. if (argc != argcToCompare) \
  34. { \
  35. carla_stderr("CarlaPluginDSSI::%s() - argument count mismatch: %i != %i", __FUNCTION__, argc, argcToCompare); \
  36. return; \
  37. } \
  38. if (argc > 0) \
  39. { \
  40. /* check for nullness */ \
  41. if (types == nullptr || typesToCompare == nullptr) \
  42. { \
  43. carla_stderr("CarlaPluginDSSI::%s() - argument types are null", __FUNCTION__); \
  44. return; \
  45. } \
  46. /* check argument types */ \
  47. if (std::strcmp(types, typesToCompare) != 0) \
  48. { \
  49. carla_stderr("CarlaPluginDSSI::%s() - argument types mismatch: '%s' != '%s'", __FUNCTION__, types, typesToCompare); \
  50. return; \
  51. } \
  52. }
  53. CARLA_BACKEND_START_NAMESPACE
  54. // -------------------------------------------------------------------
  55. // Fallback data
  56. static const CustomData kCustomDataFallback = { nullptr, nullptr, nullptr };
  57. #ifdef HAVE_LIBLO
  58. // -------------------------------------------------------------------
  59. class CarlaThreadDSSIUI : public CarlaThread
  60. {
  61. public:
  62. CarlaThreadDSSIUI(CarlaEngine* const engine, CarlaPlugin* const plugin, const CarlaOscData& oscData) noexcept
  63. : CarlaThread("CarlaThreadDSSIUI"),
  64. kEngine(engine),
  65. kPlugin(plugin),
  66. fBinary(),
  67. fLabel(),
  68. fOscData(oscData),
  69. fProcess(),
  70. leakDetector_CarlaThreadDSSIUI() {}
  71. void setData(const char* const binary, const char* const label) noexcept
  72. {
  73. CARLA_SAFE_ASSERT_RETURN(binary != nullptr && binary[0] != '\0',);
  74. CARLA_SAFE_ASSERT_RETURN(label != nullptr /*&& label[0] != '\0'*/,);
  75. CARLA_SAFE_ASSERT(! isThreadRunning());
  76. fBinary = binary;
  77. fLabel = label;
  78. if (fLabel.isEmpty())
  79. fLabel = "\"\"";
  80. }
  81. uintptr_t getProcessPID() const noexcept
  82. {
  83. CARLA_SAFE_ASSERT_RETURN(fProcess != nullptr, 0);
  84. return (uintptr_t)fProcess->getPID();
  85. }
  86. void run()
  87. {
  88. if (fProcess == nullptr)
  89. {
  90. fProcess = new ChildProcess();
  91. }
  92. else if (fProcess->isRunning())
  93. {
  94. carla_stderr("CarlaThreadDSSI::run() - already running, giving up...");
  95. kEngine->callback(CarlaBackend::ENGINE_CALLBACK_UI_STATE_CHANGED, kPlugin->getId(), 0, 0, 0.0f, nullptr);
  96. fProcess->kill();
  97. fProcess = nullptr;
  98. return;
  99. }
  100. String name(kPlugin->getName());
  101. String filename(kPlugin->getFilename());
  102. if (name.isEmpty())
  103. name = "(none)";
  104. if (filename.isEmpty())
  105. filename = "\"\"";
  106. StringArray arguments;
  107. // binary
  108. arguments.add(fBinary.buffer());
  109. // osc-url
  110. arguments.add(String(kEngine->getOscServerPathUDP()) + String("/") + String(kPlugin->getId()));
  111. // filename
  112. arguments.add(filename);
  113. // label
  114. arguments.add(fLabel.buffer());
  115. // ui-title
  116. arguments.add(name + String(" (GUI)"));
  117. bool started;
  118. {
  119. #ifdef CARLA_OS_LINUX
  120. const ScopedEngineEnvironmentLocker _seel(kEngine);
  121. const char* const oldPreload(std::getenv("LD_PRELOAD"));
  122. if (oldPreload != nullptr)
  123. ::unsetenv("LD_PRELOAD");
  124. #endif
  125. carla_stdout("starting DSSI UI...");
  126. started = fProcess->start(arguments);
  127. #ifdef CARLA_OS_LINUX
  128. if (oldPreload != nullptr)
  129. ::setenv("LD_PRELOAD", oldPreload, 1);
  130. #endif
  131. }
  132. if (! started)
  133. {
  134. carla_stdout("failed!");
  135. fProcess = nullptr;
  136. return;
  137. }
  138. if (waitForOscGuiShow())
  139. {
  140. for (; fProcess->isRunning() && ! shouldThreadExit();)
  141. carla_sleep(1);
  142. // we only get here if UI was closed or thread asked to exit
  143. if (fProcess->isRunning() && shouldThreadExit())
  144. {
  145. fProcess->waitForProcessToFinish(static_cast<int>(kEngine->getOptions().uiBridgesTimeout));
  146. if (fProcess->isRunning())
  147. {
  148. carla_stdout("CarlaThreadDSSIUI::run() - UI refused to close, force kill now");
  149. fProcess->kill();
  150. }
  151. else
  152. {
  153. carla_stdout("CarlaThreadDSSIUI::run() - UI auto-closed successfully");
  154. }
  155. }
  156. else if (fProcess->getExitCode() != 0 /*|| fProcess->exitStatus() == QProcess::CrashExit*/)
  157. carla_stderr("CarlaThreadDSSIUI::run() - UI crashed while running");
  158. else
  159. carla_stdout("CarlaThreadDSSIUI::run() - UI closed cleanly");
  160. kEngine->callback(CarlaBackend::ENGINE_CALLBACK_UI_STATE_CHANGED, kPlugin->getId(), 0, 0, 0.0f, nullptr);
  161. }
  162. else
  163. {
  164. fProcess->kill();
  165. carla_stdout("CarlaThreadDSSIUI::run() - GUI timeout");
  166. kEngine->callback(CarlaBackend::ENGINE_CALLBACK_UI_STATE_CHANGED, kPlugin->getId(), 0, 0, 0.0f, nullptr);
  167. }
  168. carla_stdout("DSSI UI finished");
  169. fProcess = nullptr;
  170. }
  171. private:
  172. CarlaEngine* const kEngine;
  173. CarlaPlugin* const kPlugin;
  174. CarlaString fBinary;
  175. CarlaString fLabel;
  176. const CarlaOscData& fOscData;
  177. ScopedPointer<ChildProcess> fProcess;
  178. bool waitForOscGuiShow()
  179. {
  180. carla_stdout("CarlaThreadDSSIUI::waitForOscGuiShow()");
  181. uint i=0, oscUiTimeout = kEngine->getOptions().uiBridgesTimeout;
  182. // wait for UI 'update' call
  183. for (; i < oscUiTimeout/100; ++i)
  184. {
  185. if (fOscData.target != nullptr)
  186. {
  187. carla_stdout("CarlaThreadDSSIUI::waitForOscGuiShow() - got response, asking UI to show itself now");
  188. osc_send_show(fOscData);
  189. return true;
  190. }
  191. if (fProcess != nullptr && fProcess->isRunning())
  192. carla_msleep(100);
  193. else
  194. return false;
  195. }
  196. carla_stdout("CarlaThreadDSSIUI::waitForOscGuiShow() - Timeout while waiting for UI to respond (waited %u msecs)", oscUiTimeout);
  197. return false;
  198. }
  199. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaThreadDSSIUI)
  200. };
  201. #endif
  202. // -----------------------------------------------------
  203. class CarlaPluginDSSI : public CarlaPlugin
  204. {
  205. public:
  206. CarlaPluginDSSI(CarlaEngine* const engine, const uint id) noexcept
  207. : CarlaPlugin(engine, id),
  208. fHandle(nullptr),
  209. fHandle2(nullptr),
  210. fDescriptor(nullptr),
  211. fDssiDescriptor(nullptr),
  212. fUsesCustomData(false),
  213. #ifdef HAVE_LIBLO
  214. fUiFilename(nullptr),
  215. #endif
  216. fAudioInBuffers(nullptr),
  217. fAudioOutBuffers(nullptr),
  218. fParamBuffers(nullptr),
  219. fLatencyChanged(false),
  220. fLatencyIndex(-1),
  221. #ifdef HAVE_LIBLO
  222. fOscData(),
  223. fThreadUI(engine, this, fOscData),
  224. #endif
  225. leakDetector_CarlaPluginDSSI()
  226. {
  227. carla_debug("CarlaPluginDSSI::CarlaPluginDSSI(%p, %i)", engine, id);
  228. }
  229. ~CarlaPluginDSSI() noexcept override
  230. {
  231. carla_debug("CarlaPluginDSSI::~CarlaPluginDSSI()");
  232. #ifdef HAVE_LIBLO
  233. // close UI
  234. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  235. {
  236. showCustomUI(false);
  237. fThreadUI.stopThread(static_cast<int>(pData->engine->getOptions().uiBridgesTimeout * 2));
  238. }
  239. #endif
  240. pData->singleMutex.lock();
  241. pData->masterMutex.lock();
  242. if (pData->client != nullptr && pData->client->isActive())
  243. pData->client->deactivate();
  244. if (pData->active)
  245. {
  246. deactivate();
  247. pData->active = false;
  248. }
  249. if (fDescriptor != nullptr)
  250. {
  251. if (pData->name != nullptr && fDssiDescriptor != nullptr && fDssiDescriptor->run_synth == nullptr && fDssiDescriptor->run_multiple_synths != nullptr)
  252. removeUniqueMultiSynth(fDescriptor->Label);
  253. if (fDescriptor->cleanup != nullptr)
  254. {
  255. if (fHandle != nullptr)
  256. {
  257. try {
  258. fDescriptor->cleanup(fHandle);
  259. } CARLA_SAFE_EXCEPTION("DSSI cleanup");
  260. }
  261. if (fHandle2 != nullptr)
  262. {
  263. try {
  264. fDescriptor->cleanup(fHandle2);
  265. } CARLA_SAFE_EXCEPTION("DSSI cleanup #2");
  266. }
  267. }
  268. fHandle = nullptr;
  269. fHandle2 = nullptr;
  270. fDescriptor = nullptr;
  271. fDssiDescriptor = nullptr;
  272. }
  273. #ifdef HAVE_LIBLO
  274. if (fUiFilename != nullptr)
  275. {
  276. delete[] fUiFilename;
  277. fUiFilename = nullptr;
  278. }
  279. #endif
  280. clearBuffers();
  281. }
  282. // -------------------------------------------------------------------
  283. // Information (base)
  284. PluginType getType() const noexcept override
  285. {
  286. return PLUGIN_DSSI;
  287. }
  288. PluginCategory getCategory() const noexcept override
  289. {
  290. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr, PLUGIN_CATEGORY_NONE);
  291. if (pData->audioIn.count == 0 && pData->audioOut.count > 0 && (fDssiDescriptor->run_synth != nullptr || fDssiDescriptor->run_multiple_synths != nullptr))
  292. return PLUGIN_CATEGORY_SYNTH;
  293. return CarlaPlugin::getCategory();
  294. }
  295. int64_t getUniqueId() const noexcept override
  296. {
  297. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, 0);
  298. return static_cast<int64_t>(fDescriptor->UniqueID);
  299. }
  300. // -------------------------------------------------------------------
  301. // Information (count)
  302. // nothing
  303. // -------------------------------------------------------------------
  304. // Information (current data)
  305. std::size_t getChunkData(void** const dataPtr) noexcept override
  306. {
  307. CARLA_SAFE_ASSERT_RETURN(fUsesCustomData, 0);
  308. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  309. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr, 0);
  310. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor->get_custom_data != nullptr, 0);
  311. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr, 0);
  312. CARLA_SAFE_ASSERT_RETURN(fHandle2 == nullptr, 0);
  313. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  314. *dataPtr = nullptr;
  315. int ret = 0;
  316. ulong dataSize = 0;
  317. try {
  318. ret = fDssiDescriptor->get_custom_data(fHandle, dataPtr, &dataSize);
  319. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPluginDSSI::getChunkData", 0);
  320. return (ret != 0) ? dataSize : 0;
  321. }
  322. // -------------------------------------------------------------------
  323. // Information (per-plugin data)
  324. uint getOptionsAvailable() const noexcept override
  325. {
  326. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr, 0x0);
  327. #ifdef __USE_GNU
  328. const bool isDssiVst(strcasestr(pData->filename, "dssi-vst") != nullptr);
  329. #else
  330. const bool isDssiVst(std::strstr(pData->filename, "dssi-vst") != nullptr);
  331. #endif
  332. uint options = 0x0;
  333. if (fDssiDescriptor->get_program != nullptr && fDssiDescriptor->select_program != nullptr)
  334. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  335. if (! isDssiVst)
  336. {
  337. if (fLatencyIndex == -1)
  338. options |= PLUGIN_OPTION_FIXED_BUFFERS;
  339. if (pData->engine->getProccessMode() != ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  340. {
  341. if (pData->options & PLUGIN_OPTION_FORCE_STEREO)
  342. options |= PLUGIN_OPTION_FORCE_STEREO;
  343. else if (pData->audioIn.count <= 1 && pData->audioOut.count <= 1 && (pData->audioIn.count != 0 || pData->audioOut.count != 0))
  344. options |= PLUGIN_OPTION_FORCE_STEREO;
  345. }
  346. }
  347. if (fUsesCustomData)
  348. options |= PLUGIN_OPTION_USE_CHUNKS;
  349. if (fDssiDescriptor->run_synth != nullptr || fDssiDescriptor->run_multiple_synths != nullptr)
  350. {
  351. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  352. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  353. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  354. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  355. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  356. }
  357. return options;
  358. }
  359. float getParameterValue(const uint32_t parameterId) const noexcept override
  360. {
  361. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr, 0.0f);
  362. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  363. return fParamBuffers[parameterId];
  364. }
  365. void getLabel(char* const strBuf) const noexcept override
  366. {
  367. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  368. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Label != nullptr, nullStrBuf(strBuf));
  369. std::strncpy(strBuf, fDescriptor->Label, STR_MAX);
  370. }
  371. void getMaker(char* const strBuf) const noexcept override
  372. {
  373. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  374. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Maker != nullptr, nullStrBuf(strBuf));
  375. std::strncpy(strBuf, fDescriptor->Maker, STR_MAX);
  376. }
  377. void getCopyright(char* const strBuf) const noexcept override
  378. {
  379. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  380. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Copyright != nullptr, nullStrBuf(strBuf));
  381. std::strncpy(strBuf, fDescriptor->Copyright, STR_MAX);
  382. }
  383. void getRealName(char* const strBuf) const noexcept override
  384. {
  385. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  386. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Name != nullptr, nullStrBuf(strBuf));
  387. std::strncpy(strBuf, fDescriptor->Name, STR_MAX);
  388. }
  389. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  390. {
  391. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  392. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, nullStrBuf(strBuf));
  393. const int32_t rindex(pData->param.data[parameterId].rindex);
  394. CARLA_SAFE_ASSERT_RETURN(rindex < static_cast<int32_t>(fDescriptor->PortCount), nullStrBuf(strBuf));
  395. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortNames[rindex] != nullptr, nullStrBuf(strBuf));
  396. if (getSeparatedParameterNameOrUnit(fDescriptor->PortNames[rindex], strBuf, true))
  397. return;
  398. std::strncpy(strBuf, fDescriptor->PortNames[rindex], STR_MAX);
  399. }
  400. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  401. {
  402. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, nullStrBuf(strBuf));
  403. const int32_t rindex(pData->param.data[parameterId].rindex);
  404. CARLA_SAFE_ASSERT_RETURN(rindex < static_cast<int32_t>(fDescriptor->PortCount), nullStrBuf(strBuf));
  405. if (getSeparatedParameterNameOrUnit(fDescriptor->PortNames[rindex], strBuf, false))
  406. return;
  407. nullStrBuf(strBuf);
  408. }
  409. // -------------------------------------------------------------------
  410. // Set data (state)
  411. // nothing
  412. // -------------------------------------------------------------------
  413. // Set data (internal stuff)
  414. void setId(const uint newId) noexcept
  415. {
  416. CarlaPlugin::setId(newId);
  417. // UI osc-url uses Id, so we need to close it when it changes
  418. // FIXME - must be RT safe
  419. showCustomUI(false);
  420. }
  421. // -------------------------------------------------------------------
  422. // Set data (plugin-specific stuff)
  423. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  424. {
  425. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr,);
  426. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  427. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  428. fParamBuffers[parameterId] = fixedValue;
  429. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  430. }
  431. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  432. {
  433. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr,);
  434. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  435. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  436. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  437. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  438. carla_debug("CarlaPluginDSSI::setCustomData(%s, %s, %s, %s)", type, key, value, bool2str(sendGui));
  439. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) != 0)
  440. return carla_stderr2("CarlaPluginDSSI::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string", type, key, value, bool2str(sendGui));
  441. if (fDssiDescriptor->configure != nullptr)
  442. {
  443. try {
  444. fDssiDescriptor->configure(fHandle, key, value);
  445. } catch(...) {}
  446. if (fHandle2 != nullptr)
  447. {
  448. try {
  449. fDssiDescriptor->configure(fHandle2, key, value);
  450. } catch(...) {}
  451. }
  452. }
  453. #ifdef HAVE_LIBLO
  454. if (sendGui && fOscData.target != nullptr)
  455. osc_send_configure(fOscData, key, value);
  456. #endif
  457. if (std::strcmp(key, "reloadprograms") == 0 || std::strcmp(key, "load") == 0 || std::strncmp(key, "patches", 7) == 0)
  458. {
  459. const ScopedSingleProcessLocker spl(this, true);
  460. reloadPrograms(false);
  461. }
  462. CarlaPlugin::setCustomData(type, key, value, sendGui);
  463. }
  464. void setChunkData(const void* const data, const std::size_t dataSize) override
  465. {
  466. CARLA_SAFE_ASSERT_RETURN(fUsesCustomData,);
  467. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  468. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr,);
  469. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor->set_custom_data != nullptr,);
  470. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  471. CARLA_SAFE_ASSERT_RETURN(fHandle2 == nullptr,);
  472. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  473. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  474. {
  475. const ScopedSingleProcessLocker spl(this, true);
  476. try {
  477. fDssiDescriptor->set_custom_data(fHandle, const_cast<void*>(data), static_cast<ulong>(dataSize));
  478. } CARLA_SAFE_EXCEPTION("CarlaPluginDSSI::setChunkData");
  479. }
  480. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  481. const bool sendOsc(pData->engine->isOscControlRegistered());
  482. #else
  483. const bool sendOsc(false);
  484. #endif
  485. pData->updateParameterValues(this, sendOsc, true, false);
  486. }
  487. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  488. {
  489. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr,);
  490. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor->select_program != nullptr,);
  491. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  492. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  493. if (index >= 0)
  494. {
  495. const uint32_t bank(pData->midiprog.data[index].bank);
  496. const uint32_t program(pData->midiprog.data[index].program);
  497. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  498. try {
  499. fDssiDescriptor->select_program(fHandle, bank, program);
  500. } catch(...) {}
  501. if (fHandle2 != nullptr)
  502. {
  503. try {
  504. fDssiDescriptor->select_program(fHandle2, bank, program);
  505. } catch(...) {}
  506. }
  507. }
  508. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  509. }
  510. #ifdef HAVE_LIBLO
  511. // -------------------------------------------------------------------
  512. // Set ui stuff
  513. void showCustomUI(const bool yesNo) override
  514. {
  515. if (yesNo)
  516. {
  517. fOscData.clear();
  518. fThreadUI.startThread();
  519. }
  520. else
  521. {
  522. pData->transientTryCounter = 0;
  523. if (fOscData.target != nullptr)
  524. {
  525. osc_send_hide(fOscData);
  526. osc_send_quit(fOscData);
  527. fOscData.clear();
  528. }
  529. fThreadUI.stopThread(static_cast<int>(pData->engine->getOptions().uiBridgesTimeout * 2));
  530. }
  531. }
  532. #endif
  533. void idle() override
  534. {
  535. if (fLatencyChanged && fLatencyIndex != -1)
  536. {
  537. fLatencyChanged = false;
  538. const int32_t latency(static_cast<int32_t>(fParamBuffers[fLatencyIndex]));
  539. if (latency >= 0)
  540. {
  541. const uint32_t ulatency(static_cast<uint32_t>(latency));
  542. if (pData->latency != ulatency)
  543. {
  544. carla_stdout("latency changed to %i", latency);
  545. const ScopedSingleProcessLocker sspl(this, true);
  546. pData->latency = ulatency;
  547. pData->client->setLatency(ulatency);
  548. #ifndef BUILD_BRIDGE
  549. pData->recreateLatencyBuffers();
  550. #endif
  551. }
  552. }
  553. else
  554. carla_safe_assert_int("latency >= 0", __FILE__, __LINE__, latency);
  555. }
  556. CarlaPlugin::idle();
  557. }
  558. // -------------------------------------------------------------------
  559. // Plugin state
  560. void reload() override
  561. {
  562. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  563. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  564. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr,);
  565. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  566. carla_debug("CarlaPluginDSSI::reload() - start");
  567. const EngineProcessMode processMode(pData->engine->getProccessMode());
  568. // Safely disable plugin for reload
  569. const ScopedDisabler sd(this);
  570. if (pData->active)
  571. deactivate();
  572. clearBuffers();
  573. const float sampleRate(static_cast<float>(pData->engine->getSampleRate()));
  574. const uint32_t portCount(getSafePortCount());
  575. uint32_t aIns, aOuts, mIns, params;
  576. aIns = aOuts = mIns = params = 0;
  577. bool forcedStereoIn, forcedStereoOut;
  578. forcedStereoIn = forcedStereoOut = false;
  579. bool needsCtrlIn, needsCtrlOut;
  580. needsCtrlIn = needsCtrlOut = false;
  581. for (uint32_t i=0; i < portCount; ++i)
  582. {
  583. const LADSPA_PortDescriptor portType(fDescriptor->PortDescriptors[i]);
  584. if (LADSPA_IS_PORT_AUDIO(portType))
  585. {
  586. if (LADSPA_IS_PORT_INPUT(portType))
  587. aIns += 1;
  588. else if (LADSPA_IS_PORT_OUTPUT(portType))
  589. aOuts += 1;
  590. }
  591. else if (LADSPA_IS_PORT_CONTROL(portType))
  592. params += 1;
  593. }
  594. if ((pData->options & PLUGIN_OPTION_FORCE_STEREO) != 0 && (aIns == 1 || aOuts == 1))
  595. {
  596. if (fHandle2 == nullptr)
  597. {
  598. try {
  599. fHandle2 = fDescriptor->instantiate(fDescriptor, static_cast<ulong>(sampleRate));
  600. } CARLA_SAFE_EXCEPTION("DSSI instantiate #2");
  601. }
  602. if (fHandle2 != nullptr)
  603. {
  604. if (aIns == 1)
  605. {
  606. aIns = 2;
  607. forcedStereoIn = true;
  608. }
  609. if (aOuts == 1)
  610. {
  611. aOuts = 2;
  612. forcedStereoOut = true;
  613. }
  614. }
  615. }
  616. if (fDssiDescriptor->run_synth != nullptr || fDssiDescriptor->run_multiple_synths != nullptr)
  617. {
  618. mIns = 1;
  619. needsCtrlIn = true;
  620. }
  621. if (aIns > 0)
  622. {
  623. pData->audioIn.createNew(aIns);
  624. fAudioInBuffers = new float*[aIns];
  625. for (uint32_t i=0; i < aIns; ++i)
  626. fAudioInBuffers[i] = nullptr;
  627. }
  628. if (aOuts > 0)
  629. {
  630. pData->audioOut.createNew(aOuts);
  631. fAudioOutBuffers = new float*[aOuts];
  632. needsCtrlIn = true;
  633. for (uint32_t i=0; i < aOuts; ++i)
  634. fAudioOutBuffers[i] = nullptr;
  635. }
  636. if (params > 0)
  637. {
  638. pData->param.createNew(params, true);
  639. fParamBuffers = new float[params];
  640. FloatVectorOperations::clear(fParamBuffers, static_cast<int>(params));
  641. }
  642. const uint portNameSize(pData->engine->getMaxPortNameSize());
  643. CarlaString portName;
  644. for (uint32_t i=0, iAudioIn=0, iAudioOut=0, iCtrl=0; i < portCount; ++i)
  645. {
  646. const LADSPA_PortDescriptor portType = fDescriptor->PortDescriptors[i];
  647. const LADSPA_PortRangeHint portRangeHints = fDescriptor->PortRangeHints[i];
  648. if (LADSPA_IS_PORT_AUDIO(portType))
  649. {
  650. portName.clear();
  651. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  652. {
  653. portName = pData->name;
  654. portName += ":";
  655. }
  656. if (fDescriptor->PortNames[i] != nullptr && fDescriptor->PortNames[i][0] != '\0')
  657. {
  658. portName += fDescriptor->PortNames[i];
  659. }
  660. else
  661. {
  662. if (LADSPA_IS_PORT_INPUT(portType))
  663. {
  664. if (aIns > 1)
  665. {
  666. portName += "audio-in_";
  667. portName += CarlaString(iAudioIn+1);
  668. }
  669. else
  670. portName += "audio-in";
  671. }
  672. else
  673. {
  674. if (aOuts > 1)
  675. {
  676. portName += "audio-out_";
  677. portName += CarlaString(iAudioOut+1);
  678. }
  679. else
  680. portName += "audio-out";
  681. }
  682. }
  683. portName.truncate(portNameSize);
  684. if (LADSPA_IS_PORT_INPUT(portType))
  685. {
  686. const uint32_t j = iAudioIn++;
  687. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  688. pData->audioIn.ports[j].rindex = i;
  689. if (forcedStereoIn)
  690. {
  691. portName += "_2";
  692. pData->audioIn.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  693. pData->audioIn.ports[1].rindex = i;
  694. }
  695. }
  696. else if (LADSPA_IS_PORT_OUTPUT(portType))
  697. {
  698. const uint32_t j = iAudioOut++;
  699. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  700. pData->audioOut.ports[j].rindex = i;
  701. if (forcedStereoOut)
  702. {
  703. portName += "_2";
  704. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  705. pData->audioOut.ports[1].rindex = i;
  706. }
  707. }
  708. else
  709. carla_stderr2("WARNING - Got a broken Port (Audio, but not input or output)");
  710. }
  711. else if (LADSPA_IS_PORT_CONTROL(portType))
  712. {
  713. const uint32_t j = iCtrl++;
  714. pData->param.data[j].index = static_cast<int32_t>(j);
  715. pData->param.data[j].rindex = static_cast<int32_t>(i);
  716. const char* const paramName(fDescriptor->PortNames[i] != nullptr ? fDescriptor->PortNames[i] : "unknown");
  717. float min, max, def, step, stepSmall, stepLarge;
  718. // min value
  719. if (LADSPA_IS_HINT_BOUNDED_BELOW(portRangeHints.HintDescriptor))
  720. min = portRangeHints.LowerBound;
  721. else
  722. min = 0.0f;
  723. // max value
  724. if (LADSPA_IS_HINT_BOUNDED_ABOVE(portRangeHints.HintDescriptor))
  725. max = portRangeHints.UpperBound;
  726. else
  727. max = 1.0f;
  728. if (min > max)
  729. {
  730. carla_stderr2("WARNING - Broken plugin parameter '%s': min > max", paramName);
  731. min = max - 0.1f;
  732. }
  733. else if (carla_compareFloats(min, max))
  734. {
  735. carla_stderr2("WARNING - Broken plugin parameter '%s': min == max", paramName);
  736. max = min + 0.1f;
  737. }
  738. // default value
  739. def = get_default_ladspa_port_value(portRangeHints.HintDescriptor, min, max);
  740. if (def < min)
  741. def = min;
  742. else if (def > max)
  743. def = max;
  744. if (LADSPA_IS_HINT_SAMPLE_RATE(portRangeHints.HintDescriptor))
  745. {
  746. min *= sampleRate;
  747. max *= sampleRate;
  748. def *= sampleRate;
  749. pData->param.data[j].hints |= PARAMETER_USES_SAMPLERATE;
  750. }
  751. if (LADSPA_IS_HINT_TOGGLED(portRangeHints.HintDescriptor))
  752. {
  753. step = max - min;
  754. stepSmall = step;
  755. stepLarge = step;
  756. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  757. }
  758. else if (LADSPA_IS_HINT_INTEGER(portRangeHints.HintDescriptor))
  759. {
  760. step = 1.0f;
  761. stepSmall = 1.0f;
  762. stepLarge = 10.0f;
  763. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  764. }
  765. else
  766. {
  767. const float range = max - min;
  768. step = range/100.0f;
  769. stepSmall = range/1000.0f;
  770. stepLarge = range/10.0f;
  771. }
  772. if (LADSPA_IS_PORT_INPUT(portType))
  773. {
  774. pData->param.data[j].type = PARAMETER_INPUT;
  775. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  776. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  777. needsCtrlIn = true;
  778. // MIDI CC value
  779. if (fDssiDescriptor->get_midi_controller_for_port != nullptr)
  780. {
  781. int controller = fDssiDescriptor->get_midi_controller_for_port(fHandle, i);
  782. if (DSSI_CONTROLLER_IS_SET(controller) && DSSI_IS_CC(controller))
  783. {
  784. int16_t cc = DSSI_CC_NUMBER(controller);
  785. if (! MIDI_IS_CONTROL_BANK_SELECT(cc))
  786. pData->param.data[j].midiCC = cc;
  787. }
  788. }
  789. }
  790. else if (LADSPA_IS_PORT_OUTPUT(portType))
  791. {
  792. pData->param.data[j].type = PARAMETER_OUTPUT;
  793. if (std::strcmp(paramName, "latency") == 0 || std::strcmp(paramName, "_latency") == 0)
  794. {
  795. min = 0.0f;
  796. max = sampleRate;
  797. def = 0.0f;
  798. step = 1.0f;
  799. stepSmall = 1.0f;
  800. stepLarge = 1.0f;
  801. pData->param.special[j] = PARAMETER_SPECIAL_LATENCY;
  802. CARLA_SAFE_ASSERT(fLatencyIndex == -1);
  803. fLatencyIndex = static_cast<int32_t>(j);
  804. }
  805. else
  806. {
  807. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  808. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  809. needsCtrlOut = true;
  810. }
  811. }
  812. else
  813. {
  814. carla_stderr2("WARNING - Got a broken Port (Control, but not input or output)");
  815. }
  816. // extra parameter hints
  817. if (LADSPA_IS_HINT_LOGARITHMIC(portRangeHints.HintDescriptor))
  818. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  819. pData->param.ranges[j].min = min;
  820. pData->param.ranges[j].max = max;
  821. pData->param.ranges[j].def = def;
  822. pData->param.ranges[j].step = step;
  823. pData->param.ranges[j].stepSmall = stepSmall;
  824. pData->param.ranges[j].stepLarge = stepLarge;
  825. // Start parameters in their default values
  826. fParamBuffers[j] = def;
  827. try {
  828. fDescriptor->connect_port(fHandle, i, &fParamBuffers[j]);
  829. } CARLA_SAFE_EXCEPTION("DSSI connect_port parameter");
  830. if (fHandle2 != nullptr)
  831. {
  832. try {
  833. fDescriptor->connect_port(fHandle2, i, &fParamBuffers[j]);
  834. } CARLA_SAFE_EXCEPTION("DSSI connect_port parameter #2");
  835. }
  836. }
  837. else
  838. {
  839. // Not Audio or Control
  840. carla_stderr2("ERROR - Got a broken Port (neither Audio or Control)");
  841. try {
  842. fDescriptor->connect_port(fHandle, i, nullptr);
  843. } CARLA_SAFE_EXCEPTION("DSSI connect_port null");
  844. if (fHandle2 != nullptr)
  845. {
  846. try {
  847. fDescriptor->connect_port(fHandle2, i, nullptr);
  848. } CARLA_SAFE_EXCEPTION("DSSI connect_port null #2");
  849. }
  850. }
  851. }
  852. if (needsCtrlIn)
  853. {
  854. portName.clear();
  855. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  856. {
  857. portName = pData->name;
  858. portName += ":";
  859. }
  860. portName += "events-in";
  861. portName.truncate(portNameSize);
  862. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  863. }
  864. if (needsCtrlOut)
  865. {
  866. portName.clear();
  867. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  868. {
  869. portName = pData->name;
  870. portName += ":";
  871. }
  872. portName += "events-out";
  873. portName.truncate(portNameSize);
  874. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false);
  875. }
  876. if (forcedStereoIn || forcedStereoOut)
  877. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  878. else
  879. pData->options &= ~PLUGIN_OPTION_FORCE_STEREO;
  880. // plugin hints
  881. pData->hints = 0x0;
  882. if (LADSPA_IS_HARD_RT_CAPABLE(fDescriptor->Properties))
  883. pData->hints |= PLUGIN_IS_RTSAFE;
  884. #ifdef HAVE_LIBLO
  885. if (fUiFilename != nullptr)
  886. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  887. #endif
  888. #ifndef BUILD_BRIDGE
  889. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  890. pData->hints |= PLUGIN_CAN_DRYWET;
  891. if (aOuts > 0)
  892. pData->hints |= PLUGIN_CAN_VOLUME;
  893. if (aOuts >= 2 && aOuts % 2 == 0)
  894. pData->hints |= PLUGIN_CAN_BALANCE;
  895. #endif
  896. // extra plugin hints
  897. pData->extraHints = 0x0;
  898. if (mIns > 0)
  899. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  900. if (aIns <= 2 && aOuts <= 2 && (aIns == aOuts || aIns == 0 || aOuts == 0))
  901. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  902. // check latency
  903. if (fLatencyIndex >= 0)
  904. {
  905. // we need to pre-run the plugin so it can update its latency control-port
  906. float tmpIn [(aIns > 0) ? aIns : 1][2];
  907. float tmpOut[(aOuts > 0) ? aOuts : 1][2];
  908. for (uint32_t j=0; j < aIns; ++j)
  909. {
  910. tmpIn[j][0] = 0.0f;
  911. tmpIn[j][1] = 0.0f;
  912. try {
  913. fDescriptor->connect_port(fHandle, pData->audioIn.ports[j].rindex, tmpIn[j]);
  914. } CARLA_SAFE_EXCEPTION("DSSI connect_port latency input");
  915. }
  916. for (uint32_t j=0; j < aOuts; ++j)
  917. {
  918. tmpOut[j][0] = 0.0f;
  919. tmpOut[j][1] = 0.0f;
  920. try {
  921. fDescriptor->connect_port(fHandle, pData->audioOut.ports[j].rindex, tmpOut[j]);
  922. } CARLA_SAFE_EXCEPTION("DSSI connect_port latency output");
  923. }
  924. if (fDescriptor->activate != nullptr)
  925. {
  926. try {
  927. fDescriptor->activate(fHandle);
  928. } CARLA_SAFE_EXCEPTION("DSSI latency activate");
  929. }
  930. try {
  931. fDescriptor->run(fHandle, 2);
  932. } CARLA_SAFE_EXCEPTION("DSSI latency run");
  933. if (fDescriptor->deactivate != nullptr)
  934. {
  935. try {
  936. fDescriptor->deactivate(fHandle);
  937. } CARLA_SAFE_EXCEPTION("DSSI latency deactivate");
  938. }
  939. const int32_t latency(static_cast<int32_t>(fParamBuffers[fLatencyIndex]));
  940. if (latency >= 0)
  941. {
  942. const uint32_t ulatency(static_cast<uint32_t>(latency));
  943. if (pData->latency != ulatency)
  944. {
  945. carla_stdout("latency = %i", latency);
  946. pData->latency = ulatency;
  947. pData->client->setLatency(ulatency);
  948. #ifndef BUILD_BRIDGE
  949. pData->recreateLatencyBuffers();
  950. #endif
  951. }
  952. }
  953. else
  954. carla_safe_assert_int("latency >= 0", __FILE__, __LINE__, latency);
  955. fLatencyChanged = false;
  956. }
  957. bufferSizeChanged(pData->engine->getBufferSize());
  958. reloadPrograms(true);
  959. if (pData->active)
  960. activate();
  961. carla_debug("CarlaPluginDSSI::reload() - end");
  962. }
  963. void reloadPrograms(const bool doInit) override
  964. {
  965. carla_debug("CarlaPluginDSSI::reloadPrograms(%s)", bool2str(doInit));
  966. const uint32_t oldCount = pData->midiprog.count;
  967. const int32_t current = pData->midiprog.current;
  968. // Delete old programs
  969. pData->midiprog.clear();
  970. // Query new programs
  971. uint32_t newCount = 0;
  972. if (fDssiDescriptor->get_program != nullptr && fDssiDescriptor->select_program != nullptr)
  973. {
  974. for (; fDssiDescriptor->get_program(fHandle, newCount) != nullptr;)
  975. ++newCount;
  976. }
  977. if (newCount > 0)
  978. {
  979. pData->midiprog.createNew(newCount);
  980. // Update data
  981. for (uint32_t i=0; i < newCount; ++i)
  982. {
  983. const DSSI_Program_Descriptor* const pdesc(fDssiDescriptor->get_program(fHandle, i));
  984. CARLA_SAFE_ASSERT_CONTINUE(pdesc != nullptr);
  985. CARLA_SAFE_ASSERT(pdesc->Name != nullptr);
  986. pData->midiprog.data[i].bank = static_cast<uint32_t>(pdesc->Bank);
  987. pData->midiprog.data[i].program = static_cast<uint32_t>(pdesc->Program);
  988. pData->midiprog.data[i].name = carla_strdup(pdesc->Name);
  989. }
  990. }
  991. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  992. // Update OSC Names
  993. if (pData->engine->isOscControlRegistered())
  994. {
  995. pData->engine->oscSend_control_set_midi_program_count(pData->id, newCount);
  996. for (uint32_t i=0; i < newCount; ++i)
  997. pData->engine->oscSend_control_set_midi_program_data(pData->id, i, pData->midiprog.data[i].bank, pData->midiprog.data[i].program, pData->midiprog.data[i].name);
  998. }
  999. #endif
  1000. if (doInit)
  1001. {
  1002. if (newCount > 0)
  1003. setMidiProgram(0, false, false, false);
  1004. }
  1005. else
  1006. {
  1007. // Check if current program is invalid
  1008. bool programChanged = false;
  1009. if (newCount == oldCount+1)
  1010. {
  1011. // one midi program added, probably created by user
  1012. pData->midiprog.current = static_cast<int32_t>(oldCount);
  1013. programChanged = true;
  1014. }
  1015. else if (current < 0 && newCount > 0)
  1016. {
  1017. // programs exist now, but not before
  1018. pData->midiprog.current = 0;
  1019. programChanged = true;
  1020. }
  1021. else if (current >= 0 && newCount == 0)
  1022. {
  1023. // programs existed before, but not anymore
  1024. pData->midiprog.current = -1;
  1025. programChanged = true;
  1026. }
  1027. else if (current >= static_cast<int32_t>(newCount))
  1028. {
  1029. // current midi program > count
  1030. pData->midiprog.current = 0;
  1031. programChanged = true;
  1032. }
  1033. else
  1034. {
  1035. // no change
  1036. pData->midiprog.current = current;
  1037. }
  1038. if (programChanged)
  1039. setMidiProgram(pData->midiprog.current, true, true, true);
  1040. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  1041. }
  1042. }
  1043. // -------------------------------------------------------------------
  1044. // Plugin processing
  1045. void activate() noexcept override
  1046. {
  1047. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  1048. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1049. if (fDescriptor->activate != nullptr)
  1050. {
  1051. try {
  1052. fDescriptor->activate(fHandle);
  1053. } CARLA_SAFE_EXCEPTION("DSSI activate");
  1054. if (fHandle2 != nullptr)
  1055. {
  1056. try {
  1057. fDescriptor->activate(fHandle2);
  1058. } CARLA_SAFE_EXCEPTION("DSSI activate #2");
  1059. }
  1060. }
  1061. }
  1062. void deactivate() noexcept override
  1063. {
  1064. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  1065. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1066. if (fDescriptor->deactivate != nullptr)
  1067. {
  1068. try {
  1069. fDescriptor->deactivate(fHandle);
  1070. } CARLA_SAFE_EXCEPTION("DSSI deactivate");
  1071. if (fHandle2 != nullptr)
  1072. {
  1073. try {
  1074. fDescriptor->deactivate(fHandle2);
  1075. } CARLA_SAFE_EXCEPTION("DSSI deactivate #2");
  1076. }
  1077. }
  1078. }
  1079. void process(const float** const audioIn, float** const audioOut, const float** const cvIn, float** const cvOut, const uint32_t frames) override
  1080. {
  1081. // --------------------------------------------------------------------------------------------------------
  1082. // Check if active
  1083. if (! pData->active)
  1084. {
  1085. // disable any output sound
  1086. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1087. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  1088. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1089. FloatVectorOperations::clear(cvOut[i], static_cast<int>(frames));
  1090. return;
  1091. }
  1092. ulong midiEventCount = 0;
  1093. carla_zeroStruct<snd_seq_event_t>(fMidiEvents, kPluginMaxMidiEvents);
  1094. // --------------------------------------------------------------------------------------------------------
  1095. // Check if needs reset
  1096. if (pData->needsReset)
  1097. {
  1098. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1099. {
  1100. midiEventCount = MAX_MIDI_CHANNELS*2;
  1101. for (uchar i=0, k=MAX_MIDI_CHANNELS; i < MAX_MIDI_CHANNELS; ++i)
  1102. {
  1103. fMidiEvents[i].type = SND_SEQ_EVENT_CONTROLLER;
  1104. fMidiEvents[i].data.control.channel = i;
  1105. fMidiEvents[i].data.control.param = MIDI_CONTROL_ALL_NOTES_OFF;
  1106. fMidiEvents[k+i].type = SND_SEQ_EVENT_CONTROLLER;
  1107. fMidiEvents[k+i].data.control.channel = i;
  1108. fMidiEvents[k+i].data.control.param = MIDI_CONTROL_ALL_SOUND_OFF;
  1109. }
  1110. }
  1111. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  1112. {
  1113. midiEventCount = MAX_MIDI_NOTE;
  1114. for (uchar i=0; i < MAX_MIDI_NOTE; ++i)
  1115. {
  1116. fMidiEvents[i].type = SND_SEQ_EVENT_NOTEOFF;
  1117. fMidiEvents[i].data.note.channel = static_cast<uchar>(pData->ctrlChannel);
  1118. fMidiEvents[i].data.note.note = i;
  1119. }
  1120. }
  1121. #ifndef BUILD_BRIDGE
  1122. if (pData->latency > 0)
  1123. {
  1124. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1125. FloatVectorOperations::clear(pData->latencyBuffers[i], static_cast<int>(pData->latency));
  1126. }
  1127. #endif
  1128. pData->needsReset = false;
  1129. }
  1130. // --------------------------------------------------------------------------------------------------------
  1131. // Event Input and Processing
  1132. if (pData->event.portIn != nullptr)
  1133. {
  1134. // ----------------------------------------------------------------------------------------------------
  1135. // MIDI Input (External)
  1136. if (pData->extNotes.mutex.tryLock())
  1137. {
  1138. ExternalMidiNote note = { 0, 0, 0 };
  1139. for (; midiEventCount < kPluginMaxMidiEvents && ! pData->extNotes.data.isEmpty();)
  1140. {
  1141. note = pData->extNotes.data.getFirst(note, true);
  1142. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1143. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1144. seqEvent.type = (note.velo > 0) ? SND_SEQ_EVENT_NOTEON : SND_SEQ_EVENT_NOTEOFF;
  1145. seqEvent.data.note.channel = static_cast<uchar>(note.channel);
  1146. seqEvent.data.note.note = note.note;
  1147. seqEvent.data.note.velocity = note.velo;
  1148. }
  1149. pData->extNotes.mutex.unlock();
  1150. } // End of MIDI Input (External)
  1151. // ----------------------------------------------------------------------------------------------------
  1152. // Event Input (System)
  1153. #ifndef BUILD_BRIDGE
  1154. bool allNotesOffSent = false;
  1155. #endif
  1156. const bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  1157. uint32_t startTime = 0;
  1158. uint32_t timeOffset = 0;
  1159. uint32_t nextBankId;
  1160. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1161. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1162. else
  1163. nextBankId = 0;
  1164. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  1165. {
  1166. const EngineEvent& event(pData->event.portIn->getEvent(i));
  1167. if (event.time >= frames)
  1168. continue;
  1169. CARLA_ASSERT_INT2(event.time >= timeOffset, event.time, timeOffset);
  1170. if (isSampleAccurate && event.time > timeOffset)
  1171. {
  1172. if (processSingle(audioIn, audioOut, cvIn, cvOut, event.time - timeOffset, timeOffset, midiEventCount))
  1173. {
  1174. startTime = 0;
  1175. timeOffset = event.time;
  1176. midiEventCount = 0;
  1177. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1178. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1179. else
  1180. nextBankId = 0;
  1181. }
  1182. else
  1183. startTime += timeOffset;
  1184. }
  1185. switch (event.type)
  1186. {
  1187. case kEngineEventTypeNull:
  1188. break;
  1189. case kEngineEventTypeControl: {
  1190. const EngineControlEvent& ctrlEvent(event.ctrl);
  1191. switch (ctrlEvent.type)
  1192. {
  1193. case kEngineControlEventTypeNull:
  1194. break;
  1195. case kEngineControlEventTypeParameter: {
  1196. #ifndef BUILD_BRIDGE
  1197. // Control backend stuff
  1198. if (event.channel == pData->ctrlChannel)
  1199. {
  1200. float value;
  1201. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1202. {
  1203. value = ctrlEvent.value;
  1204. setDryWet(value, false, false);
  1205. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  1206. break;
  1207. }
  1208. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1209. {
  1210. value = ctrlEvent.value*127.0f/100.0f;
  1211. setVolume(value, false, false);
  1212. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  1213. break;
  1214. }
  1215. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1216. {
  1217. float left, right;
  1218. value = ctrlEvent.value/0.5f - 1.0f;
  1219. if (value < 0.0f)
  1220. {
  1221. left = -1.0f;
  1222. right = (value*2.0f)+1.0f;
  1223. }
  1224. else if (value > 0.0f)
  1225. {
  1226. left = (value*2.0f)-1.0f;
  1227. right = 1.0f;
  1228. }
  1229. else
  1230. {
  1231. left = -1.0f;
  1232. right = 1.0f;
  1233. }
  1234. setBalanceLeft(left, false, false);
  1235. setBalanceRight(right, false, false);
  1236. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  1237. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  1238. break;
  1239. }
  1240. }
  1241. #endif
  1242. // Control plugin parameters
  1243. uint32_t k;
  1244. for (k=0; k < pData->param.count; ++k)
  1245. {
  1246. if (pData->param.data[k].midiChannel != event.channel)
  1247. continue;
  1248. if (pData->param.data[k].midiCC != ctrlEvent.param)
  1249. continue;
  1250. if (pData->param.data[k].type != PARAMETER_INPUT)
  1251. continue;
  1252. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  1253. continue;
  1254. float value;
  1255. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  1256. {
  1257. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  1258. }
  1259. else
  1260. {
  1261. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  1262. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  1263. value = std::rint(value);
  1264. }
  1265. setParameterValue(k, value, false, false, false);
  1266. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  1267. break;
  1268. }
  1269. // check if event is already handled
  1270. if (k != pData->param.count)
  1271. break;
  1272. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_CONTROL)
  1273. {
  1274. if (midiEventCount >= kPluginMaxMidiEvents)
  1275. continue;
  1276. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1277. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1278. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1279. seqEvent.data.control.channel = event.channel;
  1280. seqEvent.data.control.param = ctrlEvent.param;
  1281. seqEvent.data.control.value = int8_t(ctrlEvent.value*127.0f);
  1282. }
  1283. break;
  1284. } // case kEngineControlEventTypeParameter
  1285. case kEngineControlEventTypeMidiBank:
  1286. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1287. nextBankId = ctrlEvent.param;
  1288. break;
  1289. case kEngineControlEventTypeMidiProgram:
  1290. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1291. {
  1292. const uint32_t nextProgramId = ctrlEvent.param;
  1293. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  1294. {
  1295. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  1296. {
  1297. const int32_t index(static_cast<int32_t>(k));
  1298. setMidiProgram(index, false, false, false);
  1299. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, index, 0, 0.0f);
  1300. break;
  1301. }
  1302. }
  1303. }
  1304. break;
  1305. case kEngineControlEventTypeAllSoundOff:
  1306. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1307. {
  1308. if (midiEventCount >= kPluginMaxMidiEvents)
  1309. continue;
  1310. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1311. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1312. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1313. seqEvent.data.control.channel = event.channel;
  1314. seqEvent.data.control.param = MIDI_CONTROL_ALL_SOUND_OFF;
  1315. }
  1316. break;
  1317. case kEngineControlEventTypeAllNotesOff:
  1318. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1319. {
  1320. #ifndef BUILD_BRIDGE
  1321. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1322. {
  1323. allNotesOffSent = true;
  1324. sendMidiAllNotesOffToCallback();
  1325. }
  1326. #endif
  1327. if (midiEventCount >= kPluginMaxMidiEvents)
  1328. continue;
  1329. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1330. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1331. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1332. seqEvent.data.control.channel = event.channel;
  1333. seqEvent.data.control.param = MIDI_CONTROL_ALL_NOTES_OFF;
  1334. }
  1335. break;
  1336. } // switch (ctrlEvent.type)
  1337. break;
  1338. } // case kEngineEventTypeControl
  1339. case kEngineEventTypeMidi: {
  1340. if (midiEventCount >= kPluginMaxMidiEvents)
  1341. continue;
  1342. const EngineMidiEvent& midiEvent(event.midi);
  1343. if (midiEvent.size > EngineMidiEvent::kDataSize)
  1344. continue;
  1345. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1346. // Fix bad note-off (per DSSI spec)
  1347. if (status == MIDI_STATUS_NOTE_ON && midiEvent.data[2] == 0)
  1348. status = MIDI_STATUS_NOTE_OFF;
  1349. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1350. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1351. switch (status)
  1352. {
  1353. case MIDI_STATUS_NOTE_OFF: {
  1354. const uint8_t note = midiEvent.data[1];
  1355. seqEvent.type = SND_SEQ_EVENT_NOTEOFF;
  1356. seqEvent.data.note.channel = event.channel;
  1357. seqEvent.data.note.note = note;
  1358. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, note, 0.0f);
  1359. break;
  1360. }
  1361. case MIDI_STATUS_NOTE_ON: {
  1362. const uint8_t note = midiEvent.data[1];
  1363. const uint8_t velo = midiEvent.data[2];
  1364. seqEvent.type = SND_SEQ_EVENT_NOTEON;
  1365. seqEvent.data.note.channel = event.channel;
  1366. seqEvent.data.note.note = note;
  1367. seqEvent.data.note.velocity = velo;
  1368. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, note, velo);
  1369. break;
  1370. }
  1371. case MIDI_STATUS_POLYPHONIC_AFTERTOUCH:
  1372. if (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH)
  1373. {
  1374. const uint8_t note = midiEvent.data[1];
  1375. const uint8_t pressure = midiEvent.data[2];
  1376. seqEvent.type = SND_SEQ_EVENT_KEYPRESS;
  1377. seqEvent.data.note.channel = event.channel;
  1378. seqEvent.data.note.note = note;
  1379. seqEvent.data.note.velocity = pressure;
  1380. }
  1381. break;
  1382. case MIDI_STATUS_CONTROL_CHANGE:
  1383. if (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES)
  1384. {
  1385. const uint8_t control = midiEvent.data[1];
  1386. const uint8_t value = midiEvent.data[2];
  1387. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1388. seqEvent.data.control.channel = event.channel;
  1389. seqEvent.data.control.param = control;
  1390. seqEvent.data.control.value = value;
  1391. }
  1392. break;
  1393. case MIDI_STATUS_CHANNEL_PRESSURE:
  1394. if (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE)
  1395. {
  1396. const uint8_t pressure = midiEvent.data[1];
  1397. seqEvent.type = SND_SEQ_EVENT_CHANPRESS;
  1398. seqEvent.data.control.channel = event.channel;
  1399. seqEvent.data.control.value = pressure;
  1400. }
  1401. break;
  1402. case MIDI_STATUS_PITCH_WHEEL_CONTROL:
  1403. if (pData->options & PLUGIN_OPTION_SEND_PITCHBEND)
  1404. {
  1405. const uint8_t lsb = midiEvent.data[1];
  1406. const uint8_t msb = midiEvent.data[2];
  1407. seqEvent.type = SND_SEQ_EVENT_PITCHBEND;
  1408. seqEvent.data.control.channel = event.channel;
  1409. seqEvent.data.control.value = ((msb << 7) | lsb) - 8192;
  1410. }
  1411. break;
  1412. default:
  1413. --midiEventCount;
  1414. break;
  1415. } // switch (status)
  1416. } break;
  1417. } // switch (event.type)
  1418. }
  1419. pData->postRtEvents.trySplice();
  1420. if (frames > timeOffset)
  1421. processSingle(audioIn, audioOut, cvIn, cvOut, frames - timeOffset, timeOffset, midiEventCount);
  1422. } // End of Event Input and Processing
  1423. // --------------------------------------------------------------------------------------------------------
  1424. // Plugin processing (no events)
  1425. else
  1426. {
  1427. processSingle(audioIn, audioOut, cvIn, cvOut, frames, 0, midiEventCount);
  1428. } // End of Plugin processing (no events)
  1429. #ifndef BUILD_BRIDGE
  1430. // --------------------------------------------------------------------------------------------------------
  1431. // Latency, save values for next callback
  1432. if (fLatencyIndex != -1)
  1433. {
  1434. if (pData->latency != static_cast<uint32_t>(fParamBuffers[fLatencyIndex]))
  1435. {
  1436. fLatencyChanged = true;
  1437. }
  1438. else if (pData->latency > 0)
  1439. {
  1440. if (pData->latency <= frames)
  1441. {
  1442. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1443. FloatVectorOperations::copy(pData->latencyBuffers[i], audioIn[i]+(frames-pData->latency), static_cast<int>(pData->latency));
  1444. }
  1445. else
  1446. {
  1447. for (uint32_t i=0, j, k; i < pData->audioIn.count; ++i)
  1448. {
  1449. for (k=0; k < pData->latency-frames; ++k)
  1450. pData->latencyBuffers[i][k] = pData->latencyBuffers[i][k+frames];
  1451. for (j=0; k < pData->latency; ++j, ++k)
  1452. pData->latencyBuffers[i][k] = audioIn[i][j];
  1453. }
  1454. }
  1455. }
  1456. }
  1457. // --------------------------------------------------------------------------------------------------------
  1458. // Control Output
  1459. if (pData->event.portOut != nullptr)
  1460. {
  1461. uint8_t channel;
  1462. uint16_t param;
  1463. float value;
  1464. for (uint32_t k=0; k < pData->param.count; ++k)
  1465. {
  1466. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  1467. continue;
  1468. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  1469. if (pData->param.data[k].midiCC > 0)
  1470. {
  1471. channel = pData->param.data[k].midiChannel;
  1472. param = static_cast<uint16_t>(pData->param.data[k].midiCC);
  1473. value = pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]);
  1474. pData->event.portOut->writeControlEvent(0, channel, kEngineControlEventTypeParameter, param, value);
  1475. }
  1476. }
  1477. } // End of Control Output
  1478. #endif
  1479. }
  1480. bool processSingle(const float** const audioIn, float** const audioOut, const float** const cvIn, float** const cvOut, const uint32_t frames, const uint32_t timeOffset, const ulong midiEventCount)
  1481. {
  1482. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1483. if (pData->audioIn.count > 0)
  1484. {
  1485. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  1486. }
  1487. if (pData->audioOut.count > 0)
  1488. {
  1489. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  1490. }
  1491. if (pData->cvIn.count > 0)
  1492. {
  1493. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  1494. }
  1495. if (pData->cvOut.count > 0)
  1496. {
  1497. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  1498. }
  1499. // --------------------------------------------------------------------------------------------------------
  1500. // Try lock, silence otherwise
  1501. if (pData->engine->isOffline())
  1502. {
  1503. pData->singleMutex.lock();
  1504. }
  1505. else if (! pData->singleMutex.tryLock())
  1506. {
  1507. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1508. {
  1509. for (uint32_t k=0; k < frames; ++k)
  1510. audioOut[i][k+timeOffset] = 0.0f;
  1511. }
  1512. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1513. {
  1514. for (uint32_t k=0; k < frames; ++k)
  1515. cvOut[i][k+timeOffset] = 0.0f;
  1516. }
  1517. return false;
  1518. }
  1519. // --------------------------------------------------------------------------------------------------------
  1520. // Set audio buffers
  1521. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1522. FloatVectorOperations::copy(fAudioInBuffers[i], audioIn[i]+timeOffset, static_cast<int>(frames));
  1523. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1524. FloatVectorOperations::clear(fAudioOutBuffers[i], static_cast<int>(frames));
  1525. #if 0
  1526. // --------------------------------------------------------------------------------------------------------
  1527. // Set CV buffers
  1528. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  1529. FloatVectorOperations::copy(fCvInBuffers[i], cvIn[i]+timeOffset, static_cast<int>(frames));
  1530. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1531. FloatVectorOperations::clear(fCvOutBuffers[i], static_cast<int>(frames));
  1532. #endif
  1533. // --------------------------------------------------------------------------------------------------------
  1534. // Run plugin
  1535. // TODO - try catch
  1536. if (fDssiDescriptor->run_synth != nullptr)
  1537. {
  1538. fDssiDescriptor->run_synth(fHandle, frames, fMidiEvents, midiEventCount);
  1539. if (fHandle2 != nullptr)
  1540. fDssiDescriptor->run_synth(fHandle2, frames, fMidiEvents, midiEventCount);
  1541. }
  1542. else if (fDssiDescriptor->run_multiple_synths != nullptr)
  1543. {
  1544. ulong instances = (fHandle2 != nullptr) ? 2 : 1;
  1545. LADSPA_Handle handlePtr[2] = { fHandle, fHandle2 };
  1546. snd_seq_event_t* midiEventsPtr[2] = { fMidiEvents, fMidiEvents };
  1547. ulong midiEventCountPtr[2] = { midiEventCount, midiEventCount };
  1548. fDssiDescriptor->run_multiple_synths(instances, handlePtr, frames, midiEventsPtr, midiEventCountPtr);
  1549. }
  1550. else
  1551. {
  1552. fDescriptor->run(fHandle, frames);
  1553. if (fHandle2 != nullptr)
  1554. fDescriptor->run(fHandle2, frames);
  1555. }
  1556. #ifndef BUILD_BRIDGE
  1557. // --------------------------------------------------------------------------------------------------------
  1558. // Post-processing (dry/wet, volume and balance)
  1559. {
  1560. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && ! carla_compareFloats(pData->postProc.dryWet, 1.0f);
  1561. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_compareFloats(pData->postProc.balanceLeft, -1.0f) && carla_compareFloats(pData->postProc.balanceRight, 1.0f));
  1562. const bool isMono = (pData->audioIn.count == 1);
  1563. bool isPair;
  1564. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1565. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1566. {
  1567. // Dry/Wet
  1568. if (doDryWet)
  1569. {
  1570. for (uint32_t k=0; k < frames; ++k)
  1571. {
  1572. if (k < pData->latency)
  1573. bufValue = pData->latencyBuffers[isMono ? 0 : i][k];
  1574. else if (pData->latency < frames)
  1575. bufValue = fAudioInBuffers[isMono ? 0 : i][k-pData->latency];
  1576. else
  1577. bufValue = fAudioInBuffers[isMono ? 0 : i][k];
  1578. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1579. }
  1580. }
  1581. // Balance
  1582. if (doBalance)
  1583. {
  1584. isPair = (i % 2 == 0);
  1585. if (isPair)
  1586. {
  1587. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1588. FloatVectorOperations::copy(oldBufLeft, fAudioOutBuffers[i], static_cast<int>(frames));
  1589. }
  1590. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1591. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1592. for (uint32_t k=0; k < frames; ++k)
  1593. {
  1594. if (isPair)
  1595. {
  1596. // left
  1597. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1598. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  1599. }
  1600. else
  1601. {
  1602. // right
  1603. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  1604. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  1605. }
  1606. }
  1607. }
  1608. // Volume (and buffer copy)
  1609. {
  1610. for (uint32_t k=0; k < frames; ++k)
  1611. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  1612. }
  1613. }
  1614. } // End of Post-processing
  1615. #else // BUILD_BRIDGE
  1616. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1617. {
  1618. for (uint32_t k=0; k < frames; ++k)
  1619. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k];
  1620. }
  1621. #endif
  1622. #if 0
  1623. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1624. {
  1625. for (uint32_t k=0; k < frames; ++k)
  1626. cvOut[i][k+timeOffset] = fCvOutBuffers[i][k];
  1627. }
  1628. #endif
  1629. // --------------------------------------------------------------------------------------------------------
  1630. pData->singleMutex.unlock();
  1631. return true;
  1632. }
  1633. void bufferSizeChanged(const uint32_t newBufferSize) override
  1634. {
  1635. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1636. carla_debug("CarlaPluginDSSI::bufferSizeChanged(%i) - start", newBufferSize);
  1637. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1638. {
  1639. if (fAudioInBuffers[i] != nullptr)
  1640. delete[] fAudioInBuffers[i];
  1641. fAudioInBuffers[i] = new float[newBufferSize];
  1642. }
  1643. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1644. {
  1645. if (fAudioOutBuffers[i] != nullptr)
  1646. delete[] fAudioOutBuffers[i];
  1647. fAudioOutBuffers[i] = new float[newBufferSize];
  1648. }
  1649. if (fHandle2 == nullptr)
  1650. {
  1651. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1652. {
  1653. CARLA_ASSERT(fAudioInBuffers[i] != nullptr);
  1654. try {
  1655. fDescriptor->connect_port(fHandle, pData->audioIn.ports[i].rindex, fAudioInBuffers[i]);
  1656. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio input");
  1657. }
  1658. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1659. {
  1660. CARLA_ASSERT(fAudioOutBuffers[i] != nullptr);
  1661. try {
  1662. fDescriptor->connect_port(fHandle, pData->audioOut.ports[i].rindex, fAudioOutBuffers[i]);
  1663. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio output");
  1664. }
  1665. }
  1666. else
  1667. {
  1668. if (pData->audioIn.count > 0)
  1669. {
  1670. CARLA_ASSERT(pData->audioIn.count == 2);
  1671. CARLA_ASSERT(fAudioInBuffers[0] != nullptr);
  1672. CARLA_ASSERT(fAudioInBuffers[1] != nullptr);
  1673. try {
  1674. fDescriptor->connect_port(fHandle, pData->audioIn.ports[0].rindex, fAudioInBuffers[0]);
  1675. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio input #1");
  1676. try {
  1677. fDescriptor->connect_port(fHandle2, pData->audioIn.ports[1].rindex, fAudioInBuffers[1]);
  1678. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio input #2");
  1679. }
  1680. if (pData->audioOut.count > 0)
  1681. {
  1682. CARLA_ASSERT(pData->audioOut.count == 2);
  1683. CARLA_ASSERT(fAudioOutBuffers[0] != nullptr);
  1684. CARLA_ASSERT(fAudioOutBuffers[1] != nullptr);
  1685. try {
  1686. fDescriptor->connect_port(fHandle, pData->audioOut.ports[0].rindex, fAudioOutBuffers[0]);
  1687. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio output #1");
  1688. try {
  1689. fDescriptor->connect_port(fHandle2, pData->audioOut.ports[1].rindex, fAudioOutBuffers[1]);
  1690. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio output #2");
  1691. }
  1692. }
  1693. carla_debug("CarlaPluginDSSI::bufferSizeChanged(%i) - end", newBufferSize);
  1694. }
  1695. void sampleRateChanged(const double newSampleRate) override
  1696. {
  1697. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1698. carla_debug("CarlaPluginDSSI::sampleRateChanged(%g) - start", newSampleRate);
  1699. // TODO
  1700. (void)newSampleRate;
  1701. carla_debug("CarlaPluginDSSI::sampleRateChanged(%g) - end", newSampleRate);
  1702. }
  1703. // -------------------------------------------------------------------
  1704. // Plugin buffers
  1705. void clearBuffers() noexcept override
  1706. {
  1707. carla_debug("CarlaPluginDSSI::clearBuffers() - start");
  1708. if (fAudioInBuffers != nullptr)
  1709. {
  1710. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1711. {
  1712. if (fAudioInBuffers[i] != nullptr)
  1713. {
  1714. delete[] fAudioInBuffers[i];
  1715. fAudioInBuffers[i] = nullptr;
  1716. }
  1717. }
  1718. delete[] fAudioInBuffers;
  1719. fAudioInBuffers = nullptr;
  1720. }
  1721. if (fAudioOutBuffers != nullptr)
  1722. {
  1723. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1724. {
  1725. if (fAudioOutBuffers[i] != nullptr)
  1726. {
  1727. delete[] fAudioOutBuffers[i];
  1728. fAudioOutBuffers[i] = nullptr;
  1729. }
  1730. }
  1731. delete[] fAudioOutBuffers;
  1732. fAudioOutBuffers = nullptr;
  1733. }
  1734. if (fParamBuffers != nullptr)
  1735. {
  1736. delete[] fParamBuffers;
  1737. fParamBuffers = nullptr;
  1738. }
  1739. CarlaPlugin::clearBuffers();
  1740. carla_debug("CarlaPluginDSSI::clearBuffers() - end");
  1741. }
  1742. #ifdef HAVE_LIBLO
  1743. // -------------------------------------------------------------------
  1744. // OSC stuff
  1745. void handleOscMessage(const char* const method, const int argc, const void* const argvx, const char* const types, const lo_message msg) override
  1746. {
  1747. const lo_address source(lo_message_get_source(msg));
  1748. CARLA_SAFE_ASSERT_RETURN(source != nullptr,);
  1749. // protocol for DSSI UIs *must* be UDP
  1750. CARLA_SAFE_ASSERT_RETURN(lo_address_get_protocol(source) == LO_UDP,);
  1751. if (fOscData.source == nullptr)
  1752. {
  1753. // if no UI is registered yet only "update" message is valid
  1754. CARLA_SAFE_ASSERT_RETURN(std::strcmp(method, "update") == 0,)
  1755. }
  1756. else
  1757. {
  1758. // make sure message source is the DSSI UI
  1759. const char* const msghost = lo_address_get_hostname(source);
  1760. const char* const msgport = lo_address_get_port(source);
  1761. const char* const ourhost = lo_address_get_hostname(fOscData.source);
  1762. const char* const ourport = lo_address_get_port(fOscData.source);
  1763. CARLA_SAFE_ASSERT_RETURN(std::strcmp(msghost, ourhost) == 0,);
  1764. CARLA_SAFE_ASSERT_RETURN(std::strcmp(msgport, ourport) == 0,);
  1765. }
  1766. const lo_arg* const* const argv(static_cast<const lo_arg* const* const>(argvx));
  1767. if (std::strcmp(method, "configure") == 0)
  1768. return handleOscMessageConfigure(argc, argv, types);
  1769. if (std::strcmp(method, "control") == 0)
  1770. return handleOscMessageControl(argc, argv, types);
  1771. if (std::strcmp(method, "program") == 0)
  1772. return handleOscMessageProgram(argc, argv, types);
  1773. if (std::strcmp(method, "midi") == 0)
  1774. return handleOscMessageMIDI(argc, argv, types);
  1775. if (std::strcmp(method, "update") == 0)
  1776. return handleOscMessageUpdate(argc, argv, types, lo_message_get_source(msg));
  1777. if (std::strcmp(method, "exiting") == 0)
  1778. return handleOscMessageExiting();
  1779. carla_stdout("CarlaPluginDSSI::handleOscMessage() - unknown method '%s'", method);
  1780. }
  1781. void handleOscMessageConfigure(const int argc, const lo_arg* const* const argv, const char* const types)
  1782. {
  1783. carla_debug("CarlaPluginDSSI::handleMsgConfigure()");
  1784. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(2, "ss");
  1785. const char* const key = (const char*)&argv[0]->s;
  1786. const char* const value = (const char*)&argv[1]->s;
  1787. setCustomData(CUSTOM_DATA_TYPE_STRING, key, value, false);
  1788. }
  1789. void handleOscMessageControl(const int argc, const lo_arg* const* const argv, const char* const types)
  1790. {
  1791. carla_debug("CarlaPluginDSSI::handleMsgControl()");
  1792. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(2, "if");
  1793. const int32_t rindex = argv[0]->i;
  1794. const float value = argv[1]->f;
  1795. setParameterValueByRealIndex(rindex, value, false, true, true);
  1796. }
  1797. void handleOscMessageProgram(const int argc, const lo_arg* const* const argv, const char* const types)
  1798. {
  1799. carla_debug("CarlaPluginDSSI::handleMsgProgram()");
  1800. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(2, "ii");
  1801. const int32_t bank = argv[0]->i;
  1802. const int32_t program = argv[1]->i;
  1803. CARLA_SAFE_ASSERT_RETURN(bank >= 0,);
  1804. CARLA_SAFE_ASSERT_RETURN(program >= 0,);
  1805. setMidiProgramById(static_cast<uint32_t>(bank), static_cast<uint32_t>(program), false, true, true);
  1806. }
  1807. void handleOscMessageMIDI(const int argc, const lo_arg* const* const argv, const char* const types)
  1808. {
  1809. carla_debug("CarlaPluginDSSI::handleMsgMidi()");
  1810. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(1, "m");
  1811. if (getMidiInCount() == 0)
  1812. {
  1813. carla_stderr("CarlaPluginDSSI::handleMsgMidi() - received midi when plugin has no midi inputs");
  1814. return;
  1815. }
  1816. const uint8_t* const data = argv[0]->m;
  1817. uint8_t status = data[1];
  1818. uint8_t channel = status & 0x0F;
  1819. // Fix bad note-off
  1820. if (MIDI_IS_STATUS_NOTE_ON(status) && data[3] == 0)
  1821. status = MIDI_STATUS_NOTE_OFF;
  1822. if (MIDI_IS_STATUS_NOTE_OFF(status))
  1823. {
  1824. const uint8_t note = data[2];
  1825. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1826. sendMidiSingleNote(channel, note, 0, false, true, true);
  1827. }
  1828. else if (MIDI_IS_STATUS_NOTE_ON(status))
  1829. {
  1830. const uint8_t note = data[2];
  1831. const uint8_t velo = data[3];
  1832. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1833. CARLA_SAFE_ASSERT_RETURN(velo < MAX_MIDI_VALUE,);
  1834. sendMidiSingleNote(channel, note, velo, false, true, true);
  1835. }
  1836. }
  1837. void handleOscMessageUpdate(const int argc, const lo_arg* const* const argv, const char* const types, const lo_address source)
  1838. {
  1839. carla_debug("CarlaPluginDSSI::handleMsgUpdate()");
  1840. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(1, "s");
  1841. const char* const url = (const char*)&argv[0]->s;
  1842. // FIXME - remove debug prints later
  1843. carla_stdout("CarlaPluginDSSI::updateOscData(%p, \"%s\")", source, url);
  1844. fOscData.clear();
  1845. const int proto = lo_address_get_protocol(source);
  1846. {
  1847. const char* host = lo_address_get_hostname(source);
  1848. const char* port = lo_address_get_port(source);
  1849. fOscData.source = lo_address_new_with_proto(proto, host, port);
  1850. carla_stdout("CarlaPlugin::updateOscData() - source: host \"%s\", port \"%s\"", host, port);
  1851. }
  1852. {
  1853. char* host = lo_url_get_hostname(url);
  1854. char* port = lo_url_get_port(url);
  1855. fOscData.path = carla_strdup_free(lo_url_get_path(url));
  1856. fOscData.target = lo_address_new_with_proto(proto, host, port);
  1857. carla_stdout("CarlaPlugin::updateOscData() - target: host \"%s\", port \"%s\", path \"%s\"", host, port, fOscData.path);
  1858. std::free(host);
  1859. std::free(port);
  1860. }
  1861. osc_send_sample_rate(fOscData, static_cast<float>(pData->engine->getSampleRate()));
  1862. for (LinkedList<CustomData>::Itenerator it = pData->custom.begin(); it.valid(); it.next())
  1863. {
  1864. const CustomData& customData(it.getValue(kCustomDataFallback));
  1865. CARLA_SAFE_ASSERT_CONTINUE(customData.isValid());
  1866. if (std::strcmp(customData.type, CUSTOM_DATA_TYPE_STRING) == 0)
  1867. osc_send_configure(fOscData, customData.key, customData.value);
  1868. }
  1869. if (pData->prog.current >= 0)
  1870. osc_send_program(fOscData, static_cast<uint32_t>(pData->prog.current));
  1871. if (pData->midiprog.current >= 0)
  1872. {
  1873. const MidiProgramData& curMidiProg(pData->midiprog.getCurrent());
  1874. if (getType() == PLUGIN_DSSI)
  1875. osc_send_program(fOscData, curMidiProg.bank, curMidiProg.program);
  1876. else
  1877. osc_send_midi_program(fOscData, curMidiProg.bank, curMidiProg.program);
  1878. }
  1879. for (uint32_t i=0; i < pData->param.count; ++i)
  1880. osc_send_control(fOscData, pData->param.data[i].rindex, getParameterValue(i));
  1881. if ((pData->hints & PLUGIN_HAS_CUSTOM_UI) != 0 && pData->engine->getOptions().frontendWinId != 0)
  1882. pData->transientTryCounter = 1;
  1883. carla_stdout("CarlaPluginDSSI::updateOscData() - done");
  1884. }
  1885. void handleOscMessageExiting()
  1886. {
  1887. carla_debug("CarlaPluginDSSI::handleMsgExiting()");
  1888. // hide UI
  1889. showCustomUI(false);
  1890. // tell frontend
  1891. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1892. }
  1893. #endif
  1894. #ifdef HAVE_LIBLO
  1895. // -------------------------------------------------------------------
  1896. // Post-poned UI Stuff
  1897. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1898. {
  1899. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1900. if (fOscData.target == nullptr)
  1901. return;
  1902. osc_send_control(fOscData, pData->param.data[index].rindex, value);
  1903. }
  1904. void uiMidiProgramChange(const uint32_t index) noexcept override
  1905. {
  1906. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1907. if (fOscData.target == nullptr)
  1908. return;
  1909. osc_send_program(fOscData, pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  1910. }
  1911. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  1912. {
  1913. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1914. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1915. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  1916. if (fOscData.target == nullptr)
  1917. return;
  1918. #if 0
  1919. uint8_t midiData[4];
  1920. midiData[0] = 0;
  1921. midiData[1] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  1922. midiData[2] = note;
  1923. midiData[3] = velo;
  1924. osc_send_midi(fOscData, midiData);
  1925. #endif
  1926. }
  1927. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  1928. {
  1929. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1930. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1931. if (fOscData.target == nullptr)
  1932. return;
  1933. #if 0
  1934. uint8_t midiData[4];
  1935. midiData[0] = 0;
  1936. midiData[1] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  1937. midiData[2] = note;
  1938. midiData[3] = 0;
  1939. osc_send_midi(fOscData, midiData);
  1940. #endif
  1941. }
  1942. #endif
  1943. // -------------------------------------------------------------------
  1944. void* getNativeHandle() const noexcept override
  1945. {
  1946. return fHandle;
  1947. }
  1948. const void* getNativeDescriptor() const noexcept override
  1949. {
  1950. return fDssiDescriptor;
  1951. }
  1952. #ifdef HAVE_LIBLO
  1953. uintptr_t getUiBridgeProcessId() const noexcept override
  1954. {
  1955. return fThreadUI.getProcessPID();
  1956. }
  1957. const void* getExtraStuff() const noexcept override
  1958. {
  1959. return fUiFilename;
  1960. }
  1961. #endif
  1962. // -------------------------------------------------------------------
  1963. bool init(const char* const filename, const char* const name, const char* const label)
  1964. {
  1965. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1966. // ---------------------------------------------------------------
  1967. // first checks
  1968. if (pData->client != nullptr)
  1969. {
  1970. pData->engine->setLastError("Plugin client is already registered");
  1971. return false;
  1972. }
  1973. if (filename == nullptr || filename[0] == '\0')
  1974. {
  1975. pData->engine->setLastError("null filename");
  1976. return false;
  1977. }
  1978. if (label == nullptr || label[0] == '\0')
  1979. {
  1980. pData->engine->setLastError("null label");
  1981. return false;
  1982. }
  1983. // ---------------------------------------------------------------
  1984. // open DLL
  1985. if (! pData->libOpen(filename))
  1986. {
  1987. pData->engine->setLastError(pData->libError(filename));
  1988. return false;
  1989. }
  1990. // ---------------------------------------------------------------
  1991. // get DLL main entry
  1992. const DSSI_Descriptor_Function descFn = pData->libSymbol<DSSI_Descriptor_Function>("dssi_descriptor");
  1993. if (descFn == nullptr)
  1994. {
  1995. pData->engine->setLastError("Could not find the DSSI Descriptor in the plugin library");
  1996. return false;
  1997. }
  1998. // ---------------------------------------------------------------
  1999. // get descriptor that matches label
  2000. ulong i = 0;
  2001. for (;;)
  2002. {
  2003. try {
  2004. fDssiDescriptor = descFn(i++);
  2005. }
  2006. catch(...) {
  2007. carla_stderr2("Caught exception when trying to get LADSPA descriptor");
  2008. fDescriptor = nullptr;
  2009. fDssiDescriptor = nullptr;
  2010. break;
  2011. }
  2012. if (fDssiDescriptor == nullptr)
  2013. break;
  2014. fDescriptor = fDssiDescriptor->LADSPA_Plugin;
  2015. if (fDescriptor == nullptr)
  2016. {
  2017. carla_stderr2("WARNING - Missing LADSPA interface, will not use this plugin");
  2018. fDssiDescriptor = nullptr;
  2019. break;
  2020. }
  2021. if (fDescriptor->Label == nullptr || fDescriptor->Label[0] == '\0')
  2022. {
  2023. carla_stderr2("WARNING - Got an invalid label, will not use this plugin");
  2024. fDescriptor = nullptr;
  2025. fDssiDescriptor = nullptr;
  2026. break;
  2027. }
  2028. if (fDescriptor->run == nullptr)
  2029. {
  2030. carla_stderr2("WARNING - Plugin has no run, cannot use it");
  2031. fDescriptor = nullptr;
  2032. fDssiDescriptor = nullptr;
  2033. break;
  2034. }
  2035. if (std::strcmp(fDescriptor->Label, label) == 0)
  2036. break;
  2037. }
  2038. if (fDescriptor == nullptr || fDssiDescriptor == nullptr)
  2039. {
  2040. pData->engine->setLastError("Could not find the requested plugin label in the plugin library");
  2041. return false;
  2042. }
  2043. // ---------------------------------------------------------------
  2044. // check if uses global instance
  2045. if (fDssiDescriptor->run_synth == nullptr && fDssiDescriptor->run_multiple_synths != nullptr)
  2046. {
  2047. if (! addUniqueMultiSynth(fDescriptor->Label))
  2048. {
  2049. pData->engine->setLastError("This plugin uses a global instance and can't be used more than once safely");
  2050. return false;
  2051. }
  2052. }
  2053. // ---------------------------------------------------------------
  2054. // get info
  2055. if (name != nullptr && name[0] != '\0')
  2056. pData->name = pData->engine->getUniquePluginName(name);
  2057. else if (fDescriptor->Name != nullptr && fDescriptor->Name[0] != '\0')
  2058. pData->name = pData->engine->getUniquePluginName(fDescriptor->Name);
  2059. else
  2060. pData->name = pData->engine->getUniquePluginName(fDescriptor->Label);
  2061. pData->filename = carla_strdup(filename);
  2062. // ---------------------------------------------------------------
  2063. // register client
  2064. pData->client = pData->engine->addClient(this);
  2065. if (pData->client == nullptr || ! pData->client->isOk())
  2066. {
  2067. pData->engine->setLastError("Failed to register plugin client");
  2068. return false;
  2069. }
  2070. // ---------------------------------------------------------------
  2071. // initialize plugin
  2072. try {
  2073. fHandle = fDescriptor->instantiate(fDescriptor, (ulong)pData->engine->getSampleRate());
  2074. } CARLA_SAFE_EXCEPTION("DSSI instantiate");
  2075. if (fHandle == nullptr)
  2076. {
  2077. pData->engine->setLastError("Plugin failed to initialize");
  2078. return false;
  2079. }
  2080. // ---------------------------------------------------------------
  2081. // check for custom data extension
  2082. if (fDssiDescriptor->configure != nullptr)
  2083. {
  2084. if (char* const error = fDssiDescriptor->configure(fHandle, DSSI_CUSTOMDATA_EXTENSION_KEY, ""))
  2085. {
  2086. if (std::strcmp(error, "true") == 0 && fDssiDescriptor->get_custom_data != nullptr && fDssiDescriptor->set_custom_data != nullptr)
  2087. fUsesCustomData = true;
  2088. std::free(error);
  2089. }
  2090. }
  2091. #ifdef HAVE_LIBLO
  2092. // ---------------------------------------------------------------
  2093. // gui stuff
  2094. if (const char* const guiFilename = find_dssi_ui(filename, fDescriptor->Label))
  2095. {
  2096. fThreadUI.setData(guiFilename, fDescriptor->Label);
  2097. fUiFilename = guiFilename;
  2098. }
  2099. #endif
  2100. // ---------------------------------------------------------------
  2101. // set default options
  2102. #ifdef __USE_GNU
  2103. const bool isDssiVst(strcasestr(pData->filename, "dssi-vst") != nullptr);
  2104. #else
  2105. const bool isDssiVst(std::strstr(pData->filename, "dssi-vst") != nullptr);
  2106. #endif
  2107. pData->options = 0x0;
  2108. if (fLatencyIndex >= 0 || isDssiVst)
  2109. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2110. if (pData->engine->getOptions().forceStereo)
  2111. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2112. if (fUsesCustomData)
  2113. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2114. if (fDssiDescriptor->get_program != nullptr && fDssiDescriptor->select_program != nullptr)
  2115. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2116. if (fDssiDescriptor->run_synth != nullptr || fDssiDescriptor->run_multiple_synths != nullptr)
  2117. {
  2118. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2119. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2120. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2121. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2122. if (fDssiDescriptor->run_synth == nullptr)
  2123. carla_stderr("WARNING: Plugin can ONLY use run_multiple_synths!");
  2124. }
  2125. return true;
  2126. }
  2127. // -------------------------------------------------------------------
  2128. private:
  2129. LADSPA_Handle fHandle;
  2130. LADSPA_Handle fHandle2;
  2131. const LADSPA_Descriptor* fDescriptor;
  2132. const DSSI_Descriptor* fDssiDescriptor;
  2133. bool fUsesCustomData;
  2134. #ifdef HAVE_LIBLO
  2135. const char* fUiFilename;
  2136. #endif
  2137. float** fAudioInBuffers;
  2138. float** fAudioOutBuffers;
  2139. float* fParamBuffers;
  2140. bool fLatencyChanged;
  2141. int32_t fLatencyIndex; // -1 if invalid
  2142. snd_seq_event_t fMidiEvents[kPluginMaxMidiEvents];
  2143. #ifdef HAVE_LIBLO
  2144. CarlaOscData fOscData;
  2145. CarlaThreadDSSIUI fThreadUI;
  2146. #endif
  2147. // -------------------------------------------------------------------
  2148. uint32_t getSafePortCount() const noexcept
  2149. {
  2150. if (fDescriptor->PortCount == 0)
  2151. return 0;
  2152. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortDescriptors != nullptr, 0);
  2153. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortRangeHints != nullptr, 0);
  2154. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortNames != nullptr, 0);
  2155. return static_cast<uint32_t>(fDescriptor->PortCount);
  2156. }
  2157. bool getSeparatedParameterNameOrUnit(const char* const paramName, char* const strBuf, const bool wantName) const noexcept
  2158. {
  2159. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, true))
  2160. return true;
  2161. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, false))
  2162. return true;
  2163. return false;
  2164. }
  2165. bool _getSeparatedParameterNameOrUnitImpl(const char* const paramName, char* const strBuf, const bool wantName, const bool useBracket) const noexcept
  2166. {
  2167. const char* const sepBracketStart(std::strstr(paramName, useBracket ? " [" : " ("));
  2168. if (sepBracketStart == nullptr)
  2169. return false;
  2170. const char* const sepBracketEnd(std::strstr(sepBracketStart, useBracket ? "]" : ")"));
  2171. if (sepBracketEnd == nullptr)
  2172. return false;
  2173. const size_t unitSize(static_cast<size_t>(sepBracketEnd-sepBracketStart-2));
  2174. if (unitSize > 7) // very unlikely to have such big unit
  2175. return false;
  2176. const size_t sepIndex(std::strlen(paramName)-unitSize-3);
  2177. // just in case
  2178. if (sepIndex > STR_MAX)
  2179. return false;
  2180. if (wantName)
  2181. {
  2182. std::strncpy(strBuf, paramName, sepIndex);
  2183. strBuf[sepIndex] = '\0';
  2184. }
  2185. else
  2186. {
  2187. std::strncpy(strBuf, paramName+(sepIndex+2), unitSize);
  2188. strBuf[unitSize] = '\0';
  2189. }
  2190. return true;
  2191. }
  2192. // -------------------------------------------------------------------
  2193. static LinkedList<const char*> sMultiSynthList;
  2194. static bool addUniqueMultiSynth(const char* const label) noexcept
  2195. {
  2196. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0', false);
  2197. const char* dlabel = nullptr;
  2198. try {
  2199. dlabel = carla_strdup(label);
  2200. } catch(...) { return false; }
  2201. for (LinkedList<const char*>::Itenerator it = sMultiSynthList.begin(); it.valid(); it.next())
  2202. {
  2203. const char* const itLabel(it.getValue());
  2204. if (std::strcmp(dlabel, itLabel) == 0)
  2205. {
  2206. delete[] dlabel;
  2207. return false;
  2208. }
  2209. }
  2210. return sMultiSynthList.append(dlabel);
  2211. }
  2212. static void removeUniqueMultiSynth(const char* const label) noexcept
  2213. {
  2214. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0',);
  2215. for (LinkedList<const char*>::Itenerator it = sMultiSynthList.begin(); it.valid(); it.next())
  2216. {
  2217. const char* const itLabel(it.getValue());
  2218. if (std::strcmp(label, itLabel) == 0)
  2219. {
  2220. sMultiSynthList.remove(it);
  2221. delete[] itLabel;
  2222. break;
  2223. }
  2224. }
  2225. }
  2226. // -------------------------------------------------------------------
  2227. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginDSSI)
  2228. };
  2229. LinkedList<const char*> CarlaPluginDSSI::sMultiSynthList;
  2230. // -------------------------------------------------------------------------------------------------------------------
  2231. CarlaPlugin* CarlaPlugin::newDSSI(const Initializer& init)
  2232. {
  2233. carla_debug("CarlaPlugin::newDSSI({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "})", init.engine, init.filename, init.name, init.label, init.uniqueId);
  2234. CarlaPluginDSSI* const plugin(new CarlaPluginDSSI(init.engine, init.id));
  2235. if (! plugin->init(init.filename, init.name, init.label))
  2236. {
  2237. delete plugin;
  2238. return nullptr;
  2239. }
  2240. plugin->reload();
  2241. bool canRun = true;
  2242. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  2243. {
  2244. if (! plugin->canRunInRack())
  2245. {
  2246. init.engine->setLastError("Carla's rack mode can only work with Mono or Stereo DSSI plugins, sorry!");
  2247. canRun = false;
  2248. }
  2249. else if (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0)
  2250. {
  2251. init.engine->setLastError("Carla's rack mode cannot work with plugins that have CV ports, sorry!");
  2252. canRun = false;
  2253. }
  2254. }
  2255. else if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_PATCHBAY && (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0))
  2256. {
  2257. init.engine->setLastError("CV ports in patchbay mode is still TODO");
  2258. canRun = false;
  2259. }
  2260. if (! canRun)
  2261. {
  2262. delete plugin;
  2263. return nullptr;
  2264. }
  2265. return plugin;
  2266. }
  2267. // -------------------------------------------------------------------------------------------------------------------
  2268. CARLA_BACKEND_END_NAMESPACE