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.

CarlaPluginCLAP.cpp 116KB

2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417
  1. /*
  2. * Carla CLAP Plugin
  3. * Copyright (C) 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. #include "CarlaBackendUtils.hpp"
  20. #include "CarlaClapUtils.hpp"
  21. #include "CarlaMathUtils.hpp"
  22. #include "CarlaPluginUI.hpp"
  23. #ifdef CARLA_OS_MAC
  24. # include "CarlaMacUtils.hpp"
  25. # import <Foundation/Foundation.h>
  26. #endif
  27. #include "water/files/File.h"
  28. #include "water/misc/Time.h"
  29. #if defined(CLAP_WINDOW_API_NATIVE) && defined(_POSIX_VERSION)
  30. # if defined(CARLA_OS_LINUX)
  31. # define CARLA_CLAP_POSIX_EPOLL
  32. # include <sys/epoll.h>
  33. # else
  34. # include <sys/event.h>
  35. # include <sys/types.h>
  36. # endif
  37. #endif
  38. // FIXME
  39. // #ifndef CLAP_WINDOW_API_NATIVE
  40. // #define CLAP_WINDOW_API_NATIVE ""
  41. // #define HAVE_X11 1
  42. // #endif
  43. CARLA_BACKEND_START_NAMESPACE
  44. // --------------------------------------------------------------------------------------------------------------------
  45. struct ClapEventData {
  46. uint16_t clapPortIndex;
  47. uint32_t supportedDialects;
  48. CarlaEngineEventPort* port;
  49. };
  50. struct CarlaPluginClapEventData {
  51. uint32_t portCount;
  52. ClapEventData* portData;
  53. ClapEventData* defaultPort; // either this->portData[x] or pData->portIn/Out
  54. CarlaPluginClapEventData() noexcept
  55. : portCount(0),
  56. portData(nullptr),
  57. defaultPort(nullptr) {}
  58. ~CarlaPluginClapEventData() noexcept
  59. {
  60. CARLA_SAFE_ASSERT_INT(portCount == 0, portCount);
  61. CARLA_SAFE_ASSERT(portData == nullptr);
  62. CARLA_SAFE_ASSERT(defaultPort == nullptr);
  63. }
  64. void createNew(const uint32_t newCount)
  65. {
  66. CARLA_SAFE_ASSERT_INT(portCount == 0, portCount);
  67. CARLA_SAFE_ASSERT_RETURN(portData == nullptr,);
  68. CARLA_SAFE_ASSERT_RETURN(defaultPort == nullptr,);
  69. CARLA_SAFE_ASSERT_RETURN(newCount > 0,);
  70. portData = new ClapEventData[newCount];
  71. portCount = newCount;
  72. defaultPort = nullptr;
  73. }
  74. void clear(CarlaEngineEventPort* const portToIgnore) noexcept
  75. {
  76. if (portData != nullptr)
  77. {
  78. for (uint32_t i=0; i < portCount; ++i)
  79. {
  80. if (portData[i].port != nullptr)
  81. {
  82. if (portData[i].port != portToIgnore)
  83. delete portData[i].port;
  84. portData[i].port = nullptr;
  85. }
  86. }
  87. delete[] portData;
  88. portData = nullptr;
  89. }
  90. portCount = 0;
  91. defaultPort = nullptr;
  92. }
  93. void initBuffers() const noexcept
  94. {
  95. for (uint32_t i=0; i < portCount; ++i)
  96. {
  97. if (portData[i].port != nullptr && (defaultPort == nullptr || portData[i].port != defaultPort->port))
  98. portData[i].port->initBuffer();
  99. }
  100. }
  101. CARLA_DECLARE_NON_COPYABLE(CarlaPluginClapEventData)
  102. };
  103. #ifdef _POSIX_VERSION
  104. // --------------------------------------------------------------------------------------------------------------------
  105. struct HostPosixFileDescriptorDetails {
  106. int hostFd;
  107. int pluginFd;
  108. clap_posix_fd_flags_t flags;
  109. };
  110. static constexpr const HostPosixFileDescriptorDetails kPosixFileDescriptorFallback = { -1, -1, 0x0 };
  111. static /* */ HostPosixFileDescriptorDetails kPosixFileDescriptorFallbackNC = { -1, -1, 0x0 };
  112. #endif
  113. // --------------------------------------------------------------------------------------------------------------------
  114. struct HostTimerDetails {
  115. clap_id clapId;
  116. uint32_t periodInMs;
  117. uint32_t lastCallTimeInMs;
  118. };
  119. static constexpr const HostTimerDetails kTimerFallback = { CLAP_INVALID_ID, 0, 0 };
  120. static /* */ HostTimerDetails kTimerFallbackNC = { CLAP_INVALID_ID, 0, 0 };
  121. // --------------------------------------------------------------------------------------------------------------------
  122. struct carla_clap_host : clap_host_t {
  123. class Callbacks {
  124. public:
  125. virtual ~Callbacks() {}
  126. virtual void clapRequestRestart() = 0;
  127. virtual void clapRequestProcess() = 0;
  128. virtual void clapRequestCallback() = 0;
  129. virtual void clapMarkDirty() = 0;
  130. virtual void clapLatencyChanged() = 0;
  131. #ifdef CLAP_WINDOW_API_NATIVE
  132. // gui
  133. virtual void clapGuiResizeHintsChanged() = 0;
  134. virtual bool clapGuiRequestResize(uint width, uint height) = 0;
  135. virtual bool clapGuiRequestShow() = 0;
  136. virtual bool clapGuiRequestHide() = 0;
  137. virtual void clapGuiClosed(bool wasDestroyed) = 0;
  138. #ifdef _POSIX_VERSION
  139. // posix fd
  140. virtual bool clapRegisterPosixFD(int fd, clap_posix_fd_flags_t flags) = 0;
  141. virtual bool clapModifyPosixFD(int fd, clap_posix_fd_flags_t flags) = 0;
  142. virtual bool clapUnregisterPosixFD(int fd) = 0;
  143. #endif
  144. // timer
  145. virtual bool clapRegisterTimer(uint32_t periodInMs, clap_id* timerId) = 0;
  146. virtual bool clapUnregisterTimer(clap_id timerId) = 0;
  147. #endif
  148. };
  149. Callbacks* const hostCallbacks;
  150. clap_host_latency_t latency;
  151. clap_host_state_t state;
  152. #ifdef CLAP_WINDOW_API_NATIVE
  153. clap_host_gui_t gui;
  154. #ifdef _POSIX_VERSION
  155. clap_host_posix_fd_support_t posixFD;
  156. #endif
  157. clap_host_timer_support_t timer;
  158. #endif
  159. carla_clap_host(Callbacks* const hostCb)
  160. : hostCallbacks(hostCb)
  161. {
  162. clap_version = CLAP_VERSION;
  163. host_data = this;
  164. name = "Carla";
  165. vendor = "falkTX";
  166. url = "https://kx.studio/carla";
  167. version = CARLA_VERSION_STRING;
  168. get_extension = carla_get_extension;
  169. request_restart = carla_request_restart;
  170. request_process = carla_request_process;
  171. request_callback = carla_request_callback;
  172. latency.changed = carla_latency_changed;
  173. state.mark_dirty = carla_mark_dirty;
  174. #ifdef CLAP_WINDOW_API_NATIVE
  175. gui.resize_hints_changed = carla_resize_hints_changed;
  176. gui.request_resize = carla_request_resize;
  177. gui.request_show = carla_request_show;
  178. gui.request_hide = carla_request_hide;
  179. gui.closed = carla_closed;
  180. #ifdef _POSIX_VERSION
  181. posixFD.register_fd = carla_register_fd;
  182. posixFD.modify_fd = carla_modify_fd;
  183. posixFD.unregister_fd = carla_unregister_fd;
  184. #endif
  185. timer.register_timer = carla_register_timer;
  186. timer.unregister_timer = carla_unregister_timer;
  187. #endif
  188. }
  189. static CLAP_ABI const void* carla_get_extension(const clap_host_t* const host, const char* const extension_id)
  190. {
  191. carla_clap_host* const self = static_cast<carla_clap_host*>(host->host_data);
  192. if (std::strcmp(extension_id, CLAP_EXT_LATENCY) == 0)
  193. return &self->latency;
  194. if (std::strcmp(extension_id, CLAP_EXT_STATE) == 0)
  195. return &self->state;
  196. #ifdef CLAP_WINDOW_API_NATIVE
  197. if (std::strcmp(extension_id, CLAP_EXT_GUI) == 0)
  198. return &self->gui;
  199. #ifdef _POSIX_VERSION
  200. if (std::strcmp(extension_id, CLAP_EXT_POSIX_FD_SUPPORT) == 0)
  201. return &self->posixFD;
  202. #endif
  203. if (std::strcmp(extension_id, CLAP_EXT_TIMER_SUPPORT) == 0)
  204. return &self->timer;
  205. #endif
  206. carla_stderr("Plugin requested unsupported CLAP extension '%s'", extension_id);
  207. return nullptr;
  208. }
  209. static CLAP_ABI void carla_request_restart(const clap_host_t* const host)
  210. {
  211. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRequestRestart();
  212. }
  213. static CLAP_ABI void carla_request_process(const clap_host_t* const host)
  214. {
  215. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRequestProcess();
  216. }
  217. static CLAP_ABI void carla_request_callback(const clap_host_t* const host)
  218. {
  219. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRequestCallback();
  220. }
  221. static CLAP_ABI void carla_latency_changed(const clap_host_t* const host)
  222. {
  223. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapLatencyChanged();
  224. }
  225. static CLAP_ABI void carla_mark_dirty(const clap_host_t* const host)
  226. {
  227. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapMarkDirty();
  228. }
  229. #ifdef CLAP_WINDOW_API_NATIVE
  230. static CLAP_ABI void carla_resize_hints_changed(const clap_host_t* const host)
  231. {
  232. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiResizeHintsChanged();
  233. }
  234. static CLAP_ABI bool carla_request_resize(const clap_host_t* const host, const uint32_t width, const uint32_t height)
  235. {
  236. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiRequestResize(width, height);
  237. }
  238. static CLAP_ABI bool carla_request_show(const clap_host_t* const host)
  239. {
  240. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiRequestShow();
  241. }
  242. static CLAP_ABI bool carla_request_hide(const clap_host_t* const host)
  243. {
  244. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiRequestHide();
  245. }
  246. static CLAP_ABI void carla_closed(const clap_host_t* const host, bool was_destroyed)
  247. {
  248. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiClosed(was_destroyed);
  249. }
  250. #ifdef _POSIX_VERSION
  251. static CLAP_ABI bool carla_register_fd(const clap_host_t* const host, const int fd, const clap_posix_fd_flags_t flags)
  252. {
  253. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRegisterPosixFD(fd, flags);
  254. }
  255. static CLAP_ABI bool carla_modify_fd(const clap_host_t* const host, const int fd, const clap_posix_fd_flags_t flags)
  256. {
  257. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapModifyPosixFD(fd, flags);
  258. }
  259. static CLAP_ABI bool carla_unregister_fd(const clap_host_t* const host, const int fd)
  260. {
  261. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapUnregisterPosixFD(fd);
  262. }
  263. #endif
  264. static CLAP_ABI bool carla_register_timer(const clap_host_t* const host, const uint32_t period_ms, clap_id* const timer_id)
  265. {
  266. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRegisterTimer(period_ms, timer_id);
  267. }
  268. static CLAP_ABI bool carla_unregister_timer(const clap_host_t* const host, const clap_id timer_id)
  269. {
  270. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapUnregisterTimer(timer_id);
  271. }
  272. #endif
  273. };
  274. // --------------------------------------------------------------------------------------------------------------------
  275. struct carla_clap_input_audio_buffers {
  276. clap_audio_buffer_const_t* buffers;
  277. clap_audio_buffer_extra_data_t* extra;
  278. uint32_t count;
  279. carla_clap_input_audio_buffers() noexcept
  280. : buffers(nullptr),
  281. extra(nullptr),
  282. count(0) {}
  283. ~carla_clap_input_audio_buffers()
  284. {
  285. delete[] buffers;
  286. delete[] extra;
  287. }
  288. void realloc(const uint32_t portCount)
  289. {
  290. delete[] buffers;
  291. delete[] extra;
  292. count = portCount;
  293. if (portCount != 0)
  294. {
  295. buffers = new clap_audio_buffer_const_t[portCount];
  296. extra = new clap_audio_buffer_extra_data_t[portCount];
  297. carla_zeroStructs(buffers, portCount);
  298. carla_zeroStructs(extra, portCount);
  299. }
  300. else
  301. {
  302. buffers = nullptr;
  303. extra = nullptr;
  304. }
  305. }
  306. const clap_audio_buffer_t* cast() const noexcept
  307. {
  308. return static_cast<const clap_audio_buffer_t*>(static_cast<const void*>(buffers));
  309. }
  310. };
  311. struct carla_clap_output_audio_buffers {
  312. clap_audio_buffer_t* buffers;
  313. clap_audio_buffer_extra_data_t* extra;
  314. uint32_t count;
  315. carla_clap_output_audio_buffers() noexcept
  316. : buffers(nullptr),
  317. extra(nullptr),
  318. count(0) {}
  319. ~carla_clap_output_audio_buffers()
  320. {
  321. delete[] buffers;
  322. delete[] extra;
  323. }
  324. void realloc(const uint32_t portCount)
  325. {
  326. delete[] buffers;
  327. delete[] extra;
  328. count = portCount;
  329. if (portCount != 0)
  330. {
  331. buffers = new clap_audio_buffer_t[portCount];
  332. extra = new clap_audio_buffer_extra_data_t[portCount];
  333. carla_zeroStructs(buffers, portCount);
  334. carla_zeroStructs(extra, portCount);
  335. }
  336. else
  337. {
  338. buffers = nullptr;
  339. extra = nullptr;
  340. }
  341. }
  342. };
  343. // --------------------------------------------------------------------------------------------------------------------
  344. struct carla_clap_input_events : clap_input_events_t, CarlaPluginClapEventData {
  345. union Event {
  346. clap_event_header_t header;
  347. clap_event_param_value_t param;
  348. clap_event_param_gesture_t gesture;
  349. clap_event_midi_t midi;
  350. clap_event_note_t note;
  351. clap_event_midi_sysex_t sysex;
  352. };
  353. struct ScheduledParameterUpdate {
  354. bool updated;
  355. double value;
  356. clap_id clapId;
  357. void* cookie;
  358. ScheduledParameterUpdate()
  359. : updated(false),
  360. value(0.f),
  361. clapId(0),
  362. cookie(0) {}
  363. };
  364. Event* events;
  365. ScheduledParameterUpdate* updatedParams;
  366. uint32_t numEventsAllocated;
  367. uint32_t numEventsUsed;
  368. uint32_t numParams;
  369. carla_clap_input_events()
  370. : CarlaPluginClapEventData(),
  371. events(nullptr),
  372. updatedParams(nullptr),
  373. numEventsAllocated(0),
  374. numEventsUsed(0),
  375. numParams(0)
  376. {
  377. ctx = this;
  378. size = carla_size;
  379. get = carla_get;
  380. }
  381. ~carla_clap_input_events()
  382. {
  383. delete[] events;
  384. delete[] updatedParams;
  385. }
  386. // called on plugin reload
  387. // NOTE: clapId and cookie must be separately set outside this function
  388. void realloc(CarlaEngineEventPort* const defPortIn, const uint32_t portCount, const uint32_t paramCount)
  389. {
  390. numEventsUsed = 0;
  391. numParams = paramCount;
  392. delete[] events;
  393. delete[] updatedParams;
  394. if (portCount != 0 || paramCount != 0)
  395. {
  396. static_assert(kPluginMaxMidiEvents > MAX_MIDI_NOTE, "Enough space for input events");
  397. numEventsAllocated = paramCount * 2 + kPluginMaxMidiEvents * std::max(1u, portCount);
  398. events = new Event[numEventsAllocated];
  399. updatedParams = new ScheduledParameterUpdate[paramCount];
  400. }
  401. else
  402. {
  403. numEventsAllocated = 0;
  404. events = nullptr;
  405. updatedParams = nullptr;
  406. }
  407. CarlaPluginClapEventData::clear(defPortIn);
  408. if (portCount != 0)
  409. CarlaPluginClapEventData::createNew(portCount);
  410. }
  411. // used for temporary copies (this instance must be empty)
  412. void reallocEqualTo(const carla_clap_input_events& other)
  413. {
  414. numParams = other.numParams;
  415. numEventsAllocated = other.numEventsAllocated;
  416. if (numEventsAllocated != 0)
  417. {
  418. events = new Event[numEventsAllocated];
  419. updatedParams = new ScheduledParameterUpdate[numParams];
  420. for (uint32_t i=0; i<numParams; ++i)
  421. {
  422. updatedParams[i].clapId = other.updatedParams[i].clapId;
  423. updatedParams[i].cookie = other.updatedParams[i].cookie;
  424. }
  425. }
  426. }
  427. void swap(carla_clap_input_events& other)
  428. {
  429. CARLA_SAFE_ASSERT_RETURN(numParams == other.numParams,);
  430. CARLA_SAFE_ASSERT_RETURN(numEventsAllocated == other.numEventsAllocated,);
  431. std::swap(numEventsUsed, other.numEventsUsed);
  432. std::swap(updatedParams, other.updatedParams);
  433. std::swap(events, other.events);
  434. }
  435. const clap_input_events_t* cast() const noexcept
  436. {
  437. return static_cast<const clap_input_events_t*>(this);
  438. }
  439. // called just before plugin processing
  440. void handleScheduledParameterUpdates()
  441. {
  442. uint32_t count = 0;
  443. for (uint32_t i=0; i<numParams; ++i)
  444. {
  445. if (updatedParams[i].updated)
  446. {
  447. events[count++].param = {
  448. { sizeof(clap_event_param_value_t), 0, 0, CLAP_EVENT_PARAM_VALUE, 0 },
  449. updatedParams[i].clapId,
  450. updatedParams[i].cookie,
  451. -1, -1, -1, -1,
  452. updatedParams[i].value
  453. };
  454. updatedParams[i].updated = false;
  455. }
  456. }
  457. numEventsUsed = count;
  458. }
  459. // called when a parameter is set from non-rt thread
  460. void setParamValue(const uint32_t index, const float value) noexcept
  461. {
  462. CARLA_SAFE_ASSERT_RETURN(index < numParams,);
  463. updatedParams[index].value = value;
  464. updatedParams[index].updated = true;
  465. }
  466. // called when a parameter is set from rt thread
  467. void setParamValueRT(const uint32_t index, const float value, const uint32_t frameOffset) noexcept
  468. {
  469. CARLA_SAFE_ASSERT_RETURN(index < numParams,);
  470. if (numEventsUsed == numEventsAllocated)
  471. return;
  472. events[numEventsUsed++].param = {
  473. { sizeof(clap_event_param_value_t), frameOffset, 0, CLAP_EVENT_PARAM_VALUE, CLAP_EVENT_IS_LIVE },
  474. updatedParams[index].clapId,
  475. updatedParams[index].cookie,
  476. -1, -1, -1, -1,
  477. value
  478. };
  479. }
  480. void addSimpleMidiEvent(const bool isLive, const uint16_t port, const uint32_t frameOffset, const uint8_t data[3])
  481. {
  482. if (numEventsUsed == numEventsAllocated)
  483. return;
  484. events[numEventsUsed++].midi = {
  485. { sizeof(clap_event_midi_t), frameOffset, 0, CLAP_EVENT_MIDI, isLive ? (uint32_t)CLAP_EVENT_IS_LIVE : 0u },
  486. port,
  487. { data[0], data[1], data[2] }
  488. };
  489. }
  490. void addSimpleNoteEvent(const bool isLive, const int16_t port, const uint32_t frameOffset,
  491. const uint8_t channel, const uint8_t key, const uint8_t velocity)
  492. {
  493. if (numEventsUsed == numEventsAllocated)
  494. return;
  495. const uint16_t eventType = velocity > 0 ? CLAP_EVENT_NOTE_ON : CLAP_EVENT_NOTE_OFF;
  496. events[numEventsUsed++].note = {
  497. { sizeof(clap_event_note_t), frameOffset, 0, eventType, isLive ? (uint32_t)CLAP_EVENT_IS_LIVE : 0u },
  498. -1,
  499. port,
  500. channel,
  501. key,
  502. static_cast<double>(velocity) / 127.0
  503. };
  504. }
  505. static CLAP_ABI uint32_t carla_size(const clap_input_events_t* const list) noexcept
  506. {
  507. return static_cast<const carla_clap_input_events*>(list->ctx)->numEventsUsed;
  508. }
  509. static CLAP_ABI const clap_event_header_t* carla_get(const clap_input_events_t* const list, const uint32_t index) noexcept
  510. {
  511. return &static_cast<const carla_clap_input_events*>(list->ctx)->events[index].header;
  512. }
  513. };
  514. // --------------------------------------------------------------------------------------------------------------------
  515. struct carla_clap_output_events : clap_output_events_t, CarlaPluginClapEventData {
  516. union Event {
  517. clap_event_header_t header;
  518. clap_event_param_value_t param;
  519. clap_event_midi_t midi;
  520. };
  521. Event* events;
  522. uint32_t numEventsAllocated;
  523. uint32_t numEventsUsed;
  524. carla_clap_output_events()
  525. : events(nullptr),
  526. numEventsAllocated(0),
  527. numEventsUsed(0)
  528. {
  529. ctx = this;
  530. try_push = carla_try_push;
  531. }
  532. ~carla_clap_output_events()
  533. {
  534. delete[] events;
  535. }
  536. // called on plugin reload
  537. void realloc(CarlaEngineEventPort* const defPortOut, const uint32_t portCount, const uint32_t paramCount)
  538. {
  539. numEventsUsed = 0;
  540. delete[] events;
  541. if (portCount != 0 || paramCount != 0)
  542. {
  543. numEventsAllocated = paramCount + kPluginMaxMidiEvents * std::max(1u, portCount);
  544. events = new Event[numEventsAllocated];
  545. }
  546. else
  547. {
  548. numEventsAllocated = 0;
  549. events = nullptr;
  550. }
  551. CarlaPluginClapEventData::clear(defPortOut);
  552. if (portCount != 0)
  553. CarlaPluginClapEventData::createNew(portCount);
  554. }
  555. const clap_output_events_t* cast() const noexcept
  556. {
  557. return static_cast<const clap_output_events_t*>(this);
  558. }
  559. bool tryPush(const clap_event_header_t* const event)
  560. {
  561. if (numEventsUsed == numEventsAllocated)
  562. return false;
  563. Event e;
  564. switch (event->type)
  565. {
  566. case CLAP_EVENT_PARAM_VALUE:
  567. e.param = *static_cast<const clap_event_param_value_t*>(static_cast<const void*>(event));
  568. break;
  569. case CLAP_EVENT_MIDI:
  570. e.midi = *static_cast<const clap_event_midi_t*>(static_cast<const void*>(event));
  571. break;
  572. default:
  573. return false;
  574. }
  575. events[numEventsUsed++] = e;
  576. return true;
  577. }
  578. static CLAP_ABI bool carla_try_push(const clap_output_events_t* const list, const clap_event_header_t* const event)
  579. {
  580. return static_cast<carla_clap_output_events*>(list->ctx)->tryPush(event);
  581. }
  582. };
  583. // --------------------------------------------------------------------------------------------------------------------
  584. class CarlaPluginCLAP : public CarlaPlugin,
  585. #ifdef CLAP_WINDOW_API_NATIVE
  586. private CarlaPluginUI::Callback,
  587. #endif
  588. private carla_clap_host::Callbacks
  589. {
  590. public:
  591. CarlaPluginCLAP(CarlaEngine* const engine, const uint id)
  592. : CarlaPlugin(engine, id),
  593. fPlugin(nullptr),
  594. fPluginDescriptor(nullptr),
  595. fPluginEntry(nullptr),
  596. fHost(this),
  597. fExtensions(),
  598. fInputAudioBuffers(),
  599. fOutputAudioBuffers(),
  600. fInputEvents(),
  601. fOutputEvents(),
  602. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  603. fAudioOutBuffers(nullptr),
  604. #endif
  605. fLastChunk(nullptr),
  606. fLastKnownLatency(0),
  607. kEngineHasIdleOnMainThread(engine->hasIdleOnMainThread()),
  608. fNeedsParamFlush(false),
  609. fNeedsRestart(false),
  610. fNeedsProcess(false),
  611. fNeedsIdleCallback(false)
  612. {
  613. carla_debug("CarlaPluginCLAP::CarlaPluginCLAP(%p, %i)", engine, id);
  614. }
  615. ~CarlaPluginCLAP() override
  616. {
  617. carla_debug("CarlaPluginCLAP::~CarlaPluginCLAP()");
  618. runIdleCallbacksAsNeeded(false);
  619. #ifdef CLAP_WINDOW_API_NATIVE
  620. // close UI
  621. if (fUI.isCreated)
  622. showCustomUI(false);
  623. #endif
  624. pData->singleMutex.lock();
  625. pData->masterMutex.lock();
  626. if (pData->client != nullptr && pData->client->isActive())
  627. pData->client->deactivate(true);
  628. if (pData->active)
  629. {
  630. deactivate();
  631. pData->active = false;
  632. }
  633. if (fPlugin != nullptr)
  634. {
  635. fPlugin->destroy(fPlugin);
  636. fPlugin = nullptr;
  637. }
  638. if (fLastChunk != nullptr)
  639. {
  640. std::free(fLastChunk);
  641. fLastChunk = nullptr;
  642. }
  643. clearBuffers();
  644. if (fPluginEntry != nullptr)
  645. {
  646. fPluginEntry->deinit();
  647. fPluginEntry = nullptr;
  648. }
  649. }
  650. // -------------------------------------------------------------------
  651. // Information (base)
  652. PluginType getType() const noexcept override
  653. {
  654. return PLUGIN_CLAP;
  655. }
  656. PluginCategory getCategory() const noexcept override
  657. {
  658. CARLA_SAFE_ASSERT_RETURN(fPluginDescriptor != nullptr, PLUGIN_CATEGORY_NONE);
  659. if (fPluginDescriptor->features == nullptr)
  660. return PLUGIN_CATEGORY_NONE;
  661. return getPluginCategoryFromClapFeatures(fPluginDescriptor->features);
  662. }
  663. uint32_t getLatencyInFrames() const noexcept override
  664. {
  665. // under clap we can only request plugin latency in main thread,
  666. // which is unsuitable for this call
  667. return fLastKnownLatency;
  668. }
  669. // -------------------------------------------------------------------
  670. // Information (count)
  671. uint32_t getMidiInCount() const noexcept override
  672. {
  673. return fInputEvents.portCount;
  674. }
  675. uint32_t getMidiOutCount() const noexcept override
  676. {
  677. return fOutputEvents.portCount;
  678. }
  679. // -------------------------------------------------------------------
  680. // Information (current data)
  681. uint getAudioPortHints(const bool isOutput, const uint32_t portIndex) const noexcept override
  682. {
  683. uint hints = 0x0;
  684. if (isOutput)
  685. {
  686. for (uint32_t i=0, j=0; i<fOutputAudioBuffers.count; ++i, j+=fOutputAudioBuffers.buffers[i].channel_count)
  687. {
  688. if (j != portIndex)
  689. continue;
  690. if (!fOutputAudioBuffers.extra[i].isMain)
  691. hints |= AUDIO_PORT_IS_SIDECHAIN;
  692. }
  693. }
  694. else
  695. {
  696. for (uint32_t i=0, j=0; i<fInputAudioBuffers.count; ++i, j+=fInputAudioBuffers.buffers[i].channel_count)
  697. {
  698. if (j != portIndex)
  699. continue;
  700. if (!fInputAudioBuffers.extra[i].isMain)
  701. hints |= AUDIO_PORT_IS_SIDECHAIN;
  702. }
  703. }
  704. return hints;
  705. }
  706. std::size_t getChunkData(void** const dataPtr) noexcept override
  707. {
  708. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  709. CARLA_SAFE_ASSERT_RETURN(fExtensions.state != nullptr, 0);
  710. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  711. std::free(fLastChunk);
  712. clap_ostream_impl stream;
  713. if (fExtensions.state->save(fPlugin, &stream))
  714. {
  715. *dataPtr = fLastChunk = stream.buffer;
  716. runIdleCallbacksAsNeeded(false);
  717. return stream.size;
  718. }
  719. else
  720. {
  721. *dataPtr = fLastChunk = nullptr;
  722. runIdleCallbacksAsNeeded(false);
  723. return 0;
  724. }
  725. }
  726. // -------------------------------------------------------------------
  727. // Information (per-plugin data)
  728. uint getOptionsAvailable() const noexcept override
  729. {
  730. uint options = 0x0;
  731. if (fExtensions.state != nullptr)
  732. options |= PLUGIN_OPTION_USE_CHUNKS;
  733. for (uint32_t i=0; i<fInputEvents.portCount; ++i)
  734. {
  735. if (fInputEvents.portData[i].supportedDialects & CLAP_NOTE_DIALECT_MIDI)
  736. {
  737. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  738. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  739. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  740. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  741. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  742. options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  743. options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  744. break;
  745. }
  746. if (fInputEvents.portData[i].supportedDialects & CLAP_NOTE_DIALECT_CLAP)
  747. {
  748. options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  749. // nobreak, in case another port supports MIDI
  750. }
  751. }
  752. return options;
  753. }
  754. double getBestParameterValue(const uint32_t parameterId, const clap_id clapId) const noexcept
  755. {
  756. if (fInputEvents.updatedParams[parameterId].updated)
  757. return fInputEvents.updatedParams[parameterId].value;
  758. double value;
  759. CARLA_SAFE_ASSERT_RETURN(fExtensions.params->get_value(fPlugin, clapId, &value), 0.0);
  760. return value;
  761. }
  762. float getParameterValue(const uint32_t parameterId) const noexcept override
  763. {
  764. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, 0.f);
  765. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, 0.f);
  766. return getBestParameterValue(parameterId, pData->param.data[parameterId].rindex);
  767. }
  768. bool getLabel(char* const strBuf) const noexcept override
  769. {
  770. CARLA_SAFE_ASSERT_RETURN(fPluginDescriptor != nullptr, false);
  771. std::strncpy(strBuf, fPluginDescriptor->id, STR_MAX);
  772. return true;
  773. }
  774. bool getMaker(char* const strBuf) const noexcept override
  775. {
  776. CARLA_SAFE_ASSERT_RETURN(fPluginDescriptor != nullptr, false);
  777. std::strncpy(strBuf, fPluginDescriptor->vendor, STR_MAX);
  778. return true;
  779. }
  780. bool getCopyright(char* const strBuf) const noexcept override
  781. {
  782. return getMaker(strBuf);
  783. }
  784. bool getRealName(char* const strBuf) const noexcept override
  785. {
  786. CARLA_SAFE_ASSERT_RETURN(fPluginDescriptor != nullptr, false);
  787. std::strncpy(strBuf, fPluginDescriptor->name, STR_MAX);
  788. return true;
  789. }
  790. bool getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  791. {
  792. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, false);
  793. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, false);
  794. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  795. clap_param_info_t paramInfo = {};
  796. CARLA_SAFE_ASSERT_RETURN(fExtensions.params->get_info(fPlugin, parameterId, &paramInfo), false);
  797. std::strncpy(strBuf, paramInfo.name, STR_MAX);
  798. return true;
  799. }
  800. bool getParameterSymbol(const uint32_t parameterId, char* const strBuf) const noexcept override
  801. {
  802. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  803. const clap_id clapId = pData->param.data[parameterId].rindex;
  804. std::snprintf(strBuf, STR_MAX, "%u", clapId);
  805. return true;
  806. }
  807. bool getParameterText(const uint32_t parameterId, char* const strBuf) noexcept override
  808. {
  809. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, false);
  810. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, false);
  811. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  812. const clap_id clapId = pData->param.data[parameterId].rindex;
  813. const double value = getBestParameterValue(parameterId, clapId);
  814. return fExtensions.params->value_to_text(fPlugin, clapId, value, strBuf, STR_MAX);
  815. }
  816. bool getParameterGroupName(const uint32_t parameterId, char* const strBuf) const noexcept override
  817. {
  818. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, false);
  819. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, false);
  820. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  821. clap_param_info_t paramInfo = {};
  822. CARLA_SAFE_ASSERT_RETURN(fExtensions.params->get_info(fPlugin, parameterId, &paramInfo), false);
  823. if (paramInfo.module[0] == '\0')
  824. return false;
  825. if (char* const sep = std::strrchr(paramInfo.module, '/'))
  826. {
  827. paramInfo.module[STR_MAX/2-2] = sep[0] = '\0';
  828. std::snprintf(strBuf, STR_MAX, "%s:%s", paramInfo.module, paramInfo.module);
  829. return true;
  830. }
  831. return false;
  832. }
  833. // -------------------------------------------------------------------
  834. // Set data (state)
  835. // nothing
  836. // -------------------------------------------------------------------
  837. // Set data (internal stuff)
  838. #ifdef CLAP_WINDOW_API_NATIVE
  839. void setName(const char* const newName) override
  840. {
  841. CarlaPlugin::setName(newName);
  842. if (fUI.isCreated && pData->uiTitle.isEmpty())
  843. setWindowTitle(nullptr);
  844. }
  845. #endif
  846. // -------------------------------------------------------------------
  847. // Set data (plugin-specific stuff)
  848. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  849. {
  850. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  851. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  852. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  853. fInputEvents.setParamValue(parameterId, fixedValue);
  854. if (!pData->active && fExtensions.params->flush != nullptr)
  855. fNeedsParamFlush = true;
  856. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  857. }
  858. void setParameterValueRT(const uint32_t parameterId, const float value, const uint32_t frameOffset, const bool sendCallbackLater) noexcept override
  859. {
  860. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  861. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  862. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  863. fInputEvents.setParamValueRT(parameterId, fixedValue, frameOffset);
  864. CarlaPlugin::setParameterValueRT(parameterId, fixedValue, frameOffset, sendCallbackLater);
  865. }
  866. void setChunkData(const void* const data, const std::size_t dataSize) override
  867. {
  868. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  869. CARLA_SAFE_ASSERT_RETURN(fExtensions.state != nullptr,);
  870. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  871. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  872. const clap_istream_impl stream(data, dataSize);
  873. if (fExtensions.state->load(fPlugin, &stream))
  874. pData->updateParameterValues(this, true, true, false);
  875. runIdleCallbacksAsNeeded(false);
  876. }
  877. // -------------------------------------------------------------------
  878. // Set ui stuff
  879. #ifdef CLAP_WINDOW_API_NATIVE
  880. void setWindowTitle(const char* const title) noexcept
  881. {
  882. if (!fUI.isCreated)
  883. return;
  884. CarlaString uiTitle;
  885. if (title != nullptr)
  886. {
  887. uiTitle = title;
  888. }
  889. else
  890. {
  891. uiTitle = pData->name;
  892. uiTitle += " (GUI)";
  893. }
  894. if (fUI.isEmbed)
  895. {
  896. if (fUI.window != nullptr)
  897. fUI.window->setTitle(uiTitle.buffer());
  898. }
  899. else
  900. {
  901. fExtensions.gui->suggest_title(fPlugin, uiTitle.buffer());
  902. }
  903. }
  904. void setCustomUITitle(const char* const title) noexcept override
  905. {
  906. setWindowTitle(title);
  907. CarlaPlugin::setCustomUITitle(title);
  908. }
  909. void showCustomUI(const bool yesNo) override
  910. {
  911. CARLA_SAFE_ASSERT_RETURN(fExtensions.gui != nullptr,);
  912. if (yesNo)
  913. {
  914. if (fUI.isVisible)
  915. {
  916. fExtensions.gui->show(fPlugin);
  917. if (fUI.isEmbed)
  918. {
  919. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  920. fUI.window->show();
  921. fUI.window->focus();
  922. }
  923. runIdleCallbacksAsNeeded(false);
  924. return;
  925. }
  926. if (!fUI.initalized)
  927. {
  928. fUI.isEmbed = fExtensions.gui->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, false);
  929. fUI.initalized = true;
  930. }
  931. if (!fUI.isCreated)
  932. {
  933. if (!fExtensions.gui->create(fPlugin, CLAP_WINDOW_API_NATIVE, !fUI.isEmbed))
  934. {
  935. pData->engine->callback(true, true,
  936. ENGINE_CALLBACK_UI_STATE_CHANGED,
  937. pData->id,
  938. -1,
  939. 0, 0, 0.0f,
  940. "Plugin refused to open its own UI");
  941. return;
  942. }
  943. fUI.isCreated = true;
  944. }
  945. const bool resizable = fExtensions.gui->can_resize(fPlugin);
  946. const EngineOptions& opts(pData->engine->getOptions());
  947. #if defined(CARLA_OS_WIN)
  948. fUI.window = CarlaPluginUI::newWindows(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable);
  949. #elif defined(CARLA_OS_MAC)
  950. fUI.window = CarlaPluginUI::newCocoa(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable);
  951. #elif defined(HAVE_X11)
  952. fUI.window = CarlaPluginUI::newX11(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable, false);
  953. #else
  954. #error why is CLAP_WINDOW_API_NATIVE defined??
  955. #endif
  956. #ifndef CARLA_OS_MAC
  957. if (carla_isNotZero(opts.uiScale))
  958. fExtensions.gui->set_scale(fPlugin, opts.uiScale);
  959. #endif
  960. setWindowTitle(nullptr);
  961. if (fUI.isEmbed)
  962. {
  963. clap_window_t win = { CLAP_WINDOW_API_NATIVE, {} };
  964. win.ptr = fUI.window->getPtr();
  965. fExtensions.gui->set_parent(fPlugin, &win);
  966. uint32_t width, height;
  967. if (fExtensions.gui->get_size(fPlugin, &width, &height))
  968. {
  969. fUI.isResizingFromInit = true;
  970. fUI.width = width;
  971. fUI.height = height;
  972. fUI.window->setSize(width, height, true, true);
  973. }
  974. fExtensions.gui->show(fPlugin);
  975. fUI.window->show();
  976. }
  977. else
  978. {
  979. clap_window_t win = { CLAP_WINDOW_API_NATIVE, {} };
  980. win.uptr = opts.frontendWinId;
  981. fExtensions.gui->set_transient(fPlugin, &win);
  982. fExtensions.gui->show(fPlugin);
  983. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  984. pData->tryTransient();
  985. #endif
  986. }
  987. fUI.isVisible = true;
  988. }
  989. else
  990. {
  991. fUI.isVisible = false;
  992. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  993. pData->transientTryCounter = 0;
  994. #endif
  995. if (fUI.window != nullptr)
  996. fUI.window->hide();
  997. fExtensions.gui->hide(fPlugin);
  998. if (fUI.isCreated)
  999. {
  1000. fExtensions.gui->destroy(fPlugin);
  1001. fUI.isCreated = false;
  1002. }
  1003. if (fUI.window != nullptr)
  1004. {
  1005. delete fUI.window;
  1006. fUI.window = nullptr;
  1007. }
  1008. }
  1009. runIdleCallbacksAsNeeded(false);
  1010. }
  1011. void* embedCustomUI(void* const ptr) override
  1012. {
  1013. CARLA_SAFE_ASSERT_RETURN(fUI.window == nullptr, nullptr);
  1014. if (!fUI.initalized)
  1015. {
  1016. fUI.isEmbed = fExtensions.gui->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, false);
  1017. fUI.initalized = true;
  1018. }
  1019. if (!fUI.isCreated)
  1020. {
  1021. if (!fExtensions.gui->create(fPlugin, CLAP_WINDOW_API_NATIVE, false))
  1022. {
  1023. pData->engine->callback(true, true,
  1024. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1025. pData->id,
  1026. -1,
  1027. 0, 0, 0.0f,
  1028. "Plugin refused to open its own UI");
  1029. return nullptr;
  1030. }
  1031. fUI.isCreated = true;
  1032. }
  1033. fUI.isVisible = true;
  1034. #ifndef CARLA_OS_MAC
  1035. const EngineOptions& opts(pData->engine->getOptions());
  1036. if (carla_isNotZero(opts.uiScale))
  1037. fExtensions.gui->set_scale(fPlugin, opts.uiScale);
  1038. #endif
  1039. clap_window_t win = { CLAP_WINDOW_API_NATIVE, {} };
  1040. win.ptr = ptr;
  1041. fExtensions.gui->set_parent(fPlugin, &win);
  1042. uint32_t width, height;
  1043. if (fExtensions.gui->get_size(fPlugin, &width, &height))
  1044. {
  1045. fUI.isResizingFromInit = true;
  1046. fUI.width = width;
  1047. fUI.height = height;
  1048. pData->engine->callback(true, true,
  1049. ENGINE_CALLBACK_EMBED_UI_RESIZED,
  1050. pData->id, width, height,
  1051. 0, 0.0f, nullptr);
  1052. }
  1053. fExtensions.gui->show(fPlugin);
  1054. return nullptr;
  1055. }
  1056. #endif
  1057. void idle() override
  1058. {
  1059. if (kEngineHasIdleOnMainThread)
  1060. runIdleCallbacksAsNeeded(true);
  1061. CarlaPlugin::idle();
  1062. }
  1063. void uiIdle() override
  1064. {
  1065. #ifdef CLAP_WINDOW_API_NATIVE
  1066. if (fUI.shouldClose)
  1067. {
  1068. fUI.shouldClose = false;
  1069. fUI.isResizingFromHost = fUI.isResizingFromInit = false;
  1070. fUI.isResizingFromPlugin = 0;
  1071. showCustomUI(false);
  1072. pData->engine->callback(true, true,
  1073. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1074. pData->id,
  1075. 0,
  1076. 0, 0, 0.0f, nullptr);
  1077. }
  1078. if (fUI.isResizingFromHost)
  1079. {
  1080. fUI.isResizingFromHost = false;
  1081. if (fUI.isResizingFromPlugin == 0 && !fUI.isResizingFromInit == false)
  1082. {
  1083. carla_stdout("Host resize restarted");
  1084. fExtensions.gui->set_size(fPlugin, fUI.width, fUI.height);
  1085. }
  1086. }
  1087. if (fUI.window != nullptr)
  1088. fUI.window->idle();
  1089. if (fUI.isResizingFromPlugin == 2)
  1090. {
  1091. fUI.isResizingFromPlugin = 1;
  1092. }
  1093. else if (fUI.isResizingFromPlugin == 1)
  1094. {
  1095. fUI.isResizingFromPlugin = 0;
  1096. carla_stdout("Plugin resize stopped");
  1097. }
  1098. #endif
  1099. if (!kEngineHasIdleOnMainThread)
  1100. runIdleCallbacksAsNeeded(true);
  1101. CarlaPlugin::uiIdle();
  1102. }
  1103. // -------------------------------------------------------------------
  1104. // Plugin state
  1105. void reload() override
  1106. {
  1107. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  1108. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1109. carla_debug("CarlaPluginCLAP::reload() - start");
  1110. // Safely disable plugin for reload
  1111. const ScopedDisabler sd(this);
  1112. if (pData->active)
  1113. deactivate();
  1114. clearBuffers();
  1115. const clap_plugin_audio_ports_t* audioPortsExt = static_cast<const clap_plugin_audio_ports_t*>(
  1116. fPlugin->get_extension(fPlugin, CLAP_EXT_AUDIO_PORTS));
  1117. const clap_plugin_latency_t* latencyExt = static_cast<const clap_plugin_latency_t*>(
  1118. fPlugin->get_extension(fPlugin, CLAP_EXT_LATENCY));
  1119. const clap_plugin_note_ports_t* notePortsExt = static_cast<const clap_plugin_note_ports_t*>(
  1120. fPlugin->get_extension(fPlugin, CLAP_EXT_NOTE_PORTS));
  1121. const clap_plugin_params_t* paramsExt = static_cast<const clap_plugin_params_t*>(
  1122. fPlugin->get_extension(fPlugin, CLAP_EXT_PARAMS));
  1123. const clap_plugin_state_t* stateExt = static_cast<const clap_plugin_state_t*>(
  1124. fPlugin->get_extension(fPlugin, CLAP_EXT_STATE));
  1125. const clap_plugin_timer_support_t* timerExt = static_cast<const clap_plugin_timer_support_t*>(
  1126. fPlugin->get_extension(fPlugin, CLAP_EXT_TIMER_SUPPORT));
  1127. if (audioPortsExt != nullptr && (audioPortsExt->count == nullptr || audioPortsExt->get == nullptr))
  1128. audioPortsExt = nullptr;
  1129. if (latencyExt != nullptr && latencyExt->get == nullptr)
  1130. latencyExt = nullptr;
  1131. if (notePortsExt != nullptr && (notePortsExt->count == nullptr || notePortsExt->get == nullptr))
  1132. notePortsExt = nullptr;
  1133. if (paramsExt != nullptr && (paramsExt->count == nullptr || paramsExt->get_info == nullptr))
  1134. paramsExt = nullptr;
  1135. if (stateExt != nullptr && (stateExt->save == nullptr || stateExt->load == nullptr))
  1136. stateExt = nullptr;
  1137. if (timerExt != nullptr && timerExt->on_timer == nullptr)
  1138. timerExt = nullptr;
  1139. fExtensions.latency = latencyExt;
  1140. fExtensions.params = paramsExt;
  1141. fExtensions.state = stateExt;
  1142. fExtensions.timer = timerExt;
  1143. #ifdef CLAP_WINDOW_API_NATIVE
  1144. const clap_plugin_gui_t* guiExt = static_cast<const clap_plugin_gui_t*>(
  1145. fPlugin->get_extension(fPlugin, CLAP_EXT_GUI));
  1146. if (guiExt != nullptr && (guiExt->is_api_supported == nullptr
  1147. || guiExt->create == nullptr
  1148. || guiExt->destroy == nullptr
  1149. || guiExt->set_scale == nullptr
  1150. || guiExt->get_size == nullptr
  1151. || guiExt->can_resize == nullptr
  1152. || guiExt->get_resize_hints == nullptr
  1153. || guiExt->adjust_size == nullptr
  1154. || guiExt->set_size == nullptr
  1155. || guiExt->set_parent == nullptr
  1156. || guiExt->set_transient == nullptr
  1157. || guiExt->suggest_title == nullptr
  1158. || guiExt->show == nullptr
  1159. || guiExt->hide == nullptr))
  1160. guiExt = nullptr;
  1161. fExtensions.gui = guiExt;
  1162. #endif
  1163. #if defined(CLAP_WINDOW_API_NATIVE) && defined(_POSIX_VERSION)
  1164. const clap_plugin_posix_fd_support_t* posixFdExt = static_cast<const clap_plugin_posix_fd_support_t*>(
  1165. fPlugin->get_extension(fPlugin, CLAP_EXT_POSIX_FD_SUPPORT));
  1166. if (posixFdExt != nullptr && posixFdExt->on_fd == nullptr)
  1167. posixFdExt = nullptr;
  1168. fExtensions.posixFD = posixFdExt;
  1169. #endif
  1170. const uint32_t numAudioInputPorts = audioPortsExt != nullptr ? audioPortsExt->count(fPlugin, true) : 0;
  1171. const uint32_t numAudioOutputPorts = audioPortsExt != nullptr ? audioPortsExt->count(fPlugin, false) : 0;
  1172. const uint32_t numNoteInputPorts = notePortsExt != nullptr ? notePortsExt->count(fPlugin, true) : 0;
  1173. const uint32_t numNoteOutputPorts = notePortsExt != nullptr ? notePortsExt->count(fPlugin, false) : 0;
  1174. const uint32_t numParameters = paramsExt != nullptr ? paramsExt->count(fPlugin) : 0;
  1175. uint32_t aIns, aOuts, mIns, mOuts, params;
  1176. aIns = aOuts = mIns = mOuts = params = 0;
  1177. bool needsCtrlIn, needsCtrlOut;
  1178. needsCtrlIn = needsCtrlOut = false;
  1179. fInputAudioBuffers.realloc(numAudioInputPorts);
  1180. fOutputAudioBuffers.realloc(numAudioOutputPorts);
  1181. for (uint32_t i=0; i<numAudioInputPorts; ++i)
  1182. {
  1183. clap_audio_port_info_t portInfo = {};
  1184. CARLA_SAFE_ASSERT_BREAK(audioPortsExt->get(fPlugin, i, true, &portInfo));
  1185. CARLA_SAFE_ASSERT(portInfo.channel_count != 0);
  1186. fInputAudioBuffers.buffers[i].channel_count = portInfo.channel_count;
  1187. fInputAudioBuffers.extra[i].offset = aIns;
  1188. fInputAudioBuffers.extra[i].isMain = portInfo.flags & CLAP_AUDIO_PORT_IS_MAIN;
  1189. aIns += portInfo.channel_count;
  1190. }
  1191. for (uint32_t i=0; i<numAudioOutputPorts; ++i)
  1192. {
  1193. clap_audio_port_info_t portInfo = {};
  1194. CARLA_SAFE_ASSERT_BREAK(audioPortsExt->get(fPlugin, i, false, &portInfo));
  1195. CARLA_SAFE_ASSERT(portInfo.channel_count != 0);
  1196. fOutputAudioBuffers.buffers[i].channel_count = portInfo.channel_count;
  1197. fOutputAudioBuffers.extra[i].offset = aOuts;
  1198. fOutputAudioBuffers.extra[i].isMain = portInfo.flags & CLAP_AUDIO_PORT_IS_MAIN;
  1199. for (uint32_t j=0; j<portInfo.channel_count; ++j)
  1200. fOutputAudioBuffers.buffers[i].constant_mask |= (1 << j);
  1201. aOuts += portInfo.channel_count;
  1202. }
  1203. for (uint32_t i=0; i<numNoteInputPorts; ++i)
  1204. {
  1205. clap_note_port_info_t portInfo = {};
  1206. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  1207. if (portInfo.supported_dialects & (CLAP_NOTE_DIALECT_CLAP|CLAP_NOTE_DIALECT_MIDI))
  1208. ++mIns;
  1209. }
  1210. for (uint32_t i=0; i<numNoteOutputPorts; ++i)
  1211. {
  1212. clap_note_port_info_t portInfo = {};
  1213. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, false, &portInfo));
  1214. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI)
  1215. ++mOuts;
  1216. }
  1217. for (uint32_t i=0; i<numParameters; ++i, ++params)
  1218. {
  1219. clap_param_info_t paramInfo = {};
  1220. CARLA_SAFE_ASSERT_BREAK(paramsExt->get_info(fPlugin, i, &paramInfo));
  1221. }
  1222. if (aIns > 0)
  1223. {
  1224. pData->audioIn.createNew(aIns);
  1225. }
  1226. if (aOuts > 0)
  1227. {
  1228. pData->audioOut.createNew(aOuts);
  1229. needsCtrlIn = true;
  1230. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1231. fAudioOutBuffers = new float*[aOuts];
  1232. for (uint32_t i=0; i < aOuts; ++i)
  1233. fAudioOutBuffers[i] = nullptr;
  1234. #endif
  1235. }
  1236. if (mIns == 1)
  1237. needsCtrlIn = true;
  1238. if (mOuts == 1)
  1239. needsCtrlOut = true;
  1240. if (params > 0)
  1241. {
  1242. pData->param.createNew(params, false);
  1243. needsCtrlIn = true;
  1244. }
  1245. fInputEvents.realloc(pData->event.portIn, mIns, params);
  1246. fOutputEvents.realloc(pData->event.portOut, mOuts, params);
  1247. const EngineProcessMode processMode = pData->engine->getProccessMode();
  1248. const uint portNameSize = pData->engine->getMaxPortNameSize();
  1249. CarlaString portName;
  1250. // Audio Ins
  1251. for (uint32_t j=0; j < aIns; ++j)
  1252. {
  1253. portName.clear();
  1254. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1255. {
  1256. portName = pData->name;
  1257. portName += ":";
  1258. }
  1259. if (aIns > 1)
  1260. {
  1261. portName += "input_";
  1262. portName += CarlaString(j+1);
  1263. }
  1264. else
  1265. portName += "input";
  1266. portName.truncate(portNameSize);
  1267. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  1268. pData->audioIn.ports[j].rindex = j;
  1269. }
  1270. // Audio Outs
  1271. for (uint32_t j=0; j < aOuts; ++j)
  1272. {
  1273. portName.clear();
  1274. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1275. {
  1276. portName = pData->name;
  1277. portName += ":";
  1278. }
  1279. if (aOuts > 1)
  1280. {
  1281. portName += "output_";
  1282. portName += CarlaString(j+1);
  1283. }
  1284. else
  1285. portName += "output";
  1286. portName.truncate(portNameSize);
  1287. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  1288. pData->audioOut.ports[j].rindex = j;
  1289. }
  1290. // MIDI Ins
  1291. for (uint32_t i=0, j=0; i<numNoteInputPorts; ++i)
  1292. {
  1293. clap_note_port_info_t portInfo = {};
  1294. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  1295. if ((portInfo.supported_dialects & (CLAP_NOTE_DIALECT_CLAP|CLAP_NOTE_DIALECT_MIDI)) == 0x0)
  1296. continue;
  1297. CARLA_SAFE_ASSERT_UINT2_BREAK(j < mIns, j, mIns);
  1298. fInputEvents.portData[j].clapPortIndex = i;
  1299. fInputEvents.portData[j].supportedDialects = portInfo.supported_dialects;
  1300. if (mIns > 1)
  1301. {
  1302. portName.clear();
  1303. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1304. {
  1305. portName = pData->name;
  1306. portName += ":";
  1307. }
  1308. portName += portInfo.name;
  1309. portName.truncate(portNameSize);
  1310. fInputEvents.portData[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  1311. }
  1312. else
  1313. {
  1314. fInputEvents.portData[j].port = nullptr;
  1315. fInputEvents.defaultPort = &fInputEvents.portData[0];
  1316. }
  1317. ++j;
  1318. }
  1319. // MIDI Outs
  1320. for (uint32_t i=0, j=0; i<numNoteOutputPorts; ++i)
  1321. {
  1322. clap_note_port_info_t portInfo = {};
  1323. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, false, &portInfo));
  1324. if ((portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI) == 0x0)
  1325. continue;
  1326. CARLA_SAFE_ASSERT_UINT2_BREAK(j < mOuts, j, mOuts);
  1327. fOutputEvents.portData[j].clapPortIndex = i;
  1328. fOutputEvents.portData[j].supportedDialects = portInfo.supported_dialects;
  1329. if (mOuts > 1)
  1330. {
  1331. portName.clear();
  1332. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1333. {
  1334. portName = pData->name;
  1335. portName += ":";
  1336. }
  1337. portName += portInfo.name;
  1338. portName.truncate(portNameSize);
  1339. fOutputEvents.portData[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  1340. }
  1341. else
  1342. {
  1343. fOutputEvents.portData[j].port = nullptr;
  1344. fOutputEvents.defaultPort = &fOutputEvents.portData[0];
  1345. }
  1346. ++j;
  1347. }
  1348. // Parameters
  1349. for (uint32_t i=0; i<numParameters; ++i)
  1350. {
  1351. clap_param_info_t paramInfo = {};
  1352. CARLA_SAFE_ASSERT_BREAK(paramsExt->get_info(fPlugin, i, &paramInfo));
  1353. CARLA_SAFE_ASSERT_BREAK(i < params);
  1354. pData->param.data[i].index = i;
  1355. pData->param.data[i].rindex = static_cast<int32_t>(paramInfo.id);
  1356. double min, max, def, step, stepSmall, stepLarge;
  1357. min = paramInfo.min_value;
  1358. max = paramInfo.max_value;
  1359. def = paramInfo.default_value;
  1360. if (min >= max)
  1361. max = min + 0.1;
  1362. if (def < min)
  1363. def = min;
  1364. else if (def > max)
  1365. def = max;
  1366. if (paramInfo.flags & (CLAP_PARAM_IS_HIDDEN|CLAP_PARAM_IS_BYPASS))
  1367. {
  1368. pData->param.data[i].type = PARAMETER_UNKNOWN;
  1369. }
  1370. else if (paramInfo.flags & CLAP_PARAM_IS_READONLY)
  1371. {
  1372. pData->param.data[i].type = PARAMETER_OUTPUT;
  1373. needsCtrlOut = true;
  1374. }
  1375. else
  1376. {
  1377. pData->param.data[i].type = PARAMETER_INPUT;
  1378. }
  1379. if (paramInfo.flags & CLAP_PARAM_IS_STEPPED)
  1380. {
  1381. if (carla_isEqual(max - min, 1.0))
  1382. {
  1383. step = stepSmall = stepLarge = 1.0;
  1384. pData->param.data[i].hints |= PARAMETER_IS_BOOLEAN;
  1385. }
  1386. else
  1387. {
  1388. step = 1.0;
  1389. stepSmall = 1.0;
  1390. stepLarge = std::min(max - min, 10.0);
  1391. }
  1392. pData->param.data[i].hints |= PARAMETER_IS_INTEGER;
  1393. }
  1394. else
  1395. {
  1396. double range = max - min;
  1397. step = range/100.0;
  1398. stepSmall = range/1000.0;
  1399. stepLarge = range/10.0;
  1400. }
  1401. if (pData->param.data[i].type != PARAMETER_UNKNOWN)
  1402. {
  1403. pData->param.data[i].hints |= PARAMETER_IS_ENABLED;
  1404. pData->param.data[i].hints |= PARAMETER_USES_CUSTOM_TEXT;
  1405. if (paramInfo.flags & CLAP_PARAM_IS_AUTOMATABLE)
  1406. {
  1407. pData->param.data[i].hints |= PARAMETER_IS_AUTOMATABLE;
  1408. if ((paramInfo.flags & CLAP_PARAM_IS_STEPPED) == 0x0)
  1409. pData->param.data[i].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  1410. }
  1411. }
  1412. pData->param.ranges[i].min = min;
  1413. pData->param.ranges[i].max = max;
  1414. pData->param.ranges[i].def = def;
  1415. pData->param.ranges[i].step = step;
  1416. pData->param.ranges[i].stepSmall = stepSmall;
  1417. pData->param.ranges[i].stepLarge = stepLarge;
  1418. fInputEvents.updatedParams[i].clapId = paramInfo.id;
  1419. fInputEvents.updatedParams[i].cookie = paramInfo.cookie;
  1420. }
  1421. if (needsCtrlIn)
  1422. {
  1423. portName.clear();
  1424. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1425. {
  1426. portName = pData->name;
  1427. portName += ":";
  1428. }
  1429. portName += "events-in";
  1430. portName.truncate(portNameSize);
  1431. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  1432. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1433. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  1434. #endif
  1435. if (mIns == 1)
  1436. fInputEvents.portData[0].port = pData->event.portIn;
  1437. }
  1438. if (needsCtrlOut)
  1439. {
  1440. portName.clear();
  1441. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1442. {
  1443. portName = pData->name;
  1444. portName += ":";
  1445. }
  1446. portName += "events-out";
  1447. portName.truncate(portNameSize);
  1448. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  1449. if (mOuts == 1)
  1450. fOutputEvents.portData[0].port = pData->event.portOut;
  1451. }
  1452. // plugin hints
  1453. pData->hints = PLUGIN_NEEDS_MAIN_THREAD_IDLE;
  1454. if (clapFeaturesContainInstrument(fPluginDescriptor->features))
  1455. pData->hints |= PLUGIN_IS_SYNTH;
  1456. #ifdef CLAP_WINDOW_API_NATIVE
  1457. if (guiExt != nullptr)
  1458. {
  1459. if (guiExt->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, false))
  1460. {
  1461. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1462. pData->hints |= PLUGIN_HAS_CUSTOM_EMBED_UI;
  1463. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1464. }
  1465. else if (guiExt->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, true))
  1466. {
  1467. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1468. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1469. }
  1470. }
  1471. #endif
  1472. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  1473. pData->hints |= PLUGIN_CAN_DRYWET;
  1474. if (aOuts > 0)
  1475. pData->hints |= PLUGIN_CAN_VOLUME;
  1476. if (aOuts >= 2 && aOuts % 2 == 0)
  1477. pData->hints |= PLUGIN_CAN_BALANCE;
  1478. // extra plugin hints
  1479. pData->extraHints = 0x0;
  1480. if (const uint32_t latency = fExtensions.latency != nullptr ? fExtensions.latency->get(fPlugin) : 0)
  1481. {
  1482. fLastKnownLatency = latency;
  1483. pData->client->setLatency(latency);
  1484. #ifndef BUILD_BRIDGE
  1485. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  1486. #endif
  1487. }
  1488. else
  1489. {
  1490. fLastKnownLatency = 0;
  1491. }
  1492. bufferSizeChanged(pData->engine->getBufferSize());
  1493. reloadPrograms(true);
  1494. if (pData->active)
  1495. activate();
  1496. else
  1497. runIdleCallbacksAsNeeded(false);
  1498. carla_debug("CarlaPluginCLAP::reload() - end");
  1499. }
  1500. void reloadPrograms(const bool doInit) override
  1501. {
  1502. carla_debug("CarlaPluginCLAP::reloadPrograms(%s)", bool2str(doInit));
  1503. }
  1504. // -------------------------------------------------------------------
  1505. // Plugin processing
  1506. void activate() noexcept override
  1507. {
  1508. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1509. // FIXME check return status
  1510. fPlugin->activate(fPlugin, pData->engine->getSampleRate(), 1, pData->engine->getBufferSize());
  1511. fPlugin->start_processing(fPlugin);
  1512. fNeedsParamFlush = false;
  1513. runIdleCallbacksAsNeeded(false);
  1514. }
  1515. void deactivate() noexcept override
  1516. {
  1517. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1518. // FIXME check return status
  1519. fPlugin->stop_processing(fPlugin);
  1520. fPlugin->deactivate(fPlugin);
  1521. runIdleCallbacksAsNeeded(false);
  1522. }
  1523. void process(const float* const* const audioIn,
  1524. float** const audioOut,
  1525. const float* const* const cvIn,
  1526. float** const,
  1527. const uint32_t frames) override
  1528. {
  1529. // --------------------------------------------------------------------------------------------------------
  1530. // Check if active
  1531. if (! pData->active)
  1532. {
  1533. // disable any output sound
  1534. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1535. carla_zeroFloats(audioOut[i], frames);
  1536. return;
  1537. }
  1538. // --------------------------------------------------------------------------------------------------------
  1539. // Check buffers
  1540. CARLA_SAFE_ASSERT_RETURN(frames > 0,);
  1541. if (pData->audioIn.count > 0)
  1542. {
  1543. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr,);
  1544. }
  1545. if (pData->audioOut.count > 0)
  1546. {
  1547. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr,);
  1548. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1549. CARLA_SAFE_ASSERT_RETURN(fAudioOutBuffers != nullptr,);
  1550. #endif
  1551. }
  1552. // --------------------------------------------------------------------------------------------------------
  1553. // Set audio buffers
  1554. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1555. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1556. carla_zeroFloats(fAudioOutBuffers[i], frames);
  1557. #endif
  1558. // --------------------------------------------------------------------------------------------------------
  1559. // Try lock, silence otherwise
  1560. if (pData->engine->isOffline())
  1561. {
  1562. pData->singleMutex.lock();
  1563. }
  1564. else if (! pData->singleMutex.tryLock())
  1565. {
  1566. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1567. carla_zeroFloats(audioOut[i], frames);
  1568. return;
  1569. }
  1570. // --------------------------------------------------------------------------------------------------------
  1571. fInputEvents.handleScheduledParameterUpdates();
  1572. // --------------------------------------------------------------------------------------------------------
  1573. // Check if needs reset
  1574. if (pData->needsReset)
  1575. {
  1576. // TODO alternative if plugin does not support CLAP_NOTE_DIALECT_MIDI
  1577. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1578. {
  1579. for (uint32_t p=0; p<fInputEvents.portCount; ++p)
  1580. {
  1581. const uint16_t port = fInputEvents.portData[p].clapPortIndex;
  1582. for (uint8_t i=0, k=fInputEvents.numEventsUsed; i < MAX_MIDI_CHANNELS; ++i)
  1583. {
  1584. fInputEvents.events[k + i].midi = {
  1585. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1586. port,
  1587. {
  1588. uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT)),
  1589. MIDI_CONTROL_ALL_NOTES_OFF, 0
  1590. }
  1591. };
  1592. fInputEvents.events[k + MAX_MIDI_CHANNELS + i].midi = {
  1593. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1594. port,
  1595. {
  1596. uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT)),
  1597. MIDI_CONTROL_ALL_SOUND_OFF, 0
  1598. }
  1599. };
  1600. }
  1601. fInputEvents.numEventsUsed += MAX_MIDI_CHANNELS * 2;
  1602. }
  1603. }
  1604. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  1605. {
  1606. for (uint32_t p=0; p<fInputEvents.portCount; ++p)
  1607. {
  1608. const uint16_t port = fInputEvents.portData[p].clapPortIndex;
  1609. for (uint8_t i=0, k=fInputEvents.numEventsUsed; i < MAX_MIDI_NOTE; ++i)
  1610. {
  1611. fInputEvents.events[k + i].midi = {
  1612. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1613. port,
  1614. {
  1615. uint8_t(MIDI_STATUS_NOTE_OFF | (pData->ctrlChannel & MIDI_CHANNEL_BIT)),
  1616. i, 0
  1617. }
  1618. };
  1619. }
  1620. fInputEvents.numEventsUsed += MAX_MIDI_NOTE;
  1621. }
  1622. }
  1623. pData->needsReset = false;
  1624. }
  1625. // --------------------------------------------------------------------------------------------------------
  1626. // Set TimeInfo
  1627. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1628. clap_event_transport_t clapTransport = {
  1629. { sizeof(clap_event_transport_t), 0, 0, CLAP_EVENT_TRANSPORT, 0 },
  1630. 0x0, // flags
  1631. 0, // song_pos_beats, position in beats
  1632. 0, // song_pos_seconds, position in seconds
  1633. 0.0, // tempo, in bpm
  1634. 0.0, // tempo_inc, tempo increment for each samples and until the next time info event
  1635. 0, // loop_start_beats;
  1636. 0, // loop_end_beats;
  1637. 0, // loop_start_seconds;
  1638. 0, // loop_end_seconds;
  1639. 0, // bar_start, start pos of the current bar
  1640. 0, // bar_number, bar at song pos 0 has the number 0
  1641. 0, // tsig_num, time signature numerator
  1642. 0, // tsig_denom, time signature denominator
  1643. };
  1644. if (timeInfo.playing)
  1645. clapTransport.flags |= CLAP_TRANSPORT_IS_PLAYING;
  1646. // TODO song_pos_seconds (based on frame and sample rate)
  1647. if (timeInfo.bbt.valid)
  1648. {
  1649. // TODO song_pos_beats
  1650. // Tempo
  1651. clapTransport.tempo = timeInfo.bbt.beatsPerMinute;
  1652. clapTransport.flags |= CLAP_TRANSPORT_HAS_TEMPO;
  1653. // Bar
  1654. // TODO bar_start
  1655. clapTransport.bar_number = timeInfo.bbt.bar - 1;
  1656. // Time Signature
  1657. clapTransport.tsig_num = static_cast<uint16_t>(timeInfo.bbt.beatsPerBar + 0.5f);
  1658. clapTransport.tsig_denom = static_cast<uint16_t>(timeInfo.bbt.beatType + 0.5f);
  1659. clapTransport.flags |= CLAP_TRANSPORT_HAS_TIME_SIGNATURE;
  1660. }
  1661. else
  1662. {
  1663. // Tempo
  1664. clapTransport.tempo = 120.0;
  1665. clapTransport.flags |= CLAP_TRANSPORT_HAS_TEMPO;
  1666. // Time Signature
  1667. clapTransport.tsig_num = 4;
  1668. clapTransport.tsig_denom = 4;
  1669. clapTransport.flags |= CLAP_TRANSPORT_HAS_TIME_SIGNATURE;
  1670. }
  1671. // --------------------------------------------------------------------------------------------------------
  1672. // Event Input (main port)
  1673. if (pData->event.portIn != nullptr)
  1674. {
  1675. // ----------------------------------------------------------------------------------------------------
  1676. // MIDI Input (External)
  1677. if (pData->extNotes.mutex.tryLock())
  1678. {
  1679. if (fInputEvents.portCount == 0)
  1680. {
  1681. // does not handle MIDI
  1682. pData->extNotes.data.clear();
  1683. }
  1684. else
  1685. {
  1686. ExternalMidiNote note = { -1, 0, 0 };
  1687. const uint16_t p = fInputEvents.portData[0].clapPortIndex;
  1688. for (; fInputEvents.numEventsUsed < fInputEvents.numEventsAllocated && ! pData->extNotes.data.isEmpty();)
  1689. {
  1690. note = pData->extNotes.data.getFirst(note, true);
  1691. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1692. if (fInputEvents.portData[0].supportedDialects & CLAP_NOTE_DIALECT_MIDI)
  1693. {
  1694. const uint8_t data[3] = {
  1695. uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT)),
  1696. note.note,
  1697. note.velo
  1698. };
  1699. fInputEvents.addSimpleMidiEvent(true, p, 0, data);
  1700. }
  1701. else
  1702. {
  1703. fInputEvents.addSimpleNoteEvent(true, -1, 0, note.channel, note.note, note.velo);
  1704. }
  1705. }
  1706. }
  1707. pData->extNotes.mutex.unlock();
  1708. } // End of MIDI Input (External)
  1709. // ----------------------------------------------------------------------------------------------------
  1710. // Event Input (System)
  1711. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1712. bool allNotesOffSent = false;
  1713. #endif
  1714. uint32_t previousEventTime = 0;
  1715. uint32_t nextBankId;
  1716. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1717. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1718. else
  1719. nextBankId = 0;
  1720. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1721. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  1722. pData->event.cvSourcePorts->initPortBuffers(cvIn + pData->cvIn.count, frames, true, pData->event.portIn);
  1723. #endif
  1724. const uint32_t numSysEvents = pData->event.portIn->getEventCount();
  1725. for (uint32_t i=0; i < numSysEvents; ++i)
  1726. {
  1727. EngineEvent& event(fInputEvents.defaultPort->port->getEvent(i));
  1728. uint32_t eventTime = event.time;
  1729. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  1730. if (eventTime < previousEventTime)
  1731. {
  1732. carla_stderr2("Timing error, eventTime:%u < previousEventTime:%u for '%s'",
  1733. eventTime, previousEventTime, pData->name);
  1734. eventTime = previousEventTime;
  1735. }
  1736. previousEventTime = eventTime;
  1737. switch (event.type)
  1738. {
  1739. case kEngineEventTypeNull:
  1740. break;
  1741. case kEngineEventTypeControl: {
  1742. EngineControlEvent& ctrlEvent(event.ctrl);
  1743. switch (ctrlEvent.type)
  1744. {
  1745. case kEngineControlEventTypeNull:
  1746. break;
  1747. case kEngineControlEventTypeParameter: {
  1748. float value;
  1749. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1750. // non-midi
  1751. if (event.channel == kEngineEventNonMidiChannel)
  1752. {
  1753. const uint32_t k = ctrlEvent.param;
  1754. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  1755. ctrlEvent.handled = true;
  1756. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1757. setParameterValueRT(k, value, event.time, true);
  1758. continue;
  1759. }
  1760. // Control backend stuff
  1761. if (event.channel == pData->ctrlChannel)
  1762. {
  1763. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1764. {
  1765. ctrlEvent.handled = true;
  1766. value = ctrlEvent.normalizedValue;
  1767. setDryWetRT(value, true);
  1768. }
  1769. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1770. {
  1771. ctrlEvent.handled = true;
  1772. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  1773. setVolumeRT(value, true);
  1774. }
  1775. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1776. {
  1777. float left, right;
  1778. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  1779. if (value < 0.0f)
  1780. {
  1781. left = -1.0f;
  1782. right = (value*2.0f)+1.0f;
  1783. }
  1784. else if (value > 0.0f)
  1785. {
  1786. left = (value*2.0f)-1.0f;
  1787. right = 1.0f;
  1788. }
  1789. else
  1790. {
  1791. left = -1.0f;
  1792. right = 1.0f;
  1793. }
  1794. ctrlEvent.handled = true;
  1795. setBalanceLeftRT(left, true);
  1796. setBalanceRightRT(right, true);
  1797. }
  1798. }
  1799. #endif
  1800. // Control plugin parameters
  1801. uint32_t k;
  1802. for (k=0; k < pData->param.count; ++k)
  1803. {
  1804. if (pData->param.data[k].midiChannel != event.channel)
  1805. continue;
  1806. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  1807. continue;
  1808. if (pData->param.data[k].type != PARAMETER_INPUT)
  1809. continue;
  1810. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  1811. continue;
  1812. ctrlEvent.handled = true;
  1813. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1814. setParameterValueRT(k, value, event.time, true);
  1815. }
  1816. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  1817. {
  1818. uint8_t midiData[3];
  1819. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1820. midiData[1] = uint8_t(ctrlEvent.param);
  1821. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  1822. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1823. }
  1824. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1825. if (! ctrlEvent.handled)
  1826. checkForMidiLearn(event);
  1827. #endif
  1828. break;
  1829. } // case kEngineControlEventTypeParameter
  1830. case kEngineControlEventTypeMidiBank:
  1831. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1832. {
  1833. if (event.channel == pData->ctrlChannel)
  1834. nextBankId = ctrlEvent.param;
  1835. }
  1836. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1837. {
  1838. uint8_t midiData[3];
  1839. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1840. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  1841. midiData[2] = uint8_t(ctrlEvent.param);
  1842. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1843. }
  1844. break;
  1845. case kEngineControlEventTypeMidiProgram:
  1846. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1847. {
  1848. if (event.channel == pData->ctrlChannel)
  1849. {
  1850. const uint32_t nextProgramId(ctrlEvent.param);
  1851. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  1852. {
  1853. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  1854. {
  1855. setMidiProgramRT(k, true);
  1856. break;
  1857. }
  1858. }
  1859. }
  1860. }
  1861. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1862. {
  1863. uint8_t midiData[3];
  1864. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1865. midiData[1] = uint8_t(ctrlEvent.param);
  1866. midiData[2] = 0;
  1867. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1868. }
  1869. break;
  1870. case kEngineControlEventTypeAllSoundOff:
  1871. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1872. {
  1873. uint8_t midiData[3];
  1874. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1875. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  1876. midiData[2] = 0;
  1877. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1878. }
  1879. break;
  1880. case kEngineControlEventTypeAllNotesOff:
  1881. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1882. {
  1883. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1884. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1885. {
  1886. allNotesOffSent = true;
  1887. postponeRtAllNotesOff();
  1888. }
  1889. #endif
  1890. uint8_t midiData[3];
  1891. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1892. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1893. midiData[2] = 0;
  1894. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1895. }
  1896. break;
  1897. } // switch (ctrlEvent.type)
  1898. break;
  1899. } // case kEngineEventTypeControl
  1900. case kEngineEventTypeMidi: {
  1901. const EngineMidiEvent& midiEvent(event.midi);
  1902. if (midiEvent.size > 3)
  1903. continue;
  1904. CARLA_SAFE_ASSERT_BREAK(midiEvent.port < fInputEvents.portCount);
  1905. const uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1906. if (status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON)
  1907. {
  1908. if (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES)
  1909. continue;
  1910. // plugin does not support MIDI, send a simple note instead
  1911. if ((fInputEvents.portData[midiEvent.port].supportedDialects & CLAP_NOTE_DIALECT_MIDI) == 0x0)
  1912. {
  1913. fInputEvents.addSimpleNoteEvent(true, midiEvent.port, event.time,
  1914. event.channel, midiEvent.data[1], midiEvent.data[2]);
  1915. }
  1916. }
  1917. if (fInputEvents.portData[midiEvent.port].supportedDialects & CLAP_NOTE_DIALECT_MIDI)
  1918. {
  1919. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1920. continue;
  1921. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1922. continue;
  1923. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1924. continue;
  1925. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1926. continue;
  1927. // put back channel in data
  1928. uint8_t midiData[3] = { uint8_t(status | (event.channel & MIDI_CHANNEL_BIT)), 0, 0 };
  1929. switch (midiEvent.size)
  1930. {
  1931. case 3:
  1932. midiData[2] = midiEvent.data[2];
  1933. // fall through
  1934. case 2:
  1935. midiData[1] = midiEvent.data[1];
  1936. break;
  1937. }
  1938. fInputEvents.addSimpleMidiEvent(true, midiEvent.port, eventTime, midiData);
  1939. }
  1940. switch (status)
  1941. {
  1942. case MIDI_STATUS_NOTE_ON:
  1943. if (midiEvent.data[2] != 0)
  1944. {
  1945. pData->postponeNoteOnRtEvent(true, event.channel, midiEvent.data[1], midiEvent.data[2]);
  1946. break;
  1947. }
  1948. // fall through
  1949. case MIDI_STATUS_NOTE_OFF:
  1950. pData->postponeNoteOffRtEvent(true, event.channel, midiEvent.data[1]);
  1951. break;
  1952. }
  1953. } break;
  1954. } // switch (event.type)
  1955. }
  1956. pData->postRtEvents.trySplice();
  1957. } // End of Event Input (main port)
  1958. // --------------------------------------------------------------------------------------------------------
  1959. // Event input (multi MIDI port)
  1960. if (fInputEvents.portCount > 1)
  1961. {
  1962. // TODO
  1963. }
  1964. // --------------------------------------------------------------------------------------------------------
  1965. // Plugin processing
  1966. for (uint32_t i=0; i<fInputAudioBuffers.count; ++i)
  1967. fInputAudioBuffers.buffers[i].data32 = audioIn + fInputAudioBuffers.extra[i].offset;
  1968. for (uint32_t i=0; i<fOutputAudioBuffers.count; ++i)
  1969. {
  1970. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1971. fOutputAudioBuffers.buffers[i].data32 = fAudioOutBuffers + fOutputAudioBuffers.extra[i].offset;
  1972. #else
  1973. fOutputAudioBuffers.buffers[i].data32 = audioOut + fOutputAudioBuffers.extra[i].offset;
  1974. #endif
  1975. }
  1976. const clap_process_t process = {
  1977. static_cast<int64_t>(timeInfo.frame),
  1978. frames,
  1979. &clapTransport,
  1980. fInputAudioBuffers.cast(),
  1981. fOutputAudioBuffers.buffers,
  1982. fInputAudioBuffers.count,
  1983. fOutputAudioBuffers.count,
  1984. fInputEvents.cast(),
  1985. fOutputEvents.cast()
  1986. };
  1987. fPlugin->process(fPlugin, &process);
  1988. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1989. // --------------------------------------------------------------------------------------------------------
  1990. // Post-processing (dry/wet, volume and balance)
  1991. {
  1992. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1993. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1994. const bool isMono = (pData->audioIn.count == 1);
  1995. bool isPair;
  1996. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1997. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1998. {
  1999. // Dry/Wet
  2000. if (doDryWet)
  2001. {
  2002. const uint32_t c = isMono ? 0 : i;
  2003. for (uint32_t k=0; k < frames; ++k)
  2004. {
  2005. bufValue = audioIn[c][k];
  2006. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  2007. }
  2008. }
  2009. // Balance
  2010. if (doBalance)
  2011. {
  2012. isPair = (i % 2 == 0);
  2013. if (isPair)
  2014. {
  2015. CARLA_ASSERT(i+1 < pData->audioOut.count);
  2016. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  2017. }
  2018. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  2019. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  2020. for (uint32_t k=0; k < frames; ++k)
  2021. {
  2022. if (isPair)
  2023. {
  2024. // left
  2025. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  2026. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  2027. }
  2028. else
  2029. {
  2030. // right
  2031. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  2032. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  2033. }
  2034. }
  2035. }
  2036. // Volume (and buffer copy)
  2037. {
  2038. for (uint32_t k=0; k < frames; ++k)
  2039. audioOut[i][k] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  2040. }
  2041. }
  2042. } // End of Post-processing
  2043. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  2044. // --------------------------------------------------------------------------------------------------------
  2045. pData->singleMutex.unlock();
  2046. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2047. // --------------------------------------------------------------------------------------------------------
  2048. // Control Output
  2049. if (pData->event.portOut != nullptr && fExtensions.params != nullptr)
  2050. {
  2051. uint8_t channel;
  2052. uint16_t param;
  2053. double value;
  2054. for (uint32_t k=0; k < pData->param.count; ++k)
  2055. {
  2056. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  2057. continue;
  2058. if (pData->param.data[k].mappedControlIndex <= 0)
  2059. continue;
  2060. if (!fExtensions.params->get_value(fPlugin, pData->param.data[k].rindex, &value))
  2061. continue;
  2062. channel = pData->param.data[k].midiChannel;
  2063. param = static_cast<uint16_t>(pData->param.data[k].mappedControlIndex);
  2064. value = pData->param.ranges[k].getNormalizedValue(value);
  2065. pData->event.portOut->writeControlEvent(0, channel,
  2066. kEngineControlEventTypeParameter, param, -1,
  2067. value);
  2068. }
  2069. } // End of Control Output
  2070. #endif
  2071. // --------------------------------------------------------------------------------------------------------
  2072. // Events/MIDI Output
  2073. for (uint32_t i=0; i<fOutputEvents.numEventsUsed; ++i)
  2074. {
  2075. const carla_clap_output_events::Event& ev(fOutputEvents.events[i]);
  2076. switch (ev.header.type)
  2077. {
  2078. case CLAP_EVENT_PARAM_VALUE:
  2079. for (uint32_t j=0; j<pData->param.count; ++j)
  2080. {
  2081. if (pData->param.data[j].rindex != static_cast<int32_t>(ev.param.param_id))
  2082. continue;
  2083. pData->postponeParameterChangeRtEvent(true, static_cast<int32_t>(j), ev.param.value);
  2084. break;
  2085. }
  2086. break;
  2087. case CLAP_EVENT_MIDI:
  2088. for (uint32_t j=0; j<fOutputEvents.portCount; ++j)
  2089. {
  2090. if (fOutputEvents.portData[j].clapPortIndex != ev.midi.port_index)
  2091. continue;
  2092. fOutputEvents.portData[j].port->writeMidiEvent(ev.midi.header.time, 3, ev.midi.data);
  2093. break;
  2094. }
  2095. break;
  2096. }
  2097. }
  2098. fOutputEvents.numEventsUsed = 0;
  2099. // --------------------------------------------------------------------------------------------------------
  2100. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2101. return;
  2102. // unused
  2103. (void)cvIn;
  2104. #endif
  2105. }
  2106. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2107. void bufferSizeChanged(const uint32_t newBufferSize) override
  2108. {
  2109. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  2110. carla_debug("CarlaPluginCLAP::bufferSizeChanged(%i)", newBufferSize);
  2111. if (pData->active)
  2112. deactivate();
  2113. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2114. {
  2115. if (fAudioOutBuffers[i] != nullptr)
  2116. delete[] fAudioOutBuffers[i];
  2117. fAudioOutBuffers[i] = new float[newBufferSize];
  2118. }
  2119. if (pData->active)
  2120. activate();
  2121. }
  2122. #endif
  2123. // -------------------------------------------------------------------
  2124. // Plugin buffers
  2125. void initBuffers() const noexcept override
  2126. {
  2127. fInputEvents.initBuffers();
  2128. fOutputEvents.initBuffers();
  2129. CarlaPlugin::initBuffers();
  2130. }
  2131. void clearBuffers() noexcept override
  2132. {
  2133. carla_debug("CarlaPluginCLAP::clearBuffers() - start");
  2134. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2135. if (fAudioOutBuffers != nullptr)
  2136. {
  2137. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2138. {
  2139. if (fAudioOutBuffers[i] != nullptr)
  2140. {
  2141. delete[] fAudioOutBuffers[i];
  2142. fAudioOutBuffers[i] = nullptr;
  2143. }
  2144. }
  2145. delete[] fAudioOutBuffers;
  2146. fAudioOutBuffers = nullptr;
  2147. }
  2148. #endif
  2149. fInputEvents.clear(pData->event.portIn);
  2150. fOutputEvents.clear(pData->event.portOut);
  2151. CarlaPlugin::clearBuffers();
  2152. carla_debug("CarlaPluginCLAP::clearBuffers() - end");
  2153. }
  2154. // -------------------------------------------------------------------
  2155. // Post-poned UI Stuff
  2156. // nothing
  2157. // -------------------------------------------------------------------
  2158. protected:
  2159. #ifdef CLAP_WINDOW_API_NATIVE
  2160. void handlePluginUIClosed() override
  2161. {
  2162. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2163. carla_stdout("CarlaPluginCLAP::handlePluginUIClosed()");
  2164. fUI.shouldClose = true;
  2165. }
  2166. void handlePluginUIResized(const uint width, const uint height) override
  2167. {
  2168. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2169. carla_stdout("CarlaPluginCLAP::handlePluginUIResized(%u, %u | vs %u %u) %d %s %s",
  2170. width, height,
  2171. fUI.width, fUI.height,
  2172. fUI.isResizingFromPlugin, bool2str(fUI.isResizingFromInit), bool2str(fUI.isResizingFromHost));
  2173. if (fExtensions.gui == nullptr)
  2174. return;
  2175. if (fUI.isResizingFromPlugin != 0)
  2176. {
  2177. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2178. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2179. fUI.isResizingFromPlugin = 2;
  2180. return;
  2181. }
  2182. if (fUI.isResizingFromInit)
  2183. {
  2184. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2185. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2186. fUI.isResizingFromInit = false;
  2187. return;
  2188. }
  2189. if (fUI.isResizingFromHost)
  2190. {
  2191. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2192. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2193. fUI.isResizingFromHost = false;
  2194. return;
  2195. }
  2196. if (fUI.width != width || fUI.height != height)
  2197. {
  2198. uint width2 = width;
  2199. uint height2 = height;
  2200. if (fExtensions.gui->adjust_size(fPlugin, &width2, &height2))
  2201. {
  2202. if (width2 != width || height2 != height)
  2203. {
  2204. fUI.isResizingFromHost = true;
  2205. fUI.width = width2;
  2206. fUI.height = height2;
  2207. fUI.window->setSize(width2, height2, false, false);
  2208. }
  2209. else
  2210. {
  2211. fExtensions.gui->set_size(fPlugin, width2, height2);
  2212. }
  2213. }
  2214. }
  2215. }
  2216. #endif
  2217. // -------------------------------------------------------------------
  2218. void clapRequestRestart() override
  2219. {
  2220. carla_stdout("CarlaPluginCLAP::clapRequestRestart()");
  2221. fNeedsRestart = true;
  2222. }
  2223. void clapRequestProcess() override
  2224. {
  2225. carla_stdout("CarlaPluginCLAP::clapRequestProcess()");
  2226. fNeedsProcess = true;
  2227. }
  2228. void clapRequestCallback() override
  2229. {
  2230. carla_stdout("CarlaPluginCLAP::clapRequestCallback()");
  2231. if (fPlugin->on_main_thread != nullptr)
  2232. fNeedsIdleCallback = true;
  2233. }
  2234. // -------------------------------------------------------------------
  2235. void clapLatencyChanged() override
  2236. {
  2237. carla_stdout("CarlaPluginCLAP::clapLatencyChanged()");
  2238. CARLA_SAFE_ASSERT_RETURN(fExtensions.latency != nullptr,);
  2239. fLastKnownLatency = fExtensions.latency->get(fPlugin);
  2240. }
  2241. // -------------------------------------------------------------------
  2242. void clapMarkDirty() override
  2243. {
  2244. carla_stdout("CarlaPluginCLAP::clapMarkDirty()");
  2245. }
  2246. // -------------------------------------------------------------------
  2247. #ifdef CLAP_WINDOW_API_NATIVE
  2248. void clapGuiResizeHintsChanged() override
  2249. {
  2250. carla_stdout("CarlaPluginCLAP::clapGuiResizeHintsChanged()");
  2251. }
  2252. bool clapGuiRequestResize(const uint width, const uint height) override
  2253. {
  2254. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr, false);
  2255. carla_stdout("CarlaPluginCLAP::hostRequestResize(%u, %u)", width, height);
  2256. fUI.isResizingFromPlugin = 3;
  2257. fUI.width = width;
  2258. fUI.height = height;
  2259. fUI.window->setSize(width, height, true, false);
  2260. return true;
  2261. }
  2262. bool clapGuiRequestShow() override
  2263. {
  2264. carla_stdout("CarlaPluginCLAP::clapGuiRequestShow()");
  2265. return false;
  2266. }
  2267. bool clapGuiRequestHide() override
  2268. {
  2269. carla_stdout("CarlaPluginCLAP::clapGuiRequestHide()");
  2270. return false;
  2271. }
  2272. void clapGuiClosed(const bool wasDestroyed) override
  2273. {
  2274. carla_stdout("CarlaPluginCLAP::clapGuiClosed(%s)", bool2str(wasDestroyed));
  2275. CARLA_SAFE_ASSERT_RETURN(!fUI.isEmbed,);
  2276. CARLA_SAFE_ASSERT_RETURN(fUI.isVisible,);
  2277. fUI.isVisible = false;
  2278. if (wasDestroyed)
  2279. {
  2280. CARLA_SAFE_ASSERT_RETURN(fUI.isCreated,);
  2281. fExtensions.gui->destroy(fPlugin);
  2282. fUI.isCreated = false;
  2283. }
  2284. pData->engine->callback(true, true,
  2285. ENGINE_CALLBACK_UI_STATE_CHANGED,
  2286. pData->id,
  2287. 0,
  2288. 0, 0, 0.0f, nullptr);
  2289. }
  2290. // -------------------------------------------------------------------
  2291. #ifdef _POSIX_VERSION
  2292. bool clapRegisterPosixFD(const int fd, const clap_posix_fd_flags_t flags) override
  2293. {
  2294. carla_stdout("CarlaPluginCLAP::clapRegisterPosixFD(%i, %x)", fd, flags);
  2295. // NOTE some plugins wont have their posix fd extension ready when first loaded, so try again here
  2296. if (fExtensions.posixFD == nullptr)
  2297. {
  2298. const clap_plugin_posix_fd_support_t* const posixFdExt = static_cast<const clap_plugin_posix_fd_support_t*>(
  2299. fPlugin->get_extension(fPlugin, CLAP_EXT_POSIX_FD_SUPPORT));
  2300. if (posixFdExt != nullptr && posixFdExt->on_fd != nullptr)
  2301. fExtensions.posixFD = posixFdExt;
  2302. }
  2303. CARLA_SAFE_ASSERT_RETURN(fExtensions.posixFD != nullptr, false);
  2304. // FIXME events only driven as long as UI is open
  2305. // CARLA_SAFE_ASSERT_RETURN(fUI.isCreated, false);
  2306. if (flags & (CLAP_POSIX_FD_READ|CLAP_POSIX_FD_WRITE))
  2307. {
  2308. #ifdef CARLA_CLAP_POSIX_EPOLL
  2309. const int hostFd = ::epoll_create1(0);
  2310. #else
  2311. const int hostFd = ::kqueue();
  2312. #endif
  2313. CARLA_SAFE_ASSERT_RETURN(hostFd >= 0, false);
  2314. #ifdef CARLA_CLAP_POSIX_EPOLL
  2315. struct ::epoll_event ev = {};
  2316. if (flags & CLAP_POSIX_FD_READ)
  2317. ev.events |= EPOLLIN;
  2318. if (flags & CLAP_POSIX_FD_WRITE)
  2319. ev.events |= EPOLLOUT;
  2320. ev.data.fd = fd;
  2321. if (::epoll_ctl(hostFd, EPOLL_CTL_ADD, fd, &ev) < 0)
  2322. {
  2323. ::close(hostFd);
  2324. return false;
  2325. }
  2326. #endif
  2327. const HostPosixFileDescriptorDetails posixFD = {
  2328. hostFd,
  2329. fd,
  2330. flags,
  2331. };
  2332. fPosixFileDescriptors.append(posixFD);
  2333. return true;
  2334. }
  2335. return false;
  2336. }
  2337. bool clapModifyPosixFD(const int fd, const clap_posix_fd_flags_t flags) override
  2338. {
  2339. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%i, %x)", fd, flags);
  2340. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2341. {
  2342. HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallbackNC));
  2343. if (posixFD.pluginFd == fd)
  2344. {
  2345. if (posixFD.flags == flags)
  2346. return true;
  2347. #ifdef CARLA_CLAP_POSIX_EPOLL
  2348. struct ::epoll_event ev = {};
  2349. if (flags & CLAP_POSIX_FD_READ)
  2350. ev.events |= EPOLLIN;
  2351. if (flags & CLAP_POSIX_FD_WRITE)
  2352. ev.events |= EPOLLOUT;
  2353. ev.data.fd = fd;
  2354. if (::epoll_ctl(posixFD.hostFd, EPOLL_CTL_MOD, fd, &ev) < 0)
  2355. return false;
  2356. #endif
  2357. posixFD.flags = flags;
  2358. return true;
  2359. }
  2360. }
  2361. return false;
  2362. }
  2363. bool clapUnregisterPosixFD(const int fd) override
  2364. {
  2365. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%i)", fd);
  2366. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2367. {
  2368. const HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallback));
  2369. if (posixFD.pluginFd == fd)
  2370. {
  2371. #ifdef CARLA_CLAP_POSIX_EPOLL
  2372. ::epoll_ctl(posixFD.hostFd, EPOLL_CTL_DEL, fd, nullptr);
  2373. #endif
  2374. ::close(posixFD.hostFd);
  2375. fPosixFileDescriptors.remove(it);
  2376. return true;
  2377. }
  2378. }
  2379. return false;
  2380. }
  2381. #endif // _POSIX_VERSION
  2382. // -------------------------------------------------------------------
  2383. bool clapRegisterTimer(const uint32_t periodInMs, clap_id* const timerId) override
  2384. {
  2385. carla_stdout("CarlaPluginCLAP::clapTimerRegister(%u, %p)", periodInMs, timerId);
  2386. // NOTE some plugins wont have their timer extension ready when first loaded, so try again here
  2387. if (fExtensions.timer == nullptr)
  2388. {
  2389. const clap_plugin_timer_support_t* const timerExt = static_cast<const clap_plugin_timer_support_t*>(
  2390. fPlugin->get_extension(fPlugin, CLAP_EXT_TIMER_SUPPORT));
  2391. if (timerExt != nullptr && timerExt->on_timer != nullptr)
  2392. fExtensions.timer = timerExt;
  2393. }
  2394. CARLA_SAFE_ASSERT_RETURN(fExtensions.timer != nullptr, false);
  2395. // FIXME events only driven as long as UI is open
  2396. // CARLA_SAFE_ASSERT_RETURN(fUI.isCreated, false);
  2397. const HostTimerDetails timer = {
  2398. fTimers.isNotEmpty() ? fTimers.getLast(kTimerFallback).clapId + 1 : 1,
  2399. periodInMs,
  2400. 0
  2401. };
  2402. fTimers.append(timer);
  2403. *timerId = timer.clapId;
  2404. return true;
  2405. }
  2406. bool clapUnregisterTimer(const clap_id timerId) override
  2407. {
  2408. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%u)", timerId);
  2409. for (LinkedList<HostTimerDetails>::Itenerator it = fTimers.begin2(); it.valid(); it.next())
  2410. {
  2411. const HostTimerDetails& timer(it.getValue(kTimerFallback));
  2412. if (timer.clapId == timerId)
  2413. {
  2414. fTimers.remove(it);
  2415. return true;
  2416. }
  2417. }
  2418. return false;
  2419. }
  2420. #endif // CLAP_WINDOW_API_NATIVE
  2421. // -------------------------------------------------------------------
  2422. public:
  2423. bool init(const CarlaPluginPtr plugin,
  2424. const char* const filename, const char* const name, const char* const id, const uint options)
  2425. {
  2426. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  2427. // ---------------------------------------------------------------
  2428. // first checks
  2429. if (pData->client != nullptr)
  2430. {
  2431. pData->engine->setLastError("Plugin client is already registered");
  2432. return false;
  2433. }
  2434. if (filename == nullptr || filename[0] == '\0')
  2435. {
  2436. pData->engine->setLastError("null filename");
  2437. return false;
  2438. }
  2439. // ---------------------------------------------------------------
  2440. const clap_plugin_entry_t* entry;
  2441. #ifdef CARLA_OS_MAC
  2442. if (!water::File(filename).existsAsFile())
  2443. {
  2444. if (! fBundleLoader.load(filename))
  2445. {
  2446. pData->engine->setLastError("Failed to load CLAP bundle executable");
  2447. return false;
  2448. }
  2449. entry = fBundleLoader.getSymbol<const clap_plugin_entry_t*>(CFSTR("clap_entry"));
  2450. }
  2451. else
  2452. #endif
  2453. {
  2454. if (! pData->libOpen(filename))
  2455. {
  2456. pData->engine->setLastError(pData->libError(filename));
  2457. return false;
  2458. }
  2459. entry = pData->libSymbol<const clap_plugin_entry_t*>("clap_entry");
  2460. }
  2461. if (entry == nullptr)
  2462. {
  2463. pData->engine->setLastError("Could not find the CLAP entry in the plugin library");
  2464. return false;
  2465. }
  2466. if (entry->init == nullptr || entry->deinit == nullptr || entry->get_factory == nullptr)
  2467. {
  2468. pData->engine->setLastError("CLAP factory entries are null");
  2469. return false;
  2470. }
  2471. if (!clap_version_is_compatible(entry->clap_version))
  2472. {
  2473. pData->engine->setLastError("Incompatible CLAP plugin");
  2474. return false;
  2475. }
  2476. // ---------------------------------------------------------------
  2477. const water::String pluginPath(water::File(filename).getParentDirectory().getFullPathName());
  2478. if (!entry->init(pluginPath.toRawUTF8()))
  2479. {
  2480. pData->engine->setLastError("Plugin entry failed to initialize");
  2481. return false;
  2482. }
  2483. fPluginEntry = entry;
  2484. // ---------------------------------------------------------------
  2485. const clap_plugin_factory_t* const factory = static_cast<const clap_plugin_factory_t*>(
  2486. entry->get_factory(CLAP_PLUGIN_FACTORY_ID));
  2487. if (factory == nullptr
  2488. || factory->get_plugin_count == nullptr
  2489. || factory->get_plugin_descriptor == nullptr
  2490. || factory->create_plugin == nullptr)
  2491. {
  2492. pData->engine->setLastError("Plugin is missing factory methods");
  2493. return false;
  2494. }
  2495. // ---------------------------------------------------------------
  2496. if (const uint32_t count = factory->get_plugin_count(factory))
  2497. {
  2498. // null id requested, use first available plugin
  2499. if (id == nullptr || id[0] == '\0')
  2500. {
  2501. fPluginDescriptor = factory->get_plugin_descriptor(factory, 0);
  2502. if (fPluginDescriptor == nullptr)
  2503. {
  2504. pData->engine->setLastError("Plugin library does not contain a valid first plugin");
  2505. return false;
  2506. }
  2507. }
  2508. else
  2509. {
  2510. for (uint32_t i=0; i<count; ++i)
  2511. {
  2512. const clap_plugin_descriptor_t* const desc = factory->get_plugin_descriptor(factory, i);
  2513. CARLA_SAFE_ASSERT_CONTINUE(desc != nullptr);
  2514. CARLA_SAFE_ASSERT_CONTINUE(desc->id != nullptr);
  2515. if (std::strcmp(desc->id, id) == 0)
  2516. {
  2517. fPluginDescriptor = desc;
  2518. break;
  2519. }
  2520. }
  2521. if (fPluginDescriptor == nullptr)
  2522. {
  2523. pData->engine->setLastError("Plugin library does not contain the requested plugin");
  2524. return false;
  2525. }
  2526. }
  2527. }
  2528. else
  2529. {
  2530. pData->engine->setLastError("Plugin library contains no plugins");
  2531. return false;
  2532. }
  2533. // ---------------------------------------------------------------
  2534. fPlugin = factory->create_plugin(factory, &fHost, fPluginDescriptor->id);
  2535. if (fPlugin == nullptr)
  2536. {
  2537. pData->engine->setLastError("Failed to create CLAP plugin instance");
  2538. return false;
  2539. }
  2540. if (!fPlugin->init(fPlugin))
  2541. {
  2542. pData->engine->setLastError("Failed to initialize CLAP plugin instance");
  2543. return false;
  2544. }
  2545. // ---------------------------------------------------------------
  2546. // get info
  2547. pData->name = pData->engine->getUniquePluginName(name != nullptr && name[0] != '\0' ? name
  2548. : fPluginDescriptor->name);
  2549. pData->filename = carla_strdup(filename);
  2550. // ---------------------------------------------------------------
  2551. // register client
  2552. pData->client = pData->engine->addClient(plugin);
  2553. if (pData->client == nullptr || ! pData->client->isOk())
  2554. {
  2555. pData->engine->setLastError("Failed to register plugin client");
  2556. return false;
  2557. }
  2558. // ---------------------------------------------------------------
  2559. // set default options
  2560. pData->options = PLUGIN_OPTION_FIXED_BUFFERS;
  2561. if (const clap_plugin_state_t* const stateExt =
  2562. static_cast<const clap_plugin_state_t*>(fPlugin->get_extension(fPlugin, CLAP_EXT_STATE)))
  2563. {
  2564. if (stateExt->save != nullptr && stateExt->load != nullptr)
  2565. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2566. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2567. }
  2568. if (const clap_plugin_note_ports_t* const notePortsExt =
  2569. static_cast<const clap_plugin_note_ports_t*>(fPlugin->get_extension(fPlugin, CLAP_EXT_NOTE_PORTS)))
  2570. {
  2571. const uint32_t numNoteInputPorts = notePortsExt->count != nullptr && notePortsExt->get != nullptr
  2572. ? notePortsExt->count(fPlugin, true) : 0;
  2573. for (uint32_t i=0; i<numNoteInputPorts; ++i)
  2574. {
  2575. clap_note_port_info_t portInfo = {};
  2576. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  2577. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI)
  2578. {
  2579. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2580. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2581. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2582. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2583. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2584. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2585. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2586. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2587. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2588. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2589. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2590. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2591. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2592. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2593. break;
  2594. }
  2595. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_CLAP)
  2596. {
  2597. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2598. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2599. // nobreak, in case another port supports MIDI
  2600. }
  2601. }
  2602. }
  2603. // if (fEffect->numPrograms > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  2604. // if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2605. // pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2606. return true;
  2607. }
  2608. private:
  2609. const clap_plugin_t* fPlugin;
  2610. const clap_plugin_descriptor_t* fPluginDescriptor;
  2611. const clap_plugin_entry_t* fPluginEntry;
  2612. const carla_clap_host fHost;
  2613. struct Extensions {
  2614. const clap_plugin_latency_t* latency;
  2615. const clap_plugin_params_t* params;
  2616. const clap_plugin_state_t* state;
  2617. const clap_plugin_timer_support_t* timer;
  2618. #ifdef CLAP_WINDOW_API_NATIVE
  2619. const clap_plugin_gui_t* gui;
  2620. #ifdef _POSIX_VERSION
  2621. const clap_plugin_posix_fd_support_t* posixFD;
  2622. #endif
  2623. #endif
  2624. Extensions()
  2625. : latency(nullptr),
  2626. params(nullptr),
  2627. state(nullptr),
  2628. timer(nullptr)
  2629. #ifdef CLAP_WINDOW_API_NATIVE
  2630. , gui(nullptr)
  2631. #ifdef _POSIX_VERSION
  2632. , posixFD(nullptr)
  2633. #endif
  2634. #endif
  2635. {
  2636. }
  2637. CARLA_DECLARE_NON_COPYABLE(Extensions)
  2638. } fExtensions;
  2639. #ifdef CLAP_WINDOW_API_NATIVE
  2640. struct UI {
  2641. bool initalized;
  2642. bool isCreated;
  2643. bool isEmbed;
  2644. bool isVisible;
  2645. bool isResizingFromHost;
  2646. bool isResizingFromInit;
  2647. int isResizingFromPlugin;
  2648. bool shouldClose;
  2649. uint32_t width, height;
  2650. CarlaPluginUI* window;
  2651. UI()
  2652. : initalized(false),
  2653. isCreated(false),
  2654. isEmbed(false),
  2655. isVisible(false),
  2656. isResizingFromHost(false),
  2657. isResizingFromInit(false),
  2658. isResizingFromPlugin(0),
  2659. shouldClose(false),
  2660. width(0),
  2661. height(0),
  2662. window(nullptr) {}
  2663. ~UI()
  2664. {
  2665. CARLA_SAFE_ASSERT(window == nullptr);
  2666. }
  2667. CARLA_DECLARE_NON_COPYABLE(UI)
  2668. } fUI;
  2669. #ifdef _POSIX_VERSION
  2670. LinkedList<HostPosixFileDescriptorDetails> fPosixFileDescriptors;
  2671. #endif
  2672. LinkedList<HostTimerDetails> fTimers;
  2673. #endif
  2674. carla_clap_input_audio_buffers fInputAudioBuffers;
  2675. carla_clap_output_audio_buffers fOutputAudioBuffers;
  2676. carla_clap_input_events fInputEvents;
  2677. carla_clap_output_events fOutputEvents;
  2678. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2679. float** fAudioOutBuffers;
  2680. #endif
  2681. void* fLastChunk;
  2682. uint32_t fLastKnownLatency;
  2683. const bool kEngineHasIdleOnMainThread;
  2684. bool fNeedsParamFlush;
  2685. bool fNeedsRestart;
  2686. bool fNeedsProcess;
  2687. bool fNeedsIdleCallback;
  2688. #ifdef CARLA_OS_MAC
  2689. BundleLoader fBundleLoader;
  2690. #endif
  2691. void runIdleCallbacksAsNeeded(const bool isIdleCallback)
  2692. {
  2693. if (isIdleCallback && (fNeedsRestart || fNeedsProcess))
  2694. {
  2695. carla_stdout("runIdleCallbacksAsNeeded %d %d", fNeedsRestart, fNeedsProcess);
  2696. const bool needsRestart = fNeedsRestart;
  2697. if (needsRestart)
  2698. {
  2699. fNeedsRestart = false;
  2700. setActive(false, true, true);
  2701. }
  2702. if (fNeedsProcess)
  2703. {
  2704. fNeedsProcess = false;
  2705. setEnabled(true);
  2706. setActive(true, true, true);
  2707. }
  2708. else if (needsRestart)
  2709. {
  2710. setActive(true, true, true);
  2711. }
  2712. }
  2713. if (fNeedsParamFlush)
  2714. {
  2715. fNeedsParamFlush = false;
  2716. carla_clap_input_events copy;
  2717. copy.reallocEqualTo(fInputEvents);
  2718. {
  2719. const ScopedSingleProcessLocker sspl(this, true);
  2720. fInputEvents.handleScheduledParameterUpdates();
  2721. fInputEvents.swap(copy);
  2722. }
  2723. fExtensions.params->flush(fPlugin, copy.cast(), nullptr);
  2724. }
  2725. if (fNeedsIdleCallback)
  2726. {
  2727. fNeedsIdleCallback = false;
  2728. fPlugin->on_main_thread(fPlugin);
  2729. }
  2730. #ifdef CLAP_WINDOW_API_NATIVE
  2731. #ifdef _POSIX_VERSION
  2732. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2733. {
  2734. const HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallback));
  2735. #ifdef CARLA_CLAP_POSIX_EPOLL
  2736. struct ::epoll_event event;
  2737. #else
  2738. const int16_t filter = posixFD.flags & CLAP_POSIX_FD_WRITE ? EVFILT_WRITE : EVFILT_READ;
  2739. struct ::kevent kev = {}, event;
  2740. struct ::timespec timeout = {};
  2741. EV_SET(&kev, posixFD.pluginFd, filter, EV_ADD|EV_ENABLE, 0, 0, nullptr);
  2742. #endif
  2743. for (int i=0; i<50; ++i)
  2744. {
  2745. #ifdef CARLA_CLAP_POSIX_EPOLL
  2746. switch (::epoll_wait(posixFD.hostFd, &event, 1, 0))
  2747. #else
  2748. switch (::kevent(posixFD.hostFd, &kev, 1, &event, 1, &timeout))
  2749. #endif
  2750. {
  2751. case 1:
  2752. fExtensions.posixFD->on_fd(fPlugin, posixFD.pluginFd, posixFD.flags);
  2753. break;
  2754. case -1:
  2755. fExtensions.posixFD->on_fd(fPlugin, posixFD.pluginFd, posixFD.flags | CLAP_POSIX_FD_ERROR);
  2756. // fall through
  2757. case 0:
  2758. i = 50;
  2759. break;
  2760. default:
  2761. carla_safe_exception("posix fd received abnormal value", __FILE__, __LINE__);
  2762. i = 50;
  2763. break;
  2764. }
  2765. }
  2766. }
  2767. #endif // _POSIX_VERSION
  2768. const uint32_t currentTimeInMs = water::Time::getMillisecondCounter();
  2769. for (LinkedList<HostTimerDetails>::Itenerator it = fTimers.begin2(); it.valid(); it.next())
  2770. {
  2771. HostTimerDetails& timer(it.getValue(kTimerFallbackNC));
  2772. if (currentTimeInMs > timer.lastCallTimeInMs + timer.periodInMs)
  2773. {
  2774. timer.lastCallTimeInMs = currentTimeInMs;
  2775. fExtensions.timer->on_timer(fPlugin, timer.clapId);
  2776. }
  2777. }
  2778. #endif // CLAP_WINDOW_API_NATIVE
  2779. }
  2780. };
  2781. // --------------------------------------------------------------------------------------------------------------------
  2782. CarlaPluginPtr CarlaPlugin::newCLAP(const Initializer& init)
  2783. {
  2784. carla_debug("CarlaPlugin::newCLAP({%p, \"%s\", \"%s\", \"%s\"})",
  2785. init.engine, init.filename, init.name, init.label);
  2786. std::shared_ptr<CarlaPluginCLAP> plugin(new CarlaPluginCLAP(init.engine, init.id));
  2787. if (! plugin->init(plugin, init.filename, init.name, init.label, init.options))
  2788. return nullptr;
  2789. return plugin;
  2790. }
  2791. // -------------------------------------------------------------------------------------------------------------------
  2792. CARLA_BACKEND_END_NAMESPACE