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.

2861 lines
102KB

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