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.

2850 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. #if 0 // TODO
  546. void idle() override
  547. {
  548. if (fLatencyChanged && fLatencyIndex != -1)
  549. {
  550. fLatencyChanged = false;
  551. const int32_t latency(static_cast<int32_t>(fParamBuffers[fLatencyIndex]));
  552. if (latency >= 0)
  553. {
  554. const uint32_t ulatency(static_cast<uint32_t>(latency));
  555. if (pData->latency != ulatency)
  556. {
  557. carla_stdout("latency changed to %i", latency);
  558. const ScopedSingleProcessLocker sspl(this, true);
  559. pData->latency = ulatency;
  560. pData->client->setLatency(ulatency);
  561. #ifndef BUILD_BRIDGE
  562. pData->recreateLatencyBuffers();
  563. #endif
  564. }
  565. }
  566. else
  567. carla_safe_assert_int("latency >= 0", __FILE__, __LINE__, latency);
  568. }
  569. CarlaPlugin::idle();
  570. }
  571. #endif
  572. // -------------------------------------------------------------------
  573. // Plugin state
  574. void reload() override
  575. {
  576. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  577. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  578. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr,);
  579. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  580. carla_debug("CarlaPluginDSSI::reload() - start");
  581. const EngineProcessMode processMode(pData->engine->getProccessMode());
  582. // Safely disable plugin for reload
  583. const ScopedDisabler sd(this);
  584. if (pData->active)
  585. deactivate();
  586. clearBuffers();
  587. const float sampleRate(static_cast<float>(pData->engine->getSampleRate()));
  588. const uint32_t portCount(getSafePortCount());
  589. uint32_t aIns, aOuts, mIns, params;
  590. aIns = aOuts = mIns = params = 0;
  591. bool forcedStereoIn, forcedStereoOut;
  592. forcedStereoIn = forcedStereoOut = false;
  593. bool needsCtrlIn, needsCtrlOut;
  594. needsCtrlIn = needsCtrlOut = false;
  595. for (uint32_t i=0; i < portCount; ++i)
  596. {
  597. const LADSPA_PortDescriptor portType(fDescriptor->PortDescriptors[i]);
  598. if (LADSPA_IS_PORT_AUDIO(portType))
  599. {
  600. if (LADSPA_IS_PORT_INPUT(portType))
  601. aIns += 1;
  602. else if (LADSPA_IS_PORT_OUTPUT(portType))
  603. aOuts += 1;
  604. }
  605. else if (LADSPA_IS_PORT_CONTROL(portType))
  606. params += 1;
  607. }
  608. if ((pData->options & PLUGIN_OPTION_FORCE_STEREO) != 0 && (aIns == 1 || aOuts == 1))
  609. {
  610. if (fHandle2 == nullptr)
  611. {
  612. try {
  613. fHandle2 = fDescriptor->instantiate(fDescriptor, static_cast<ulong>(sampleRate));
  614. } CARLA_SAFE_EXCEPTION("DSSI instantiate #2");
  615. }
  616. if (fHandle2 != nullptr)
  617. {
  618. if (aIns == 1)
  619. {
  620. aIns = 2;
  621. forcedStereoIn = true;
  622. }
  623. if (aOuts == 1)
  624. {
  625. aOuts = 2;
  626. forcedStereoOut = true;
  627. }
  628. }
  629. }
  630. if (fDssiDescriptor->run_synth != nullptr || fDssiDescriptor->run_multiple_synths != nullptr)
  631. {
  632. mIns = 1;
  633. needsCtrlIn = true;
  634. }
  635. if (aIns > 0)
  636. {
  637. pData->audioIn.createNew(aIns);
  638. fAudioInBuffers = new float*[aIns];
  639. for (uint32_t i=0; i < aIns; ++i)
  640. fAudioInBuffers[i] = nullptr;
  641. }
  642. if (aOuts > 0)
  643. {
  644. pData->audioOut.createNew(aOuts);
  645. fAudioOutBuffers = new float*[aOuts];
  646. needsCtrlIn = true;
  647. for (uint32_t i=0; i < aOuts; ++i)
  648. fAudioOutBuffers[i] = nullptr;
  649. }
  650. if (params > 0)
  651. {
  652. pData->param.createNew(params, true);
  653. fParamBuffers = new float[params];
  654. FloatVectorOperations::clear(fParamBuffers, static_cast<int>(params));
  655. }
  656. const uint portNameSize(pData->engine->getMaxPortNameSize());
  657. CarlaString portName;
  658. for (uint32_t i=0, iAudioIn=0, iAudioOut=0, iCtrl=0; i < portCount; ++i)
  659. {
  660. const LADSPA_PortDescriptor portType = fDescriptor->PortDescriptors[i];
  661. const LADSPA_PortRangeHint portRangeHints = fDescriptor->PortRangeHints[i];
  662. if (LADSPA_IS_PORT_AUDIO(portType))
  663. {
  664. portName.clear();
  665. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  666. {
  667. portName = pData->name;
  668. portName += ":";
  669. }
  670. if (fDescriptor->PortNames[i] != nullptr && fDescriptor->PortNames[i][0] != '\0')
  671. {
  672. portName += fDescriptor->PortNames[i];
  673. }
  674. else
  675. {
  676. if (LADSPA_IS_PORT_INPUT(portType))
  677. {
  678. if (aIns > 1)
  679. {
  680. portName += "audio-in_";
  681. portName += CarlaString(iAudioIn+1);
  682. }
  683. else
  684. portName += "audio-in";
  685. }
  686. else
  687. {
  688. if (aOuts > 1)
  689. {
  690. portName += "audio-out_";
  691. portName += CarlaString(iAudioOut+1);
  692. }
  693. else
  694. portName += "audio-out";
  695. }
  696. }
  697. portName.truncate(portNameSize);
  698. if (LADSPA_IS_PORT_INPUT(portType))
  699. {
  700. const uint32_t j = iAudioIn++;
  701. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  702. pData->audioIn.ports[j].rindex = i;
  703. if (forcedStereoIn)
  704. {
  705. portName += "_2";
  706. pData->audioIn.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  707. pData->audioIn.ports[1].rindex = i;
  708. }
  709. }
  710. else if (LADSPA_IS_PORT_OUTPUT(portType))
  711. {
  712. const uint32_t j = iAudioOut++;
  713. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  714. pData->audioOut.ports[j].rindex = i;
  715. if (forcedStereoOut)
  716. {
  717. portName += "_2";
  718. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  719. pData->audioOut.ports[1].rindex = i;
  720. }
  721. }
  722. else
  723. carla_stderr2("WARNING - Got a broken Port (Audio, but not input or output)");
  724. }
  725. else if (LADSPA_IS_PORT_CONTROL(portType))
  726. {
  727. const uint32_t j = iCtrl++;
  728. pData->param.data[j].index = static_cast<int32_t>(j);
  729. pData->param.data[j].rindex = static_cast<int32_t>(i);
  730. const char* const paramName(fDescriptor->PortNames[i] != nullptr ? fDescriptor->PortNames[i] : "unknown");
  731. float min, max, def, step, stepSmall, stepLarge;
  732. // min value
  733. if (LADSPA_IS_HINT_BOUNDED_BELOW(portRangeHints.HintDescriptor))
  734. min = portRangeHints.LowerBound;
  735. else
  736. min = 0.0f;
  737. // max value
  738. if (LADSPA_IS_HINT_BOUNDED_ABOVE(portRangeHints.HintDescriptor))
  739. max = portRangeHints.UpperBound;
  740. else
  741. max = 1.0f;
  742. if (min > max)
  743. {
  744. carla_stderr2("WARNING - Broken plugin parameter '%s': min > max", paramName);
  745. min = max - 0.1f;
  746. }
  747. else if (carla_compareFloats(min, max))
  748. {
  749. carla_stderr2("WARNING - Broken plugin parameter '%s': min == max", paramName);
  750. max = min + 0.1f;
  751. }
  752. // default value
  753. def = get_default_ladspa_port_value(portRangeHints.HintDescriptor, min, max);
  754. if (def < min)
  755. def = min;
  756. else if (def > max)
  757. def = max;
  758. if (LADSPA_IS_HINT_SAMPLE_RATE(portRangeHints.HintDescriptor))
  759. {
  760. min *= sampleRate;
  761. max *= sampleRate;
  762. def *= sampleRate;
  763. pData->param.data[j].hints |= PARAMETER_USES_SAMPLERATE;
  764. }
  765. if (LADSPA_IS_HINT_TOGGLED(portRangeHints.HintDescriptor))
  766. {
  767. step = max - min;
  768. stepSmall = step;
  769. stepLarge = step;
  770. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  771. }
  772. else if (LADSPA_IS_HINT_INTEGER(portRangeHints.HintDescriptor))
  773. {
  774. step = 1.0f;
  775. stepSmall = 1.0f;
  776. stepLarge = 10.0f;
  777. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  778. }
  779. else
  780. {
  781. const float range = max - min;
  782. step = range/100.0f;
  783. stepSmall = range/1000.0f;
  784. stepLarge = range/10.0f;
  785. }
  786. if (LADSPA_IS_PORT_INPUT(portType))
  787. {
  788. pData->param.data[j].type = PARAMETER_INPUT;
  789. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  790. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  791. needsCtrlIn = true;
  792. // MIDI CC value
  793. if (fDssiDescriptor->get_midi_controller_for_port != nullptr)
  794. {
  795. int controller = fDssiDescriptor->get_midi_controller_for_port(fHandle, i);
  796. if (DSSI_CONTROLLER_IS_SET(controller) && DSSI_IS_CC(controller))
  797. {
  798. int16_t cc = DSSI_CC_NUMBER(controller);
  799. if (! MIDI_IS_CONTROL_BANK_SELECT(cc))
  800. pData->param.data[j].midiCC = cc;
  801. }
  802. }
  803. }
  804. else if (LADSPA_IS_PORT_OUTPUT(portType))
  805. {
  806. pData->param.data[j].type = PARAMETER_OUTPUT;
  807. if (std::strcmp(paramName, "latency") == 0 || std::strcmp(paramName, "_latency") == 0)
  808. {
  809. min = 0.0f;
  810. max = sampleRate;
  811. def = 0.0f;
  812. step = 1.0f;
  813. stepSmall = 1.0f;
  814. stepLarge = 1.0f;
  815. pData->param.special[j] = PARAMETER_SPECIAL_LATENCY;
  816. CARLA_SAFE_ASSERT(fLatencyIndex == -1);
  817. fLatencyIndex = static_cast<int32_t>(j);
  818. }
  819. else
  820. {
  821. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  822. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  823. needsCtrlOut = true;
  824. }
  825. }
  826. else
  827. {
  828. carla_stderr2("WARNING - Got a broken Port (Control, but not input or output)");
  829. }
  830. // extra parameter hints
  831. if (LADSPA_IS_HINT_LOGARITHMIC(portRangeHints.HintDescriptor))
  832. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  833. pData->param.ranges[j].min = min;
  834. pData->param.ranges[j].max = max;
  835. pData->param.ranges[j].def = def;
  836. pData->param.ranges[j].step = step;
  837. pData->param.ranges[j].stepSmall = stepSmall;
  838. pData->param.ranges[j].stepLarge = stepLarge;
  839. // Start parameters in their default values
  840. fParamBuffers[j] = def;
  841. try {
  842. fDescriptor->connect_port(fHandle, i, &fParamBuffers[j]);
  843. } CARLA_SAFE_EXCEPTION("DSSI connect_port parameter");
  844. if (fHandle2 != nullptr)
  845. {
  846. try {
  847. fDescriptor->connect_port(fHandle2, i, &fParamBuffers[j]);
  848. } CARLA_SAFE_EXCEPTION("DSSI connect_port parameter #2");
  849. }
  850. }
  851. else
  852. {
  853. // Not Audio or Control
  854. carla_stderr2("ERROR - Got a broken Port (neither Audio or Control)");
  855. try {
  856. fDescriptor->connect_port(fHandle, i, nullptr);
  857. } CARLA_SAFE_EXCEPTION("DSSI connect_port null");
  858. if (fHandle2 != nullptr)
  859. {
  860. try {
  861. fDescriptor->connect_port(fHandle2, i, nullptr);
  862. } CARLA_SAFE_EXCEPTION("DSSI connect_port null #2");
  863. }
  864. }
  865. }
  866. if (needsCtrlIn)
  867. {
  868. portName.clear();
  869. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  870. {
  871. portName = pData->name;
  872. portName += ":";
  873. }
  874. portName += "events-in";
  875. portName.truncate(portNameSize);
  876. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  877. }
  878. if (needsCtrlOut)
  879. {
  880. portName.clear();
  881. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  882. {
  883. portName = pData->name;
  884. portName += ":";
  885. }
  886. portName += "events-out";
  887. portName.truncate(portNameSize);
  888. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false);
  889. }
  890. if (forcedStereoIn || forcedStereoOut)
  891. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  892. else
  893. pData->options &= ~PLUGIN_OPTION_FORCE_STEREO;
  894. // plugin hints
  895. pData->hints = 0x0;
  896. if (LADSPA_IS_HARD_RT_CAPABLE(fDescriptor->Properties))
  897. pData->hints |= PLUGIN_IS_RTSAFE;
  898. #ifdef HAVE_LIBLO
  899. if (fUiFilename != nullptr)
  900. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  901. #endif
  902. #ifndef BUILD_BRIDGE
  903. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  904. pData->hints |= PLUGIN_CAN_DRYWET;
  905. if (aOuts > 0)
  906. pData->hints |= PLUGIN_CAN_VOLUME;
  907. if (aOuts >= 2 && aOuts % 2 == 0)
  908. pData->hints |= PLUGIN_CAN_BALANCE;
  909. #endif
  910. // extra plugin hints
  911. pData->extraHints = 0x0;
  912. if (mIns > 0)
  913. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  914. if (aIns <= 2 && aOuts <= 2 && (aIns == aOuts || aIns == 0 || aOuts == 0))
  915. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  916. #if 0 // TODO
  917. // check latency
  918. if (fLatencyIndex >= 0)
  919. {
  920. // we need to pre-run the plugin so it can update its latency control-port
  921. float tmpIn [(aIns > 0) ? aIns : 1][2];
  922. float tmpOut[(aOuts > 0) ? aOuts : 1][2];
  923. for (uint32_t j=0; j < aIns; ++j)
  924. {
  925. tmpIn[j][0] = 0.0f;
  926. tmpIn[j][1] = 0.0f;
  927. try {
  928. fDescriptor->connect_port(fHandle, pData->audioIn.ports[j].rindex, tmpIn[j]);
  929. } CARLA_SAFE_EXCEPTION("DSSI connect_port latency input");
  930. }
  931. for (uint32_t j=0; j < aOuts; ++j)
  932. {
  933. tmpOut[j][0] = 0.0f;
  934. tmpOut[j][1] = 0.0f;
  935. try {
  936. fDescriptor->connect_port(fHandle, pData->audioOut.ports[j].rindex, tmpOut[j]);
  937. } CARLA_SAFE_EXCEPTION("DSSI connect_port latency output");
  938. }
  939. if (fDescriptor->activate != nullptr)
  940. {
  941. try {
  942. fDescriptor->activate(fHandle);
  943. } CARLA_SAFE_EXCEPTION("DSSI latency activate");
  944. }
  945. try {
  946. fDescriptor->run(fHandle, 2);
  947. } CARLA_SAFE_EXCEPTION("DSSI latency run");
  948. if (fDescriptor->deactivate != nullptr)
  949. {
  950. try {
  951. fDescriptor->deactivate(fHandle);
  952. } CARLA_SAFE_EXCEPTION("DSSI latency deactivate");
  953. }
  954. const int32_t latency(static_cast<int32_t>(fParamBuffers[fLatencyIndex]));
  955. if (latency >= 0)
  956. {
  957. const uint32_t ulatency(static_cast<uint32_t>(latency));
  958. if (pData->latency != ulatency)
  959. {
  960. carla_stdout("latency = %i", latency);
  961. pData->latency = ulatency;
  962. pData->client->setLatency(ulatency);
  963. #ifndef BUILD_BRIDGE
  964. pData->recreateLatencyBuffers();
  965. #endif
  966. }
  967. }
  968. else
  969. carla_safe_assert_int("latency >= 0", __FILE__, __LINE__, latency);
  970. fLatencyChanged = false;
  971. }
  972. #endif
  973. bufferSizeChanged(pData->engine->getBufferSize());
  974. reloadPrograms(true);
  975. if (pData->active)
  976. activate();
  977. carla_debug("CarlaPluginDSSI::reload() - end");
  978. }
  979. void reloadPrograms(const bool doInit) override
  980. {
  981. carla_debug("CarlaPluginDSSI::reloadPrograms(%s)", bool2str(doInit));
  982. const uint32_t oldCount = pData->midiprog.count;
  983. const int32_t current = pData->midiprog.current;
  984. // Delete old programs
  985. pData->midiprog.clear();
  986. // Query new programs
  987. uint32_t newCount = 0;
  988. if (fDssiDescriptor->get_program != nullptr && fDssiDescriptor->select_program != nullptr)
  989. {
  990. for (; fDssiDescriptor->get_program(fHandle, newCount) != nullptr;)
  991. ++newCount;
  992. }
  993. if (newCount > 0)
  994. {
  995. pData->midiprog.createNew(newCount);
  996. // Update data
  997. for (uint32_t i=0; i < newCount; ++i)
  998. {
  999. const DSSI_Program_Descriptor* const pdesc(fDssiDescriptor->get_program(fHandle, i));
  1000. CARLA_SAFE_ASSERT_CONTINUE(pdesc != nullptr);
  1001. CARLA_SAFE_ASSERT(pdesc->Name != nullptr);
  1002. pData->midiprog.data[i].bank = static_cast<uint32_t>(pdesc->Bank);
  1003. pData->midiprog.data[i].program = static_cast<uint32_t>(pdesc->Program);
  1004. pData->midiprog.data[i].name = carla_strdup(pdesc->Name);
  1005. }
  1006. }
  1007. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  1008. // Update OSC Names
  1009. if (pData->engine->isOscControlRegistered())
  1010. {
  1011. pData->engine->oscSend_control_set_midi_program_count(pData->id, newCount);
  1012. for (uint32_t i=0; i < newCount; ++i)
  1013. 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);
  1014. }
  1015. #endif
  1016. if (doInit)
  1017. {
  1018. if (newCount > 0)
  1019. setMidiProgram(0, false, false, false);
  1020. }
  1021. else
  1022. {
  1023. // Check if current program is invalid
  1024. bool programChanged = false;
  1025. if (newCount == oldCount+1)
  1026. {
  1027. // one midi program added, probably created by user
  1028. pData->midiprog.current = static_cast<int32_t>(oldCount);
  1029. programChanged = true;
  1030. }
  1031. else if (current < 0 && newCount > 0)
  1032. {
  1033. // programs exist now, but not before
  1034. pData->midiprog.current = 0;
  1035. programChanged = true;
  1036. }
  1037. else if (current >= 0 && newCount == 0)
  1038. {
  1039. // programs existed before, but not anymore
  1040. pData->midiprog.current = -1;
  1041. programChanged = true;
  1042. }
  1043. else if (current >= static_cast<int32_t>(newCount))
  1044. {
  1045. // current midi program > count
  1046. pData->midiprog.current = 0;
  1047. programChanged = true;
  1048. }
  1049. else
  1050. {
  1051. // no change
  1052. pData->midiprog.current = current;
  1053. }
  1054. if (programChanged)
  1055. setMidiProgram(pData->midiprog.current, true, true, true);
  1056. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  1057. }
  1058. }
  1059. // -------------------------------------------------------------------
  1060. // Plugin processing
  1061. void activate() noexcept override
  1062. {
  1063. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  1064. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1065. if (fDescriptor->activate != nullptr)
  1066. {
  1067. try {
  1068. fDescriptor->activate(fHandle);
  1069. } CARLA_SAFE_EXCEPTION("DSSI activate");
  1070. if (fHandle2 != nullptr)
  1071. {
  1072. try {
  1073. fDescriptor->activate(fHandle2);
  1074. } CARLA_SAFE_EXCEPTION("DSSI activate #2");
  1075. }
  1076. }
  1077. }
  1078. void deactivate() noexcept override
  1079. {
  1080. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  1081. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1082. if (fDescriptor->deactivate != nullptr)
  1083. {
  1084. try {
  1085. fDescriptor->deactivate(fHandle);
  1086. } CARLA_SAFE_EXCEPTION("DSSI deactivate");
  1087. if (fHandle2 != nullptr)
  1088. {
  1089. try {
  1090. fDescriptor->deactivate(fHandle2);
  1091. } CARLA_SAFE_EXCEPTION("DSSI deactivate #2");
  1092. }
  1093. }
  1094. }
  1095. void process(const float** const audioIn, float** const audioOut, const float** const cvIn, float** const cvOut, const uint32_t frames) override
  1096. {
  1097. // --------------------------------------------------------------------------------------------------------
  1098. // Check if active
  1099. if (! pData->active)
  1100. {
  1101. // disable any output sound
  1102. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1103. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  1104. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1105. FloatVectorOperations::clear(cvOut[i], static_cast<int>(frames));
  1106. return;
  1107. }
  1108. ulong midiEventCount = 0;
  1109. carla_zeroStruct<snd_seq_event_t>(fMidiEvents, kPluginMaxMidiEvents);
  1110. // --------------------------------------------------------------------------------------------------------
  1111. // Check if needs reset
  1112. if (pData->needsReset)
  1113. {
  1114. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1115. {
  1116. midiEventCount = MAX_MIDI_CHANNELS*2;
  1117. for (uchar i=0, k=MAX_MIDI_CHANNELS; i < MAX_MIDI_CHANNELS; ++i)
  1118. {
  1119. fMidiEvents[i].type = SND_SEQ_EVENT_CONTROLLER;
  1120. fMidiEvents[i].data.control.channel = i;
  1121. fMidiEvents[i].data.control.param = MIDI_CONTROL_ALL_NOTES_OFF;
  1122. fMidiEvents[k+i].type = SND_SEQ_EVENT_CONTROLLER;
  1123. fMidiEvents[k+i].data.control.channel = i;
  1124. fMidiEvents[k+i].data.control.param = MIDI_CONTROL_ALL_SOUND_OFF;
  1125. }
  1126. }
  1127. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  1128. {
  1129. midiEventCount = MAX_MIDI_NOTE;
  1130. for (uchar i=0; i < MAX_MIDI_NOTE; ++i)
  1131. {
  1132. fMidiEvents[i].type = SND_SEQ_EVENT_NOTEOFF;
  1133. fMidiEvents[i].data.note.channel = static_cast<uchar>(pData->ctrlChannel);
  1134. fMidiEvents[i].data.note.note = i;
  1135. }
  1136. }
  1137. #ifndef BUILD_BRIDGE
  1138. #if 0 // TODO
  1139. if (pData->latency > 0)
  1140. {
  1141. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1142. FloatVectorOperations::clear(pData->latencyBuffers[i], static_cast<int>(pData->latency));
  1143. }
  1144. #endif
  1145. #endif
  1146. pData->needsReset = false;
  1147. }
  1148. // --------------------------------------------------------------------------------------------------------
  1149. // Event Input and Processing
  1150. if (pData->event.portIn != nullptr)
  1151. {
  1152. // ----------------------------------------------------------------------------------------------------
  1153. // MIDI Input (External)
  1154. if (pData->extNotes.mutex.tryLock())
  1155. {
  1156. ExternalMidiNote note = { 0, 0, 0 };
  1157. for (; midiEventCount < kPluginMaxMidiEvents && ! pData->extNotes.data.isEmpty();)
  1158. {
  1159. note = pData->extNotes.data.getFirst(note, true);
  1160. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1161. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1162. seqEvent.type = (note.velo > 0) ? SND_SEQ_EVENT_NOTEON : SND_SEQ_EVENT_NOTEOFF;
  1163. seqEvent.data.note.channel = static_cast<uchar>(note.channel);
  1164. seqEvent.data.note.note = note.note;
  1165. seqEvent.data.note.velocity = note.velo;
  1166. }
  1167. pData->extNotes.mutex.unlock();
  1168. } // End of MIDI Input (External)
  1169. // ----------------------------------------------------------------------------------------------------
  1170. // Event Input (System)
  1171. #ifndef BUILD_BRIDGE
  1172. bool allNotesOffSent = false;
  1173. #endif
  1174. const bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  1175. uint32_t startTime = 0;
  1176. uint32_t timeOffset = 0;
  1177. uint32_t nextBankId;
  1178. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1179. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1180. else
  1181. nextBankId = 0;
  1182. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  1183. {
  1184. const EngineEvent& event(pData->event.portIn->getEvent(i));
  1185. if (event.time >= frames)
  1186. continue;
  1187. CARLA_ASSERT_INT2(event.time >= timeOffset, event.time, timeOffset);
  1188. if (isSampleAccurate && event.time > timeOffset)
  1189. {
  1190. if (processSingle(audioIn, audioOut, cvIn, cvOut, event.time - timeOffset, timeOffset, midiEventCount))
  1191. {
  1192. startTime = 0;
  1193. timeOffset = event.time;
  1194. midiEventCount = 0;
  1195. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1196. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1197. else
  1198. nextBankId = 0;
  1199. }
  1200. else
  1201. startTime += timeOffset;
  1202. }
  1203. switch (event.type)
  1204. {
  1205. case kEngineEventTypeNull:
  1206. break;
  1207. case kEngineEventTypeControl: {
  1208. const EngineControlEvent& ctrlEvent(event.ctrl);
  1209. switch (ctrlEvent.type)
  1210. {
  1211. case kEngineControlEventTypeNull:
  1212. break;
  1213. case kEngineControlEventTypeParameter: {
  1214. #ifndef BUILD_BRIDGE
  1215. // Control backend stuff
  1216. if (event.channel == pData->ctrlChannel)
  1217. {
  1218. float value;
  1219. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1220. {
  1221. value = ctrlEvent.value;
  1222. setDryWet(value, false, false);
  1223. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  1224. break;
  1225. }
  1226. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1227. {
  1228. value = ctrlEvent.value*127.0f/100.0f;
  1229. setVolume(value, false, false);
  1230. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  1231. break;
  1232. }
  1233. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1234. {
  1235. float left, right;
  1236. value = ctrlEvent.value/0.5f - 1.0f;
  1237. if (value < 0.0f)
  1238. {
  1239. left = -1.0f;
  1240. right = (value*2.0f)+1.0f;
  1241. }
  1242. else if (value > 0.0f)
  1243. {
  1244. left = (value*2.0f)-1.0f;
  1245. right = 1.0f;
  1246. }
  1247. else
  1248. {
  1249. left = -1.0f;
  1250. right = 1.0f;
  1251. }
  1252. setBalanceLeft(left, false, false);
  1253. setBalanceRight(right, false, false);
  1254. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  1255. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  1256. break;
  1257. }
  1258. }
  1259. #endif
  1260. // Control plugin parameters
  1261. uint32_t k;
  1262. for (k=0; k < pData->param.count; ++k)
  1263. {
  1264. if (pData->param.data[k].midiChannel != event.channel)
  1265. continue;
  1266. if (pData->param.data[k].midiCC != ctrlEvent.param)
  1267. continue;
  1268. if (pData->param.data[k].type != PARAMETER_INPUT)
  1269. continue;
  1270. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  1271. continue;
  1272. float value;
  1273. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  1274. {
  1275. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  1276. }
  1277. else
  1278. {
  1279. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  1280. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  1281. value = std::rint(value);
  1282. }
  1283. setParameterValue(k, value, false, false, false);
  1284. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  1285. break;
  1286. }
  1287. // check if event is already handled
  1288. if (k != pData->param.count)
  1289. break;
  1290. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_CONTROL)
  1291. {
  1292. if (midiEventCount >= kPluginMaxMidiEvents)
  1293. continue;
  1294. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1295. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1296. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1297. seqEvent.data.control.channel = event.channel;
  1298. seqEvent.data.control.param = ctrlEvent.param;
  1299. seqEvent.data.control.value = int8_t(ctrlEvent.value*127.0f);
  1300. }
  1301. break;
  1302. } // case kEngineControlEventTypeParameter
  1303. case kEngineControlEventTypeMidiBank:
  1304. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1305. nextBankId = ctrlEvent.param;
  1306. break;
  1307. case kEngineControlEventTypeMidiProgram:
  1308. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1309. {
  1310. const uint32_t nextProgramId = ctrlEvent.param;
  1311. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  1312. {
  1313. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  1314. {
  1315. const int32_t index(static_cast<int32_t>(k));
  1316. setMidiProgram(index, false, false, false);
  1317. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, index, 0, 0.0f);
  1318. break;
  1319. }
  1320. }
  1321. }
  1322. break;
  1323. case kEngineControlEventTypeAllSoundOff:
  1324. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1325. {
  1326. if (midiEventCount >= kPluginMaxMidiEvents)
  1327. continue;
  1328. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1329. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1330. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1331. seqEvent.data.control.channel = event.channel;
  1332. seqEvent.data.control.param = MIDI_CONTROL_ALL_SOUND_OFF;
  1333. }
  1334. break;
  1335. case kEngineControlEventTypeAllNotesOff:
  1336. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1337. {
  1338. #ifndef BUILD_BRIDGE
  1339. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1340. {
  1341. allNotesOffSent = true;
  1342. sendMidiAllNotesOffToCallback();
  1343. }
  1344. #endif
  1345. if (midiEventCount >= kPluginMaxMidiEvents)
  1346. continue;
  1347. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1348. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1349. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1350. seqEvent.data.control.channel = event.channel;
  1351. seqEvent.data.control.param = MIDI_CONTROL_ALL_NOTES_OFF;
  1352. }
  1353. break;
  1354. } // switch (ctrlEvent.type)
  1355. break;
  1356. } // case kEngineEventTypeControl
  1357. case kEngineEventTypeMidi: {
  1358. if (midiEventCount >= kPluginMaxMidiEvents)
  1359. continue;
  1360. const EngineMidiEvent& midiEvent(event.midi);
  1361. if (midiEvent.size > EngineMidiEvent::kDataSize)
  1362. continue;
  1363. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1364. // Fix bad note-off (per DSSI spec)
  1365. if (status == MIDI_STATUS_NOTE_ON && midiEvent.data[2] == 0)
  1366. status = MIDI_STATUS_NOTE_OFF;
  1367. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1368. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1369. switch (status)
  1370. {
  1371. case MIDI_STATUS_NOTE_OFF: {
  1372. const uint8_t note = midiEvent.data[1];
  1373. seqEvent.type = SND_SEQ_EVENT_NOTEOFF;
  1374. seqEvent.data.note.channel = event.channel;
  1375. seqEvent.data.note.note = note;
  1376. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, note, 0.0f);
  1377. break;
  1378. }
  1379. case MIDI_STATUS_NOTE_ON: {
  1380. const uint8_t note = midiEvent.data[1];
  1381. const uint8_t velo = midiEvent.data[2];
  1382. seqEvent.type = SND_SEQ_EVENT_NOTEON;
  1383. seqEvent.data.note.channel = event.channel;
  1384. seqEvent.data.note.note = note;
  1385. seqEvent.data.note.velocity = velo;
  1386. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, note, velo);
  1387. break;
  1388. }
  1389. case MIDI_STATUS_POLYPHONIC_AFTERTOUCH:
  1390. if (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH)
  1391. {
  1392. const uint8_t note = midiEvent.data[1];
  1393. const uint8_t pressure = midiEvent.data[2];
  1394. seqEvent.type = SND_SEQ_EVENT_KEYPRESS;
  1395. seqEvent.data.note.channel = event.channel;
  1396. seqEvent.data.note.note = note;
  1397. seqEvent.data.note.velocity = pressure;
  1398. }
  1399. break;
  1400. case MIDI_STATUS_CONTROL_CHANGE:
  1401. if (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES)
  1402. {
  1403. const uint8_t control = midiEvent.data[1];
  1404. const uint8_t value = midiEvent.data[2];
  1405. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1406. seqEvent.data.control.channel = event.channel;
  1407. seqEvent.data.control.param = control;
  1408. seqEvent.data.control.value = value;
  1409. }
  1410. break;
  1411. case MIDI_STATUS_CHANNEL_PRESSURE:
  1412. if (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE)
  1413. {
  1414. const uint8_t pressure = midiEvent.data[1];
  1415. seqEvent.type = SND_SEQ_EVENT_CHANPRESS;
  1416. seqEvent.data.control.channel = event.channel;
  1417. seqEvent.data.control.value = pressure;
  1418. }
  1419. break;
  1420. case MIDI_STATUS_PITCH_WHEEL_CONTROL:
  1421. if (pData->options & PLUGIN_OPTION_SEND_PITCHBEND)
  1422. {
  1423. const uint8_t lsb = midiEvent.data[1];
  1424. const uint8_t msb = midiEvent.data[2];
  1425. seqEvent.type = SND_SEQ_EVENT_PITCHBEND;
  1426. seqEvent.data.control.channel = event.channel;
  1427. seqEvent.data.control.value = ((msb << 7) | lsb) - 8192;
  1428. }
  1429. break;
  1430. default:
  1431. --midiEventCount;
  1432. break;
  1433. } // switch (status)
  1434. } break;
  1435. } // switch (event.type)
  1436. }
  1437. pData->postRtEvents.trySplice();
  1438. if (frames > timeOffset)
  1439. processSingle(audioIn, audioOut, cvIn, cvOut, frames - timeOffset, timeOffset, midiEventCount);
  1440. } // End of Event Input and Processing
  1441. // --------------------------------------------------------------------------------------------------------
  1442. // Plugin processing (no events)
  1443. else
  1444. {
  1445. processSingle(audioIn, audioOut, cvIn, cvOut, frames, 0, midiEventCount);
  1446. } // End of Plugin processing (no events)
  1447. #ifndef BUILD_BRIDGE
  1448. #if 0 // TODO
  1449. // --------------------------------------------------------------------------------------------------------
  1450. // Latency, save values for next callback
  1451. if (fLatencyIndex != -1)
  1452. {
  1453. if (pData->latency != static_cast<uint32_t>(fParamBuffers[fLatencyIndex]))
  1454. {
  1455. fLatencyChanged = true;
  1456. }
  1457. else if (pData->latency > 0)
  1458. {
  1459. if (pData->latency <= frames)
  1460. {
  1461. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1462. FloatVectorOperations::copy(pData->latencyBuffers[i], audioIn[i]+(frames-pData->latency), static_cast<int>(pData->latency));
  1463. }
  1464. else
  1465. {
  1466. for (uint32_t i=0, j, k; i < pData->audioIn.count; ++i)
  1467. {
  1468. for (k=0; k < pData->latency-frames; ++k)
  1469. pData->latencyBuffers[i][k] = pData->latencyBuffers[i][k+frames];
  1470. for (j=0; k < pData->latency; ++j, ++k)
  1471. pData->latencyBuffers[i][k] = audioIn[i][j];
  1472. }
  1473. }
  1474. }
  1475. }
  1476. #endif
  1477. // --------------------------------------------------------------------------------------------------------
  1478. // Control Output
  1479. if (pData->event.portOut != nullptr)
  1480. {
  1481. uint8_t channel;
  1482. uint16_t param;
  1483. float value;
  1484. for (uint32_t k=0; k < pData->param.count; ++k)
  1485. {
  1486. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  1487. continue;
  1488. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  1489. if (pData->param.data[k].midiCC > 0)
  1490. {
  1491. channel = pData->param.data[k].midiChannel;
  1492. param = static_cast<uint16_t>(pData->param.data[k].midiCC);
  1493. value = pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]);
  1494. pData->event.portOut->writeControlEvent(0, channel, kEngineControlEventTypeParameter, param, value);
  1495. }
  1496. }
  1497. } // End of Control Output
  1498. #endif
  1499. }
  1500. 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)
  1501. {
  1502. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1503. if (pData->audioIn.count > 0)
  1504. {
  1505. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  1506. }
  1507. if (pData->audioOut.count > 0)
  1508. {
  1509. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  1510. }
  1511. if (pData->cvIn.count > 0)
  1512. {
  1513. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  1514. }
  1515. if (pData->cvOut.count > 0)
  1516. {
  1517. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  1518. }
  1519. // --------------------------------------------------------------------------------------------------------
  1520. // Try lock, silence otherwise
  1521. if (pData->engine->isOffline())
  1522. {
  1523. pData->singleMutex.lock();
  1524. }
  1525. else if (! pData->singleMutex.tryLock())
  1526. {
  1527. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1528. {
  1529. for (uint32_t k=0; k < frames; ++k)
  1530. audioOut[i][k+timeOffset] = 0.0f;
  1531. }
  1532. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1533. {
  1534. for (uint32_t k=0; k < frames; ++k)
  1535. cvOut[i][k+timeOffset] = 0.0f;
  1536. }
  1537. return false;
  1538. }
  1539. // --------------------------------------------------------------------------------------------------------
  1540. // Set audio buffers
  1541. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1542. FloatVectorOperations::copy(fAudioInBuffers[i], audioIn[i]+timeOffset, static_cast<int>(frames));
  1543. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1544. FloatVectorOperations::clear(fAudioOutBuffers[i], static_cast<int>(frames));
  1545. #if 0
  1546. // --------------------------------------------------------------------------------------------------------
  1547. // Set CV buffers
  1548. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  1549. FloatVectorOperations::copy(fCvInBuffers[i], cvIn[i]+timeOffset, static_cast<int>(frames));
  1550. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1551. FloatVectorOperations::clear(fCvOutBuffers[i], static_cast<int>(frames));
  1552. #endif
  1553. // --------------------------------------------------------------------------------------------------------
  1554. // Run plugin
  1555. // TODO - try catch
  1556. if (fDssiDescriptor->run_synth != nullptr)
  1557. {
  1558. fDssiDescriptor->run_synth(fHandle, frames, fMidiEvents, midiEventCount);
  1559. if (fHandle2 != nullptr)
  1560. fDssiDescriptor->run_synth(fHandle2, frames, fMidiEvents, midiEventCount);
  1561. }
  1562. else if (fDssiDescriptor->run_multiple_synths != nullptr)
  1563. {
  1564. ulong instances = (fHandle2 != nullptr) ? 2 : 1;
  1565. LADSPA_Handle handlePtr[2] = { fHandle, fHandle2 };
  1566. snd_seq_event_t* midiEventsPtr[2] = { fMidiEvents, fMidiEvents };
  1567. ulong midiEventCountPtr[2] = { midiEventCount, midiEventCount };
  1568. fDssiDescriptor->run_multiple_synths(instances, handlePtr, frames, midiEventsPtr, midiEventCountPtr);
  1569. }
  1570. else
  1571. {
  1572. fDescriptor->run(fHandle, frames);
  1573. if (fHandle2 != nullptr)
  1574. fDescriptor->run(fHandle2, frames);
  1575. }
  1576. #ifndef BUILD_BRIDGE
  1577. // --------------------------------------------------------------------------------------------------------
  1578. // Post-processing (dry/wet, volume and balance)
  1579. {
  1580. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && ! carla_compareFloats(pData->postProc.dryWet, 1.0f);
  1581. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_compareFloats(pData->postProc.balanceLeft, -1.0f) && carla_compareFloats(pData->postProc.balanceRight, 1.0f));
  1582. const bool isMono = (pData->audioIn.count == 1);
  1583. bool isPair;
  1584. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1585. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1586. {
  1587. // Dry/Wet
  1588. if (doDryWet)
  1589. {
  1590. for (uint32_t k=0; k < frames; ++k)
  1591. {
  1592. #if 0 // TODO
  1593. if (k < pData->latency)
  1594. bufValue = pData->latencyBuffers[isMono ? 0 : i][k];
  1595. else if (pData->latency < frames)
  1596. bufValue = fAudioInBuffers[isMono ? 0 : i][k-pData->latency];
  1597. else
  1598. #endif
  1599. bufValue = fAudioInBuffers[isMono ? 0 : i][k];
  1600. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1601. }
  1602. }
  1603. // Balance
  1604. if (doBalance)
  1605. {
  1606. isPair = (i % 2 == 0);
  1607. if (isPair)
  1608. {
  1609. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1610. FloatVectorOperations::copy(oldBufLeft, fAudioOutBuffers[i], static_cast<int>(frames));
  1611. }
  1612. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1613. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1614. for (uint32_t k=0; k < frames; ++k)
  1615. {
  1616. if (isPair)
  1617. {
  1618. // left
  1619. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1620. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  1621. }
  1622. else
  1623. {
  1624. // right
  1625. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  1626. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  1627. }
  1628. }
  1629. }
  1630. // Volume (and buffer copy)
  1631. {
  1632. for (uint32_t k=0; k < frames; ++k)
  1633. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  1634. }
  1635. }
  1636. } // End of Post-processing
  1637. #else // BUILD_BRIDGE
  1638. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1639. {
  1640. for (uint32_t k=0; k < frames; ++k)
  1641. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k];
  1642. }
  1643. #endif
  1644. #if 0
  1645. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1646. {
  1647. for (uint32_t k=0; k < frames; ++k)
  1648. cvOut[i][k+timeOffset] = fCvOutBuffers[i][k];
  1649. }
  1650. #endif
  1651. // --------------------------------------------------------------------------------------------------------
  1652. pData->singleMutex.unlock();
  1653. return true;
  1654. }
  1655. void bufferSizeChanged(const uint32_t newBufferSize) override
  1656. {
  1657. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1658. carla_debug("CarlaPluginDSSI::bufferSizeChanged(%i) - start", newBufferSize);
  1659. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1660. {
  1661. if (fAudioInBuffers[i] != nullptr)
  1662. delete[] fAudioInBuffers[i];
  1663. fAudioInBuffers[i] = new float[newBufferSize];
  1664. }
  1665. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1666. {
  1667. if (fAudioOutBuffers[i] != nullptr)
  1668. delete[] fAudioOutBuffers[i];
  1669. fAudioOutBuffers[i] = new float[newBufferSize];
  1670. }
  1671. if (fHandle2 == nullptr)
  1672. {
  1673. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1674. {
  1675. CARLA_ASSERT(fAudioInBuffers[i] != nullptr);
  1676. try {
  1677. fDescriptor->connect_port(fHandle, pData->audioIn.ports[i].rindex, fAudioInBuffers[i]);
  1678. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio input");
  1679. }
  1680. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1681. {
  1682. CARLA_ASSERT(fAudioOutBuffers[i] != nullptr);
  1683. try {
  1684. fDescriptor->connect_port(fHandle, pData->audioOut.ports[i].rindex, fAudioOutBuffers[i]);
  1685. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio output");
  1686. }
  1687. }
  1688. else
  1689. {
  1690. if (pData->audioIn.count > 0)
  1691. {
  1692. CARLA_ASSERT(pData->audioIn.count == 2);
  1693. CARLA_ASSERT(fAudioInBuffers[0] != nullptr);
  1694. CARLA_ASSERT(fAudioInBuffers[1] != nullptr);
  1695. try {
  1696. fDescriptor->connect_port(fHandle, pData->audioIn.ports[0].rindex, fAudioInBuffers[0]);
  1697. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio input #1");
  1698. try {
  1699. fDescriptor->connect_port(fHandle2, pData->audioIn.ports[1].rindex, fAudioInBuffers[1]);
  1700. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio input #2");
  1701. }
  1702. if (pData->audioOut.count > 0)
  1703. {
  1704. CARLA_ASSERT(pData->audioOut.count == 2);
  1705. CARLA_ASSERT(fAudioOutBuffers[0] != nullptr);
  1706. CARLA_ASSERT(fAudioOutBuffers[1] != nullptr);
  1707. try {
  1708. fDescriptor->connect_port(fHandle, pData->audioOut.ports[0].rindex, fAudioOutBuffers[0]);
  1709. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio output #1");
  1710. try {
  1711. fDescriptor->connect_port(fHandle2, pData->audioOut.ports[1].rindex, fAudioOutBuffers[1]);
  1712. } CARLA_SAFE_EXCEPTION("DSSI connect_port audio output #2");
  1713. }
  1714. }
  1715. carla_debug("CarlaPluginDSSI::bufferSizeChanged(%i) - end", newBufferSize);
  1716. }
  1717. void sampleRateChanged(const double newSampleRate) override
  1718. {
  1719. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1720. carla_debug("CarlaPluginDSSI::sampleRateChanged(%g) - start", newSampleRate);
  1721. // TODO
  1722. (void)newSampleRate;
  1723. carla_debug("CarlaPluginDSSI::sampleRateChanged(%g) - end", newSampleRate);
  1724. }
  1725. // -------------------------------------------------------------------
  1726. // Plugin buffers
  1727. void clearBuffers() noexcept override
  1728. {
  1729. carla_debug("CarlaPluginDSSI::clearBuffers() - start");
  1730. if (fAudioInBuffers != nullptr)
  1731. {
  1732. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1733. {
  1734. if (fAudioInBuffers[i] != nullptr)
  1735. {
  1736. delete[] fAudioInBuffers[i];
  1737. fAudioInBuffers[i] = nullptr;
  1738. }
  1739. }
  1740. delete[] fAudioInBuffers;
  1741. fAudioInBuffers = nullptr;
  1742. }
  1743. if (fAudioOutBuffers != nullptr)
  1744. {
  1745. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1746. {
  1747. if (fAudioOutBuffers[i] != nullptr)
  1748. {
  1749. delete[] fAudioOutBuffers[i];
  1750. fAudioOutBuffers[i] = nullptr;
  1751. }
  1752. }
  1753. delete[] fAudioOutBuffers;
  1754. fAudioOutBuffers = nullptr;
  1755. }
  1756. if (fParamBuffers != nullptr)
  1757. {
  1758. delete[] fParamBuffers;
  1759. fParamBuffers = nullptr;
  1760. }
  1761. CarlaPlugin::clearBuffers();
  1762. carla_debug("CarlaPluginDSSI::clearBuffers() - end");
  1763. }
  1764. #ifdef HAVE_LIBLO
  1765. // -------------------------------------------------------------------
  1766. // OSC stuff
  1767. void handleOscMessage(const char* const method, const int argc, const void* const argvx, const char* const types, const lo_message msg) override
  1768. {
  1769. const lo_address source(lo_message_get_source(msg));
  1770. CARLA_SAFE_ASSERT_RETURN(source != nullptr,);
  1771. // protocol for DSSI UIs *must* be UDP
  1772. CARLA_SAFE_ASSERT_RETURN(lo_address_get_protocol(source) == LO_UDP,);
  1773. if (fOscData.source == nullptr)
  1774. {
  1775. // if no UI is registered yet only "update" message is valid
  1776. CARLA_SAFE_ASSERT_RETURN(std::strcmp(method, "update") == 0,)
  1777. }
  1778. else
  1779. {
  1780. // make sure message source is the DSSI UI
  1781. const char* const msghost = lo_address_get_hostname(source);
  1782. const char* const msgport = lo_address_get_port(source);
  1783. const char* const ourhost = lo_address_get_hostname(fOscData.source);
  1784. const char* const ourport = lo_address_get_port(fOscData.source);
  1785. CARLA_SAFE_ASSERT_RETURN(std::strcmp(msghost, ourhost) == 0,);
  1786. CARLA_SAFE_ASSERT_RETURN(std::strcmp(msgport, ourport) == 0,);
  1787. }
  1788. const lo_arg* const* const argv(static_cast<const lo_arg* const* const>(argvx));
  1789. if (std::strcmp(method, "configure") == 0)
  1790. return handleOscMessageConfigure(argc, argv, types);
  1791. if (std::strcmp(method, "control") == 0)
  1792. return handleOscMessageControl(argc, argv, types);
  1793. if (std::strcmp(method, "program") == 0)
  1794. return handleOscMessageProgram(argc, argv, types);
  1795. if (std::strcmp(method, "midi") == 0)
  1796. return handleOscMessageMIDI(argc, argv, types);
  1797. if (std::strcmp(method, "update") == 0)
  1798. return handleOscMessageUpdate(argc, argv, types, lo_message_get_source(msg));
  1799. if (std::strcmp(method, "exiting") == 0)
  1800. return handleOscMessageExiting();
  1801. carla_stdout("CarlaPluginDSSI::handleOscMessage() - unknown method '%s'", method);
  1802. }
  1803. void handleOscMessageConfigure(const int argc, const lo_arg* const* const argv, const char* const types)
  1804. {
  1805. carla_debug("CarlaPluginDSSI::handleMsgConfigure()");
  1806. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(2, "ss");
  1807. const char* const key = (const char*)&argv[0]->s;
  1808. const char* const value = (const char*)&argv[1]->s;
  1809. setCustomData(CUSTOM_DATA_TYPE_STRING, key, value, false);
  1810. }
  1811. void handleOscMessageControl(const int argc, const lo_arg* const* const argv, const char* const types)
  1812. {
  1813. carla_debug("CarlaPluginDSSI::handleMsgControl()");
  1814. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(2, "if");
  1815. const int32_t rindex = argv[0]->i;
  1816. const float value = argv[1]->f;
  1817. setParameterValueByRealIndex(rindex, value, false, true, true);
  1818. }
  1819. void handleOscMessageProgram(const int argc, const lo_arg* const* const argv, const char* const types)
  1820. {
  1821. carla_debug("CarlaPluginDSSI::handleMsgProgram()");
  1822. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(2, "ii");
  1823. const int32_t bank = argv[0]->i;
  1824. const int32_t program = argv[1]->i;
  1825. CARLA_SAFE_ASSERT_RETURN(bank >= 0,);
  1826. CARLA_SAFE_ASSERT_RETURN(program >= 0,);
  1827. setMidiProgramById(static_cast<uint32_t>(bank), static_cast<uint32_t>(program), false, true, true);
  1828. }
  1829. void handleOscMessageMIDI(const int argc, const lo_arg* const* const argv, const char* const types)
  1830. {
  1831. carla_debug("CarlaPluginDSSI::handleMsgMidi()");
  1832. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(1, "m");
  1833. if (getMidiInCount() == 0)
  1834. {
  1835. carla_stderr("CarlaPluginDSSI::handleMsgMidi() - received midi when plugin has no midi inputs");
  1836. return;
  1837. }
  1838. const uint8_t* const data = argv[0]->m;
  1839. uint8_t status = data[1];
  1840. uint8_t channel = status & 0x0F;
  1841. // Fix bad note-off
  1842. if (MIDI_IS_STATUS_NOTE_ON(status) && data[3] == 0)
  1843. status = MIDI_STATUS_NOTE_OFF;
  1844. if (MIDI_IS_STATUS_NOTE_OFF(status))
  1845. {
  1846. const uint8_t note = data[2];
  1847. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1848. sendMidiSingleNote(channel, note, 0, false, true, true);
  1849. }
  1850. else if (MIDI_IS_STATUS_NOTE_ON(status))
  1851. {
  1852. const uint8_t note = data[2];
  1853. const uint8_t velo = data[3];
  1854. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1855. CARLA_SAFE_ASSERT_RETURN(velo < MAX_MIDI_VALUE,);
  1856. sendMidiSingleNote(channel, note, velo, false, true, true);
  1857. }
  1858. }
  1859. void handleOscMessageUpdate(const int argc, const lo_arg* const* const argv, const char* const types, const lo_address source)
  1860. {
  1861. carla_debug("CarlaPluginDSSI::handleMsgUpdate()");
  1862. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(1, "s");
  1863. const char* const url = (const char*)&argv[0]->s;
  1864. // FIXME - remove debug prints later
  1865. carla_stdout("CarlaPluginDSSI::updateOscData(%p, \"%s\")", source, url);
  1866. fOscData.clear();
  1867. const int proto = lo_address_get_protocol(source);
  1868. {
  1869. const char* host = lo_address_get_hostname(source);
  1870. const char* port = lo_address_get_port(source);
  1871. fOscData.source = lo_address_new_with_proto(proto, host, port);
  1872. carla_stdout("CarlaPlugin::updateOscData() - source: host \"%s\", port \"%s\"", host, port);
  1873. }
  1874. {
  1875. char* host = lo_url_get_hostname(url);
  1876. char* port = lo_url_get_port(url);
  1877. fOscData.path = carla_strdup_free(lo_url_get_path(url));
  1878. fOscData.target = lo_address_new_with_proto(proto, host, port);
  1879. carla_stdout("CarlaPlugin::updateOscData() - target: host \"%s\", port \"%s\", path \"%s\"", host, port, fOscData.path);
  1880. std::free(host);
  1881. std::free(port);
  1882. }
  1883. osc_send_sample_rate(fOscData, static_cast<float>(pData->engine->getSampleRate()));
  1884. for (LinkedList<CustomData>::Itenerator it = pData->custom.begin(); it.valid(); it.next())
  1885. {
  1886. const CustomData& customData(it.getValue(kCustomDataFallback));
  1887. CARLA_SAFE_ASSERT_CONTINUE(customData.isValid());
  1888. if (std::strcmp(customData.type, CUSTOM_DATA_TYPE_STRING) == 0)
  1889. osc_send_configure(fOscData, customData.key, customData.value);
  1890. }
  1891. if (pData->prog.current >= 0)
  1892. osc_send_program(fOscData, static_cast<uint32_t>(pData->prog.current));
  1893. if (pData->midiprog.current >= 0)
  1894. {
  1895. const MidiProgramData& curMidiProg(pData->midiprog.getCurrent());
  1896. if (getType() == PLUGIN_DSSI)
  1897. osc_send_program(fOscData, curMidiProg.bank, curMidiProg.program);
  1898. else
  1899. osc_send_midi_program(fOscData, curMidiProg.bank, curMidiProg.program);
  1900. }
  1901. for (uint32_t i=0; i < pData->param.count; ++i)
  1902. osc_send_control(fOscData, pData->param.data[i].rindex, getParameterValue(i));
  1903. if ((pData->hints & PLUGIN_HAS_CUSTOM_UI) != 0 && pData->engine->getOptions().frontendWinId != 0)
  1904. pData->transientTryCounter = 1;
  1905. carla_stdout("CarlaPluginDSSI::updateOscData() - done");
  1906. }
  1907. void handleOscMessageExiting()
  1908. {
  1909. carla_debug("CarlaPluginDSSI::handleMsgExiting()");
  1910. // hide UI
  1911. showCustomUI(false);
  1912. // tell frontend
  1913. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1914. }
  1915. #endif
  1916. #ifdef HAVE_LIBLO
  1917. // -------------------------------------------------------------------
  1918. // Post-poned UI Stuff
  1919. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1920. {
  1921. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1922. if (fOscData.target == nullptr)
  1923. return;
  1924. osc_send_control(fOscData, pData->param.data[index].rindex, value);
  1925. }
  1926. void uiMidiProgramChange(const uint32_t index) noexcept override
  1927. {
  1928. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1929. if (fOscData.target == nullptr)
  1930. return;
  1931. osc_send_program(fOscData, pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  1932. }
  1933. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  1934. {
  1935. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1936. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1937. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  1938. if (fOscData.target == nullptr)
  1939. return;
  1940. #if 0
  1941. uint8_t midiData[4];
  1942. midiData[0] = 0;
  1943. midiData[1] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  1944. midiData[2] = note;
  1945. midiData[3] = velo;
  1946. osc_send_midi(fOscData, midiData);
  1947. #endif
  1948. }
  1949. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  1950. {
  1951. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1952. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1953. if (fOscData.target == nullptr)
  1954. return;
  1955. #if 0
  1956. uint8_t midiData[4];
  1957. midiData[0] = 0;
  1958. midiData[1] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  1959. midiData[2] = note;
  1960. midiData[3] = 0;
  1961. osc_send_midi(fOscData, midiData);
  1962. #endif
  1963. }
  1964. #endif
  1965. // -------------------------------------------------------------------
  1966. void* getNativeHandle() const noexcept override
  1967. {
  1968. return fHandle;
  1969. }
  1970. const void* getNativeDescriptor() const noexcept override
  1971. {
  1972. return fDssiDescriptor;
  1973. }
  1974. #ifdef HAVE_LIBLO
  1975. uintptr_t getUiBridgeProcessId() const noexcept override
  1976. {
  1977. return fThreadUI.getProcessPID();
  1978. }
  1979. const void* getExtraStuff() const noexcept override
  1980. {
  1981. return fUiFilename;
  1982. }
  1983. #endif
  1984. // -------------------------------------------------------------------
  1985. bool init(const char* const filename, const char* const name, const char* const label)
  1986. {
  1987. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1988. // ---------------------------------------------------------------
  1989. // first checks
  1990. if (pData->client != nullptr)
  1991. {
  1992. pData->engine->setLastError("Plugin client is already registered");
  1993. return false;
  1994. }
  1995. if (filename == nullptr || filename[0] == '\0')
  1996. {
  1997. pData->engine->setLastError("null filename");
  1998. return false;
  1999. }
  2000. if (label == nullptr || label[0] == '\0')
  2001. {
  2002. pData->engine->setLastError("null label");
  2003. return false;
  2004. }
  2005. // ---------------------------------------------------------------
  2006. // open DLL
  2007. if (! pData->libOpen(filename))
  2008. {
  2009. pData->engine->setLastError(pData->libError(filename));
  2010. return false;
  2011. }
  2012. // ---------------------------------------------------------------
  2013. // get DLL main entry
  2014. const DSSI_Descriptor_Function descFn = pData->libSymbol<DSSI_Descriptor_Function>("dssi_descriptor");
  2015. if (descFn == nullptr)
  2016. {
  2017. pData->engine->setLastError("Could not find the DSSI Descriptor in the plugin library");
  2018. return false;
  2019. }
  2020. // ---------------------------------------------------------------
  2021. // get descriptor that matches label
  2022. ulong i = 0;
  2023. for (;;)
  2024. {
  2025. try {
  2026. fDssiDescriptor = descFn(i++);
  2027. }
  2028. catch(...) {
  2029. carla_stderr2("Caught exception when trying to get LADSPA descriptor");
  2030. fDescriptor = nullptr;
  2031. fDssiDescriptor = nullptr;
  2032. break;
  2033. }
  2034. if (fDssiDescriptor == nullptr)
  2035. break;
  2036. fDescriptor = fDssiDescriptor->LADSPA_Plugin;
  2037. if (fDescriptor == nullptr)
  2038. {
  2039. carla_stderr2("WARNING - Missing LADSPA interface, will not use this plugin");
  2040. fDssiDescriptor = nullptr;
  2041. break;
  2042. }
  2043. if (fDescriptor->Label == nullptr || fDescriptor->Label[0] == '\0')
  2044. {
  2045. carla_stderr2("WARNING - Got an invalid label, will not use this plugin");
  2046. fDescriptor = nullptr;
  2047. fDssiDescriptor = nullptr;
  2048. break;
  2049. }
  2050. if (fDescriptor->run == nullptr)
  2051. {
  2052. carla_stderr2("WARNING - Plugin has no run, cannot use it");
  2053. fDescriptor = nullptr;
  2054. fDssiDescriptor = nullptr;
  2055. break;
  2056. }
  2057. if (std::strcmp(fDescriptor->Label, label) == 0)
  2058. break;
  2059. }
  2060. if (fDescriptor == nullptr || fDssiDescriptor == nullptr)
  2061. {
  2062. pData->engine->setLastError("Could not find the requested plugin label in the plugin library");
  2063. return false;
  2064. }
  2065. // ---------------------------------------------------------------
  2066. // check if uses global instance
  2067. if (fDssiDescriptor->run_synth == nullptr && fDssiDescriptor->run_multiple_synths != nullptr)
  2068. {
  2069. if (! addUniqueMultiSynth(fDescriptor->Label))
  2070. {
  2071. pData->engine->setLastError("This plugin uses a global instance and can't be used more than once safely");
  2072. return false;
  2073. }
  2074. }
  2075. // ---------------------------------------------------------------
  2076. // get info
  2077. if (name != nullptr && name[0] != '\0')
  2078. pData->name = pData->engine->getUniquePluginName(name);
  2079. else if (fDescriptor->Name != nullptr && fDescriptor->Name[0] != '\0')
  2080. pData->name = pData->engine->getUniquePluginName(fDescriptor->Name);
  2081. else
  2082. pData->name = pData->engine->getUniquePluginName(fDescriptor->Label);
  2083. pData->filename = carla_strdup(filename);
  2084. // ---------------------------------------------------------------
  2085. // register client
  2086. pData->client = pData->engine->addClient(this);
  2087. if (pData->client == nullptr || ! pData->client->isOk())
  2088. {
  2089. pData->engine->setLastError("Failed to register plugin client");
  2090. return false;
  2091. }
  2092. // ---------------------------------------------------------------
  2093. // initialize plugin
  2094. try {
  2095. fHandle = fDescriptor->instantiate(fDescriptor, (ulong)pData->engine->getSampleRate());
  2096. } CARLA_SAFE_EXCEPTION("DSSI instantiate");
  2097. if (fHandle == nullptr)
  2098. {
  2099. pData->engine->setLastError("Plugin failed to initialize");
  2100. return false;
  2101. }
  2102. // ---------------------------------------------------------------
  2103. // check for custom data extension
  2104. if (fDssiDescriptor->configure != nullptr)
  2105. {
  2106. if (char* const error = fDssiDescriptor->configure(fHandle, DSSI_CUSTOMDATA_EXTENSION_KEY, ""))
  2107. {
  2108. if (std::strcmp(error, "true") == 0 && fDssiDescriptor->get_custom_data != nullptr && fDssiDescriptor->set_custom_data != nullptr)
  2109. fUsesCustomData = true;
  2110. std::free(error);
  2111. }
  2112. }
  2113. #ifdef HAVE_LIBLO
  2114. // ---------------------------------------------------------------
  2115. // gui stuff
  2116. if (const char* const guiFilename = find_dssi_ui(filename, fDescriptor->Label))
  2117. {
  2118. fThreadUI.setData(guiFilename, fDescriptor->Label);
  2119. fUiFilename = guiFilename;
  2120. }
  2121. #endif
  2122. // ---------------------------------------------------------------
  2123. // set default options
  2124. #ifdef __USE_GNU
  2125. const bool isDssiVst(strcasestr(pData->filename, "dssi-vst") != nullptr);
  2126. #else
  2127. const bool isDssiVst(std::strstr(pData->filename, "dssi-vst") != nullptr);
  2128. #endif
  2129. pData->options = 0x0;
  2130. if (fLatencyIndex >= 0 || isDssiVst)
  2131. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2132. if (pData->engine->getOptions().forceStereo)
  2133. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2134. if (fUsesCustomData)
  2135. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2136. if (fDssiDescriptor->get_program != nullptr && fDssiDescriptor->select_program != nullptr)
  2137. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2138. if (fDssiDescriptor->run_synth != nullptr || fDssiDescriptor->run_multiple_synths != nullptr)
  2139. {
  2140. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2141. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2142. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2143. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2144. if (fDssiDescriptor->run_synth == nullptr)
  2145. carla_stderr("WARNING: Plugin can ONLY use run_multiple_synths!");
  2146. }
  2147. return true;
  2148. }
  2149. // -------------------------------------------------------------------
  2150. private:
  2151. LADSPA_Handle fHandle;
  2152. LADSPA_Handle fHandle2;
  2153. const LADSPA_Descriptor* fDescriptor;
  2154. const DSSI_Descriptor* fDssiDescriptor;
  2155. bool fUsesCustomData;
  2156. #ifdef HAVE_LIBLO
  2157. const char* fUiFilename;
  2158. #endif
  2159. float** fAudioInBuffers;
  2160. float** fAudioOutBuffers;
  2161. float* fParamBuffers;
  2162. bool fLatencyChanged;
  2163. int32_t fLatencyIndex; // -1 if invalid
  2164. snd_seq_event_t fMidiEvents[kPluginMaxMidiEvents];
  2165. #ifdef HAVE_LIBLO
  2166. CarlaOscData fOscData;
  2167. CarlaThreadDSSIUI fThreadUI;
  2168. #endif
  2169. // -------------------------------------------------------------------
  2170. uint32_t getSafePortCount() const noexcept
  2171. {
  2172. if (fDescriptor->PortCount == 0)
  2173. return 0;
  2174. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortDescriptors != nullptr, 0);
  2175. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortRangeHints != nullptr, 0);
  2176. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortNames != nullptr, 0);
  2177. return static_cast<uint32_t>(fDescriptor->PortCount);
  2178. }
  2179. bool getSeparatedParameterNameOrUnit(const char* const paramName, char* const strBuf, const bool wantName) const noexcept
  2180. {
  2181. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, true))
  2182. return true;
  2183. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, false))
  2184. return true;
  2185. return false;
  2186. }
  2187. bool _getSeparatedParameterNameOrUnitImpl(const char* const paramName, char* const strBuf, const bool wantName, const bool useBracket) const noexcept
  2188. {
  2189. const char* const sepBracketStart(std::strstr(paramName, useBracket ? " [" : " ("));
  2190. if (sepBracketStart == nullptr)
  2191. return false;
  2192. const char* const sepBracketEnd(std::strstr(sepBracketStart, useBracket ? "]" : ")"));
  2193. if (sepBracketEnd == nullptr)
  2194. return false;
  2195. const size_t unitSize(static_cast<size_t>(sepBracketEnd-sepBracketStart-2));
  2196. if (unitSize > 7) // very unlikely to have such big unit
  2197. return false;
  2198. const size_t sepIndex(std::strlen(paramName)-unitSize-3);
  2199. // just in case
  2200. if (sepIndex > STR_MAX)
  2201. return false;
  2202. if (wantName)
  2203. {
  2204. std::strncpy(strBuf, paramName, sepIndex);
  2205. strBuf[sepIndex] = '\0';
  2206. }
  2207. else
  2208. {
  2209. std::strncpy(strBuf, paramName+(sepIndex+2), unitSize);
  2210. strBuf[unitSize] = '\0';
  2211. }
  2212. return true;
  2213. }
  2214. // -------------------------------------------------------------------
  2215. static LinkedList<const char*> sMultiSynthList;
  2216. static bool addUniqueMultiSynth(const char* const label) noexcept
  2217. {
  2218. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0', false);
  2219. const char* dlabel = nullptr;
  2220. try {
  2221. dlabel = carla_strdup(label);
  2222. } catch(...) { return false; }
  2223. for (LinkedList<const char*>::Itenerator it = sMultiSynthList.begin(); it.valid(); it.next())
  2224. {
  2225. const char* const itLabel(it.getValue());
  2226. if (std::strcmp(dlabel, itLabel) == 0)
  2227. {
  2228. delete[] dlabel;
  2229. return false;
  2230. }
  2231. }
  2232. return sMultiSynthList.append(dlabel);
  2233. }
  2234. static void removeUniqueMultiSynth(const char* const label) noexcept
  2235. {
  2236. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0',);
  2237. for (LinkedList<const char*>::Itenerator it = sMultiSynthList.begin(); it.valid(); it.next())
  2238. {
  2239. const char* const itLabel(it.getValue());
  2240. if (std::strcmp(label, itLabel) == 0)
  2241. {
  2242. sMultiSynthList.remove(it);
  2243. delete[] itLabel;
  2244. break;
  2245. }
  2246. }
  2247. }
  2248. // -------------------------------------------------------------------
  2249. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginDSSI)
  2250. };
  2251. LinkedList<const char*> CarlaPluginDSSI::sMultiSynthList;
  2252. // -------------------------------------------------------------------------------------------------------------------
  2253. CarlaPlugin* CarlaPlugin::newDSSI(const Initializer& init)
  2254. {
  2255. carla_debug("CarlaPlugin::newDSSI({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "})", init.engine, init.filename, init.name, init.label, init.uniqueId);
  2256. CarlaPluginDSSI* const plugin(new CarlaPluginDSSI(init.engine, init.id));
  2257. if (! plugin->init(init.filename, init.name, init.label))
  2258. {
  2259. delete plugin;
  2260. return nullptr;
  2261. }
  2262. plugin->reload();
  2263. bool canRun = true;
  2264. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  2265. {
  2266. if (! plugin->canRunInRack())
  2267. {
  2268. init.engine->setLastError("Carla's rack mode can only work with Mono or Stereo DSSI plugins, sorry!");
  2269. canRun = false;
  2270. }
  2271. else if (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0)
  2272. {
  2273. init.engine->setLastError("Carla's rack mode cannot work with plugins that have CV ports, sorry!");
  2274. canRun = false;
  2275. }
  2276. }
  2277. else if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_PATCHBAY && (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0))
  2278. {
  2279. init.engine->setLastError("CV ports in patchbay mode is still TODO");
  2280. canRun = false;
  2281. }
  2282. if (! canRun)
  2283. {
  2284. delete plugin;
  2285. return nullptr;
  2286. }
  2287. return plugin;
  2288. }
  2289. // -------------------------------------------------------------------------------------------------------------------
  2290. CARLA_BACKEND_END_NAMESPACE