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.

2817 lines
101KB

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