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.

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