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.

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