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.

1916 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. def = parameter->getDefaultValue();
  669. if (def < min)
  670. def = min;
  671. else if (def > max)
  672. def = max;
  673. pData->param.ranges[j].min = min;
  674. pData->param.ranges[j].max = max;
  675. pData->param.ranges[j].def = def;
  676. pData->param.ranges[j].step = step;
  677. pData->param.ranges[j].stepSmall = stepSmall;
  678. pData->param.ranges[j].stepLarge = stepLarge;
  679. }
  680. if (needsCtrlIn)
  681. {
  682. portName.clear();
  683. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  684. {
  685. portName = pData->name;
  686. portName += ":";
  687. }
  688. portName += "events-in";
  689. portName.truncate(portNameSize);
  690. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  691. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  692. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  693. #endif
  694. }
  695. if (needsCtrlOut)
  696. {
  697. portName.clear();
  698. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  699. {
  700. portName = pData->name;
  701. portName += ":";
  702. }
  703. portName += "events-out";
  704. portName.truncate(portNameSize);
  705. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  706. }
  707. // plugin hints
  708. pData->hints = 0x0;
  709. pData->hints |= PLUGIN_NEEDS_FIXED_BUFFERS;
  710. if (fDesc.isInstrument)
  711. pData->hints |= PLUGIN_IS_SYNTH;
  712. if (fInstance->hasEditor())
  713. {
  714. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  715. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  716. }
  717. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  718. pData->hints |= PLUGIN_CAN_DRYWET;
  719. if (aOuts > 0)
  720. pData->hints |= PLUGIN_CAN_VOLUME;
  721. if (aOuts >= 2 && aOuts % 2 == 0)
  722. pData->hints |= PLUGIN_CAN_BALANCE;
  723. // extra plugin hints
  724. pData->extraHints = 0x0;
  725. if (mIns > 0)
  726. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  727. if (mOuts > 0)
  728. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  729. fInstance->setRateAndBufferSizeDetails(pData->engine->getSampleRate(),
  730. static_cast<int>(pData->engine->getBufferSize()));
  731. bufferSizeChanged(pData->engine->getBufferSize());
  732. reloadPrograms(true);
  733. if (pData->active)
  734. activate();
  735. carla_debug("CarlaPluginJuce::reload() - end");
  736. }
  737. void reloadPrograms(const bool doInit) override
  738. {
  739. carla_debug("CarlaPluginJuce::reloadPrograms(%s)", bool2str(doInit));
  740. const uint32_t oldCount = pData->prog.count;
  741. const int32_t current = pData->prog.current;
  742. // Delete old programs
  743. pData->prog.clear();
  744. // Query new programs
  745. const uint32_t newCount = (fInstance->getNumPrograms() > 0)
  746. ? static_cast<uint32_t>(fInstance->getNumPrograms())
  747. : 0;
  748. if (newCount > 0)
  749. {
  750. pData->prog.createNew(newCount);
  751. // Update names
  752. for (uint32_t i=0; i < newCount; ++i)
  753. pData->prog.names[i] = carla_strdup(fInstance->getProgramName(static_cast<int>(i)).toRawUTF8());
  754. }
  755. if (doInit)
  756. {
  757. if (newCount > 0)
  758. setProgram(0, false, false, false, true);
  759. }
  760. else
  761. {
  762. // Check if current program is invalid
  763. bool programChanged = false;
  764. if (newCount == oldCount+1)
  765. {
  766. // one program added, probably created by user
  767. pData->prog.current = static_cast<int32_t>(oldCount);
  768. programChanged = true;
  769. }
  770. else if (current < 0 && newCount > 0)
  771. {
  772. // programs exist now, but not before
  773. pData->prog.current = 0;
  774. programChanged = true;
  775. }
  776. else if (current >= 0 && newCount == 0)
  777. {
  778. // programs existed before, but not anymore
  779. pData->prog.current = -1;
  780. programChanged = true;
  781. }
  782. else if (current >= static_cast<int32_t>(newCount))
  783. {
  784. // current program > count
  785. pData->prog.current = 0;
  786. programChanged = true;
  787. }
  788. else
  789. {
  790. // no change
  791. pData->prog.current = current;
  792. }
  793. if (programChanged)
  794. {
  795. setProgram(pData->prog.current, true, true, true, false);
  796. }
  797. else
  798. {
  799. // Program was changed during update, re-set it
  800. if (pData->prog.current >= 0)
  801. fInstance->setCurrentProgram(pData->prog.current);
  802. }
  803. pData->engine->callback(true, true, ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0, 0.0f, nullptr);
  804. }
  805. }
  806. // -------------------------------------------------------------------
  807. // Plugin processing
  808. void activate() noexcept override
  809. {
  810. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  811. try {
  812. fInstance->prepareToPlay(pData->engine->getSampleRate(), static_cast<int>(pData->engine->getBufferSize()));
  813. } catch(...) {}
  814. }
  815. void deactivate() noexcept override
  816. {
  817. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  818. try {
  819. fInstance->releaseResources();
  820. } catch(...) {}
  821. }
  822. void process(const float* const* const audioIn,
  823. float** const audioOut,
  824. const float* const* const cvIn,
  825. float**,
  826. const uint32_t frames) override
  827. {
  828. // --------------------------------------------------------------------------------------------------------
  829. // Check if active
  830. if (! pData->active)
  831. {
  832. // disable any output sound
  833. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  834. carla_zeroFloats(audioOut[i], frames);
  835. return;
  836. }
  837. // --------------------------------------------------------------------------------------------------------
  838. // Check if needs reset
  839. if (pData->needsReset)
  840. {
  841. fInstance->reset();
  842. pData->needsReset = false;
  843. }
  844. // --------------------------------------------------------------------------------------------------------
  845. // Event Input
  846. fMidiBuffer.clear();
  847. if (pData->event.portIn != nullptr)
  848. {
  849. // ----------------------------------------------------------------------------------------------------
  850. // MIDI Input (External)
  851. if (pData->extNotes.mutex.tryLock())
  852. {
  853. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  854. {
  855. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  856. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  857. uint8_t midiEvent[3];
  858. midiEvent[0] = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  859. midiEvent[1] = note.note;
  860. midiEvent[2] = note.velo;
  861. fMidiBuffer.addEvent(midiEvent, 3, 0);
  862. }
  863. pData->extNotes.data.clear();
  864. pData->extNotes.mutex.unlock();
  865. } // End of MIDI Input (External)
  866. // ----------------------------------------------------------------------------------------------------
  867. // Event Input (System)
  868. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  869. bool allNotesOffSent = false;
  870. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  871. pData->event.cvSourcePorts->initPortBuffers(cvIn, frames, false, pData->event.portIn);
  872. #endif
  873. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  874. {
  875. EngineEvent& event(pData->event.portIn->getEvent(i));
  876. if (event.time >= frames)
  877. continue;
  878. switch (event.type)
  879. {
  880. case kEngineEventTypeNull:
  881. break;
  882. case kEngineEventTypeControl: {
  883. EngineControlEvent& ctrlEvent(event.ctrl);
  884. switch (ctrlEvent.type)
  885. {
  886. case kEngineControlEventTypeNull:
  887. break;
  888. case kEngineControlEventTypeParameter: {
  889. float value;
  890. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  891. // non-midi
  892. if (event.channel == kEngineEventNonMidiChannel)
  893. {
  894. const uint32_t k = ctrlEvent.param;
  895. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  896. ctrlEvent.handled = true;
  897. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  898. setParameterValueRT(k, value, event.time, true);
  899. continue;
  900. }
  901. // Control backend stuff
  902. if (event.channel == pData->ctrlChannel)
  903. {
  904. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  905. {
  906. ctrlEvent.handled = true;
  907. value = ctrlEvent.normalizedValue;
  908. setDryWetRT(value, true);
  909. }
  910. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  911. {
  912. ctrlEvent.handled = true;
  913. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  914. setVolumeRT(value, true);
  915. }
  916. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  917. {
  918. float left, right;
  919. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  920. if (value < 0.0f)
  921. {
  922. left = -1.0f;
  923. right = (value*2.0f)+1.0f;
  924. }
  925. else if (value > 0.0f)
  926. {
  927. left = (value*2.0f)-1.0f;
  928. right = 1.0f;
  929. }
  930. else
  931. {
  932. left = -1.0f;
  933. right = 1.0f;
  934. }
  935. ctrlEvent.handled = true;
  936. setBalanceLeftRT(left, true);
  937. setBalanceRightRT(right, true);
  938. }
  939. }
  940. #endif
  941. // Control plugin parameters
  942. uint32_t k;
  943. for (k=0; k < pData->param.count; ++k)
  944. {
  945. if (pData->param.data[k].midiChannel != event.channel)
  946. continue;
  947. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  948. continue;
  949. if (pData->param.data[k].type != PARAMETER_INPUT)
  950. continue;
  951. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  952. continue;
  953. ctrlEvent.handled = true;
  954. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  955. setParameterValueRT(k, value, event.time, true);
  956. }
  957. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  958. {
  959. uint8_t midiData[3];
  960. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  961. midiData[1] = uint8_t(ctrlEvent.param);
  962. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  963. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  964. }
  965. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  966. if (! ctrlEvent.handled)
  967. checkForMidiLearn(event);
  968. #endif
  969. break;
  970. } // case kEngineControlEventTypeParameter
  971. case kEngineControlEventTypeMidiBank:
  972. if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  973. {
  974. uint8_t midiData[3];
  975. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  976. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  977. midiData[2] = 0;
  978. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  979. midiData[1] = MIDI_CONTROL_BANK_SELECT__LSB;
  980. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  981. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  982. }
  983. break;
  984. case kEngineControlEventTypeMidiProgram:
  985. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  986. {
  987. if (ctrlEvent.param < pData->prog.count)
  988. {
  989. setProgramRT(ctrlEvent.param, true);
  990. }
  991. }
  992. else if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  993. {
  994. uint8_t midiData[2];
  995. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  996. midiData[1] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  997. fMidiBuffer.addEvent(midiData, 2, static_cast<int>(event.time));
  998. }
  999. break;
  1000. case kEngineControlEventTypeAllSoundOff:
  1001. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1002. {
  1003. uint8_t midiData[3];
  1004. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1005. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  1006. midiData[2] = 0;
  1007. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  1008. }
  1009. break;
  1010. case kEngineControlEventTypeAllNotesOff:
  1011. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1012. {
  1013. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1014. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1015. {
  1016. allNotesOffSent = true;
  1017. postponeRtAllNotesOff();
  1018. }
  1019. #endif
  1020. uint8_t midiData[3];
  1021. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1022. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1023. midiData[2] = 0;
  1024. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  1025. }
  1026. break;
  1027. } // switch (ctrlEvent.type)
  1028. break;
  1029. } // case kEngineEventTypeControl
  1030. case kEngineEventTypeMidi: {
  1031. const EngineMidiEvent& midiEvent(event.midi);
  1032. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  1033. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  1034. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1035. continue;
  1036. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1037. continue;
  1038. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1039. continue;
  1040. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1041. continue;
  1042. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1043. continue;
  1044. // Fix bad note-off
  1045. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  1046. status = MIDI_STATUS_NOTE_OFF;
  1047. // put back channel in data
  1048. uint8_t midiData2[midiEvent.size];
  1049. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  1050. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  1051. fMidiBuffer.addEvent(midiData2, midiEvent.size, static_cast<int>(event.time));
  1052. if (status == MIDI_STATUS_NOTE_ON)
  1053. {
  1054. pData->postponeNoteOnRtEvent(true, event.channel, midiData[1], midiData[2]);
  1055. }
  1056. else if (status == MIDI_STATUS_NOTE_OFF)
  1057. {
  1058. pData->postponeNoteOffRtEvent(true, event.channel, midiData[1]);
  1059. }
  1060. } break;
  1061. } // switch (event.type)
  1062. }
  1063. pData->postRtEvents.trySplice();
  1064. } // End of Event Input
  1065. // --------------------------------------------------------------------------------------------------------
  1066. // Set TimeInfo
  1067. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  1068. fPosInfo.setIsPlaying(timeInfo.playing);
  1069. fPosInfo.setTimeInSamples(static_cast<int64_t>(timeInfo.frame));
  1070. fPosInfo.setTimeInSeconds(static_cast<double>(timeInfo.frame)/pData->engine->getSampleRate());
  1071. if (timeInfo.bbt.valid)
  1072. {
  1073. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  1074. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  1075. const double ppqBar = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  1076. const double ppqBeat = static_cast<double>(timeInfo.bbt.beat - 1);
  1077. const double ppqTick = timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat;
  1078. fPosInfo.setBarCount(timeInfo.bbt.bar);
  1079. fPosInfo.setBpm(timeInfo.bbt.beatsPerMinute);
  1080. fPosInfo.setTimeSignature(TimeSignature{static_cast<int>(timeInfo.bbt.beatsPerBar+0.5f),
  1081. static_cast<int>(timeInfo.bbt.beatType+0.5f)});
  1082. fPosInfo.setPpqPosition(ppqBar + ppqBeat + ppqTick);
  1083. fPosInfo.setPpqPositionOfLastBarStart(ppqBar);
  1084. }
  1085. // --------------------------------------------------------------------------------------------------------
  1086. // Process
  1087. processSingle(audioIn, audioOut, frames);
  1088. // --------------------------------------------------------------------------------------------------------
  1089. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1090. return;
  1091. // unused
  1092. (void)cvIn;
  1093. #endif
  1094. }
  1095. bool processSingle(const float* const* const inBuffer, float** const outBuffer, const uint32_t frames)
  1096. {
  1097. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1098. if (pData->audioIn.count > 0)
  1099. {
  1100. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  1101. }
  1102. if (pData->audioOut.count > 0)
  1103. {
  1104. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  1105. }
  1106. // --------------------------------------------------------------------------------------------------------
  1107. // Try lock, silence otherwise
  1108. if (pData->engine->isOffline())
  1109. {
  1110. pData->singleMutex.lock();
  1111. }
  1112. else if (! pData->singleMutex.tryLock())
  1113. {
  1114. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1115. carla_zeroFloats(outBuffer[i], frames);
  1116. return false;
  1117. }
  1118. // --------------------------------------------------------------------------------------------------------
  1119. // Set audio in buffers
  1120. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1121. fAudioBuffer.copyFrom(static_cast<int>(i), 0, inBuffer[i], static_cast<int>(frames));
  1122. // --------------------------------------------------------------------------------------------------------
  1123. // Run plugin
  1124. fInstance->processBlock(fAudioBuffer, fMidiBuffer);
  1125. // --------------------------------------------------------------------------------------------------------
  1126. // Set audio out buffers
  1127. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1128. carla_copyFloats(outBuffer[i], fAudioBuffer.getReadPointer(static_cast<int>(i)), frames);
  1129. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1130. // --------------------------------------------------------------------------------------------------------
  1131. // Post-processing (dry/wet, volume and balance)
  1132. {
  1133. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1134. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1135. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1136. const bool isMono = (pData->audioIn.count == 1);
  1137. bool isPair;
  1138. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1139. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1140. {
  1141. // Dry/Wet
  1142. if (doDryWet)
  1143. {
  1144. const uint32_t c = isMono ? 0 : i;
  1145. for (uint32_t k=0; k < frames; ++k)
  1146. {
  1147. bufValue = inBuffer[c][k];
  1148. outBuffer[i][k] = (outBuffer[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1149. }
  1150. }
  1151. // Balance
  1152. if (doBalance)
  1153. {
  1154. isPair = (i % 2 == 0);
  1155. if (isPair)
  1156. {
  1157. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1158. carla_copyFloats(oldBufLeft, outBuffer[i], frames);
  1159. }
  1160. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1161. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1162. for (uint32_t k=0; k < frames; ++k)
  1163. {
  1164. if (isPair)
  1165. {
  1166. // left
  1167. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1168. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  1169. }
  1170. else
  1171. {
  1172. // right
  1173. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  1174. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  1175. }
  1176. }
  1177. }
  1178. // Volume
  1179. if (doVolume)
  1180. {
  1181. for (uint32_t k=0; k < frames; ++k)
  1182. outBuffer[i][k] *= pData->postProc.volume;
  1183. }
  1184. }
  1185. } // End of Post-processing
  1186. #endif
  1187. // --------------------------------------------------------------------------------------------------------
  1188. // Midi out
  1189. if (! fMidiBuffer.isEmpty())
  1190. {
  1191. if (pData->event.portOut != nullptr)
  1192. {
  1193. for (juce::MidiBufferIterator it = fMidiBuffer.cbegin(), end = fMidiBuffer.cend(); it != end; ++it)
  1194. {
  1195. const juce::MidiMessageMetadata metadata(*it);
  1196. CARLA_SAFE_ASSERT_BREAK(metadata.samplePosition >= 0);
  1197. CARLA_SAFE_ASSERT_BREAK(metadata.samplePosition < static_cast<int>(frames));
  1198. CARLA_SAFE_ASSERT_BREAK(metadata.numBytes > 0);
  1199. CARLA_SAFE_ASSERT_CONTINUE(metadata.numBytes <= 0xff);
  1200. if (! pData->event.portOut->writeMidiEvent(static_cast<uint32_t>(metadata.samplePosition),
  1201. static_cast<uint8_t>(metadata.numBytes),
  1202. metadata.data))
  1203. break;
  1204. }
  1205. }
  1206. fMidiBuffer.clear();
  1207. }
  1208. // --------------------------------------------------------------------------------------------------------
  1209. pData->singleMutex.unlock();
  1210. return true;
  1211. }
  1212. void bufferSizeChanged(const uint32_t newBufferSize) override
  1213. {
  1214. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1215. carla_debug("CarlaPluginJuce::bufferSizeChanged(%i)", newBufferSize);
  1216. fAudioBuffer.setSize(static_cast<int>(std::max<uint32_t>(pData->audioIn.count, pData->audioOut.count)), static_cast<int>(newBufferSize));
  1217. if (pData->active)
  1218. {
  1219. deactivate();
  1220. activate();
  1221. }
  1222. }
  1223. void sampleRateChanged(const double newSampleRate) override
  1224. {
  1225. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1226. carla_debug("CarlaPluginJuce::sampleRateChanged(%g)", newSampleRate);
  1227. if (pData->active)
  1228. {
  1229. deactivate();
  1230. activate();
  1231. }
  1232. }
  1233. // -------------------------------------------------------------------
  1234. // Misc
  1235. void idle() override
  1236. {
  1237. if (fNeedsUpdate)
  1238. {
  1239. fNeedsUpdate = false;
  1240. pData->engine->callback(true, true, ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0, 0.0f, nullptr);
  1241. }
  1242. CarlaPlugin::idle();
  1243. }
  1244. // -------------------------------------------------------------------
  1245. // Plugin buffers
  1246. // nothing
  1247. // -------------------------------------------------------------------
  1248. // Post-poned UI Stuff
  1249. // nothing
  1250. // -------------------------------------------------------------------
  1251. void* getNativeHandle() const noexcept override
  1252. {
  1253. return (fInstance != nullptr) ? getPlatformSpecificDataForAll(fInstance) : nullptr;
  1254. }
  1255. // -------------------------------------------------------------------
  1256. protected:
  1257. void audioProcessorParameterChanged(juce::AudioProcessor*, int index, float value) override
  1258. {
  1259. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1260. const uint32_t uindex(static_cast<uint32_t>(index));
  1261. const float fixedValue(pData->param.getFixedValue(uindex, value));
  1262. CarlaPlugin::setParameterValue(static_cast<uint32_t>(index), fixedValue, false, true, true);
  1263. }
  1264. void audioProcessorChanged(juce::AudioProcessor*, const ChangeDetails& details) override
  1265. {
  1266. if (details.parameterInfoChanged || details.programChanged)
  1267. fNeedsUpdate = true;
  1268. }
  1269. void audioProcessorParameterChangeGestureBegin(juce::AudioProcessor*, int index) override
  1270. {
  1271. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1272. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), true);
  1273. }
  1274. void audioProcessorParameterChangeGestureEnd(juce::AudioProcessor*, int index) override
  1275. {
  1276. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1277. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), false);
  1278. }
  1279. juce::Optional<juce::AudioPlayHead::PositionInfo> getPosition() const override
  1280. {
  1281. return fPosInfo;
  1282. }
  1283. // -------------------------------------------------------------------
  1284. public:
  1285. bool init(const CarlaPluginPtr plugin,
  1286. const char* const filename, const char* const name, const char* const label,
  1287. const int64_t uniqueId, const uint options, const char* const format)
  1288. {
  1289. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1290. // ---------------------------------------------------------------
  1291. // first checks
  1292. if (pData->client != nullptr)
  1293. {
  1294. pData->engine->setLastError("Plugin client is already registered");
  1295. return false;
  1296. }
  1297. if (format == nullptr || format[0] == '\0')
  1298. {
  1299. pData->engine->setLastError("null format");
  1300. return false;
  1301. }
  1302. // AU requires label
  1303. if (std::strcmp(format, "AU") == 0)
  1304. {
  1305. if (label == nullptr || label[0] == '\0')
  1306. {
  1307. pData->engine->setLastError("null label");
  1308. return false;
  1309. }
  1310. }
  1311. juce::String fileOrIdentifier;
  1312. if (std::strcmp(format, "AU") == 0)
  1313. {
  1314. fileOrIdentifier = label;
  1315. }
  1316. else
  1317. {
  1318. // VST2 and VST3 require filename
  1319. if (filename == nullptr || filename[0] == '\0')
  1320. {
  1321. pData->engine->setLastError("null filename");
  1322. return false;
  1323. }
  1324. juce::String jfilename(filename);
  1325. #ifdef CARLA_OS_WIN
  1326. // Fix for wine usage
  1327. if (juce::File("Z:\\usr\\").isDirectory() && filename[0] == '/')
  1328. {
  1329. jfilename.replace("/", "\\");
  1330. jfilename = "Z:" + jfilename;
  1331. }
  1332. #endif
  1333. fileOrIdentifier = jfilename;
  1334. if (label != nullptr && label[0] != '\0')
  1335. fDesc.name = label;
  1336. }
  1337. /**/ if (std::strcmp(format, "AU") == 0)
  1338. {
  1339. #if JUCE_PLUGINHOST_AU
  1340. fFormatManager.addFormat(new juce::AudioUnitPluginFormat());
  1341. #endif
  1342. }
  1343. else if (std::strcmp(format, "VST2") == 0)
  1344. {
  1345. #if JUCE_PLUGINHOST_VST
  1346. fFormatManager.addFormat(new juce::VSTPluginFormat());
  1347. #endif
  1348. }
  1349. else if (std::strcmp(format, "VST3") == 0)
  1350. {
  1351. #if JUCE_PLUGINHOST_VST3
  1352. fFormatManager.addFormat(new juce::VST3PluginFormat());
  1353. #endif
  1354. }
  1355. else
  1356. {
  1357. fFormatManager.addDefaultFormats();
  1358. }
  1359. {
  1360. juce::OwnedArray<juce::PluginDescription> pluginDescriptions;
  1361. juce::KnownPluginList plist;
  1362. {
  1363. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1364. const ScopedAbortCatcher sac;
  1365. #endif
  1366. for (int i = 0; i < fFormatManager.getNumFormats(); ++i)
  1367. {
  1368. juce::AudioPluginFormat* const apformat = fFormatManager.getFormat(i);
  1369. CARLA_SAFE_ASSERT_CONTINUE(apformat != nullptr);
  1370. carla_debug("Trying to load '%s' plugin with format '%s'", fileOrIdentifier.toRawUTF8(), apformat->getName().toRawUTF8());
  1371. try {
  1372. plist.scanAndAddFile(fileOrIdentifier, true, pluginDescriptions, *apformat);
  1373. } CARLA_SAFE_EXCEPTION_CONTINUE("scanAndAddFile")
  1374. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1375. if (sac.wasTriggered())
  1376. {
  1377. carla_stderr("WARNING: Caught exception while scanning file, will not load this plugin");
  1378. pluginDescriptions.clearQuick(false);
  1379. break;
  1380. }
  1381. #endif
  1382. }
  1383. }
  1384. if (pluginDescriptions.size() == 0)
  1385. {
  1386. pData->engine->setLastError("Failed to get plugin description");
  1387. return false;
  1388. }
  1389. fDesc = *pluginDescriptions[0];
  1390. }
  1391. if (uniqueId != 0)
  1392. fDesc.uniqueId = static_cast<int>(uniqueId);
  1393. juce::String error;
  1394. {
  1395. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1396. const ScopedAbortCatcher sac;
  1397. #endif
  1398. try {
  1399. fInstance = fFormatManager.createPluginInstance(fDesc,
  1400. pData->engine->getSampleRate(),
  1401. static_cast<int>(pData->engine->getBufferSize()),
  1402. error);
  1403. } CARLA_SAFE_EXCEPTION("createPluginInstance")
  1404. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1405. if (sac.wasTriggered())
  1406. {
  1407. fInstance = nullptr;
  1408. carla_stderr("WARNING: Caught exception while instantiating, will not load this plugin");
  1409. }
  1410. #endif
  1411. }
  1412. if (fInstance == nullptr)
  1413. {
  1414. pData->engine->setLastError(error.toRawUTF8());
  1415. return false;
  1416. }
  1417. fInstance->fillInPluginDescription(fDesc);
  1418. fInstance->setPlayHead(this);
  1419. fInstance->addListener(this);
  1420. fFormatName = format;
  1421. // ---------------------------------------------------------------
  1422. // get info
  1423. if (name != nullptr && name[0] != '\0')
  1424. pData->name = pData->engine->getUniquePluginName(name);
  1425. else
  1426. pData->name = pData->engine->getUniquePluginName(fInstance->getName().toRawUTF8());
  1427. if (filename != nullptr && filename[0] != '\0')
  1428. pData->filename = carla_strdup(filename);
  1429. // ---------------------------------------------------------------
  1430. // register client
  1431. pData->client = pData->engine->addClient(plugin);
  1432. if (pData->client == nullptr || ! pData->client->isOk())
  1433. {
  1434. pData->engine->setLastError("Failed to register plugin client");
  1435. return false;
  1436. }
  1437. // ---------------------------------------------------------------
  1438. // set options
  1439. pData->options = 0x0;
  1440. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1441. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  1442. if (fInstance->acceptsMidi())
  1443. {
  1444. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  1445. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1446. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  1447. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1448. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  1449. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1450. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  1451. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1452. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  1453. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1454. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  1455. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  1456. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1457. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  1458. }
  1459. if (fInstance->getNumPrograms() > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  1460. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  1461. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1462. return true;
  1463. }
  1464. private:
  1465. juce::PluginDescription fDesc;
  1466. juce::AudioPluginFormatManager fFormatManager;
  1467. std::unique_ptr<juce::AudioPluginInstance> fInstance;
  1468. juce::AudioSampleBuffer fAudioBuffer;
  1469. juce::MidiBuffer fMidiBuffer;
  1470. PositionInfo fPosInfo;
  1471. juce::MemoryBlock fChunk;
  1472. juce::String fFormatName;
  1473. CarlaScopedPointer<JucePluginWindow> fWindow;
  1474. bool fNeedsUpdate;
  1475. bool isJuceSaveFormat(const void* const data, const std::size_t dataSize)
  1476. {
  1477. if (fFormatName != "VST2")
  1478. return true;
  1479. if (dataSize < 160)
  1480. return false;
  1481. const int32_t* const set = (const int32_t*)data;
  1482. // chunkMagic
  1483. if (! compareMagic(set[0], "CcnK"))
  1484. return false;
  1485. // version
  1486. if (fxbSwap(set[3]) > 1)
  1487. return false;
  1488. // fxMagic, data contents depend on this value
  1489. if (compareMagic(set[2], "FBCh") || compareMagic(set[2], "FJuc"))
  1490. {
  1491. const int32_t chunkSize = fxbSwap(set[39]);
  1492. return static_cast<std::size_t>(chunkSize + 160) == dataSize;
  1493. }
  1494. if (compareMagic(set[2], "FxBk"))
  1495. {
  1496. const int32_t numPrograms = fxbSwap(set[6]);
  1497. return numPrograms >= 1;
  1498. }
  1499. return false;
  1500. }
  1501. static bool compareMagic(int32_t magic, const char* name) noexcept
  1502. {
  1503. return magic == (int32_t)juce::ByteOrder::littleEndianInt (name)
  1504. || magic == (int32_t)juce::ByteOrder::bigEndianInt (name);
  1505. }
  1506. static int32_t fxbSwap(const int32_t x) noexcept
  1507. {
  1508. return (int32_t)juce::ByteOrder::swapIfLittleEndian ((uint32_t) x);
  1509. }
  1510. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJuce)
  1511. };
  1512. CARLA_BACKEND_END_NAMESPACE
  1513. #endif // USING_JUCE
  1514. // -------------------------------------------------------------------------------------------------------------------
  1515. CARLA_BACKEND_START_NAMESPACE
  1516. CarlaPluginPtr CarlaPlugin::newJuce(const Initializer& init, const char* const format)
  1517. {
  1518. carla_debug("CarlaPlugin::newJuce({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s)",
  1519. init.engine, init.filename, init.name, init.label, init.uniqueId, format);
  1520. #ifdef USING_JUCE
  1521. std::shared_ptr<CarlaPluginJuce> plugin(new CarlaPluginJuce(init.engine, init.id));
  1522. if (! plugin->init(plugin, init.filename, init.name, init.label, init.uniqueId, init.options, format))
  1523. return nullptr;
  1524. return plugin;
  1525. #else
  1526. init.engine->setLastError("Juce-based plugin not available");
  1527. return nullptr;
  1528. // unused
  1529. (void)format;
  1530. #endif
  1531. }
  1532. CARLA_BACKEND_END_NAMESPACE
  1533. // -------------------------------------------------------------------------------------------------------------------