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.

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