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.

2847 lines
102KB

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