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.

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