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.

1510 lines
52KB

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