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

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917
  1. /*
  2. * Carla Juce Plugin
  3. * Copyright (C) 2013-2022 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. #include "CarlaVst2Utils.hpp"
  25. #include "CarlaVst3Utils.hpp"
  26. #define JUCE_GUI_BASICS_INCLUDE_XHEADERS 1
  27. #include "carla_juce/carla_juce.h"
  28. #pragma GCC diagnostic push
  29. #pragma GCC diagnostic ignored "-Wdouble-promotion"
  30. #pragma GCC diagnostic ignored "-Wduplicated-branches"
  31. #pragma GCC diagnostic ignored "-Weffc++"
  32. #pragma GCC diagnostic ignored "-Wfloat-equal"
  33. #include "juce_audio_processors/juce_audio_processors.h"
  34. #include "juce_gui_basics/juce_gui_basics.h"
  35. #pragma GCC diagnostic pop
  36. #include "JucePluginWindow.hpp"
  37. CARLA_BACKEND_START_NAMESPACE
  38. // -------------------------------------------------------------------------------------------------------------------
  39. // Fallback data
  40. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  41. // -------------------------------------------------------------------------------------------------------------------
  42. // find all available plugin audio ports
  43. static void findMaxTotalChannels(juce::AudioProcessor* const filter,
  44. const bool isAU, uint32_t& maxTotalIns, uint32_t& maxTotalOuts)
  45. {
  46. filter->enableAllBuses();
  47. if (isAU)
  48. {
  49. maxTotalIns = static_cast<uint32_t>(juce::jmax(0, filter->getTotalNumInputChannels()));
  50. maxTotalOuts = static_cast<uint32_t>(juce::jmax(0, filter->getTotalNumOutputChannels()));
  51. return;
  52. }
  53. const int numInputBuses = filter->getBusCount(true);
  54. const int numOutputBuses = filter->getBusCount(false);
  55. if (numInputBuses > 1 || numOutputBuses > 1)
  56. {
  57. maxTotalIns = maxTotalOuts = 0;
  58. for (int i = 0; i < numInputBuses; ++i)
  59. maxTotalIns += static_cast<uint32_t>(juce::jmax(0, filter->getChannelCountOfBus(true, i)));
  60. for (int i = 0; i < numOutputBuses; ++i)
  61. maxTotalOuts += static_cast<uint32_t>(juce::jmax(0, filter->getChannelCountOfBus(false, i)));
  62. }
  63. else
  64. {
  65. maxTotalIns = numInputBuses > 0
  66. ? static_cast<uint32_t>(juce::jmax(0, filter->getBus(true, 0)->getMaxSupportedChannels(64)))
  67. : 0;
  68. maxTotalOuts = numOutputBuses > 0
  69. ? static_cast<uint32_t>(juce::jmax(0, filter->getBus(false, 0)->getMaxSupportedChannels(64)))
  70. : 0;
  71. }
  72. }
  73. // -------------------------------------------------------------------------------------------------------------------
  74. // ExtensionsVisitor for various formats
  75. static void* getPlatformSpecificDataForAll(const std::unique_ptr<juce::AudioPluginInstance>& instance)
  76. {
  77. struct ExtensionsVisitorForVST2 : public juce::ExtensionsVisitor
  78. {
  79. void* ptr = nullptr;
  80. void visitVST3Client (const VST3Client& c) override { ptr = c.getIComponentPtr(); }
  81. void visitVSTClient (const VSTClient& c) override { ptr = c.getAEffectPtr(); }
  82. void visitAudioUnitClient(const AudioUnitClient& c) override { ptr = c.getAudioUnitHandle(); }
  83. } visitor;
  84. instance->getExtensions(visitor);
  85. return visitor.ptr;
  86. }
  87. static AEffect* getPlatformSpecificDataForVST2(const std::unique_ptr<juce::AudioPluginInstance>& instance)
  88. {
  89. struct ExtensionsVisitorForVST2 : public juce::ExtensionsVisitor
  90. {
  91. AEffect* aeffect = nullptr;
  92. void visitVSTClient(const VSTClient& c) override { aeffect = c.getAEffectPtr(); }
  93. } visitor;
  94. instance->getExtensions(visitor);
  95. return visitor.aeffect;
  96. }
  97. static v3_component** getPlatformSpecificDataForVST3(const std::unique_ptr<juce::AudioPluginInstance>& instance)
  98. {
  99. struct ExtensionsVisitorForVST3 : public juce::ExtensionsVisitor
  100. {
  101. v3_component** component = nullptr;
  102. void visitVST3Client(const VST3Client& c) override { component = (v3_component**)c.getIComponentPtr(); }
  103. } visitor;
  104. instance->getExtensions(visitor);
  105. return visitor.component;
  106. }
  107. // -------------------------------------------------------------------------------------------------------------------
  108. class CarlaPluginJuce : public CarlaPlugin,
  109. private juce::AudioPlayHead,
  110. private juce::AudioProcessorListener
  111. {
  112. public:
  113. CarlaPluginJuce(CarlaEngine* const engine, const uint id)
  114. : CarlaPlugin(engine, id),
  115. fDesc(),
  116. fFormatManager(),
  117. fInstance(),
  118. fAudioBuffer(),
  119. fMidiBuffer(),
  120. fPosInfo(),
  121. fChunk(),
  122. fFormatName(),
  123. fWindow(),
  124. fNeedsUpdate(false)
  125. {
  126. carla_debug("CarlaPluginJuce::CarlaPluginJuce(%p, %i)", engine, id);
  127. fMidiBuffer.ensureSize(2048);
  128. fMidiBuffer.clear();
  129. }
  130. ~CarlaPluginJuce() override
  131. {
  132. carla_debug("CarlaPluginJuce::~CarlaPluginJuce()");
  133. // close UI
  134. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  135. showCustomUI(false);
  136. pData->singleMutex.lock();
  137. pData->masterMutex.lock();
  138. if (pData->client != nullptr && pData->client->isActive())
  139. pData->client->deactivate(true);
  140. if (pData->active)
  141. {
  142. deactivate();
  143. pData->active = false;
  144. }
  145. fInstance = nullptr;
  146. clearBuffers();
  147. }
  148. // -------------------------------------------------------------------
  149. // Information (base)
  150. PluginType getType() const noexcept override
  151. {
  152. return getPluginTypeFromString(fDesc.pluginFormatName.toRawUTF8());
  153. }
  154. PluginCategory getCategory() const noexcept override
  155. {
  156. if (fDesc.isInstrument)
  157. return PLUGIN_CATEGORY_SYNTH;
  158. return getPluginCategoryFromName(fDesc.category.isNotEmpty()
  159. ? fDesc.category.toRawUTF8()
  160. : fDesc.name.toRawUTF8());
  161. }
  162. int64_t getUniqueId() const noexcept override
  163. {
  164. return fDesc.uniqueId;
  165. }
  166. uint32_t getLatencyInFrames() const noexcept override
  167. {
  168. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0);
  169. const int latency = fInstance->getLatencySamples();
  170. CARLA_SAFE_ASSERT_RETURN(latency >= 0, 0);
  171. return static_cast<uint32_t>(latency);
  172. }
  173. // -------------------------------------------------------------------
  174. // Information (count)
  175. // nothing
  176. // -------------------------------------------------------------------
  177. // Information (current data)
  178. std::size_t getChunkData(void** const dataPtr) noexcept override
  179. {
  180. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  181. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0);
  182. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  183. *dataPtr = nullptr;
  184. try {
  185. fChunk.reset();
  186. fInstance->getStateInformation(fChunk);
  187. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPluginJuce::getChunkData", 0);
  188. if (const std::size_t size = fChunk.getSize())
  189. {
  190. *dataPtr = fChunk.getData();
  191. return size;
  192. }
  193. return 0;
  194. }
  195. // -------------------------------------------------------------------
  196. // Information (per-plugin data)
  197. uint getOptionsAvailable() const noexcept override
  198. {
  199. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0x0);
  200. uint options = 0x0;
  201. options |= PLUGIN_OPTION_USE_CHUNKS;
  202. if (fInstance->getNumPrograms() > 1)
  203. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  204. if (fInstance->acceptsMidi())
  205. {
  206. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  207. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  208. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  209. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  210. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  211. options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  212. options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  213. }
  214. return options;
  215. }
  216. float getParameterValue(const uint32_t parameterId) const noexcept override
  217. {
  218. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  219. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0.0f);
  220. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  221. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr, 0.0f);
  222. return parameter->getValue();
  223. }
  224. bool getLabel(char* const strBuf) const noexcept override
  225. {
  226. if (fDesc.pluginFormatName == "AU" || fDesc.pluginFormatName == "AudioUnit")
  227. std::strncpy(strBuf, fDesc.fileOrIdentifier.toRawUTF8(), STR_MAX);
  228. else
  229. std::strncpy(strBuf, fDesc.name.toRawUTF8(), STR_MAX);
  230. return true;
  231. }
  232. bool getMaker(char* const strBuf) const noexcept override
  233. {
  234. std::strncpy(strBuf, fDesc.manufacturerName.toRawUTF8(), STR_MAX);
  235. return true;
  236. }
  237. bool getCopyright(char* const strBuf) const noexcept override
  238. {
  239. return getMaker(strBuf);
  240. }
  241. bool getRealName(char* const strBuf) const noexcept override
  242. {
  243. std::strncpy(strBuf, fDesc.descriptiveName.toRawUTF8(), STR_MAX);
  244. return true;
  245. }
  246. bool getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  247. {
  248. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  249. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, false);
  250. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  251. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr, false);
  252. std::strncpy(strBuf, parameter->getName(STR_MAX).toRawUTF8(), STR_MAX);
  253. return true;
  254. }
  255. bool getParameterText(const uint32_t parameterId, char* const strBuf) noexcept override
  256. {
  257. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  258. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, false);
  259. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  260. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr, false);
  261. std::strncpy(strBuf, parameter->getCurrentValueAsText().toRawUTF8(), STR_MAX);
  262. return true;
  263. }
  264. bool getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  265. {
  266. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  267. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, false);
  268. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  269. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr, false);
  270. std::strncpy(strBuf, parameter->getLabel().toRawUTF8(), STR_MAX);
  271. return true;
  272. }
  273. bool getParameterGroupName(const uint32_t parameterId, char* const strBuf) const noexcept override
  274. {
  275. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  276. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, false);
  277. if (fDesc.pluginFormatName != "VST" && fDesc.pluginFormatName != "VST2")
  278. return false;
  279. AEffect* const effect = getPlatformSpecificDataForVST2(fInstance);
  280. if (effect == nullptr)
  281. return false;
  282. VstParameterProperties prop;
  283. carla_zeroStruct(prop);
  284. if (effect->dispatcher(effect, effGetParameterProperties, static_cast<int32_t>(parameterId), 0, &prop, 0.0f) == 1
  285. && prop.category != 0 && prop.categoryLabel[0] != '\0')
  286. {
  287. std::snprintf(strBuf, STR_MAX, "%d:%s", prop.category, prop.categoryLabel);
  288. return true;
  289. }
  290. return false;
  291. }
  292. // -------------------------------------------------------------------
  293. // Set data (state)
  294. // nothing
  295. // -------------------------------------------------------------------
  296. // Set data (internal stuff)
  297. void setName(const char* const newName) override
  298. {
  299. CarlaPlugin::setName(newName);
  300. if (fWindow == nullptr || pData->uiTitle.isNotEmpty())
  301. return;
  302. juce::String uiName(pData->name);
  303. uiName += " (GUI)";
  304. fWindow->setName(uiName);
  305. }
  306. // -------------------------------------------------------------------
  307. // Set data (plugin-specific stuff)
  308. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  309. {
  310. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  311. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  312. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  313. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr,);
  314. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  315. try {
  316. parameter->setValue(value);
  317. } CARLA_SAFE_EXCEPTION("setValue");
  318. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  319. }
  320. void setParameterValueRT(const uint32_t parameterId, const float value, const uint32_t frameOffset, const bool sendCallbackLater) noexcept override
  321. {
  322. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  323. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  324. juce::AudioProcessorParameter* const parameter = fInstance->getParameters()[static_cast<int>(parameterId)];
  325. CARLA_SAFE_ASSERT_RETURN(parameter != nullptr,);
  326. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  327. try {
  328. parameter->setValue(value);
  329. } CARLA_SAFE_EXCEPTION("setValue(RT)");
  330. CarlaPlugin::setParameterValueRT(parameterId, fixedValue, frameOffset, sendCallbackLater);
  331. }
  332. void setChunkData(const void* const data, const std::size_t dataSize) override
  333. {
  334. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  335. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  336. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  337. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  338. if (isJuceSaveFormat(data, dataSize))
  339. {
  340. const ScopedSingleProcessLocker spl(this, true);
  341. fInstance->setStateInformation(data, static_cast<int>(dataSize));
  342. }
  343. else
  344. {
  345. uint8_t* const dataCompat = (uint8_t*)std::malloc(dataSize + 160);
  346. CARLA_SAFE_ASSERT_RETURN(dataCompat != nullptr,);
  347. carla_stdout("NOTE: Loading plugin state in Carla JUCE/VST2 compatibility mode");
  348. std::memset(dataCompat, 0, 160);
  349. std::memcpy(dataCompat+160, data, dataSize);
  350. int32_t* const set = (int32_t*)dataCompat;
  351. set[0] = (int32_t)juce::ByteOrder::littleEndianInt("CcnK");
  352. set[2] = (int32_t)juce::ByteOrder::littleEndianInt("FBCh");
  353. set[3] = fxbSwap(1);
  354. set[39] = fxbSwap(static_cast<int32_t>(dataSize));
  355. {
  356. const ScopedSingleProcessLocker spl(this, true);
  357. fInstance->setStateInformation(dataCompat, static_cast<int>(dataSize+160));
  358. }
  359. std::free(dataCompat);
  360. }
  361. pData->updateParameterValues(this, true, true, false);
  362. }
  363. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback, const bool doingInit) noexcept override
  364. {
  365. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  366. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  367. if (index >= 0)
  368. {
  369. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  370. try {
  371. fInstance->setCurrentProgram(index);
  372. } CARLA_SAFE_EXCEPTION("setCurrentProgram");
  373. }
  374. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback, doingInit);
  375. }
  376. void setProgramRT(const uint32_t index, const bool sendCallbackLater) noexcept override
  377. {
  378. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  379. CARLA_SAFE_ASSERT_RETURN(index < pData->prog.count,);
  380. try {
  381. fInstance->setCurrentProgram(static_cast<int32_t>(index));
  382. } CARLA_SAFE_EXCEPTION("setCurrentProgram");
  383. CarlaPlugin::setProgramRT(index, sendCallbackLater);
  384. }
  385. // -------------------------------------------------------------------
  386. // Set ui stuff
  387. void setCustomUITitle(const char* const title) noexcept override
  388. {
  389. if (fWindow != nullptr)
  390. {
  391. try {
  392. fWindow->setName(title);
  393. } CARLA_SAFE_EXCEPTION("set custom ui title");
  394. }
  395. CarlaPlugin::setCustomUITitle(title);
  396. }
  397. void showCustomUI(const bool yesNo) override
  398. {
  399. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  400. carla_debug("CarlaPluginJuce::showCustomUI(%s)", bool2str(yesNo));
  401. if (yesNo)
  402. {
  403. if (juce::AudioProcessorEditor* const editor = fInstance->createEditorIfNeeded())
  404. {
  405. const EngineOptions& opts(pData->engine->getOptions());
  406. #ifndef CARLA_OS_MAC
  407. editor->setScaleFactor(opts.uiScale);
  408. #endif
  409. if (fWindow == nullptr)
  410. {
  411. juce::String uiName;
  412. if (pData->uiTitle.isNotEmpty())
  413. {
  414. uiName = pData->uiTitle.buffer();
  415. }
  416. else
  417. {
  418. uiName = pData->name;
  419. uiName += " (GUI)";
  420. }
  421. AEffect* const vst2effect = fDesc.pluginFormatName == "VST" || fDesc.pluginFormatName == "VST2"
  422. ? getPlatformSpecificDataForVST2(fInstance)
  423. : nullptr;
  424. /* TODO update to juce7 APIs
  425. v3_plugin_view** const vst3view = fDesc.pluginFormatName == "VST3"
  426. ? (v3_plugin_view**)editor->getPlatformSpecificData()
  427. : nullptr;
  428. */
  429. v3_plugin_view** const vst3view = nullptr;
  430. fWindow = new JucePluginWindow(opts.frontendWinId, opts.pluginsAreStandalone,
  431. vst2effect, vst3view);
  432. fWindow->setName(uiName);
  433. }
  434. fWindow->show(editor);
  435. fWindow->toFront(true);
  436. }
  437. }
  438. else
  439. {
  440. if (juce::AudioProcessorEditor* const editor = fInstance->getActiveEditor())
  441. delete editor;
  442. fWindow = nullptr;
  443. }
  444. }
  445. void uiIdle() override
  446. {
  447. if (fWindow != nullptr)
  448. {
  449. if (fWindow->wasClosedByUser())
  450. {
  451. showCustomUI(false);
  452. pData->engine->callback(true, true,
  453. ENGINE_CALLBACK_UI_STATE_CHANGED,
  454. pData->id,
  455. 0,
  456. 0, 0, 0.0f, nullptr);
  457. }
  458. }
  459. CarlaPlugin::uiIdle();
  460. }
  461. // -------------------------------------------------------------------
  462. // Plugin state
  463. void reload() override
  464. {
  465. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  466. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  467. carla_debug("CarlaPluginJuce::reload() - start");
  468. const EngineProcessMode processMode(pData->engine->getProccessMode());
  469. // Safely disable plugin for reload
  470. const ScopedDisabler sd(this);
  471. if (pData->active)
  472. deactivate();
  473. clearBuffers();
  474. uint32_t aIns, aOuts, mIns, mOuts, params;
  475. mIns = mOuts = 0;
  476. bool needsCtrlIn, needsCtrlOut;
  477. needsCtrlIn = needsCtrlOut = false;
  478. const bool isAU = fDesc.pluginFormatName == "AU" || fDesc.pluginFormatName == "AudioUnit";
  479. const bool isVST2 = fDesc.pluginFormatName == "VST" || fDesc.pluginFormatName == "VST2";
  480. const bool isVST3 = fDesc.pluginFormatName == "VST3";
  481. findMaxTotalChannels(fInstance.get(), isAU, aIns, aOuts);
  482. fInstance->refreshParameterList();
  483. const juce::Array<juce::AudioProcessorParameter*>& parameters(fInstance->getParameters());
  484. params = static_cast<uint32_t>(std::max(parameters.size(), 0));
  485. if (fInstance->acceptsMidi())
  486. {
  487. mIns = 1;
  488. needsCtrlIn = true;
  489. }
  490. if (fInstance->producesMidi())
  491. {
  492. mOuts = 1;
  493. needsCtrlOut = true;
  494. }
  495. if (aIns > 0)
  496. {
  497. pData->audioIn.createNew(aIns);
  498. }
  499. if (aOuts > 0)
  500. {
  501. pData->audioOut.createNew(aOuts);
  502. needsCtrlIn = true;
  503. }
  504. if (params > 0)
  505. {
  506. pData->param.createNew(params, false);
  507. needsCtrlIn = true;
  508. }
  509. const uint portNameSize(pData->engine->getMaxPortNameSize());
  510. CarlaString portName;
  511. // Audio Ins
  512. for (uint32_t j=0; j < aIns; ++j)
  513. {
  514. portName.clear();
  515. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  516. {
  517. portName = pData->name;
  518. portName += ":";
  519. }
  520. if (aIns > 1)
  521. {
  522. portName += "input_";
  523. portName += CarlaString(j+1);
  524. }
  525. else
  526. portName += "input";
  527. portName.truncate(portNameSize);
  528. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  529. pData->audioIn.ports[j].rindex = j;
  530. }
  531. // Audio Outs
  532. for (uint32_t j=0; j < aOuts; ++j)
  533. {
  534. portName.clear();
  535. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  536. {
  537. portName = pData->name;
  538. portName += ":";
  539. }
  540. if (aOuts > 1)
  541. {
  542. portName += "output_";
  543. portName += CarlaString(j+1);
  544. }
  545. else
  546. portName += "output";
  547. portName.truncate(portNameSize);
  548. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  549. pData->audioOut.ports[j].rindex = j;
  550. }
  551. for (uint32_t j=0; j < params; ++j)
  552. {
  553. const int32_t ij = static_cast<int>(j);
  554. juce::AudioProcessorParameter* const parameter = parameters[ij];
  555. CARLA_SAFE_ASSERT_CONTINUE(parameter != nullptr);
  556. pData->param.data[j].type = PARAMETER_INPUT;
  557. pData->param.data[j].index = static_cast<int32_t>(j);
  558. pData->param.data[j].rindex = static_cast<int32_t>(j);
  559. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  560. pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  561. if (parameter->isAutomatable())
  562. pData->param.data[j].hints |= PARAMETER_IS_AUTOMATABLE;
  563. const float min = 0.0f;
  564. const float max = 1.0f;
  565. float def, step, stepSmall, stepLarge;
  566. bool hasDetails = false;
  567. if (isVST2)
  568. {
  569. AEffect* const effect = getPlatformSpecificDataForVST2(fInstance);
  570. VstParameterProperties prop;
  571. carla_zeroStruct(prop);
  572. if (effect != nullptr && effect->dispatcher(effect, effGetParameterProperties, ij, 0, &prop, 0.0f) == 1)
  573. {
  574. hasDetails = true;
  575. /**/ if (prop.flags & kVstParameterIsSwitch)
  576. {
  577. step = max - min;
  578. stepSmall = step;
  579. stepLarge = step;
  580. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  581. }
  582. else if (prop.flags & kVstParameterUsesIntStep)
  583. {
  584. step = static_cast<float>(prop.stepInteger);
  585. stepSmall = static_cast<float>(prop.stepInteger)/10.0f;
  586. stepLarge = static_cast<float>(prop.largeStepInteger);
  587. }
  588. else if (prop.flags & kVstParameterUsesFloatStep)
  589. {
  590. step = prop.stepFloat;
  591. stepSmall = prop.smallStepFloat;
  592. stepLarge = prop.largeStepFloat;
  593. }
  594. else
  595. {
  596. const float range = max - min;
  597. step = range/100.0f;
  598. stepSmall = range/1000.0f;
  599. stepLarge = range/10.0f;
  600. }
  601. if ((prop.flags & (kVstParameterIsSwitch|kVstParameterUsesIntStep)) == 0x0)
  602. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  603. if (prop.flags & kVstParameterCanRamp)
  604. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  605. }
  606. }
  607. else if (isVST3)
  608. {
  609. v3_component** const component = getPlatformSpecificDataForVST3(fInstance);
  610. /* FIXME query edit controller the long way too */
  611. v3_edit_controller** controller = nullptr;
  612. v3_cpp_obj_query_interface(component, v3_edit_controller_iid, &controller);
  613. if (controller != nullptr)
  614. {
  615. v3_param_info info;
  616. if (v3_cpp_obj(controller)->get_parameter_info(controller, static_cast<int32_t>(j), &info) == V3_OK)
  617. {
  618. hasDetails = true;
  619. if (info.step_count == 1)
  620. {
  621. step = stepSmall = stepLarge = 1;
  622. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  623. }
  624. else if (info.step_count != 0)
  625. {
  626. step = 1.0f / static_cast<float>(info.step_count);
  627. stepSmall = step/10.0f;
  628. stepLarge = std::min(1.0f, step*10.0f);
  629. }
  630. else
  631. {
  632. const float range = max - min;
  633. step = range/100.0f;
  634. stepSmall = range/1000.0f;
  635. stepLarge = range/10.0f;
  636. }
  637. if (info.flags & V3_PARAM_READ_ONLY)
  638. pData->param.data[j].type = PARAMETER_OUTPUT;
  639. // TODO V3_PARAM_IS_LIST
  640. if (info.flags & (V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE))
  641. pData->param.data[j].hints &= ~PARAMETER_IS_ENABLED;
  642. if ((info.flags & (V3_PARAM_IS_LIST|V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE)) == 0x0)
  643. if (info.flags & V3_PARAM_CAN_AUTOMATE)
  644. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  645. }
  646. v3_cpp_obj_unref(controller);
  647. }
  648. }
  649. if (! hasDetails)
  650. {
  651. if (parameter->isBoolean())
  652. {
  653. step = max - min;
  654. stepSmall = step;
  655. stepLarge = step;
  656. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  657. }
  658. else
  659. {
  660. const float range = max - min;
  661. step = range/100.0f;
  662. stepSmall = range/1000.0f;
  663. stepLarge = range/10.0f;
  664. if (! parameter->isMetaParameter())
  665. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  666. }
  667. }
  668. // this gives wrong values!
  669. // def = parameter->getDefaultValue();
  670. def = parameter->getValue();
  671. if (def < min)
  672. def = min;
  673. else if (def > max)
  674. def = max;
  675. pData->param.ranges[j].min = min;
  676. pData->param.ranges[j].max = max;
  677. pData->param.ranges[j].def = def;
  678. pData->param.ranges[j].step = step;
  679. pData->param.ranges[j].stepSmall = stepSmall;
  680. pData->param.ranges[j].stepLarge = stepLarge;
  681. }
  682. if (needsCtrlIn)
  683. {
  684. portName.clear();
  685. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  686. {
  687. portName = pData->name;
  688. portName += ":";
  689. }
  690. portName += "events-in";
  691. portName.truncate(portNameSize);
  692. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  693. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  694. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  695. #endif
  696. }
  697. if (needsCtrlOut)
  698. {
  699. portName.clear();
  700. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  701. {
  702. portName = pData->name;
  703. portName += ":";
  704. }
  705. portName += "events-out";
  706. portName.truncate(portNameSize);
  707. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  708. }
  709. // plugin hints
  710. pData->hints = 0x0;
  711. pData->hints |= PLUGIN_NEEDS_FIXED_BUFFERS;
  712. if (fDesc.isInstrument)
  713. pData->hints |= PLUGIN_IS_SYNTH;
  714. if (fInstance->hasEditor())
  715. {
  716. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  717. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  718. }
  719. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  720. pData->hints |= PLUGIN_CAN_DRYWET;
  721. if (aOuts > 0)
  722. pData->hints |= PLUGIN_CAN_VOLUME;
  723. if (aOuts >= 2 && aOuts % 2 == 0)
  724. pData->hints |= PLUGIN_CAN_BALANCE;
  725. // extra plugin hints
  726. pData->extraHints = 0x0;
  727. if (mIns > 0)
  728. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  729. if (mOuts > 0)
  730. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  731. fInstance->setRateAndBufferSizeDetails(pData->engine->getSampleRate(),
  732. static_cast<int>(pData->engine->getBufferSize()));
  733. bufferSizeChanged(pData->engine->getBufferSize());
  734. reloadPrograms(true);
  735. if (pData->active)
  736. activate();
  737. carla_debug("CarlaPluginJuce::reload() - end");
  738. }
  739. void reloadPrograms(const bool doInit) override
  740. {
  741. carla_debug("CarlaPluginJuce::reloadPrograms(%s)", bool2str(doInit));
  742. const uint32_t oldCount = pData->prog.count;
  743. const int32_t current = pData->prog.current;
  744. // Delete old programs
  745. pData->prog.clear();
  746. // Query new programs
  747. const uint32_t newCount = (fInstance->getNumPrograms() > 0)
  748. ? static_cast<uint32_t>(fInstance->getNumPrograms())
  749. : 0;
  750. if (newCount > 0)
  751. {
  752. pData->prog.createNew(newCount);
  753. // Update names
  754. for (uint32_t i=0; i < newCount; ++i)
  755. pData->prog.names[i] = carla_strdup(fInstance->getProgramName(static_cast<int>(i)).toRawUTF8());
  756. }
  757. if (doInit)
  758. {
  759. if (newCount > 0)
  760. setProgram(0, false, false, false, true);
  761. }
  762. else
  763. {
  764. // Check if current program is invalid
  765. bool programChanged = false;
  766. if (newCount == oldCount+1)
  767. {
  768. // one program added, probably created by user
  769. pData->prog.current = static_cast<int32_t>(oldCount);
  770. programChanged = true;
  771. }
  772. else if (current < 0 && newCount > 0)
  773. {
  774. // programs exist now, but not before
  775. pData->prog.current = 0;
  776. programChanged = true;
  777. }
  778. else if (current >= 0 && newCount == 0)
  779. {
  780. // programs existed before, but not anymore
  781. pData->prog.current = -1;
  782. programChanged = true;
  783. }
  784. else if (current >= static_cast<int32_t>(newCount))
  785. {
  786. // current program > count
  787. pData->prog.current = 0;
  788. programChanged = true;
  789. }
  790. else
  791. {
  792. // no change
  793. pData->prog.current = current;
  794. }
  795. if (programChanged)
  796. {
  797. setProgram(pData->prog.current, true, true, true, false);
  798. }
  799. else
  800. {
  801. // Program was changed during update, re-set it
  802. if (pData->prog.current >= 0)
  803. fInstance->setCurrentProgram(pData->prog.current);
  804. }
  805. pData->engine->callback(true, true, ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0, 0.0f, nullptr);
  806. }
  807. }
  808. // -------------------------------------------------------------------
  809. // Plugin processing
  810. void activate() noexcept override
  811. {
  812. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  813. try {
  814. fInstance->prepareToPlay(pData->engine->getSampleRate(), static_cast<int>(pData->engine->getBufferSize()));
  815. } catch(...) {}
  816. }
  817. void deactivate() noexcept override
  818. {
  819. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  820. try {
  821. fInstance->releaseResources();
  822. } catch(...) {}
  823. }
  824. void process(const float* const* const audioIn,
  825. float** const audioOut,
  826. const float* const* const cvIn,
  827. float**,
  828. const uint32_t frames) override
  829. {
  830. // --------------------------------------------------------------------------------------------------------
  831. // Check if active
  832. if (! pData->active)
  833. {
  834. // disable any output sound
  835. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  836. carla_zeroFloats(audioOut[i], frames);
  837. return;
  838. }
  839. // --------------------------------------------------------------------------------------------------------
  840. // Check if needs reset
  841. if (pData->needsReset)
  842. {
  843. fInstance->reset();
  844. pData->needsReset = false;
  845. }
  846. // --------------------------------------------------------------------------------------------------------
  847. // Event Input
  848. fMidiBuffer.clear();
  849. if (pData->event.portIn != nullptr)
  850. {
  851. // ----------------------------------------------------------------------------------------------------
  852. // MIDI Input (External)
  853. if (pData->extNotes.mutex.tryLock())
  854. {
  855. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  856. {
  857. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  858. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  859. uint8_t midiEvent[3];
  860. midiEvent[0] = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  861. midiEvent[1] = note.note;
  862. midiEvent[2] = note.velo;
  863. fMidiBuffer.addEvent(midiEvent, 3, 0);
  864. }
  865. pData->extNotes.data.clear();
  866. pData->extNotes.mutex.unlock();
  867. } // End of MIDI Input (External)
  868. // ----------------------------------------------------------------------------------------------------
  869. // Event Input (System)
  870. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  871. bool allNotesOffSent = false;
  872. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  873. pData->event.cvSourcePorts->initPortBuffers(cvIn, frames, false, pData->event.portIn);
  874. #endif
  875. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  876. {
  877. EngineEvent& event(pData->event.portIn->getEvent(i));
  878. if (event.time >= frames)
  879. continue;
  880. switch (event.type)
  881. {
  882. case kEngineEventTypeNull:
  883. break;
  884. case kEngineEventTypeControl: {
  885. EngineControlEvent& ctrlEvent(event.ctrl);
  886. switch (ctrlEvent.type)
  887. {
  888. case kEngineControlEventTypeNull:
  889. break;
  890. case kEngineControlEventTypeParameter: {
  891. float value;
  892. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  893. // non-midi
  894. if (event.channel == kEngineEventNonMidiChannel)
  895. {
  896. const uint32_t k = ctrlEvent.param;
  897. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  898. ctrlEvent.handled = true;
  899. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  900. setParameterValueRT(k, value, event.time, true);
  901. continue;
  902. }
  903. // Control backend stuff
  904. if (event.channel == pData->ctrlChannel)
  905. {
  906. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  907. {
  908. ctrlEvent.handled = true;
  909. value = ctrlEvent.normalizedValue;
  910. setDryWetRT(value, true);
  911. }
  912. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  913. {
  914. ctrlEvent.handled = true;
  915. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  916. setVolumeRT(value, true);
  917. }
  918. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  919. {
  920. float left, right;
  921. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  922. if (value < 0.0f)
  923. {
  924. left = -1.0f;
  925. right = (value*2.0f)+1.0f;
  926. }
  927. else if (value > 0.0f)
  928. {
  929. left = (value*2.0f)-1.0f;
  930. right = 1.0f;
  931. }
  932. else
  933. {
  934. left = -1.0f;
  935. right = 1.0f;
  936. }
  937. ctrlEvent.handled = true;
  938. setBalanceLeftRT(left, true);
  939. setBalanceRightRT(right, true);
  940. }
  941. }
  942. #endif
  943. // Control plugin parameters
  944. uint32_t k;
  945. for (k=0; k < pData->param.count; ++k)
  946. {
  947. if (pData->param.data[k].midiChannel != event.channel)
  948. continue;
  949. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  950. continue;
  951. if (pData->param.data[k].type != PARAMETER_INPUT)
  952. continue;
  953. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  954. continue;
  955. ctrlEvent.handled = true;
  956. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  957. setParameterValueRT(k, value, event.time, true);
  958. }
  959. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  960. {
  961. uint8_t midiData[3];
  962. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  963. midiData[1] = uint8_t(ctrlEvent.param);
  964. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  965. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  966. }
  967. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  968. if (! ctrlEvent.handled)
  969. checkForMidiLearn(event);
  970. #endif
  971. break;
  972. } // case kEngineControlEventTypeParameter
  973. case kEngineControlEventTypeMidiBank:
  974. if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  975. {
  976. uint8_t midiData[3];
  977. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  978. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  979. midiData[2] = 0;
  980. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  981. midiData[1] = MIDI_CONTROL_BANK_SELECT__LSB;
  982. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  983. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  984. }
  985. break;
  986. case kEngineControlEventTypeMidiProgram:
  987. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  988. {
  989. if (ctrlEvent.param < pData->prog.count)
  990. {
  991. setProgramRT(ctrlEvent.param, true);
  992. }
  993. }
  994. else if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  995. {
  996. uint8_t midiData[2];
  997. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  998. midiData[1] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  999. fMidiBuffer.addEvent(midiData, 2, static_cast<int>(event.time));
  1000. }
  1001. break;
  1002. case kEngineControlEventTypeAllSoundOff:
  1003. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1004. {
  1005. uint8_t midiData[3];
  1006. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1007. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  1008. midiData[2] = 0;
  1009. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  1010. }
  1011. break;
  1012. case kEngineControlEventTypeAllNotesOff:
  1013. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1014. {
  1015. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1016. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1017. {
  1018. allNotesOffSent = true;
  1019. postponeRtAllNotesOff();
  1020. }
  1021. #endif
  1022. uint8_t midiData[3];
  1023. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1024. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1025. midiData[2] = 0;
  1026. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  1027. }
  1028. break;
  1029. } // switch (ctrlEvent.type)
  1030. break;
  1031. } // case kEngineEventTypeControl
  1032. case kEngineEventTypeMidi: {
  1033. const EngineMidiEvent& midiEvent(event.midi);
  1034. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  1035. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  1036. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1037. continue;
  1038. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1039. continue;
  1040. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1041. continue;
  1042. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1043. continue;
  1044. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1045. continue;
  1046. // Fix bad note-off
  1047. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  1048. status = MIDI_STATUS_NOTE_OFF;
  1049. // put back channel in data
  1050. uint8_t midiData2[midiEvent.size];
  1051. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  1052. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  1053. fMidiBuffer.addEvent(midiData2, midiEvent.size, static_cast<int>(event.time));
  1054. if (status == MIDI_STATUS_NOTE_ON)
  1055. {
  1056. pData->postponeNoteOnRtEvent(true, event.channel, midiData[1], midiData[2]);
  1057. }
  1058. else if (status == MIDI_STATUS_NOTE_OFF)
  1059. {
  1060. pData->postponeNoteOffRtEvent(true, event.channel, midiData[1]);
  1061. }
  1062. } break;
  1063. } // switch (event.type)
  1064. }
  1065. pData->postRtEvents.trySplice();
  1066. } // End of Event Input
  1067. // --------------------------------------------------------------------------------------------------------
  1068. // Set TimeInfo
  1069. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  1070. fPosInfo.setIsPlaying(timeInfo.playing);
  1071. fPosInfo.setTimeInSamples(static_cast<int64_t>(timeInfo.frame));
  1072. fPosInfo.setTimeInSeconds(static_cast<double>(timeInfo.frame)/pData->engine->getSampleRate());
  1073. if (timeInfo.bbt.valid)
  1074. {
  1075. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  1076. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  1077. const double ppqBar = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  1078. const double ppqBeat = static_cast<double>(timeInfo.bbt.beat - 1);
  1079. const double ppqTick = timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat;
  1080. fPosInfo.setBarCount(timeInfo.bbt.bar);
  1081. fPosInfo.setBpm(timeInfo.bbt.beatsPerMinute);
  1082. fPosInfo.setTimeSignature(TimeSignature{static_cast<int>(timeInfo.bbt.beatsPerBar+0.5f),
  1083. static_cast<int>(timeInfo.bbt.beatType+0.5f)});
  1084. fPosInfo.setPpqPosition(ppqBar + ppqBeat + ppqTick);
  1085. fPosInfo.setPpqPositionOfLastBarStart(ppqBar);
  1086. }
  1087. // --------------------------------------------------------------------------------------------------------
  1088. // Process
  1089. processSingle(audioIn, audioOut, frames);
  1090. // --------------------------------------------------------------------------------------------------------
  1091. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1092. return;
  1093. // unused
  1094. (void)cvIn;
  1095. #endif
  1096. }
  1097. bool processSingle(const float* const* const inBuffer, float** const outBuffer, const uint32_t frames)
  1098. {
  1099. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1100. if (pData->audioIn.count > 0)
  1101. {
  1102. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  1103. }
  1104. if (pData->audioOut.count > 0)
  1105. {
  1106. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  1107. }
  1108. // --------------------------------------------------------------------------------------------------------
  1109. // Try lock, silence otherwise
  1110. if (pData->engine->isOffline())
  1111. {
  1112. pData->singleMutex.lock();
  1113. }
  1114. else if (! pData->singleMutex.tryLock())
  1115. {
  1116. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1117. carla_zeroFloats(outBuffer[i], frames);
  1118. return false;
  1119. }
  1120. // --------------------------------------------------------------------------------------------------------
  1121. // Set audio in buffers
  1122. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1123. fAudioBuffer.copyFrom(static_cast<int>(i), 0, inBuffer[i], static_cast<int>(frames));
  1124. // --------------------------------------------------------------------------------------------------------
  1125. // Run plugin
  1126. fInstance->processBlock(fAudioBuffer, fMidiBuffer);
  1127. // --------------------------------------------------------------------------------------------------------
  1128. // Set audio out buffers
  1129. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1130. carla_copyFloats(outBuffer[i], fAudioBuffer.getReadPointer(static_cast<int>(i)), frames);
  1131. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1132. // --------------------------------------------------------------------------------------------------------
  1133. // Post-processing (dry/wet, volume and balance)
  1134. {
  1135. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1136. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1137. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1138. const bool isMono = (pData->audioIn.count == 1);
  1139. bool isPair;
  1140. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1141. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1142. {
  1143. // Dry/Wet
  1144. if (doDryWet)
  1145. {
  1146. const uint32_t c = isMono ? 0 : i;
  1147. for (uint32_t k=0; k < frames; ++k)
  1148. {
  1149. bufValue = inBuffer[c][k];
  1150. outBuffer[i][k] = (outBuffer[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1151. }
  1152. }
  1153. // Balance
  1154. if (doBalance)
  1155. {
  1156. isPair = (i % 2 == 0);
  1157. if (isPair)
  1158. {
  1159. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1160. carla_copyFloats(oldBufLeft, outBuffer[i], frames);
  1161. }
  1162. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1163. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1164. for (uint32_t k=0; k < frames; ++k)
  1165. {
  1166. if (isPair)
  1167. {
  1168. // left
  1169. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1170. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  1171. }
  1172. else
  1173. {
  1174. // right
  1175. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  1176. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  1177. }
  1178. }
  1179. }
  1180. // Volume
  1181. if (doVolume)
  1182. {
  1183. for (uint32_t k=0; k < frames; ++k)
  1184. outBuffer[i][k] *= pData->postProc.volume;
  1185. }
  1186. }
  1187. } // End of Post-processing
  1188. #endif
  1189. // --------------------------------------------------------------------------------------------------------
  1190. // Midi out
  1191. if (! fMidiBuffer.isEmpty())
  1192. {
  1193. if (pData->event.portOut != nullptr)
  1194. {
  1195. for (juce::MidiBufferIterator it = fMidiBuffer.cbegin(), end = fMidiBuffer.cend(); it != end; ++it)
  1196. {
  1197. const juce::MidiMessageMetadata metadata(*it);
  1198. CARLA_SAFE_ASSERT_BREAK(metadata.samplePosition >= 0);
  1199. CARLA_SAFE_ASSERT_BREAK(metadata.samplePosition < static_cast<int>(frames));
  1200. CARLA_SAFE_ASSERT_BREAK(metadata.numBytes > 0);
  1201. CARLA_SAFE_ASSERT_CONTINUE(metadata.numBytes <= 0xff);
  1202. if (! pData->event.portOut->writeMidiEvent(static_cast<uint32_t>(metadata.samplePosition),
  1203. static_cast<uint8_t>(metadata.numBytes),
  1204. metadata.data))
  1205. break;
  1206. }
  1207. }
  1208. fMidiBuffer.clear();
  1209. }
  1210. // --------------------------------------------------------------------------------------------------------
  1211. pData->singleMutex.unlock();
  1212. return true;
  1213. }
  1214. void bufferSizeChanged(const uint32_t newBufferSize) override
  1215. {
  1216. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1217. carla_debug("CarlaPluginJuce::bufferSizeChanged(%i)", newBufferSize);
  1218. fAudioBuffer.setSize(static_cast<int>(std::max<uint32_t>(pData->audioIn.count, pData->audioOut.count)), static_cast<int>(newBufferSize));
  1219. if (pData->active)
  1220. {
  1221. deactivate();
  1222. activate();
  1223. }
  1224. }
  1225. void sampleRateChanged(const double newSampleRate) override
  1226. {
  1227. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1228. carla_debug("CarlaPluginJuce::sampleRateChanged(%g)", newSampleRate);
  1229. if (pData->active)
  1230. {
  1231. deactivate();
  1232. activate();
  1233. }
  1234. }
  1235. // -------------------------------------------------------------------
  1236. // Misc
  1237. void idle() override
  1238. {
  1239. if (fNeedsUpdate)
  1240. {
  1241. fNeedsUpdate = false;
  1242. pData->engine->callback(true, true, ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0, 0.0f, nullptr);
  1243. }
  1244. CarlaPlugin::idle();
  1245. }
  1246. // -------------------------------------------------------------------
  1247. // Plugin buffers
  1248. // nothing
  1249. // -------------------------------------------------------------------
  1250. // Post-poned UI Stuff
  1251. // nothing
  1252. // -------------------------------------------------------------------
  1253. void* getNativeHandle() const noexcept override
  1254. {
  1255. return (fInstance != nullptr) ? getPlatformSpecificDataForAll(fInstance) : nullptr;
  1256. }
  1257. // -------------------------------------------------------------------
  1258. protected:
  1259. void audioProcessorParameterChanged(juce::AudioProcessor*, int index, float value) override
  1260. {
  1261. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1262. const uint32_t uindex(static_cast<uint32_t>(index));
  1263. const float fixedValue(pData->param.getFixedValue(uindex, value));
  1264. CarlaPlugin::setParameterValue(static_cast<uint32_t>(index), fixedValue, false, true, true);
  1265. }
  1266. void audioProcessorChanged(juce::AudioProcessor*, const ChangeDetails& details) override
  1267. {
  1268. if (details.parameterInfoChanged || details.programChanged)
  1269. fNeedsUpdate = true;
  1270. }
  1271. void audioProcessorParameterChangeGestureBegin(juce::AudioProcessor*, int index) override
  1272. {
  1273. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1274. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), true);
  1275. }
  1276. void audioProcessorParameterChangeGestureEnd(juce::AudioProcessor*, int index) override
  1277. {
  1278. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  1279. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), false);
  1280. }
  1281. juce::Optional<juce::AudioPlayHead::PositionInfo> getPosition() const override
  1282. {
  1283. return fPosInfo;
  1284. }
  1285. // -------------------------------------------------------------------
  1286. public:
  1287. bool init(const CarlaPluginPtr plugin,
  1288. const char* const filename, const char* const name, const char* const label,
  1289. const int64_t uniqueId, const uint options, const char* const format)
  1290. {
  1291. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1292. // ---------------------------------------------------------------
  1293. // first checks
  1294. if (pData->client != nullptr)
  1295. {
  1296. pData->engine->setLastError("Plugin client is already registered");
  1297. return false;
  1298. }
  1299. if (format == nullptr || format[0] == '\0')
  1300. {
  1301. pData->engine->setLastError("null format");
  1302. return false;
  1303. }
  1304. // AU requires label
  1305. if (std::strcmp(format, "AU") == 0)
  1306. {
  1307. if (label == nullptr || label[0] == '\0')
  1308. {
  1309. pData->engine->setLastError("null label");
  1310. return false;
  1311. }
  1312. }
  1313. juce::String fileOrIdentifier;
  1314. if (std::strcmp(format, "AU") == 0)
  1315. {
  1316. fileOrIdentifier = label;
  1317. }
  1318. else
  1319. {
  1320. // VST2 and VST3 require filename
  1321. if (filename == nullptr || filename[0] == '\0')
  1322. {
  1323. pData->engine->setLastError("null filename");
  1324. return false;
  1325. }
  1326. juce::String jfilename(filename);
  1327. #ifdef CARLA_OS_WIN
  1328. // Fix for wine usage
  1329. if (juce::File("Z:\\usr\\").isDirectory() && filename[0] == '/')
  1330. {
  1331. jfilename.replace("/", "\\");
  1332. jfilename = "Z:" + jfilename;
  1333. }
  1334. #endif
  1335. fileOrIdentifier = jfilename;
  1336. if (label != nullptr && label[0] != '\0')
  1337. fDesc.name = label;
  1338. }
  1339. /**/ if (std::strcmp(format, "AU") == 0)
  1340. {
  1341. #if JUCE_PLUGINHOST_AU
  1342. fFormatManager.addFormat(new juce::AudioUnitPluginFormat());
  1343. #endif
  1344. }
  1345. else if (std::strcmp(format, "VST2") == 0)
  1346. {
  1347. #if JUCE_PLUGINHOST_VST
  1348. fFormatManager.addFormat(new juce::VSTPluginFormat());
  1349. #endif
  1350. }
  1351. else if (std::strcmp(format, "VST3") == 0)
  1352. {
  1353. #if JUCE_PLUGINHOST_VST3
  1354. fFormatManager.addFormat(new juce::VST3PluginFormat());
  1355. #endif
  1356. }
  1357. else
  1358. {
  1359. fFormatManager.addDefaultFormats();
  1360. }
  1361. {
  1362. juce::OwnedArray<juce::PluginDescription> pluginDescriptions;
  1363. juce::KnownPluginList plist;
  1364. {
  1365. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1366. const ScopedAbortCatcher sac;
  1367. #endif
  1368. for (int i = 0; i < fFormatManager.getNumFormats(); ++i)
  1369. {
  1370. juce::AudioPluginFormat* const apformat = fFormatManager.getFormat(i);
  1371. CARLA_SAFE_ASSERT_CONTINUE(apformat != nullptr);
  1372. carla_debug("Trying to load '%s' plugin with format '%s'", fileOrIdentifier.toRawUTF8(), apformat->getName().toRawUTF8());
  1373. try {
  1374. plist.scanAndAddFile(fileOrIdentifier, true, pluginDescriptions, *apformat);
  1375. } CARLA_SAFE_EXCEPTION_CONTINUE("scanAndAddFile")
  1376. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1377. if (sac.wasTriggered())
  1378. {
  1379. carla_stderr("WARNING: Caught exception while scanning file, will not load this plugin");
  1380. pluginDescriptions.clearQuick(false);
  1381. break;
  1382. }
  1383. #endif
  1384. }
  1385. }
  1386. if (pluginDescriptions.size() == 0)
  1387. {
  1388. pData->engine->setLastError("Failed to get plugin description");
  1389. return false;
  1390. }
  1391. fDesc = *pluginDescriptions[0];
  1392. }
  1393. if (uniqueId != 0)
  1394. fDesc.uniqueId = static_cast<int>(uniqueId);
  1395. juce::String error;
  1396. {
  1397. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1398. const ScopedAbortCatcher sac;
  1399. #endif
  1400. try {
  1401. fInstance = fFormatManager.createPluginInstance(fDesc,
  1402. pData->engine->getSampleRate(),
  1403. static_cast<int>(pData->engine->getBufferSize()),
  1404. error);
  1405. } CARLA_SAFE_EXCEPTION("createPluginInstance")
  1406. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  1407. if (sac.wasTriggered())
  1408. {
  1409. fInstance = nullptr;
  1410. carla_stderr("WARNING: Caught exception while instantiating, will not load this plugin");
  1411. }
  1412. #endif
  1413. }
  1414. if (fInstance == nullptr)
  1415. {
  1416. pData->engine->setLastError(error.toRawUTF8());
  1417. return false;
  1418. }
  1419. fInstance->fillInPluginDescription(fDesc);
  1420. fInstance->setPlayHead(this);
  1421. fInstance->addListener(this);
  1422. fFormatName = format;
  1423. // ---------------------------------------------------------------
  1424. // get info
  1425. if (name != nullptr && name[0] != '\0')
  1426. pData->name = pData->engine->getUniquePluginName(name);
  1427. else
  1428. pData->name = pData->engine->getUniquePluginName(fInstance->getName().toRawUTF8());
  1429. if (filename != nullptr && filename[0] != '\0')
  1430. pData->filename = carla_strdup(filename);
  1431. // ---------------------------------------------------------------
  1432. // register client
  1433. pData->client = pData->engine->addClient(plugin);
  1434. if (pData->client == nullptr || ! pData->client->isOk())
  1435. {
  1436. pData->engine->setLastError("Failed to register plugin client");
  1437. return false;
  1438. }
  1439. // ---------------------------------------------------------------
  1440. // set options
  1441. pData->options = 0x0;
  1442. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1443. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  1444. if (fInstance->acceptsMidi())
  1445. {
  1446. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  1447. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1448. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  1449. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1450. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  1451. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1452. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  1453. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1454. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  1455. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1456. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  1457. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  1458. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1459. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  1460. }
  1461. if (fInstance->getNumPrograms() > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  1462. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  1463. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1464. return true;
  1465. }
  1466. private:
  1467. juce::PluginDescription fDesc;
  1468. juce::AudioPluginFormatManager fFormatManager;
  1469. std::unique_ptr<juce::AudioPluginInstance> fInstance;
  1470. juce::AudioSampleBuffer fAudioBuffer;
  1471. juce::MidiBuffer fMidiBuffer;
  1472. PositionInfo fPosInfo;
  1473. juce::MemoryBlock fChunk;
  1474. juce::String fFormatName;
  1475. CarlaScopedPointer<JucePluginWindow> fWindow;
  1476. bool fNeedsUpdate;
  1477. bool isJuceSaveFormat(const void* const data, const std::size_t dataSize)
  1478. {
  1479. if (fFormatName != "VST2")
  1480. return true;
  1481. if (dataSize < 160)
  1482. return false;
  1483. const int32_t* const set = (const int32_t*)data;
  1484. // chunkMagic
  1485. if (! compareMagic(set[0], "CcnK"))
  1486. return false;
  1487. // version
  1488. if (fxbSwap(set[3]) > 1)
  1489. return false;
  1490. // fxMagic, data contents depend on this value
  1491. if (compareMagic(set[2], "FBCh") || compareMagic(set[2], "FJuc"))
  1492. {
  1493. const int32_t chunkSize = fxbSwap(set[39]);
  1494. return static_cast<std::size_t>(chunkSize + 160) == dataSize;
  1495. }
  1496. if (compareMagic(set[2], "FxBk"))
  1497. {
  1498. const int32_t numPrograms = fxbSwap(set[6]);
  1499. return numPrograms >= 1;
  1500. }
  1501. return false;
  1502. }
  1503. static bool compareMagic(int32_t magic, const char* name) noexcept
  1504. {
  1505. return magic == (int32_t)juce::ByteOrder::littleEndianInt (name)
  1506. || magic == (int32_t)juce::ByteOrder::bigEndianInt (name);
  1507. }
  1508. static int32_t fxbSwap(const int32_t x) noexcept
  1509. {
  1510. return (int32_t)juce::ByteOrder::swapIfLittleEndian ((uint32_t) x);
  1511. }
  1512. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJuce)
  1513. };
  1514. CARLA_BACKEND_END_NAMESPACE
  1515. #endif // USING_JUCE
  1516. // -------------------------------------------------------------------------------------------------------------------
  1517. CARLA_BACKEND_START_NAMESPACE
  1518. CarlaPluginPtr CarlaPlugin::newJuce(const Initializer& init, const char* const format)
  1519. {
  1520. carla_debug("CarlaPlugin::newJuce({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s)",
  1521. init.engine, init.filename, init.name, init.label, init.uniqueId, format);
  1522. #ifdef USING_JUCE
  1523. std::shared_ptr<CarlaPluginJuce> plugin(new CarlaPluginJuce(init.engine, init.id));
  1524. if (! plugin->init(plugin, init.filename, init.name, init.label, init.uniqueId, init.options, format))
  1525. return nullptr;
  1526. return plugin;
  1527. #else
  1528. init.engine->setLastError("Juce-based plugin not available");
  1529. return nullptr;
  1530. // unused
  1531. (void)format;
  1532. #endif
  1533. }
  1534. CARLA_BACKEND_END_NAMESPACE
  1535. // -------------------------------------------------------------------------------------------------------------------