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.

1781 lines
63KB

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