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.

2895 lines
104KB

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