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.

1490 lines
51KB

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