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.

1607 lines
55KB

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