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.

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