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.

2956 lines
105KB

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