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.

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