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 52KB

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