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.

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