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.

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