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.

CarlaPluginJuce.cpp 48KB

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