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.

1881 lines
67KB

  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. /* TODO update to juce7 APIs
  392. v3_plugin_view** const vst3view = fDesc.pluginFormatName == "VST3"
  393. ? (v3_plugin_view**)editor->getPlatformSpecificData()
  394. : nullptr;
  395. */
  396. v3_plugin_view** const vst3view = nullptr;
  397. fWindow = new JucePluginWindow(opts.frontendWinId, opts.pluginsAreStandalone,
  398. vst2effect, vst3view);
  399. fWindow->setName(uiName);
  400. }
  401. fWindow->show(editor);
  402. fWindow->toFront(true);
  403. }
  404. }
  405. else
  406. {
  407. if (juce::AudioProcessorEditor* const editor = fInstance->getActiveEditor())
  408. delete editor;
  409. fWindow = nullptr;
  410. }
  411. }
  412. void uiIdle() override
  413. {
  414. if (fWindow != nullptr)
  415. {
  416. if (fWindow->wasClosedByUser())
  417. {
  418. showCustomUI(false);
  419. pData->engine->callback(true, true,
  420. ENGINE_CALLBACK_UI_STATE_CHANGED,
  421. pData->id,
  422. 0,
  423. 0, 0, 0.0f, nullptr);
  424. }
  425. }
  426. CarlaPlugin::uiIdle();
  427. }
  428. // -------------------------------------------------------------------
  429. // Plugin state
  430. void reload() override
  431. {
  432. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  433. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  434. carla_debug("CarlaPluginJuce::reload() - start");
  435. const EngineProcessMode processMode(pData->engine->getProccessMode());
  436. // Safely disable plugin for reload
  437. const ScopedDisabler sd(this);
  438. if (pData->active)
  439. deactivate();
  440. clearBuffers();
  441. uint32_t aIns, aOuts, mIns, mOuts, params;
  442. mIns = mOuts = 0;
  443. bool needsCtrlIn, needsCtrlOut;
  444. needsCtrlIn = needsCtrlOut = false;
  445. const bool isAU = fDesc.pluginFormatName == "AU" || fDesc.pluginFormatName == "AudioUnit";
  446. const bool isVST2 = fDesc.pluginFormatName == "VST" || fDesc.pluginFormatName == "VST2";
  447. const bool isVST3 = fDesc.pluginFormatName == "VST3";
  448. findMaxTotalChannels(fInstance.get(), isAU, aIns, aOuts);
  449. fInstance->refreshParameterList();
  450. const juce::Array<juce::AudioProcessorParameter*>& parameters(fInstance->getParameters());
  451. params = static_cast<uint32_t>(std::max(parameters.size(), 0));
  452. if (fInstance->acceptsMidi())
  453. {
  454. mIns = 1;
  455. needsCtrlIn = true;
  456. }
  457. if (fInstance->producesMidi())
  458. {
  459. mOuts = 1;
  460. needsCtrlOut = true;
  461. }
  462. if (aIns > 0)
  463. {
  464. pData->audioIn.createNew(aIns);
  465. }
  466. if (aOuts > 0)
  467. {
  468. pData->audioOut.createNew(aOuts);
  469. needsCtrlIn = true;
  470. }
  471. if (params > 0)
  472. {
  473. pData->param.createNew(params, false);
  474. needsCtrlIn = true;
  475. }
  476. const uint portNameSize(pData->engine->getMaxPortNameSize());
  477. CarlaString portName;
  478. // Audio Ins
  479. for (uint32_t j=0; j < aIns; ++j)
  480. {
  481. portName.clear();
  482. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  483. {
  484. portName = pData->name;
  485. portName += ":";
  486. }
  487. if (aIns > 1)
  488. {
  489. portName += "input_";
  490. portName += CarlaString(j+1);
  491. }
  492. else
  493. portName += "input";
  494. portName.truncate(portNameSize);
  495. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  496. pData->audioIn.ports[j].rindex = j;
  497. }
  498. // Audio Outs
  499. for (uint32_t j=0; j < aOuts; ++j)
  500. {
  501. portName.clear();
  502. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  503. {
  504. portName = pData->name;
  505. portName += ":";
  506. }
  507. if (aOuts > 1)
  508. {
  509. portName += "output_";
  510. portName += CarlaString(j+1);
  511. }
  512. else
  513. portName += "output";
  514. portName.truncate(portNameSize);
  515. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  516. pData->audioOut.ports[j].rindex = j;
  517. }
  518. for (uint32_t j=0; j < params; ++j)
  519. {
  520. const int32_t ij = static_cast<int>(j);
  521. juce::AudioProcessorParameter* const parameter = parameters[ij];
  522. CARLA_SAFE_ASSERT_CONTINUE(parameter != nullptr);
  523. pData->param.data[j].type = PARAMETER_INPUT;
  524. pData->param.data[j].index = static_cast<int32_t>(j);
  525. pData->param.data[j].rindex = static_cast<int32_t>(j);
  526. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  527. pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  528. if (parameter->isAutomatable())
  529. pData->param.data[j].hints |= PARAMETER_IS_AUTOMATABLE;
  530. const float min = 0.0f;
  531. const float max = 1.0f;
  532. float def, step, stepSmall, stepLarge;
  533. bool hasDetails = false;
  534. if (isVST2)
  535. {
  536. AEffect* const effect = (AEffect*)fInstance->getPlatformSpecificData();
  537. VstParameterProperties prop;
  538. carla_zeroStruct(prop);
  539. if (effect != nullptr && effect->dispatcher(effect, effGetParameterProperties, ij, 0, &prop, 0.0f) == 1)
  540. {
  541. hasDetails = true;
  542. /**/ if (prop.flags & kVstParameterIsSwitch)
  543. {
  544. step = max - min;
  545. stepSmall = step;
  546. stepLarge = step;
  547. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  548. }
  549. else if (prop.flags & kVstParameterUsesIntStep)
  550. {
  551. step = static_cast<float>(prop.stepInteger);
  552. stepSmall = static_cast<float>(prop.stepInteger)/10.0f;
  553. stepLarge = static_cast<float>(prop.largeStepInteger);
  554. }
  555. else if (prop.flags & kVstParameterUsesFloatStep)
  556. {
  557. step = prop.stepFloat;
  558. stepSmall = prop.smallStepFloat;
  559. stepLarge = prop.largeStepFloat;
  560. }
  561. else
  562. {
  563. const float range = max - min;
  564. step = range/100.0f;
  565. stepSmall = range/1000.0f;
  566. stepLarge = range/10.0f;
  567. }
  568. if ((prop.flags & (kVstParameterIsSwitch|kVstParameterUsesIntStep)) == 0x0)
  569. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  570. if (prop.flags & kVstParameterCanRamp)
  571. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  572. }
  573. }
  574. else if (isVST3)
  575. {
  576. v3_component** const component = (v3_component**)fInstance->getPlatformSpecificData();
  577. v3_edit_controller** controller = nullptr;
  578. v3_cpp_obj_query_interface(component, v3_edit_controller_iid, &controller);
  579. if (controller != nullptr)
  580. {
  581. v3_param_info info;
  582. if (v3_cpp_obj(controller)->get_parameter_info(controller, static_cast<int32_t>(j), &info) == V3_OK)
  583. {
  584. hasDetails = true;
  585. if (info.step_count == 1)
  586. {
  587. step = stepSmall = stepLarge = 1;
  588. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  589. }
  590. else if (info.step_count != 0)
  591. {
  592. step = 1.0f / static_cast<float>(info.step_count);
  593. stepSmall = step/10.0f;
  594. stepLarge = std::min(1.0f, step*10.0f);
  595. }
  596. else
  597. {
  598. const float range = max - min;
  599. step = range/100.0f;
  600. stepSmall = range/1000.0f;
  601. stepLarge = range/10.0f;
  602. }
  603. if (info.flags & V3_PARAM_READ_ONLY)
  604. pData->param.data[j].type = PARAMETER_OUTPUT;
  605. // TODO V3_PARAM_IS_LIST
  606. if (info.flags & (V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE))
  607. pData->param.data[j].hints &= ~PARAMETER_IS_ENABLED;
  608. if ((info.flags & (V3_PARAM_IS_LIST|V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE)) == 0x0)
  609. if (info.flags & V3_PARAM_CAN_AUTOMATE)
  610. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  611. }
  612. v3_cpp_obj_unref(controller);
  613. }
  614. }
  615. if (! hasDetails)
  616. {
  617. if (parameter->isBoolean())
  618. {
  619. step = max - min;
  620. stepSmall = step;
  621. stepLarge = step;
  622. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  623. }
  624. else
  625. {
  626. const float range = max - min;
  627. step = range/100.0f;
  628. stepSmall = range/1000.0f;
  629. stepLarge = range/10.0f;
  630. if (! parameter->isMetaParameter())
  631. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  632. }
  633. }
  634. def = parameter->getDefaultValue();
  635. if (def < min)
  636. def = min;
  637. else if (def > max)
  638. def = max;
  639. pData->param.ranges[j].min = min;
  640. pData->param.ranges[j].max = max;
  641. pData->param.ranges[j].def = def;
  642. pData->param.ranges[j].step = step;
  643. pData->param.ranges[j].stepSmall = stepSmall;
  644. pData->param.ranges[j].stepLarge = stepLarge;
  645. }
  646. if (needsCtrlIn)
  647. {
  648. portName.clear();
  649. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  650. {
  651. portName = pData->name;
  652. portName += ":";
  653. }
  654. portName += "events-in";
  655. portName.truncate(portNameSize);
  656. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  657. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  658. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  659. #endif
  660. }
  661. if (needsCtrlOut)
  662. {
  663. portName.clear();
  664. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  665. {
  666. portName = pData->name;
  667. portName += ":";
  668. }
  669. portName += "events-out";
  670. portName.truncate(portNameSize);
  671. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  672. }
  673. // plugin hints
  674. pData->hints = 0x0;
  675. pData->hints |= PLUGIN_NEEDS_FIXED_BUFFERS;
  676. if (fDesc.isInstrument)
  677. pData->hints |= PLUGIN_IS_SYNTH;
  678. if (fInstance->hasEditor())
  679. {
  680. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  681. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  682. }
  683. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  684. pData->hints |= PLUGIN_CAN_DRYWET;
  685. if (aOuts > 0)
  686. pData->hints |= PLUGIN_CAN_VOLUME;
  687. if (aOuts >= 2 && aOuts % 2 == 0)
  688. pData->hints |= PLUGIN_CAN_BALANCE;
  689. // extra plugin hints
  690. pData->extraHints = 0x0;
  691. if (mIns > 0)
  692. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  693. if (mOuts > 0)
  694. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  695. fInstance->setRateAndBufferSizeDetails(pData->engine->getSampleRate(),
  696. static_cast<int>(pData->engine->getBufferSize()));
  697. bufferSizeChanged(pData->engine->getBufferSize());
  698. reloadPrograms(true);
  699. if (pData->active)
  700. activate();
  701. carla_debug("CarlaPluginJuce::reload() - end");
  702. }
  703. void reloadPrograms(const bool doInit) override
  704. {
  705. carla_debug("CarlaPluginJuce::reloadPrograms(%s)", bool2str(doInit));
  706. const uint32_t oldCount = pData->prog.count;
  707. const int32_t current = pData->prog.current;
  708. // Delete old programs
  709. pData->prog.clear();
  710. // Query new programs
  711. const uint32_t newCount = (fInstance->getNumPrograms() > 0)
  712. ? static_cast<uint32_t>(fInstance->getNumPrograms())
  713. : 0;
  714. if (newCount > 0)
  715. {
  716. pData->prog.createNew(newCount);
  717. // Update names
  718. for (uint32_t i=0; i < newCount; ++i)
  719. pData->prog.names[i] = carla_strdup(fInstance->getProgramName(static_cast<int>(i)).toRawUTF8());
  720. }
  721. if (doInit)
  722. {
  723. if (newCount > 0)
  724. setProgram(0, false, false, false, true);
  725. }
  726. else
  727. {
  728. // Check if current program is invalid
  729. bool programChanged = false;
  730. if (newCount == oldCount+1)
  731. {
  732. // one program added, probably created by user
  733. pData->prog.current = static_cast<int32_t>(oldCount);
  734. programChanged = true;
  735. }
  736. else if (current < 0 && newCount > 0)
  737. {
  738. // programs exist now, but not before
  739. pData->prog.current = 0;
  740. programChanged = true;
  741. }
  742. else if (current >= 0 && newCount == 0)
  743. {
  744. // programs existed before, but not anymore
  745. pData->prog.current = -1;
  746. programChanged = true;
  747. }
  748. else if (current >= static_cast<int32_t>(newCount))
  749. {
  750. // current program > count
  751. pData->prog.current = 0;
  752. programChanged = true;
  753. }
  754. else
  755. {
  756. // no change
  757. pData->prog.current = current;
  758. }
  759. if (programChanged)
  760. {
  761. setProgram(pData->prog.current, true, true, true, false);
  762. }
  763. else
  764. {
  765. // Program was changed during update, re-set it
  766. if (pData->prog.current >= 0)
  767. fInstance->setCurrentProgram(pData->prog.current);
  768. }
  769. pData->engine->callback(true, true, ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0, 0.0f, nullptr);
  770. }
  771. }
  772. // -------------------------------------------------------------------
  773. // Plugin processing
  774. void activate() noexcept override
  775. {
  776. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  777. try {
  778. fInstance->prepareToPlay(pData->engine->getSampleRate(), static_cast<int>(pData->engine->getBufferSize()));
  779. } catch(...) {}
  780. }
  781. void deactivate() noexcept override
  782. {
  783. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  784. try {
  785. fInstance->releaseResources();
  786. } catch(...) {}
  787. }
  788. void process(const float* const* const audioIn,
  789. float** const audioOut,
  790. const float* const* const cvIn,
  791. float**,
  792. const uint32_t frames) override
  793. {
  794. // --------------------------------------------------------------------------------------------------------
  795. // Check if active
  796. if (! pData->active)
  797. {
  798. // disable any output sound
  799. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  800. carla_zeroFloats(audioOut[i], frames);
  801. return;
  802. }
  803. // --------------------------------------------------------------------------------------------------------
  804. // Check if needs reset
  805. if (pData->needsReset)
  806. {
  807. fInstance->reset();
  808. pData->needsReset = false;
  809. }
  810. // --------------------------------------------------------------------------------------------------------
  811. // Event Input
  812. fMidiBuffer.clear();
  813. if (pData->event.portIn != nullptr)
  814. {
  815. // ----------------------------------------------------------------------------------------------------
  816. // MIDI Input (External)
  817. if (pData->extNotes.mutex.tryLock())
  818. {
  819. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  820. {
  821. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  822. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  823. uint8_t midiEvent[3];
  824. midiEvent[0] = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  825. midiEvent[1] = note.note;
  826. midiEvent[2] = note.velo;
  827. fMidiBuffer.addEvent(midiEvent, 3, 0);
  828. }
  829. pData->extNotes.data.clear();
  830. pData->extNotes.mutex.unlock();
  831. } // End of MIDI Input (External)
  832. // ----------------------------------------------------------------------------------------------------
  833. // Event Input (System)
  834. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  835. bool allNotesOffSent = false;
  836. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  837. pData->event.cvSourcePorts->initPortBuffers(cvIn, frames, false, pData->event.portIn);
  838. #endif
  839. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  840. {
  841. EngineEvent& event(pData->event.portIn->getEvent(i));
  842. if (event.time >= frames)
  843. continue;
  844. switch (event.type)
  845. {
  846. case kEngineEventTypeNull:
  847. break;
  848. case kEngineEventTypeControl: {
  849. EngineControlEvent& ctrlEvent(event.ctrl);
  850. switch (ctrlEvent.type)
  851. {
  852. case kEngineControlEventTypeNull:
  853. break;
  854. case kEngineControlEventTypeParameter: {
  855. float value;
  856. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  857. // non-midi
  858. if (event.channel == kEngineEventNonMidiChannel)
  859. {
  860. const uint32_t k = ctrlEvent.param;
  861. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  862. ctrlEvent.handled = true;
  863. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  864. setParameterValueRT(k, value, event.time, true);
  865. continue;
  866. }
  867. // Control backend stuff
  868. if (event.channel == pData->ctrlChannel)
  869. {
  870. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  871. {
  872. ctrlEvent.handled = true;
  873. value = ctrlEvent.normalizedValue;
  874. setDryWetRT(value, true);
  875. }
  876. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  877. {
  878. ctrlEvent.handled = true;
  879. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  880. setVolumeRT(value, true);
  881. }
  882. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  883. {
  884. float left, right;
  885. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  886. if (value < 0.0f)
  887. {
  888. left = -1.0f;
  889. right = (value*2.0f)+1.0f;
  890. }
  891. else if (value > 0.0f)
  892. {
  893. left = (value*2.0f)-1.0f;
  894. right = 1.0f;
  895. }
  896. else
  897. {
  898. left = -1.0f;
  899. right = 1.0f;
  900. }
  901. ctrlEvent.handled = true;
  902. setBalanceLeftRT(left, true);
  903. setBalanceRightRT(right, true);
  904. }
  905. }
  906. #endif
  907. // Control plugin parameters
  908. uint32_t k;
  909. for (k=0; k < pData->param.count; ++k)
  910. {
  911. if (pData->param.data[k].midiChannel != event.channel)
  912. continue;
  913. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  914. continue;
  915. if (pData->param.data[k].type != PARAMETER_INPUT)
  916. continue;
  917. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  918. continue;
  919. ctrlEvent.handled = true;
  920. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  921. setParameterValueRT(k, value, event.time, true);
  922. }
  923. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  924. {
  925. uint8_t midiData[3];
  926. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  927. midiData[1] = uint8_t(ctrlEvent.param);
  928. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  929. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  930. }
  931. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  932. if (! ctrlEvent.handled)
  933. checkForMidiLearn(event);
  934. #endif
  935. break;
  936. } // case kEngineControlEventTypeParameter
  937. case kEngineControlEventTypeMidiBank:
  938. if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  939. {
  940. uint8_t midiData[3];
  941. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  942. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  943. midiData[2] = 0;
  944. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  945. midiData[1] = MIDI_CONTROL_BANK_SELECT__LSB;
  946. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  947. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  948. }
  949. break;
  950. case kEngineControlEventTypeMidiProgram:
  951. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  952. {
  953. if (ctrlEvent.param < pData->prog.count)
  954. {
  955. setProgramRT(ctrlEvent.param, true);
  956. }
  957. }
  958. else if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  959. {
  960. uint8_t midiData[2];
  961. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  962. midiData[1] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  963. fMidiBuffer.addEvent(midiData, 2, static_cast<int>(event.time));
  964. }
  965. break;
  966. case kEngineControlEventTypeAllSoundOff:
  967. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  968. {
  969. uint8_t midiData[3];
  970. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  971. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  972. midiData[2] = 0;
  973. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  974. }
  975. break;
  976. case kEngineControlEventTypeAllNotesOff:
  977. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  978. {
  979. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  980. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  981. {
  982. allNotesOffSent = true;
  983. postponeRtAllNotesOff();
  984. }
  985. #endif
  986. uint8_t midiData[3];
  987. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  988. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  989. midiData[2] = 0;
  990. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  991. }
  992. break;
  993. } // switch (ctrlEvent.type)
  994. break;
  995. } // case kEngineEventTypeControl
  996. case kEngineEventTypeMidi: {
  997. const EngineMidiEvent& midiEvent(event.midi);
  998. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  999. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  1000. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1001. continue;
  1002. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1003. continue;
  1004. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1005. continue;
  1006. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1007. continue;
  1008. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1009. continue;
  1010. // Fix bad note-off
  1011. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  1012. status = MIDI_STATUS_NOTE_OFF;
  1013. // put back channel in data
  1014. uint8_t midiData2[midiEvent.size];
  1015. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  1016. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  1017. fMidiBuffer.addEvent(midiData2, midiEvent.size, static_cast<int>(event.time));
  1018. if (status == MIDI_STATUS_NOTE_ON)
  1019. {
  1020. pData->postponeNoteOnRtEvent(true, event.channel, midiData[1], midiData[2]);
  1021. }
  1022. else if (status == MIDI_STATUS_NOTE_OFF)
  1023. {
  1024. pData->postponeNoteOffRtEvent(true, event.channel, midiData[1]);
  1025. }
  1026. } break;
  1027. } // switch (event.type)
  1028. }
  1029. pData->postRtEvents.trySplice();
  1030. } // End of Event Input
  1031. // --------------------------------------------------------------------------------------------------------
  1032. // Set TimeInfo
  1033. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  1034. fPosInfo.isPlaying = timeInfo.playing;
  1035. if (timeInfo.bbt.valid)
  1036. {
  1037. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  1038. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  1039. const double ppqBar = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  1040. const double ppqBeat = static_cast<double>(timeInfo.bbt.beat - 1);
  1041. const double ppqTick = timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat;
  1042. fPosInfo.bpm = timeInfo.bbt.beatsPerMinute;
  1043. fPosInfo.timeSigNumerator = static_cast<int>(timeInfo.bbt.beatsPerBar);
  1044. fPosInfo.timeSigDenominator = static_cast<int>(timeInfo.bbt.beatType);
  1045. fPosInfo.timeInSamples = static_cast<int64_t>(timeInfo.frame);
  1046. fPosInfo.timeInSeconds = static_cast<double>(fPosInfo.timeInSamples)/pData->engine->getSampleRate();
  1047. fPosInfo.ppqPosition = ppqBar + ppqBeat + ppqTick;
  1048. fPosInfo.ppqPositionOfLastBarStart = ppqBar;
  1049. }
  1050. // --------------------------------------------------------------------------------------------------------
  1051. // Process
  1052. processSingle(audioIn, audioOut, frames);
  1053. // --------------------------------------------------------------------------------------------------------
  1054. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1055. return;
  1056. // unused
  1057. (void)cvIn;
  1058. #endif
  1059. }
  1060. bool processSingle(const float* const* const inBuffer, float** const outBuffer, const uint32_t frames)
  1061. {
  1062. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1063. if (pData->audioIn.count > 0)
  1064. {
  1065. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  1066. }
  1067. if (pData->audioOut.count > 0)
  1068. {
  1069. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  1070. }
  1071. // --------------------------------------------------------------------------------------------------------
  1072. // Try lock, silence otherwise
  1073. if (pData->engine->isOffline())
  1074. {
  1075. pData->singleMutex.lock();
  1076. }
  1077. else if (! pData->singleMutex.tryLock())
  1078. {
  1079. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1080. carla_zeroFloats(outBuffer[i], frames);
  1081. return false;
  1082. }
  1083. // --------------------------------------------------------------------------------------------------------
  1084. // Set audio in buffers
  1085. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1086. fAudioBuffer.copyFrom(static_cast<int>(i), 0, inBuffer[i], static_cast<int>(frames));
  1087. // --------------------------------------------------------------------------------------------------------
  1088. // Run plugin
  1089. fInstance->processBlock(fAudioBuffer, fMidiBuffer);
  1090. // --------------------------------------------------------------------------------------------------------
  1091. // Set audio out buffers
  1092. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1093. carla_copyFloats(outBuffer[i], fAudioBuffer.getReadPointer(static_cast<int>(i)), frames);
  1094. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1095. // --------------------------------------------------------------------------------------------------------
  1096. // Post-processing (dry/wet, volume and balance)
  1097. {
  1098. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1099. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1100. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1101. const bool isMono = (pData->audioIn.count == 1);
  1102. bool isPair;
  1103. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1104. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1105. {
  1106. // Dry/Wet
  1107. if (doDryWet)
  1108. {
  1109. const uint32_t c = isMono ? 0 : i;
  1110. for (uint32_t k=0; k < frames; ++k)
  1111. {
  1112. bufValue = inBuffer[c][k];
  1113. outBuffer[i][k] = (outBuffer[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1114. }
  1115. }
  1116. // Balance
  1117. if (doBalance)
  1118. {
  1119. isPair = (i % 2 == 0);
  1120. if (isPair)
  1121. {
  1122. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1123. carla_copyFloats(oldBufLeft, outBuffer[i], frames);
  1124. }
  1125. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1126. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1127. for (uint32_t k=0; k < frames; ++k)
  1128. {
  1129. if (isPair)
  1130. {
  1131. // left
  1132. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1133. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  1134. }
  1135. else
  1136. {
  1137. // right
  1138. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  1139. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  1140. }
  1141. }
  1142. }
  1143. // Volume
  1144. if (doVolume)
  1145. {
  1146. for (uint32_t k=0; k < frames; ++k)
  1147. outBuffer[i][k] *= pData->postProc.volume;
  1148. }
  1149. }
  1150. } // End of Post-processing
  1151. #endif
  1152. // --------------------------------------------------------------------------------------------------------
  1153. // Midi out
  1154. if (! fMidiBuffer.isEmpty())
  1155. {
  1156. if (pData->event.portOut != nullptr)
  1157. {
  1158. for (juce::MidiBufferIterator it = fMidiBuffer.cbegin(), end = fMidiBuffer.cend(); it != end; ++it)
  1159. {
  1160. const juce::MidiMessageMetadata metadata(*it);
  1161. CARLA_SAFE_ASSERT_BREAK(metadata.samplePosition >= 0);
  1162. CARLA_SAFE_ASSERT_BREAK(metadata.samplePosition < static_cast<int>(frames));
  1163. CARLA_SAFE_ASSERT_BREAK(metadata.numBytes > 0);
  1164. CARLA_SAFE_ASSERT_CONTINUE(metadata.numBytes <= 0xff);
  1165. if (! pData->event.portOut->writeMidiEvent(static_cast<uint32_t>(metadata.samplePosition),
  1166. static_cast<uint8_t>(metadata.numBytes),
  1167. metadata.data))
  1168. break;
  1169. }
  1170. }
  1171. fMidiBuffer.clear();
  1172. }
  1173. // --------------------------------------------------------------------------------------------------------
  1174. pData->singleMutex.unlock();
  1175. return true;
  1176. }
  1177. void bufferSizeChanged(const uint32_t newBufferSize) override
  1178. {
  1179. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1180. carla_debug("CarlaPluginJuce::bufferSizeChanged(%i)", newBufferSize);
  1181. fAudioBuffer.setSize(static_cast<int>(std::max<uint32_t>(pData->audioIn.count, pData->audioOut.count)), static_cast<int>(newBufferSize));
  1182. if (pData->active)
  1183. {
  1184. deactivate();
  1185. activate();
  1186. }
  1187. }
  1188. void sampleRateChanged(const double newSampleRate) override
  1189. {
  1190. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1191. carla_debug("CarlaPluginJuce::sampleRateChanged(%g)", newSampleRate);
  1192. if (pData->active)
  1193. {
  1194. deactivate();
  1195. activate();
  1196. }
  1197. }
  1198. // -------------------------------------------------------------------
  1199. // Misc
  1200. void idle() override
  1201. {
  1202. if (fNeedsUpdate)
  1203. {
  1204. fNeedsUpdate = false;
  1205. pData->engine->callback(true, true, ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0, 0.0f, nullptr);
  1206. }
  1207. CarlaPlugin::idle();
  1208. }
  1209. // -------------------------------------------------------------------
  1210. // Plugin buffers
  1211. // nothing
  1212. // -------------------------------------------------------------------
  1213. // Post-poned UI Stuff
  1214. // nothing
  1215. // -------------------------------------------------------------------
  1216. void* getNativeHandle() const noexcept override
  1217. {
  1218. return (fInstance != nullptr) ? fInstance->getPlatformSpecificData() : nullptr;
  1219. }
  1220. // -------------------------------------------------------------------
  1221. protected:
  1222. void audioProcessorParameterChanged(juce::AudioProcessor*, int index, float value) override
  1223. {
  1224. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1225. const uint32_t uindex(static_cast<uint32_t>(index));
  1226. const float fixedValue(pData->param.getFixedValue(uindex, value));
  1227. CarlaPlugin::setParameterValue(static_cast<uint32_t>(index), fixedValue, false, true, true);
  1228. }
  1229. void audioProcessorChanged(juce::AudioProcessor*, const ChangeDetails& details) override
  1230. {
  1231. if (details.parameterInfoChanged || details.programChanged)
  1232. fNeedsUpdate = true;
  1233. }
  1234. void audioProcessorParameterChangeGestureBegin(juce::AudioProcessor*, int index) override
  1235. {
  1236. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1237. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), true);
  1238. }
  1239. void audioProcessorParameterChangeGestureEnd(juce::AudioProcessor*, int index) override
  1240. {
  1241. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1242. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), false);
  1243. }
  1244. juce::Optional<juce::AudioPlayHead::PositionInfo> getPosition() const override
  1245. {
  1246. /* TODO update to juce7 APIs
  1247. carla_copyStruct(result, fPosInfo);
  1248. */
  1249. return {};
  1250. }
  1251. // -------------------------------------------------------------------
  1252. public:
  1253. bool init(const CarlaPluginPtr plugin,
  1254. const char* const filename, const char* const name, const char* const label,
  1255. const int64_t uniqueId, const uint options, const char* const format)
  1256. {
  1257. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1258. // ---------------------------------------------------------------
  1259. // first checks
  1260. if (pData->client != nullptr)
  1261. {
  1262. pData->engine->setLastError("Plugin client is already registered");
  1263. return false;
  1264. }
  1265. if (format == nullptr || format[0] == '\0')
  1266. {
  1267. pData->engine->setLastError("null format");
  1268. return false;
  1269. }
  1270. // AU requires label
  1271. if (std::strcmp(format, "AU") == 0)
  1272. {
  1273. if (label == nullptr || label[0] == '\0')
  1274. {
  1275. pData->engine->setLastError("null label");
  1276. return false;
  1277. }
  1278. }
  1279. juce::String fileOrIdentifier;
  1280. if (std::strcmp(format, "AU") == 0)
  1281. {
  1282. fileOrIdentifier = label;
  1283. }
  1284. else
  1285. {
  1286. // VST2 and VST3 require filename
  1287. if (filename == nullptr || filename[0] == '\0')
  1288. {
  1289. pData->engine->setLastError("null filename");
  1290. return false;
  1291. }
  1292. juce::String jfilename(filename);
  1293. #ifdef CARLA_OS_WIN
  1294. // Fix for wine usage
  1295. if (juce::File("Z:\\usr\\").isDirectory() && filename[0] == '/')
  1296. {
  1297. jfilename.replace("/", "\\");
  1298. jfilename = "Z:" + jfilename;
  1299. }
  1300. #endif
  1301. fileOrIdentifier = jfilename;
  1302. if (label != nullptr && label[0] != '\0')
  1303. fDesc.name = label;
  1304. }
  1305. /**/ if (std::strcmp(format, "AU") == 0)
  1306. {
  1307. #if JUCE_PLUGINHOST_AU
  1308. fFormatManager.addFormat(new juce::AudioUnitPluginFormat());
  1309. #endif
  1310. }
  1311. else if (std::strcmp(format, "VST2") == 0)
  1312. {
  1313. #if JUCE_PLUGINHOST_VST
  1314. fFormatManager.addFormat(new juce::VSTPluginFormat());
  1315. #endif
  1316. }
  1317. else if (std::strcmp(format, "VST3") == 0)
  1318. {
  1319. #if JUCE_PLUGINHOST_VST3
  1320. fFormatManager.addFormat(new juce::VST3PluginFormat());
  1321. #endif
  1322. }
  1323. else
  1324. {
  1325. fFormatManager.addDefaultFormats();
  1326. }
  1327. {
  1328. juce::OwnedArray<juce::PluginDescription> pluginDescriptions;
  1329. juce::KnownPluginList plist;
  1330. {
  1331. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1332. const ScopedAbortCatcher sac;
  1333. #endif
  1334. for (int i = 0; i < fFormatManager.getNumFormats(); ++i)
  1335. {
  1336. juce::AudioPluginFormat* const apformat = fFormatManager.getFormat(i);
  1337. CARLA_SAFE_ASSERT_CONTINUE(apformat != nullptr);
  1338. carla_debug("Trying to load '%s' plugin with format '%s'", fileOrIdentifier.toRawUTF8(), apformat->getName().toRawUTF8());
  1339. try {
  1340. plist.scanAndAddFile(fileOrIdentifier, true, pluginDescriptions, *apformat);
  1341. } CARLA_SAFE_EXCEPTION_CONTINUE("scanAndAddFile")
  1342. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1343. if (sac.wasTriggered())
  1344. {
  1345. carla_stderr("WARNING: Caught exception while scanning file, will not load this plugin");
  1346. pluginDescriptions.clearQuick(false);
  1347. break;
  1348. }
  1349. #endif
  1350. }
  1351. }
  1352. if (pluginDescriptions.size() == 0)
  1353. {
  1354. pData->engine->setLastError("Failed to get plugin description");
  1355. return false;
  1356. }
  1357. fDesc = *pluginDescriptions[0];
  1358. }
  1359. if (uniqueId != 0)
  1360. fDesc.uniqueId = static_cast<int>(uniqueId);
  1361. juce::String error;
  1362. {
  1363. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1364. const ScopedAbortCatcher sac;
  1365. #endif
  1366. try {
  1367. fInstance = fFormatManager.createPluginInstance(fDesc,
  1368. pData->engine->getSampleRate(),
  1369. static_cast<int>(pData->engine->getBufferSize()),
  1370. error);
  1371. } CARLA_SAFE_EXCEPTION("createPluginInstance")
  1372. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1373. if (sac.wasTriggered())
  1374. {
  1375. fInstance = nullptr;
  1376. carla_stderr("WARNING: Caught exception while instantiating, will not load this plugin");
  1377. }
  1378. #endif
  1379. }
  1380. if (fInstance == nullptr)
  1381. {
  1382. pData->engine->setLastError(error.toRawUTF8());
  1383. return false;
  1384. }
  1385. fInstance->fillInPluginDescription(fDesc);
  1386. fInstance->setPlayHead(this);
  1387. fInstance->addListener(this);
  1388. fFormatName = format;
  1389. // ---------------------------------------------------------------
  1390. // get info
  1391. if (name != nullptr && name[0] != '\0')
  1392. pData->name = pData->engine->getUniquePluginName(name);
  1393. else
  1394. pData->name = pData->engine->getUniquePluginName(fInstance->getName().toRawUTF8());
  1395. if (filename != nullptr && filename[0] != '\0')
  1396. pData->filename = carla_strdup(filename);
  1397. // ---------------------------------------------------------------
  1398. // register client
  1399. pData->client = pData->engine->addClient(plugin);
  1400. if (pData->client == nullptr || ! pData->client->isOk())
  1401. {
  1402. pData->engine->setLastError("Failed to register plugin client");
  1403. return false;
  1404. }
  1405. // ---------------------------------------------------------------
  1406. // set options
  1407. pData->options = 0x0;
  1408. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1409. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  1410. if (fInstance->acceptsMidi())
  1411. {
  1412. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  1413. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1414. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  1415. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1416. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  1417. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1418. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  1419. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1420. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  1421. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1422. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  1423. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  1424. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1425. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  1426. }
  1427. if (fInstance->getNumPrograms() > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  1428. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  1429. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1430. return true;
  1431. }
  1432. private:
  1433. juce::PluginDescription fDesc;
  1434. juce::AudioPluginFormatManager fFormatManager;
  1435. std::unique_ptr<juce::AudioPluginInstance> fInstance;
  1436. juce::AudioSampleBuffer fAudioBuffer;
  1437. juce::MidiBuffer fMidiBuffer;
  1438. CurrentPositionInfo fPosInfo;
  1439. juce::MemoryBlock fChunk;
  1440. juce::String fFormatName;
  1441. CarlaScopedPointer<JucePluginWindow> fWindow;
  1442. bool fNeedsUpdate;
  1443. bool isJuceSaveFormat(const void* const data, const std::size_t dataSize)
  1444. {
  1445. if (fFormatName != "VST2")
  1446. return true;
  1447. if (dataSize < 160)
  1448. return false;
  1449. const int32_t* const set = (const int32_t*)data;
  1450. // chunkMagic
  1451. if (! compareMagic(set[0], "CcnK"))
  1452. return false;
  1453. // version
  1454. if (fxbSwap(set[3]) > 1)
  1455. return false;
  1456. // fxMagic, data contents depend on this value
  1457. if (compareMagic(set[2], "FBCh") || compareMagic(set[2], "FJuc"))
  1458. {
  1459. const int32_t chunkSize = fxbSwap(set[39]);
  1460. return static_cast<std::size_t>(chunkSize + 160) == dataSize;
  1461. }
  1462. if (compareMagic(set[2], "FxBk"))
  1463. {
  1464. const int32_t numPrograms = fxbSwap(set[6]);
  1465. return numPrograms >= 1;
  1466. }
  1467. return false;
  1468. }
  1469. static bool compareMagic(int32_t magic, const char* name) noexcept
  1470. {
  1471. return magic == (int32_t)juce::ByteOrder::littleEndianInt (name)
  1472. || magic == (int32_t)juce::ByteOrder::bigEndianInt (name);
  1473. }
  1474. static int32_t fxbSwap(const int32_t x) noexcept
  1475. {
  1476. return (int32_t)juce::ByteOrder::swapIfLittleEndian ((uint32_t) x);
  1477. }
  1478. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJuce)
  1479. };
  1480. CARLA_BACKEND_END_NAMESPACE
  1481. #endif // USING_JUCE
  1482. // -------------------------------------------------------------------------------------------------------------------
  1483. CARLA_BACKEND_START_NAMESPACE
  1484. CarlaPluginPtr CarlaPlugin::newJuce(const Initializer& init, const char* const format)
  1485. {
  1486. carla_debug("CarlaPlugin::newJuce({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s)",
  1487. init.engine, init.filename, init.name, init.label, init.uniqueId, format);
  1488. #ifdef USING_JUCE
  1489. std::shared_ptr<CarlaPluginJuce> plugin(new CarlaPluginJuce(init.engine, init.id));
  1490. if (! plugin->init(plugin, init.filename, init.name, init.label, init.uniqueId, init.options, format))
  1491. return nullptr;
  1492. return plugin;
  1493. #else
  1494. init.engine->setLastError("Juce-based plugin not available");
  1495. return nullptr;
  1496. // unused
  1497. (void)format;
  1498. #endif
  1499. }
  1500. CARLA_BACKEND_END_NAMESPACE
  1501. // -------------------------------------------------------------------------------------------------------------------