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.

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