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

2 years ago
2 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452
  1. /*
  2. * Carla CLAP Plugin
  3. * Copyright (C) 2022-2023 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 const void* CLAP_ABI 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 void CLAP_ABI 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 void CLAP_ABI 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 void CLAP_ABI 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 void CLAP_ABI 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 void CLAP_ABI 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 void CLAP_ABI 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 bool CLAP_ABI 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 bool CLAP_ABI 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 bool CLAP_ABI 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 void CLAP_ABI 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 bool CLAP_ABI 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 bool CLAP_ABI 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 bool CLAP_ABI 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 bool CLAP_ABI 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 bool CLAP_ABI 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 uint32_t CLAP_ABI 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 const clap_event_header_t* CLAP_ABI 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 bool CLAP_ABI 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. strBuf[STR_MAX-1] = '\0';
  799. return true;
  800. }
  801. bool getParameterSymbol(const uint32_t parameterId, char* const strBuf) const noexcept override
  802. {
  803. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  804. const clap_id clapId = pData->param.data[parameterId].rindex;
  805. std::snprintf(strBuf, STR_MAX, "%u", clapId);
  806. return true;
  807. }
  808. bool getParameterText(const uint32_t parameterId, char* const strBuf) noexcept override
  809. {
  810. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, false);
  811. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, false);
  812. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  813. const clap_id clapId = pData->param.data[parameterId].rindex;
  814. const double value = getBestParameterValue(parameterId, clapId);
  815. return fExtensions.params->value_to_text(fPlugin, clapId, value, strBuf, STR_MAX);
  816. }
  817. bool getParameterGroupName(const uint32_t parameterId, char* const strBuf) const noexcept override
  818. {
  819. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, false);
  820. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, false);
  821. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  822. clap_param_info_t paramInfo = {};
  823. CARLA_SAFE_ASSERT_RETURN(fExtensions.params->get_info(fPlugin, parameterId, &paramInfo), false);
  824. if (paramInfo.module[0] == '\0')
  825. return false;
  826. if (char* const sep = std::strrchr(paramInfo.module, '/'))
  827. {
  828. paramInfo.module[STR_MAX/2-2] = sep[0] = '\0';
  829. char strBuf2[STR_MAX/2];
  830. std::strncpy(strBuf2, paramInfo.module, STR_MAX/2);
  831. strBuf2[STR_MAX/2-1] = '\0';
  832. std::snprintf(strBuf, STR_MAX, "%s:%s", strBuf2, strBuf2);
  833. strBuf[STR_MAX-1] = '\0';
  834. return true;
  835. }
  836. return false;
  837. }
  838. // -------------------------------------------------------------------
  839. // Set data (state)
  840. // nothing
  841. // -------------------------------------------------------------------
  842. // Set data (internal stuff)
  843. #ifdef CLAP_WINDOW_API_NATIVE
  844. void setName(const char* const newName) override
  845. {
  846. CarlaPlugin::setName(newName);
  847. if (fUI.isCreated && pData->uiTitle.isEmpty())
  848. setWindowTitle(nullptr);
  849. }
  850. #endif
  851. // -------------------------------------------------------------------
  852. // Set data (plugin-specific stuff)
  853. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  854. {
  855. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  856. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  857. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  858. fInputEvents.setParamValue(parameterId, fixedValue);
  859. if (!pData->active && fExtensions.params->flush != nullptr)
  860. fNeedsParamFlush = true;
  861. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  862. }
  863. void setParameterValueRT(const uint32_t parameterId, const float value, const uint32_t frameOffset, const bool sendCallbackLater) noexcept override
  864. {
  865. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  866. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  867. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  868. fInputEvents.setParamValueRT(parameterId, fixedValue, frameOffset);
  869. CarlaPlugin::setParameterValueRT(parameterId, fixedValue, frameOffset, sendCallbackLater);
  870. }
  871. void setChunkData(const void* const data, const std::size_t dataSize) override
  872. {
  873. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  874. CARLA_SAFE_ASSERT_RETURN(fExtensions.state != nullptr,);
  875. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  876. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  877. const clap_istream_impl stream(data, dataSize);
  878. if (fExtensions.state->load(fPlugin, &stream))
  879. pData->updateParameterValues(this, true, true, false);
  880. runIdleCallbacksAsNeeded(false);
  881. }
  882. // -------------------------------------------------------------------
  883. // Set ui stuff
  884. #ifdef CLAP_WINDOW_API_NATIVE
  885. void setWindowTitle(const char* const title) noexcept
  886. {
  887. if (!fUI.isCreated)
  888. return;
  889. CarlaString uiTitle;
  890. if (title != nullptr)
  891. {
  892. uiTitle = title;
  893. }
  894. else
  895. {
  896. uiTitle = pData->name;
  897. uiTitle += " (GUI)";
  898. }
  899. if (fUI.isEmbed)
  900. {
  901. if (fUI.window != nullptr)
  902. fUI.window->setTitle(uiTitle.buffer());
  903. }
  904. else
  905. {
  906. fExtensions.gui->suggest_title(fPlugin, uiTitle.buffer());
  907. }
  908. }
  909. void setCustomUITitle(const char* const title) noexcept override
  910. {
  911. setWindowTitle(title);
  912. CarlaPlugin::setCustomUITitle(title);
  913. }
  914. void showCustomUI(const bool yesNo) override
  915. {
  916. CARLA_SAFE_ASSERT_RETURN(fExtensions.gui != nullptr,);
  917. if (fUI.isVisible == yesNo)
  918. return;
  919. if (yesNo)
  920. {
  921. if (fUI.isVisible)
  922. {
  923. fExtensions.gui->show(fPlugin);
  924. if (fUI.isEmbed)
  925. {
  926. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  927. fUI.window->show();
  928. fUI.window->focus();
  929. }
  930. runIdleCallbacksAsNeeded(false);
  931. return;
  932. }
  933. if (!fUI.initalized)
  934. {
  935. fUI.isEmbed = fExtensions.gui->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, false);
  936. fUI.initalized = true;
  937. }
  938. if (!fUI.isCreated)
  939. {
  940. if (!fExtensions.gui->create(fPlugin, CLAP_WINDOW_API_NATIVE, !fUI.isEmbed))
  941. {
  942. pData->engine->callback(true, true,
  943. ENGINE_CALLBACK_UI_STATE_CHANGED,
  944. pData->id,
  945. -1,
  946. 0, 0, 0.0f,
  947. "Plugin refused to open its own UI");
  948. return;
  949. }
  950. fUI.isCreated = true;
  951. }
  952. const bool resizable = fExtensions.gui->can_resize(fPlugin);
  953. const EngineOptions& opts(pData->engine->getOptions());
  954. #if defined(CARLA_OS_WIN)
  955. fUI.window = CarlaPluginUI::newWindows(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable);
  956. #elif defined(CARLA_OS_MAC)
  957. fUI.window = CarlaPluginUI::newCocoa(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable);
  958. #elif defined(HAVE_X11)
  959. fUI.window = CarlaPluginUI::newX11(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable, false);
  960. #else
  961. pData->engine->callback(true, true,
  962. ENGINE_CALLBACK_UI_STATE_CHANGED,
  963. pData->id,
  964. -1,
  965. 0, 0, 0.0f,
  966. "Unsupported UI type");
  967. return;
  968. #endif
  969. #ifndef CARLA_OS_MAC
  970. if (carla_isNotZero(opts.uiScale))
  971. fExtensions.gui->set_scale(fPlugin, opts.uiScale);
  972. #endif
  973. setWindowTitle(nullptr);
  974. if (fUI.isEmbed)
  975. {
  976. clap_window_t win = { CLAP_WINDOW_API_NATIVE, {} };
  977. win.ptr = fUI.window->getPtr();
  978. fExtensions.gui->set_parent(fPlugin, &win);
  979. uint32_t width, height;
  980. if (fExtensions.gui->get_size(fPlugin, &width, &height))
  981. {
  982. fUI.isResizingFromInit = true;
  983. fUI.width = width;
  984. fUI.height = height;
  985. fUI.window->setSize(width, height, true, true);
  986. }
  987. fExtensions.gui->show(fPlugin);
  988. fUI.window->show();
  989. }
  990. else
  991. {
  992. clap_window_t win = { CLAP_WINDOW_API_NATIVE, {} };
  993. win.uptr = opts.frontendWinId;
  994. fExtensions.gui->set_transient(fPlugin, &win);
  995. fExtensions.gui->show(fPlugin);
  996. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  997. pData->tryTransient();
  998. #endif
  999. }
  1000. fUI.isVisible = true;
  1001. }
  1002. else
  1003. {
  1004. fUI.isVisible = false;
  1005. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1006. pData->transientTryCounter = 0;
  1007. #endif
  1008. if (fUI.window != nullptr)
  1009. fUI.window->hide();
  1010. fExtensions.gui->hide(fPlugin);
  1011. if (fUI.isCreated)
  1012. {
  1013. fExtensions.gui->destroy(fPlugin);
  1014. fUI.isCreated = false;
  1015. }
  1016. if (fUI.window != nullptr)
  1017. {
  1018. delete fUI.window;
  1019. fUI.window = nullptr;
  1020. }
  1021. }
  1022. runIdleCallbacksAsNeeded(true);
  1023. }
  1024. void* embedCustomUI(void* const ptr) override
  1025. {
  1026. CARLA_SAFE_ASSERT_RETURN(fUI.window == nullptr, nullptr);
  1027. if (!fUI.initalized)
  1028. {
  1029. fUI.isEmbed = fExtensions.gui->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, false);
  1030. fUI.initalized = true;
  1031. }
  1032. if (!fUI.isCreated)
  1033. {
  1034. if (!fExtensions.gui->create(fPlugin, CLAP_WINDOW_API_NATIVE, false))
  1035. {
  1036. pData->engine->callback(true, true,
  1037. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1038. pData->id,
  1039. -1,
  1040. 0, 0, 0.0f,
  1041. "Plugin refused to open its own UI");
  1042. return nullptr;
  1043. }
  1044. fUI.isCreated = true;
  1045. }
  1046. fUI.isVisible = true;
  1047. #ifndef CARLA_OS_MAC
  1048. const EngineOptions& opts(pData->engine->getOptions());
  1049. if (carla_isNotZero(opts.uiScale))
  1050. fExtensions.gui->set_scale(fPlugin, opts.uiScale);
  1051. #endif
  1052. clap_window_t win = { CLAP_WINDOW_API_NATIVE, {} };
  1053. win.ptr = ptr;
  1054. fExtensions.gui->set_parent(fPlugin, &win);
  1055. uint32_t width, height;
  1056. if (fExtensions.gui->get_size(fPlugin, &width, &height))
  1057. {
  1058. fUI.isResizingFromInit = true;
  1059. fUI.width = width;
  1060. fUI.height = height;
  1061. pData->engine->callback(true, true,
  1062. ENGINE_CALLBACK_EMBED_UI_RESIZED,
  1063. pData->id, width, height,
  1064. 0, 0.0f, nullptr);
  1065. }
  1066. fExtensions.gui->show(fPlugin);
  1067. return nullptr;
  1068. }
  1069. #endif
  1070. void idle() override
  1071. {
  1072. if (kEngineHasIdleOnMainThread)
  1073. runIdleCallbacksAsNeeded(true);
  1074. CarlaPlugin::idle();
  1075. }
  1076. void uiIdle() override
  1077. {
  1078. #ifdef CLAP_WINDOW_API_NATIVE
  1079. if (fUI.shouldClose)
  1080. {
  1081. fUI.shouldClose = false;
  1082. fUI.isResizingFromHost = fUI.isResizingFromInit = false;
  1083. fUI.isResizingFromPlugin = 0;
  1084. showCustomUI(false);
  1085. pData->engine->callback(true, true,
  1086. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1087. pData->id,
  1088. 0,
  1089. 0, 0, 0.0f, nullptr);
  1090. }
  1091. if (fUI.isResizingFromHost)
  1092. {
  1093. fUI.isResizingFromHost = false;
  1094. if (fUI.isResizingFromPlugin == 0 && !fUI.isResizingFromInit == false)
  1095. {
  1096. carla_stdout("Host resize restarted");
  1097. fExtensions.gui->set_size(fPlugin, fUI.width, fUI.height);
  1098. }
  1099. }
  1100. if (fUI.window != nullptr)
  1101. fUI.window->idle();
  1102. if (fUI.isResizingFromPlugin == 2)
  1103. {
  1104. fUI.isResizingFromPlugin = 1;
  1105. }
  1106. else if (fUI.isResizingFromPlugin == 1)
  1107. {
  1108. fUI.isResizingFromPlugin = 0;
  1109. carla_stdout("Plugin resize stopped");
  1110. }
  1111. #endif
  1112. if (!kEngineHasIdleOnMainThread)
  1113. runIdleCallbacksAsNeeded(true);
  1114. CarlaPlugin::uiIdle();
  1115. }
  1116. // -------------------------------------------------------------------
  1117. // Plugin state
  1118. void reload() override
  1119. {
  1120. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  1121. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1122. carla_debug("CarlaPluginCLAP::reload() - start");
  1123. // Safely disable plugin for reload
  1124. const ScopedDisabler sd(this);
  1125. if (pData->active)
  1126. deactivate();
  1127. clearBuffers();
  1128. const clap_plugin_audio_ports_t* audioPortsExt = static_cast<const clap_plugin_audio_ports_t*>(
  1129. fPlugin->get_extension(fPlugin, CLAP_EXT_AUDIO_PORTS));
  1130. const clap_plugin_latency_t* latencyExt = static_cast<const clap_plugin_latency_t*>(
  1131. fPlugin->get_extension(fPlugin, CLAP_EXT_LATENCY));
  1132. const clap_plugin_note_ports_t* notePortsExt = static_cast<const clap_plugin_note_ports_t*>(
  1133. fPlugin->get_extension(fPlugin, CLAP_EXT_NOTE_PORTS));
  1134. const clap_plugin_params_t* paramsExt = static_cast<const clap_plugin_params_t*>(
  1135. fPlugin->get_extension(fPlugin, CLAP_EXT_PARAMS));
  1136. const clap_plugin_state_t* stateExt = static_cast<const clap_plugin_state_t*>(
  1137. fPlugin->get_extension(fPlugin, CLAP_EXT_STATE));
  1138. const clap_plugin_timer_support_t* timerExt = static_cast<const clap_plugin_timer_support_t*>(
  1139. fPlugin->get_extension(fPlugin, CLAP_EXT_TIMER_SUPPORT));
  1140. if (audioPortsExt != nullptr && (audioPortsExt->count == nullptr || audioPortsExt->get == nullptr))
  1141. audioPortsExt = nullptr;
  1142. if (latencyExt != nullptr && latencyExt->get == nullptr)
  1143. latencyExt = nullptr;
  1144. if (notePortsExt != nullptr && (notePortsExt->count == nullptr || notePortsExt->get == nullptr))
  1145. notePortsExt = nullptr;
  1146. if (paramsExt != nullptr && (paramsExt->count == nullptr || paramsExt->get_info == nullptr))
  1147. paramsExt = nullptr;
  1148. if (stateExt != nullptr && (stateExt->save == nullptr || stateExt->load == nullptr))
  1149. stateExt = nullptr;
  1150. if (timerExt != nullptr && timerExt->on_timer == nullptr)
  1151. timerExt = nullptr;
  1152. fExtensions.latency = latencyExt;
  1153. fExtensions.params = paramsExt;
  1154. fExtensions.state = stateExt;
  1155. fExtensions.timer = timerExt;
  1156. #ifdef CLAP_WINDOW_API_NATIVE
  1157. const clap_plugin_gui_t* guiExt = static_cast<const clap_plugin_gui_t*>(
  1158. fPlugin->get_extension(fPlugin, CLAP_EXT_GUI));
  1159. if (guiExt != nullptr && (guiExt->is_api_supported == nullptr
  1160. || guiExt->create == nullptr
  1161. || guiExt->destroy == nullptr
  1162. || guiExt->set_scale == nullptr
  1163. || guiExt->get_size == nullptr
  1164. || guiExt->can_resize == nullptr
  1165. || guiExt->get_resize_hints == nullptr
  1166. || guiExt->adjust_size == nullptr
  1167. || guiExt->set_size == nullptr
  1168. || guiExt->set_parent == nullptr
  1169. || guiExt->set_transient == nullptr
  1170. || guiExt->suggest_title == nullptr
  1171. || guiExt->show == nullptr
  1172. || guiExt->hide == nullptr))
  1173. guiExt = nullptr;
  1174. fExtensions.gui = guiExt;
  1175. #endif
  1176. #if defined(CLAP_WINDOW_API_NATIVE) && defined(_POSIX_VERSION)
  1177. const clap_plugin_posix_fd_support_t* posixFdExt = static_cast<const clap_plugin_posix_fd_support_t*>(
  1178. fPlugin->get_extension(fPlugin, CLAP_EXT_POSIX_FD_SUPPORT));
  1179. if (posixFdExt != nullptr && posixFdExt->on_fd == nullptr)
  1180. posixFdExt = nullptr;
  1181. fExtensions.posixFD = posixFdExt;
  1182. #endif
  1183. const uint32_t numAudioInputPorts = audioPortsExt != nullptr ? audioPortsExt->count(fPlugin, true) : 0;
  1184. const uint32_t numAudioOutputPorts = audioPortsExt != nullptr ? audioPortsExt->count(fPlugin, false) : 0;
  1185. const uint32_t numNoteInputPorts = notePortsExt != nullptr ? notePortsExt->count(fPlugin, true) : 0;
  1186. const uint32_t numNoteOutputPorts = notePortsExt != nullptr ? notePortsExt->count(fPlugin, false) : 0;
  1187. const uint32_t numParameters = paramsExt != nullptr ? paramsExt->count(fPlugin) : 0;
  1188. uint32_t aIns, aOuts, mIns, mOuts, params;
  1189. aIns = aOuts = mIns = mOuts = params = 0;
  1190. bool needsCtrlIn, needsCtrlOut;
  1191. needsCtrlIn = needsCtrlOut = false;
  1192. fInputAudioBuffers.realloc(numAudioInputPorts);
  1193. fOutputAudioBuffers.realloc(numAudioOutputPorts);
  1194. for (uint32_t i=0; i<numAudioInputPorts; ++i)
  1195. {
  1196. clap_audio_port_info_t portInfo = {};
  1197. CARLA_SAFE_ASSERT_BREAK(audioPortsExt->get(fPlugin, i, true, &portInfo));
  1198. CARLA_SAFE_ASSERT(portInfo.channel_count != 0);
  1199. fInputAudioBuffers.buffers[i].channel_count = portInfo.channel_count;
  1200. fInputAudioBuffers.extra[i].offset = aIns;
  1201. fInputAudioBuffers.extra[i].isMain = portInfo.flags & CLAP_AUDIO_PORT_IS_MAIN;
  1202. aIns += portInfo.channel_count;
  1203. }
  1204. for (uint32_t i=0; i<numAudioOutputPorts; ++i)
  1205. {
  1206. clap_audio_port_info_t portInfo = {};
  1207. CARLA_SAFE_ASSERT_BREAK(audioPortsExt->get(fPlugin, i, false, &portInfo));
  1208. CARLA_SAFE_ASSERT(portInfo.channel_count != 0);
  1209. fOutputAudioBuffers.buffers[i].channel_count = portInfo.channel_count;
  1210. fOutputAudioBuffers.extra[i].offset = aOuts;
  1211. fOutputAudioBuffers.extra[i].isMain = portInfo.flags & CLAP_AUDIO_PORT_IS_MAIN;
  1212. for (uint32_t j=0; j<portInfo.channel_count; ++j)
  1213. fOutputAudioBuffers.buffers[i].constant_mask |= (1ULL << j);
  1214. aOuts += portInfo.channel_count;
  1215. }
  1216. for (uint32_t i=0; i<numNoteInputPorts; ++i)
  1217. {
  1218. clap_note_port_info_t portInfo = {};
  1219. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  1220. if (portInfo.supported_dialects & (CLAP_NOTE_DIALECT_CLAP|CLAP_NOTE_DIALECT_MIDI))
  1221. ++mIns;
  1222. }
  1223. for (uint32_t i=0; i<numNoteOutputPorts; ++i)
  1224. {
  1225. clap_note_port_info_t portInfo = {};
  1226. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, false, &portInfo));
  1227. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI)
  1228. ++mOuts;
  1229. }
  1230. for (uint32_t i=0; i<numParameters; ++i, ++params)
  1231. {
  1232. clap_param_info_t paramInfo = {};
  1233. CARLA_SAFE_ASSERT_BREAK(paramsExt->get_info(fPlugin, i, &paramInfo));
  1234. }
  1235. if (aIns > 0)
  1236. {
  1237. pData->audioIn.createNew(aIns);
  1238. }
  1239. if (aOuts > 0)
  1240. {
  1241. pData->audioOut.createNew(aOuts);
  1242. needsCtrlIn = true;
  1243. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1244. fAudioOutBuffers = new float*[aOuts];
  1245. for (uint32_t i=0; i < aOuts; ++i)
  1246. fAudioOutBuffers[i] = nullptr;
  1247. #endif
  1248. }
  1249. if (mIns == 1)
  1250. needsCtrlIn = true;
  1251. if (mOuts == 1)
  1252. needsCtrlOut = true;
  1253. if (params > 0)
  1254. {
  1255. pData->param.createNew(params, false);
  1256. needsCtrlIn = true;
  1257. }
  1258. fInputEvents.realloc(pData->event.portIn, mIns, params);
  1259. fOutputEvents.realloc(pData->event.portOut, mOuts, params);
  1260. const EngineProcessMode processMode = pData->engine->getProccessMode();
  1261. const uint portNameSize = pData->engine->getMaxPortNameSize();
  1262. CarlaString portName;
  1263. // Audio Ins
  1264. for (uint32_t j=0; j < aIns; ++j)
  1265. {
  1266. portName.clear();
  1267. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1268. {
  1269. portName = pData->name;
  1270. portName += ":";
  1271. }
  1272. if (aIns > 1)
  1273. {
  1274. portName += "input_";
  1275. portName += CarlaString(j+1);
  1276. }
  1277. else
  1278. portName += "input";
  1279. portName.truncate(portNameSize);
  1280. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio,
  1281. portName, true, j);
  1282. pData->audioIn.ports[j].rindex = j;
  1283. }
  1284. // Audio Outs
  1285. for (uint32_t j=0; j < aOuts; ++j)
  1286. {
  1287. portName.clear();
  1288. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1289. {
  1290. portName = pData->name;
  1291. portName += ":";
  1292. }
  1293. if (aOuts > 1)
  1294. {
  1295. portName += "output_";
  1296. portName += CarlaString(j+1);
  1297. }
  1298. else
  1299. portName += "output";
  1300. portName.truncate(portNameSize);
  1301. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio,
  1302. portName, false, j);
  1303. pData->audioOut.ports[j].rindex = j;
  1304. }
  1305. // MIDI Ins
  1306. for (uint32_t i=0, j=0; i<numNoteInputPorts; ++i)
  1307. {
  1308. clap_note_port_info_t portInfo = {};
  1309. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  1310. if ((portInfo.supported_dialects & (CLAP_NOTE_DIALECT_CLAP|CLAP_NOTE_DIALECT_MIDI)) == 0x0)
  1311. continue;
  1312. CARLA_SAFE_ASSERT_UINT2_BREAK(j < mIns, j, mIns);
  1313. fInputEvents.portData[j].clapPortIndex = i;
  1314. fInputEvents.portData[j].supportedDialects = portInfo.supported_dialects;
  1315. if (mIns > 1)
  1316. {
  1317. portName.clear();
  1318. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1319. {
  1320. portName = pData->name;
  1321. portName += ":";
  1322. }
  1323. portName += portInfo.name;
  1324. portName.truncate(portNameSize);
  1325. fInputEvents.portData[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent,
  1326. portName, true, j);
  1327. }
  1328. else
  1329. {
  1330. fInputEvents.portData[j].port = nullptr;
  1331. fInputEvents.defaultPort = &fInputEvents.portData[0];
  1332. }
  1333. ++j;
  1334. }
  1335. // MIDI Outs
  1336. for (uint32_t i=0, j=0; i<numNoteOutputPorts; ++i)
  1337. {
  1338. clap_note_port_info_t portInfo = {};
  1339. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, false, &portInfo));
  1340. if ((portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI) == 0x0)
  1341. continue;
  1342. CARLA_SAFE_ASSERT_UINT2_BREAK(j < mOuts, j, mOuts);
  1343. fOutputEvents.portData[j].clapPortIndex = i;
  1344. fOutputEvents.portData[j].supportedDialects = portInfo.supported_dialects;
  1345. if (mOuts > 1)
  1346. {
  1347. portName.clear();
  1348. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1349. {
  1350. portName = pData->name;
  1351. portName += ":";
  1352. }
  1353. portName += portInfo.name;
  1354. portName.truncate(portNameSize);
  1355. fOutputEvents.portData[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent,
  1356. portName, false, j);
  1357. }
  1358. else
  1359. {
  1360. fOutputEvents.portData[j].port = nullptr;
  1361. fOutputEvents.defaultPort = &fOutputEvents.portData[0];
  1362. }
  1363. ++j;
  1364. }
  1365. // Parameters
  1366. for (uint32_t i=0; i<numParameters; ++i)
  1367. {
  1368. clap_param_info_t paramInfo = {};
  1369. CARLA_SAFE_ASSERT_BREAK(paramsExt->get_info(fPlugin, i, &paramInfo));
  1370. CARLA_SAFE_ASSERT_BREAK(i < params);
  1371. pData->param.data[i].index = i;
  1372. pData->param.data[i].rindex = static_cast<int32_t>(paramInfo.id);
  1373. double min, max, def, step, stepSmall, stepLarge;
  1374. min = paramInfo.min_value;
  1375. max = paramInfo.max_value;
  1376. def = paramInfo.default_value;
  1377. if (min >= max)
  1378. max = min + 0.1;
  1379. if (def < min)
  1380. def = min;
  1381. else if (def > max)
  1382. def = max;
  1383. if (paramInfo.flags & (CLAP_PARAM_IS_HIDDEN|CLAP_PARAM_IS_BYPASS))
  1384. {
  1385. pData->param.data[i].type = PARAMETER_UNKNOWN;
  1386. }
  1387. else if (paramInfo.flags & CLAP_PARAM_IS_READONLY)
  1388. {
  1389. pData->param.data[i].type = PARAMETER_OUTPUT;
  1390. needsCtrlOut = true;
  1391. }
  1392. else
  1393. {
  1394. pData->param.data[i].type = PARAMETER_INPUT;
  1395. }
  1396. if (paramInfo.flags & CLAP_PARAM_IS_STEPPED)
  1397. {
  1398. if (carla_isEqual(max - min, 1.0))
  1399. {
  1400. step = stepSmall = stepLarge = 1.0;
  1401. pData->param.data[i].hints |= PARAMETER_IS_BOOLEAN;
  1402. }
  1403. else
  1404. {
  1405. step = 1.0;
  1406. stepSmall = 1.0;
  1407. stepLarge = std::min(max - min, 10.0);
  1408. }
  1409. pData->param.data[i].hints |= PARAMETER_IS_INTEGER;
  1410. }
  1411. else
  1412. {
  1413. double range = max - min;
  1414. step = range/100.0;
  1415. stepSmall = range/1000.0;
  1416. stepLarge = range/10.0;
  1417. }
  1418. if (pData->param.data[i].type != PARAMETER_UNKNOWN)
  1419. {
  1420. pData->param.data[i].hints |= PARAMETER_IS_ENABLED;
  1421. pData->param.data[i].hints |= PARAMETER_USES_CUSTOM_TEXT;
  1422. if (paramInfo.flags & CLAP_PARAM_IS_AUTOMATABLE)
  1423. {
  1424. pData->param.data[i].hints |= PARAMETER_IS_AUTOMATABLE;
  1425. if ((paramInfo.flags & CLAP_PARAM_IS_STEPPED) == 0x0)
  1426. pData->param.data[i].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  1427. }
  1428. }
  1429. pData->param.ranges[i].min = min;
  1430. pData->param.ranges[i].max = max;
  1431. pData->param.ranges[i].def = def;
  1432. pData->param.ranges[i].step = step;
  1433. pData->param.ranges[i].stepSmall = stepSmall;
  1434. pData->param.ranges[i].stepLarge = stepLarge;
  1435. fInputEvents.updatedParams[i].clapId = paramInfo.id;
  1436. fInputEvents.updatedParams[i].cookie = paramInfo.cookie;
  1437. }
  1438. if (needsCtrlIn)
  1439. {
  1440. portName.clear();
  1441. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1442. {
  1443. portName = pData->name;
  1444. portName += ":";
  1445. }
  1446. portName += "events-in";
  1447. portName.truncate(portNameSize);
  1448. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent,
  1449. portName, true, 0);
  1450. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1451. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  1452. #endif
  1453. if (mIns == 1)
  1454. fInputEvents.portData[0].port = pData->event.portIn;
  1455. }
  1456. if (needsCtrlOut)
  1457. {
  1458. portName.clear();
  1459. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1460. {
  1461. portName = pData->name;
  1462. portName += ":";
  1463. }
  1464. portName += "events-out";
  1465. portName.truncate(portNameSize);
  1466. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent,
  1467. portName, false, 0);
  1468. if (mOuts == 1)
  1469. fOutputEvents.portData[0].port = pData->event.portOut;
  1470. }
  1471. // plugin hints
  1472. pData->hints = PLUGIN_NEEDS_MAIN_THREAD_IDLE;
  1473. if (clapFeaturesContainInstrument(fPluginDescriptor->features))
  1474. pData->hints |= PLUGIN_IS_SYNTH;
  1475. #ifdef CLAP_WINDOW_API_NATIVE
  1476. if (guiExt != nullptr)
  1477. {
  1478. if (guiExt->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, false))
  1479. {
  1480. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1481. pData->hints |= PLUGIN_HAS_CUSTOM_EMBED_UI;
  1482. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1483. }
  1484. else if (guiExt->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, true))
  1485. {
  1486. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1487. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1488. }
  1489. }
  1490. #endif
  1491. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  1492. pData->hints |= PLUGIN_CAN_DRYWET;
  1493. if (aOuts > 0)
  1494. pData->hints |= PLUGIN_CAN_VOLUME;
  1495. if (aOuts >= 2 && aOuts % 2 == 0)
  1496. pData->hints |= PLUGIN_CAN_BALANCE;
  1497. // extra plugin hints
  1498. pData->extraHints = 0x0;
  1499. if (const uint32_t latency = fExtensions.latency != nullptr ? fExtensions.latency->get(fPlugin) : 0)
  1500. {
  1501. fLastKnownLatency = latency;
  1502. pData->client->setLatency(latency);
  1503. #ifndef BUILD_BRIDGE
  1504. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  1505. #endif
  1506. }
  1507. else
  1508. {
  1509. fLastKnownLatency = 0;
  1510. }
  1511. bufferSizeChanged(pData->engine->getBufferSize());
  1512. reloadPrograms(true);
  1513. if (pData->active)
  1514. activate();
  1515. else
  1516. runIdleCallbacksAsNeeded(false);
  1517. carla_debug("CarlaPluginCLAP::reload() - end");
  1518. }
  1519. void reloadPrograms(const bool doInit) override
  1520. {
  1521. carla_debug("CarlaPluginCLAP::reloadPrograms(%s)", bool2str(doInit));
  1522. }
  1523. // -------------------------------------------------------------------
  1524. // Plugin processing
  1525. void activate() noexcept override
  1526. {
  1527. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1528. // FIXME check return status
  1529. fPlugin->activate(fPlugin, pData->engine->getSampleRate(), 1, pData->engine->getBufferSize());
  1530. fPlugin->start_processing(fPlugin);
  1531. fNeedsParamFlush = false;
  1532. runIdleCallbacksAsNeeded(false);
  1533. }
  1534. void deactivate() noexcept override
  1535. {
  1536. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1537. // FIXME check return status
  1538. fPlugin->stop_processing(fPlugin);
  1539. fPlugin->deactivate(fPlugin);
  1540. runIdleCallbacksAsNeeded(false);
  1541. }
  1542. void process(const float* const* const audioIn,
  1543. float** const audioOut,
  1544. const float* const* const cvIn,
  1545. float** const,
  1546. const uint32_t frames) override
  1547. {
  1548. // --------------------------------------------------------------------------------------------------------
  1549. // Check if active
  1550. if (! pData->active)
  1551. {
  1552. // disable any output sound
  1553. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1554. carla_zeroFloats(audioOut[i], frames);
  1555. return;
  1556. }
  1557. // --------------------------------------------------------------------------------------------------------
  1558. // Check buffers
  1559. CARLA_SAFE_ASSERT_RETURN(frames > 0,);
  1560. if (pData->audioIn.count > 0)
  1561. {
  1562. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr,);
  1563. }
  1564. if (pData->audioOut.count > 0)
  1565. {
  1566. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr,);
  1567. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1568. CARLA_SAFE_ASSERT_RETURN(fAudioOutBuffers != nullptr,);
  1569. #endif
  1570. }
  1571. // --------------------------------------------------------------------------------------------------------
  1572. // Set audio buffers
  1573. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1574. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1575. carla_zeroFloats(fAudioOutBuffers[i], frames);
  1576. #endif
  1577. // --------------------------------------------------------------------------------------------------------
  1578. // Try lock, silence otherwise
  1579. if (pData->engine->isOffline())
  1580. {
  1581. pData->singleMutex.lock();
  1582. }
  1583. else if (! pData->singleMutex.tryLock())
  1584. {
  1585. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1586. carla_zeroFloats(audioOut[i], frames);
  1587. return;
  1588. }
  1589. // --------------------------------------------------------------------------------------------------------
  1590. fInputEvents.handleScheduledParameterUpdates();
  1591. // --------------------------------------------------------------------------------------------------------
  1592. // Check if needs reset
  1593. if (pData->needsReset)
  1594. {
  1595. // TODO alternative if plugin does not support CLAP_NOTE_DIALECT_MIDI
  1596. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1597. {
  1598. for (uint32_t p=0; p<fInputEvents.portCount; ++p)
  1599. {
  1600. const uint16_t port = fInputEvents.portData[p].clapPortIndex;
  1601. for (uint8_t i=0, k=fInputEvents.numEventsUsed; i < MAX_MIDI_CHANNELS; ++i)
  1602. {
  1603. fInputEvents.events[k + i].midi = {
  1604. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1605. port,
  1606. {
  1607. uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT)),
  1608. MIDI_CONTROL_ALL_NOTES_OFF, 0
  1609. }
  1610. };
  1611. fInputEvents.events[k + MAX_MIDI_CHANNELS + i].midi = {
  1612. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1613. port,
  1614. {
  1615. uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT)),
  1616. MIDI_CONTROL_ALL_SOUND_OFF, 0
  1617. }
  1618. };
  1619. }
  1620. fInputEvents.numEventsUsed += MAX_MIDI_CHANNELS * 2;
  1621. }
  1622. }
  1623. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  1624. {
  1625. for (uint32_t p=0; p<fInputEvents.portCount; ++p)
  1626. {
  1627. const uint16_t port = fInputEvents.portData[p].clapPortIndex;
  1628. for (uint8_t i=0, k=fInputEvents.numEventsUsed; i < MAX_MIDI_NOTE; ++i)
  1629. {
  1630. fInputEvents.events[k + i].midi = {
  1631. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1632. port,
  1633. {
  1634. uint8_t(MIDI_STATUS_NOTE_OFF | (pData->ctrlChannel & MIDI_CHANNEL_BIT)),
  1635. i, 0
  1636. }
  1637. };
  1638. }
  1639. fInputEvents.numEventsUsed += MAX_MIDI_NOTE;
  1640. }
  1641. }
  1642. pData->needsReset = false;
  1643. }
  1644. // --------------------------------------------------------------------------------------------------------
  1645. // Set TimeInfo
  1646. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1647. const double sampleRate = pData->engine->getSampleRate();
  1648. clap_event_transport_t clapTransport = {
  1649. { sizeof(clap_event_transport_t), 0, 0, CLAP_EVENT_TRANSPORT, 0 },
  1650. 0x0, // flags
  1651. 0, // song_pos_beats, position in beats
  1652. 0, // song_pos_seconds, position in seconds
  1653. 0.0, // tempo, in bpm
  1654. 0.0, // tempo_inc, tempo increment for each samples and until the next time info event
  1655. 0, // loop_start_beats
  1656. 0, // loop_end_beats
  1657. 0, // loop_start_seconds
  1658. 0, // loop_end_seconds
  1659. 0, // bar_start, start pos of the current bar
  1660. 0, // bar_number, bar at song pos 0 has the number 0
  1661. 0, // tsig_num, time signature numerator
  1662. 0, // tsig_denom, time signature denominator
  1663. };
  1664. if (timeInfo.playing)
  1665. clapTransport.flags |= CLAP_TRANSPORT_IS_PLAYING;
  1666. const double positionSeconds = static_cast<double>(timeInfo.frame) / sampleRate;
  1667. clapTransport.song_pos_seconds = std::round(CLAP_SECTIME_FACTOR * positionSeconds);
  1668. clapTransport.flags |= CLAP_TRANSPORT_HAS_SECONDS_TIMELINE;
  1669. if (timeInfo.bbt.valid)
  1670. {
  1671. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  1672. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  1673. const double barStart = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  1674. const double positionBeats = static_cast<double>(timeInfo.frame)
  1675. / (sampleRate * 60 / timeInfo.bbt.beatsPerMinute);
  1676. // Bar/Beats
  1677. clapTransport.bar_start = std::round(CLAP_BEATTIME_FACTOR * barStart);
  1678. clapTransport.bar_number = timeInfo.bbt.bar - 1;
  1679. clapTransport.song_pos_beats = std::round(CLAP_BEATTIME_FACTOR * positionBeats);
  1680. clapTransport.flags |= CLAP_TRANSPORT_HAS_BEATS_TIMELINE;
  1681. // Tempo
  1682. clapTransport.tempo = timeInfo.bbt.beatsPerMinute;
  1683. clapTransport.flags |= CLAP_TRANSPORT_HAS_TEMPO;
  1684. // Time Signature
  1685. clapTransport.tsig_num = static_cast<uint16_t>(timeInfo.bbt.beatsPerBar + 0.5f);
  1686. clapTransport.tsig_denom = static_cast<uint16_t>(timeInfo.bbt.beatType + 0.5f);
  1687. clapTransport.flags |= CLAP_TRANSPORT_HAS_TIME_SIGNATURE;
  1688. }
  1689. else
  1690. {
  1691. // Tempo
  1692. clapTransport.tempo = 120.0;
  1693. clapTransport.flags |= CLAP_TRANSPORT_HAS_TEMPO;
  1694. // Time Signature
  1695. clapTransport.tsig_num = 4;
  1696. clapTransport.tsig_denom = 4;
  1697. clapTransport.flags |= CLAP_TRANSPORT_HAS_TIME_SIGNATURE;
  1698. }
  1699. // --------------------------------------------------------------------------------------------------------
  1700. // Event Input (main port)
  1701. if (pData->event.portIn != nullptr)
  1702. {
  1703. // ----------------------------------------------------------------------------------------------------
  1704. // MIDI Input (External)
  1705. if (pData->extNotes.mutex.tryLock())
  1706. {
  1707. if (fInputEvents.portCount == 0)
  1708. {
  1709. // does not handle MIDI
  1710. pData->extNotes.data.clear();
  1711. }
  1712. else
  1713. {
  1714. ExternalMidiNote note = { -1, 0, 0 };
  1715. const uint16_t p = fInputEvents.portData[0].clapPortIndex;
  1716. for (; fInputEvents.numEventsUsed < fInputEvents.numEventsAllocated && ! pData->extNotes.data.isEmpty();)
  1717. {
  1718. note = pData->extNotes.data.getFirst(note, true);
  1719. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1720. if (fInputEvents.portData[0].supportedDialects & CLAP_NOTE_DIALECT_MIDI)
  1721. {
  1722. const uint8_t data[3] = {
  1723. uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT)),
  1724. note.note,
  1725. note.velo
  1726. };
  1727. fInputEvents.addSimpleMidiEvent(true, p, 0, data);
  1728. }
  1729. else
  1730. {
  1731. fInputEvents.addSimpleNoteEvent(true, -1, 0, note.channel, note.note, note.velo);
  1732. }
  1733. }
  1734. }
  1735. pData->extNotes.mutex.unlock();
  1736. } // End of MIDI Input (External)
  1737. // ----------------------------------------------------------------------------------------------------
  1738. // Event Input (System)
  1739. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1740. bool allNotesOffSent = false;
  1741. #endif
  1742. uint32_t previousEventTime = 0;
  1743. uint32_t nextBankId;
  1744. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1745. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1746. else
  1747. nextBankId = 0;
  1748. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1749. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  1750. pData->event.cvSourcePorts->initPortBuffers(cvIn + pData->cvIn.count, frames, true, pData->event.portIn);
  1751. #endif
  1752. const uint32_t numSysEvents = pData->event.portIn->getEventCount();
  1753. for (uint32_t i=0; i < numSysEvents; ++i)
  1754. {
  1755. EngineEvent& event(pData->event.portIn->getEvent(i));
  1756. uint32_t eventTime = event.time;
  1757. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  1758. if (eventTime < previousEventTime)
  1759. {
  1760. carla_stderr2("Timing error, eventTime:%u < previousEventTime:%u for '%s'",
  1761. eventTime, previousEventTime, pData->name);
  1762. eventTime = previousEventTime;
  1763. }
  1764. previousEventTime = eventTime;
  1765. switch (event.type)
  1766. {
  1767. case kEngineEventTypeNull:
  1768. break;
  1769. case kEngineEventTypeControl: {
  1770. EngineControlEvent& ctrlEvent(event.ctrl);
  1771. switch (ctrlEvent.type)
  1772. {
  1773. case kEngineControlEventTypeNull:
  1774. break;
  1775. case kEngineControlEventTypeParameter: {
  1776. float value;
  1777. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1778. // non-midi
  1779. if (event.channel == kEngineEventNonMidiChannel)
  1780. {
  1781. const uint32_t k = ctrlEvent.param;
  1782. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  1783. ctrlEvent.handled = true;
  1784. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1785. setParameterValueRT(k, value, event.time, true);
  1786. continue;
  1787. }
  1788. // Control backend stuff
  1789. if (event.channel == pData->ctrlChannel)
  1790. {
  1791. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1792. {
  1793. ctrlEvent.handled = true;
  1794. value = ctrlEvent.normalizedValue;
  1795. setDryWetRT(value, true);
  1796. }
  1797. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1798. {
  1799. ctrlEvent.handled = true;
  1800. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  1801. setVolumeRT(value, true);
  1802. }
  1803. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1804. {
  1805. float left, right;
  1806. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  1807. if (value < 0.0f)
  1808. {
  1809. left = -1.0f;
  1810. right = (value*2.0f)+1.0f;
  1811. }
  1812. else if (value > 0.0f)
  1813. {
  1814. left = (value*2.0f)-1.0f;
  1815. right = 1.0f;
  1816. }
  1817. else
  1818. {
  1819. left = -1.0f;
  1820. right = 1.0f;
  1821. }
  1822. ctrlEvent.handled = true;
  1823. setBalanceLeftRT(left, true);
  1824. setBalanceRightRT(right, true);
  1825. }
  1826. }
  1827. #endif
  1828. // Control plugin parameters
  1829. uint32_t k;
  1830. for (k=0; k < pData->param.count; ++k)
  1831. {
  1832. if (pData->param.data[k].midiChannel != event.channel)
  1833. continue;
  1834. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  1835. continue;
  1836. if (pData->param.data[k].type != PARAMETER_INPUT)
  1837. continue;
  1838. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  1839. continue;
  1840. ctrlEvent.handled = true;
  1841. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1842. setParameterValueRT(k, value, event.time, true);
  1843. }
  1844. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  1845. {
  1846. uint8_t midiData[3];
  1847. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1848. midiData[1] = uint8_t(ctrlEvent.param);
  1849. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  1850. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1851. }
  1852. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1853. if (! ctrlEvent.handled)
  1854. checkForMidiLearn(event);
  1855. #endif
  1856. break;
  1857. } // case kEngineControlEventTypeParameter
  1858. case kEngineControlEventTypeMidiBank:
  1859. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1860. {
  1861. if (event.channel == pData->ctrlChannel)
  1862. nextBankId = ctrlEvent.param;
  1863. }
  1864. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1865. {
  1866. uint8_t midiData[3];
  1867. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1868. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  1869. midiData[2] = uint8_t(ctrlEvent.param);
  1870. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1871. }
  1872. break;
  1873. case kEngineControlEventTypeMidiProgram:
  1874. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1875. {
  1876. if (event.channel == pData->ctrlChannel)
  1877. {
  1878. const uint32_t nextProgramId(ctrlEvent.param);
  1879. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  1880. {
  1881. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  1882. {
  1883. setMidiProgramRT(k, true);
  1884. break;
  1885. }
  1886. }
  1887. }
  1888. }
  1889. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1890. {
  1891. uint8_t midiData[3];
  1892. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1893. midiData[1] = uint8_t(ctrlEvent.param);
  1894. midiData[2] = 0;
  1895. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1896. }
  1897. break;
  1898. case kEngineControlEventTypeAllSoundOff:
  1899. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1900. {
  1901. uint8_t midiData[3];
  1902. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1903. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  1904. midiData[2] = 0;
  1905. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1906. }
  1907. break;
  1908. case kEngineControlEventTypeAllNotesOff:
  1909. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1910. {
  1911. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1912. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1913. {
  1914. allNotesOffSent = true;
  1915. postponeRtAllNotesOff();
  1916. }
  1917. #endif
  1918. uint8_t midiData[3];
  1919. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1920. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1921. midiData[2] = 0;
  1922. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1923. }
  1924. break;
  1925. } // switch (ctrlEvent.type)
  1926. break;
  1927. } // case kEngineEventTypeControl
  1928. case kEngineEventTypeMidi: {
  1929. const EngineMidiEvent& midiEvent(event.midi);
  1930. if (midiEvent.size > 3)
  1931. continue;
  1932. CARLA_SAFE_ASSERT_BREAK(midiEvent.port < fInputEvents.portCount);
  1933. const uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1934. if (status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON)
  1935. {
  1936. if (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES)
  1937. continue;
  1938. // plugin does not support MIDI, send a simple note instead
  1939. if ((fInputEvents.portData[midiEvent.port].supportedDialects & CLAP_NOTE_DIALECT_MIDI) == 0x0)
  1940. {
  1941. fInputEvents.addSimpleNoteEvent(true, midiEvent.port, event.time,
  1942. event.channel, midiEvent.data[1], midiEvent.data[2]);
  1943. }
  1944. }
  1945. if (fInputEvents.portData[midiEvent.port].supportedDialects & CLAP_NOTE_DIALECT_MIDI)
  1946. {
  1947. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1948. continue;
  1949. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1950. continue;
  1951. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1952. continue;
  1953. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1954. continue;
  1955. // put back channel in data
  1956. uint8_t midiData[3] = { uint8_t(status | (event.channel & MIDI_CHANNEL_BIT)), 0, 0 };
  1957. switch (midiEvent.size)
  1958. {
  1959. case 3:
  1960. midiData[2] = midiEvent.data[2];
  1961. // fall through
  1962. case 2:
  1963. midiData[1] = midiEvent.data[1];
  1964. break;
  1965. }
  1966. fInputEvents.addSimpleMidiEvent(true, midiEvent.port, eventTime, midiData);
  1967. }
  1968. switch (status)
  1969. {
  1970. case MIDI_STATUS_NOTE_ON:
  1971. if (midiEvent.data[2] != 0)
  1972. {
  1973. pData->postponeNoteOnRtEvent(true, event.channel, midiEvent.data[1], midiEvent.data[2]);
  1974. break;
  1975. }
  1976. // fall through
  1977. case MIDI_STATUS_NOTE_OFF:
  1978. pData->postponeNoteOffRtEvent(true, event.channel, midiEvent.data[1]);
  1979. break;
  1980. }
  1981. } break;
  1982. } // switch (event.type)
  1983. }
  1984. pData->postRtEvents.trySplice();
  1985. } // End of Event Input (main port)
  1986. // --------------------------------------------------------------------------------------------------------
  1987. // Event input (multi MIDI port)
  1988. if (fInputEvents.portCount > 1)
  1989. {
  1990. // TODO
  1991. }
  1992. // --------------------------------------------------------------------------------------------------------
  1993. // Plugin processing
  1994. for (uint32_t i=0; i<fInputAudioBuffers.count; ++i)
  1995. fInputAudioBuffers.buffers[i].data32 = audioIn + fInputAudioBuffers.extra[i].offset;
  1996. for (uint32_t i=0; i<fOutputAudioBuffers.count; ++i)
  1997. {
  1998. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1999. fOutputAudioBuffers.buffers[i].data32 = fAudioOutBuffers + fOutputAudioBuffers.extra[i].offset;
  2000. #else
  2001. fOutputAudioBuffers.buffers[i].data32 = audioOut + fOutputAudioBuffers.extra[i].offset;
  2002. #endif
  2003. }
  2004. const clap_process_t process = {
  2005. static_cast<int64_t>(timeInfo.frame),
  2006. frames,
  2007. &clapTransport,
  2008. fInputAudioBuffers.cast(),
  2009. fOutputAudioBuffers.buffers,
  2010. fInputAudioBuffers.count,
  2011. fOutputAudioBuffers.count,
  2012. fInputEvents.cast(),
  2013. fOutputEvents.cast()
  2014. };
  2015. fPlugin->process(fPlugin, &process);
  2016. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2017. // --------------------------------------------------------------------------------------------------------
  2018. // Post-processing (dry/wet, volume and balance)
  2019. {
  2020. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  2021. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  2022. const bool isMono = (pData->audioIn.count == 1);
  2023. bool isPair;
  2024. float bufValue;
  2025. float* const oldBufLeft = pData->postProc.extraBuffer;
  2026. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2027. {
  2028. // Dry/Wet
  2029. if (doDryWet)
  2030. {
  2031. const uint32_t c = isMono ? 0 : i;
  2032. for (uint32_t k=0; k < frames; ++k)
  2033. {
  2034. bufValue = audioIn[c][k];
  2035. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  2036. }
  2037. }
  2038. // Balance
  2039. if (doBalance)
  2040. {
  2041. isPair = (i % 2 == 0);
  2042. if (isPair)
  2043. {
  2044. CARLA_ASSERT(i+1 < pData->audioOut.count);
  2045. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  2046. }
  2047. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  2048. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  2049. for (uint32_t k=0; k < frames; ++k)
  2050. {
  2051. if (isPair)
  2052. {
  2053. // left
  2054. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  2055. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  2056. }
  2057. else
  2058. {
  2059. // right
  2060. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  2061. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  2062. }
  2063. }
  2064. }
  2065. // Volume (and buffer copy)
  2066. {
  2067. for (uint32_t k=0; k < frames; ++k)
  2068. audioOut[i][k] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  2069. }
  2070. }
  2071. } // End of Post-processing
  2072. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  2073. // --------------------------------------------------------------------------------------------------------
  2074. pData->singleMutex.unlock();
  2075. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2076. // --------------------------------------------------------------------------------------------------------
  2077. // Control Output
  2078. if (pData->event.portOut != nullptr && fExtensions.params != nullptr)
  2079. {
  2080. uint8_t channel;
  2081. uint16_t param;
  2082. double value;
  2083. for (uint32_t k=0; k < pData->param.count; ++k)
  2084. {
  2085. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  2086. continue;
  2087. if (pData->param.data[k].mappedControlIndex <= 0)
  2088. continue;
  2089. if (!fExtensions.params->get_value(fPlugin, pData->param.data[k].rindex, &value))
  2090. continue;
  2091. channel = pData->param.data[k].midiChannel;
  2092. param = static_cast<uint16_t>(pData->param.data[k].mappedControlIndex);
  2093. value = pData->param.ranges[k].getNormalizedValue(value);
  2094. pData->event.portOut->writeControlEvent(0, channel,
  2095. kEngineControlEventTypeParameter, param, -1,
  2096. value);
  2097. }
  2098. } // End of Control Output
  2099. #endif
  2100. // --------------------------------------------------------------------------------------------------------
  2101. // Events/MIDI Output
  2102. for (uint32_t i=0; i<fOutputEvents.numEventsUsed; ++i)
  2103. {
  2104. const carla_clap_output_events::Event& ev(fOutputEvents.events[i]);
  2105. switch (ev.header.type)
  2106. {
  2107. case CLAP_EVENT_PARAM_VALUE:
  2108. for (uint32_t j=0; j<pData->param.count; ++j)
  2109. {
  2110. if (pData->param.data[j].rindex != static_cast<int32_t>(ev.param.param_id))
  2111. continue;
  2112. pData->postponeParameterChangeRtEvent(true, static_cast<int32_t>(j), ev.param.value);
  2113. break;
  2114. }
  2115. break;
  2116. case CLAP_EVENT_MIDI:
  2117. for (uint32_t j=0; j<fOutputEvents.portCount; ++j)
  2118. {
  2119. if (fOutputEvents.portData[j].clapPortIndex != ev.midi.port_index)
  2120. continue;
  2121. fOutputEvents.portData[j].port->writeMidiEvent(ev.midi.header.time, 3, ev.midi.data);
  2122. break;
  2123. }
  2124. break;
  2125. }
  2126. }
  2127. fOutputEvents.numEventsUsed = 0;
  2128. // --------------------------------------------------------------------------------------------------------
  2129. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2130. return;
  2131. // unused
  2132. (void)cvIn;
  2133. #endif
  2134. }
  2135. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2136. void bufferSizeChanged(const uint32_t newBufferSize) override
  2137. {
  2138. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  2139. carla_debug("CarlaPluginCLAP::bufferSizeChanged(%i)", newBufferSize);
  2140. if (pData->active)
  2141. deactivate();
  2142. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2143. {
  2144. if (fAudioOutBuffers[i] != nullptr)
  2145. delete[] fAudioOutBuffers[i];
  2146. fAudioOutBuffers[i] = new float[newBufferSize];
  2147. }
  2148. if (pData->active)
  2149. activate();
  2150. CarlaPlugin::bufferSizeChanged(newBufferSize);
  2151. }
  2152. #endif
  2153. // -------------------------------------------------------------------
  2154. // Plugin buffers
  2155. void initBuffers() const noexcept override
  2156. {
  2157. fInputEvents.initBuffers();
  2158. fOutputEvents.initBuffers();
  2159. CarlaPlugin::initBuffers();
  2160. }
  2161. void clearBuffers() noexcept override
  2162. {
  2163. carla_debug("CarlaPluginCLAP::clearBuffers() - start");
  2164. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2165. if (fAudioOutBuffers != nullptr)
  2166. {
  2167. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2168. {
  2169. if (fAudioOutBuffers[i] != nullptr)
  2170. {
  2171. delete[] fAudioOutBuffers[i];
  2172. fAudioOutBuffers[i] = nullptr;
  2173. }
  2174. }
  2175. delete[] fAudioOutBuffers;
  2176. fAudioOutBuffers = nullptr;
  2177. }
  2178. #endif
  2179. fInputEvents.clear(pData->event.portIn);
  2180. fOutputEvents.clear(pData->event.portOut);
  2181. CarlaPlugin::clearBuffers();
  2182. carla_debug("CarlaPluginCLAP::clearBuffers() - end");
  2183. }
  2184. // -------------------------------------------------------------------
  2185. // Post-poned UI Stuff
  2186. // nothing
  2187. // -------------------------------------------------------------------
  2188. protected:
  2189. #ifdef CLAP_WINDOW_API_NATIVE
  2190. void handlePluginUIClosed() override
  2191. {
  2192. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2193. carla_stdout("CarlaPluginCLAP::handlePluginUIClosed()");
  2194. fUI.shouldClose = true;
  2195. }
  2196. void handlePluginUIResized(const uint width, const uint height) override
  2197. {
  2198. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2199. carla_stdout("CarlaPluginCLAP::handlePluginUIResized(%u, %u | vs %u %u) %d %s %s",
  2200. width, height,
  2201. fUI.width, fUI.height,
  2202. fUI.isResizingFromPlugin, bool2str(fUI.isResizingFromInit), bool2str(fUI.isResizingFromHost));
  2203. if (fExtensions.gui == nullptr)
  2204. return;
  2205. if (fUI.isResizingFromPlugin != 0)
  2206. {
  2207. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2208. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2209. fUI.isResizingFromPlugin = 2;
  2210. return;
  2211. }
  2212. if (fUI.isResizingFromInit)
  2213. {
  2214. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2215. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2216. fUI.isResizingFromInit = false;
  2217. return;
  2218. }
  2219. if (fUI.isResizingFromHost)
  2220. {
  2221. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2222. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2223. fUI.isResizingFromHost = false;
  2224. return;
  2225. }
  2226. if (fUI.width != width || fUI.height != height)
  2227. {
  2228. uint width2 = width;
  2229. uint height2 = height;
  2230. if (fExtensions.gui->adjust_size(fPlugin, &width2, &height2))
  2231. {
  2232. if (width2 != width || height2 != height)
  2233. {
  2234. fUI.isResizingFromHost = true;
  2235. fUI.width = width2;
  2236. fUI.height = height2;
  2237. fUI.window->setSize(width2, height2, false, false);
  2238. }
  2239. else
  2240. {
  2241. fExtensions.gui->set_size(fPlugin, width2, height2);
  2242. }
  2243. }
  2244. }
  2245. }
  2246. #endif
  2247. // -------------------------------------------------------------------
  2248. void clapRequestRestart() override
  2249. {
  2250. carla_stdout("CarlaPluginCLAP::clapRequestRestart()");
  2251. fNeedsRestart = true;
  2252. }
  2253. void clapRequestProcess() override
  2254. {
  2255. carla_stdout("CarlaPluginCLAP::clapRequestProcess()");
  2256. fNeedsProcess = true;
  2257. }
  2258. void clapRequestCallback() override
  2259. {
  2260. carla_stdout("CarlaPluginCLAP::clapRequestCallback()");
  2261. if (fPlugin->on_main_thread != nullptr)
  2262. fNeedsIdleCallback = true;
  2263. }
  2264. // -------------------------------------------------------------------
  2265. void clapLatencyChanged() override
  2266. {
  2267. carla_stdout("CarlaPluginCLAP::clapLatencyChanged()");
  2268. CARLA_SAFE_ASSERT_RETURN(fExtensions.latency != nullptr,);
  2269. fLastKnownLatency = fExtensions.latency->get(fPlugin);
  2270. }
  2271. // -------------------------------------------------------------------
  2272. void clapMarkDirty() override
  2273. {
  2274. carla_stdout("CarlaPluginCLAP::clapMarkDirty()");
  2275. }
  2276. // -------------------------------------------------------------------
  2277. #ifdef CLAP_WINDOW_API_NATIVE
  2278. void clapGuiResizeHintsChanged() override
  2279. {
  2280. carla_stdout("CarlaPluginCLAP::clapGuiResizeHintsChanged()");
  2281. }
  2282. bool clapGuiRequestResize(const uint width, const uint height) override
  2283. {
  2284. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr, false);
  2285. carla_stdout("CarlaPluginCLAP::hostRequestResize(%u, %u)", width, height);
  2286. fUI.isResizingFromPlugin = 3;
  2287. fUI.width = width;
  2288. fUI.height = height;
  2289. fUI.window->setSize(width, height, true, false);
  2290. return true;
  2291. }
  2292. bool clapGuiRequestShow() override
  2293. {
  2294. carla_stdout("CarlaPluginCLAP::clapGuiRequestShow()");
  2295. return false;
  2296. }
  2297. bool clapGuiRequestHide() override
  2298. {
  2299. carla_stdout("CarlaPluginCLAP::clapGuiRequestHide()");
  2300. return false;
  2301. }
  2302. void clapGuiClosed(const bool wasDestroyed) override
  2303. {
  2304. carla_stdout("CarlaPluginCLAP::clapGuiClosed(%s)", bool2str(wasDestroyed));
  2305. CARLA_SAFE_ASSERT_RETURN(!fUI.isEmbed,);
  2306. CARLA_SAFE_ASSERT_RETURN(fUI.isVisible,);
  2307. fUI.isVisible = false;
  2308. if (wasDestroyed)
  2309. {
  2310. CARLA_SAFE_ASSERT_RETURN(fUI.isCreated,);
  2311. fExtensions.gui->destroy(fPlugin);
  2312. fUI.isCreated = false;
  2313. }
  2314. pData->engine->callback(true, true,
  2315. ENGINE_CALLBACK_UI_STATE_CHANGED,
  2316. pData->id,
  2317. 0,
  2318. 0, 0, 0.0f, nullptr);
  2319. }
  2320. // -------------------------------------------------------------------
  2321. #ifdef _POSIX_VERSION
  2322. bool clapRegisterPosixFD(const int fd, const clap_posix_fd_flags_t flags) override
  2323. {
  2324. carla_stdout("CarlaPluginCLAP::clapRegisterPosixFD(%i, %x)", fd, flags);
  2325. // NOTE some plugins wont have their posix fd extension ready when first loaded, so try again here
  2326. if (fExtensions.posixFD == nullptr)
  2327. {
  2328. const clap_plugin_posix_fd_support_t* const posixFdExt = static_cast<const clap_plugin_posix_fd_support_t*>(
  2329. fPlugin->get_extension(fPlugin, CLAP_EXT_POSIX_FD_SUPPORT));
  2330. if (posixFdExt != nullptr && posixFdExt->on_fd != nullptr)
  2331. fExtensions.posixFD = posixFdExt;
  2332. }
  2333. CARLA_SAFE_ASSERT_RETURN(fExtensions.posixFD != nullptr, false);
  2334. // FIXME events only driven as long as UI is open
  2335. // CARLA_SAFE_ASSERT_RETURN(fUI.isCreated, false);
  2336. if (flags & (CLAP_POSIX_FD_READ|CLAP_POSIX_FD_WRITE))
  2337. {
  2338. #ifdef CARLA_CLAP_POSIX_EPOLL
  2339. const int hostFd = ::epoll_create1(0);
  2340. #else
  2341. const int hostFd = ::kqueue();
  2342. #endif
  2343. CARLA_SAFE_ASSERT_RETURN(hostFd >= 0, false);
  2344. #ifdef CARLA_CLAP_POSIX_EPOLL
  2345. struct ::epoll_event ev = {};
  2346. if (flags & CLAP_POSIX_FD_READ)
  2347. ev.events |= EPOLLIN;
  2348. if (flags & CLAP_POSIX_FD_WRITE)
  2349. ev.events |= EPOLLOUT;
  2350. ev.data.fd = fd;
  2351. if (::epoll_ctl(hostFd, EPOLL_CTL_ADD, fd, &ev) < 0)
  2352. {
  2353. ::close(hostFd);
  2354. return false;
  2355. }
  2356. #endif
  2357. const HostPosixFileDescriptorDetails posixFD = {
  2358. hostFd,
  2359. fd,
  2360. flags,
  2361. };
  2362. fPosixFileDescriptors.append(posixFD);
  2363. return true;
  2364. }
  2365. return false;
  2366. }
  2367. bool clapModifyPosixFD(const int fd, const clap_posix_fd_flags_t flags) override
  2368. {
  2369. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%i, %x)", fd, flags);
  2370. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2371. {
  2372. HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallbackNC));
  2373. if (posixFD.pluginFd == fd)
  2374. {
  2375. if (posixFD.flags == flags)
  2376. return true;
  2377. #ifdef CARLA_CLAP_POSIX_EPOLL
  2378. struct ::epoll_event ev = {};
  2379. if (flags & CLAP_POSIX_FD_READ)
  2380. ev.events |= EPOLLIN;
  2381. if (flags & CLAP_POSIX_FD_WRITE)
  2382. ev.events |= EPOLLOUT;
  2383. ev.data.fd = fd;
  2384. if (::epoll_ctl(posixFD.hostFd, EPOLL_CTL_MOD, fd, &ev) < 0)
  2385. return false;
  2386. #endif
  2387. posixFD.flags = flags;
  2388. return true;
  2389. }
  2390. }
  2391. return false;
  2392. }
  2393. bool clapUnregisterPosixFD(const int fd) override
  2394. {
  2395. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%i)", fd);
  2396. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2397. {
  2398. const HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallback));
  2399. if (posixFD.pluginFd == fd)
  2400. {
  2401. #ifdef CARLA_CLAP_POSIX_EPOLL
  2402. ::epoll_ctl(posixFD.hostFd, EPOLL_CTL_DEL, fd, nullptr);
  2403. #endif
  2404. ::close(posixFD.hostFd);
  2405. fPosixFileDescriptors.remove(it);
  2406. return true;
  2407. }
  2408. }
  2409. return false;
  2410. }
  2411. #endif // _POSIX_VERSION
  2412. // -------------------------------------------------------------------
  2413. bool clapRegisterTimer(const uint32_t periodInMs, clap_id* const timerId) override
  2414. {
  2415. carla_stdout("CarlaPluginCLAP::clapTimerRegister(%u, %p)", periodInMs, timerId);
  2416. // NOTE some plugins wont have their timer extension ready when first loaded, so try again here
  2417. if (fExtensions.timer == nullptr)
  2418. {
  2419. const clap_plugin_timer_support_t* const timerExt = static_cast<const clap_plugin_timer_support_t*>(
  2420. fPlugin->get_extension(fPlugin, CLAP_EXT_TIMER_SUPPORT));
  2421. if (timerExt != nullptr && timerExt->on_timer != nullptr)
  2422. fExtensions.timer = timerExt;
  2423. }
  2424. CARLA_SAFE_ASSERT_RETURN(fExtensions.timer != nullptr, false);
  2425. // FIXME events only driven as long as UI is open
  2426. // CARLA_SAFE_ASSERT_RETURN(fUI.isCreated, false);
  2427. const HostTimerDetails timer = {
  2428. fTimers.isNotEmpty() ? fTimers.getLast(kTimerFallback).clapId + 1 : 1,
  2429. periodInMs,
  2430. 0
  2431. };
  2432. fTimers.append(timer);
  2433. *timerId = timer.clapId;
  2434. return true;
  2435. }
  2436. bool clapUnregisterTimer(const clap_id timerId) override
  2437. {
  2438. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%u)", timerId);
  2439. for (LinkedList<HostTimerDetails>::Itenerator it = fTimers.begin2(); it.valid(); it.next())
  2440. {
  2441. const HostTimerDetails& timer(it.getValue(kTimerFallback));
  2442. if (timer.clapId == timerId)
  2443. {
  2444. fTimers.remove(it);
  2445. return true;
  2446. }
  2447. }
  2448. return false;
  2449. }
  2450. #endif // CLAP_WINDOW_API_NATIVE
  2451. // -------------------------------------------------------------------
  2452. public:
  2453. bool init(const CarlaPluginPtr plugin,
  2454. const char* const filename, const char* const name, const char* const id, const uint options)
  2455. {
  2456. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  2457. // ---------------------------------------------------------------
  2458. // first checks
  2459. if (pData->client != nullptr)
  2460. {
  2461. pData->engine->setLastError("Plugin client is already registered");
  2462. return false;
  2463. }
  2464. if (filename == nullptr || filename[0] == '\0')
  2465. {
  2466. pData->engine->setLastError("null filename");
  2467. return false;
  2468. }
  2469. // ---------------------------------------------------------------
  2470. const clap_plugin_entry_t* entry;
  2471. #ifdef CARLA_OS_MAC
  2472. if (!water::File(filename).existsAsFile())
  2473. {
  2474. if (! fBundleLoader.load(filename))
  2475. {
  2476. pData->engine->setLastError("Failed to load CLAP bundle executable");
  2477. return false;
  2478. }
  2479. entry = fBundleLoader.getSymbol<const clap_plugin_entry_t*>(CFSTR("clap_entry"));
  2480. }
  2481. else
  2482. #endif
  2483. {
  2484. if (! pData->libOpen(filename))
  2485. {
  2486. pData->engine->setLastError(pData->libError(filename));
  2487. return false;
  2488. }
  2489. entry = pData->libSymbol<const clap_plugin_entry_t*>("clap_entry");
  2490. }
  2491. if (entry == nullptr)
  2492. {
  2493. pData->engine->setLastError("Could not find the CLAP entry in the plugin library");
  2494. return false;
  2495. }
  2496. if (entry->init == nullptr || entry->deinit == nullptr || entry->get_factory == nullptr)
  2497. {
  2498. pData->engine->setLastError("CLAP factory entries are null");
  2499. return false;
  2500. }
  2501. if (!clap_version_is_compatible(entry->clap_version))
  2502. {
  2503. pData->engine->setLastError("Incompatible CLAP plugin");
  2504. return false;
  2505. }
  2506. // ---------------------------------------------------------------
  2507. const water::String pluginPath(water::File(filename).getParentDirectory().getFullPathName());
  2508. if (!entry->init(pluginPath.toRawUTF8()))
  2509. {
  2510. pData->engine->setLastError("Plugin entry failed to initialize");
  2511. return false;
  2512. }
  2513. fPluginEntry = entry;
  2514. // ---------------------------------------------------------------
  2515. const clap_plugin_factory_t* const factory = static_cast<const clap_plugin_factory_t*>(
  2516. entry->get_factory(CLAP_PLUGIN_FACTORY_ID));
  2517. if (factory == nullptr
  2518. || factory->get_plugin_count == nullptr
  2519. || factory->get_plugin_descriptor == nullptr
  2520. || factory->create_plugin == nullptr)
  2521. {
  2522. pData->engine->setLastError("Plugin is missing factory methods");
  2523. return false;
  2524. }
  2525. // ---------------------------------------------------------------
  2526. if (const uint32_t count = factory->get_plugin_count(factory))
  2527. {
  2528. // null id requested, use first available plugin
  2529. if (id == nullptr || id[0] == '\0')
  2530. {
  2531. fPluginDescriptor = factory->get_plugin_descriptor(factory, 0);
  2532. if (fPluginDescriptor == nullptr)
  2533. {
  2534. pData->engine->setLastError("Plugin library does not contain a valid first plugin");
  2535. return false;
  2536. }
  2537. }
  2538. else
  2539. {
  2540. for (uint32_t i=0; i<count; ++i)
  2541. {
  2542. const clap_plugin_descriptor_t* const desc = factory->get_plugin_descriptor(factory, i);
  2543. CARLA_SAFE_ASSERT_CONTINUE(desc != nullptr);
  2544. CARLA_SAFE_ASSERT_CONTINUE(desc->id != nullptr);
  2545. if (std::strcmp(desc->id, id) == 0)
  2546. {
  2547. fPluginDescriptor = desc;
  2548. break;
  2549. }
  2550. }
  2551. if (fPluginDescriptor == nullptr)
  2552. {
  2553. pData->engine->setLastError("Plugin library does not contain the requested plugin");
  2554. return false;
  2555. }
  2556. }
  2557. }
  2558. else
  2559. {
  2560. pData->engine->setLastError("Plugin library contains no plugins");
  2561. return false;
  2562. }
  2563. // ---------------------------------------------------------------
  2564. fPlugin = factory->create_plugin(factory, &fHost, fPluginDescriptor->id);
  2565. if (fPlugin == nullptr)
  2566. {
  2567. pData->engine->setLastError("Failed to create CLAP plugin instance");
  2568. return false;
  2569. }
  2570. if (!fPlugin->init(fPlugin))
  2571. {
  2572. pData->engine->setLastError("Failed to initialize CLAP plugin instance");
  2573. return false;
  2574. }
  2575. // ---------------------------------------------------------------
  2576. // get info
  2577. pData->name = pData->engine->getUniquePluginName(name != nullptr && name[0] != '\0' ? name
  2578. : fPluginDescriptor->name);
  2579. pData->filename = carla_strdup(filename);
  2580. // ---------------------------------------------------------------
  2581. // register client
  2582. pData->client = pData->engine->addClient(plugin);
  2583. if (pData->client == nullptr || ! pData->client->isOk())
  2584. {
  2585. pData->engine->setLastError("Failed to register plugin client");
  2586. return false;
  2587. }
  2588. // ---------------------------------------------------------------
  2589. // set default options
  2590. pData->options = PLUGIN_OPTION_FIXED_BUFFERS;
  2591. if (const clap_plugin_state_t* const stateExt =
  2592. static_cast<const clap_plugin_state_t*>(fPlugin->get_extension(fPlugin, CLAP_EXT_STATE)))
  2593. {
  2594. if (stateExt->save != nullptr && stateExt->load != nullptr)
  2595. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2596. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2597. }
  2598. if (const clap_plugin_note_ports_t* const notePortsExt =
  2599. static_cast<const clap_plugin_note_ports_t*>(fPlugin->get_extension(fPlugin, CLAP_EXT_NOTE_PORTS)))
  2600. {
  2601. const uint32_t numNoteInputPorts = notePortsExt->count != nullptr && notePortsExt->get != nullptr
  2602. ? notePortsExt->count(fPlugin, true) : 0;
  2603. for (uint32_t i=0; i<numNoteInputPorts; ++i)
  2604. {
  2605. clap_note_port_info_t portInfo = {};
  2606. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  2607. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI)
  2608. {
  2609. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2610. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2611. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2612. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2613. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2614. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2615. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2616. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2617. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2618. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2619. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2620. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2621. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2622. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2623. break;
  2624. }
  2625. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_CLAP)
  2626. {
  2627. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2628. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2629. // nobreak, in case another port supports MIDI
  2630. }
  2631. }
  2632. }
  2633. // if (fEffect->numPrograms > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  2634. // if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2635. // pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2636. return true;
  2637. }
  2638. private:
  2639. const clap_plugin_t* fPlugin;
  2640. const clap_plugin_descriptor_t* fPluginDescriptor;
  2641. const clap_plugin_entry_t* fPluginEntry;
  2642. const carla_clap_host fHost;
  2643. struct Extensions {
  2644. const clap_plugin_latency_t* latency;
  2645. const clap_plugin_params_t* params;
  2646. const clap_plugin_state_t* state;
  2647. const clap_plugin_timer_support_t* timer;
  2648. #ifdef CLAP_WINDOW_API_NATIVE
  2649. const clap_plugin_gui_t* gui;
  2650. #ifdef _POSIX_VERSION
  2651. const clap_plugin_posix_fd_support_t* posixFD;
  2652. #endif
  2653. #endif
  2654. Extensions()
  2655. : latency(nullptr),
  2656. params(nullptr),
  2657. state(nullptr),
  2658. timer(nullptr)
  2659. #ifdef CLAP_WINDOW_API_NATIVE
  2660. , gui(nullptr)
  2661. #ifdef _POSIX_VERSION
  2662. , posixFD(nullptr)
  2663. #endif
  2664. #endif
  2665. {
  2666. }
  2667. CARLA_DECLARE_NON_COPYABLE(Extensions)
  2668. } fExtensions;
  2669. #ifdef CLAP_WINDOW_API_NATIVE
  2670. struct UI {
  2671. bool initalized;
  2672. bool isCreated;
  2673. bool isEmbed;
  2674. bool isVisible;
  2675. bool isResizingFromHost;
  2676. bool isResizingFromInit;
  2677. int isResizingFromPlugin;
  2678. bool shouldClose;
  2679. uint32_t width, height;
  2680. CarlaPluginUI* window;
  2681. UI()
  2682. : initalized(false),
  2683. isCreated(false),
  2684. isEmbed(false),
  2685. isVisible(false),
  2686. isResizingFromHost(false),
  2687. isResizingFromInit(false),
  2688. isResizingFromPlugin(0),
  2689. shouldClose(false),
  2690. width(0),
  2691. height(0),
  2692. window(nullptr) {}
  2693. ~UI()
  2694. {
  2695. CARLA_SAFE_ASSERT(window == nullptr);
  2696. }
  2697. CARLA_DECLARE_NON_COPYABLE(UI)
  2698. } fUI;
  2699. #ifdef _POSIX_VERSION
  2700. LinkedList<HostPosixFileDescriptorDetails> fPosixFileDescriptors;
  2701. #endif
  2702. LinkedList<HostTimerDetails> fTimers;
  2703. #endif
  2704. carla_clap_input_audio_buffers fInputAudioBuffers;
  2705. carla_clap_output_audio_buffers fOutputAudioBuffers;
  2706. carla_clap_input_events fInputEvents;
  2707. carla_clap_output_events fOutputEvents;
  2708. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2709. float** fAudioOutBuffers;
  2710. #endif
  2711. void* fLastChunk;
  2712. uint32_t fLastKnownLatency;
  2713. const bool kEngineHasIdleOnMainThread;
  2714. bool fNeedsParamFlush;
  2715. bool fNeedsRestart;
  2716. bool fNeedsProcess;
  2717. bool fNeedsIdleCallback;
  2718. #ifdef CARLA_OS_MAC
  2719. BundleLoader fBundleLoader;
  2720. #endif
  2721. void runIdleCallbacksAsNeeded(const bool isIdleCallback)
  2722. {
  2723. if (isIdleCallback && (fNeedsRestart || fNeedsProcess))
  2724. {
  2725. carla_stdout("runIdleCallbacksAsNeeded %d %d", fNeedsRestart, fNeedsProcess);
  2726. const bool needsRestart = fNeedsRestart;
  2727. if (needsRestart)
  2728. {
  2729. fNeedsRestart = false;
  2730. setActive(false, true, true);
  2731. }
  2732. if (fNeedsProcess)
  2733. {
  2734. fNeedsProcess = false;
  2735. setEnabled(true);
  2736. setActive(true, true, true);
  2737. }
  2738. else if (needsRestart)
  2739. {
  2740. setActive(true, true, true);
  2741. }
  2742. }
  2743. if (fNeedsParamFlush)
  2744. {
  2745. fNeedsParamFlush = false;
  2746. carla_clap_input_events copy;
  2747. copy.reallocEqualTo(fInputEvents);
  2748. {
  2749. const ScopedSingleProcessLocker sspl(this, true);
  2750. fInputEvents.handleScheduledParameterUpdates();
  2751. fInputEvents.swap(copy);
  2752. }
  2753. fExtensions.params->flush(fPlugin, copy.cast(), nullptr);
  2754. }
  2755. if (fNeedsIdleCallback)
  2756. {
  2757. fNeedsIdleCallback = false;
  2758. fPlugin->on_main_thread(fPlugin);
  2759. }
  2760. #ifdef CLAP_WINDOW_API_NATIVE
  2761. #ifdef _POSIX_VERSION
  2762. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2763. {
  2764. const HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallback));
  2765. #ifdef CARLA_CLAP_POSIX_EPOLL
  2766. struct ::epoll_event event;
  2767. #else
  2768. const int16_t filter = posixFD.flags & CLAP_POSIX_FD_WRITE ? EVFILT_WRITE : EVFILT_READ;
  2769. struct ::kevent kev = {}, event;
  2770. struct ::timespec timeout = {};
  2771. EV_SET(&kev, posixFD.pluginFd, filter, EV_ADD|EV_ENABLE, 0, 0, nullptr);
  2772. #endif
  2773. for (int i=0; i<50; ++i)
  2774. {
  2775. #ifdef CARLA_CLAP_POSIX_EPOLL
  2776. switch (::epoll_wait(posixFD.hostFd, &event, 1, 0))
  2777. #else
  2778. switch (::kevent(posixFD.hostFd, &kev, 1, &event, 1, &timeout))
  2779. #endif
  2780. {
  2781. case 1:
  2782. fExtensions.posixFD->on_fd(fPlugin, posixFD.pluginFd, posixFD.flags);
  2783. break;
  2784. case -1:
  2785. fExtensions.posixFD->on_fd(fPlugin, posixFD.pluginFd, posixFD.flags | CLAP_POSIX_FD_ERROR);
  2786. // fall through
  2787. case 0:
  2788. i = 50;
  2789. break;
  2790. default:
  2791. carla_safe_exception("posix fd received abnormal value", __FILE__, __LINE__);
  2792. i = 50;
  2793. break;
  2794. }
  2795. }
  2796. }
  2797. #endif // _POSIX_VERSION
  2798. for (LinkedList<HostTimerDetails>::Itenerator it = fTimers.begin2(); it.valid(); it.next())
  2799. {
  2800. const uint32_t currentTimeInMs = water::Time::getMillisecondCounter();
  2801. HostTimerDetails& timer(it.getValue(kTimerFallbackNC));
  2802. if (currentTimeInMs > timer.lastCallTimeInMs + timer.periodInMs)
  2803. {
  2804. timer.lastCallTimeInMs = currentTimeInMs;
  2805. fExtensions.timer->on_timer(fPlugin, timer.clapId);
  2806. }
  2807. }
  2808. #endif // CLAP_WINDOW_API_NATIVE
  2809. }
  2810. };
  2811. // --------------------------------------------------------------------------------------------------------------------
  2812. CarlaPluginPtr CarlaPlugin::newCLAP(const Initializer& init)
  2813. {
  2814. carla_debug("CarlaPlugin::newCLAP({%p, \"%s\", \"%s\", \"%s\"})",
  2815. init.engine, init.filename, init.name, init.label);
  2816. std::shared_ptr<CarlaPluginCLAP> plugin(new CarlaPluginCLAP(init.engine, init.id));
  2817. if (! plugin->init(plugin, init.filename, init.name, init.label, init.options))
  2818. return nullptr;
  2819. return plugin;
  2820. }
  2821. // -------------------------------------------------------------------------------------------------------------------
  2822. CARLA_BACKEND_END_NAMESPACE