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.

1921 lines
68KB

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