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.

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