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.

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