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.

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