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.

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