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.

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