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.

1477 lines
51KB

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