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

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