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.

1579 lines
54KB

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