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.

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