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.

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