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.

2848 lines
102KB

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