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

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