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.

1556 lines
53KB

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