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.

2843 lines
102KB

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