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

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