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.

2863 lines
103KB

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