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.

CarlaPluginBridge.cpp 118KB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308
  1. /*
  2. * Carla Plugin Bridge
  3. * Copyright (C) 2011-2022 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #include "CarlaPluginInternal.hpp"
  18. #include "CarlaBackendUtils.hpp"
  19. #include "CarlaBase64Utils.hpp"
  20. #include "CarlaBridgeUtils.hpp"
  21. #include "CarlaEngineUtils.hpp"
  22. #include "CarlaMathUtils.hpp"
  23. #include "CarlaPipeUtils.hpp"
  24. #include "CarlaScopeUtils.hpp"
  25. #include "CarlaShmUtils.hpp"
  26. #include "CarlaThread.hpp"
  27. #include "jackbridge/JackBridge.hpp"
  28. #include <ctime>
  29. #include "water/files/File.h"
  30. #include "water/misc/Time.h"
  31. #include "water/threads/ChildProcess.h"
  32. // --------------------------------------------------------------------------------------------------------------------
  33. using water::ChildProcess;
  34. using water::File;
  35. using water::String;
  36. using water::StringArray;
  37. using water::Time;
  38. CARLA_BACKEND_START_NAMESPACE
  39. // --------------------------------------------------------------------------------------------------------------------
  40. // Fallback data
  41. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  42. // --------------------------------------------------------------------------------------------------------------------
  43. static String findWinePrefix(const String filename, const int recursionLimit = 10)
  44. {
  45. if (recursionLimit == 0 || filename.length() < 5 || ! filename.contains("/"))
  46. return "";
  47. const String path(filename.upToLastOccurrenceOf("/", false, false));
  48. if (File(path + "/dosdevices").isDirectory())
  49. return path;
  50. return findWinePrefix(path, recursionLimit-1);
  51. }
  52. // --------------------------------------------------------------------------------------------------------------------
  53. struct BridgeParamInfo {
  54. float value;
  55. CarlaString name;
  56. CarlaString symbol;
  57. CarlaString unit;
  58. BridgeParamInfo() noexcept
  59. : value(0.0f),
  60. name(),
  61. symbol(),
  62. unit() {}
  63. CARLA_DECLARE_NON_COPYABLE(BridgeParamInfo)
  64. };
  65. struct BridgeTextReader {
  66. char* text;
  67. BridgeTextReader(BridgeNonRtServerControl& nonRtServerCtrl)
  68. : text(nullptr)
  69. {
  70. const uint32_t size = nonRtServerCtrl.readUInt();
  71. CARLA_SAFE_ASSERT_RETURN(size != 0,);
  72. text = new char[size + 1];
  73. nonRtServerCtrl.readCustomData(text, size);
  74. text[size] = '\0';
  75. }
  76. BridgeTextReader(BridgeNonRtServerControl& nonRtServerCtrl, const uint32_t size)
  77. : text(nullptr)
  78. {
  79. text = new char[size + 1];
  80. if (size != 0)
  81. nonRtServerCtrl.readCustomData(text, size);
  82. text[size] = '\0';
  83. }
  84. ~BridgeTextReader() noexcept
  85. {
  86. delete[] text;
  87. }
  88. CARLA_DECLARE_NON_COPYABLE(BridgeTextReader)
  89. };
  90. // --------------------------------------------------------------------------------------------------------------------
  91. class CarlaPluginBridgeThread : public CarlaThread
  92. {
  93. public:
  94. CarlaPluginBridgeThread(CarlaEngine* const engine, CarlaPlugin* const plugin) noexcept
  95. : CarlaThread("CarlaPluginBridgeThread"),
  96. kEngine(engine),
  97. kPlugin(plugin),
  98. fBinaryArchName(),
  99. fBridgeBinary(),
  100. fLabel(),
  101. fShmIds(),
  102. #ifndef CARLA_OS_WIN
  103. fWinePrefix(),
  104. #endif
  105. fProcess() {}
  106. void setData(
  107. #ifndef CARLA_OS_WIN
  108. const char* const winePrefix,
  109. #endif
  110. const char* const binaryArchName,
  111. const char* const bridgeBinary,
  112. const char* const label,
  113. const char* const shmIds) noexcept
  114. {
  115. CARLA_SAFE_ASSERT_RETURN(bridgeBinary != nullptr && bridgeBinary[0] != '\0',);
  116. CARLA_SAFE_ASSERT_RETURN(shmIds != nullptr && shmIds[0] != '\0',);
  117. CARLA_SAFE_ASSERT(! isThreadRunning());
  118. #ifndef CARLA_OS_WIN
  119. fWinePrefix = winePrefix;
  120. #endif
  121. fBinaryArchName = binaryArchName;
  122. fBridgeBinary = bridgeBinary;
  123. fShmIds = shmIds;
  124. if (label != nullptr)
  125. fLabel = label;
  126. if (fLabel.isEmpty())
  127. fLabel = "(none)";
  128. }
  129. uintptr_t getProcessPID() const noexcept
  130. {
  131. CARLA_SAFE_ASSERT_RETURN(fProcess != nullptr, 0);
  132. return (uintptr_t)fProcess->getPID();
  133. }
  134. protected:
  135. void run()
  136. {
  137. if (fProcess == nullptr)
  138. {
  139. fProcess = new ChildProcess();
  140. }
  141. else if (fProcess->isRunning())
  142. {
  143. carla_stderr("CarlaPluginBridgeThread::run() - already running");
  144. }
  145. char strBuf[STR_MAX+1];
  146. strBuf[STR_MAX] = '\0';
  147. const EngineOptions& options(kEngine->getOptions());
  148. String filename(kPlugin->getFilename());
  149. if (filename.isEmpty())
  150. filename = "(none)";
  151. StringArray arguments;
  152. #ifndef CARLA_OS_WIN
  153. // start with "wine" if needed
  154. if (fBridgeBinary.endsWithIgnoreCase(".exe"))
  155. {
  156. String wineCMD;
  157. if (options.wine.executable != nullptr && options.wine.executable[0] != '\0')
  158. {
  159. wineCMD = options.wine.executable;
  160. if (fBridgeBinary.endsWithIgnoreCase("64.exe")
  161. && options.wine.executable[0] == CARLA_OS_SEP
  162. && File(wineCMD + "64").existsAsFile())
  163. wineCMD += "64";
  164. }
  165. else
  166. {
  167. wineCMD = "wine";
  168. }
  169. arguments.add(wineCMD);
  170. }
  171. #endif
  172. // setup binary arch
  173. ChildProcess::Type childType;
  174. #ifdef CARLA_OS_MAC
  175. if (fBinaryArchName == "arm64")
  176. childType = ChildProcess::TypeARM;
  177. else if (fBinaryArchName == "x86_64")
  178. childType = ChildProcess::TypeIntel;
  179. else
  180. #endif
  181. childType = ChildProcess::TypeAny;
  182. // bridge binary
  183. arguments.add(fBridgeBinary);
  184. // plugin type
  185. arguments.add(getPluginTypeAsString(kPlugin->getType()));
  186. // filename
  187. arguments.add(filename);
  188. // label
  189. arguments.add(fLabel);
  190. // uniqueId
  191. arguments.add(String(static_cast<water::int64>(kPlugin->getUniqueId())));
  192. bool started;
  193. {
  194. const ScopedEngineEnvironmentLocker _seel(kEngine);
  195. #ifdef CARLA_OS_LINUX
  196. const CarlaScopedEnvVar sev1("LD_LIBRARY_PATH", nullptr);
  197. const CarlaScopedEnvVar sev2("LD_PRELOAD", nullptr);
  198. #endif
  199. carla_setenv("ENGINE_OPTION_FORCE_STEREO", bool2str(options.forceStereo));
  200. carla_setenv("ENGINE_OPTION_PREFER_PLUGIN_BRIDGES", bool2str(options.preferPluginBridges));
  201. carla_setenv("ENGINE_OPTION_PREFER_UI_BRIDGES", bool2str(options.preferUiBridges));
  202. carla_setenv("ENGINE_OPTION_UIS_ALWAYS_ON_TOP", bool2str(options.uisAlwaysOnTop));
  203. std::snprintf(strBuf, STR_MAX, "%u", options.maxParameters);
  204. carla_setenv("ENGINE_OPTION_MAX_PARAMETERS", strBuf);
  205. std::snprintf(strBuf, STR_MAX, "%u", options.uiBridgesTimeout);
  206. carla_setenv("ENGINE_OPTION_UI_BRIDGES_TIMEOUT",strBuf);
  207. if (options.pathLADSPA != nullptr)
  208. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LADSPA", options.pathLADSPA);
  209. else
  210. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LADSPA", "");
  211. if (options.pathDSSI != nullptr)
  212. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_DSSI", options.pathDSSI);
  213. else
  214. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_DSSI", "");
  215. if (options.pathLV2 != nullptr)
  216. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LV2", options.pathLV2);
  217. else
  218. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LV2", "");
  219. if (options.pathVST2 != nullptr)
  220. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST2", options.pathVST2);
  221. else
  222. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST2", "");
  223. if (options.pathVST3 != nullptr)
  224. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST3", options.pathVST3);
  225. else
  226. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST3", "");
  227. if (options.pathSF2 != nullptr)
  228. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SF2", options.pathSF2);
  229. else
  230. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SF2", "");
  231. if (options.pathSFZ != nullptr)
  232. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SFZ", options.pathSFZ);
  233. else
  234. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SFZ", "");
  235. if (options.pathJSFX != nullptr)
  236. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_JSFX", options.pathJSFX);
  237. else
  238. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_JSFX", "");
  239. if (options.binaryDir != nullptr)
  240. carla_setenv("ENGINE_OPTION_PATH_BINARIES", options.binaryDir);
  241. else
  242. carla_setenv("ENGINE_OPTION_PATH_BINARIES", "");
  243. if (options.resourceDir != nullptr)
  244. carla_setenv("ENGINE_OPTION_PATH_RESOURCES", options.resourceDir);
  245. else
  246. carla_setenv("ENGINE_OPTION_PATH_RESOURCES", "");
  247. carla_setenv("ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR", bool2str(options.preventBadBehaviour));
  248. std::snprintf(strBuf, STR_MAX, P_UINTPTR, options.frontendWinId);
  249. carla_setenv("ENGINE_OPTION_FRONTEND_WIN_ID", strBuf);
  250. carla_setenv("ENGINE_BRIDGE_SHM_IDS", fShmIds.toRawUTF8());
  251. #ifndef CARLA_OS_WIN
  252. if (fWinePrefix.isNotEmpty())
  253. {
  254. carla_setenv("WINEDEBUG", "-all");
  255. carla_setenv("WINEPREFIX", fWinePrefix.toRawUTF8());
  256. if (options.wine.rtPrio)
  257. {
  258. carla_setenv("STAGING_SHARED_MEMORY", "1");
  259. carla_setenv("WINE_RT_POLICY", "FF");
  260. std::snprintf(strBuf, STR_MAX, "%i", options.wine.baseRtPrio);
  261. carla_setenv("STAGING_RT_PRIORITY_BASE", strBuf);
  262. carla_setenv("WINE_RT", strBuf);
  263. carla_setenv("WINE_RT_PRIO", strBuf);
  264. std::snprintf(strBuf, STR_MAX, "%i", options.wine.serverRtPrio);
  265. carla_setenv("STAGING_RT_PRIORITY_SERVER", strBuf);
  266. carla_setenv("WINE_SVR_RT", strBuf);
  267. carla_stdout("Using WINEPREFIX '%s', with base RT prio %i and server RT prio %i",
  268. fWinePrefix.toRawUTF8(), options.wine.baseRtPrio, options.wine.serverRtPrio);
  269. }
  270. else
  271. {
  272. carla_unsetenv("STAGING_SHARED_MEMORY");
  273. carla_unsetenv("WINE_RT_POLICY");
  274. carla_unsetenv("STAGING_RT_PRIORITY_BASE");
  275. carla_unsetenv("STAGING_RT_PRIORITY_SERVER");
  276. carla_unsetenv("WINE_RT");
  277. carla_unsetenv("WINE_RT_PRIO");
  278. carla_unsetenv("WINE_SVR_RT");
  279. carla_stdout("Using WINEPREFIX '%s', without RT priorities", fWinePrefix.toRawUTF8());
  280. }
  281. }
  282. #endif
  283. carla_stdout("Starting plugin bridge, command is:\n%s \"%s\" \"%s\" \"%s\" " P_INT64,
  284. fBridgeBinary.toRawUTF8(), getPluginTypeAsString(kPlugin->getType()), filename.toRawUTF8(), fLabel.toRawUTF8(), kPlugin->getUniqueId());
  285. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  286. const File projFolder(kEngine->getCurrentProjectFolder());
  287. if (projFolder.isNotNull())
  288. {
  289. const File oldFolder(File::getCurrentWorkingDirectory());
  290. projFolder.setAsCurrentWorkingDirectory();
  291. started = fProcess->start(arguments, childType);
  292. oldFolder.setAsCurrentWorkingDirectory();
  293. }
  294. else
  295. #endif
  296. {
  297. started = fProcess->start(arguments, childType);
  298. }
  299. }
  300. if (! started)
  301. {
  302. carla_stdout("failed!");
  303. fProcess = nullptr;
  304. return;
  305. }
  306. for (; fProcess->isRunning() && ! shouldThreadExit();)
  307. carla_sleep(1);
  308. // we only get here if bridge crashed or thread asked to exit
  309. if (fProcess->isRunning() && shouldThreadExit())
  310. {
  311. fProcess->waitForProcessToFinish(2000);
  312. if (fProcess->isRunning())
  313. {
  314. carla_stdout("CarlaPluginBridgeThread::run() - bridge refused to close, force kill now");
  315. fProcess->kill();
  316. }
  317. else
  318. {
  319. carla_stdout("CarlaPluginBridgeThread::run() - bridge auto-closed successfully");
  320. }
  321. }
  322. else
  323. {
  324. // forced quit, may have crashed
  325. if (fProcess->getExitCodeAndClearPID() != 0)
  326. {
  327. carla_stderr("CarlaPluginBridgeThread::run() - bridge crashed");
  328. CarlaString errorString("Plugin '" + CarlaString(kPlugin->getName()) + "' has crashed!\n"
  329. "Saving now will lose its current settings.\n"
  330. "Please remove this plugin, and not rely on it from this point.");
  331. kEngine->callback(true, true,
  332. ENGINE_CALLBACK_ERROR, kPlugin->getId(), 0, 0, 0, 0.0f, errorString);
  333. }
  334. }
  335. fProcess = nullptr;
  336. }
  337. private:
  338. CarlaEngine* const kEngine;
  339. CarlaPlugin* const kPlugin;
  340. String fBinaryArchName;
  341. String fBridgeBinary;
  342. String fLabel;
  343. String fShmIds;
  344. #ifndef CARLA_OS_WIN
  345. String fWinePrefix;
  346. #endif
  347. CarlaScopedPointer<ChildProcess> fProcess;
  348. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginBridgeThread)
  349. };
  350. // ---------------------------------------------------------------------------------------------------------------------
  351. class CarlaPluginBridge : public CarlaPlugin
  352. {
  353. public:
  354. CarlaPluginBridge(CarlaEngine* const engine, const uint id, const BinaryType btype, const PluginType ptype)
  355. : CarlaPlugin(engine, id),
  356. fBinaryType(btype),
  357. fPluginType(ptype),
  358. fBridgeVersion(6), // before kPluginBridgeNonRtServerVersion was a thing, API was at 6
  359. fInitiated(false),
  360. fInitError(false),
  361. fSaved(true),
  362. fTimedOut(false),
  363. fTimedError(false),
  364. fBufferSize(engine->getBufferSize()),
  365. fProcWaitTime(0),
  366. fPendingEmbedCustomUI(0),
  367. fBridgeBinary(),
  368. fBridgeThread(engine, this),
  369. fShmAudioPool(),
  370. fShmRtClientControl(),
  371. fShmNonRtClientControl(),
  372. fShmNonRtServerControl(),
  373. #ifndef CARLA_OS_WIN
  374. fWinePrefix(),
  375. #endif
  376. fReceivingParamText(),
  377. fInfo(),
  378. fUniqueId(0),
  379. fLatency(0),
  380. fParams(nullptr)
  381. {
  382. carla_debug("CarlaPluginBridge::CarlaPluginBridge(%p, %i, %s, %s)", engine, id, BinaryType2Str(btype), PluginType2Str(ptype));
  383. pData->hints |= PLUGIN_IS_BRIDGE;
  384. }
  385. ~CarlaPluginBridge() override
  386. {
  387. carla_debug("CarlaPluginBridge::~CarlaPluginBridge()");
  388. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  389. // close UI
  390. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  391. pData->transientTryCounter = 0;
  392. #endif
  393. pData->singleMutex.lock();
  394. pData->masterMutex.lock();
  395. if (pData->client != nullptr && pData->client->isActive())
  396. pData->client->deactivate(true);
  397. if (pData->active)
  398. {
  399. deactivate();
  400. pData->active = false;
  401. }
  402. if (fBridgeThread.isThreadRunning())
  403. {
  404. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientQuit);
  405. fShmNonRtClientControl.commitWrite();
  406. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientQuit);
  407. fShmRtClientControl.commitWrite();
  408. if (! fTimedOut)
  409. waitForClient("stopping", 3000);
  410. }
  411. fBridgeThread.stopThread(3000);
  412. fShmNonRtServerControl.clear();
  413. fShmNonRtClientControl.clear();
  414. fShmRtClientControl.clear();
  415. fShmAudioPool.clear();
  416. clearBuffers();
  417. fInfo.chunk.clear();
  418. }
  419. // -------------------------------------------------------------------
  420. // Information (base)
  421. BinaryType getBinaryType() const noexcept override
  422. {
  423. return fBinaryType;
  424. }
  425. PluginType getType() const noexcept override
  426. {
  427. return fPluginType;
  428. }
  429. PluginCategory getCategory() const noexcept override
  430. {
  431. return fInfo.category;
  432. }
  433. int64_t getUniqueId() const noexcept override
  434. {
  435. return fUniqueId;
  436. }
  437. uint32_t getLatencyInFrames() const noexcept override
  438. {
  439. return fLatency;
  440. }
  441. // -------------------------------------------------------------------
  442. // Information (count)
  443. uint32_t getMidiInCount() const noexcept override
  444. {
  445. return fInfo.mIns;
  446. }
  447. uint32_t getMidiOutCount() const noexcept override
  448. {
  449. return fInfo.mOuts;
  450. }
  451. // -------------------------------------------------------------------
  452. // Information (current data)
  453. std::size_t getChunkData(void** const dataPtr) noexcept override
  454. {
  455. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  456. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  457. waitForSaved();
  458. CARLA_SAFE_ASSERT_RETURN(fInfo.chunk.size() > 0, 0);
  459. #ifdef CARLA_PROPER_CPP11_SUPPORT
  460. *dataPtr = fInfo.chunk.data();
  461. #else
  462. *dataPtr = &fInfo.chunk.front();
  463. #endif
  464. return fInfo.chunk.size();
  465. }
  466. // -------------------------------------------------------------------
  467. // Information (per-plugin data)
  468. uint getOptionsAvailable() const noexcept override
  469. {
  470. return fInfo.optionsAvailable;
  471. }
  472. float getParameterValue(const uint32_t parameterId) const noexcept override
  473. {
  474. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  475. return fParams[parameterId].value;
  476. }
  477. bool getLabel(char* const strBuf) const noexcept override
  478. {
  479. std::strncpy(strBuf, fInfo.label, STR_MAX);
  480. return true;
  481. }
  482. bool getMaker(char* const strBuf) const noexcept override
  483. {
  484. std::strncpy(strBuf, fInfo.maker, STR_MAX);
  485. return true;
  486. }
  487. bool getCopyright(char* const strBuf) const noexcept override
  488. {
  489. std::strncpy(strBuf, fInfo.copyright, STR_MAX);
  490. return true;
  491. }
  492. bool getRealName(char* const strBuf) const noexcept override
  493. {
  494. std::strncpy(strBuf, fInfo.name, STR_MAX);
  495. return true;
  496. }
  497. bool getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  498. {
  499. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  500. std::strncpy(strBuf, fParams[parameterId].name.buffer(), STR_MAX);
  501. return true;
  502. }
  503. bool getParameterText(const uint32_t parameterId, char* const strBuf) noexcept override
  504. {
  505. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  506. CARLA_SAFE_ASSERT_RETURN(! fReceivingParamText.isCurrentlyWaitingData(), false);
  507. const int32_t parameterIdi = static_cast<int32_t>(parameterId);
  508. fReceivingParamText.setTargetData(parameterIdi, strBuf);
  509. {
  510. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  511. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientGetParameterText);
  512. fShmNonRtClientControl.writeInt(parameterIdi);
  513. fShmNonRtClientControl.commitWrite();
  514. }
  515. if (waitForParameterText())
  516. return true;
  517. std::snprintf(strBuf, STR_MAX, "%.12g", static_cast<double>(fParams[parameterId].value));
  518. return false;
  519. }
  520. bool getParameterSymbol(const uint32_t parameterId, char* const strBuf) const noexcept override
  521. {
  522. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  523. std::strncpy(strBuf, fParams[parameterId].symbol.buffer(), STR_MAX);
  524. return true;
  525. }
  526. bool getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  527. {
  528. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  529. std::strncpy(strBuf, fParams[parameterId].unit.buffer(), STR_MAX);
  530. return true;
  531. }
  532. // -------------------------------------------------------------------
  533. // Set data (state)
  534. void prepareForSave(bool) noexcept override
  535. {
  536. fSaved = false;
  537. {
  538. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  539. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPrepareForSave);
  540. fShmNonRtClientControl.commitWrite();
  541. }
  542. }
  543. bool waitForParameterText()
  544. {
  545. bool success;
  546. if (fReceivingParamText.wasDataReceived(&success))
  547. return success;
  548. const uint32_t timeoutEnd = Time::getMillisecondCounter() + 500; // 500 ms
  549. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  550. for (; Time::getMillisecondCounter() < timeoutEnd && fBridgeThread.isThreadRunning();)
  551. {
  552. if (fReceivingParamText.wasDataReceived(&success))
  553. return success;
  554. if (needsEngineIdle)
  555. pData->engine->idle();
  556. carla_msleep(5);
  557. }
  558. if (! fBridgeThread.isThreadRunning())
  559. {
  560. carla_stderr("CarlaPluginBridge::waitForParameterText() - Bridge is not running");
  561. return false;
  562. }
  563. carla_stderr("CarlaPluginBridge::waitForParameterText() - Timeout while requesting text");
  564. return false;
  565. }
  566. void waitForSaved()
  567. {
  568. if (fSaved)
  569. return;
  570. // TODO: only wait 1 minute for NI plugins
  571. const uint32_t timeoutEnd = Time::getMillisecondCounter() + 60*1000; // 60 secs, 1 minute
  572. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  573. for (; Time::getMillisecondCounter() < timeoutEnd && fBridgeThread.isThreadRunning();)
  574. {
  575. pData->engine->callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  576. if (needsEngineIdle)
  577. pData->engine->idle();
  578. if (fSaved)
  579. break;
  580. carla_msleep(20);
  581. }
  582. if (! fBridgeThread.isThreadRunning())
  583. return carla_stderr("CarlaPluginBridge::waitForSaved() - Bridge is not running");
  584. if (! fSaved)
  585. return carla_stderr("CarlaPluginBridge::waitForSaved() - Timeout while requesting save state");
  586. }
  587. // -------------------------------------------------------------------
  588. // Set data (internal stuff)
  589. void setOption(const uint option, const bool yesNo, const bool sendCallback) override
  590. {
  591. {
  592. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  593. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOption);
  594. fShmNonRtClientControl.writeUInt(option);
  595. fShmNonRtClientControl.writeBool(yesNo);
  596. fShmNonRtClientControl.commitWrite();
  597. }
  598. CarlaPlugin::setOption(option, yesNo, sendCallback);
  599. }
  600. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  601. {
  602. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,);
  603. {
  604. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  605. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCtrlChannel);
  606. fShmNonRtClientControl.writeShort(channel);
  607. fShmNonRtClientControl.commitWrite();
  608. }
  609. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  610. }
  611. void setName(const char* const newName) override
  612. {
  613. CarlaPlugin::setName(newName);
  614. if (pData->uiTitle.isEmpty() && fBridgeVersion >= 8)
  615. _setUiTitleFromName();
  616. }
  617. // -------------------------------------------------------------------
  618. // Set data (plugin-specific stuff)
  619. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  620. {
  621. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  622. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback,);
  623. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  624. fParams[parameterId].value = fixedValue;
  625. {
  626. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  627. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterValue);
  628. fShmNonRtClientControl.writeUInt(parameterId);
  629. fShmNonRtClientControl.writeFloat(value);
  630. fShmNonRtClientControl.commitWrite();
  631. fShmNonRtClientControl.waitIfDataIsReachingLimit();
  632. }
  633. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  634. }
  635. void setParameterValueRT(const uint32_t parameterId, const float value, const uint32_t frameOffset, const bool sendCallbackLater) noexcept override
  636. {
  637. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  638. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  639. fParams[parameterId].value = fixedValue;
  640. {
  641. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  642. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterValue);
  643. fShmNonRtClientControl.writeUInt(parameterId);
  644. fShmNonRtClientControl.writeFloat(value);
  645. fShmNonRtClientControl.commitWrite();
  646. fShmNonRtClientControl.waitIfDataIsReachingLimit();
  647. }
  648. CarlaPlugin::setParameterValueRT(parameterId, fixedValue, frameOffset, sendCallbackLater);
  649. }
  650. void setParameterMidiChannel(const uint32_t parameterId, const uint8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  651. {
  652. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  653. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  654. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,);
  655. {
  656. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  657. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterMidiChannel);
  658. fShmNonRtClientControl.writeUInt(parameterId);
  659. fShmNonRtClientControl.writeByte(channel);
  660. fShmNonRtClientControl.commitWrite();
  661. }
  662. CarlaPlugin::setParameterMidiChannel(parameterId, channel, sendOsc, sendCallback);
  663. }
  664. void setParameterMappedControlIndex(const uint32_t parameterId, const int16_t index,
  665. const bool sendOsc, const bool sendCallback,
  666. const bool reconfigureNow) noexcept override
  667. {
  668. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  669. CARLA_SAFE_ASSERT_RETURN(index >= CONTROL_INDEX_NONE && index <= CONTROL_INDEX_MAX_ALLOWED,);
  670. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,);
  671. {
  672. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  673. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterMappedControlIndex);
  674. fShmNonRtClientControl.writeUInt(parameterId);
  675. fShmNonRtClientControl.writeShort(index);
  676. fShmNonRtClientControl.commitWrite();
  677. }
  678. CarlaPlugin::setParameterMappedControlIndex(parameterId, index, sendOsc, sendCallback, reconfigureNow);
  679. }
  680. void setParameterMappedRange(const uint32_t parameterId, const float minimum, const float maximum, const bool sendOsc, const bool sendCallback) noexcept override
  681. {
  682. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  683. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,);
  684. // kPluginBridgeNonRtClientSetParameterMappedRange was added in API 7
  685. if (fBridgeVersion >= 7)
  686. {
  687. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  688. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterMappedRange);
  689. fShmNonRtClientControl.writeUInt(parameterId);
  690. fShmNonRtClientControl.writeFloat(minimum);
  691. fShmNonRtClientControl.writeFloat(maximum);
  692. fShmNonRtClientControl.commitWrite();
  693. }
  694. CarlaPlugin::setParameterMappedRange(parameterId, minimum, maximum, sendOsc, sendCallback);
  695. }
  696. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback, const bool doingInit) noexcept override
  697. {
  698. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  699. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback || doingInit,);
  700. {
  701. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  702. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetProgram);
  703. fShmNonRtClientControl.writeInt(index);
  704. fShmNonRtClientControl.commitWrite();
  705. }
  706. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback, doingInit);
  707. }
  708. void setProgramRT(const uint32_t index, const bool sendCallbackLater) noexcept override
  709. {
  710. CARLA_SAFE_ASSERT_RETURN(index < pData->prog.count,);
  711. {
  712. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  713. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetProgram);
  714. fShmNonRtClientControl.writeInt(static_cast<int32_t>(index));
  715. fShmNonRtClientControl.commitWrite();
  716. }
  717. CarlaPlugin::setProgramRT(index, sendCallbackLater);
  718. }
  719. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback, const bool doingInit) noexcept override
  720. {
  721. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  722. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback || doingInit,);
  723. {
  724. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  725. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetMidiProgram);
  726. fShmNonRtClientControl.writeInt(index);
  727. fShmNonRtClientControl.commitWrite();
  728. }
  729. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback, doingInit);
  730. }
  731. void setMidiProgramRT(const uint32_t uindex, const bool sendCallbackLater) noexcept override
  732. {
  733. CARLA_SAFE_ASSERT_RETURN(uindex < pData->midiprog.count,);
  734. {
  735. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  736. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetMidiProgram);
  737. fShmNonRtClientControl.writeInt(static_cast<int32_t>(uindex));
  738. fShmNonRtClientControl.commitWrite();
  739. }
  740. CarlaPlugin::setMidiProgramRT(uindex, sendCallbackLater);
  741. }
  742. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  743. {
  744. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  745. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  746. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  747. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  748. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  749. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) == 0 && std::strcmp(key, "__CarlaPingOnOff__") == 0)
  750. {
  751. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  752. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPingOnOff);
  753. fShmNonRtClientControl.writeBool(std::strcmp(value, "true") == 0);
  754. fShmNonRtClientControl.commitWrite();
  755. return;
  756. }
  757. const uint32_t typeLen = static_cast<uint32_t>(std::strlen(type));
  758. const uint32_t keyLen = static_cast<uint32_t>(std::strlen(key));
  759. const uint32_t valueLen = static_cast<uint32_t>(std::strlen(value));
  760. /*
  761. if (valueLen > 16384)
  762. fShmNonRtClientControl.waitIfDataIsReachingLimit();
  763. */
  764. {
  765. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  766. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCustomData);
  767. fShmNonRtClientControl.writeUInt(typeLen);
  768. fShmNonRtClientControl.writeCustomData(type, typeLen);
  769. fShmNonRtClientControl.writeUInt(keyLen);
  770. fShmNonRtClientControl.writeCustomData(key, keyLen);
  771. fShmNonRtClientControl.writeUInt(valueLen);
  772. if (valueLen > 0)
  773. {
  774. if (valueLen > 16384)
  775. {
  776. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  777. filePath += CARLA_OS_SEP_STR ".CarlaCustomData_";
  778. filePath += fShmAudioPool.getFilenameSuffix();
  779. if (File(filePath).replaceWithText(value))
  780. {
  781. const uint32_t ulength = static_cast<uint32_t>(filePath.length());
  782. fShmNonRtClientControl.writeUInt(ulength);
  783. fShmNonRtClientControl.writeCustomData(filePath.toRawUTF8(), ulength);
  784. }
  785. else
  786. {
  787. fShmNonRtClientControl.writeUInt(0);
  788. }
  789. }
  790. else
  791. {
  792. fShmNonRtClientControl.writeCustomData(value, valueLen);
  793. }
  794. }
  795. fShmNonRtClientControl.commitWrite();
  796. }
  797. CarlaPlugin::setCustomData(type, key, value, sendGui);
  798. }
  799. void setChunkData(const void* const data, const std::size_t dataSize) override
  800. {
  801. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  802. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  803. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  804. CarlaString dataBase64(CarlaString::asBase64(data, dataSize));
  805. CARLA_SAFE_ASSERT_RETURN(dataBase64.length() > 0,);
  806. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  807. filePath += CARLA_OS_SEP_STR ".CarlaChunk_";
  808. filePath += fShmAudioPool.getFilenameSuffix();
  809. if (File(filePath).replaceWithText(dataBase64.buffer()))
  810. {
  811. const uint32_t ulength = static_cast<uint32_t>(filePath.length());
  812. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  813. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetChunkDataFile);
  814. fShmNonRtClientControl.writeUInt(ulength);
  815. fShmNonRtClientControl.writeCustomData(filePath.toRawUTF8(), ulength);
  816. fShmNonRtClientControl.commitWrite();
  817. }
  818. // save data internally as well
  819. fInfo.chunk.resize(dataSize);
  820. #ifdef CARLA_PROPER_CPP11_SUPPORT
  821. std::memcpy(fInfo.chunk.data(), data, dataSize);
  822. #else
  823. std::memcpy(&fInfo.chunk.front(), data, dataSize);
  824. #endif
  825. }
  826. // -------------------------------------------------------------------
  827. // Set ui stuff
  828. void setCustomUITitle(const char* const title) noexcept override
  829. {
  830. carla_debug("CarlaPluginBridge::setCustomUITitle(%s)", title);
  831. if (fBridgeVersion >= 8)
  832. {
  833. const uint32_t size = static_cast<uint32_t>(std::strlen(title));
  834. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  835. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetWindowTitle);
  836. fShmNonRtClientControl.writeUInt(size);
  837. fShmNonRtClientControl.writeCustomData(title, size);
  838. fShmNonRtClientControl.commitWrite();
  839. }
  840. CarlaPlugin::setCustomUITitle(title);
  841. }
  842. void showCustomUI(const bool yesNo) override
  843. {
  844. if (yesNo && pData->uiTitle.isEmpty() && fBridgeVersion >= 8)
  845. _setUiTitleFromName();
  846. {
  847. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  848. fShmNonRtClientControl.writeOpcode(yesNo ? kPluginBridgeNonRtClientShowUI : kPluginBridgeNonRtClientHideUI);
  849. fShmNonRtClientControl.commitWrite();
  850. }
  851. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  852. if (yesNo)
  853. {
  854. pData->tryTransient();
  855. }
  856. else
  857. {
  858. pData->transientTryCounter = 0;
  859. }
  860. #endif
  861. }
  862. void* embedCustomUI(void* const ptr) override
  863. {
  864. if (fBridgeVersion < 9)
  865. return nullptr;
  866. fPendingEmbedCustomUI = 0;
  867. {
  868. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  869. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientEmbedUI);
  870. fShmNonRtClientControl.writeULong(reinterpret_cast<uint64_t>(ptr));
  871. fShmNonRtClientControl.commitWrite();
  872. }
  873. const uint32_t timeoutEnd = Time::getMillisecondCounter() + 15*1000; // 15 secs
  874. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  875. for (; Time::getMillisecondCounter() < timeoutEnd && fBridgeThread.isThreadRunning();)
  876. {
  877. pData->engine->callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  878. if (needsEngineIdle)
  879. pData->engine->idle();
  880. if (fPendingEmbedCustomUI != 0)
  881. {
  882. if (fPendingEmbedCustomUI == 1)
  883. fPendingEmbedCustomUI = 0;
  884. break;
  885. }
  886. carla_msleep(20);
  887. }
  888. return reinterpret_cast<void*>(fPendingEmbedCustomUI);
  889. }
  890. void idle() override
  891. {
  892. if (fBridgeThread.isThreadRunning())
  893. {
  894. if (fInitiated && fTimedOut && pData->active)
  895. setActive(false, true, true);
  896. {
  897. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  898. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  899. fShmNonRtClientControl.commitWrite();
  900. }
  901. try {
  902. handleNonRtData();
  903. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  904. }
  905. else if (fInitiated)
  906. {
  907. fTimedOut = true;
  908. fTimedError = true;
  909. fInitiated = false;
  910. handleProcessStopped();
  911. }
  912. CarlaPlugin::idle();
  913. }
  914. // -------------------------------------------------------------------
  915. // Plugin state
  916. void reload() override
  917. {
  918. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  919. carla_debug("CarlaPluginBridge::reload() - start");
  920. const EngineProcessMode processMode(pData->engine->getProccessMode());
  921. // Safely disable plugin for reload
  922. const ScopedDisabler sd(this);
  923. // cleanup of previous data
  924. pData->audioIn.clear();
  925. pData->audioOut.clear();
  926. pData->cvIn.clear();
  927. pData->cvOut.clear();
  928. pData->event.clear();
  929. bool needsCtrlIn, needsCtrlOut;
  930. needsCtrlIn = needsCtrlOut = false;
  931. if (fInfo.aIns > 0)
  932. {
  933. pData->audioIn.createNew(fInfo.aIns);
  934. }
  935. if (fInfo.aOuts > 0)
  936. {
  937. pData->audioOut.createNew(fInfo.aOuts);
  938. needsCtrlIn = true;
  939. }
  940. if (fInfo.cvIns > 0)
  941. {
  942. pData->cvIn.createNew(fInfo.cvIns);
  943. }
  944. if (fInfo.cvOuts > 0)
  945. {
  946. pData->cvOut.createNew(fInfo.cvOuts);
  947. }
  948. if (fInfo.mIns > 0)
  949. needsCtrlIn = true;
  950. if (fInfo.mOuts > 0)
  951. needsCtrlOut = true;
  952. const uint portNameSize(pData->engine->getMaxPortNameSize());
  953. CarlaString portName;
  954. // Audio Ins
  955. for (uint32_t j=0; j < fInfo.aIns; ++j)
  956. {
  957. portName.clear();
  958. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  959. {
  960. portName = pData->name;
  961. portName += ":";
  962. }
  963. if (fInfo.aInNames != nullptr && fInfo.aInNames[j] != nullptr)
  964. {
  965. portName += fInfo.aInNames[j];
  966. }
  967. else if (fInfo.aIns > 1)
  968. {
  969. portName += "input_";
  970. portName += CarlaString(j+1);
  971. }
  972. else
  973. portName += "input";
  974. portName.truncate(portNameSize);
  975. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  976. pData->audioIn.ports[j].rindex = j;
  977. }
  978. // Audio Outs
  979. for (uint32_t j=0; j < fInfo.aOuts; ++j)
  980. {
  981. portName.clear();
  982. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  983. {
  984. portName = pData->name;
  985. portName += ":";
  986. }
  987. if (fInfo.aOutNames != nullptr && fInfo.aOutNames[j] != nullptr)
  988. {
  989. portName += fInfo.aOutNames[j];
  990. }
  991. else if (fInfo.aOuts > 1)
  992. {
  993. portName += "output_";
  994. portName += CarlaString(j+1);
  995. }
  996. else
  997. portName += "output";
  998. portName.truncate(portNameSize);
  999. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  1000. pData->audioOut.ports[j].rindex = j;
  1001. }
  1002. // TODO - MIDI
  1003. // CV Ins
  1004. for (uint32_t j=0; j < fInfo.cvIns; ++j)
  1005. {
  1006. portName.clear();
  1007. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1008. {
  1009. portName = pData->name;
  1010. portName += ":";
  1011. }
  1012. if (fInfo.cvInNames != nullptr && fInfo.cvInNames[j] != nullptr)
  1013. {
  1014. portName += fInfo.cvInNames[j];
  1015. }
  1016. else if (fInfo.cvIns > 1)
  1017. {
  1018. portName += "cv_input_";
  1019. portName += CarlaString(j+1);
  1020. }
  1021. else
  1022. portName += "cv_input";
  1023. portName.truncate(portNameSize);
  1024. pData->cvIn.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, true, j);
  1025. pData->cvIn.ports[j].rindex = j;
  1026. }
  1027. // CV Outs
  1028. for (uint32_t j=0; j < fInfo.cvOuts; ++j)
  1029. {
  1030. portName.clear();
  1031. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1032. {
  1033. portName = pData->name;
  1034. portName += ":";
  1035. }
  1036. if (fInfo.cvOutNames != nullptr && fInfo.cvOutNames[j] != nullptr)
  1037. {
  1038. portName += fInfo.cvOutNames[j];
  1039. }
  1040. else if (fInfo.cvOuts > 1)
  1041. {
  1042. portName += "cv_output_";
  1043. portName += CarlaString(j+1);
  1044. }
  1045. else
  1046. portName += "cv_output";
  1047. portName.truncate(portNameSize);
  1048. pData->cvOut.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, false, j);
  1049. pData->cvOut.ports[j].rindex = j;
  1050. }
  1051. if (needsCtrlIn)
  1052. {
  1053. portName.clear();
  1054. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1055. {
  1056. portName = pData->name;
  1057. portName += ":";
  1058. }
  1059. portName += "event-in";
  1060. portName.truncate(portNameSize);
  1061. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  1062. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1063. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  1064. #endif
  1065. }
  1066. if (needsCtrlOut)
  1067. {
  1068. portName.clear();
  1069. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1070. {
  1071. portName = pData->name;
  1072. portName += ":";
  1073. }
  1074. portName += "event-out";
  1075. portName.truncate(portNameSize);
  1076. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  1077. }
  1078. // extra plugin hints
  1079. pData->extraHints = 0x0;
  1080. if (fInfo.mIns > 0)
  1081. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  1082. if (fInfo.mOuts > 0)
  1083. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  1084. bufferSizeChanged(pData->engine->getBufferSize());
  1085. reloadPrograms(true);
  1086. carla_debug("CarlaPluginBridge::reload() - end");
  1087. }
  1088. // -------------------------------------------------------------------
  1089. // Plugin processing
  1090. void activate() noexcept override
  1091. {
  1092. if (! fBridgeThread.isThreadRunning())
  1093. {
  1094. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  1095. }
  1096. {
  1097. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1098. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  1099. fShmNonRtClientControl.commitWrite();
  1100. }
  1101. fTimedOut = false;
  1102. try {
  1103. waitForClient("activate", 2000);
  1104. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  1105. }
  1106. void deactivate() noexcept override
  1107. {
  1108. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1109. {
  1110. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1111. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  1112. fShmNonRtClientControl.commitWrite();
  1113. }
  1114. fTimedOut = false;
  1115. try {
  1116. waitForClient("deactivate", 2000);
  1117. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  1118. }
  1119. void process(const float* const* const audioIn,
  1120. float** const audioOut,
  1121. const float* const* const cvIn,
  1122. float** const cvOut,
  1123. const uint32_t frames) override
  1124. {
  1125. // --------------------------------------------------------------------------------------------------------
  1126. // Check if active
  1127. if (fTimedOut || fTimedError || ! pData->active)
  1128. {
  1129. // disable any output sound
  1130. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1131. carla_zeroFloats(audioOut[i], frames);
  1132. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1133. carla_zeroFloats(cvOut[i], frames);
  1134. return;
  1135. }
  1136. // --------------------------------------------------------------------------------------------------------
  1137. // Check if needs reset
  1138. if (pData->needsReset)
  1139. {
  1140. // TODO
  1141. pData->needsReset = false;
  1142. }
  1143. // --------------------------------------------------------------------------------------------------------
  1144. // Event Input
  1145. if (pData->event.portIn != nullptr)
  1146. {
  1147. // ----------------------------------------------------------------------------------------------------
  1148. // MIDI Input (External)
  1149. if (pData->extNotes.mutex.tryLock())
  1150. {
  1151. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  1152. {
  1153. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  1154. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1155. uint8_t data1, data2, data3;
  1156. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  1157. data2 = note.note;
  1158. data3 = note.velo;
  1159. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1160. fShmRtClientControl.writeUInt(0); // time
  1161. fShmRtClientControl.writeByte(0); // port
  1162. fShmRtClientControl.writeByte(3); // size
  1163. fShmRtClientControl.writeByte(data1);
  1164. fShmRtClientControl.writeByte(data2);
  1165. fShmRtClientControl.writeByte(data3);
  1166. fShmRtClientControl.commitWrite();
  1167. }
  1168. pData->extNotes.data.clear();
  1169. pData->extNotes.mutex.unlock();
  1170. } // End of MIDI Input (External)
  1171. // ----------------------------------------------------------------------------------------------------
  1172. // Event Input (System)
  1173. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1174. bool allNotesOffSent = false;
  1175. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  1176. {
  1177. const bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0x0;
  1178. pData->event.cvSourcePorts->initPortBuffers(cvIn + pData->cvIn.count, frames, isSampleAccurate, pData->event.portIn);
  1179. }
  1180. #endif
  1181. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  1182. {
  1183. EngineEvent& event(pData->event.portIn->getEvent(i));
  1184. // Control change
  1185. switch (event.type)
  1186. {
  1187. case kEngineEventTypeNull:
  1188. break;
  1189. case kEngineEventTypeControl: {
  1190. EngineControlEvent& ctrlEvent = event.ctrl;
  1191. switch (ctrlEvent.type)
  1192. {
  1193. case kEngineControlEventTypeNull:
  1194. break;
  1195. case kEngineControlEventTypeParameter: {
  1196. float value;
  1197. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1198. // non-midi
  1199. if (event.channel == kEngineEventNonMidiChannel)
  1200. {
  1201. const uint32_t k = ctrlEvent.param;
  1202. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  1203. ctrlEvent.handled = true;
  1204. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1205. setParameterValueRT(k, value, event.time, true);
  1206. continue;
  1207. }
  1208. // Control backend stuff
  1209. if (event.channel == pData->ctrlChannel)
  1210. {
  1211. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1212. {
  1213. ctrlEvent.handled = true;
  1214. value = ctrlEvent.normalizedValue;
  1215. setDryWetRT(value, true);
  1216. }
  1217. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1218. {
  1219. ctrlEvent.handled = true;
  1220. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  1221. setVolumeRT(value, true);
  1222. }
  1223. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1224. {
  1225. float left, right;
  1226. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  1227. if (value < 0.0f)
  1228. {
  1229. left = -1.0f;
  1230. right = (value*2.0f)+1.0f;
  1231. }
  1232. else if (value > 0.0f)
  1233. {
  1234. left = (value*2.0f)-1.0f;
  1235. right = 1.0f;
  1236. }
  1237. else
  1238. {
  1239. left = -1.0f;
  1240. right = 1.0f;
  1241. }
  1242. ctrlEvent.handled = true;
  1243. setBalanceLeftRT(left, true);
  1244. setBalanceRightRT(right, true);
  1245. }
  1246. }
  1247. #endif
  1248. // Control plugin parameters
  1249. for (uint32_t k=0; k < pData->param.count; ++k)
  1250. {
  1251. if (pData->param.data[k].midiChannel != event.channel)
  1252. continue;
  1253. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  1254. continue;
  1255. if (pData->param.data[k].type != PARAMETER_INPUT)
  1256. continue;
  1257. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  1258. continue;
  1259. ctrlEvent.handled = true;
  1260. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1261. setParameterValueRT(k, value, event.time, true);
  1262. }
  1263. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1264. if (! ctrlEvent.handled)
  1265. checkForMidiLearn(event);
  1266. #endif
  1267. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  1268. {
  1269. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1270. fShmRtClientControl.writeUInt(event.time);
  1271. fShmRtClientControl.writeByte(0); // port
  1272. fShmRtClientControl.writeByte(3); // size
  1273. fShmRtClientControl.writeByte(uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT)));
  1274. fShmRtClientControl.writeByte(uint8_t(ctrlEvent.param));
  1275. fShmRtClientControl.writeByte(uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f));
  1276. }
  1277. break;
  1278. }
  1279. case kEngineControlEventTypeMidiBank:
  1280. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1281. {
  1282. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  1283. fShmRtClientControl.writeUInt(event.time);
  1284. fShmRtClientControl.writeByte(event.channel);
  1285. fShmRtClientControl.writeUShort(event.ctrl.param);
  1286. fShmRtClientControl.commitWrite();
  1287. }
  1288. else if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  1289. {
  1290. // VST2's that use banks usually require both a MSB bank message and a LSB bank message. The MSB bank message can just be 0
  1291. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1292. fShmRtClientControl.writeUInt(event.time);
  1293. fShmRtClientControl.writeByte(0); // port
  1294. fShmRtClientControl.writeByte(3); // size
  1295. fShmRtClientControl.writeByte(uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT)));
  1296. fShmRtClientControl.writeByte(MIDI_CONTROL_BANK_SELECT);
  1297. fShmRtClientControl.writeByte(0);
  1298. fShmRtClientControl.commitWrite();
  1299. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1300. fShmRtClientControl.writeUInt(event.time);
  1301. fShmRtClientControl.writeByte(0); // port
  1302. fShmRtClientControl.writeByte(3); // size
  1303. fShmRtClientControl.writeByte(uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT)));
  1304. fShmRtClientControl.writeByte(MIDI_CONTROL_BANK_SELECT__LSB);
  1305. fShmRtClientControl.writeByte(uint8_t(event.ctrl.param));
  1306. fShmRtClientControl.commitWrite();
  1307. }
  1308. break;
  1309. case kEngineControlEventTypeMidiProgram:
  1310. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES || pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1311. {
  1312. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  1313. fShmRtClientControl.writeUInt(event.time);
  1314. fShmRtClientControl.writeByte(event.channel);
  1315. fShmRtClientControl.writeUShort(event.ctrl.param);
  1316. fShmRtClientControl.commitWrite();
  1317. }
  1318. break;
  1319. case kEngineControlEventTypeAllSoundOff:
  1320. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1321. {
  1322. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  1323. fShmRtClientControl.writeUInt(event.time);
  1324. fShmRtClientControl.writeByte(event.channel);
  1325. fShmRtClientControl.commitWrite();
  1326. }
  1327. break;
  1328. case kEngineControlEventTypeAllNotesOff:
  1329. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1330. {
  1331. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1332. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1333. {
  1334. allNotesOffSent = true;
  1335. postponeRtAllNotesOff();
  1336. }
  1337. #endif
  1338. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  1339. fShmRtClientControl.writeUInt(event.time);
  1340. fShmRtClientControl.writeByte(event.channel);
  1341. fShmRtClientControl.commitWrite();
  1342. }
  1343. break;
  1344. } // switch (ctrlEvent.type)
  1345. break;
  1346. } // case kEngineEventTypeControl
  1347. case kEngineEventTypeMidi: {
  1348. const EngineMidiEvent& midiEvent(event.midi);
  1349. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  1350. continue;
  1351. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  1352. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  1353. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1354. continue;
  1355. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1356. continue;
  1357. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1358. continue;
  1359. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1360. continue;
  1361. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1362. continue;
  1363. // Fix bad note-off
  1364. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  1365. status = MIDI_STATUS_NOTE_OFF;
  1366. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1367. fShmRtClientControl.writeUInt(event.time);
  1368. fShmRtClientControl.writeByte(midiEvent.port);
  1369. fShmRtClientControl.writeByte(midiEvent.size);
  1370. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  1371. for (uint8_t j=1; j < midiEvent.size; ++j)
  1372. fShmRtClientControl.writeByte(midiData[j]);
  1373. fShmRtClientControl.commitWrite();
  1374. if (status == MIDI_STATUS_NOTE_ON)
  1375. {
  1376. pData->postponeNoteOnRtEvent(true, event.channel, midiData[1], midiData[2]);
  1377. }
  1378. else if (status == MIDI_STATUS_NOTE_OFF)
  1379. {
  1380. pData->postponeNoteOffRtEvent(true, event.channel, midiData[1]);
  1381. }
  1382. } break;
  1383. }
  1384. }
  1385. pData->postRtEvents.trySplice();
  1386. } // End of Event Input
  1387. if (! processSingle(audioIn, audioOut, cvIn, cvOut, frames))
  1388. return;
  1389. // --------------------------------------------------------------------------------------------------------
  1390. // Control and MIDI Output
  1391. if (pData->event.portOut != nullptr)
  1392. {
  1393. float value;
  1394. for (uint32_t k=0; k < pData->param.count; ++k)
  1395. {
  1396. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  1397. continue;
  1398. if (pData->param.data[k].mappedControlIndex > 0)
  1399. {
  1400. value = pData->param.ranges[k].getNormalizedValue(fParams[k].value);
  1401. pData->event.portOut->writeControlEvent(0,
  1402. pData->param.data[k].midiChannel,
  1403. kEngineControlEventTypeParameter,
  1404. static_cast<uint16_t>(pData->param.data[k].mappedControlIndex),
  1405. -1,
  1406. value);
  1407. }
  1408. }
  1409. uint32_t time;
  1410. uint8_t port, size;
  1411. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  1412. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  1413. {
  1414. // get time
  1415. time = *(const uint32_t*)midiData;
  1416. midiData += 4;
  1417. // get port and size
  1418. port = *midiData++;
  1419. size = *midiData++;
  1420. if (size == 0)
  1421. break;
  1422. // store midi data advancing as needed
  1423. uint8_t data[size];
  1424. for (uint8_t j=0; j<size; ++j)
  1425. data[j] = *midiData++;
  1426. pData->event.portOut->writeMidiEvent(time, size, data);
  1427. read += kBridgeBaseMidiOutHeaderSize + size;
  1428. }
  1429. // TODO
  1430. (void)port;
  1431. } // End of Control and MIDI Output
  1432. }
  1433. bool processSingle(const float* const* const audioIn, float** const audioOut,
  1434. const float* const* const cvIn, float** const cvOut, const uint32_t frames)
  1435. {
  1436. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  1437. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1438. CARLA_SAFE_ASSERT_RETURN(frames <= fBufferSize, false);
  1439. if (pData->audioIn.count > 0)
  1440. {
  1441. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  1442. }
  1443. if (pData->audioOut.count > 0)
  1444. {
  1445. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  1446. }
  1447. if (pData->cvIn.count > 0)
  1448. {
  1449. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  1450. }
  1451. if (pData->cvOut.count > 0)
  1452. {
  1453. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  1454. }
  1455. // --------------------------------------------------------------------------------------------------------
  1456. // Try lock, silence otherwise
  1457. #ifndef STOAT_TEST_BUILD
  1458. if (pData->engine->isOffline())
  1459. {
  1460. pData->singleMutex.lock();
  1461. }
  1462. else
  1463. #endif
  1464. if (! pData->singleMutex.tryLock())
  1465. {
  1466. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1467. carla_zeroFloats(audioOut[i], frames);
  1468. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1469. carla_zeroFloats(cvOut[i], frames);
  1470. return false;
  1471. }
  1472. // --------------------------------------------------------------------------------------------------------
  1473. // Reset audio buffers
  1474. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1475. carla_copyFloats(fShmAudioPool.data + (i * fBufferSize), audioIn[i], frames);
  1476. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  1477. carla_copyFloats(fShmAudioPool.data + ((pData->audioIn.count + pData->audioOut.count + i) * fBufferSize), cvIn[i], frames);
  1478. // --------------------------------------------------------------------------------------------------------
  1479. // TimeInfo
  1480. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1481. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  1482. bridgeTimeInfo.playing = timeInfo.playing;
  1483. bridgeTimeInfo.frame = timeInfo.frame;
  1484. bridgeTimeInfo.usecs = timeInfo.usecs;
  1485. bridgeTimeInfo.validFlags = timeInfo.bbt.valid ? kPluginBridgeTimeInfoValidBBT : 0x0;
  1486. if (timeInfo.bbt.valid)
  1487. {
  1488. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  1489. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  1490. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  1491. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  1492. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  1493. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  1494. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  1495. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  1496. }
  1497. // --------------------------------------------------------------------------------------------------------
  1498. // Run plugin
  1499. {
  1500. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  1501. fShmRtClientControl.writeUInt(frames);
  1502. fShmRtClientControl.commitWrite();
  1503. }
  1504. waitForClient("process", fProcWaitTime);
  1505. if (fTimedOut)
  1506. {
  1507. pData->singleMutex.unlock();
  1508. return false;
  1509. }
  1510. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1511. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((pData->audioIn.count + i) * fBufferSize), frames);
  1512. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1513. carla_copyFloats(cvOut[i], fShmAudioPool.data + ((pData->audioIn.count + pData->audioOut.count + pData->cvIn.count + i) * fBufferSize), frames);
  1514. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1515. // --------------------------------------------------------------------------------------------------------
  1516. // Post-processing (dry/wet, volume and balance)
  1517. {
  1518. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1519. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1520. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1521. const bool isMono = (pData->audioIn.count == 1);
  1522. bool isPair;
  1523. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1524. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1525. {
  1526. // Dry/Wet
  1527. if (doDryWet)
  1528. {
  1529. const uint32_t c = isMono ? 0 : i;
  1530. for (uint32_t k=0; k < frames; ++k)
  1531. {
  1532. # ifndef BUILD_BRIDGE
  1533. if (k < pData->latency.frames && pData->latency.buffers != nullptr)
  1534. bufValue = pData->latency.buffers[c][k];
  1535. else if (pData->latency.frames < frames)
  1536. bufValue = audioIn[c][k-pData->latency.frames];
  1537. else
  1538. # endif
  1539. bufValue = audioIn[c][k];
  1540. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1541. }
  1542. }
  1543. // Balance
  1544. if (doBalance)
  1545. {
  1546. isPair = (i % 2 == 0);
  1547. if (isPair)
  1548. {
  1549. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1550. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  1551. }
  1552. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1553. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1554. for (uint32_t k=0; k < frames; ++k)
  1555. {
  1556. if (isPair)
  1557. {
  1558. // left
  1559. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1560. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  1561. }
  1562. else
  1563. {
  1564. // right
  1565. audioOut[i][k] = audioOut[i][k] * balRangeR;
  1566. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  1567. }
  1568. }
  1569. }
  1570. // Volume (and buffer copy)
  1571. if (doVolume)
  1572. {
  1573. for (uint32_t k=0; k < frames; ++k)
  1574. audioOut[i][k] *= pData->postProc.volume;
  1575. }
  1576. }
  1577. } // End of Post-processing
  1578. # ifndef BUILD_BRIDGE
  1579. // --------------------------------------------------------------------------------------------------------
  1580. // Save latency values for next callback
  1581. if (pData->latency.frames != 0 && pData->latency.buffers != nullptr)
  1582. {
  1583. const uint32_t latframes = pData->latency.frames;
  1584. if (latframes <= frames)
  1585. {
  1586. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1587. carla_copyFloats(pData->latency.buffers[i], audioIn[i]+(frames-latframes), latframes);
  1588. }
  1589. else
  1590. {
  1591. const uint32_t diff = latframes - frames;
  1592. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  1593. {
  1594. // push back buffer by 'frames'
  1595. for (k=0; k < diff; ++k)
  1596. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  1597. // put current input at the end
  1598. for (uint32_t j=0; k < latframes; ++j, ++k)
  1599. pData->latency.buffers[i][k] = audioIn[i][j];
  1600. }
  1601. }
  1602. }
  1603. # endif
  1604. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  1605. // --------------------------------------------------------------------------------------------------------
  1606. pData->singleMutex.unlock();
  1607. return true;
  1608. }
  1609. void bufferSizeChanged(const uint32_t newBufferSize) override
  1610. {
  1611. fBufferSize = newBufferSize;
  1612. resizeAudioPool(newBufferSize);
  1613. {
  1614. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  1615. fShmRtClientControl.writeUInt(newBufferSize);
  1616. fShmRtClientControl.commitWrite();
  1617. }
  1618. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  1619. fProcWaitTime = 1000;
  1620. waitForClient("buffersize", 1000);
  1621. }
  1622. void sampleRateChanged(const double newSampleRate) override
  1623. {
  1624. {
  1625. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  1626. fShmRtClientControl.writeDouble(newSampleRate);
  1627. fShmRtClientControl.commitWrite();
  1628. }
  1629. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  1630. fProcWaitTime = 1000;
  1631. waitForClient("samplerate", 1000);
  1632. }
  1633. void offlineModeChanged(const bool isOffline) override
  1634. {
  1635. {
  1636. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  1637. fShmRtClientControl.writeBool(isOffline);
  1638. fShmRtClientControl.commitWrite();
  1639. }
  1640. waitForClient("offline", 1000);
  1641. }
  1642. // -------------------------------------------------------------------
  1643. // Plugin buffers
  1644. void clearBuffers() noexcept override
  1645. {
  1646. if (fParams != nullptr)
  1647. {
  1648. delete[] fParams;
  1649. fParams = nullptr;
  1650. }
  1651. CarlaPlugin::clearBuffers();
  1652. }
  1653. // -------------------------------------------------------------------
  1654. // Post-poned UI Stuff
  1655. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1656. {
  1657. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1658. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1659. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiParameterChange);
  1660. fShmNonRtClientControl.writeUInt(index);
  1661. fShmNonRtClientControl.writeFloat(value);
  1662. fShmNonRtClientControl.commitWrite();
  1663. }
  1664. void uiProgramChange(const uint32_t index) noexcept override
  1665. {
  1666. CARLA_SAFE_ASSERT_RETURN(index < pData->prog.count,);
  1667. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1668. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiProgramChange);
  1669. fShmNonRtClientControl.writeUInt(index);
  1670. fShmNonRtClientControl.commitWrite();
  1671. }
  1672. void uiMidiProgramChange(const uint32_t index) noexcept override
  1673. {
  1674. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1675. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1676. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiMidiProgramChange);
  1677. fShmNonRtClientControl.writeUInt(index);
  1678. fShmNonRtClientControl.commitWrite();
  1679. }
  1680. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  1681. {
  1682. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1683. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1684. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  1685. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1686. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiNoteOn);
  1687. fShmNonRtClientControl.writeByte(channel);
  1688. fShmNonRtClientControl.writeByte(note);
  1689. fShmNonRtClientControl.writeByte(velo);
  1690. fShmNonRtClientControl.commitWrite();
  1691. }
  1692. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  1693. {
  1694. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1695. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1696. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1697. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiNoteOff);
  1698. fShmNonRtClientControl.writeByte(channel);
  1699. fShmNonRtClientControl.writeByte(note);
  1700. fShmNonRtClientControl.commitWrite();
  1701. }
  1702. // -------------------------------------------------------------------
  1703. // Internal helper functions
  1704. void restoreLV2State(bool) noexcept override
  1705. {
  1706. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1707. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientRestoreLV2State);
  1708. fShmNonRtClientControl.commitWrite();
  1709. }
  1710. void waitForBridgeSaveSignal() noexcept override
  1711. {
  1712. // VSTs only save chunks, for which we already have a waitForSaved there
  1713. if (fPluginType != PLUGIN_VST2)
  1714. waitForSaved();
  1715. }
  1716. // -------------------------------------------------------------------
  1717. void handleNonRtData()
  1718. {
  1719. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  1720. {
  1721. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  1722. #ifdef DEBUG
  1723. if (opcode != kPluginBridgeNonRtServerPong && opcode != kPluginBridgeNonRtServerParameterValue2) {
  1724. carla_debug("CarlaPluginBridge::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  1725. }
  1726. #endif
  1727. switch (opcode)
  1728. {
  1729. case kPluginBridgeNonRtServerNull:
  1730. case kPluginBridgeNonRtServerPong:
  1731. break;
  1732. case kPluginBridgeNonRtServerVersion:
  1733. fBridgeVersion = fShmNonRtServerControl.readUInt();
  1734. break;
  1735. case kPluginBridgeNonRtServerPluginInfo1: {
  1736. // uint/category, uint/hints, uint/optionsAvailable, uint/optionsEnabled, long/uniqueId
  1737. const uint32_t category = fShmNonRtServerControl.readUInt();
  1738. const uint32_t hints = fShmNonRtServerControl.readUInt();
  1739. const uint32_t optionAv = fShmNonRtServerControl.readUInt();
  1740. const uint32_t optionEn = fShmNonRtServerControl.readUInt();
  1741. const int64_t uniqueId = fShmNonRtServerControl.readLong();
  1742. if (fUniqueId != 0) {
  1743. CARLA_SAFE_ASSERT_INT2(fUniqueId == uniqueId, fUniqueId, uniqueId);
  1744. }
  1745. pData->hints = hints | PLUGIN_IS_BRIDGE;
  1746. pData->options = optionEn;
  1747. #ifdef HAVE_X11
  1748. if (fBridgeVersion < 9 || fBinaryType == BINARY_WIN32 || fBinaryType == BINARY_WIN64)
  1749. #endif
  1750. {
  1751. pData->hints &= ~PLUGIN_HAS_CUSTOM_EMBED_UI;
  1752. }
  1753. fInfo.category = static_cast<PluginCategory>(category);
  1754. fInfo.optionsAvailable = optionAv;
  1755. } break;
  1756. case kPluginBridgeNonRtServerPluginInfo2: {
  1757. // uint/size, str[] (realName), uint/size, str[] (label), uint/size, str[] (maker), uint/size, str[] (copyright)
  1758. // realName
  1759. const BridgeTextReader realName(fShmNonRtServerControl);
  1760. // label
  1761. const BridgeTextReader label(fShmNonRtServerControl);
  1762. // maker
  1763. const BridgeTextReader maker(fShmNonRtServerControl);
  1764. // copyright
  1765. const BridgeTextReader copyright(fShmNonRtServerControl);
  1766. fInfo.name = realName.text;
  1767. fInfo.label = label.text;
  1768. fInfo.maker = maker.text;
  1769. fInfo.copyright = copyright.text;
  1770. if (pData->name == nullptr)
  1771. pData->name = pData->engine->getUniquePluginName(realName.text);
  1772. } break;
  1773. case kPluginBridgeNonRtServerAudioCount: {
  1774. // uint/ins, uint/outs
  1775. fInfo.clear();
  1776. fInfo.aIns = fShmNonRtServerControl.readUInt();
  1777. fInfo.aOuts = fShmNonRtServerControl.readUInt();
  1778. if (fInfo.aIns > 0)
  1779. {
  1780. fInfo.aInNames = new const char*[fInfo.aIns];
  1781. carla_zeroPointers(fInfo.aInNames, fInfo.aIns);
  1782. }
  1783. if (fInfo.aOuts > 0)
  1784. {
  1785. fInfo.aOutNames = new const char*[fInfo.aOuts];
  1786. carla_zeroPointers(fInfo.aOutNames, fInfo.aOuts);
  1787. }
  1788. } break;
  1789. case kPluginBridgeNonRtServerMidiCount: {
  1790. // uint/ins, uint/outs
  1791. fInfo.mIns = fShmNonRtServerControl.readUInt();
  1792. fInfo.mOuts = fShmNonRtServerControl.readUInt();
  1793. } break;
  1794. case kPluginBridgeNonRtServerCvCount: {
  1795. // uint/ins, uint/outs
  1796. fInfo.cvIns = fShmNonRtServerControl.readUInt();
  1797. fInfo.cvOuts = fShmNonRtServerControl.readUInt();
  1798. } break;
  1799. case kPluginBridgeNonRtServerParameterCount: {
  1800. // uint/count
  1801. const uint32_t count = fShmNonRtServerControl.readUInt();
  1802. // delete old data
  1803. pData->param.clear();
  1804. if (fParams != nullptr)
  1805. {
  1806. delete[] fParams;
  1807. fParams = nullptr;
  1808. }
  1809. if (count > 0)
  1810. {
  1811. pData->param.createNew(count, false);
  1812. fParams = new BridgeParamInfo[count];
  1813. // we might not receive all parameter data, so ensure range max is not 0
  1814. for (uint32_t i=0; i<count; ++i)
  1815. {
  1816. pData->param.ranges[i].def = 0.0f;
  1817. pData->param.ranges[i].min = 0.0f;
  1818. pData->param.ranges[i].max = 1.0f;
  1819. pData->param.ranges[i].step = 0.001f;
  1820. pData->param.ranges[i].stepSmall = 0.0001f;
  1821. pData->param.ranges[i].stepLarge = 0.1f;
  1822. }
  1823. }
  1824. } break;
  1825. case kPluginBridgeNonRtServerProgramCount: {
  1826. // uint/count
  1827. pData->prog.clear();
  1828. if (const uint32_t count = fShmNonRtServerControl.readUInt())
  1829. pData->prog.createNew(count);
  1830. } break;
  1831. case kPluginBridgeNonRtServerMidiProgramCount: {
  1832. // uint/count
  1833. pData->midiprog.clear();
  1834. if (const uint32_t count = fShmNonRtServerControl.readUInt())
  1835. pData->midiprog.createNew(count);
  1836. } break;
  1837. case kPluginBridgeNonRtServerPortName: {
  1838. // byte/type, uint/index, uint/size, str[] (name)
  1839. const uint8_t portType = fShmNonRtServerControl.readByte();
  1840. const uint32_t index = fShmNonRtServerControl.readUInt();
  1841. // name
  1842. const BridgeTextReader name(fShmNonRtServerControl);
  1843. CARLA_SAFE_ASSERT_BREAK(portType > kPluginBridgePortNull && portType < kPluginBridgePortTypeCount);
  1844. switch (portType)
  1845. {
  1846. case kPluginBridgePortAudioInput:
  1847. CARLA_SAFE_ASSERT_BREAK(index < fInfo.aIns);
  1848. fInfo.aInNames[index] = name.text;
  1849. break;
  1850. case kPluginBridgePortAudioOutput:
  1851. CARLA_SAFE_ASSERT_BREAK(index < fInfo.aOuts);
  1852. fInfo.aOutNames[index] = name.text;
  1853. break;
  1854. }
  1855. } break;
  1856. case kPluginBridgeNonRtServerParameterData1: {
  1857. // uint/index, int/rindex, uint/type, uint/hints, short/cc
  1858. const uint32_t index = fShmNonRtServerControl.readUInt();
  1859. const int32_t rindex = fShmNonRtServerControl.readInt();
  1860. const uint32_t type = fShmNonRtServerControl.readUInt();
  1861. const uint32_t hints = fShmNonRtServerControl.readUInt();
  1862. const int16_t ctrl = fShmNonRtServerControl.readShort();
  1863. CARLA_SAFE_ASSERT_INT_BREAK(ctrl >= CONTROL_INDEX_NONE && ctrl <= CONTROL_INDEX_MAX_ALLOWED, ctrl);
  1864. CARLA_SAFE_ASSERT_UINT2_BREAK(index < pData->param.count, index, pData->param.count);
  1865. pData->param.data[index].type = static_cast<ParameterType>(type);
  1866. pData->param.data[index].index = static_cast<int32_t>(index);
  1867. pData->param.data[index].rindex = rindex;
  1868. pData->param.data[index].hints = hints;
  1869. pData->param.data[index].mappedControlIndex = ctrl;
  1870. } break;
  1871. case kPluginBridgeNonRtServerParameterData2: {
  1872. // uint/index, uint/size, str[] (name), uint/size, str[] (unit)
  1873. const uint32_t index = fShmNonRtServerControl.readUInt();
  1874. // name
  1875. const BridgeTextReader name(fShmNonRtServerControl);
  1876. // symbol
  1877. const BridgeTextReader symbol(fShmNonRtServerControl);
  1878. // unit
  1879. const BridgeTextReader unit(fShmNonRtServerControl);
  1880. CARLA_SAFE_ASSERT_UINT2_BREAK(index < pData->param.count, index, pData->param.count);
  1881. fParams[index].name = name.text;
  1882. fParams[index].symbol = symbol.text;
  1883. fParams[index].unit = unit.text;
  1884. } break;
  1885. case kPluginBridgeNonRtServerParameterRanges: {
  1886. // uint/index, float/def, float/min, float/max, float/step, float/stepSmall, float/stepLarge
  1887. const uint32_t index = fShmNonRtServerControl.readUInt();
  1888. const float def = fShmNonRtServerControl.readFloat();
  1889. const float min = fShmNonRtServerControl.readFloat();
  1890. const float max = fShmNonRtServerControl.readFloat();
  1891. const float step = fShmNonRtServerControl.readFloat();
  1892. const float stepSmall = fShmNonRtServerControl.readFloat();
  1893. const float stepLarge = fShmNonRtServerControl.readFloat();
  1894. CARLA_SAFE_ASSERT_BREAK(min < max);
  1895. CARLA_SAFE_ASSERT_BREAK(def >= min);
  1896. CARLA_SAFE_ASSERT_BREAK(def <= max);
  1897. CARLA_SAFE_ASSERT_UINT2_BREAK(index < pData->param.count, index, pData->param.count);
  1898. pData->param.ranges[index].def = def;
  1899. pData->param.ranges[index].min = min;
  1900. pData->param.ranges[index].max = max;
  1901. pData->param.ranges[index].step = step;
  1902. pData->param.ranges[index].stepSmall = stepSmall;
  1903. pData->param.ranges[index].stepLarge = stepLarge;
  1904. } break;
  1905. case kPluginBridgeNonRtServerParameterValue: {
  1906. // uint/index, float/value
  1907. const uint32_t index = fShmNonRtServerControl.readUInt();
  1908. const float value = fShmNonRtServerControl.readFloat();
  1909. if (index < pData->param.count)
  1910. {
  1911. const float fixedValue(pData->param.getFixedValue(index, value));
  1912. if (carla_isNotEqual(fParams[index].value, fixedValue))
  1913. {
  1914. fParams[index].value = fixedValue;
  1915. CarlaPlugin::setParameterValue(index, fixedValue, false, true, true);
  1916. }
  1917. }
  1918. } break;
  1919. case kPluginBridgeNonRtServerParameterValue2: {
  1920. // uint/index, float/value
  1921. const uint32_t index = fShmNonRtServerControl.readUInt();
  1922. const float value = fShmNonRtServerControl.readFloat();
  1923. if (index < pData->param.count)
  1924. {
  1925. const float fixedValue(pData->param.getFixedValue(index, value));
  1926. fParams[index].value = fixedValue;
  1927. }
  1928. } break;
  1929. case kPluginBridgeNonRtServerParameterTouch: {
  1930. // uint/index, bool/touch
  1931. const uint32_t index = fShmNonRtServerControl.readUInt();
  1932. const bool touch = fShmNonRtServerControl.readBool();
  1933. pData->engine->touchPluginParameter(pData->id, index, touch);
  1934. } break;
  1935. case kPluginBridgeNonRtServerDefaultValue: {
  1936. // uint/index, float/value
  1937. const uint32_t index = fShmNonRtServerControl.readUInt();
  1938. const float value = fShmNonRtServerControl.readFloat();
  1939. if (index < pData->param.count)
  1940. pData->param.ranges[index].def = value;
  1941. } break;
  1942. case kPluginBridgeNonRtServerCurrentProgram: {
  1943. // int/index
  1944. const int32_t index = fShmNonRtServerControl.readInt();
  1945. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1946. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->prog.count), index, pData->prog.count);
  1947. CarlaPlugin::setProgram(index, false, true, true);
  1948. } break;
  1949. case kPluginBridgeNonRtServerCurrentMidiProgram: {
  1950. // int/index
  1951. const int32_t index = fShmNonRtServerControl.readInt();
  1952. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1953. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->midiprog.count), index, pData->midiprog.count);
  1954. CarlaPlugin::setMidiProgram(index, false, true, true);
  1955. } break;
  1956. case kPluginBridgeNonRtServerProgramName: {
  1957. // uint/index, uint/size, str[] (name)
  1958. const uint32_t index = fShmNonRtServerControl.readUInt();
  1959. // name
  1960. const BridgeTextReader name(fShmNonRtServerControl);
  1961. CARLA_SAFE_ASSERT_INT2(index < pData->prog.count, index, pData->prog.count);
  1962. if (index < pData->prog.count)
  1963. {
  1964. if (pData->prog.names[index] != nullptr)
  1965. delete[] pData->prog.names[index];
  1966. pData->prog.names[index] = carla_strdup(name.text);
  1967. }
  1968. } break;
  1969. case kPluginBridgeNonRtServerMidiProgramData: {
  1970. // uint/index, uint/bank, uint/program, uint/size, str[] (name)
  1971. const uint32_t index = fShmNonRtServerControl.readUInt();
  1972. const uint32_t bank = fShmNonRtServerControl.readUInt();
  1973. const uint32_t program = fShmNonRtServerControl.readUInt();
  1974. // name
  1975. const BridgeTextReader name(fShmNonRtServerControl);
  1976. CARLA_SAFE_ASSERT_INT2(index < pData->midiprog.count, index, pData->midiprog.count);
  1977. if (index < pData->midiprog.count)
  1978. {
  1979. if (pData->midiprog.data[index].name != nullptr)
  1980. delete[] pData->midiprog.data[index].name;
  1981. pData->midiprog.data[index].bank = bank;
  1982. pData->midiprog.data[index].program = program;
  1983. pData->midiprog.data[index].name = carla_strdup(name.text);
  1984. }
  1985. } break;
  1986. case kPluginBridgeNonRtServerSetCustomData: {
  1987. // uint/size, str[], uint/size, str[], uint/size, str[]
  1988. // type
  1989. const BridgeTextReader type(fShmNonRtServerControl);
  1990. // key
  1991. const BridgeTextReader key(fShmNonRtServerControl);
  1992. // value
  1993. const uint32_t valueSize = fShmNonRtServerControl.readUInt();
  1994. // special case for big values
  1995. if (valueSize > 16384)
  1996. {
  1997. const BridgeTextReader bigValueFilePath(fShmNonRtServerControl);
  1998. String realBigValueFilePath(bigValueFilePath.text);
  1999. #ifndef CARLA_OS_WIN
  2000. // Using Wine, fix temp dir
  2001. if (fBinaryType == BINARY_WIN32 || fBinaryType == BINARY_WIN64)
  2002. {
  2003. const StringArray driveLetterSplit(StringArray::fromTokens(realBigValueFilePath, ":/", ""));
  2004. carla_stdout("big value save path BEFORE => %s", realBigValueFilePath.toRawUTF8());
  2005. realBigValueFilePath = fWinePrefix;
  2006. realBigValueFilePath += "/drive_";
  2007. realBigValueFilePath += driveLetterSplit[0].toLowerCase();
  2008. realBigValueFilePath += driveLetterSplit[1];
  2009. realBigValueFilePath = realBigValueFilePath.replace("\\", "/");
  2010. carla_stdout("big value save path AFTER => %s", realBigValueFilePath.toRawUTF8());
  2011. }
  2012. #endif
  2013. const File bigValueFile(realBigValueFilePath);
  2014. CARLA_SAFE_ASSERT_BREAK(bigValueFile.existsAsFile());
  2015. CarlaPlugin::setCustomData(type.text, key.text, bigValueFile.loadFileAsString().toRawUTF8(), false);
  2016. bigValueFile.deleteFile();
  2017. }
  2018. else
  2019. {
  2020. const BridgeTextReader value(fShmNonRtServerControl, valueSize);
  2021. CarlaPlugin::setCustomData(type.text, key.text, value.text, false);
  2022. }
  2023. } break;
  2024. case kPluginBridgeNonRtServerSetChunkDataFile: {
  2025. // uint/size, str[] (filename)
  2026. // chunkFilePath
  2027. const BridgeTextReader chunkFilePath(fShmNonRtServerControl);
  2028. String realChunkFilePath(chunkFilePath.text);
  2029. #ifndef CARLA_OS_WIN
  2030. // Using Wine, fix temp dir
  2031. if (fBinaryType == BINARY_WIN32 || fBinaryType == BINARY_WIN64)
  2032. {
  2033. const StringArray driveLetterSplit(StringArray::fromTokens(realChunkFilePath, ":/", ""));
  2034. carla_stdout("chunk save path BEFORE => %s", realChunkFilePath.toRawUTF8());
  2035. realChunkFilePath = fWinePrefix;
  2036. realChunkFilePath += "/drive_";
  2037. realChunkFilePath += driveLetterSplit[0].toLowerCase();
  2038. realChunkFilePath += driveLetterSplit[1];
  2039. realChunkFilePath = realChunkFilePath.replace("\\", "/");
  2040. carla_stdout("chunk save path AFTER => %s", realChunkFilePath.toRawUTF8());
  2041. }
  2042. #endif
  2043. const File chunkFile(realChunkFilePath);
  2044. CARLA_SAFE_ASSERT_BREAK(chunkFile.existsAsFile());
  2045. fInfo.chunk = carla_getChunkFromBase64String(chunkFile.loadFileAsString().toRawUTF8());
  2046. chunkFile.deleteFile();
  2047. } break;
  2048. case kPluginBridgeNonRtServerSetLatency:
  2049. // uint
  2050. fLatency = fShmNonRtServerControl.readUInt();
  2051. #ifndef BUILD_BRIDGE
  2052. if (! fInitiated)
  2053. pData->latency.recreateBuffers(std::max(fInfo.aIns, fInfo.aOuts), fLatency);
  2054. #endif
  2055. break;
  2056. case kPluginBridgeNonRtServerSetParameterText: {
  2057. const int32_t index = fShmNonRtServerControl.readInt();
  2058. const uint32_t textSize = fShmNonRtServerControl.readUInt();
  2059. const BridgeTextReader text(fShmNonRtServerControl, textSize);
  2060. fReceivingParamText.setReceivedData(index, text.text, textSize);
  2061. } break;
  2062. case kPluginBridgeNonRtServerReady:
  2063. fInitiated = true;
  2064. break;
  2065. case kPluginBridgeNonRtServerSaved:
  2066. fSaved = true;
  2067. break;
  2068. case kPluginBridgeNonRtServerRespEmbedUI:
  2069. fPendingEmbedCustomUI = fShmNonRtServerControl.readULong();
  2070. break;
  2071. case kPluginBridgeNonRtServerResizeEmbedUI: {
  2072. const uint width = fShmNonRtServerControl.readUInt();
  2073. const uint height = fShmNonRtServerControl.readUInt();
  2074. pData->engine->callback(true, true, ENGINE_CALLBACK_EMBED_UI_RESIZED, pData->id,
  2075. static_cast<int>(width), static_cast<int>(height),
  2076. 0, 0.0f, nullptr);
  2077. } break;
  2078. case kPluginBridgeNonRtServerUiClosed:
  2079. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2080. pData->transientTryCounter = 0;
  2081. #endif
  2082. pData->engine->callback(true, true, ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id,
  2083. 0, 0, 0, 0.0f, nullptr);
  2084. break;
  2085. case kPluginBridgeNonRtServerError: {
  2086. // error
  2087. const BridgeTextReader error(fShmNonRtServerControl);
  2088. if (fInitiated)
  2089. {
  2090. pData->engine->callback(true, true, ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0, 0.0f, error.text);
  2091. // just in case
  2092. pData->engine->setLastError(error.text);
  2093. fInitError = true;
  2094. }
  2095. else
  2096. {
  2097. pData->engine->setLastError(error.text);
  2098. fInitError = true;
  2099. fInitiated = true;
  2100. }
  2101. } break;
  2102. }
  2103. }
  2104. }
  2105. // -------------------------------------------------------------------
  2106. uintptr_t getUiBridgeProcessId() const noexcept override
  2107. {
  2108. return fBridgeThread.getProcessPID();
  2109. }
  2110. const void* getExtraStuff() const noexcept override
  2111. {
  2112. return fBridgeBinary.isNotEmpty() ? fBridgeBinary.buffer() : nullptr;
  2113. }
  2114. // -------------------------------------------------------------------
  2115. bool init(CarlaPluginPtr plugin,
  2116. const char* const filename,
  2117. const char* const name,
  2118. const char* const label,
  2119. const int64_t uniqueId,
  2120. const uint options,
  2121. const char* const binaryArchName,
  2122. const char* const bridgeBinary)
  2123. {
  2124. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  2125. // ---------------------------------------------------------------
  2126. // first checks
  2127. if (pData->client != nullptr)
  2128. {
  2129. pData->engine->setLastError("Plugin client is already registered");
  2130. return false;
  2131. }
  2132. if (bridgeBinary == nullptr || bridgeBinary[0] == '\0')
  2133. {
  2134. pData->engine->setLastError("null bridge binary");
  2135. return false;
  2136. }
  2137. // ---------------------------------------------------------------
  2138. // set info
  2139. if (name != nullptr && name[0] != '\0')
  2140. pData->name = pData->engine->getUniquePluginName(name);
  2141. if (filename != nullptr && filename[0] != '\0')
  2142. pData->filename = carla_strdup(filename);
  2143. else
  2144. pData->filename = carla_strdup("");
  2145. fUniqueId = uniqueId;
  2146. fBridgeBinary = bridgeBinary;
  2147. std::srand(static_cast<uint>(std::time(nullptr)));
  2148. // ---------------------------------------------------------------
  2149. // init sem/shm
  2150. if (! fShmAudioPool.initializeServer())
  2151. {
  2152. carla_stderr("Failed to initialize shared memory audio pool");
  2153. return false;
  2154. }
  2155. if (! fShmRtClientControl.initializeServer())
  2156. {
  2157. carla_stderr("Failed to initialize RT client control");
  2158. fShmAudioPool.clear();
  2159. return false;
  2160. }
  2161. if (! fShmNonRtClientControl.initializeServer())
  2162. {
  2163. carla_stderr("Failed to initialize Non-RT client control");
  2164. fShmRtClientControl.clear();
  2165. fShmAudioPool.clear();
  2166. return false;
  2167. }
  2168. if (! fShmNonRtServerControl.initializeServer())
  2169. {
  2170. carla_stderr("Failed to initialize Non-RT server control");
  2171. fShmNonRtClientControl.clear();
  2172. fShmRtClientControl.clear();
  2173. fShmAudioPool.clear();
  2174. return false;
  2175. }
  2176. #ifndef CARLA_OS_WIN
  2177. // ---------------------------------------------------------------
  2178. // set wine prefix
  2179. if (fBridgeBinary.contains(".exe", true))
  2180. {
  2181. const EngineOptions& engineOptions(pData->engine->getOptions());
  2182. if (engineOptions.wine.autoPrefix)
  2183. fWinePrefix = findWinePrefix(pData->filename);
  2184. if (fWinePrefix.isEmpty())
  2185. {
  2186. const char* const envWinePrefix(std::getenv("WINEPREFIX"));
  2187. if (envWinePrefix != nullptr && envWinePrefix[0] != '\0')
  2188. fWinePrefix = envWinePrefix;
  2189. else if (engineOptions.wine.fallbackPrefix != nullptr && engineOptions.wine.fallbackPrefix[0] != '\0')
  2190. fWinePrefix = engineOptions.wine.fallbackPrefix;
  2191. else
  2192. fWinePrefix = File::getSpecialLocation(File::userHomeDirectory).getFullPathName() + "/.wine";
  2193. }
  2194. }
  2195. #endif
  2196. // ---------------------------------------------------------------
  2197. // init bridge thread
  2198. {
  2199. char shmIdsStr[6*4+1];
  2200. carla_zeroChars(shmIdsStr, 6*4+1);
  2201. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  2202. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  2203. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  2204. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  2205. fBridgeThread.setData(
  2206. #ifndef CARLA_OS_WIN
  2207. fWinePrefix.toRawUTF8(),
  2208. #endif
  2209. binaryArchName, bridgeBinary, label, shmIdsStr);
  2210. }
  2211. if (! restartBridgeThread())
  2212. return false;
  2213. // ---------------------------------------------------------------
  2214. // register client
  2215. if (pData->name == nullptr)
  2216. {
  2217. if (label != nullptr && label[0] != '\0')
  2218. pData->name = pData->engine->getUniquePluginName(label);
  2219. else
  2220. pData->name = pData->engine->getUniquePluginName("unknown");
  2221. }
  2222. pData->client = pData->engine->addClient(plugin);
  2223. if (pData->client == nullptr || ! pData->client->isOk())
  2224. {
  2225. pData->engine->setLastError("Failed to register plugin client");
  2226. return false;
  2227. }
  2228. // ---------------------------------------------------------------
  2229. // set options
  2230. pData->options = 0x0;
  2231. if ((fInfo.optionsAvailable & PLUGIN_OPTION_FIXED_BUFFERS) == 0x0)
  2232. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2233. else if (isPluginOptionEnabled(options, PLUGIN_OPTION_FIXED_BUFFERS))
  2234. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2235. if (pData->engine->getOptions().forceStereo)
  2236. {
  2237. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2238. }
  2239. else if (fInfo.optionsAvailable & PLUGIN_OPTION_FORCE_STEREO)
  2240. {
  2241. if (options & PLUGIN_OPTION_FORCE_STEREO)
  2242. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2243. }
  2244. if (fInfo.optionsAvailable & PLUGIN_OPTION_USE_CHUNKS)
  2245. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2246. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2247. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_CONTROL_CHANGES)
  2248. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2249. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2250. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE)
  2251. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2252. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2253. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH)
  2254. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2255. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2256. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_PITCHBEND)
  2257. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2258. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2259. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2260. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2261. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2262. if (fInfo.optionsAvailable & PLUGIN_OPTION_SKIP_SENDING_NOTES)
  2263. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2264. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2265. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  2266. {
  2267. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2268. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2269. }
  2270. else if (fInfo.optionsAvailable & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  2271. {
  2272. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2273. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2274. }
  2275. // kPluginBridgeNonRtClientSetOptions was added in API 7
  2276. if (fBridgeVersion >= 7)
  2277. {
  2278. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  2279. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOptions);
  2280. fShmNonRtClientControl.writeUInt(pData->options);
  2281. fShmNonRtClientControl.commitWrite();
  2282. }
  2283. return true;
  2284. }
  2285. private:
  2286. const BinaryType fBinaryType;
  2287. const PluginType fPluginType;
  2288. uint fBridgeVersion;
  2289. bool fInitiated;
  2290. bool fInitError;
  2291. bool fSaved;
  2292. bool fTimedOut;
  2293. bool fTimedError;
  2294. uint fBufferSize;
  2295. uint fProcWaitTime;
  2296. uint64_t fPendingEmbedCustomUI;
  2297. CarlaString fBridgeBinary;
  2298. CarlaPluginBridgeThread fBridgeThread;
  2299. BridgeAudioPool fShmAudioPool;
  2300. BridgeRtClientControl fShmRtClientControl;
  2301. BridgeNonRtClientControl fShmNonRtClientControl;
  2302. BridgeNonRtServerControl fShmNonRtServerControl;
  2303. #ifndef CARLA_OS_WIN
  2304. String fWinePrefix;
  2305. #endif
  2306. class ReceivingParamText {
  2307. public:
  2308. ReceivingParamText() noexcept
  2309. : dataRecv(false),
  2310. dataOk(false),
  2311. index(-1),
  2312. strBuf(nullptr),
  2313. mutex() {}
  2314. bool isCurrentlyWaitingData() const noexcept
  2315. {
  2316. return index >= 0;
  2317. }
  2318. bool wasDataReceived(bool* const success) const noexcept
  2319. {
  2320. *success = dataOk;
  2321. return dataRecv;
  2322. }
  2323. void setTargetData(const int32_t i, char* const b) noexcept
  2324. {
  2325. const CarlaMutexLocker cml(mutex);
  2326. dataOk = false;
  2327. dataRecv = false;
  2328. index = i;
  2329. strBuf = b;
  2330. }
  2331. void setReceivedData(const int32_t i, const char* const b, const uint blen) noexcept
  2332. {
  2333. CarlaScopedValueSetter<bool> svs(dataRecv, false, true);
  2334. const CarlaMutexLocker cml(mutex);
  2335. // make backup and reset data
  2336. const int32_t indexCopy = index;
  2337. char* const strBufCopy = strBuf;
  2338. index = -1;
  2339. strBuf = nullptr;
  2340. CARLA_SAFE_ASSERT_RETURN(indexCopy == i,);
  2341. CARLA_SAFE_ASSERT_RETURN(strBufCopy != nullptr,);
  2342. std::strncpy(strBufCopy, b, std::min(blen, STR_MAX-1U));
  2343. dataOk = true;
  2344. }
  2345. private:
  2346. bool dataRecv;
  2347. bool dataOk;
  2348. int32_t index;
  2349. char* strBuf;
  2350. CarlaMutex mutex;
  2351. CARLA_DECLARE_NON_COPYABLE(ReceivingParamText)
  2352. } fReceivingParamText;
  2353. struct Info {
  2354. uint32_t aIns, aOuts;
  2355. uint32_t cvIns, cvOuts;
  2356. uint32_t mIns, mOuts;
  2357. PluginCategory category;
  2358. uint optionsAvailable;
  2359. CarlaString name;
  2360. CarlaString label;
  2361. CarlaString maker;
  2362. CarlaString copyright;
  2363. const char** aInNames;
  2364. const char** aOutNames;
  2365. const char** cvInNames;
  2366. const char** cvOutNames;
  2367. std::vector<uint8_t> chunk;
  2368. Info()
  2369. : aIns(0),
  2370. aOuts(0),
  2371. cvIns(0),
  2372. cvOuts(0),
  2373. mIns(0),
  2374. mOuts(0),
  2375. category(PLUGIN_CATEGORY_NONE),
  2376. optionsAvailable(0),
  2377. name(),
  2378. label(),
  2379. maker(),
  2380. copyright(),
  2381. aInNames(nullptr),
  2382. aOutNames(nullptr),
  2383. cvInNames(nullptr),
  2384. cvOutNames(nullptr),
  2385. chunk() {}
  2386. ~Info()
  2387. {
  2388. clear();
  2389. }
  2390. void clear()
  2391. {
  2392. if (aInNames != nullptr)
  2393. {
  2394. CARLA_SAFE_ASSERT_INT(aIns > 0, aIns);
  2395. for (uint32_t i=0; i<aIns; ++i)
  2396. delete[] aInNames[i];
  2397. delete[] aInNames;
  2398. aInNames = nullptr;
  2399. }
  2400. if (aOutNames != nullptr)
  2401. {
  2402. CARLA_SAFE_ASSERT_INT(aOuts > 0, aOuts);
  2403. for (uint32_t i=0; i<aOuts; ++i)
  2404. delete[] aOutNames[i];
  2405. delete[] aOutNames;
  2406. aOutNames = nullptr;
  2407. }
  2408. if (cvInNames != nullptr)
  2409. {
  2410. CARLA_SAFE_ASSERT_INT(cvIns > 0, cvIns);
  2411. for (uint32_t i=0; i<cvIns; ++i)
  2412. delete[] cvInNames[i];
  2413. delete[] cvInNames;
  2414. cvInNames = nullptr;
  2415. }
  2416. if (cvOutNames != nullptr)
  2417. {
  2418. CARLA_SAFE_ASSERT_INT(cvOuts > 0, cvOuts);
  2419. for (uint32_t i=0; i<cvOuts; ++i)
  2420. delete[] cvOutNames[i];
  2421. delete[] cvOutNames;
  2422. cvOutNames = nullptr;
  2423. }
  2424. aIns = aOuts = cvIns = cvOuts = 0;
  2425. }
  2426. CARLA_DECLARE_NON_COPYABLE(Info)
  2427. } fInfo;
  2428. int64_t fUniqueId;
  2429. uint32_t fLatency;
  2430. BridgeParamInfo* fParams;
  2431. void handleProcessStopped() noexcept
  2432. {
  2433. const bool wasActive = pData->active;
  2434. pData->active = false;
  2435. if (wasActive)
  2436. {
  2437. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2438. pData->engine->callback(true, true,
  2439. ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED,
  2440. pData->id,
  2441. PARAMETER_ACTIVE,
  2442. 0, 0,
  2443. 0.0f,
  2444. nullptr);
  2445. #endif
  2446. }
  2447. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  2448. {
  2449. pData->engine->callback(true, true,
  2450. ENGINE_CALLBACK_UI_STATE_CHANGED,
  2451. pData->id,
  2452. 0,
  2453. 0, 0, 0.0f, nullptr);
  2454. }
  2455. }
  2456. void resizeAudioPool(const uint32_t bufferSize)
  2457. {
  2458. fShmAudioPool.resize(bufferSize, fInfo.aIns+fInfo.aOuts, fInfo.cvIns+fInfo.cvOuts);
  2459. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  2460. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  2461. fShmRtClientControl.commitWrite();
  2462. waitForClient("resize-pool", 5000);
  2463. }
  2464. void waitForClient(const char* const action, const uint msecs)
  2465. {
  2466. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  2467. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  2468. if (fShmRtClientControl.waitForClient(msecs))
  2469. return;
  2470. fTimedOut = true;
  2471. carla_stderr2("waitForClient(%s) timed out", action);
  2472. }
  2473. bool restartBridgeThread()
  2474. {
  2475. fInitiated = false;
  2476. fInitError = false;
  2477. fTimedError = false;
  2478. // reset memory
  2479. fShmRtClientControl.data->procFlags = 0;
  2480. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  2481. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  2482. fShmRtClientControl.clearData();
  2483. fShmNonRtClientControl.clearData();
  2484. fShmNonRtServerControl.clearData();
  2485. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  2486. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT);
  2487. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  2488. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  2489. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  2490. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  2491. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  2492. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  2493. fShmNonRtClientControl.commitWrite();
  2494. if (fShmAudioPool.dataSize != 0)
  2495. {
  2496. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  2497. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  2498. fShmRtClientControl.commitWrite();
  2499. }
  2500. else
  2501. {
  2502. // testing dummy message
  2503. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  2504. fShmRtClientControl.commitWrite();
  2505. }
  2506. fBridgeThread.startThread();
  2507. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  2508. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2509. const bool needsCancelableAction = ! pData->engine->isLoadingProject();
  2510. if (needsCancelableAction)
  2511. {
  2512. pData->engine->setActionCanceled(false);
  2513. pData->engine->callback(true, true,
  2514. ENGINE_CALLBACK_CANCELABLE_ACTION,
  2515. pData->id,
  2516. 1,
  2517. 0, 0, 0.0f,
  2518. "Loading plugin bridge");
  2519. }
  2520. #endif
  2521. for (;fBridgeThread.isThreadRunning();)
  2522. {
  2523. pData->engine->callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2524. if (needsEngineIdle)
  2525. pData->engine->idle();
  2526. idle();
  2527. if (fInitiated)
  2528. break;
  2529. if (pData->engine->isAboutToClose() || pData->engine->wasActionCanceled())
  2530. break;
  2531. carla_msleep(5);
  2532. }
  2533. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2534. if (needsCancelableAction)
  2535. {
  2536. pData->engine->callback(true, true,
  2537. ENGINE_CALLBACK_CANCELABLE_ACTION,
  2538. pData->id,
  2539. 0,
  2540. 0, 0, 0.0f,
  2541. "Loading plugin bridge");
  2542. }
  2543. #endif
  2544. if (fInitError || ! fInitiated)
  2545. {
  2546. fBridgeThread.stopThread(6000);
  2547. if (! fInitError)
  2548. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  2549. "(or the plugin crashed on initialization?)");
  2550. return false;
  2551. }
  2552. if (const size_t dataSize = fInfo.chunk.size())
  2553. {
  2554. #ifdef CARLA_PROPER_CPP11_SUPPORT
  2555. void* data = fInfo.chunk.data();
  2556. #else
  2557. void* data = &fInfo.chunk.front();
  2558. #endif
  2559. CarlaString dataBase64(CarlaString::asBase64(data, dataSize));
  2560. CARLA_SAFE_ASSERT_RETURN(dataBase64.length() > 0, true);
  2561. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  2562. filePath += CARLA_OS_SEP_STR ".CarlaChunk_";
  2563. filePath += fShmAudioPool.getFilenameSuffix();
  2564. if (File(filePath).replaceWithText(dataBase64.buffer()))
  2565. {
  2566. const uint32_t ulength(static_cast<uint32_t>(filePath.length()));
  2567. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  2568. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetChunkDataFile);
  2569. fShmNonRtClientControl.writeUInt(ulength);
  2570. fShmNonRtClientControl.writeCustomData(filePath.toRawUTF8(), ulength);
  2571. fShmNonRtClientControl.commitWrite();
  2572. }
  2573. }
  2574. return true;
  2575. }
  2576. void _setUiTitleFromName()
  2577. {
  2578. CarlaString uiName(pData->name);
  2579. uiName += " (GUI)";
  2580. const uint32_t size = static_cast<uint32_t>(uiName.length());
  2581. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  2582. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetWindowTitle);
  2583. fShmNonRtClientControl.writeUInt(size);
  2584. fShmNonRtClientControl.writeCustomData(uiName.buffer(), size);
  2585. fShmNonRtClientControl.commitWrite();
  2586. }
  2587. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginBridge)
  2588. };
  2589. CARLA_BACKEND_END_NAMESPACE
  2590. // ---------------------------------------------------------------------------------------------------------------------
  2591. CARLA_BACKEND_START_NAMESPACE
  2592. CarlaPluginPtr CarlaPlugin::newBridge(const Initializer& init,
  2593. const BinaryType btype,
  2594. const PluginType ptype,
  2595. const char* const binaryArchName,
  2596. const char* bridgeBinary)
  2597. {
  2598. carla_debug("CarlaPlugin::newBridge({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\", \"%s\")",
  2599. init.engine, init.filename, init.name, init.label,
  2600. BinaryType2Str(btype), PluginType2Str(ptype), binaryArchName, bridgeBinary);
  2601. if (bridgeBinary == nullptr || bridgeBinary[0] == '\0')
  2602. {
  2603. init.engine->setLastError("Bridge not possible, bridge-binary not found");
  2604. return nullptr;
  2605. }
  2606. #ifndef CARLA_OS_WIN
  2607. // FIXME: somewhere, somehow, we end up with double slashes, wine doesn't like that.
  2608. if (std::strncmp(bridgeBinary, "//", 2) == 0)
  2609. ++bridgeBinary;
  2610. #endif
  2611. std::shared_ptr<CarlaPluginBridge> plugin(new CarlaPluginBridge(init.engine, init.id, btype, ptype));
  2612. if (! plugin->init(plugin, init.filename, init.name, init.label, init.uniqueId, init.options, binaryArchName, bridgeBinary))
  2613. return nullptr;
  2614. return plugin;
  2615. }
  2616. CARLA_BACKEND_END_NAMESPACE
  2617. // ---------------------------------------------------------------------------------------------------------------------
  2618. #ifndef BUILD_BRIDGE
  2619. # include "CarlaBridgeUtils.cpp"
  2620. #endif
  2621. // ---------------------------------------------------------------------------------------------------------------------