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.

1870 lines
66KB

  1. /*
  2. * Carla Juce Plugin
  3. * Copyright (C) 2013-2021 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 "CarlaEngine.hpp"
  19. #ifdef USING_JUCE
  20. #include "CarlaBackendUtils.hpp"
  21. #include "CarlaMathUtils.hpp"
  22. #include "CarlaProcessUtils.hpp"
  23. #include "CarlaScopeUtils.hpp"
  24. #include "CarlaVst2Utils.hpp"
  25. #include "CarlaVst3Utils.hpp"
  26. #define JUCE_GUI_BASICS_INCLUDE_XHEADERS 1
  27. #include "carla_juce/carla_juce.h"
  28. #pragma GCC diagnostic push
  29. #pragma GCC diagnostic ignored "-Wdouble-promotion"
  30. #pragma GCC diagnostic ignored "-Wduplicated-branches"
  31. #pragma GCC diagnostic ignored "-Weffc++"
  32. #pragma GCC diagnostic ignored "-Wfloat-equal"
  33. #include "juce_audio_processors/juce_audio_processors.h"
  34. #include "juce_gui_basics/juce_gui_basics.h"
  35. #pragma GCC diagnostic pop
  36. #include "JucePluginWindow.hpp"
  37. CARLA_BACKEND_START_NAMESPACE
  38. // -------------------------------------------------------------------------------------------------------------------
  39. // Fallback data
  40. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  41. // -------------------------------------------------------------------------------------------------------------------
  42. // find all available plugin audio ports
  43. static void findMaxTotalChannels(juce::AudioProcessor* const filter,
  44. const bool isAU, uint32_t& maxTotalIns, uint32_t& maxTotalOuts)
  45. {
  46. filter->enableAllBuses();
  47. if (isAU)
  48. {
  49. maxTotalIns = static_cast<uint32_t>(juce::jmax(0, filter->getTotalNumInputChannels()));
  50. maxTotalOuts = static_cast<uint32_t>(juce::jmax(0, filter->getTotalNumOutputChannels()));
  51. return;
  52. }
  53. const int numInputBuses = filter->getBusCount(true);
  54. const int numOutputBuses = filter->getBusCount(false);
  55. if (numInputBuses > 1 || numOutputBuses > 1)
  56. {
  57. maxTotalIns = maxTotalOuts = 0;
  58. for (int i = 0; i < numInputBuses; ++i)
  59. maxTotalIns += static_cast<uint32_t>(juce::jmax(0, filter->getChannelCountOfBus(true, i)));
  60. for (int i = 0; i < numOutputBuses; ++i)
  61. maxTotalOuts += static_cast<uint32_t>(juce::jmax(0, filter->getChannelCountOfBus(false, i)));
  62. }
  63. else
  64. {
  65. maxTotalIns = numInputBuses > 0
  66. ? static_cast<uint32_t>(juce::jmax(0, filter->getBus(true, 0)->getMaxSupportedChannels(64)))
  67. : 0;
  68. maxTotalOuts = numOutputBuses > 0
  69. ? static_cast<uint32_t>(juce::jmax(0, filter->getBus(false, 0)->getMaxSupportedChannels(64)))
  70. : 0;
  71. }
  72. }
  73. // -------------------------------------------------------------------------------------------------------------------
  74. class CarlaPluginJuce : public CarlaPlugin,
  75. private juce::AudioPlayHead,
  76. private juce::AudioProcessorListener
  77. {
  78. public:
  79. CarlaPluginJuce(CarlaEngine* const engine, const uint id)
  80. : CarlaPlugin(engine, id),
  81. fDesc(),
  82. fFormatManager(),
  83. fInstance(),
  84. fAudioBuffer(),
  85. fMidiBuffer(),
  86. fPosInfo(),
  87. fChunk(),
  88. fFormatName(),
  89. fWindow(),
  90. fNeedsUpdate(false)
  91. {
  92. carla_debug("CarlaPluginJuce::CarlaPluginJuce(%p, %i)", engine, id);
  93. fMidiBuffer.ensureSize(2048);
  94. fMidiBuffer.clear();
  95. fPosInfo.resetToDefault();
  96. }
  97. ~CarlaPluginJuce() override
  98. {
  99. carla_debug("CarlaPluginJuce::~CarlaPluginJuce()");
  100. // close UI
  101. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  102. showCustomUI(false);
  103. pData->singleMutex.lock();
  104. pData->masterMutex.lock();
  105. if (pData->client != nullptr && pData->client->isActive())
  106. pData->client->deactivate(true);
  107. if (pData->active)
  108. {
  109. deactivate();
  110. pData->active = false;
  111. }
  112. fInstance = nullptr;
  113. clearBuffers();
  114. }
  115. // -------------------------------------------------------------------
  116. // Information (base)
  117. PluginType getType() const noexcept override
  118. {
  119. return getPluginTypeFromString(fDesc.pluginFormatName.toRawUTF8());
  120. }
  121. PluginCategory getCategory() const noexcept override
  122. {
  123. if (fDesc.isInstrument)
  124. return PLUGIN_CATEGORY_SYNTH;
  125. return getPluginCategoryFromName(fDesc.category.isNotEmpty()
  126. ? fDesc.category.toRawUTF8()
  127. : fDesc.name.toRawUTF8());
  128. }
  129. int64_t getUniqueId() const noexcept override
  130. {
  131. return fDesc.uniqueId;
  132. }
  133. uint32_t getLatencyInFrames() const noexcept override
  134. {
  135. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0);
  136. const int latency = fInstance->getLatencySamples();
  137. CARLA_SAFE_ASSERT_RETURN(latency >= 0, 0);
  138. return static_cast<uint32_t>(latency);
  139. }
  140. // -------------------------------------------------------------------
  141. // Information (count)
  142. // nothing
  143. // -------------------------------------------------------------------
  144. // Information (current data)
  145. std::size_t getChunkData(void** const dataPtr) noexcept override
  146. {
  147. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  148. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0);
  149. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  150. *dataPtr = nullptr;
  151. try {
  152. fChunk.reset();
  153. fInstance->getStateInformation(fChunk);
  154. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPluginJuce::getChunkData", 0);
  155. if (const std::size_t size = fChunk.getSize())
  156. {
  157. *dataPtr = fChunk.getData();
  158. return size;
  159. }
  160. return 0;
  161. }
  162. // -------------------------------------------------------------------
  163. // Information (per-plugin data)
  164. uint getOptionsAvailable() const noexcept override
  165. {
  166. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0x0);
  167. uint options = 0x0;
  168. options |= PLUGIN_OPTION_USE_CHUNKS;
  169. if (fInstance->getNumPrograms() > 1)
  170. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  171. if (fInstance->acceptsMidi())
  172. {
  173. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  174. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  175. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  176. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  177. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  178. options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  179. options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  180. }
  181. return options;
  182. }
  183. float getParameterValue(const uint32_t parameterId) const noexcept override
  184. {
  185. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  186. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0.0f);
  187. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  188. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr, 0.0f);
  189. return parameter->getValue();
  190. }
  191. bool getLabel(char* const strBuf) const noexcept override
  192. {
  193. if (fDesc.pluginFormatName == "AU" || fDesc.pluginFormatName == "AudioUnit")
  194. std::strncpy(strBuf, fDesc.fileOrIdentifier.toRawUTF8(), STR_MAX);
  195. else
  196. std::strncpy(strBuf, fDesc.name.toRawUTF8(), STR_MAX);
  197. return true;
  198. }
  199. bool getMaker(char* const strBuf) const noexcept override
  200. {
  201. std::strncpy(strBuf, fDesc.manufacturerName.toRawUTF8(), STR_MAX);
  202. return true;
  203. }
  204. bool getCopyright(char* const strBuf) const noexcept override
  205. {
  206. return getMaker(strBuf);
  207. }
  208. bool getRealName(char* const strBuf) const noexcept override
  209. {
  210. std::strncpy(strBuf, fDesc.descriptiveName.toRawUTF8(), STR_MAX);
  211. return true;
  212. }
  213. bool getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  214. {
  215. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  216. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, false);
  217. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  218. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr, false);
  219. std::strncpy(strBuf, parameter->getName(STR_MAX).toRawUTF8(), STR_MAX);
  220. return true;
  221. }
  222. bool getParameterText(const uint32_t parameterId, char* const strBuf) noexcept override
  223. {
  224. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  225. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, false);
  226. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  227. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr, false);
  228. std::strncpy(strBuf, parameter->getCurrentValueAsText().toRawUTF8(), STR_MAX);
  229. return true;
  230. }
  231. bool getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  232. {
  233. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  234. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, false);
  235. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  236. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr, false);
  237. std::strncpy(strBuf, parameter->getLabel().toRawUTF8(), STR_MAX);
  238. return true;
  239. }
  240. bool getParameterGroupName(const uint32_t parameterId, char* const strBuf) const noexcept override
  241. {
  242. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  243. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, false);
  244. if (fDesc.pluginFormatName != "VST" && fDesc.pluginFormatName != "VST2")
  245. return false;
  246. AEffect* const effect = (AEffect*)fInstance->getPlatformSpecificData();
  247. if (effect == nullptr)
  248. return false;
  249. VstParameterProperties prop;
  250. carla_zeroStruct(prop);
  251. if (effect->dispatcher(effect, effGetParameterProperties, static_cast<int32_t>(parameterId), 0, &prop, 0.0f) == 1
  252. && prop.category != 0 && prop.categoryLabel[0] != '\0')
  253. {
  254. std::snprintf(strBuf, STR_MAX, "%d:%s", prop.category, prop.categoryLabel);
  255. return true;
  256. }
  257. return false;
  258. }
  259. // -------------------------------------------------------------------
  260. // Set data (state)
  261. // nothing
  262. // -------------------------------------------------------------------
  263. // Set data (internal stuff)
  264. void setName(const char* const newName) override
  265. {
  266. CarlaPlugin::setName(newName);
  267. if (fWindow == nullptr || pData->uiTitle.isNotEmpty())
  268. return;
  269. juce::String uiName(pData->name);
  270. uiName += " (GUI)";
  271. fWindow->setName(uiName);
  272. }
  273. // -------------------------------------------------------------------
  274. // Set data (plugin-specific stuff)
  275. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  276. {
  277. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  278. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  279. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  280. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr,);
  281. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  282. try {
  283. parameter->setValue(value);
  284. } CARLA_SAFE_EXCEPTION("setValue");
  285. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  286. }
  287. void setParameterValueRT(const uint32_t parameterId, const float value, const uint32_t frameOffset, const bool sendCallbackLater) noexcept override
  288. {
  289. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  290. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  291. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  292. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr,);
  293. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  294. try {
  295. parameter->setValue(value);
  296. } CARLA_SAFE_EXCEPTION("setValue(RT)");
  297. CarlaPlugin::setParameterValueRT(parameterId, fixedValue, frameOffset, sendCallbackLater);
  298. }
  299. void setChunkData(const void* const data, const std::size_t dataSize) override
  300. {
  301. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  302. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  303. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  304. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  305. if (isJuceSaveFormat(data, dataSize))
  306. {
  307. const ScopedSingleProcessLocker spl(this, true);
  308. fInstance->setStateInformation(data, static_cast<int>(dataSize));
  309. }
  310. else
  311. {
  312. uint8_t* const dataCompat = (uint8_t*)std::malloc(dataSize + 160);
  313. CARLA_SAFE_ASSERT_RETURN(dataCompat != nullptr,);
  314. carla_stdout("NOTE: Loading plugin state in Carla JUCE/VST2 compatibility mode");
  315. std::memset(dataCompat, 0, 160);
  316. std::memcpy(dataCompat+160, data, dataSize);
  317. int32_t* const set = (int32_t*)dataCompat;
  318. set[0] = (int32_t)juce::ByteOrder::littleEndianInt("CcnK");
  319. set[2] = (int32_t)juce::ByteOrder::littleEndianInt("FBCh");
  320. set[3] = fxbSwap(1);
  321. set[39] = fxbSwap(static_cast<int32_t>(dataSize));
  322. {
  323. const ScopedSingleProcessLocker spl(this, true);
  324. fInstance->setStateInformation(dataCompat, static_cast<int>(dataSize+160));
  325. }
  326. std::free(dataCompat);
  327. }
  328. pData->updateParameterValues(this, true, true, false);
  329. }
  330. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback, const bool doingInit) noexcept override
  331. {
  332. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  333. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  334. if (index >= 0)
  335. {
  336. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  337. try {
  338. fInstance->setCurrentProgram(index);
  339. } CARLA_SAFE_EXCEPTION("setCurrentProgram");
  340. }
  341. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback, doingInit);
  342. }
  343. void setProgramRT(const uint32_t index, const bool sendCallbackLater) noexcept override
  344. {
  345. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  346. CARLA_SAFE_ASSERT_RETURN(index < pData->prog.count,);
  347. try {
  348. fInstance->setCurrentProgram(static_cast<int32_t>(index));
  349. } CARLA_SAFE_EXCEPTION("setCurrentProgram");
  350. CarlaPlugin::setProgramRT(index, sendCallbackLater);
  351. }
  352. // -------------------------------------------------------------------
  353. // Set ui stuff
  354. void setCustomUITitle(const char* const title) noexcept override
  355. {
  356. if (fWindow != nullptr)
  357. {
  358. try {
  359. fWindow->setName(title);
  360. } CARLA_SAFE_EXCEPTION("set custom ui title");
  361. }
  362. CarlaPlugin::setCustomUITitle(title);
  363. }
  364. void showCustomUI(const bool yesNo) override
  365. {
  366. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  367. carla_debug("CarlaPluginJuce::showCustomUI(%s)", bool2str(yesNo));
  368. if (yesNo)
  369. {
  370. if (juce::AudioProcessorEditor* const editor = fInstance->createEditorIfNeeded())
  371. {
  372. const EngineOptions& opts(pData->engine->getOptions());
  373. #ifndef CARLA_OS_MAC
  374. editor->setScaleFactor(opts.uiScale);
  375. #endif
  376. if (fWindow == nullptr)
  377. {
  378. juce::String uiName;
  379. if (pData->uiTitle.isNotEmpty())
  380. {
  381. uiName = pData->uiTitle.buffer();
  382. }
  383. else
  384. {
  385. uiName = pData->name;
  386. uiName += " (GUI)";
  387. }
  388. AEffect* const vst2effect = fDesc.pluginFormatName == "VST" || fDesc.pluginFormatName == "VST2"
  389. ? (AEffect*)fInstance->getPlatformSpecificData()
  390. : nullptr;
  391. v3_plugin_view** const vst3view = fDesc.pluginFormatName == "VST3"
  392. ? (v3_plugin_view**)editor->getPlatformSpecificData()
  393. : nullptr;
  394. fWindow = new JucePluginWindow(opts.frontendWinId, opts.pluginsAreStandalone,
  395. vst2effect, vst3view);
  396. fWindow->setName(uiName);
  397. }
  398. fWindow->show(editor);
  399. fWindow->toFront(true);
  400. }
  401. }
  402. else
  403. {
  404. if (juce::AudioProcessorEditor* const editor = fInstance->getActiveEditor())
  405. delete editor;
  406. fWindow = nullptr;
  407. }
  408. }
  409. void uiIdle() override
  410. {
  411. if (fWindow != nullptr)
  412. {
  413. if (fWindow->wasClosedByUser())
  414. {
  415. showCustomUI(false);
  416. pData->engine->callback(true, true,
  417. ENGINE_CALLBACK_UI_STATE_CHANGED,
  418. pData->id,
  419. 0,
  420. 0, 0, 0.0f, nullptr);
  421. }
  422. }
  423. CarlaPlugin::uiIdle();
  424. }
  425. // -------------------------------------------------------------------
  426. // Plugin state
  427. void reload() override
  428. {
  429. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  430. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  431. carla_debug("CarlaPluginJuce::reload() - start");
  432. const EngineProcessMode processMode(pData->engine->getProccessMode());
  433. // Safely disable plugin for reload
  434. const ScopedDisabler sd(this);
  435. if (pData->active)
  436. deactivate();
  437. clearBuffers();
  438. uint32_t aIns, aOuts, mIns, mOuts, params;
  439. mIns = mOuts = 0;
  440. bool needsCtrlIn, needsCtrlOut;
  441. needsCtrlIn = needsCtrlOut = false;
  442. const bool isAU = fDesc.pluginFormatName == "AU" || fDesc.pluginFormatName == "AudioUnit";
  443. const bool isVST2 = fDesc.pluginFormatName == "VST" || fDesc.pluginFormatName == "VST2";
  444. const bool isVST3 = fDesc.pluginFormatName == "VST3";
  445. findMaxTotalChannels(fInstance.get(), isAU, aIns, aOuts);
  446. fInstance->refreshParameterList();
  447. const juce::Array<juce::AudioProcessorParameter*>& parameters(fInstance->getParameters());
  448. params = static_cast<uint32_t>(std::max(parameters.size(), 0));
  449. if (fInstance->acceptsMidi())
  450. {
  451. mIns = 1;
  452. needsCtrlIn = true;
  453. }
  454. if (fInstance->producesMidi())
  455. {
  456. mOuts = 1;
  457. needsCtrlOut = true;
  458. }
  459. if (aIns > 0)
  460. {
  461. pData->audioIn.createNew(aIns);
  462. }
  463. if (aOuts > 0)
  464. {
  465. pData->audioOut.createNew(aOuts);
  466. needsCtrlIn = true;
  467. }
  468. if (params > 0)
  469. {
  470. pData->param.createNew(params, false);
  471. needsCtrlIn = true;
  472. }
  473. const uint portNameSize(pData->engine->getMaxPortNameSize());
  474. CarlaString portName;
  475. // Audio Ins
  476. for (uint32_t j=0; j < aIns; ++j)
  477. {
  478. portName.clear();
  479. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  480. {
  481. portName = pData->name;
  482. portName += ":";
  483. }
  484. if (aIns > 1)
  485. {
  486. portName += "input_";
  487. portName += CarlaString(j+1);
  488. }
  489. else
  490. portName += "input";
  491. portName.truncate(portNameSize);
  492. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  493. pData->audioIn.ports[j].rindex = j;
  494. }
  495. // Audio Outs
  496. for (uint32_t j=0; j < aOuts; ++j)
  497. {
  498. portName.clear();
  499. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  500. {
  501. portName = pData->name;
  502. portName += ":";
  503. }
  504. if (aOuts > 1)
  505. {
  506. portName += "output_";
  507. portName += CarlaString(j+1);
  508. }
  509. else
  510. portName += "output";
  511. portName.truncate(portNameSize);
  512. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  513. pData->audioOut.ports[j].rindex = j;
  514. }
  515. for (uint32_t j=0; j < params; ++j)
  516. {
  517. const int32_t ij = static_cast<int>(j);
  518. juce::AudioProcessorParameter* const parameter = parameters[ij];
  519. CARLA_SAFE_ASSERT_CONTINUE(parameter != nullptr);
  520. pData->param.data[j].type = PARAMETER_INPUT;
  521. pData->param.data[j].index = static_cast<int32_t>(j);
  522. pData->param.data[j].rindex = static_cast<int32_t>(j);
  523. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  524. pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  525. if (parameter->isAutomatable())
  526. pData->param.data[j].hints |= PARAMETER_IS_AUTOMATABLE;
  527. const float min = 0.0f;
  528. const float max = 1.0f;
  529. float def, step, stepSmall, stepLarge;
  530. bool hasDetails = false;
  531. if (isVST2)
  532. {
  533. AEffect* const effect = (AEffect*)fInstance->getPlatformSpecificData();
  534. VstParameterProperties prop;
  535. carla_zeroStruct(prop);
  536. if (effect != nullptr && effect->dispatcher(effect, effGetParameterProperties, ij, 0, &prop, 0.0f) == 1)
  537. {
  538. hasDetails = true;
  539. /**/ if (prop.flags & kVstParameterIsSwitch)
  540. {
  541. step = max - min;
  542. stepSmall = step;
  543. stepLarge = step;
  544. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  545. }
  546. else if (prop.flags & kVstParameterUsesIntStep)
  547. {
  548. step = static_cast<float>(prop.stepInteger);
  549. stepSmall = static_cast<float>(prop.stepInteger)/10.0f;
  550. stepLarge = static_cast<float>(prop.largeStepInteger);
  551. }
  552. else if (prop.flags & kVstParameterUsesFloatStep)
  553. {
  554. step = prop.stepFloat;
  555. stepSmall = prop.smallStepFloat;
  556. stepLarge = prop.largeStepFloat;
  557. }
  558. else
  559. {
  560. const float range = max - min;
  561. step = range/100.0f;
  562. stepSmall = range/1000.0f;
  563. stepLarge = range/10.0f;
  564. }
  565. if ((prop.flags & (kVstParameterIsSwitch|kVstParameterUsesIntStep)) == 0x0)
  566. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  567. if (prop.flags & kVstParameterCanRamp)
  568. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  569. }
  570. }
  571. else if (isVST3)
  572. {
  573. v3_component** const component = (v3_component**)fInstance->getPlatformSpecificData();
  574. v3_edit_controller** controller = nullptr;
  575. v3_cpp_obj_query_interface(component, v3_edit_controller_iid, &controller);
  576. if (controller != nullptr)
  577. {
  578. v3_param_info info;
  579. if (v3_cpp_obj(controller)->get_parameter_info(controller, static_cast<int32_t>(j), &info) == V3_OK)
  580. {
  581. hasDetails = true;
  582. if (info.step_count == 1)
  583. {
  584. step = stepSmall = stepLarge = 1;
  585. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  586. }
  587. else if (info.step_count != 0)
  588. {
  589. step = 1.0f / static_cast<float>(info.step_count);
  590. stepSmall = step/10.0f;
  591. stepLarge = std::min(1.0f, step*10.0f);
  592. }
  593. else
  594. {
  595. const float range = max - min;
  596. step = range/100.0f;
  597. stepSmall = range/1000.0f;
  598. stepLarge = range/10.0f;
  599. }
  600. if (info.flags & V3_PARAM_READ_ONLY)
  601. pData->param.data[j].type = PARAMETER_OUTPUT;
  602. // TODO V3_PARAM_IS_LIST
  603. if (info.flags & (V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE))
  604. pData->param.data[j].hints &= ~PARAMETER_IS_ENABLED;
  605. if ((info.flags & (V3_PARAM_IS_LIST|V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE)) == 0x0)
  606. if (info.flags & V3_PARAM_CAN_AUTOMATE)
  607. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  608. }
  609. v3_cpp_obj_unref(controller);
  610. }
  611. }
  612. if (! hasDetails)
  613. {
  614. if (parameter->isBoolean())
  615. {
  616. step = max - min;
  617. stepSmall = step;
  618. stepLarge = step;
  619. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  620. }
  621. else
  622. {
  623. const float range = max - min;
  624. step = range/100.0f;
  625. stepSmall = range/1000.0f;
  626. stepLarge = range/10.0f;
  627. if (! parameter->isMetaParameter())
  628. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  629. }
  630. }
  631. def = parameter->getDefaultValue();
  632. if (def < min)
  633. def = min;
  634. else if (def > max)
  635. def = max;
  636. pData->param.ranges[j].min = min;
  637. pData->param.ranges[j].max = max;
  638. pData->param.ranges[j].def = def;
  639. pData->param.ranges[j].step = step;
  640. pData->param.ranges[j].stepSmall = stepSmall;
  641. pData->param.ranges[j].stepLarge = stepLarge;
  642. }
  643. if (needsCtrlIn)
  644. {
  645. portName.clear();
  646. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  647. {
  648. portName = pData->name;
  649. portName += ":";
  650. }
  651. portName += "events-in";
  652. portName.truncate(portNameSize);
  653. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  654. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  655. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  656. #endif
  657. }
  658. if (needsCtrlOut)
  659. {
  660. portName.clear();
  661. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  662. {
  663. portName = pData->name;
  664. portName += ":";
  665. }
  666. portName += "events-out";
  667. portName.truncate(portNameSize);
  668. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  669. }
  670. // plugin hints
  671. pData->hints = 0x0;
  672. pData->hints |= PLUGIN_NEEDS_FIXED_BUFFERS;
  673. if (fDesc.isInstrument)
  674. pData->hints |= PLUGIN_IS_SYNTH;
  675. if (fInstance->hasEditor())
  676. {
  677. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  678. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  679. }
  680. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  681. pData->hints |= PLUGIN_CAN_DRYWET;
  682. if (aOuts > 0)
  683. pData->hints |= PLUGIN_CAN_VOLUME;
  684. if (aOuts >= 2 && aOuts % 2 == 0)
  685. pData->hints |= PLUGIN_CAN_BALANCE;
  686. // extra plugin hints
  687. pData->extraHints = 0x0;
  688. if (mIns > 0)
  689. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  690. if (mOuts > 0)
  691. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  692. fInstance->setRateAndBufferSizeDetails(pData->engine->getSampleRate(),
  693. static_cast<int>(pData->engine->getBufferSize()));
  694. bufferSizeChanged(pData->engine->getBufferSize());
  695. reloadPrograms(true);
  696. if (pData->active)
  697. activate();
  698. carla_debug("CarlaPluginJuce::reload() - end");
  699. }
  700. void reloadPrograms(const bool doInit) override
  701. {
  702. carla_debug("CarlaPluginJuce::reloadPrograms(%s)", bool2str(doInit));
  703. const uint32_t oldCount = pData->prog.count;
  704. const int32_t current = pData->prog.current;
  705. // Delete old programs
  706. pData->prog.clear();
  707. // Query new programs
  708. const uint32_t newCount = (fInstance->getNumPrograms() > 0)
  709. ? static_cast<uint32_t>(fInstance->getNumPrograms())
  710. : 0;
  711. if (newCount > 0)
  712. {
  713. pData->prog.createNew(newCount);
  714. // Update names
  715. for (uint32_t i=0; i < newCount; ++i)
  716. pData->prog.names[i] = carla_strdup(fInstance->getProgramName(static_cast<int>(i)).toRawUTF8());
  717. }
  718. if (doInit)
  719. {
  720. if (newCount > 0)
  721. setProgram(0, false, false, false, true);
  722. }
  723. else
  724. {
  725. // Check if current program is invalid
  726. bool programChanged = false;
  727. if (newCount == oldCount+1)
  728. {
  729. // one program added, probably created by user
  730. pData->prog.current = static_cast<int32_t>(oldCount);
  731. programChanged = true;
  732. }
  733. else if (current < 0 && newCount > 0)
  734. {
  735. // programs exist now, but not before
  736. pData->prog.current = 0;
  737. programChanged = true;
  738. }
  739. else if (current >= 0 && newCount == 0)
  740. {
  741. // programs existed before, but not anymore
  742. pData->prog.current = -1;
  743. programChanged = true;
  744. }
  745. else if (current >= static_cast<int32_t>(newCount))
  746. {
  747. // current program > count
  748. pData->prog.current = 0;
  749. programChanged = true;
  750. }
  751. else
  752. {
  753. // no change
  754. pData->prog.current = current;
  755. }
  756. if (programChanged)
  757. {
  758. setProgram(pData->prog.current, true, true, true, false);
  759. }
  760. else
  761. {
  762. // Program was changed during update, re-set it
  763. if (pData->prog.current >= 0)
  764. fInstance->setCurrentProgram(pData->prog.current);
  765. }
  766. pData->engine->callback(true, true, ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0, 0.0f, nullptr);
  767. }
  768. }
  769. // -------------------------------------------------------------------
  770. // Plugin processing
  771. void activate() noexcept override
  772. {
  773. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  774. try {
  775. fInstance->prepareToPlay(pData->engine->getSampleRate(), static_cast<int>(pData->engine->getBufferSize()));
  776. } catch(...) {}
  777. }
  778. void deactivate() noexcept override
  779. {
  780. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  781. try {
  782. fInstance->releaseResources();
  783. } catch(...) {}
  784. }
  785. void process(const float* const* const audioIn,
  786. float** const audioOut,
  787. const float* const* const cvIn,
  788. float**,
  789. const uint32_t frames) override
  790. {
  791. // --------------------------------------------------------------------------------------------------------
  792. // Check if active
  793. if (! pData->active)
  794. {
  795. // disable any output sound
  796. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  797. carla_zeroFloats(audioOut[i], frames);
  798. return;
  799. }
  800. // --------------------------------------------------------------------------------------------------------
  801. // Check if needs reset
  802. if (pData->needsReset)
  803. {
  804. fInstance->reset();
  805. pData->needsReset = false;
  806. }
  807. // --------------------------------------------------------------------------------------------------------
  808. // Event Input
  809. fMidiBuffer.clear();
  810. if (pData->event.portIn != nullptr)
  811. {
  812. // ----------------------------------------------------------------------------------------------------
  813. // MIDI Input (External)
  814. if (pData->extNotes.mutex.tryLock())
  815. {
  816. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  817. {
  818. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  819. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  820. uint8_t midiEvent[3];
  821. midiEvent[0] = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  822. midiEvent[1] = note.note;
  823. midiEvent[2] = note.velo;
  824. fMidiBuffer.addEvent(midiEvent, 3, 0);
  825. }
  826. pData->extNotes.data.clear();
  827. pData->extNotes.mutex.unlock();
  828. } // End of MIDI Input (External)
  829. // ----------------------------------------------------------------------------------------------------
  830. // Event Input (System)
  831. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  832. bool allNotesOffSent = false;
  833. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  834. pData->event.cvSourcePorts->initPortBuffers(cvIn, frames, false, pData->event.portIn);
  835. #endif
  836. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  837. {
  838. EngineEvent& event(pData->event.portIn->getEvent(i));
  839. if (event.time >= frames)
  840. continue;
  841. switch (event.type)
  842. {
  843. case kEngineEventTypeNull:
  844. break;
  845. case kEngineEventTypeControl: {
  846. EngineControlEvent& ctrlEvent(event.ctrl);
  847. switch (ctrlEvent.type)
  848. {
  849. case kEngineControlEventTypeNull:
  850. break;
  851. case kEngineControlEventTypeParameter: {
  852. float value;
  853. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  854. // non-midi
  855. if (event.channel == kEngineEventNonMidiChannel)
  856. {
  857. const uint32_t k = ctrlEvent.param;
  858. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  859. ctrlEvent.handled = true;
  860. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  861. setParameterValueRT(k, value, event.time, true);
  862. continue;
  863. }
  864. // Control backend stuff
  865. if (event.channel == pData->ctrlChannel)
  866. {
  867. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  868. {
  869. ctrlEvent.handled = true;
  870. value = ctrlEvent.normalizedValue;
  871. setDryWetRT(value, true);
  872. }
  873. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  874. {
  875. ctrlEvent.handled = true;
  876. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  877. setVolumeRT(value, true);
  878. }
  879. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  880. {
  881. float left, right;
  882. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  883. if (value < 0.0f)
  884. {
  885. left = -1.0f;
  886. right = (value*2.0f)+1.0f;
  887. }
  888. else if (value > 0.0f)
  889. {
  890. left = (value*2.0f)-1.0f;
  891. right = 1.0f;
  892. }
  893. else
  894. {
  895. left = -1.0f;
  896. right = 1.0f;
  897. }
  898. ctrlEvent.handled = true;
  899. setBalanceLeftRT(left, true);
  900. setBalanceRightRT(right, true);
  901. }
  902. }
  903. #endif
  904. // Control plugin parameters
  905. uint32_t k;
  906. for (k=0; k < pData->param.count; ++k)
  907. {
  908. if (pData->param.data[k].midiChannel != event.channel)
  909. continue;
  910. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  911. continue;
  912. if (pData->param.data[k].type != PARAMETER_INPUT)
  913. continue;
  914. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  915. continue;
  916. ctrlEvent.handled = true;
  917. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  918. setParameterValueRT(k, value, event.time, true);
  919. }
  920. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  921. {
  922. uint8_t midiData[3];
  923. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  924. midiData[1] = uint8_t(ctrlEvent.param);
  925. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  926. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  927. }
  928. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  929. if (! ctrlEvent.handled)
  930. checkForMidiLearn(event);
  931. #endif
  932. break;
  933. } // case kEngineControlEventTypeParameter
  934. case kEngineControlEventTypeMidiBank:
  935. if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  936. {
  937. uint8_t midiData[3];
  938. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  939. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  940. midiData[2] = 0;
  941. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  942. midiData[1] = MIDI_CONTROL_BANK_SELECT__LSB;
  943. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  944. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  945. }
  946. break;
  947. case kEngineControlEventTypeMidiProgram:
  948. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  949. {
  950. if (ctrlEvent.param < pData->prog.count)
  951. {
  952. setProgramRT(ctrlEvent.param, true);
  953. }
  954. }
  955. else if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  956. {
  957. uint8_t midiData[2];
  958. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  959. midiData[1] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  960. fMidiBuffer.addEvent(midiData, 2, static_cast<int>(event.time));
  961. }
  962. break;
  963. case kEngineControlEventTypeAllSoundOff:
  964. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  965. {
  966. uint8_t midiData[3];
  967. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  968. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  969. midiData[2] = 0;
  970. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  971. }
  972. break;
  973. case kEngineControlEventTypeAllNotesOff:
  974. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  975. {
  976. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  977. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  978. {
  979. allNotesOffSent = true;
  980. postponeRtAllNotesOff();
  981. }
  982. #endif
  983. uint8_t midiData[3];
  984. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  985. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  986. midiData[2] = 0;
  987. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  988. }
  989. break;
  990. } // switch (ctrlEvent.type)
  991. break;
  992. } // case kEngineEventTypeControl
  993. case kEngineEventTypeMidi: {
  994. const EngineMidiEvent& midiEvent(event.midi);
  995. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  996. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  997. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  998. continue;
  999. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1000. continue;
  1001. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1002. continue;
  1003. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1004. continue;
  1005. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1006. continue;
  1007. // Fix bad note-off
  1008. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  1009. status = MIDI_STATUS_NOTE_OFF;
  1010. // put back channel in data
  1011. uint8_t midiData2[midiEvent.size];
  1012. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  1013. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  1014. fMidiBuffer.addEvent(midiData2, midiEvent.size, static_cast<int>(event.time));
  1015. if (status == MIDI_STATUS_NOTE_ON)
  1016. {
  1017. pData->postponeNoteOnRtEvent(true, event.channel, midiData[1], midiData[2]);
  1018. }
  1019. else if (status == MIDI_STATUS_NOTE_OFF)
  1020. {
  1021. pData->postponeNoteOffRtEvent(true, event.channel, midiData[1]);
  1022. }
  1023. } break;
  1024. } // switch (event.type)
  1025. }
  1026. pData->postRtEvents.trySplice();
  1027. } // End of Event Input
  1028. // --------------------------------------------------------------------------------------------------------
  1029. // Set TimeInfo
  1030. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  1031. fPosInfo.isPlaying = timeInfo.playing;
  1032. if (timeInfo.bbt.valid)
  1033. {
  1034. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  1035. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  1036. const double ppqBar = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  1037. const double ppqBeat = static_cast<double>(timeInfo.bbt.beat - 1);
  1038. const double ppqTick = timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat;
  1039. fPosInfo.bpm = timeInfo.bbt.beatsPerMinute;
  1040. fPosInfo.timeSigNumerator = static_cast<int>(timeInfo.bbt.beatsPerBar);
  1041. fPosInfo.timeSigDenominator = static_cast<int>(timeInfo.bbt.beatType);
  1042. fPosInfo.timeInSamples = static_cast<int64_t>(timeInfo.frame);
  1043. fPosInfo.timeInSeconds = static_cast<double>(fPosInfo.timeInSamples)/pData->engine->getSampleRate();
  1044. fPosInfo.ppqPosition = ppqBar + ppqBeat + ppqTick;
  1045. fPosInfo.ppqPositionOfLastBarStart = ppqBar;
  1046. }
  1047. // --------------------------------------------------------------------------------------------------------
  1048. // Process
  1049. processSingle(audioIn, audioOut, frames);
  1050. // --------------------------------------------------------------------------------------------------------
  1051. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1052. return;
  1053. // unused
  1054. (void)cvIn;
  1055. #endif
  1056. }
  1057. bool processSingle(const float* const* const inBuffer, float** const outBuffer, const uint32_t frames)
  1058. {
  1059. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1060. if (pData->audioIn.count > 0)
  1061. {
  1062. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  1063. }
  1064. if (pData->audioOut.count > 0)
  1065. {
  1066. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  1067. }
  1068. // --------------------------------------------------------------------------------------------------------
  1069. // Try lock, silence otherwise
  1070. if (pData->engine->isOffline())
  1071. {
  1072. pData->singleMutex.lock();
  1073. }
  1074. else if (! pData->singleMutex.tryLock())
  1075. {
  1076. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1077. carla_zeroFloats(outBuffer[i], frames);
  1078. return false;
  1079. }
  1080. // --------------------------------------------------------------------------------------------------------
  1081. // Set audio in buffers
  1082. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1083. fAudioBuffer.copyFrom(static_cast<int>(i), 0, inBuffer[i], static_cast<int>(frames));
  1084. // --------------------------------------------------------------------------------------------------------
  1085. // Run plugin
  1086. fInstance->processBlock(fAudioBuffer, fMidiBuffer);
  1087. // --------------------------------------------------------------------------------------------------------
  1088. // Set audio out buffers
  1089. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1090. carla_copyFloats(outBuffer[i], fAudioBuffer.getReadPointer(static_cast<int>(i)), frames);
  1091. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1092. // --------------------------------------------------------------------------------------------------------
  1093. // Post-processing (dry/wet, volume and balance)
  1094. {
  1095. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1096. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1097. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1098. const bool isMono = (pData->audioIn.count == 1);
  1099. bool isPair;
  1100. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1101. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1102. {
  1103. // Dry/Wet
  1104. if (doDryWet)
  1105. {
  1106. const uint32_t c = isMono ? 0 : i;
  1107. for (uint32_t k=0; k < frames; ++k)
  1108. {
  1109. bufValue = inBuffer[c][k];
  1110. outBuffer[i][k] = (outBuffer[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1111. }
  1112. }
  1113. // Balance
  1114. if (doBalance)
  1115. {
  1116. isPair = (i % 2 == 0);
  1117. if (isPair)
  1118. {
  1119. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1120. carla_copyFloats(oldBufLeft, outBuffer[i], frames);
  1121. }
  1122. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1123. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1124. for (uint32_t k=0; k < frames; ++k)
  1125. {
  1126. if (isPair)
  1127. {
  1128. // left
  1129. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1130. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  1131. }
  1132. else
  1133. {
  1134. // right
  1135. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  1136. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  1137. }
  1138. }
  1139. }
  1140. // Volume
  1141. if (doVolume)
  1142. {
  1143. for (uint32_t k=0; k < frames; ++k)
  1144. outBuffer[i][k] *= pData->postProc.volume;
  1145. }
  1146. }
  1147. } // End of Post-processing
  1148. #endif
  1149. // --------------------------------------------------------------------------------------------------------
  1150. // Midi out
  1151. if (! fMidiBuffer.isEmpty())
  1152. {
  1153. if (pData->event.portOut != nullptr)
  1154. {
  1155. for (juce::MidiBufferIterator it = fMidiBuffer.cbegin(), end = fMidiBuffer.cend(); it != end; ++it)
  1156. {
  1157. const juce::MidiMessageMetadata metadata(*it);
  1158. CARLA_SAFE_ASSERT_BREAK(metadata.samplePosition >= 0);
  1159. CARLA_SAFE_ASSERT_BREAK(metadata.samplePosition < static_cast<int>(frames));
  1160. CARLA_SAFE_ASSERT_BREAK(metadata.numBytes > 0);
  1161. CARLA_SAFE_ASSERT_CONTINUE(metadata.numBytes <= 0xff);
  1162. if (! pData->event.portOut->writeMidiEvent(static_cast<uint32_t>(metadata.samplePosition),
  1163. static_cast<uint8_t>(metadata.numBytes),
  1164. metadata.data))
  1165. break;
  1166. }
  1167. }
  1168. fMidiBuffer.clear();
  1169. }
  1170. // --------------------------------------------------------------------------------------------------------
  1171. pData->singleMutex.unlock();
  1172. return true;
  1173. }
  1174. void bufferSizeChanged(const uint32_t newBufferSize) override
  1175. {
  1176. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1177. carla_debug("CarlaPluginJuce::bufferSizeChanged(%i)", newBufferSize);
  1178. fAudioBuffer.setSize(static_cast<int>(std::max<uint32_t>(pData->audioIn.count, pData->audioOut.count)), static_cast<int>(newBufferSize));
  1179. if (pData->active)
  1180. {
  1181. deactivate();
  1182. activate();
  1183. }
  1184. }
  1185. void sampleRateChanged(const double newSampleRate) override
  1186. {
  1187. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1188. carla_debug("CarlaPluginJuce::sampleRateChanged(%g)", newSampleRate);
  1189. if (pData->active)
  1190. {
  1191. deactivate();
  1192. activate();
  1193. }
  1194. }
  1195. // -------------------------------------------------------------------
  1196. // Misc
  1197. void idle() override
  1198. {
  1199. if (fNeedsUpdate)
  1200. {
  1201. fNeedsUpdate = false;
  1202. pData->engine->callback(true, true, ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0, 0.0f, nullptr);
  1203. }
  1204. CarlaPlugin::idle();
  1205. }
  1206. // -------------------------------------------------------------------
  1207. // Plugin buffers
  1208. // nothing
  1209. // -------------------------------------------------------------------
  1210. // Post-poned UI Stuff
  1211. // nothing
  1212. // -------------------------------------------------------------------
  1213. void* getNativeHandle() const noexcept override
  1214. {
  1215. return (fInstance != nullptr) ? fInstance->getPlatformSpecificData() : nullptr;
  1216. }
  1217. // -------------------------------------------------------------------
  1218. protected:
  1219. void audioProcessorParameterChanged(juce::AudioProcessor*, int index, float value) override
  1220. {
  1221. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1222. const uint32_t uindex(static_cast<uint32_t>(index));
  1223. const float fixedValue(pData->param.getFixedValue(uindex, value));
  1224. CarlaPlugin::setParameterValue(static_cast<uint32_t>(index), fixedValue, false, true, true);
  1225. }
  1226. void audioProcessorChanged(juce::AudioProcessor*, const ChangeDetails& details) override
  1227. {
  1228. if (details.parameterInfoChanged || details.programChanged)
  1229. fNeedsUpdate = true;
  1230. }
  1231. void audioProcessorParameterChangeGestureBegin(juce::AudioProcessor*, int index) override
  1232. {
  1233. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1234. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), true);
  1235. }
  1236. void audioProcessorParameterChangeGestureEnd(juce::AudioProcessor*, int index) override
  1237. {
  1238. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1239. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), false);
  1240. }
  1241. bool getCurrentPosition(CurrentPositionInfo& result) override
  1242. {
  1243. carla_copyStruct(result, fPosInfo);
  1244. return true;
  1245. }
  1246. // -------------------------------------------------------------------
  1247. public:
  1248. bool init(const CarlaPluginPtr plugin,
  1249. const char* const filename, const char* const name, const char* const label,
  1250. const int64_t uniqueId, const uint options, const char* const format)
  1251. {
  1252. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1253. // ---------------------------------------------------------------
  1254. // first checks
  1255. if (pData->client != nullptr)
  1256. {
  1257. pData->engine->setLastError("Plugin client is already registered");
  1258. return false;
  1259. }
  1260. if (format == nullptr || format[0] == '\0')
  1261. {
  1262. pData->engine->setLastError("null format");
  1263. return false;
  1264. }
  1265. // AU requires label
  1266. if (std::strcmp(format, "AU") == 0)
  1267. {
  1268. if (label == nullptr || label[0] == '\0')
  1269. {
  1270. pData->engine->setLastError("null label");
  1271. return false;
  1272. }
  1273. }
  1274. juce::String fileOrIdentifier;
  1275. if (std::strcmp(format, "AU") == 0)
  1276. {
  1277. fileOrIdentifier = label;
  1278. }
  1279. else
  1280. {
  1281. // VST2 and VST3 require filename
  1282. if (filename == nullptr || filename[0] == '\0')
  1283. {
  1284. pData->engine->setLastError("null filename");
  1285. return false;
  1286. }
  1287. juce::String jfilename(filename);
  1288. #ifdef CARLA_OS_WIN
  1289. // Fix for wine usage
  1290. if (juce::File("Z:\\usr\\").isDirectory() && filename[0] == '/')
  1291. {
  1292. jfilename.replace("/", "\\");
  1293. jfilename = "Z:" + jfilename;
  1294. }
  1295. #endif
  1296. fileOrIdentifier = jfilename;
  1297. if (label != nullptr && label[0] != '\0')
  1298. fDesc.name = label;
  1299. }
  1300. /**/ if (std::strcmp(format, "AU") == 0)
  1301. {
  1302. #if JUCE_PLUGINHOST_AU
  1303. fFormatManager.addFormat(new juce::AudioUnitPluginFormat());
  1304. #endif
  1305. }
  1306. else if (std::strcmp(format, "VST2") == 0)
  1307. {
  1308. #if JUCE_PLUGINHOST_VST
  1309. fFormatManager.addFormat(new juce::VSTPluginFormat());
  1310. #endif
  1311. }
  1312. else if (std::strcmp(format, "VST3") == 0)
  1313. {
  1314. #if JUCE_PLUGINHOST_VST3
  1315. fFormatManager.addFormat(new juce::VST3PluginFormat());
  1316. #endif
  1317. }
  1318. else
  1319. {
  1320. fFormatManager.addDefaultFormats();
  1321. }
  1322. {
  1323. juce::OwnedArray<juce::PluginDescription> pluginDescriptions;
  1324. juce::KnownPluginList plist;
  1325. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1326. {
  1327. const ScopedAbortCatcher sac;
  1328. for (int i = 0; i < fFormatManager.getNumFormats(); ++i)
  1329. {
  1330. juce::AudioPluginFormat* const apformat = fFormatManager.getFormat(i);
  1331. CARLA_SAFE_ASSERT_CONTINUE(apformat != nullptr);
  1332. carla_debug("Trying to load '%s' plugin with format '%s'", fileOrIdentifier.toRawUTF8(), apformat->getName().toRawUTF8());
  1333. try {
  1334. plist.scanAndAddFile(fileOrIdentifier, true, pluginDescriptions, *apformat);
  1335. } CARLA_SAFE_EXCEPTION_CONTINUE("scanAndAddFile")
  1336. if (sac.wasTriggered())
  1337. {
  1338. carla_stderr("WARNING: Caught exception while scanning file, will not load this plugin");
  1339. pluginDescriptions.clearQuick(false);
  1340. break;
  1341. }
  1342. }
  1343. }
  1344. #endif
  1345. if (pluginDescriptions.size() == 0)
  1346. {
  1347. pData->engine->setLastError("Failed to get plugin description");
  1348. return false;
  1349. }
  1350. fDesc = *pluginDescriptions[0];
  1351. }
  1352. if (uniqueId != 0)
  1353. fDesc.uniqueId = static_cast<int>(uniqueId);
  1354. juce::String error;
  1355. {
  1356. const ScopedAbortCatcher sac;
  1357. try {
  1358. fInstance = fFormatManager.createPluginInstance(fDesc,
  1359. pData->engine->getSampleRate(),
  1360. static_cast<int>(pData->engine->getBufferSize()),
  1361. error);
  1362. } CARLA_SAFE_EXCEPTION("createPluginInstance")
  1363. if (sac.wasTriggered())
  1364. {
  1365. fInstance = nullptr;
  1366. carla_stderr("WARNING: Caught exception while instantiating, will not load this plugin");
  1367. }
  1368. }
  1369. if (fInstance == nullptr)
  1370. {
  1371. pData->engine->setLastError(error.toRawUTF8());
  1372. return false;
  1373. }
  1374. fInstance->fillInPluginDescription(fDesc);
  1375. fInstance->setPlayHead(this);
  1376. fInstance->addListener(this);
  1377. fFormatName = format;
  1378. // ---------------------------------------------------------------
  1379. // get info
  1380. if (name != nullptr && name[0] != '\0')
  1381. pData->name = pData->engine->getUniquePluginName(name);
  1382. else
  1383. pData->name = pData->engine->getUniquePluginName(fInstance->getName().toRawUTF8());
  1384. if (filename != nullptr && filename[0] != '\0')
  1385. pData->filename = carla_strdup(filename);
  1386. // ---------------------------------------------------------------
  1387. // register client
  1388. pData->client = pData->engine->addClient(plugin);
  1389. if (pData->client == nullptr || ! pData->client->isOk())
  1390. {
  1391. pData->engine->setLastError("Failed to register plugin client");
  1392. return false;
  1393. }
  1394. // ---------------------------------------------------------------
  1395. // set options
  1396. pData->options = 0x0;
  1397. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1398. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  1399. if (fInstance->acceptsMidi())
  1400. {
  1401. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  1402. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1403. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  1404. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1405. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  1406. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1407. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  1408. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1409. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  1410. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1411. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  1412. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  1413. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1414. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  1415. }
  1416. if (fInstance->getNumPrograms() > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  1417. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  1418. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1419. return true;
  1420. }
  1421. private:
  1422. juce::PluginDescription fDesc;
  1423. juce::AudioPluginFormatManager fFormatManager;
  1424. std::unique_ptr<juce::AudioPluginInstance> fInstance;
  1425. juce::AudioSampleBuffer fAudioBuffer;
  1426. juce::MidiBuffer fMidiBuffer;
  1427. CurrentPositionInfo fPosInfo;
  1428. juce::MemoryBlock fChunk;
  1429. juce::String fFormatName;
  1430. CarlaScopedPointer<JucePluginWindow> fWindow;
  1431. bool fNeedsUpdate;
  1432. bool isJuceSaveFormat(const void* const data, const std::size_t dataSize)
  1433. {
  1434. if (fFormatName != "VST2")
  1435. return true;
  1436. if (dataSize < 160)
  1437. return false;
  1438. const int32_t* const set = (const int32_t*)data;
  1439. // chunkMagic
  1440. if (! compareMagic(set[0], "CcnK"))
  1441. return false;
  1442. // version
  1443. if (fxbSwap(set[3]) > 1)
  1444. return false;
  1445. // fxMagic, data contents depend on this value
  1446. if (compareMagic(set[2], "FBCh") || compareMagic(set[2], "FJuc"))
  1447. {
  1448. const int32_t chunkSize = fxbSwap(set[39]);
  1449. return static_cast<std::size_t>(chunkSize + 160) == dataSize;
  1450. }
  1451. if (compareMagic(set[2], "FxBk"))
  1452. {
  1453. const int32_t numPrograms = fxbSwap(set[6]);
  1454. return numPrograms >= 1;
  1455. }
  1456. return false;
  1457. }
  1458. static bool compareMagic(int32_t magic, const char* name) noexcept
  1459. {
  1460. return magic == (int32_t)juce::ByteOrder::littleEndianInt (name)
  1461. || magic == (int32_t)juce::ByteOrder::bigEndianInt (name);
  1462. }
  1463. static int32_t fxbSwap(const int32_t x) noexcept
  1464. {
  1465. return (int32_t)juce::ByteOrder::swapIfLittleEndian ((uint32_t) x);
  1466. }
  1467. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJuce)
  1468. };
  1469. CARLA_BACKEND_END_NAMESPACE
  1470. #endif // USING_JUCE
  1471. // -------------------------------------------------------------------------------------------------------------------
  1472. CARLA_BACKEND_START_NAMESPACE
  1473. CarlaPluginPtr CarlaPlugin::newJuce(const Initializer& init, const char* const format)
  1474. {
  1475. carla_debug("CarlaPlugin::newJuce({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s)",
  1476. init.engine, init.filename, init.name, init.label, init.uniqueId, format);
  1477. #ifdef USING_JUCE
  1478. std::shared_ptr<CarlaPluginJuce> plugin(new CarlaPluginJuce(init.engine, init.id));
  1479. if (! plugin->init(plugin, init.filename, init.name, init.label, init.uniqueId, init.options, format))
  1480. return nullptr;
  1481. return plugin;
  1482. #else
  1483. init.engine->setLastError("Juce-based plugin not available");
  1484. return nullptr;
  1485. // unused
  1486. (void)format;
  1487. #endif
  1488. }
  1489. CARLA_BACKEND_END_NAMESPACE
  1490. // -------------------------------------------------------------------------------------------------------------------