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.

2886 lines
104KB

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