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.

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