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.

2809 lines
102KB

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