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.

1474 lines
51KB

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