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.

2794 lines
100KB

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