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.

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