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.

1723 lines
60KB

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