Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CarlaPluginBridge.cpp 110KB

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