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.

2882 lines
103KB

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