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.

1475 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* const audioIn, float** const audioOut,
  599. const float* const*, float**, const uint32_t frames) override
  600. {
  601. // --------------------------------------------------------------------------------------------------------
  602. // Check if active
  603. if (! pData->active)
  604. {
  605. // disable any output sound
  606. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  607. carla_zeroFloats(audioOut[i], frames);
  608. return;
  609. }
  610. // --------------------------------------------------------------------------------------------------------
  611. // Check if needs reset
  612. if (pData->needsReset)
  613. {
  614. fInstance->reset();
  615. pData->needsReset = false;
  616. }
  617. // --------------------------------------------------------------------------------------------------------
  618. // Event Input
  619. fMidiBuffer.clear();
  620. if (pData->event.portIn != nullptr)
  621. {
  622. // ----------------------------------------------------------------------------------------------------
  623. // MIDI Input (External)
  624. if (pData->extNotes.mutex.tryLock())
  625. {
  626. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  627. {
  628. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  629. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  630. uint8_t midiEvent[3];
  631. midiEvent[0] = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  632. midiEvent[1] = note.note;
  633. midiEvent[2] = note.velo;
  634. fMidiBuffer.addEvent(midiEvent, 3, 0);
  635. }
  636. pData->extNotes.data.clear();
  637. pData->extNotes.mutex.unlock();
  638. } // End of MIDI Input (External)
  639. // ----------------------------------------------------------------------------------------------------
  640. // Event Input (System)
  641. #ifndef BUILD_BRIDGE
  642. bool allNotesOffSent = false;
  643. #endif
  644. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  645. {
  646. const EngineEvent& event(pData->event.portIn->getEvent(i));
  647. if (event.time >= frames)
  648. continue;
  649. switch (event.type)
  650. {
  651. case kEngineEventTypeNull:
  652. break;
  653. case kEngineEventTypeControl: {
  654. const EngineControlEvent& ctrlEvent(event.ctrl);
  655. switch (ctrlEvent.type)
  656. {
  657. case kEngineControlEventTypeNull:
  658. break;
  659. case kEngineControlEventTypeParameter: {
  660. #ifndef BUILD_BRIDGE
  661. // Control backend stuff
  662. if (event.channel == pData->ctrlChannel)
  663. {
  664. float value;
  665. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  666. {
  667. value = ctrlEvent.value;
  668. setDryWetRT(value, true);
  669. }
  670. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  671. {
  672. value = ctrlEvent.value*127.0f/100.0f;
  673. setVolumeRT(value, true);
  674. }
  675. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  676. {
  677. float left, right;
  678. value = ctrlEvent.value/0.5f - 1.0f;
  679. if (value < 0.0f)
  680. {
  681. left = -1.0f;
  682. right = (value*2.0f)+1.0f;
  683. }
  684. else if (value > 0.0f)
  685. {
  686. left = (value*2.0f)-1.0f;
  687. right = 1.0f;
  688. }
  689. else
  690. {
  691. left = -1.0f;
  692. right = 1.0f;
  693. }
  694. setBalanceLeftRT(left, true);
  695. setBalanceRightRT(right, true);
  696. }
  697. }
  698. #endif
  699. // Control plugin parameters
  700. uint32_t k;
  701. for (k=0; k < pData->param.count; ++k)
  702. {
  703. if (pData->param.data[k].midiChannel != event.channel)
  704. continue;
  705. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  706. continue;
  707. if (pData->param.data[k].type != PARAMETER_INPUT)
  708. continue;
  709. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  710. continue;
  711. float value;
  712. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  713. {
  714. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  715. }
  716. else
  717. {
  718. if (pData->param.data[k].hints & PARAMETER_IS_LOGARITHMIC)
  719. value = pData->param.ranges[k].getUnnormalizedLogValue(ctrlEvent.value);
  720. else
  721. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  722. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  723. value = std::rint(value);
  724. }
  725. setParameterValueRT(k, value, true);
  726. }
  727. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  728. {
  729. uint8_t midiData[3];
  730. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  731. midiData[1] = uint8_t(ctrlEvent.param);
  732. midiData[2] = uint8_t(ctrlEvent.value*127.0f);
  733. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  734. }
  735. break;
  736. } // case kEngineControlEventTypeParameter
  737. case kEngineControlEventTypeMidiBank:
  738. if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  739. {
  740. uint8_t midiData[3];
  741. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  742. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  743. midiData[2] = 0;
  744. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  745. midiData[1] = MIDI_CONTROL_BANK_SELECT__LSB;
  746. midiData[2] = uint8_t(ctrlEvent.value*127.0f);
  747. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  748. }
  749. break;
  750. case kEngineControlEventTypeMidiProgram:
  751. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  752. {
  753. if (ctrlEvent.param < pData->prog.count)
  754. {
  755. setProgramRT(ctrlEvent.param, true);
  756. }
  757. }
  758. else if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  759. {
  760. uint8_t midiData[3];
  761. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  762. midiData[1] = uint8_t(ctrlEvent.value*127.0f);
  763. fMidiBuffer.addEvent(midiData, 2, static_cast<int>(event.time));
  764. }
  765. break;
  766. case kEngineControlEventTypeAllSoundOff:
  767. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  768. {
  769. uint8_t midiData[3];
  770. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  771. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  772. midiData[2] = 0;
  773. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  774. }
  775. break;
  776. case kEngineControlEventTypeAllNotesOff:
  777. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  778. {
  779. #ifndef BUILD_BRIDGE
  780. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  781. {
  782. allNotesOffSent = true;
  783. postponeRtAllNotesOff();
  784. }
  785. #endif
  786. uint8_t midiData[3];
  787. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  788. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  789. midiData[2] = 0;
  790. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  791. }
  792. break;
  793. } // switch (ctrlEvent.type)
  794. break;
  795. } // case kEngineEventTypeControl
  796. case kEngineEventTypeMidi: {
  797. const EngineMidiEvent& midiEvent(event.midi);
  798. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  799. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  800. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  801. continue;
  802. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  803. continue;
  804. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  805. continue;
  806. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  807. continue;
  808. // Fix bad note-off
  809. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  810. status = MIDI_STATUS_NOTE_OFF;
  811. // put back channel in data
  812. uint8_t midiData2[midiEvent.size];
  813. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  814. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  815. fMidiBuffer.addEvent(midiData2, midiEvent.size, static_cast<int>(event.time));
  816. if (status == MIDI_STATUS_NOTE_ON)
  817. {
  818. pData->postponeRtEvent(kPluginPostRtEventNoteOn,
  819. true,
  820. event.channel,
  821. midiData[1],
  822. midiData[2],
  823. 0.0f);
  824. }
  825. else if (status == MIDI_STATUS_NOTE_OFF)
  826. {
  827. pData->postponeRtEvent(kPluginPostRtEventNoteOff,
  828. true,
  829. event.channel,
  830. midiData[1],
  831. 0, 0.0f);
  832. }
  833. } break;
  834. } // switch (event.type)
  835. }
  836. pData->postRtEvents.trySplice();
  837. } // End of Event Input
  838. // --------------------------------------------------------------------------------------------------------
  839. // Set TimeInfo
  840. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  841. fPosInfo.isPlaying = timeInfo.playing;
  842. if (timeInfo.bbt.valid)
  843. {
  844. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  845. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  846. const double ppqBar = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  847. const double ppqBeat = static_cast<double>(timeInfo.bbt.beat - 1);
  848. const double ppqTick = timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat;
  849. fPosInfo.bpm = timeInfo.bbt.beatsPerMinute;
  850. fPosInfo.timeSigNumerator = static_cast<int>(timeInfo.bbt.beatsPerBar);
  851. fPosInfo.timeSigDenominator = static_cast<int>(timeInfo.bbt.beatType);
  852. fPosInfo.timeInSamples = static_cast<int64_t>(timeInfo.frame);
  853. fPosInfo.timeInSeconds = static_cast<double>(fPosInfo.timeInSamples)/pData->engine->getSampleRate();
  854. fPosInfo.ppqPosition = ppqBar + ppqBeat + ppqTick;
  855. fPosInfo.ppqPositionOfLastBarStart = ppqBar;
  856. }
  857. // --------------------------------------------------------------------------------------------------------
  858. // Process
  859. processSingle(audioIn, audioOut, frames);
  860. }
  861. bool processSingle(const float* const* const inBuffer, float** const outBuffer, const uint32_t frames)
  862. {
  863. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  864. if (pData->audioIn.count > 0)
  865. {
  866. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  867. }
  868. if (pData->audioOut.count > 0)
  869. {
  870. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  871. }
  872. // --------------------------------------------------------------------------------------------------------
  873. // Try lock, silence otherwise
  874. if (pData->engine->isOffline())
  875. {
  876. pData->singleMutex.lock();
  877. }
  878. else if (! pData->singleMutex.tryLock())
  879. {
  880. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  881. carla_zeroFloats(outBuffer[i], frames);
  882. return false;
  883. }
  884. // --------------------------------------------------------------------------------------------------------
  885. // Set audio in buffers
  886. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  887. fAudioBuffer.copyFrom(static_cast<int>(i), 0, inBuffer[i], static_cast<int>(frames));
  888. // --------------------------------------------------------------------------------------------------------
  889. // Run plugin
  890. fInstance->processBlock(fAudioBuffer, fMidiBuffer);
  891. // --------------------------------------------------------------------------------------------------------
  892. // Set audio out buffers
  893. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  894. carla_copyFloats(outBuffer[i], fAudioBuffer.getReadPointer(static_cast<int>(i)), frames);
  895. // --------------------------------------------------------------------------------------------------------
  896. // Midi out
  897. if (! fMidiBuffer.isEmpty())
  898. {
  899. if (pData->event.portOut != nullptr)
  900. {
  901. const uint8_t* midiEventData;
  902. int midiEventSize, midiEventPosition;
  903. for (juce::MidiBuffer::Iterator i(fMidiBuffer); i.getNextEvent(midiEventData, midiEventSize, midiEventPosition);)
  904. {
  905. CARLA_SAFE_ASSERT_BREAK(midiEventPosition >= 0 && midiEventPosition < static_cast<int>(frames));
  906. CARLA_SAFE_ASSERT_BREAK(midiEventSize > 0);
  907. if (! pData->event.portOut->writeMidiEvent(static_cast<uint32_t>(midiEventPosition), static_cast<uint8_t>(midiEventSize), midiEventData))
  908. break;
  909. }
  910. }
  911. fMidiBuffer.clear();
  912. }
  913. // --------------------------------------------------------------------------------------------------------
  914. pData->singleMutex.unlock();
  915. return true;
  916. }
  917. void bufferSizeChanged(const uint32_t newBufferSize) override
  918. {
  919. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  920. carla_debug("CarlaPluginJuce::bufferSizeChanged(%i)", newBufferSize);
  921. fAudioBuffer.setSize(static_cast<int>(std::max<uint32_t>(pData->audioIn.count, pData->audioOut.count)), static_cast<int>(newBufferSize));
  922. if (pData->active)
  923. {
  924. deactivate();
  925. activate();
  926. }
  927. }
  928. void sampleRateChanged(const double newSampleRate) override
  929. {
  930. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  931. carla_debug("CarlaPluginJuce::sampleRateChanged(%g)", newSampleRate);
  932. if (pData->active)
  933. {
  934. deactivate();
  935. activate();
  936. }
  937. }
  938. // -------------------------------------------------------------------
  939. // Plugin buffers
  940. // nothing
  941. // -------------------------------------------------------------------
  942. // Post-poned UI Stuff
  943. // nothing
  944. // -------------------------------------------------------------------
  945. void* getNativeHandle() const noexcept override
  946. {
  947. return (fInstance != nullptr) ? fInstance->getPlatformSpecificData() : nullptr;
  948. }
  949. // -------------------------------------------------------------------
  950. protected:
  951. void audioProcessorParameterChanged(juce::AudioProcessor*, int index, float value) override
  952. {
  953. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  954. const uint32_t uindex(static_cast<uint32_t>(index));
  955. const float fixedValue(pData->param.getFixedValue(uindex, value));
  956. CarlaPlugin::setParameterValue(static_cast<uint32_t>(index), fixedValue, false, true, true);
  957. }
  958. void audioProcessorChanged(juce::AudioProcessor*) override
  959. {
  960. pData->engine->callback(true, true, ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0, 0.0f, nullptr);
  961. }
  962. void audioProcessorParameterChangeGestureBegin(juce::AudioProcessor*, int index) override
  963. {
  964. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  965. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), true);
  966. }
  967. void audioProcessorParameterChangeGestureEnd(juce::AudioProcessor*, int index) override
  968. {
  969. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  970. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), false);
  971. }
  972. bool getCurrentPosition(CurrentPositionInfo& result) override
  973. {
  974. carla_copyStruct(result, fPosInfo);
  975. return true;
  976. }
  977. // -------------------------------------------------------------------
  978. public:
  979. 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)
  980. {
  981. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  982. // ---------------------------------------------------------------
  983. // first checks
  984. if (pData->client != nullptr)
  985. {
  986. pData->engine->setLastError("Plugin client is already registered");
  987. return false;
  988. }
  989. if (format == nullptr || format[0] == '\0')
  990. {
  991. pData->engine->setLastError("null format");
  992. return false;
  993. }
  994. // AU requires label
  995. if (std::strcmp(format, "AU") == 0)
  996. {
  997. if (label == nullptr || label[0] == '\0')
  998. {
  999. pData->engine->setLastError("null label");
  1000. return false;
  1001. }
  1002. }
  1003. juce::String fileOrIdentifier;
  1004. if (std::strcmp(format, "AU") == 0)
  1005. {
  1006. fileOrIdentifier = label;
  1007. }
  1008. else
  1009. {
  1010. // VST2 and VST3 require filename
  1011. if (filename == nullptr || filename[0] == '\0')
  1012. {
  1013. pData->engine->setLastError("null filename");
  1014. return false;
  1015. }
  1016. juce::String jfilename(filename);
  1017. #ifdef CARLA_OS_WIN
  1018. // Fix for wine usage
  1019. if (juce::juce_isRunningInWine() && filename[0] == '/')
  1020. {
  1021. jfilename.replace("/", "\\");
  1022. jfilename = "Z:" + jfilename;
  1023. }
  1024. #endif
  1025. fileOrIdentifier = jfilename;
  1026. if (label != nullptr && label[0] != '\0')
  1027. fDesc.name = label;
  1028. }
  1029. fFormatManager.addDefaultFormats();
  1030. {
  1031. juce::OwnedArray<juce::PluginDescription> pluginDescriptions;
  1032. juce::KnownPluginList plist;
  1033. for (int i = 0; i < fFormatManager.getNumFormats(); ++i)
  1034. plist.scanAndAddFile(fileOrIdentifier, true, pluginDescriptions, *fFormatManager.getFormat(i));
  1035. if (pluginDescriptions.size() == 0)
  1036. {
  1037. pData->engine->setLastError("Failed to get plugin description");
  1038. return false;
  1039. }
  1040. fDesc = *pluginDescriptions[0];
  1041. }
  1042. if (uniqueId != 0)
  1043. fDesc.uid = static_cast<int>(uniqueId);
  1044. juce::String error;
  1045. fInstance = fFormatManager.createPluginInstance(fDesc,
  1046. pData->engine->getSampleRate(),
  1047. static_cast<int>(pData->engine->getBufferSize()),
  1048. error);
  1049. if (fInstance == nullptr)
  1050. {
  1051. pData->engine->setLastError(error.toRawUTF8());
  1052. return false;
  1053. }
  1054. fInstance->fillInPluginDescription(fDesc);
  1055. fInstance->setPlayHead(this);
  1056. fInstance->addListener(this);
  1057. fFormatName = format;
  1058. // ---------------------------------------------------------------
  1059. // get info
  1060. if (name != nullptr && name[0] != '\0')
  1061. pData->name = pData->engine->getUniquePluginName(name);
  1062. else
  1063. pData->name = pData->engine->getUniquePluginName(fInstance->getName().toRawUTF8());
  1064. if (filename != nullptr && filename[0] != '\0')
  1065. pData->filename = carla_strdup(filename);
  1066. // ---------------------------------------------------------------
  1067. // register client
  1068. pData->client = pData->engine->addClient(this);
  1069. if (pData->client == nullptr || ! pData->client->isOk())
  1070. {
  1071. pData->engine->setLastError("Failed to register plugin client");
  1072. return false;
  1073. }
  1074. // ---------------------------------------------------------------
  1075. // set options
  1076. pData->options = 0x0;
  1077. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1078. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  1079. if (fInstance->acceptsMidi())
  1080. {
  1081. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  1082. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1083. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  1084. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1085. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  1086. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1087. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  1088. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1089. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  1090. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1091. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  1092. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  1093. }
  1094. if (fInstance->getNumPrograms() > 1 && ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0))
  1095. {
  1096. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  1097. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1098. }
  1099. return true;
  1100. }
  1101. private:
  1102. juce::PluginDescription fDesc;
  1103. juce::AudioPluginInstance* fInstance;
  1104. juce::AudioPluginFormatManager fFormatManager;
  1105. juce::AudioSampleBuffer fAudioBuffer;
  1106. juce::MidiBuffer fMidiBuffer;
  1107. CurrentPositionInfo fPosInfo;
  1108. juce::MemoryBlock fChunk;
  1109. juce::String fFormatName;
  1110. CarlaScopedPointer<JucePluginWindow> fWindow;
  1111. bool isJuceSaveFormat(const void* const data, const std::size_t dataSize)
  1112. {
  1113. if (fFormatName != "VST2")
  1114. return true;
  1115. if (dataSize < 160)
  1116. return false;
  1117. const int32_t* const set = (const int32_t*)data;
  1118. if (! compareMagic(set[0], "CcnK"))
  1119. return false;
  1120. if (! compareMagic(set[2], "FBCh") && ! compareMagic(set[2], "FJuc"))
  1121. return false;
  1122. if (fxbSwap(set[3]) > 1)
  1123. return false;
  1124. const int32_t chunkSize = fxbSwap(set[39]);
  1125. return static_cast<std::size_t>(chunkSize + 160) == dataSize;
  1126. }
  1127. static bool compareMagic(int32_t magic, const char* name) noexcept
  1128. {
  1129. return magic == (int32_t)juce::ByteOrder::littleEndianInt (name)
  1130. || magic == (int32_t)juce::ByteOrder::bigEndianInt (name);
  1131. }
  1132. static int32_t fxbSwap(const int32_t x) noexcept
  1133. {
  1134. return (int32_t)juce::ByteOrder::swapIfLittleEndian ((uint32_t) x);
  1135. }
  1136. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJuce)
  1137. };
  1138. CARLA_BACKEND_END_NAMESPACE
  1139. #endif // USING_JUCE
  1140. // -------------------------------------------------------------------------------------------------------------------
  1141. CARLA_BACKEND_START_NAMESPACE
  1142. CarlaPlugin* CarlaPlugin::newJuce(const Initializer& init, const char* const format)
  1143. {
  1144. carla_debug("CarlaPlugin::newJuce({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s)", init.engine, init.filename, init.name, init.label, init.uniqueId, format);
  1145. #ifdef USING_JUCE
  1146. CarlaPluginJuce* const plugin(new CarlaPluginJuce(init.engine, init.id));
  1147. if (! plugin->init(init.filename, init.name, init.label, init.uniqueId, init.options, format))
  1148. {
  1149. delete plugin;
  1150. return nullptr;
  1151. }
  1152. return plugin;
  1153. #else
  1154. init.engine->setLastError("Juce-based plugin not available");
  1155. return nullptr;
  1156. // unused
  1157. (void)format;
  1158. #endif
  1159. }
  1160. CARLA_BACKEND_END_NAMESPACE
  1161. // -------------------------------------------------------------------------------------------------------------------