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.

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