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.

2533 lines
89KB

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