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.

1524 lines
52KB

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