AudioEngine.cpp 272 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252
  1. #include "engine/AudioEngine.h"
  2. #include "core/VideoPlayer.h"
  3. #include "core/Comping.h"
  4. #include "core/EdisonFx.h"
  5. #include "core/FlSettings.h"
  6. #include "core/LiveSession.h"
  7. #include "core/SessionIds.h"
  8. #include "core/StandIns.h"
  9. #include "engine/SessionPack.h"
  10. #include "core/ClipOps.h"
  11. #include "core/MarkerPlan.h"
  12. #include "engine/AudioLogger.h"
  13. #include "core/HardwareInsert.h"
  14. #include "core/Patcher.h"
  15. #include "core/ValueMath.h"
  16. #include "platform/Paths.h"
  17. #include "engine/FlStudio.h"
  18. #include <limits>
  19. #include <map>
  20. #include <thread>
  21. #include "engine/Text.h"
  22. #include "ui/I18n.h"
  23. #include "core/FlpImport.h"
  24. #include "core/AlsImport.h"
  25. #include "core/FlmImport.h"
  26. #include "core/LoadTrace.h"
  27. #include "core/Instruments.h"
  28. #include "core/Denormals.h"
  29. #include "core/Dither.h"
  30. #include "core/ProjectSafety.h"
  31. #include "core/SoftClip.h"
  32. #include "core/Scheduler.h"
  33. #include "engine/ChannelRackProcessor.h"
  34. #include "engine/DllAsioDevice.h"
  35. #include "engine/PipeWireDevice.h"
  36. #include "platform/LinuxRealtime.h"
  37. #include "engine/Metronome.h"
  38. #include "core/NoteTools.h"
  39. #include "core/VfxScript.h"
  40. #include "core/SamplePrecompute.h"
  41. #include "engine/PreviewPlayer.h"
  42. #include "engine/PluginSandbox.h"
  43. #include "core/PluginPresets.h"
  44. #include "flp/Flp.h"
  45. #if JUCE_WINDOWS
  46. #include <windows.h>
  47. #elif JUCE_MAC
  48. #include <pthread.h>
  49. #include <sys/qos.h>
  50. #elif JUCE_LINUX || JUCE_BSD
  51. #include <pthread.h>
  52. #include <sched.h>
  53. #endif
  54. namespace lynx
  55. {
  56. using IONode = juce::AudioProcessorGraph::AudioGraphIOProcessor;
  57. // The FL Studio installation (registry, else the usual folders) to resolve %FLStudio...%.
  58. FlPathRoots findFlStudioRoots()
  59. {
  60. FlPathRoots roots;
  61. const auto fl = findFlStudio();
  62. if (fl.installDir.isDirectory())
  63. {
  64. roots.factoryData = fl.installDir.getFullPathName().toStdString();
  65. roots.data = fl.installDir.getChildFile ("Data").getFullPathName().toStdString();
  66. }
  67. if (fl.userData.isDirectory())
  68. roots.userData = fl.userData.getFullPathName().toStdString();
  69. // FL's Shared data folder and its Downloads (issue #124: FL Cloud sounds and other samples kept there)
  70. if (fl.sharedData.isDirectory())
  71. {
  72. roots.sharedData = fl.sharedData.getFullPathName().toStdString();
  73. roots.downloadsData = fl.sharedData.getChildFile ("Downloads").getFullPathName().toStdString();
  74. }
  75. roots.home = juce::File::getSpecialLocation (juce::File::userHomeDirectory).getFullPathName().toStdString();
  76. return roots;
  77. }
  78. const natives::FlAccess& flStudioAccess()
  79. {
  80. static const natives::FlAccess cached = [] {
  81. natives::FlAccess access;
  82. access.roots = findFlStudioRoots();
  83. access.fileExists = [] (const std::string& path) { return platform::localFile (path).existsAsFile(); };
  84. access.readFile = [] (const std::string& path) {
  85. juce::MemoryBlock data;
  86. platform::localFile (path).loadFileAsData (data);
  87. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  88. return std::vector<std::uint8_t> (bytes, bytes + data.getSize());
  89. };
  90. access.listPresets = [] (const std::string& folder) {
  91. std::vector<std::string> out;
  92. auto files = platform::localFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst;*.tbio;*.gmsynth;*.mrp");
  93. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) {
  94. return a.getFullPathName().compareNatural (b.getFullPathName()) < 0;
  95. });
  96. for (const auto& f : files)
  97. out.push_back (f.getFullPathName().toStdString());
  98. return out;
  99. };
  100. // (FL Keys' raw wavetables become WAV files of LYNX's settings folder, like an .flp's embedded samples)
  101. access.saveEmbedded = [] (const std::vector<std::uint8_t>& wav, const std::string& name) -> std::string {
  102. const auto folder = PluginHost::settingsFolder().getChildFile ("flp-embedded");
  103. folder.createDirectory();
  104. const auto hash = juce::String::toHexString ((juce::int64) juce::DefaultHashFunctions::generateHash (
  105. juce::String::createStringFromData (wav.data(), (int) std::min<std::size_t> (wav.size(), 65536)) + juce::String ((juce::int64) wav.size()),
  106. 0x7FFFFFFF));
  107. const auto file = folder.getChildFile (juce::File::createLegalFileName (juce::String::fromUTF8 (name.c_str())) + "-" + hash + ".wav");
  108. if (! file.existsAsFile() && ! file.replaceWithData (wav.data(), wav.size()))
  109. return {};
  110. return file.getFullPathName().toStdString();
  111. };
  112. return access;
  113. }();
  114. return cached;
  115. }
  116. namespace
  117. {
  118. // Audio workers with real-time priority (MMCSS "Pro Audio" on Windows, like the driver; QoS class on macOS; SCHED_FIFO
  119. // on Linux when allowed).
  120. void raiseAudioThreadPriority()
  121. {
  122. #if JUCE_WINDOWS
  123. using AvSet = void* (__stdcall*) (const wchar_t*, unsigned long*);
  124. static const auto avSet = [] () -> AvSet {
  125. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  126. return reinterpret_cast<AvSet> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadCharacteristicsW")));
  127. return nullptr;
  128. }();
  129. // FL's audio worker threads also raise their MMCSS priority to "high" (FLEngine_x64.dll, REA round 87)
  130. using AvPriority = int (__stdcall*) (void*, int);
  131. static const auto avPriority = [] () -> AvPriority {
  132. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  133. return reinterpret_cast<AvPriority> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadPriority")));
  134. return nullptr;
  135. }();
  136. unsigned long task = 0;
  137. if (auto* handle = avSet != nullptr ? avSet (L"Pro Audio", &task) : nullptr)
  138. {
  139. if (avPriority != nullptr)
  140. avPriority (handle, 1 /* AVRT_PRIORITY_HIGH */);
  141. }
  142. else
  143. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  144. #elif JUCE_MAC
  145. // the highest quality-of-service class: scheduled like the UI's own interactive work, on the performance cores
  146. pthread_set_qos_class_self_np (QOS_CLASS_USER_INTERACTIVE, 0);
  147. #elif JUCE_LINUX || JUCE_BSD
  148. // real-time FIFO scheduling when the user may have it (audio group / rtkit limits, as JACK and PipeWire set up);
  149. // below the usual JACK/PipeWire audio thread priorities. Without the permission the thread stays as it is.
  150. sched_param param {};
  151. param.sched_priority = juce::jlimit (sched_get_priority_min (SCHED_FIFO), sched_get_priority_max (SCHED_FIFO), 70);
  152. if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &param) != 0)
  153. rt::noteAudioThread (false); // RealtimeKit / the portal may grant it (round 161)
  154. #endif
  155. }
  156. int workerCount()
  157. {
  158. // diagnostics: LYNX_WORKERS=n fixes the number of extra threads
  159. if (const auto forced = juce::SystemStats::getEnvironmentVariable ("LYNX_WORKERS", {}); forced.isNotEmpty())
  160. return juce::jlimit (0, 31, forced.getIntValue());
  161. // the audio thread works too; leave one core free for the UI
  162. const auto cores = (int) std::thread::hardware_concurrency();
  163. return juce::jlimit (0, 7, cores - 2);
  164. }
  165. juce::File midiSettingsFile() { return PluginHost::settingsFolder().getChildFile ("midi-settings.txt"); }
  166. juce::File audioDeviceFile() { return PluginHost::settingsFolder().getChildFile ("audio-device.xml"); }
  167. } // namespace
  168. // Saves the audio device setup whenever it changes (Settings › Audio, the setup wizard, a driver's own panel), so
  169. // the next start opens the same device.
  170. struct AudioEngine::DeviceStateSaver final : public juce::ChangeListener
  171. {
  172. explicit DeviceStateSaver (AudioEngine& e) : engine (e) { engine.deviceManager.addChangeListener (this); }
  173. ~DeviceStateSaver() override { engine.deviceManager.removeChangeListener (this); }
  174. void changeListenerCallback (juce::ChangeBroadcaster*) override { engine.saveAudioDeviceState(); }
  175. AudioEngine& engine;
  176. };
  177. // written by fileJobs: the write ends with FlushFileBuffers on Windows, which took 2 s on a busy disk and froze the UI
  178. // after every device change (issue #13). In order, so the newest setup is the one left on disk.
  179. void AudioEngine::saveAudioDeviceState()
  180. {
  181. if (auto xml = deviceManager.createStateXml())
  182. fileJobs.post ([text = xml->toString(), file = audioDeviceFile()] { file.replaceWithText (text); });
  183. }
  184. void AudioEngine::restoreAudioDeviceState (const juce::XmlElement* state)
  185. {
  186. deviceStateSaver = nullptr;
  187. fileJobs.post ([text = state != nullptr ? state->toString() : juce::String(), restore = state != nullptr, file = audioDeviceFile()] {
  188. if (restore)
  189. file.replaceWithText (text);
  190. else
  191. file.deleteFile();
  192. });
  193. fileJobs.waitIdle(); // (after the saves still queued, and done when this returns)
  194. }
  195. namespace
  196. {
  197. AudioEngine::RecordingSettings loadRecordingSettings();
  198. }
  199. struct AudioEngine::Drainer final : juce::TimeSliceClient
  200. {
  201. explicit Drainer (AudioEngine& e) : engine (e) {}
  202. int useTimeSlice() override
  203. {
  204. std::vector<std::shared_ptr<Take>> list;
  205. {
  206. const juce::ScopedLock lock (engine.drainLock);
  207. list = engine.draining;
  208. }
  209. for (auto& take : list)
  210. {
  211. const juce::ScopedLock lock (take->drainMutex);
  212. take->drain();
  213. }
  214. return list.empty() ? 50 : 5;
  215. }
  216. AudioEngine& engine;
  217. };
  218. namespace
  219. {
  220. // the engine whose project the plugin hold is for (round 190ap): the hold ends when that engine opens another project
  221. std::atomic<const AudioEngine*> pluginHoldOwner { nullptr };
  222. } // namespace
  223. AudioEngine::AudioEngine (bool openAudioDevice, int workerThreads, bool userPluginList)
  224. : workers (std::make_unique<WorkerPool> (workerThreads >= 0 ? workerThreads : workerCount(), raiseAudioThreadPriority)),
  225. plugins (userPluginList),
  226. song (Song::makeDefault())
  227. {
  228. boostDeviceThread = juce::SystemStats::getEnvironmentVariable ("LYNX_DEVICE_BOOST", {}) != "0";
  229. inputSlot.fill (-1);
  230. outputSlot.fill (-1);
  231. // VFX Script (round 165d): the audio thread waits a bounded time for the Python thread (exports wait for it)
  232. vfx::script::setRealtime (openAudioDevice);
  233. const auto mark = [] (const char* step) { if (startupMark != nullptr) startupMark (step); };
  234. mark (" engine: workers + default song");
  235. if (juce::JUCEApplicationBase::getInstance() != nullptr) // issue #36: retired racks are freed from their own message
  236. rackExchange.dispose = [this] (const RackState* rack) { rackDisposer.add (rack); };
  237. publishSong();
  238. buildInitialGraph();
  239. mark (" engine: graph");
  240. if (openAudioDevice)
  241. {
  242. player.setProcessor (&graph);
  243. // LYNX ASIO without installation: lynx-asio.dll next to LYNX.exe, when it is not registered (REA round 106)
  244. if (auto lynxAsio = makeBuiltInLynxAsioType())
  245. {
  246. deviceManager.getAvailableDeviceTypes(); // the standard types first
  247. deviceManager.addAudioDeviceType (std::move (lynxAsio));
  248. }
  249. // LYNX's own PipeWire client on Linux (round 161), listed when a PipeWire daemon answers
  250. if (auto pipeWire = makePipeWireDeviceType())
  251. {
  252. deviceManager.getAvailableDeviceTypes();
  253. deviceManager.addAudioDeviceType (std::move (pipeWire));
  254. }
  255. mark (" engine: device types");
  256. // 0 inputs, 2 outputs; the device of the last session (Settings › Audio) if it is still there, else the default.
  257. const auto saved = juce::XmlDocument::parse (audioDeviceFile());
  258. auto fresh = saved == nullptr;
  259. if (deviceManager.initialise (0, 2, saved.get(), true).isNotEmpty() && saved != nullptr)
  260. {
  261. deviceManager.initialise (0, 2, nullptr, true);
  262. fresh = true;
  263. }
  264. if (fresh)
  265. {
  266. choosePreferredDriver(); // Linux: PipeWire, then JACK, then ALSA
  267. chooseSafeBufferSize(); // no saved setup: a buffer with room for heavy projects (Settings › Audio changes it)
  268. }
  269. mark (" engine: device opened");
  270. deviceManager.addAudioCallback (this);
  271. if (rackProcessor != nullptr)
  272. rackProcessor->getRenderer().setProfiling (true); // per-unit CPU for the CPU meter and the glitch log
  273. deviceStateSaver = std::make_unique<DeviceStateSaver> (*this);
  274. midiPrefs = midiPrefsShared = prefs::MidiPrefs::fromText (midiSettingsFile().loadFileAsString().toStdString());
  275. performanceMidiChannel.store (midiPrefs.performanceChannel);
  276. controllerIo.loadProfiles (controllerProfilesFolder());
  277. recordingSettings = loadRecordingSettings();
  278. saveGlobalLinks = true;
  279. mark (" engine: callback + settings");
  280. prefetcher = std::make_unique<StreamPrefetcher> (transport);
  281. prefetcher->update (song, samples);
  282. enableAllMidiInputs();
  283. midiSync.configure (midiPrefs);
  284. midiSync.sendAllNotesOff(); // FL's "Send all notes off": on init and after a render
  285. deviceManager.addMidiInputDeviceCallback ({}, this); // {} = all inputs enabled
  286. midiDevicesChanged = juce::MidiDeviceListConnection::make ([this] { enableAllMidiInputs(); });
  287. mark (" engine: MIDI inputs");
  288. }
  289. startTimerHz (30); // recording and collection of retired snapshots
  290. }
  291. AudioLogger& AudioEngine::getAudioLogger()
  292. {
  293. if (audioLogger == nullptr)
  294. audioLogger = std::make_unique<AudioLogger> (meters.logTap);
  295. return *audioLogger;
  296. }
  297. AudioEngine::~AudioEngine()
  298. {
  299. if (pluginHoldOwner.load() == this) // (round 190ap: the hold goes with its project's engine)
  300. {
  301. pluginHoldOwner.store (nullptr);
  302. endPluginHold();
  303. }
  304. previewAlive->store (false); // (round 190aq: a preview still being prepared ends without touching the engine)
  305. previewJobs.stop();
  306. stopTimer();
  307. rackExchange.dispose = nullptr; // (from here the racks are freed at once)
  308. rackDisposer.flush();
  309. audioLogger.reset(); // closes the log file
  310. // the takes in progress are closed as they are (complete WAVs); their journals stay, so the next start offers to
  311. // put them on the Playlist (round 163)
  312. {
  313. const juce::SpinLock::ScopedLockType lock (takeLock);
  314. takes.fill (nullptr);
  315. takeCount = 0;
  316. }
  317. {
  318. const juce::ScopedLock lock (drainLock);
  319. draining.clear();
  320. }
  321. if (drainer != nullptr)
  322. recordThread.removeTimeSliceClient (drainer.get());
  323. for (auto& take : openTakes)
  324. {
  325. take->stream->finish();
  326. const juce::ScopedLock lock (take->drainMutex);
  327. take->drain();
  328. take->writer.close();
  329. }
  330. openTakes.clear();
  331. recordThread.stopThread (2000);
  332. prefetcher = nullptr;
  333. midiDevicesChanged = {};
  334. deviceStateSaver = nullptr;
  335. deviceManager.removeMidiInputDeviceCallback ({}, this);
  336. deviceManager.removeAudioCallback (this);
  337. player.setProcessor (nullptr);
  338. graph.clear(); // the nodes reference rackExchange and transport
  339. }
  340. void AudioEngine::buildInitialGraph()
  341. {
  342. // The output node inherits the graph's channel count at the moment it is created.
  343. // Without this the graph still has 0 outputs and JUCE silently rejects the connections.
  344. graph.setPlayConfigDetails (0, 2, transport.sampleRate.load(), 512);
  345. auto output = graph.addNode (std::make_unique<IONode> (IONode::audioOutputNode));
  346. auto rack = graph.addNode (std::make_unique<ChannelRackProcessor> (transport, rackExchange, liveEvents, midiEvents, meters, workers.get()));
  347. rackProcessor = dynamic_cast<ChannelRackProcessor*> (rack->getProcessor());
  348. if (rackProcessor != nullptr)
  349. {
  350. rackProcessor->setLiveInput (&liveInput);
  351. rackProcessor->setHardwareOutput (&hwOutput);
  352. rackProcessor->setPerformance (performanceLive.get());
  353. // FL's own metronome sounds from its install (Data\System), LYNX's stand-ins without it (round 165z-a2)
  354. const auto& flData = flStudioAccess().roots.data;
  355. rackProcessor->setMetronome (std::make_unique<Metronome> (transport, flData.empty() ? juce::File() : platform::localFile (flData)));
  356. }
  357. auto previewOwned = std::make_unique<PreviewPlayer>();
  358. preview = previewOwned.get();
  359. preview->setTransport (&transport); // (round 190aq: "Preview in time" starts on its beats)
  360. preview->setVolume (controls::previewGain (previewVolume));
  361. preview->setEditorVolume (controls::previewGain (editorVolume));
  362. auto previewNode = graph.addNode (std::move (previewOwned));
  363. for (int channel = 0; channel < 2; ++channel)
  364. {
  365. graph.addConnection ({ { rack->nodeID, channel }, { output->nodeID, channel } });
  366. graph.addConnection ({ { previewNode->nodeID, channel }, { output->nodeID, channel } });
  367. }
  368. jassert (graph.getConnections().size() == 4);
  369. }
  370. std::atomic<int>& AudioEngine::offlineRendersRunning() noexcept
  371. {
  372. static std::atomic<int> count { 0 };
  373. return count;
  374. }
  375. float AudioEngine::renderOffline (const RenderOptions& options)
  376. {
  377. offlineRendersRunning().fetch_add (1, std::memory_order_acq_rel);
  378. const juce::ScopeGuard rendered { [] { offlineRendersRunning().fetch_sub (1, std::memory_order_acq_rel); } };
  379. const auto seconds = options.seconds;
  380. const auto sampleRate = options.sampleRate;
  381. auto* output = options.output;
  382. const auto& progress = options.progress;
  383. const auto tailSeconds = options.tailSeconds;
  384. const auto trimSamples = options.trimSamples;
  385. std::optional<Dither> dither;
  386. if (options.ditherBits > 0)
  387. dither.emplace (options.ditherBits, options.ditherShaping);
  388. constexpr int blockSize = 512;
  389. constexpr float silence = 3.0e-5f; // ~ -90 dB
  390. // "HQ for all plugins" (REA round 134): engines with FL render-quality settings use them (Sytrus) and HQ switches
  391. // are forced on; without it the export keeps the playback quality
  392. setOfflineRendering (options.hqAllPlugins);
  393. setRenderInProgress (true); // (whatever the quality: LYNX Soundfont waits for a font that is still loading, issue #138)
  394. setHqForAllPlugins (options.hqAllPlugins);
  395. setPluginsRenderMode (true); // and hosted plugins are told an export is running (FL: "notify about rendering mode")
  396. transport.sampleRate.store (sampleRate);
  397. // round 164c: JUCE's graph builds its render sequence on the message thread. Prepared from the Export window's
  398. // thread it rebuilt later (asynchronously) and rendered silence until then: the first ~0.05–2 s of the song were
  399. // lost (the transport kept moving). It is prepared on the message thread, and the render waits for that.
  400. {
  401. auto prepareGraph = [this, sampleRate] {
  402. graph.setPlayConfigDetails (0, 2, sampleRate, blockSize);
  403. graph.prepareToPlay (sampleRate, blockSize);
  404. };
  405. auto* mm = juce::MessageManager::getInstanceWithoutCreating();
  406. if (mm == nullptr || mm->isThisTheMessageThread())
  407. prepareGraph();
  408. else
  409. {
  410. struct Handshake
  411. {
  412. juce::WaitableEvent done;
  413. std::atomic<bool> abandoned { false };
  414. };
  415. auto handshake = std::make_shared<Handshake>();
  416. juce::MessageManager::callAsync ([prepareGraph, handshake] {
  417. if (handshake->abandoned.load())
  418. return;
  419. prepareGraph();
  420. handshake->done.signal();
  421. });
  422. if (! handshake->done.wait (10000)) // (a message thread that is blocked: as before)
  423. {
  424. handshake->abandoned = true;
  425. prepareGraph();
  426. }
  427. }
  428. }
  429. if (rackProcessor != nullptr)
  430. {
  431. rackProcessor->setMetering (false); // nobody looks at the meters during the render
  432. rackProcessor->setMetronomeAllowed (options.includeMetronome);
  433. }
  434. lastRenderStats = {};
  435. // FL's init list first (play() would do it at the first block), so the plugins settle on those values too
  436. resetToInitialValues();
  437. int latency = getLatencySamples();
  438. if (options.pluginWarmUp)
  439. lastRenderStats.warmUp = warmUpPlugins (options.warmUp, sampleRate, blockSize, progress, latency);
  440. play();
  441. juce::AudioBuffer<float> buffer (2, blockSize);
  442. juce::MidiBuffer midi;
  443. float peak = 0.0f;
  444. // PDC trim with the latency the plugins report once they have settled
  445. const auto trim = (std::int64_t) juce::jmax (0, trimSamples + (options.trimPdc ? latency : 0));
  446. lastRenderStats.trimmedSamples = (int) trim;
  447. const auto musicSamples = (std::int64_t) (seconds * sampleRate) + trim;
  448. const auto totalSamples = musicSamples + (std::int64_t) (juce::jmax (0.0, tailSeconds) * sampleRate);
  449. std::int64_t quietSamples = 0;
  450. bool cancelled = lastRenderStats.warmUp.cancelled;
  451. vfx::script::setSongEnded (false);
  452. for (std::int64_t done = 0; done < totalSamples && ! cancelled; done += blockSize)
  453. {
  454. const auto n = (int) juce::jmin<std::int64_t> (blockSize, totalSamples - done);
  455. // the tail: the song has ended (VFX Script sees the transport stopped, like FL's render; round 167e)
  456. if (done >= musicSamples)
  457. vfx::script::setSongEnded (true);
  458. juce::AudioBuffer<float> view (buffer.getArrayOfWritePointers(), 2, n);
  459. view.clear();
  460. const auto before = juce::Time::getMillisecondCounterHiRes();
  461. graph.processBlock (view, midi);
  462. const auto afterGraph = juce::Time::getMillisecondCounterHiRes();
  463. lastRenderStats.graphMs += afterGraph - before;
  464. if (! options.keepOvers) // float WAV and the buffered export (normalize) keep what goes above 0 dBFS, like FL
  465. for (int ch = 0; ch < view.getNumChannels(); ++ch)
  466. clipOvers (view.getWritePointer (ch), n);
  467. const auto blockPeak = view.getMagnitude (0, n);
  468. peak = juce::jmax (peak, blockPeak);
  469. if (dither)
  470. for (int ch = 0; ch < view.getNumChannels(); ++ch)
  471. dither->process (view.getWritePointer (ch), n, ch);
  472. // PDC: the start is the latency's silence; the song's end arrives `trim` samples later
  473. if ((output != nullptr || options.capture) && done + n > trim)
  474. {
  475. const auto skip = (int) juce::jmax<std::int64_t> (0, trim - done);
  476. const auto beforeWrite = juce::Time::getMillisecondCounterHiRes();
  477. if (output != nullptr)
  478. output->writeFromAudioSampleBuffer (view, skip, n - skip);
  479. if (options.capture)
  480. options.capture (view.getReadPointer (0, skip), view.getReadPointer (1, skip), n - skip);
  481. lastRenderStats.writeMs += juce::Time::getMillisecondCounterHiRes() - beforeWrite;
  482. }
  483. transport.positionTicks.store (transport.positionTicks.load() + n * transport.ticksPerSample());
  484. // in the tail: half a second of silence ends it
  485. if (done + n > musicSamples)
  486. {
  487. quietSamples = blockPeak < silence ? quietSamples + n : 0;
  488. if (quietSamples > (std::int64_t) (sampleRate * 0.5))
  489. break;
  490. }
  491. if (progress && (done / blockSize) % 32 == 0 && ! progress ((double) done / (double) juce::jmax<std::int64_t> (1, totalSamples)))
  492. {
  493. cancelled = true;
  494. break;
  495. }
  496. }
  497. stop();
  498. vfx::script::setSongEnded (false);
  499. if (rackProcessor != nullptr)
  500. {
  501. rackProcessor->setMetering (true);
  502. rackProcessor->setMetronomeAllowed (true);
  503. }
  504. graph.releaseResources();
  505. setPluginsRenderMode (false);
  506. setOfflineRendering (false);
  507. setRenderInProgress (false);
  508. setHqForAllPlugins (false);
  509. return cancelled ? -1.0f : peak;
  510. }
  511. warmup::Result AudioEngine::warmUpPlugins (const warmup::Settings& settings, double sampleRate, int blockSize,
  512. const std::function<bool (double)>& progress, int& latency)
  513. {
  514. // the hosted plugins, collected once: the timer may republish the song meanwhile (the instances stay the same)
  515. std::vector<juce::AudioPluginInstance*> hosted;
  516. forEachHostedPlugin ([&hosted] (juce::AudioPluginInstance& p, bool) { hosted.push_back (&p); });
  517. if (hosted.empty())
  518. return {}; // LYNX's own engines are ready as soon as they are created: nothing to wait for
  519. // keeps the units alive whatever the timer publishes during the warm-up
  520. std::vector<std::shared_ptr<Instrument>> keepInstruments;
  521. std::vector<std::shared_ptr<Effect>> keepEffects;
  522. for (std::size_t i = 0; i < song.channels.size(); ++i)
  523. keepInstruments.push_back (getChannelInstrument ((int) i));
  524. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  525. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  526. keepEffects.push_back (getEffect ((int) t, (int) s));
  527. juce::AudioBuffer<float> buffer (2, blockSize);
  528. juce::MidiBuffer midi;
  529. int blocks = 0;
  530. // transport stopped at the start position: no note plays, and the automation / pattern events at that position
  531. // reach the plugins (the rack evaluates them every block), so they settle on the values the song starts with
  532. const auto result = warmup::run (
  533. settings, sampleRate,
  534. [&]() -> int {
  535. if (progress && ++blocks % 32 == 0 && ! progress (0.0))
  536. return -1;
  537. buffer.clear();
  538. midi.clear();
  539. graph.processBlock (buffer, midi);
  540. return blockSize;
  541. },
  542. [&hosted] {
  543. warmup::Hash h;
  544. for (auto* p : hosted)
  545. {
  546. h.add ((std::uint64_t) (std::int64_t) p->getLatencySamples());
  547. for (auto* param : p->getParameters())
  548. h.addValue (param->getValue());
  549. }
  550. return h.value;
  551. },
  552. [] { return juce::Time::getMillisecondCounterHiRes() * 0.001; },
  553. [] (double s) { juce::Thread::sleep (juce::jlimit (1, 20, (int) std::lround (s * 1000.0))); });
  554. // a latency that changed (reported late) gets its PDC plan before the render, on the message thread as the
  555. // timer does it (renders from the Export window run on a thread of their own)
  556. auto republish = [this] {
  557. if (lastPublishedShape.currentLatencies() != lastPublishedShape.latencies)
  558. {
  559. ++latencyRepublishes;
  560. publishSong();
  561. }
  562. return getLatencySamples();
  563. };
  564. auto* mm = juce::MessageManager::getInstanceWithoutCreating();
  565. if (mm == nullptr || mm->isThisTheMessageThread())
  566. latency = republish();
  567. else
  568. {
  569. struct Reply
  570. {
  571. juce::WaitableEvent done;
  572. std::atomic<int> latency { 0 };
  573. };
  574. auto reply = std::make_shared<Reply>();
  575. reply->latency = getLatencySamples();
  576. juce::MessageManager::callAsync ([this, reply, republish] {
  577. reply->latency = republish();
  578. reply->done.signal();
  579. });
  580. reply->done.wait (3000);
  581. latency = reply->latency.load();
  582. }
  583. // LYNX's own units start the render from a clean state, as without the warm-up (free-running LFOs, the delay
  584. // compensation's lines); the hosted plugins are not reset: they keep what they settled on (a reset re-activates
  585. // them, which is what they had to settle from)
  586. if (rackProcessor != nullptr)
  587. rackProcessor->prepareToPlay (sampleRate, blockSize);
  588. return result;
  589. }
  590. void AudioEngine::forEachHostedPlugin (const std::function<void (juce::AudioPluginInstance&, bool notifyRender)>& visit) const
  591. {
  592. for (std::size_t i = 0; i < song.channels.size(); ++i)
  593. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()); p != nullptr && ! p->hasCrashed())
  594. visit (p->getInstance(), song.channels[i].plugin.notifyRender);
  595. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  596. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  597. if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()); p != nullptr && ! p->hasCrashed())
  598. visit (p->getInstance(), song.mixer[t].effects[s].plugin.notifyRender);
  599. std::function<void (patcher::Graph*)> inGraph = [&] (patcher::Graph* graph) {
  600. if (graph == nullptr)
  601. return;
  602. for (int n = 0; n < graph->nodeCount(); ++n)
  603. {
  604. auto effect = graph->effectAt (n);
  605. auto instrument = graph->instrumentAt (n);
  606. if (auto* p = dynamic_cast<PluginEffect*> (effect.get()); p != nullptr && ! p->hasCrashed())
  607. visit (p->getInstance(), true);
  608. if (auto* p = dynamic_cast<PluginInstrument*> (instrument.get()); p != nullptr && ! p->hasCrashed())
  609. visit (p->getInstance(), true);
  610. inGraph (patcher::graphOf (effect.get()));
  611. inGraph (patcher::graphOf (instrument.get()));
  612. }
  613. };
  614. for (std::size_t i = 0; i < song.channels.size(); ++i)
  615. inGraph (patcher::graphOf (getChannelInstrument ((int) i).get()));
  616. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  617. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  618. inGraph (patcher::graphOf (getEffect ((int) t, (int) s).get()));
  619. }
  620. ProcessTimes* AudioEngine::getProcessTimes() noexcept
  621. {
  622. if (externalTimes != nullptr)
  623. return externalTimes;
  624. return rackProcessor != nullptr ? &rackProcessor->processTimes() : nullptr;
  625. }
  626. void AudioEngine::play() noexcept
  627. {
  628. if (! transport.playing.load())
  629. {
  630. resetToInitialValues();
  631. // Performance mode: the song plays from its Start marker (the zone before it is launched, not played)
  632. if (const auto zone = song.mode == PlayMode::song ? song.performanceZoneEnd() : 0; zone > 0 && transport.positionTicks.load() < (double) zone)
  633. seek ((double) zone);
  634. // FL's "Start" marker: Play from the song's beginning starts at the marker (Song mode)
  635. if (song.mode == PlayMode::song && transport.seekRequest.load() < 0.0 && transport.positionTicks.load() <= 0.0)
  636. if (const auto start = transport.markerStart.load(); start > 0)
  637. transport.seekRequest.store ((double) start);
  638. }
  639. transport.playing.store (true);
  640. }
  641. // FL resets its "initialized controls" whenever the song position is set in song mode (playing starts, a jump):
  642. // FUN_011e7470 plays the song's init list (PTR_DAT_015dfc48) before the pattern events (REA round 146).
  643. void AudioEngine::resetToInitialValues() noexcept
  644. {
  645. if (song.initialValues.empty() || song.mode != PlayMode::song)
  646. return;
  647. try
  648. {
  649. auto differs = false;
  650. for (const auto& v : song.initialValues)
  651. {
  652. const auto now = currentTargetValue (v.target);
  653. differs = differs || (now >= 0.0f && std::abs (now - v.value) > 1.0e-6f);
  654. }
  655. if (! differs)
  656. return;
  657. std::vector<Song::InitialValue> plugins;
  658. editSong ([&plugins] (Song& s) { s.applyInitialValues ([&plugins] (const AutomationTarget& t, float v) { plugins.push_back ({ t, v }); }); },
  659. false);
  660. for (const auto& v : plugins)
  661. {
  662. if (v.target.kind == AutomationTargetKind::channelParam)
  663. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (v.target.index).get()))
  664. p->setParameterFromUi (v.target.param, v.value);
  665. if (v.target.kind == AutomationTargetKind::effectParam)
  666. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (v.target.index, v.target.slot).get()))
  667. p->setParameterFromUi (v.target.param, v.value);
  668. }
  669. }
  670. catch (...)
  671. {
  672. }
  673. }
  674. void AudioEngine::stop() noexcept
  675. {
  676. waitingForInput.store (false);
  677. transport.countIn.store (0.0);
  678. transport.playing.store (false);
  679. }
  680. std::vector<char> AudioEngine::lowLatencyTracksNow() const
  681. {
  682. return recordOptions.lowLatencyRecording ? lowlatency::bypassTracks (song, armedInserts) : std::vector<char> {};
  683. }
  684. void AudioEngine::refreshLowLatency()
  685. {
  686. if (lowLatencyTracksNow() != publishedLowLatency)
  687. publishSong();
  688. }
  689. int AudioEngine::lowLatencyBypassedLatency (int track, int slot) const noexcept
  690. {
  691. const auto& saved = lastPublishedShape.lowLatencySaved;
  692. return isSlotLowLatencyBypassed (track, slot) && (std::size_t) track < saved.size() && (std::size_t) slot < saved[(std::size_t) track].size()
  693. ? saved[(std::size_t) track][(std::size_t) slot]
  694. : 0;
  695. }
  696. int AudioEngine::lowLatencyBypassedCount() const noexcept
  697. {
  698. int count = 0;
  699. for (const auto mask : lastPublishedShape.lowLatencySlots)
  700. for (auto m = (unsigned) mask; m != 0; m &= m - 1)
  701. ++count;
  702. return count;
  703. }
  704. void AudioEngine::setRecordOptions (const RecordOptions& options)
  705. {
  706. recordOptions = options;
  707. recordOptions.countInBars = juce::jlimit (0, 4, options.countInBars);
  708. recordOptions.preRollBars = juce::jlimit (0, 8, options.preRollBars);
  709. recordOptions.postRollBars = juce::jlimit (0, 8, options.postRollBars);
  710. recordOptions.catchWindow = juce::jlimit<std::int64_t> (0, ppq, options.catchWindow);
  711. compensatePlayed.store (options.compensateOutput);
  712. updateLinearSong();
  713. refreshLowLatency(); // (round 190aq: the option switched while an insert is live)
  714. sendChangeMessage();
  715. }
  716. void AudioEngine::startPlayback()
  717. {
  718. if (! transport.recording.load())
  719. {
  720. play();
  721. return;
  722. }
  723. // pre-roll and punch (round 163): playback starts before the range the take keeps; post-roll stops it after
  724. activePunch.reset();
  725. punchStopAt = -1;
  726. auto startAt = (std::int64_t) transport.positionTicks.load();
  727. if (audioArmed && recordOptions.recordAudio)
  728. {
  729. const auto here = (std::int64_t) std::llround (transport.positionTicks.load());
  730. const auto punching = recordOptions.punchLoopRegion && song.mode == PlayMode::song && song.hasLoop();
  731. const auto in = punching ? song.loopStart : here;
  732. const auto out = punching ? song.loopEnd : std::numeric_limits<std::int64_t>::max() / 4;
  733. // (seconds: the ADR window's pre-roll, round 174d)
  734. auto secondsBack = [this] (std::int64_t at, double seconds) {
  735. const auto from = std::max (0.0, song.secondsForTicks (at) - seconds);
  736. return std::max<std::int64_t> (0, at - (std::int64_t) std::llround (videotrack::ticksForSeconds (song, from)));
  737. };
  738. auto secondsOn = [this] (std::int64_t at, double seconds) {
  739. return std::max<std::int64_t> (0, (std::int64_t) std::llround (videotrack::ticksForSeconds (song, song.secondsForTicks (at) + seconds)) - at);
  740. };
  741. const auto pre = recordOptions.preRollSeconds >= 0.0 ? secondsBack (in, recordOptions.preRollSeconds)
  742. : recordOptions.preRollBars > 0 ? countInLength (song, recordOptions.preRollBars, std::max<std::int64_t> (0, in - 1)) : 0;
  743. if (punching || pre > 0)
  744. {
  745. activePunch = PunchRange { in, out };
  746. if (punching)
  747. punchStopAt = out + (recordOptions.postRollSeconds >= 0.0 ? secondsOn (out, recordOptions.postRollSeconds)
  748. : recordOptions.postRollBars > 0 ? countInLength (song, recordOptions.postRollBars, out) : 0);
  749. startAt = std::max<std::int64_t> (0, in - pre);
  750. transport.seekRequest.store ((double) startAt);
  751. }
  752. updateLinearSong();
  753. }
  754. if (recordOptions.waitForInput)
  755. {
  756. waitingForInput.store (true);
  757. sendChangeMessage();
  758. return;
  759. }
  760. if (recordOptions.countInBars > 0)
  761. {
  762. // the notes played during the count-in belong to this take (round 170d)
  763. const auto length = countInLength (song, recordOptions.countInBars, startAt);
  764. takeCatch = {};
  765. takeCatch.start = startAt;
  766. takeCatch.window = recordOptions.catchWindow;
  767. takeCatch.songMode = song.mode == PlayMode::song;
  768. if (! song.patterns.empty())
  769. takeCatch.wrap = countInWrap (length, song.patterns[(std::size_t) juce::jlimit (0, (int) song.patterns.size() - 1, song.currentPattern)]
  770. .effectiveLength (song.beatsPerBar));
  771. transport.countIn.store ((double) length);
  772. sendChangeMessage();
  773. return;
  774. }
  775. play();
  776. }
  777. void AudioEngine::startOnInput() noexcept
  778. {
  779. if (waitingForInput.exchange (false))
  780. transport.playing.store (true);
  781. }
  782. void AudioEngine::setInsertArmed (int track, bool armed)
  783. {
  784. const auto it = std::find (armedInserts.begin(), armedInserts.end(), track);
  785. const auto wasArmed = it != armedInserts.end();
  786. if (armed == wasArmed || track <= 0)
  787. return;
  788. if (armed && isInsertRecordSafe (track)) // record safe (round 163): never armed by accident
  789. {
  790. notify (InputIssue::recordSafe, track);
  791. return;
  792. }
  793. if (armed)
  794. armedInserts.push_back (track);
  795. else
  796. armedInserts.erase (it);
  797. if (track < maxMixerTracks)
  798. liveInput.armed[(std::size_t) track].store (armed);
  799. if (armed && ! audioArmed)
  800. setAudioRecordingArmed (true);
  801. else if (! armed && armedInserts.empty() && audioArmed)
  802. setAudioRecordingArmed (false);
  803. refreshLowLatency(); // (round 190aq: "Low latency while recording" follows the arm switches)
  804. sendChangeMessage();
  805. }
  806. bool AudioEngine::isInsertArmed (int track) const noexcept
  807. {
  808. return std::find (armedInserts.begin(), armedInserts.end(), track) != armedInserts.end();
  809. }
  810. void AudioEngine::rewind() noexcept { transport.rewindRequested.store (true); }
  811. void AudioEngine::jumpTo (double tick) noexcept
  812. {
  813. tick = juce::jmax (0.0, tick);
  814. const auto quantize = quantizeSongJumps.load();
  815. if (! transport.playing.load() || quantize <= 0 || song.mode != PlayMode::song)
  816. {
  817. seek (tick);
  818. return;
  819. }
  820. // the jump waits for the next beat / bar(s) (FL's "Quantize song jumps"); the audio thread makes it there
  821. const auto at = (double) markers::quantizedJumpTick (song, transport.positionTicks.load(), quantize);
  822. transport.pendingJumpTo.store (tick);
  823. transport.pendingJumpAt.store (at);
  824. }
  825. void AudioEngine::jumpToMarker (int index) noexcept
  826. {
  827. const auto& list = song.markers();
  828. if (index < 0 || index >= (int) list.size())
  829. return;
  830. if (song.mode != PlayMode::song)
  831. editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  832. jumpTo ((double) list[(std::size_t) index].tick);
  833. }
  834. void AudioEngine::jumpToNextMarker (bool forward) noexcept
  835. {
  836. // from where the song is (or where a quantized jump is going)
  837. const auto pending = transport.pendingJumpAt.load() >= 0.0 ? transport.pendingJumpTo.load() : -1.0;
  838. const auto here = pending >= 0.0 ? pending : transport.positionTicks.load();
  839. const auto& list = song.markers();
  840. int best = -1;
  841. for (int i = 0; i < (int) list.size(); ++i)
  842. {
  843. const auto t = (double) list[(std::size_t) i].tick;
  844. if (forward ? t > here + 0.5 : t < here - 0.5)
  845. {
  846. if (forward)
  847. {
  848. best = i;
  849. break;
  850. }
  851. best = i;
  852. }
  853. }
  854. if (best >= 0)
  855. jumpToMarker (best);
  856. else if (! forward)
  857. jumpTo (0.0);
  858. }
  859. void AudioEngine::seek (double ticks) noexcept
  860. {
  861. transport.pendingJumpAt.store (-1.0); // a direct seek replaces a quantized jump still waiting
  862. if (transport.playing.load())
  863. resetToInitialValues(); // a jump while the song plays (FL sets the position the same way)
  864. transport.seekRequest.store (juce::jmax (0.0, ticks));
  865. }
  866. void AudioEngine::copyScope (float* destination, int count) const noexcept
  867. {
  868. count = juce::jmin (count, scopeSize);
  869. auto r = (scopeWrite.load (std::memory_order_acquire) - count + scopeSize) % scopeSize;
  870. for (int i = 0; i < count; ++i)
  871. {
  872. destination[i] = scope[(std::size_t) r].load (std::memory_order_relaxed);
  873. r = (r + 1) % scopeSize;
  874. }
  875. }
  876. void AudioEngine::previewFile (const juce::File& file)
  877. {
  878. ++previewSerial; // (a preview still being prepared is dropped)
  879. previewTiming = {};
  880. if (preview == nullptr)
  881. return;
  882. auto sample = file.existsAsFile() ? samples.load (file.getFullPathName()) : nullptr;
  883. if (! previewInTime || sample == nullptr)
  884. {
  885. preview->playBrowser (std::move (sample)); // FL's preview: the file as it is, at once
  886. return;
  887. }
  888. // "Preview in time" (round 190aq, core/PreviewTempo.h): the file's tempo from its ACID beats or its name (cheap,
  889. // here), else from LYNX's tempo detection (on the worker); a file that can have none plays as it always did
  890. const auto path = file.getFullPathName();
  891. const auto name = file.getFileName().toStdString();
  892. const auto external = transport.externalBpm.load (std::memory_order_relaxed);
  893. const auto projectBpm = external > 0.0 ? external : transport.bpm.load (std::memory_order_relaxed);
  894. auto found = previewtempo::quick (*sample, name);
  895. auto known = found.bpm > 0.0;
  896. if (! known)
  897. if (const auto it = previewTempos.find (path); it != previewTempos.end())
  898. {
  899. found = it->second;
  900. known = true;
  901. }
  902. if (! known && ! previewtempo::worthDetecting (*sample))
  903. {
  904. preview->playBrowser (std::move (sample));
  905. return;
  906. }
  907. PreviewTiming timing;
  908. timing.path = path;
  909. timing.projectBpm = projectBpm;
  910. timing.fileBpm = found.bpm;
  911. timing.source = found.source;
  912. timing.ratio = previewtempo::stretchRatio (found.bpm, projectBpm);
  913. timing.inTime = found.bpm > 0.0;
  914. if (known)
  915. {
  916. if (found.bpm <= 0.0) // (analysed before: no tempo)
  917. {
  918. preview->playBrowser (std::move (sample));
  919. return;
  920. }
  921. if (timing.ratio == 1.0) // already at the project's tempo: only the start waits for the beat
  922. {
  923. startPreviewInTime (path, std::move (sample), timing);
  924. return;
  925. }
  926. for (const auto& s : previewStretches)
  927. if (s.path == path && s.ratio == timing.ratio && s.sample != nullptr)
  928. {
  929. startPreviewInTime (path, s.sample, timing);
  930. return;
  931. }
  932. }
  933. // the tempo detection and / or the stretch, off the message thread; what was playing stops now
  934. preview->playBrowser (nullptr);
  935. timing.pending = true;
  936. previewTiming = timing;
  937. const auto started = juce::Time::getMillisecondCounterHiRes();
  938. previewJobs.post ([this, alive = previewAlive, serial = previewSerial, path, sample, timing, known, started]() mutable {
  939. if (! alive->load())
  940. return;
  941. auto found = previewtempo::Found { timing.fileBpm, timing.source };
  942. if (! known)
  943. found = previewtempo::detect (*sample);
  944. timing.fileBpm = found.bpm;
  945. timing.source = found.source;
  946. timing.inTime = found.bpm > 0.0;
  947. timing.ratio = previewtempo::stretchRatio (found.bpm, timing.projectBpm);
  948. std::shared_ptr<const SampleData> out = sample;
  949. if (timing.inTime && timing.ratio != 1.0)
  950. if (auto stretched = timeStretch (*sample, timing.ratio, StretchMethod::general); stretched != nullptr && stretched->frames() > 1)
  951. out = std::move (stretched);
  952. timing.prepareMs = juce::Time::getMillisecondCounterHiRes() - started;
  953. {
  954. const std::lock_guard<std::mutex> lock (previewResultLock);
  955. previewResults.push_back ({ serial, path, sample, out, timing, found, ! known });
  956. }
  957. juce::MessageManager::callAsync ([this, alive] {
  958. if (alive->load())
  959. takePreviewResults();
  960. });
  961. });
  962. }
  963. // The prepared previews, on the message thread: the tempo and the stretch are kept for the next click on the same
  964. // file, and the newest one plays unless another file was clicked meanwhile.
  965. void AudioEngine::takePreviewResults()
  966. {
  967. std::vector<PreviewResult> results;
  968. {
  969. const std::lock_guard<std::mutex> lock (previewResultLock);
  970. results.swap (previewResults);
  971. }
  972. for (auto& r : results)
  973. {
  974. if (r.detected)
  975. {
  976. if (previewTempos.size() > 512)
  977. previewTempos.clear();
  978. previewTempos[r.path] = r.found;
  979. }
  980. if (r.out != r.sample)
  981. {
  982. if (previewStretches.size() >= 6)
  983. previewStretches.erase (previewStretches.begin());
  984. previewStretches.push_back ({ r.path, r.timing.ratio, r.out });
  985. }
  986. if (r.serial != previewSerial || preview == nullptr)
  987. continue; // another file was clicked meanwhile (or the preview was stopped)
  988. lastPreviewPrepareMs = r.timing.prepareMs;
  989. if (! r.timing.inTime)
  990. {
  991. previewTiming = {};
  992. preview->playBrowser (r.out); // no tempo found: as it is
  993. continue;
  994. }
  995. startPreviewInTime (r.path, r.out, r.timing);
  996. }
  997. }
  998. void AudioEngine::finishPreviewJobs()
  999. {
  1000. previewJobs.waitIdle();
  1001. takePreviewResults();
  1002. }
  1003. void AudioEngine::startPreviewInTime (const juce::String& path, std::shared_ptr<const SampleData> sample, const PreviewTiming& timing)
  1004. {
  1005. previewTiming = timing;
  1006. previewTiming.path = path;
  1007. previewTiming.pending = false;
  1008. previewTiming.inTime = true;
  1009. previewTiming.frames = sample != nullptr ? sample->frames() : 0;
  1010. previewHandedAtMs = juce::Time::getMillisecondCounterHiRes();
  1011. preview->setSyncLatency (getLatencySamples());
  1012. preview->playBrowser (std::move (sample), 0.8f, true);
  1013. }
  1014. int AudioEngine::getPreviewBeatStarts() const noexcept { return preview != nullptr ? preview->beatStarts() : 0; }
  1015. double AudioEngine::getPreviewInTimeProgress() const noexcept
  1016. {
  1017. if (previewTiming.pending)
  1018. return 0.0;
  1019. if (! previewTiming.inTime || preview == nullptr)
  1020. return -1.0;
  1021. const auto position = preview->getPlayPosition();
  1022. if (position < 0.0) // (the audio thread takes the sample at its next block)
  1023. return juce::Time::getMillisecondCounterHiRes() - previewHandedAtMs < 200.0 ? 0.0 : -1.0;
  1024. return previewTiming.frames > 1 ? juce::jlimit (0.0, 1.0, position / (double) (previewTiming.frames - 1)) : 0.0;
  1025. }
  1026. void AudioEngine::setInputScale (int scale, int root) noexcept
  1027. {
  1028. inputScaleRoot.store (root);
  1029. inputScale.store (scale);
  1030. }
  1031. int AudioEngine::snapInputKey (int key) const noexcept
  1032. {
  1033. const auto scale = inputScale.load();
  1034. return scale > 0 ? notetools::snapToScale (key, inputScaleRoot.load(), scale) : key;
  1035. }
  1036. void AudioEngine::previewSample (std::shared_ptr<const SampleData> sample, bool loop, float gain, bool audioEditor)
  1037. {
  1038. if (preview != nullptr)
  1039. preview->play (std::move (sample), loop, gain, audioEditor);
  1040. }
  1041. void AudioEngine::setEditorVolume (double volume) noexcept
  1042. {
  1043. editorVolume = controls::clampUtilityVolume (volume);
  1044. if (preview != nullptr)
  1045. preview->setEditorVolume (controls::previewGain (editorVolume));
  1046. }
  1047. void AudioEngine::setPreviewVolume (double volume) noexcept
  1048. {
  1049. previewVolume = controls::clampUtilityVolume (volume);
  1050. if (preview != nullptr)
  1051. preview->setVolume (controls::previewGain (previewVolume));
  1052. }
  1053. double AudioEngine::getPreviewPosition() const noexcept
  1054. {
  1055. return preview != nullptr ? preview->getPlayPosition() : -1.0;
  1056. }
  1057. void AudioEngine::markHeldKey (int midiChannel, int key, bool on) noexcept
  1058. {
  1059. if (key < 0 || key > 127 || midiChannel < 0 || midiChannel > 15)
  1060. return;
  1061. auto& count = heldKeyCount[midiChannel][(std::size_t) key];
  1062. auto before = count.load();
  1063. std::uint8_t after = 0;
  1064. do
  1065. after = on ? (std::uint8_t) std::min (255, before + 1) : (std::uint8_t) (before > 0 ? before - 1 : 0);
  1066. while (! count.compare_exchange_weak (before, after));
  1067. const auto bit = std::uint64_t { 1 } << (key & 63);
  1068. if (after > 0)
  1069. heldKeyBits[midiChannel][key >> 6].fetch_or (bit);
  1070. else
  1071. heldKeyBits[midiChannel][key >> 6].fetch_and (~bit);
  1072. }
  1073. void AudioEngine::logPlayedNote (int channel, int key, float velocity, bool on, double tick, bool recorded)
  1074. {
  1075. if (channel < 0)
  1076. return;
  1077. const auto ms = juce::Time::getMillisecondCounterHiRes();
  1078. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1079. if (on)
  1080. scoreLog.noteOn (ms, channel, key, velocity, tick, recorded);
  1081. else
  1082. scoreLog.noteOff (ms, channel, key);
  1083. if (stepEditOn.load (std::memory_order_relaxed) && stepEditQueue.size() < 512)
  1084. stepEditQueue.push_back ({ channel, key, velocity, on });
  1085. }
  1086. void AudioEngine::setStepEdit (bool on) noexcept
  1087. {
  1088. stepEditOn.store (on, std::memory_order_relaxed);
  1089. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1090. stepEditQueue.clear();
  1091. }
  1092. std::vector<stepedit::Played> AudioEngine::takeStepEditNotes()
  1093. {
  1094. std::vector<stepedit::Played> out;
  1095. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1096. out.swap (stepEditQueue);
  1097. return out;
  1098. }
  1099. std::vector<scorelog::Entry> AudioEngine::scoreLogSnapshot() const
  1100. {
  1101. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1102. return scoreLog.snapshot();
  1103. }
  1104. bool AudioEngine::scoreLogEmpty() const
  1105. {
  1106. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1107. return scoreLog.size() == 0;
  1108. }
  1109. void AudioEngine::clearScoreLog()
  1110. {
  1111. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1112. scoreLog.clear();
  1113. }
  1114. NoteMask AudioEngine::soundingKeys (int channel) const noexcept
  1115. {
  1116. return rackProcessor != nullptr ? rackProcessor->getRenderer().soundingKeys (channel) : NoteMask {};
  1117. }
  1118. std::vector<int> AudioEngine::heldInputKeys() const
  1119. {
  1120. std::vector<int> keys;
  1121. std::uint64_t all[2] {};
  1122. for (const auto& channel : heldKeyBits)
  1123. for (int word = 0; word < 2; ++word)
  1124. all[word] |= channel[word].load();
  1125. for (int word = 0; word < 2; ++word)
  1126. for (int b = 0; b < 64; ++b)
  1127. if ((all[word] >> b & 1u) != 0)
  1128. keys.push_back (word * 64 + b);
  1129. return keys;
  1130. }
  1131. std::array<std::uint64_t, 2> AudioEngine::heldInputKeyBits (int midiChannel) const noexcept
  1132. {
  1133. if (midiChannel < 0 || midiChannel > 15)
  1134. return {};
  1135. return { heldKeyBits[midiChannel][0].load (std::memory_order_relaxed), heldKeyBits[midiChannel][1].load (std::memory_order_relaxed) };
  1136. }
  1137. RollingAudioLog& AudioEngine::getRollingLog() noexcept
  1138. {
  1139. return meters.rollingLog;
  1140. }
  1141. void AudioEngine::sendLiveNote (int channel, int key, float velocity, bool on, bool record)
  1142. {
  1143. if (record) // played notes (the PC keyboard) follow the scale snap; previews don't
  1144. {
  1145. markHeldKey (0, key, on); // (FL sends the typing keyboard as MIDI channel 1)
  1146. // the note-off stops the key its note-on started, even if the snap changed in between
  1147. const auto requested = key;
  1148. if (on)
  1149. {
  1150. key = snapInputKey (key);
  1151. playedKeys.on (channel, requested, key);
  1152. startOnInput();
  1153. }
  1154. else
  1155. key = playedKeys.off (channel, requested, snapInputKey (key));
  1156. }
  1157. NoteEvent e;
  1158. e.type = on ? NoteEvent::Type::on : NoteEvent::Type::off;
  1159. e.channel = channel;
  1160. e.key = key;
  1161. e.velocity = velocity;
  1162. liveEvents.push (e);
  1163. // (round 170d: recorded during the count-in too, at the audio clock's position)
  1164. const auto now = juce::Time::getMillisecondCounterHiRes();
  1165. const auto taking = record && transport.recording.load() && (transport.playing.load() || isCountingIn());
  1166. if (record)
  1167. logPlayedNote (channel, key, velocity, on, transport.playing.load() ? recordTickFor (now) : -1.0, taking);
  1168. if (taking)
  1169. uiRecorded.push_back ({ recordTickFor (now), channel, key, velocity, on });
  1170. if (record && slotTaking.load (std::memory_order_relaxed)) // a slot of the clip grid records (round 190bv)
  1171. uiSlotRecorded.push_back ({ recordTickFor (now), channel, key, velocity, on });
  1172. }
  1173. void AudioEngine::panic()
  1174. {
  1175. NoteEvent e;
  1176. e.type = NoteEvent::Type::choke;
  1177. e.channel = -1; // every channel
  1178. liveEvents.push (e);
  1179. for (auto& channel : heldKeyCount)
  1180. for (auto& c : channel)
  1181. c.store (0);
  1182. for (auto& channel : heldKeyBits)
  1183. for (auto& w : channel)
  1184. w.store (0);
  1185. }
  1186. void AudioEngine::stopSound()
  1187. {
  1188. panic();
  1189. NoteEvent e;
  1190. e.type = NoteEvent::Type::choke;
  1191. e.channel = RackRenderer::stopSoundChannel; // and every effect / plugin reset
  1192. liveEvents.push (e);
  1193. }
  1194. double AudioEngine::songPlayheadTicks() const noexcept
  1195. {
  1196. const auto tick = juce::jmax (0.0, transport.positionTicks.load (std::memory_order_relaxed));
  1197. if (song.loopPlays() || liveInput.linearSong.load (std::memory_order_relaxed))
  1198. return tick;
  1199. return std::fmod (tick, (double) juce::jmax<std::int64_t> (1, song.songLength()));
  1200. }
  1201. double AudioEngine::playheadAdvanceTicks() const noexcept
  1202. {
  1203. if (! transport.playing.load (std::memory_order_relaxed) || ! clockRunning.load (std::memory_order_relaxed))
  1204. return 0.0;
  1205. const auto since = juce::Time::getMillisecondCounterHiRes() - blockTimeMs.load (std::memory_order_acquire);
  1206. return juce::jlimit (0.0, juce::jmax (0.0, blockDurationMs.load (std::memory_order_relaxed)), since) * clockTicksPerMs.load (std::memory_order_relaxed);
  1207. }
  1208. LiveClock AudioEngine::liveClock() const noexcept
  1209. {
  1210. LiveClock c;
  1211. c.timeMs = blockTimeMs.load (std::memory_order_acquire);
  1212. c.tick = clockTick.load (std::memory_order_relaxed);
  1213. c.ticksPerMs = clockTicksPerMs.load (std::memory_order_relaxed);
  1214. c.running = clockRunning.load (std::memory_order_relaxed);
  1215. return c;
  1216. }
  1217. double AudioEngine::recordTickFor (double eventMs) const noexcept
  1218. {
  1219. const auto clock = liveClock();
  1220. // (stopped, or no callback since Play / the count-in started: the transport's own position, as before)
  1221. if (! clock.running)
  1222. return transport.positionTicks.load (std::memory_order_relaxed)
  1223. - (transport.playing.load (std::memory_order_relaxed) ? 0.0 : transport.countIn.load (std::memory_order_relaxed));
  1224. return liveTickAt (clock, eventMs, compensatePlayed.load (std::memory_order_relaxed) ? outputCompensationMs.load (std::memory_order_relaxed) : 0.0);
  1225. }
  1226. CaptureResult AudioEngine::captureMidi()
  1227. {
  1228. CaptureOptions o;
  1229. o.afterMs = lastCaptureMs;
  1230. o.nowMs = juce::Time::getMillisecondCounterHiRes();
  1231. o.gapMs = 2.0 * juce::jmax (1, song.beatsPerBar) * 60000.0 / juce::jmax (1.0, song.bpm); // two bars of silence end a phrase
  1232. o.playhead = (std::int64_t) std::llround (songPlayheadTicks());
  1233. o.mode = recordOptions.mode;
  1234. o.quantize.grid = recordOptions.quantise;
  1235. o.quantize.starts = recordOptions.quantiseStarts;
  1236. o.quantize.end = recordOptions.noteEnd;
  1237. o.quantize.stepSequencer = recordOptions.toStepSequencer;
  1238. o.placeClip = recordOptions.placeSongClip;
  1239. const auto log = scoreLogSnapshot();
  1240. if (capturePhrase (song, log, o).empty()) // (nothing to capture: no undo step)
  1241. return {};
  1242. CaptureResult result;
  1243. editSong ([&] (Song& s) { result = lynx::captureMidi (s, log, o); });
  1244. if (result.newestMs > lastCaptureMs)
  1245. lastCaptureMs = result.newestMs;
  1246. return result;
  1247. }
  1248. double AudioEngine::estimatedPositionNow() const noexcept
  1249. {
  1250. // the position only moves block by block; interpolate by the time since the last block
  1251. auto tick = transport.positionTicks.load (std::memory_order_relaxed);
  1252. if (transport.playing.load (std::memory_order_relaxed))
  1253. {
  1254. const auto elapsedMs = juce::jlimit (0.0, 100.0, juce::Time::getMillisecondCounterHiRes() - blockTimeMs.load());
  1255. tick += elapsedMs * 0.001 * transport.sampleRate.load() * transport.ticksPerSample();
  1256. }
  1257. return tick;
  1258. }
  1259. AudioEngine::LiveRecording AudioEngine::liveRecording() const
  1260. {
  1261. LiveRecording live;
  1262. if (! isLiveRecording())
  1263. return live;
  1264. live.punch = activePunch;
  1265. // the note take
  1266. if (recorder.isActive() && song.currentPattern >= 0 && song.currentPattern < (int) song.patterns.size())
  1267. {
  1268. const auto now = transport.playing.load() ? estimatedPositionNow() : lastPlayingTick;
  1269. auto preview = recorder.preview (song, now);
  1270. live.notes = true;
  1271. live.pattern = song.currentPattern;
  1272. live.held = std::move (preview.notes);
  1273. if (song.mode == PlayMode::song && preview.origin >= 0)
  1274. {
  1275. // the take's clip (placed with its first finished note) or, before it, where it will be placed
  1276. const Clip* clip = nullptr;
  1277. for (const auto& c : song.playlist)
  1278. if (c.kind == ClipKind::pattern && c.pattern == song.currentPattern && c.start - c.offset == preview.origin
  1279. && (clip == nullptr || c.end() > clip->end()))
  1280. clip = &c;
  1281. live.track = clip != nullptr ? clip->track : patternClipTrack (song, song.barAt (preview.origin).tick);
  1282. live.from = clip != nullptr ? clip->start : preview.origin;
  1283. live.origin = preview.origin;
  1284. auto to = preview.reach;
  1285. for (const auto& n : live.held)
  1286. to = std::max (to, preview.origin + n.start + n.length);
  1287. if (! preview.fromClip && noteTakeLinear)
  1288. to = std::max (to, (std::int64_t) now); // (a linear take: the region follows the playhead)
  1289. live.to = std::max (live.from, to);
  1290. }
  1291. }
  1292. // the audio takes
  1293. const auto startTick = takeStartTick.load();
  1294. const auto frames = takeFrames.load();
  1295. if (! openTakes.empty() && startTick >= 0.0 && frames > 0)
  1296. {
  1297. const auto wraps = takeWrapCount.load();
  1298. const auto lastWrap = song.mode == PlayMode::song && song.loopPlays() && wraps > 0 ? (std::int64_t) takeWraps[(std::size_t) wraps - 1].load() : -1;
  1299. const auto span = liverec::audioSpan (startTick, frames, takeTicksPerSample, takeLatency, lastWrap, song.loopStart);
  1300. if (liveTakeTracks.size() != openTakes.size())
  1301. {
  1302. // the tracks takes::placeTakeClips will pick (each file's insert, one track each)
  1303. liveTakeTracks.clear();
  1304. const auto from = (std::int64_t) span.start, to = from + std::max<std::int64_t> (1, (std::int64_t) span.length);
  1305. for (const auto& take : openTakes)
  1306. {
  1307. auto track = takes::takeTrack (song, take->playThrough > 0 ? take->playThrough : -1, from, to);
  1308. for (const auto used : liveTakeTracks)
  1309. if (used >= track)
  1310. track = used + 1;
  1311. liveTakeTracks.push_back (track);
  1312. }
  1313. }
  1314. if (span.valid())
  1315. for (std::size_t k = 0; k < openTakes.size(); ++k)
  1316. {
  1317. LiveRecording::Audio a;
  1318. a.track = liveTakeTracks[k];
  1319. a.span = span;
  1320. a.peaks = openTakes[k]->peaks;
  1321. a.name = openTakes[k]->file.getFileNameWithoutExtension();
  1322. live.audio.push_back (std::move (a));
  1323. }
  1324. }
  1325. return live;
  1326. }
  1327. void AudioEngine::updateAudioRecording()
  1328. {
  1329. // (round 190bv: a slot of the clip grid recording audio runs the armed inserts' takes too)
  1330. const auto wantTake = audioArmed && recordOptions.recordAudio && (transport.recording.load() || slotAudioWanted);
  1331. const auto open = takeCount > 0;
  1332. // the files are ready before Play: the very first block gets recorded
  1333. if (wantTake && ! open && recordingError.isEmpty())
  1334. startAudioTake();
  1335. // post-roll over: playback stops (the take is closed below on the next tick)
  1336. if (open && punchStopAt >= 0 && transport.playing.load() && transport.positionTicks.load() >= (double) punchStopAt)
  1337. {
  1338. punchStopAt = -1;
  1339. stop();
  1340. }
  1341. // the first samples arrived: the journals that let a crash be recovered (round 163)
  1342. if (open && ! journalsWritten && takeStartTick.load() >= 0.0)
  1343. writeJournals();
  1344. // a file that could not be written (disk full, drive gone): say it once, the take stops there
  1345. for (auto& take : openTakes)
  1346. if (take->failed.load() && recordingError.isEmpty())
  1347. {
  1348. recordingError = take->writer.error().empty() ? juce::String ("could not write ") + take->file.getFullPathName()
  1349. : juce::String::fromUTF8 (take->writer.error().c_str()) + ": " + take->file.getFullPathName();
  1350. notify (InputIssue::failed, take->track, recordingError);
  1351. }
  1352. // playback stopped (or recording turned off) with something recorded: close the takes
  1353. if (open && (! wantTake || (! transport.playing.load() && takeFrames.load() > 0)))
  1354. finishAudioTake();
  1355. }
  1356. bool AudioEngine::Take::drain()
  1357. {
  1358. if (stream == nullptr || failed.load())
  1359. return false;
  1360. const auto n = 8192;
  1361. if (scratch.size() < (std::size_t) (2 * n))
  1362. scratch.resize ((std::size_t) (2 * n));
  1363. auto any = false;
  1364. for (;;)
  1365. {
  1366. float* out[] = { scratch.data(), scratch.data() + n };
  1367. const auto got = stream->pull (out, n);
  1368. if (got <= 0)
  1369. break;
  1370. any = true;
  1371. const float* in[] = { out[0], out[1] };
  1372. if (! writer.write (in, got))
  1373. {
  1374. failed.store (true);
  1375. break;
  1376. }
  1377. peaks->append (in, stream->channels(), got);
  1378. }
  1379. return any;
  1380. }
  1381. namespace
  1382. {
  1383. juce::File recordingSettingsFile() { return PluginHost::settingsFolder().getChildFile ("recording.txt"); }
  1384. juce::File inProgressFile() { return PluginHost::settingsFolder().getChildFile ("recordings-in-progress.txt"); }
  1385. AudioEngine::RecordingSettings loadRecordingSettings()
  1386. {
  1387. AudioEngine::RecordingSettings s;
  1388. for (const auto& raw : juce::StringArray::fromLines (recordingSettingsFile().loadFileAsString()))
  1389. {
  1390. const auto key = raw.upToFirstOccurrenceOf ("=", false, false).trim();
  1391. const auto value = raw.fromFirstOccurrenceOf ("=", false, false);
  1392. if (key == "format")
  1393. s.format = value.trim() == "float32" ? takes::SampleFormat::float32 : value.trim() == "pcm16" ? takes::SampleFormat::pcm16 : takes::SampleFormat::pcm24;
  1394. else if (key == "trackTakeNames")
  1395. s.trackTakeNames = value.getIntValue() != 0;
  1396. else if (key == "manualOffset")
  1397. s.manualOffset = juce::jlimit (-48000, 48000, value.getIntValue());
  1398. else if (key == "useMeasured")
  1399. s.useMeasured = value.getIntValue() != 0;
  1400. else if (key == "pingOutput")
  1401. s.pingOutput = juce::jlimit (0, 63, value.getIntValue());
  1402. else if (key == "pingInput")
  1403. s.pingInput = juce::jlimit (0, 63, value.getIntValue());
  1404. else if (key == "measured") // measured=<samples>\t<setup key>
  1405. s.measured[value.fromFirstOccurrenceOf ("\t", false, false).toStdString()] = value.upToFirstOccurrenceOf ("\t", false, false).getIntValue();
  1406. }
  1407. return s;
  1408. }
  1409. } // namespace
  1410. void AudioEngine::setRecordingSettings (const RecordingSettings& settings)
  1411. {
  1412. // round 190bj (issue B3): takes whose files are ready but empty (made when the previous take ended, the track still
  1413. // armed) take the new sample format too; one that has samples keeps its own
  1414. if (settings.format != recordingSettings.format)
  1415. for (auto& take : openTakes)
  1416. {
  1417. const juce::ScopedLock lock (take->drainMutex);
  1418. take->writer.changeFormat (settings.format);
  1419. }
  1420. recordingSettings = settings;
  1421. juce::String text;
  1422. text << "format=" << (settings.format == takes::SampleFormat::float32 ? "float32" : settings.format == takes::SampleFormat::pcm16 ? "pcm16" : "pcm24") << "\n"
  1423. << "trackTakeNames=" << (settings.trackTakeNames ? 1 : 0) << "\n"
  1424. << "manualOffset=" << settings.manualOffset << "\n"
  1425. << "useMeasured=" << (settings.useMeasured ? 1 : 0) << "\n"
  1426. << "pingOutput=" << settings.pingOutput << "\n"
  1427. << "pingInput=" << settings.pingInput << "\n";
  1428. for (const auto& [key, samples] : settings.measured)
  1429. text << "measured=" << samples << "\t" << juce::String::fromUTF8 (key.c_str()) << "\n";
  1430. if (deviceStateSaver != nullptr) // (a headless engine — tests, export — keeps the user's file as it is)
  1431. recordingSettingsFile().replaceWithText (text);
  1432. sendChangeMessage();
  1433. }
  1434. std::string AudioEngine::currentSetupKey() const
  1435. {
  1436. auto* device = deviceManager.getCurrentAudioDevice();
  1437. if (device == nullptr)
  1438. return {};
  1439. const auto setup = deviceManager.getAudioDeviceSetup();
  1440. return takes::setupKey (device->getTypeName().toStdString(), setup.outputDeviceName.toStdString(), setup.inputDeviceName.toStdString(),
  1441. device->getCurrentSampleRate(), device->getCurrentBufferSizeSamples());
  1442. }
  1443. takes::Latency AudioEngine::currentLatency() const
  1444. {
  1445. takes::Latency l;
  1446. if (auto* device = deviceManager.getCurrentAudioDevice())
  1447. {
  1448. l.driverInput = device->getInputLatencyInSamples();
  1449. l.driverOutput = device->getOutputLatencyInSamples();
  1450. }
  1451. if (recordingSettings.useMeasured)
  1452. if (const auto it = recordingSettings.measured.find (currentSetupKey()); it != recordingSettings.measured.end())
  1453. l.measured = it->second;
  1454. l.manual = recordingSettings.manualOffset;
  1455. l.pdc = getLatencySamples();
  1456. return l;
  1457. }
  1458. juce::String AudioEngine::startLatencyPing()
  1459. {
  1460. auto* device = deviceManager.getCurrentAudioDevice();
  1461. if (device == nullptr)
  1462. return TR_NOOP ("no audio device is open");
  1463. if (transport.playing.load() || isCountingIn())
  1464. return TR_NOOP ("stop playback first");
  1465. if (! hasAudioInput())
  1466. if (const auto r = openAudioInput(); r.issue != InputIssue::none)
  1467. return TR_NOOP ("no audio input is open");
  1468. device = deviceManager.getCurrentAudioDevice();
  1469. if (device == nullptr)
  1470. return TR_NOOP ("no audio device is open");
  1471. const auto in = recordingSettings.pingInput, out = recordingSettings.pingOutput;
  1472. if (! device->getActiveInputChannels()[in])
  1473. return TR_NOOP ("the input channel is not open");
  1474. if (! device->getActiveOutputChannels()[out])
  1475. return TR_NOOP ("the output channel is not open");
  1476. // device channel -> the callback's index (only open channels are passed)
  1477. const auto slotOf = [] (const juce::BigInteger& active, int c) {
  1478. if (! active[c])
  1479. return -1;
  1480. int slot = 0;
  1481. for (int k = 0; k < c; ++k)
  1482. slot += active[k] ? 1 : 0;
  1483. return slot;
  1484. };
  1485. pingInput = slotOf (device->getActiveInputChannels(), in);
  1486. pingOutputs = { slotOf (device->getActiveOutputChannels(), out), slotOf (device->getActiveOutputChannels(), out + 1) };
  1487. const auto rate = device->getCurrentSampleRate() > 0.0 ? device->getCurrentSampleRate() : 48000.0;
  1488. ping.start (8, juce::jmax (4096, (int) (rate / 4.0)), 0.5f);
  1489. return {};
  1490. }
  1491. takes::LatencyPing::Result AudioEngine::finishLatencyPing()
  1492. {
  1493. auto r = ping.result();
  1494. if (r.ok)
  1495. {
  1496. auto s = recordingSettings;
  1497. s.measured[currentSetupKey()] = r.samples;
  1498. setRecordingSettings (s);
  1499. }
  1500. return r;
  1501. }
  1502. void AudioEngine::setInsertRecordSafe (int track, bool safe)
  1503. {
  1504. if (track <= 0 || track >= (int) song.mixer.size() || song.mixer[(std::size_t) track].recordSafe == safe)
  1505. return;
  1506. if (safe && isInsertArmed (track))
  1507. setInsertArmed (track, false);
  1508. editSong ([track, safe] (Song& s) { s.mixer[(std::size_t) track].recordSafe = safe; });
  1509. }
  1510. void AudioEngine::startAudioTake()
  1511. {
  1512. auto* device = deviceManager.getCurrentAudioDevice();
  1513. if (device == nullptr)
  1514. return;
  1515. const auto names = getInputChannelNames();
  1516. const auto deviceChannels = (int) names.size();
  1517. const auto active = device->getActiveInputChannels();
  1518. if (deviceChannels == 0 || active.isZero())
  1519. {
  1520. recordingError = "no audio input is open";
  1521. notify (InputIssue::noInputOpen);
  1522. return;
  1523. }
  1524. // one take per armed insert that has an input source; without armed inserts (Settings' "Record input audio"),
  1525. // the first two input channels into a new insert
  1526. // round 168x (issue #41): FL's "Record" position of each insert. "External input only" records the device input;
  1527. // the other positions tap the insert (stereo, after the render) and need no input of their own; LYNX's "also the
  1528. // dry input" adds the device input as a second take
  1529. struct Wanted
  1530. {
  1531. int track, first, channels;
  1532. RecordSource point = RecordSource::externalInput;
  1533. bool dry = false; // the second, dry take of "also record the dry input (LYNX)"
  1534. };
  1535. std::vector<Wanted> wanted;
  1536. std::vector<int> withoutInput;
  1537. for (const auto t : armedInserts)
  1538. {
  1539. if (t <= 0 || t >= (int) song.mixer.size() || (int) wanted.size() >= maxTakes)
  1540. continue;
  1541. const auto& mt = song.mixer[(std::size_t) t];
  1542. const auto [first, count] = inputChannelsOf (mt, deviceChannels);
  1543. if (mt.recordSource != RecordSource::externalInput)
  1544. {
  1545. wanted.push_back ({ t, 0, 2, mt.recordSource, false });
  1546. if (mt.recordDryToo && count > 0 && (int) wanted.size() < maxTakes && (int) wanted.size() < LiveInput::maxTaps)
  1547. wanted.push_back ({ t, first, count, RecordSource::externalInput, true });
  1548. continue;
  1549. }
  1550. if (count == 0)
  1551. withoutInput.push_back (t);
  1552. else
  1553. wanted.push_back ({ t, first, count });
  1554. }
  1555. if (armedInserts.empty())
  1556. wanted.push_back ({ 0, 0, juce::jmin (2, deviceChannels) });
  1557. if (wanted.empty())
  1558. {
  1559. recordingError = "the armed inserts have no audio input";
  1560. notify (InputIssue::armedWithoutInput, withoutInput.empty() ? 0 : withoutInput.front());
  1561. return;
  1562. }
  1563. if (! withoutInput.empty())
  1564. notify (InputIssue::insertWithoutInput, withoutInput.front());
  1565. auto folder = recordingFolder;
  1566. if (! folder.createDirectory()) // e.g. a read-only project folder: the global recordings folder
  1567. folder = defaultRecordingFolder(), folder.createDirectory();
  1568. takeSampleRate = device->getCurrentSampleRate();
  1569. takeLatency = currentLatency().total();
  1570. takeTicksPerSample = transport.ticksPerSample();
  1571. const auto format = recordingSettings.format;
  1572. // room on the drive (round 163): under 30 s refuse, under 10 minutes warn
  1573. {
  1574. int channels = 0;
  1575. for (const auto& w : wanted)
  1576. channels += w.channels;
  1577. const auto minutes = takes::minutesLeft (folder.getBytesFreeOnVolume(), takeSampleRate, channels, format);
  1578. if (minutes < 0.5)
  1579. {
  1580. recordingError = "the recordings drive is full";
  1581. notify (InputIssue::lowDisk, 0, juce::String (minutes, 1));
  1582. return;
  1583. }
  1584. if (minutes < 10.0)
  1585. notify (InputIssue::lowDisk, 0, juce::String (minutes, 1));
  1586. }
  1587. const auto now = juce::Time::getCurrentTime();
  1588. std::vector<std::shared_ptr<Take>> made;
  1589. int tapsUsed = 0;
  1590. for (const auto& w : wanted)
  1591. {
  1592. juce::String insert;
  1593. if (w.track > 0)
  1594. insert = song.mixer[(std::size_t) w.track].name.empty() ? "Insert " + juce::String (w.track)
  1595. : juce::String::fromUTF8 (song.mixer[(std::size_t) w.track].name.c_str());
  1596. if (w.dry)
  1597. insert += " DI"; // the dry take of "also record the dry input (LYNX)"
  1598. juce::File file;
  1599. auto recordTo = w.track > 0 ? juce::String::fromUTF8 (song.mixer[(std::size_t) w.track].recordTo.c_str()) : juce::String();
  1600. if (w.dry && recordTo.isNotEmpty())
  1601. recordTo = juce::File (recordTo).getSiblingFile (juce::File (recordTo).getFileNameWithoutExtension() + " DI.wav").getFullPathName();
  1602. if (recordTo.isNotEmpty() && juce::File::isAbsolutePath (recordTo))
  1603. {
  1604. // FL's "Record <insert> to" file (round 167a): that file; LYNX never overwrites an earlier take, the next
  1605. // ones get "_2", "_3"... (its own choice)
  1606. const auto target = juce::File (recordTo).withFileExtension (".wav");
  1607. target.getParentDirectory().createDirectory();
  1608. const auto unique = safety::uniqueName (target.getFileNameWithoutExtension().toStdString(), [&target, &made] (const std::string& n) {
  1609. const auto f = target.getSiblingFile (juce::String::fromUTF8 (n.c_str()) + ".wav");
  1610. return f.exists() || std::any_of (made.begin(), made.end(), [&f] (const std::shared_ptr<Take>& t) { return t->file == f; });
  1611. });
  1612. file = target.getSiblingFile (juce::String::fromUTF8 (unique.c_str()) + ".wav");
  1613. }
  1614. else if (recordingSettings.trackTakeNames)
  1615. {
  1616. // "<Insert>_Take<N>.wav", N raised until the name is free (round 163)
  1617. for (int n = 1; n < 100000; ++n)
  1618. {
  1619. file = folder.getChildFile (juce::File::createLegalFileName (juce::String::fromUTF8 (takes::takeName (insert.toStdString(), n).c_str())) + ".wav");
  1620. if (! file.exists() && std::none_of (made.begin(), made.end(), [&file] (const std::shared_ptr<Take>& t) { return t->file == file; }))
  1621. break;
  1622. }
  1623. }
  1624. else
  1625. {
  1626. // FL's name (REA round 134): "<project>_<yyyy-mm-dd hh-mm-ss>_<insert name>", "_2", "_3"... when taken
  1627. const auto name = juce::File::createLegalFileName (juce::String::fromUTF8 (
  1628. safety::recordingName (recordingStem.toStdString(), now.getYear(), now.getMonth() + 1, now.getDayOfMonth(), now.getHours(),
  1629. now.getMinutes(), now.getSeconds(), insert.toStdString()).c_str()));
  1630. const auto unique = safety::uniqueName (name.toStdString(), [&folder] (const std::string& n) {
  1631. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ".wav").exists();
  1632. });
  1633. file = folder.getChildFile (juce::String::fromUTF8 (unique.c_str()) + ".wav");
  1634. }
  1635. auto take = std::make_shared<Take>();
  1636. take->track = w.track;
  1637. take->first = w.first;
  1638. take->channels = w.channels;
  1639. take->file = file;
  1640. if (w.point != RecordSource::externalInput && tapsUsed < LiveInput::maxTaps)
  1641. {
  1642. take->tap = tapsUsed++;
  1643. // the effects' latency up to the tap: the slots' (the planned output latency minus the input alignment and
  1644. // the manual track latency, which delays nothing inside the insert)
  1645. if (w.point >= RecordSource::postEffects)
  1646. take->skip = insertEffectsLatency (getPdcPlan(), song, w.track, takeSampleRate);
  1647. auto& slot = liveInput.taps[(std::size_t) take->tap];
  1648. slot.point.store ((int) w.point);
  1649. slot.track.store (w.track);
  1650. }
  1651. // a tap after the slots plays back through a new insert (through its own one it would get the effects twice)
  1652. if (w.point >= RecordSource::postEffects)
  1653. take->playThrough = 0;
  1654. else
  1655. take->playThrough = w.track;
  1656. // ~22 s at 48 kHz of room between the audio thread and the disk
  1657. take->stream = std::make_unique<takes::TakeStream> (w.channels, 1 << 20);
  1658. if (! take->writer.open (file.getFullPathName().toStdString(), takeSampleRate, w.channels, format))
  1659. {
  1660. recordingError = utf8 ("could not create ") + file.getFullPathName();
  1661. continue;
  1662. }
  1663. made.push_back (std::move (take));
  1664. }
  1665. if (recordingError.isNotEmpty())
  1666. notify (InputIssue::failed, 0, recordingError);
  1667. takeStartTick.store (-1.0);
  1668. takeFrames.store (0);
  1669. takeTicks.store (0.0);
  1670. takeWrapCount.store (0);
  1671. lostFrames = 0;
  1672. journalsWritten = false;
  1673. openTakes = made;
  1674. {
  1675. const juce::ScopedLock lock (drainLock);
  1676. draining = made;
  1677. }
  1678. if (drainer == nullptr)
  1679. drainer = std::make_unique<Drainer> (*this);
  1680. if (! recordThread.isThreadRunning())
  1681. recordThread.startThread (juce::Thread::Priority::high);
  1682. recordThread.addTimeSliceClient (drainer.get());
  1683. liveInput.tapCount.store (tapsUsed);
  1684. const juce::SpinLock::ScopedLockType lock (takeLock);
  1685. takeCount = 0;
  1686. for (auto& take : made)
  1687. takes[(std::size_t) takeCount++] = take.get();
  1688. updateLinearSong();
  1689. }
  1690. void AudioEngine::writeJournals()
  1691. {
  1692. journalsWritten = true;
  1693. juce::StringArray list (juce::StringArray::fromLines (inProgressFile().loadFileAsString()));
  1694. list.removeEmptyStrings();
  1695. int k = 0;
  1696. for (const auto& take : openTakes)
  1697. {
  1698. takes::Journal j;
  1699. j.wav = take->file.getFullPathName().toStdString();
  1700. j.firstTick = takeStartTick.load();
  1701. j.ticksPerSample = takeTicksPerSample;
  1702. j.sampleRate = takeSampleRate;
  1703. j.latency = takeLatency;
  1704. j.insert = take->playThrough;
  1705. j.playlistTrack = -1;
  1706. j.project = recordingStem.toStdString();
  1707. const auto journal = journalFor (take->file);
  1708. journal.replaceWithText (juce::String::fromUTF8 (takes::journalText (j).c_str()));
  1709. list.addIfNotAlreadyThere (journal.getFullPathName());
  1710. ++k;
  1711. }
  1712. if (deviceStateSaver != nullptr)
  1713. inProgressFile().replaceWithText (list.joinIntoString ("\n"));
  1714. }
  1715. void AudioEngine::finishAudioTake()
  1716. {
  1717. liveTakeTracks.clear();
  1718. {
  1719. const juce::SpinLock::ScopedLockType lock (takeLock);
  1720. takes.fill (nullptr);
  1721. takeCount = 0;
  1722. }
  1723. liveInput.linearSong.store (false);
  1724. liveInput.noLoopRegion.store (false);
  1725. std::vector<std::shared_ptr<Take>> done;
  1726. done.swap (openTakes);
  1727. {
  1728. const juce::ScopedLock lock (drainLock);
  1729. draining.clear();
  1730. }
  1731. // the recording taps are free again (the audio thread let go of the takes under takeLock above)
  1732. liveInput.tapCount.store (0);
  1733. for (auto& tap : liveInput.taps)
  1734. tap.track.store (-1);
  1735. std::vector<std::shared_ptr<Take>> kept;
  1736. for (auto& take : done)
  1737. {
  1738. if (take->tap >= 0 && take->skipped > 0) // a tapped take: the frames it dropped at its start close it
  1739. take->stream->pushSilence (take->skipped);
  1740. take->stream->finish(); // the audio thread let go of it (takeLock above)
  1741. const juce::ScopedLock lock (take->drainMutex);
  1742. take->drain();
  1743. lostFrames += take->stream->lostFrames();
  1744. take->writer.close();
  1745. if (take->file.existsAsFile())
  1746. {
  1747. sessionRecordings.push_back (take->file);
  1748. kept.push_back (take);
  1749. }
  1750. }
  1751. if (recordOptions.disarmOnStop) // LYNX's "Disarm the inserts when recording stops" (not FL's "Disarm on stop")
  1752. for (const auto t : std::vector<int> (armedInserts))
  1753. setInsertArmed (t, false);
  1754. // the journals go once the takes are on the Playlist (or thrown away)
  1755. const auto dropJournals = [this, &done] {
  1756. juce::StringArray list (juce::StringArray::fromLines (inProgressFile().loadFileAsString()));
  1757. for (const auto& take : done)
  1758. {
  1759. journalFor (take->file).deleteFile();
  1760. list.removeString (journalFor (take->file).getFullPathName());
  1761. }
  1762. list.removeEmptyStrings();
  1763. if (deviceStateSaver != nullptr)
  1764. {
  1765. if (list.isEmpty())
  1766. inProgressFile().deleteFile();
  1767. else
  1768. inProgressFile().replaceWithText (list.joinIntoString ("\n"));
  1769. }
  1770. };
  1771. const auto frames = takeFrames.exchange (0);
  1772. const auto startTick = takeStartTick.exchange (-1.0);
  1773. const auto ticks = takeTicks.exchange (0.0);
  1774. const auto keepPunch = activePunch;
  1775. activePunch.reset();
  1776. punchStopAt = -1;
  1777. std::vector<double> wraps;
  1778. for (int k = 0, count = takeWrapCount.exchange (0); k < count; ++k)
  1779. wraps.push_back ((double) takeWraps[(std::size_t) k].load() * takeTicksPerSample);
  1780. // (round 190bv) takes made for slots of the clip grid go into those slots, not onto the Playlist
  1781. if (std::any_of (slotTakes.begin(), slotTakes.end(), [] (const SlotTake& t) { return t.audio; }) && frames > 0 && startTick >= 0.0
  1782. && ! discardAudioTakes)
  1783. {
  1784. std::vector<std::pair<juce::File, int>> files;
  1785. for (const auto& take : kept)
  1786. files.push_back ({ take->file, take->track });
  1787. const auto used = placeSlotAudio (files, takeTicksPerSample, takeLatency);
  1788. if (! used)
  1789. for (auto& take : done)
  1790. {
  1791. take->file.deleteFile();
  1792. forgetRecordings ({ take->file });
  1793. }
  1794. dropJournals();
  1795. return;
  1796. }
  1797. if (frames <= 0 || startTick < 0.0 || discardAudioTakes) // (Cancel recording drops the takes, round 187a)
  1798. {
  1799. for (auto& take : done)
  1800. {
  1801. take->file.deleteFile();
  1802. forgetRecordings ({ take->file });
  1803. }
  1804. dropJournals();
  1805. return;
  1806. }
  1807. if (lostFrames > 0)
  1808. notify (InputIssue::framesLost, 0, juce::String (lostFrames));
  1809. // what came into the interface corresponds to what was heard one latency earlier; the clip lands on that
  1810. // song position to the sample (round 163: sub-tick rest in the source offset)
  1811. const auto placement = takes::place (startTick, ticks, takeTicksPerSample, takeLatency);
  1812. std::vector<takes::Part> parts;
  1813. if (keepPunch.has_value()) // pre-roll / punch in-out: only the range (the rest stays in the file)
  1814. parts = takes::punch (placement, { *keepPunch });
  1815. else if (song.mode == PlayMode::song && song.loopPlays())
  1816. // one part per pass of the loop; FL keeps a pass of any length (REA round 177c: a 1-tick pass got its own track),
  1817. // round 163's option drops one a 1/16 note long or less
  1818. parts = takes::loopPasses (placement, song.loopStart, song.loopEnd, recordOptions.lastLoopPassPlays ? ppq / 4 : 0, wraps);
  1819. else if (recordOptions.recordingMarkers && song.mode == PlayMode::song)
  1820. parts = takes::punch (placement, punchRanges (song.markers())); // FL's "Enable recording markers"
  1821. else
  1822. parts = takes::punch (placement, {});
  1823. if (parts.empty()) // the whole take was outside the ranges
  1824. {
  1825. for (auto& take : done)
  1826. {
  1827. take->file.deleteFile();
  1828. forgetRecordings ({ take->file });
  1829. }
  1830. dropJournals();
  1831. return;
  1832. }
  1833. std::vector<takes::TakeFile> made;
  1834. for (const auto& take : kept)
  1835. made.push_back ({ take->file.getFullPathName().toStdString(), take->file.getFileNameWithoutExtension().toStdString(), take->playThrough });
  1836. // FL: Loop record over a loop region, without a punch
  1837. const auto loopRecorded = recordOptions.loopRecord && ! keepPunch.has_value() && song.mode == PlayMode::song && song.loopPlays();
  1838. const takes::TakeOptions takeOptions { loopRecorded, recordOptions.mode == RecordMode::overdub, recordOptions.lastLoopPassPlays };
  1839. editSong ([made, parts, takeOptions] (Song& s) { takes::placeTakeClips (s, made, parts, takeOptions); });
  1840. dropJournals();
  1841. }
  1842. std::vector<takes::Journal> AudioEngine::recoverInterruptedTakes (const std::vector<juce::File>& folders)
  1843. {
  1844. // the journals listed as in progress, and any journal left in the given folders
  1845. juce::StringArray journals (juce::StringArray::fromLines (inProgressFile().loadFileAsString()));
  1846. auto where = folders;
  1847. where.push_back (defaultRecordingFolder());
  1848. for (const auto& folder : where)
  1849. for (const auto& f : folder.findChildFiles (juce::File::findFiles, false, "*.lynxrec"))
  1850. journals.addIfNotAlreadyThere (f.getFullPathName());
  1851. journals.removeEmptyStrings();
  1852. std::vector<takes::Journal> out;
  1853. for (const auto& path : journals)
  1854. {
  1855. const juce::File journal (path);
  1856. takes::Journal j;
  1857. if (! journal.existsAsFile() || ! takes::parseJournal (journal.loadFileAsString().toStdString(), j))
  1858. continue;
  1859. // (a take being recorded by this very session is not "interrupted")
  1860. if (std::any_of (openTakes.begin(), openTakes.end(), [&journal, this] (const std::shared_ptr<Take>& t) { return journalFor (t->file) == journal; }))
  1861. continue;
  1862. std::int64_t frames = 0;
  1863. if (! takes::repairWav (j.wav, &frames) || frames <= 0)
  1864. continue;
  1865. out.push_back (j);
  1866. }
  1867. return out;
  1868. }
  1869. int AudioEngine::placeRecoveredTakes (const std::vector<takes::Journal>& recovered)
  1870. {
  1871. struct One
  1872. {
  1873. takes::TakeFile file;
  1874. std::vector<takes::Part> parts;
  1875. };
  1876. std::vector<One> placed;
  1877. for (const auto& j : recovered)
  1878. {
  1879. std::int64_t frames = 0;
  1880. if (! takes::repairWav (j.wav, &frames) || frames <= 0)
  1881. continue;
  1882. const auto placement = takes::place (j.firstTick, (double) frames * j.ticksPerSample, j.ticksPerSample, j.latency);
  1883. if (! placement.valid())
  1884. continue;
  1885. const juce::File wav (juce::String::fromUTF8 (j.wav.c_str()));
  1886. placed.push_back ({ { j.wav, wav.getFileNameWithoutExtension().toStdString(), j.insert }, takes::punch (placement, {}) });
  1887. }
  1888. if (! placed.empty())
  1889. editSong ([placed] (Song& s) {
  1890. for (const auto& p : placed)
  1891. takes::placeTakeClips (s, { p.file }, p.parts);
  1892. });
  1893. forgetInterruptedTakes (recovered);
  1894. return (int) placed.size();
  1895. }
  1896. void AudioEngine::forgetInterruptedTakes (const std::vector<takes::Journal>& recovered)
  1897. {
  1898. juce::StringArray list (juce::StringArray::fromLines (inProgressFile().loadFileAsString()));
  1899. for (const auto& j : recovered)
  1900. {
  1901. const auto journal = journalFor (juce::File (juce::String::fromUTF8 (j.wav.c_str())));
  1902. journal.deleteFile();
  1903. list.removeString (journal.getFullPathName());
  1904. }
  1905. list.removeEmptyStrings();
  1906. if (deviceStateSaver != nullptr)
  1907. {
  1908. if (list.isEmpty())
  1909. inProgressFile().deleteFile();
  1910. else
  1911. inProgressFile().replaceWithText (list.joinIntoString ("\n"));
  1912. }
  1913. }
  1914. juce::File AudioEngine::defaultRecordingFolder()
  1915. {
  1916. return juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("LYNX/Recordings");
  1917. }
  1918. void AudioEngine::setRecordingTarget (const juce::File& folder, const juce::String& projectStem)
  1919. {
  1920. recordingFolder = folder == juce::File() ? defaultRecordingFolder() : folder;
  1921. recordingStem = projectStem;
  1922. }
  1923. void AudioEngine::forgetRecordings (const std::vector<juce::File>& files)
  1924. {
  1925. sessionRecordings.erase (std::remove_if (sessionRecordings.begin(), sessionRecordings.end(),
  1926. [&files] (const juce::File& f) { return std::find (files.begin(), files.end(), f) != files.end(); }),
  1927. sessionRecordings.end());
  1928. }
  1929. std::vector<std::string> AudioEngine::getInputChannelNames() const
  1930. {
  1931. std::vector<std::string> names;
  1932. if (auto* device = deviceManager.getCurrentAudioDevice(); device != nullptr && ! device->getActiveInputChannels().isZero())
  1933. for (const auto& n : device->getInputChannelNames())
  1934. if ((int) names.size() < LiveInput::maxChannels)
  1935. names.push_back (n.toStdString());
  1936. return names;
  1937. }
  1938. bool AudioEngine::hasAudioInput() const
  1939. {
  1940. auto* device = deviceManager.getCurrentAudioDevice();
  1941. return device != nullptr && ! device->getActiveInputChannels().isZero();
  1942. }
  1943. void AudioEngine::notify (InputIssue issue, int track, const juce::String& detail)
  1944. {
  1945. recordingNotice = { issue, track, detail };
  1946. sendChangeMessage();
  1947. }
  1948. AudioEngine::RecordingNotice AudioEngine::openAudioInput (const juce::String& deviceName)
  1949. {
  1950. auto* type = deviceManager.getCurrentDeviceTypeObject();
  1951. if (type == nullptr || deviceManager.getCurrentAudioDevice() == nullptr)
  1952. return { InputIssue::noDevice, 0, {} };
  1953. auto setup = deviceManager.getAudioDeviceSetup();
  1954. int count = 0;
  1955. if (type->hasSeparateInputsAndOutputs())
  1956. {
  1957. // Windows Audio / DirectSound: the input is a device of its own
  1958. const auto inputs = type->getDeviceNames (true);
  1959. auto name = deviceName.isNotEmpty() ? deviceName : setup.inputDeviceName;
  1960. if (name.isEmpty())
  1961. name = releasedInputDevice; // the one releaseAudioInputIfUnused closed
  1962. if (! inputs.contains (name))
  1963. {
  1964. const auto index = type->getDefaultDeviceIndex (true);
  1965. name = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  1966. }
  1967. if (name.isEmpty())
  1968. return { InputIssue::noInputDevice, 0, {} };
  1969. auto* current = deviceManager.getCurrentAudioDevice();
  1970. if (name == setup.inputDeviceName && ! current->getActiveInputChannels().isZero())
  1971. count = current->getInputChannelNames().size();
  1972. else if (std::unique_ptr<juce::AudioIODevice> probe (type->createDevice ({}, name)); probe != nullptr)
  1973. count = probe->getInputChannelNames().size();
  1974. setup.inputDeviceName = name;
  1975. }
  1976. else
  1977. {
  1978. // ASIO: one device does both; its input channels come in pairs in the mixer
  1979. count = deviceManager.getCurrentAudioDevice()->getInputChannelNames().size();
  1980. setup.inputDeviceName = setup.outputDeviceName;
  1981. }
  1982. if (count <= 0)
  1983. count = 2;
  1984. count = juce::jmin (count, (int) LiveInput::maxChannels);
  1985. juce::BigInteger wanted;
  1986. wanted.setRange (0, count, true);
  1987. if (! setup.useDefaultInputChannels && setup.inputChannels == wanted && ! deviceManager.getCurrentAudioDevice()->getActiveInputChannels().isZero())
  1988. return {};
  1989. setup.useDefaultInputChannels = false;
  1990. setup.inputChannels = wanted;
  1991. const auto error = deviceManager.setAudioDeviceSetup (setup, true);
  1992. sendChangeMessage();
  1993. if (error.isNotEmpty())
  1994. return { InputIssue::failed, 0, error };
  1995. if (! hasAudioInput())
  1996. return { InputIssue::noInputDevice, 0, {} };
  1997. return {};
  1998. }
  1999. bool AudioEngine::audioInputNeeded() const
  2000. {
  2001. if (audioArmed || ! armedInserts.empty() || hwinsert::returnsFromInput (song))
  2002. return true;
  2003. return std::any_of (song.mixer.begin(), song.mixer.end(), [] (const MixerTrack& t) { return t.inputChannel >= 0 || t.flInput >= 0; });
  2004. }
  2005. void AudioEngine::releaseAudioInputIfUnused()
  2006. {
  2007. if (! hasAudioInput() || audioInputNeeded())
  2008. return;
  2009. auto* type = deviceManager.getCurrentDeviceTypeObject();
  2010. auto setup = deviceManager.getAudioDeviceSetup();
  2011. setup.useDefaultInputChannels = false;
  2012. setup.inputChannels.clear();
  2013. // a driver with separate input devices (Windows Audio) keeps capturing while an input device is set, even with
  2014. // no channel active: the device goes too (its name is remembered for the next openAudioInput)
  2015. if (type != nullptr && type->hasSeparateInputsAndOutputs() && setup.inputDeviceName.isNotEmpty())
  2016. {
  2017. releasedInputDevice = setup.inputDeviceName;
  2018. setup.inputDeviceName = {};
  2019. }
  2020. deviceManager.setAudioDeviceSetup (setup, true);
  2021. sendChangeMessage();
  2022. }
  2023. void AudioEngine::setInsertInput (int track, int channel, bool stereo)
  2024. {
  2025. if (track < 0 || track >= (int) song.mixer.size()) // (the Master too: REA round 143)
  2026. return;
  2027. editSong ([=] (Song& s) {
  2028. s.mixer[(std::size_t) track].inputChannel = channel;
  2029. s.mixer[(std::size_t) track].inputStereo = stereo;
  2030. });
  2031. recordingError = {};
  2032. if (channel >= 0 && ! hasAudioInput())
  2033. if (const auto result = openAudioInput(); result.issue != InputIssue::none)
  2034. notify (result.issue, track, result.detail);
  2035. }
  2036. void AudioEngine::setInsertMonitor (int track, InputMonitor mode)
  2037. {
  2038. if (track >= 0 && track < (int) song.mixer.size())
  2039. editSong ([=] (Song& s) { s.mixer[(std::size_t) track].monitor = mode; });
  2040. }
  2041. void AudioEngine::setInsertRecordSource (int track, RecordSource source)
  2042. {
  2043. if (track > 0 && track < (int) song.mixer.size() && song.mixer[(std::size_t) track].recordSource != source)
  2044. editSong ([=] (Song& s) { s.mixer[(std::size_t) track].recordSource = source; });
  2045. }
  2046. void AudioEngine::setInsertRecordDryToo (int track, bool on)
  2047. {
  2048. if (track > 0 && track < (int) song.mixer.size() && song.mixer[(std::size_t) track].recordDryToo != on)
  2049. editSong ([=] (Song& s) { s.mixer[(std::size_t) track].recordDryToo = on; });
  2050. }
  2051. void AudioEngine::handleIncomingMidiMessage (juce::MidiInput* source, const juce::MidiMessage& m)
  2052. {
  2053. // MIDI thread: queues and atomics only (and a short copy of the device settings)
  2054. prefs::MidiInputPrefs device;
  2055. auto velocityCurve = prefs::VelocityCurve::linear;
  2056. auto locked = -1; // a channel that "receives notes from" this device (FL's channel lock)
  2057. auto jumpChannel = 0;
  2058. const auto deviceName = source != nullptr ? source->getName().toStdString() : std::string();
  2059. {
  2060. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  2061. const auto& name = deviceName;
  2062. device = midiPrefsShared.input (name);
  2063. velocityCurve = midiPrefsShared.velocity;
  2064. const auto midiChannel = m.getChannel();
  2065. for (const auto& l : noteLocks)
  2066. if (l.device == name && (l.midiChannel == 0 || l.midiChannel == midiChannel))
  2067. {
  2068. locked = l.channel;
  2069. if (l.midiChannel != 0)
  2070. break; // a lock on this very MIDI channel wins over one on any channel
  2071. }
  2072. jumpChannel = midiPrefsShared.songMarkerJumpChannel;
  2073. }
  2074. if (locked >= 0)
  2075. device.target = locked;
  2076. if (! device.enabled)
  2077. return;
  2078. // the external clock LYNX follows (round 165f): clock, start / stop / continue, song position
  2079. if (m.getRawDataSize() > 0 && (m.getRawData()[0] >= 0xf2) && source != nullptr && midiSync.handleInput (source->getName(), m))
  2080. return;
  2081. midiActivity.fetch_add (1, std::memory_order_relaxed); // the toolbar's MIDI input light
  2082. if (m.getRawDataSize() > 0 && prefs::midiMeansPlaying (m.getRawData()[0]))
  2083. midiPlayed.fetch_add (1, std::memory_order_relaxed); // what holds a backup back (not clock or active sensing)
  2084. // FL's "Song marker jump (MIDI channel)": notes on that channel move the song to a marker instead of playing
  2085. if (jumpChannel > 0 && m.getChannel() == jumpChannel && m.isNoteOnOrOff())
  2086. {
  2087. if (m.isNoteOn())
  2088. pendingMarkerNote.store (m.getNoteNumber());
  2089. return;
  2090. }
  2091. // FL's playlist live mode channel (round 165m): its notes launch the performance clips instead of playing
  2092. if (const auto pc = performanceMidiChannel.load (std::memory_order_relaxed);
  2093. pc != 0 && m.getChannel() == pc && m.isNoteOnOrOff() && performanceMidiOn.load (std::memory_order_relaxed))
  2094. {
  2095. perf::Command c;
  2096. if (performanceMidi.note (m.getNoteNumber(), m.isNoteOn(), c))
  2097. performanceLive->midiCommands.push (c);
  2098. return;
  2099. }
  2100. // FL's note links (round 190cs; controller number 256 + key): a linked key moves its control instead of playing
  2101. if (m.isNoteOnOrOff())
  2102. {
  2103. const auto key = m.getNoteNumber();
  2104. const auto value = m.isNoteOn() ? (int) m.getVelocity() : 0;
  2105. if ((linkedNotes[(std::size_t) (key >> 6)].load (std::memory_order_relaxed) >> (key & 63) & 1u) != 0)
  2106. {
  2107. controllerQueue.push ({ linkNoteBase + key, m.getChannel() - 1, value, device.port });
  2108. return;
  2109. }
  2110. if (value > 0) // (and offered to the link window's Auto detect)
  2111. controllerQueue.push ({ linkNoteBase + key, m.getChannel() - 1, value, device.port, true });
  2112. }
  2113. // a controller profile's buttons, knobs and faders (round 190aw): to the message thread, not into the instruments.
  2114. // Controllers linked by hand stay with their links.
  2115. if (source != nullptr && controllerIo.take (deviceName, m.getRawData(), m.getRawDataSize(), linkedCcs))
  2116. {
  2117. if (m.isController()) // (still offered to MIDI learn)
  2118. controllerQueue.push ({ m.getControllerNumber(), m.getChannel() - 1, m.getControllerValue(), device.port });
  2119. return;
  2120. }
  2121. // issue #108: an MPE controller (the device's MPE setting). Its member channels' pitch bend, CC 74 and pressure
  2122. // belong to the notes on them: a sounding note's expression goes to the channels its note on reached, a note on /
  2123. // off carries the note's own values (played, and recorded as the note's fine pitch, Mod X and Mod Y). Everything
  2124. // else (the master channel, other controllers) is handled as from any controller. No channel filter in this mode.
  2125. mpe::InEvent mpeEvents[mpe::Input::maxEvents];
  2126. const mpe::InEvent* mpeNote = nullptr;
  2127. if (device.mpe)
  2128. {
  2129. if (const mpe::Zone zone { true, device.mpeMembers, (float) device.mpeBendRange }; ! (zone == mpeZone))
  2130. {
  2131. mpeZone = zone;
  2132. mpeInput.setZone (zone);
  2133. }
  2134. const auto count = mpeInput.feed (m.getRawData(), m.getRawDataSize(), mpeEvents);
  2135. if (count == 0)
  2136. return; // (the zone's own configuration)
  2137. if (mpeEvents[0].type == mpe::InEvent::Type::expr)
  2138. {
  2139. for (int k = 0; k < count; ++k)
  2140. {
  2141. const auto& x = mpeEvents[k];
  2142. InputHeldNotes::Target to[InputHeldNotes::maxTargets];
  2143. const auto n = midiHeld.targetsOf (x.key, to);
  2144. for (int i = 0; i < n; ++i)
  2145. {
  2146. NoteEvent e;
  2147. e.type = NoteEvent::Type::voiceProp;
  2148. e.expression = true;
  2149. e.channel = to[i].channel;
  2150. e.key = to[i].key;
  2151. e.prop = (std::uint8_t) (x.expr == mpe::Expr::pitch ? vfx::Prop::pitch : x.expr == mpe::Expr::timbre ? vfx::Prop::modX : vfx::Prop::modY);
  2152. e.velocity = x.expr == mpe::Expr::pressure ? mpe::modYOfPressure (x.value) : x.value;
  2153. if (e.channel >= 0)
  2154. midiEvents.push (e);
  2155. }
  2156. }
  2157. return;
  2158. }
  2159. if (mpeEvents[0].type != mpe::InEvent::Type::plain)
  2160. mpeNote = &mpeEvents[0];
  2161. }
  2162. else if (device.midiChannel != 0 && m.getChannel() != device.midiChannel)
  2163. return;
  2164. // the pitch wheel, the mod wheel and the other controllers play into the channels the notes go to (round 162,
  2165. // issue #9: they did nothing unless linked): hosted plugins get the MIDI message, LYNX's instruments bend by the
  2166. // channel's pitch range. A CC with a MIDI link only moves its parameter.
  2167. const auto recordBend = transport.recording.load() && transport.playing.load();
  2168. const auto bendTick = recordBend ? estimatedPositionNow() : 0.0;
  2169. auto playControl = [this, &device, &m, recordBend, bendTick] (int control, float value) {
  2170. NoteEvent e;
  2171. e.type = NoteEvent::Type::control;
  2172. e.key = control;
  2173. e.velocity = value;
  2174. auto send = [&] {
  2175. midiEvents.push (e);
  2176. // recording: the wheel is written too (the channel's pitch bend lane / automation clip, like FL)
  2177. if (recordBend && control == NoteEvent::controlPitchBend)
  2178. bendRecordQueue.push ({ bendTick, e.channel, juce::jlimit (0, 15, m.getChannel() - 1), (value + 1.0f) * 0.5f, true });
  2179. };
  2180. const auto extra = juce::jlimit (0, maxLiveChannels, extraLiveCount.load());
  2181. if (device.target >= 0)
  2182. {
  2183. e.channel = device.target;
  2184. send();
  2185. return;
  2186. }
  2187. for (int i = -1; i < extra; ++i)
  2188. {
  2189. e.channel = i < 0 ? liveChannel.load() : extraLiveChannels[(std::size_t) i].load();
  2190. if (e.channel >= 0)
  2191. send();
  2192. }
  2193. };
  2194. if (m.isController())
  2195. {
  2196. const auto cc = m.getControllerNumber();
  2197. controllerQueue.push ({ cc, m.getChannel() - 1, m.getControllerValue(), device.port });
  2198. // FL's "Foot pedal controls note off" (round 187a [DECOMP FUN_00fdb260]): with it on, CC 64 / CC 66 hold the
  2199. // played channels' notes and don't reach the plugins
  2200. if (const auto mode = PedalHold::modeFor (cc, m.getControllerValue()); mode >= 0 && footPedalNoteOff.load (std::memory_order_relaxed))
  2201. {
  2202. const auto now = juce::Time::getMillisecondCounterHiRes();
  2203. const auto stamped = m.getTimeStamp() * 1000.0;
  2204. const auto tick = recordTickFor (std::abs (stamped - now) < 1000.0 ? stamped : now);
  2205. const auto taking = transport.recording.load() && (transport.playing.load() || isCountingIn());
  2206. auto pedal = [&] (int channel) {
  2207. pedalHold.setMode (channel, mode, [&] (int key) {
  2208. NoteEvent e;
  2209. e.type = NoteEvent::Type::off;
  2210. e.channel = channel;
  2211. e.key = key;
  2212. midiEvents.push (e);
  2213. logPlayedNote (channel, key, 0.0f, false, transport.playing.load() ? tick : -1.0, taking);
  2214. if (taking) // (the recorded note lasts until the pedal comes up, as in FL)
  2215. midiRecordQueue.push ({ tick, channel, key, 0.0f, false });
  2216. });
  2217. };
  2218. if (device.target >= 0)
  2219. pedal (device.target);
  2220. else
  2221. {
  2222. const auto extra = juce::jlimit (0, maxLiveChannels, extraLiveCount.load());
  2223. for (int i = -1; i < extra; ++i)
  2224. if (const auto channel = i < 0 ? liveChannel.load() : extraLiveChannels[(std::size_t) i].load(); channel >= 0)
  2225. pedal (channel);
  2226. }
  2227. return;
  2228. }
  2229. // (120…127 are channel mode messages: All Sound / Notes Off, reset…)
  2230. if (cc >= 0 && cc < 120 && (linkedCcs[(std::size_t) (cc >> 6)].load (std::memory_order_relaxed) >> (cc & 63) & 1u) == 0)
  2231. playControl (cc, (float) m.getControllerValue() / 127.0f);
  2232. return;
  2233. }
  2234. if (m.isPitchWheel())
  2235. {
  2236. playControl (NoteEvent::controlPitchBend, juce::jlimit (-1.0f, 1.0f, (float) (m.getPitchWheelValue() - 8192) / 8192.0f));
  2237. return;
  2238. }
  2239. if (m.isChannelPressure())
  2240. {
  2241. playControl (NoteEvent::controlPressure, (float) m.getChannelPressureValue() / 127.0f);
  2242. return;
  2243. }
  2244. if (m.isProgramChange()) // (round 165c: the selected channel's plugin / VFX Sequencer, as FL passes it on)
  2245. {
  2246. playControl (NoteEvent::controlProgram, (float) m.getProgramChangeNumber() / 127.0f);
  2247. return;
  2248. }
  2249. if (! m.isNoteOnOrOff())
  2250. return;
  2251. const auto on = m.isNoteOn();
  2252. markHeldKey (m.getChannel() - 1, m.getNoteNumber(), on);
  2253. if (on)
  2254. startOnInput();
  2255. // a note-off goes to the channels and key its note-on reached (the selection or the scale snap may have
  2256. // changed while the key was down); a repeated note-on first stops what the previous one started
  2257. InputHeldNotes::Target targets[InputHeldNotes::maxTargets], stale[InputHeldNotes::maxTargets];
  2258. auto count = 0;
  2259. auto staleCount = 0;
  2260. if (on)
  2261. {
  2262. const auto key = snapInputKey (m.getNoteNumber());
  2263. const auto extra = juce::jlimit (0, maxLiveChannels, extraLiveCount.load());
  2264. // the primary selected channel, then the other selected ones (or the device's own channel)
  2265. if (device.target >= 0)
  2266. targets[count++] = { device.target, key };
  2267. else
  2268. for (int i = -1; i < extra && count < InputHeldNotes::maxTargets; ++i)
  2269. targets[count++] = { i < 0 ? liveChannel.load() : extraLiveChannels[(std::size_t) i].load(), key };
  2270. staleCount = midiHeld.noteOn (m.getNoteNumber(), targets, count, stale);
  2271. }
  2272. else
  2273. count = midiHeld.noteOff (m.getNoteNumber(), targets);
  2274. // the time the device stamped the message with (JUCE: getMillisecondCounterHiRes / 1000), not when this thread got
  2275. // to it; a stamp from elsewhere (0, another clock) falls back to now (round 170d)
  2276. const auto now = juce::Time::getMillisecondCounterHiRes();
  2277. const auto stamped = m.getTimeStamp() * 1000.0;
  2278. const auto eventMs = std::abs (stamped - now) < 1000.0 ? stamped : now;
  2279. const auto taking = transport.recording.load() && (transport.playing.load() || isCountingIn());
  2280. const auto tick = recordTickFor (eventMs);
  2281. auto push = [this, taking, tick, mpeNote] (const InputHeldNotes::Target& t, bool noteOn, float velocity) {
  2282. NoteEvent e;
  2283. e.type = noteOn ? NoteEvent::Type::on : NoteEvent::Type::off;
  2284. e.channel = t.channel;
  2285. e.key = t.key;
  2286. e.velocity = velocity;
  2287. if (mpeNote != nullptr && noteOn) // issue #108: the note starts at its own bend, timbre and pressure
  2288. {
  2289. e.expression = true;
  2290. e.cents = mpeNote->cents;
  2291. e.modX = mpeNote->timbre;
  2292. e.modY = mpe::modYOfPressure (mpeNote->pressure);
  2293. }
  2294. midiEvents.push (e);
  2295. logPlayedNote (e.channel, e.key, e.velocity, noteOn, transport.playing.load() ? tick : -1.0, taking);
  2296. // (round 170d: during the count-in too; the time is the device's, against the audio clock)
  2297. if (taking && mpeNote != nullptr) // (the "on": its bend and timbre; the "off": its peak pressure)
  2298. midiRecordQueue.push ({ tick, e.channel, e.key, e.velocity, noteOn, true, mpe::finePitchOfCents (mpeNote->cents), mpeNote->timbre,
  2299. mpe::modYOfPressure (mpeNote->pressure) });
  2300. else if (taking)
  2301. midiRecordQueue.push ({ tick, e.channel, e.key, e.velocity, noteOn });
  2302. if (slotTaking.load (std::memory_order_relaxed)) // a slot of the clip grid records (round 190bv)
  2303. slotRecordQueue.push ({ tick, e.channel, e.key, e.velocity, noteOn });
  2304. };
  2305. for (int i = 0; i < staleCount; ++i)
  2306. push (stale[i], false, 0.0f);
  2307. // round 190ao: a hosted instrument with its own velocity setting answers with it instead of the MIDI settings' curve
  2308. std::uint16_t ownVelocity[InputHeldNotes::maxTargets] {};
  2309. if (on)
  2310. {
  2311. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  2312. for (int i = 0; i < count; ++i)
  2313. if (targets[i].channel >= 0 && targets[i].channel < (int) channelVelocity.size())
  2314. ownVelocity[i] = channelVelocity[(std::size_t) targets[i].channel];
  2315. }
  2316. for (int i = 0; i < count; ++i)
  2317. {
  2318. // the foot pedal (round 187a): a held note struck again is released first; a note-off it holds waits for it
  2319. if (on && pedalHold.noteOn (targets[i].channel, targets[i].key))
  2320. push (targets[i], false, 0.0f);
  2321. if (! on && pedalHold.noteOff (targets[i].channel, targets[i].key))
  2322. continue;
  2323. push (targets[i], on, on ? prefs::mapPluginVelocity (m.getFloatVelocity(), ownVelocity[i] & 0xff, ownVelocity[i] >> 8, velocityCurve) : 0.0f);
  2324. }
  2325. }
  2326. void AudioEngine::enableAllMidiInputs()
  2327. {
  2328. // (a device turned off in the MIDI settings is closed, so other programs can use it)
  2329. std::vector<prefs::MidiPort> available;
  2330. std::vector<std::string> open;
  2331. for (const auto& device : juce::MidiInput::getAvailableDevices())
  2332. {
  2333. available.push_back ({ device.identifier.toStdString(), device.name.toStdString() });
  2334. if (deviceManager.isMidiInputDeviceEnabled (device.identifier))
  2335. open.push_back (device.identifier.toStdString());
  2336. }
  2337. const auto plan = prefs::planMidiInputs (midiPrefs, available, lastMidiInputIds, open);
  2338. for (const auto& id : plan.close)
  2339. deviceManager.setMidiInputDeviceEnabled (juce::String (id), false);
  2340. for (const auto& id : plan.reopen) // it went away and came back: the old handle may be dead
  2341. deviceManager.setMidiInputDeviceEnabled (juce::String (id), false);
  2342. for (const auto* list : { &plan.reopen, &plan.open })
  2343. for (const auto& id : *list)
  2344. deviceManager.setMidiInputDeviceEnabled (juce::String (id), true);
  2345. lastMidiInputIds.clear();
  2346. for (const auto& port : available)
  2347. lastMidiInputIds.push_back (port.id);
  2348. // the devices that run a controller profile (round 190aw)
  2349. std::vector<std::string> names;
  2350. for (const auto& port : available)
  2351. names.push_back (port.name);
  2352. controllerIo.configure (midiPrefs, names, true);
  2353. }
  2354. void AudioEngine::setControllerSurface (controller::Surface* surface) { controllerIo.setSurface (surface); }
  2355. juce::File AudioEngine::controllerProfilesFolder() { return PluginHost::settingsFolder().getChildFile ("Controllers"); }
  2356. void AudioEngine::reloadControllerProfiles()
  2357. {
  2358. controllerIo.loadProfiles (controllerProfilesFolder());
  2359. if (prefetcher != nullptr)
  2360. enableAllMidiInputs();
  2361. sendChangeMessage();
  2362. }
  2363. void AudioEngine::reconnectMidiInputs()
  2364. {
  2365. if (prefetcher == nullptr) // (only with an audio device: the real app)
  2366. return;
  2367. for (const auto& device : juce::MidiInput::getAvailableDevices())
  2368. if (deviceManager.isMidiInputDeviceEnabled (device.identifier))
  2369. deviceManager.setMidiInputDeviceEnabled (device.identifier, false);
  2370. enableAllMidiInputs();
  2371. }
  2372. void AudioEngine::setMidiPrefs (const prefs::MidiPrefs& p, bool save)
  2373. {
  2374. midiPrefs = p;
  2375. {
  2376. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  2377. midiPrefsShared = p;
  2378. }
  2379. performanceMidiChannel.store (p.performanceChannel);
  2380. footPedalNoteOff.store (p.footPedalNoteOff);
  2381. if (! p.pickup)
  2382. pickups.clear();
  2383. if (prefetcher != nullptr) // (only with an audio device: the real app)
  2384. {
  2385. enableAllMidiInputs();
  2386. midiSync.configure (p);
  2387. }
  2388. if (save)
  2389. midiSettingsFile().replaceWithText (juce::String (p.toText()));
  2390. sendChangeMessage();
  2391. }
  2392. void AudioEngine::setUndoLevels (int levels)
  2393. {
  2394. maxUndoSteps = (std::size_t) prefs::clampUndoLevels (levels);
  2395. while (undoStack.size() > maxUndoSteps)
  2396. undoStack.pop_front();
  2397. }
  2398. juce::StringArray AudioEngine::getActiveMidiInputs() const
  2399. {
  2400. juce::StringArray names;
  2401. for (const auto& device : juce::MidiInput::getAvailableDevices())
  2402. if (deviceManager.isMidiInputDeviceEnabled (device.identifier))
  2403. names.add (device.name);
  2404. return names;
  2405. }
  2406. void AudioEngine::setAudioRecordingArmed (bool armed)
  2407. {
  2408. audioArmed = armed;
  2409. recordingError = {};
  2410. if (armed)
  2411. {
  2412. // opens the input of the current driver (every channel, so each insert can pick its own)
  2413. if (! hasAudioInput())
  2414. if (const auto result = openAudioInput(); result.issue != InputIssue::none)
  2415. {
  2416. recordingError = "no audio input";
  2417. notify (result.issue, 0, result.detail);
  2418. }
  2419. if (! recordThread.isThreadRunning())
  2420. recordThread.startThread();
  2421. }
  2422. sendChangeMessage();
  2423. }
  2424. void AudioEngine::setRecording (bool shouldRecord)
  2425. {
  2426. if (shouldRecord && ! transport.recording.load())
  2427. recordingError = {}; // a new attempt
  2428. transport.recording.store (shouldRecord);
  2429. liveInput.recording.store (shouldRecord);
  2430. updateRecording();
  2431. sendChangeMessage();
  2432. }
  2433. bool AudioEngine::cancelRecording()
  2434. {
  2435. if (! transport.recording.load())
  2436. return false;
  2437. // FL [DECOMP 0xf1d7e0]: the recorded-event buffers are emptied, every disk-recording take is dropped and its track
  2438. // re-armed, the record button is released; playback is not stopped. LYNX writes a take into the song as it goes, so
  2439. // the pass's edits are undone instead (one undo step per take; a step the user made while recording goes too).
  2440. updateRecording(); // (what was played up to now, and the start of this pass if the timer hasn't seen it yet)
  2441. const auto armed = armedInserts;
  2442. const auto inPass = recordPassActive && recordPassMarked; // (record on but stopped: the last pass is already kept)
  2443. discardAudioTakes = true;
  2444. setRecording (false); // (the takes close here: the notes still held are committed, the audio files deleted)
  2445. discardAudioTakes = false;
  2446. for (const auto t : armed)
  2447. if (std::find (armedInserts.begin(), armedInserts.end(), t) == armedInserts.end())
  2448. setInsertArmed (t, true);
  2449. if (inPass && ! sessionHistory)
  2450. {
  2451. const auto made = undoStack.size() + recordPassTrimmed;
  2452. const auto steps = made > recordPassUndoBase ? made - recordPassUndoBase : 0;
  2453. for (std::size_t i = 0; i < steps && ! undoStack.empty(); ++i)
  2454. {
  2455. undo();
  2456. if (! redoStack.empty())
  2457. redoStack.pop_back(); // (nothing to redo: the pass is gone)
  2458. }
  2459. }
  2460. recordPassMarked = false;
  2461. sendChangeMessage();
  2462. return true;
  2463. }
  2464. void AudioEngine::updateRecording()
  2465. {
  2466. const auto playing = transport.playing.load();
  2467. // FL's "Disarm on stop" (round 166e): the record switch goes off once playback stops after recording
  2468. if (recordSwitch.update (playing, transport.recording.load(), recordOptions.recordOffOnStop))
  2469. {
  2470. transport.recording.store (false);
  2471. liveInput.recording.store (false);
  2472. sendChangeMessage();
  2473. }
  2474. // (round 170d: a take starts with its count-in, so the notes played during it are kept)
  2475. const auto counting = isCountingIn();
  2476. const auto active = transport.recording.load() && (playing || counting);
  2477. // a recording pass starts: what Cancel recording goes back to (round 187a)
  2478. if (active && ! recordPassActive)
  2479. {
  2480. recordPassMarked = true;
  2481. recordPassUndoBase = undoStack.size();
  2482. recordPassTrimmed = 0;
  2483. }
  2484. recordPassActive = active;
  2485. if (playing)
  2486. lastPlayingTick = estimatedPositionNow();
  2487. else if (counting && takeCatch.start >= 0)
  2488. lastPlayingTick = (double) takeCatch.start;
  2489. // the take starts when playing with recording on, or at the first recorded event
  2490. // (which is only queued in that situation, even if this timer hasn't seen it yet)
  2491. auto beginTake = [this] (double at) {
  2492. if (recorder.isActive())
  2493. return;
  2494. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  2495. recorder.begin (pattern.effectiveLength (song.beatsPerBar));
  2496. // Pattern mode with Loop record off (round 170e5, FL's "never" play end [DECOMP 0x11d4800]): the pattern plays
  2497. // once from the start of this pass and on past its end; the notes stay where they were played, so it grows
  2498. if (recordloop::patternLinear (song.mode, recordOptions.loopRecord))
  2499. {
  2500. const auto origin = recordloop::patternOrigin (at, pattern.effectiveLength (song.beatsPerBar));
  2501. recorder.setPatternOrigin (origin);
  2502. liveInput.patternOrigin.store (origin);
  2503. }
  2504. takeHasUndoStep = false;
  2505. takeClearedChannels.clear();
  2506. // Song mode without a loop region: while recording, the song plays on past its end until recording stops (FL,
  2507. // round 168k [EXEC]: a 1-bar song recorded from bar 1 counted on to bar 8 instead of going back to bar 1), so
  2508. // the notes stay where they were played
  2509. // (Loop record off, round 170e3: through the loop region as well)
  2510. if (recordloop::notesLinear (song.mode, song.loopPlays(), recordOptions.loopRecord))
  2511. {
  2512. noteTakeLinear = true;
  2513. recorder.setLinear (true);
  2514. updateLinearSong();
  2515. }
  2516. };
  2517. if (active)
  2518. beginTake (lastPlayingTick);
  2519. RecordedEvent e;
  2520. // FL's "Enable recording markers" (song mode): a note that starts outside the Start / Stop recording ranges is
  2521. // not recorded (its release finds no held note and is ignored too)
  2522. const auto punch = activePunch.has_value() ? std::vector<PunchRange> { *activePunch } // pre-roll / punch in-out (round 163)
  2523. : recordOptions.recordingMarkers && song.mode == PlayMode::song ? punchRanges (song.markers()) : std::vector<PunchRange> {};
  2524. auto outsidePunch = [this, &punch] (const RecordedEvent& ev) {
  2525. if (punch.empty() || ! ev.on)
  2526. return false;
  2527. auto tick = ev.tick;
  2528. if (! song.loopPlays() && ! noteTakeLinear)
  2529. tick = std::fmod (std::max (0.0, tick), (double) std::max<std::int64_t> (1, song.songLength()));
  2530. return ! inPunchRanges (punch, tick);
  2531. };
  2532. while (midiRecordQueue.pop (e))
  2533. {
  2534. // (count-in notes: onto the start within the catch window, else at their real time; round 170d)
  2535. if (! recordOptions.recordNotes || ! catchEarlyNote (e, takeCatch) || outsidePunch (e)) // recording filter: notes off
  2536. continue;
  2537. beginTake (std::min (lastPlayingTick, e.tick));
  2538. recorder.add (song, e);
  2539. }
  2540. for (auto ui : uiRecorded)
  2541. {
  2542. if (! recordOptions.recordNotes || ! catchEarlyNote (ui, takeCatch) || outsidePunch (ui))
  2543. continue;
  2544. beginTake (std::min (lastPlayingTick, ui.tick));
  2545. recorder.add (song, ui);
  2546. }
  2547. uiRecorded.clear();
  2548. updateAudioRecording();
  2549. takeRecordedBends();
  2550. updateAutomationRecording (active);
  2551. if (! active && recorder.isActive())
  2552. recorder.end (song, lastPlayingTick);
  2553. if (! active && ! counting)
  2554. takeCatch = {}; // the take is over: its catch with it
  2555. auto notes = recorder.takeFinished();
  2556. if (! recorder.isActive() && std::exchange (noteTakeLinear, false))
  2557. updateLinearSong();
  2558. if (! recorder.isActive() && liveInput.patternOrigin.load (std::memory_order_relaxed) >= 0.0)
  2559. liveInput.patternOrigin.store (-1.0); // the take is over: the pattern loops again
  2560. if (notes.empty())
  2561. return;
  2562. // the whole take is a single undo step: overdub or replace, quantised to the record grid; in song mode the notes
  2563. // go where they were played and a clip of the pattern is placed from the bar of the take's first note (FL; round
  2564. // 168k: they used to fold into the pattern's first bars)
  2565. const auto options = recordOptions;
  2566. editSong ([&] (Song& s) {
  2567. TakeQuantize q;
  2568. q.grid = options.quantise;
  2569. q.starts = options.quantiseStarts;
  2570. q.end = options.noteEnd;
  2571. q.stepSequencer = options.toStepSequencer;
  2572. commitNoteBatch (s, recorder, std::move (notes), options.mode, q, takeClearedChannels, options.placeSongClip, ! takeHasUndoStep);
  2573. }, ! takeHasUndoStep);
  2574. takeHasUndoStep = true;
  2575. }
  2576. void AudioEngine::launcherCommand (const launcher::Command& command)
  2577. {
  2578. if (clipLauncher == nullptr || ! song.clipGrid)
  2579. return;
  2580. using T = launcher::Command::Type;
  2581. const auto starts = command.type == T::launch || command.type == T::launchScene || command.type == T::record;
  2582. if (! transport.playing.load() && ! starts && command.type != T::backToArrangement && command.type != T::reset
  2583. && command.type != T::recordEnd) // (a recordEnd while stopped cancels a recording that never began)
  2584. return;
  2585. if (starts && song.mode != PlayMode::song) // the grid plays with the song
  2586. editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  2587. // a scene with its own tempo and bar length: the song takes them when it is launched
  2588. if (command.type == T::launchScene && command.scene >= 0 && command.scene < (int) song.clipGrid->scenes.size())
  2589. if (const auto& scene = song.clipGrid->scenes[(std::size_t) command.scene]; scene.tempo > 0.0 || scene.beatsPerBar > 0)
  2590. editSong ([tempo = scene.tempo, bar = scene.beatsPerBar] (Song& s) {
  2591. if (tempo > 0.0)
  2592. s.bpm = tempo;
  2593. if (bar > 0)
  2594. s.beatsPerBar = bar;
  2595. }, false);
  2596. if (starts && ! transport.playing.load() && ! isCountingIn())
  2597. {
  2598. // a recording into a slot counts in first, as the record options say (round 190bv)
  2599. if (command.type == T::record && recordOptions.countInBars > 0)
  2600. transport.countIn.store ((double) countInLength (song, recordOptions.countInBars, (std::int64_t) transport.positionTicks.load()));
  2601. else
  2602. play();
  2603. sendChangeMessage();
  2604. }
  2605. clipLauncher->commands.push (command);
  2606. }
  2607. void AudioEngine::setSongWithPluginsOff (Song newSong)
  2608. {
  2609. holdPlugins();
  2610. pluginHoldOwner.store (nullptr); // (so the setSong below does not end it)
  2611. setSong (std::move (newSong));
  2612. pluginHoldOwner.store (this);
  2613. }
  2614. bool AudioEngine::pluginsOff() const { return pluginsHeld() && pluginHoldOwner.load() == this; }
  2615. std::vector<pluginhold::Use> AudioEngine::hostedPluginUses() const
  2616. {
  2617. return pluginhold::uses (song, pluginsOff() ? pluginHoldState() : pluginhold::State());
  2618. }
  2619. int AudioEngine::switchPluginOn (const std::string& id)
  2620. {
  2621. if (! pluginsOff())
  2622. return 0;
  2623. // the plugins already running keep what was set in them since the last save (a Patcher that holds one of them and
  2624. // the plugin switched on now is built again from the project)
  2625. capturePluginStates();
  2626. if (id.empty())
  2627. endPluginHold();
  2628. else
  2629. releasePlugin (id);
  2630. const auto slots = pluginhold::slotsOf (song, id);
  2631. if (! id.empty() && pluginhold::countOff (song, pluginHoldState()) == 0)
  2632. endPluginHold(); // the last one: the mode is over
  2633. if (! pluginsHeld())
  2634. pluginHoldOwner.store (nullptr);
  2635. plugins.clearLoadFailures();
  2636. // this one build creates the plugin's slots anew (they hold the silent placeholders of when it was off)
  2637. rebuildPluginId = id;
  2638. rebuildPlugins = true;
  2639. publishSong();
  2640. rebuildPlugins = false;
  2641. rebuildPluginId.clear();
  2642. return slots;
  2643. }
  2644. void AudioEngine::setSong (Song newSong)
  2645. {
  2646. // round 190ap: another project in the engine that was opened without third-party plugins: the mode ends
  2647. if (pluginHoldOwner.load() == this)
  2648. {
  2649. pluginHoldOwner.store (nullptr);
  2650. endPluginHold();
  2651. }
  2652. if (clipLauncher != nullptr)
  2653. clipLauncher->commands.push ({ launcher::Command::Type::reset });
  2654. undoStack.clear();
  2655. redoStack.clear();
  2656. sessionUndo.clear();
  2657. sessionRedo.clear();
  2658. sessionAfterOpen = false;
  2659. song = std::move (newSong);
  2660. workSince = (double) juce::Time::currentTimeMillis();
  2661. flsettings::forgetSolos(); // (round 190bx: a solo's remembered mute states belong to the project that had it)
  2662. clipops::updateCrossfades (song);
  2663. selectedChannel = 0;
  2664. selectedChannels = { 0 };
  2665. modified = false;
  2666. checkHardwareInserts = true; // (a project measured on another setup: the notice, round 165c)
  2667. // arming isn't saved: a new project starts disarmed; its inserts' audio inputs open the device input
  2668. for (const auto t : std::vector<int> (armedInserts))
  2669. setInsertArmed (t, false);
  2670. if (prefetcher != nullptr && ! hasAudioInput()
  2671. && std::any_of (song.mixer.begin(), song.mixer.end(), [] (const MixerTrack& t) { return t.inputChannel >= 0 || t.flInput >= 0; }))
  2672. openAudioInput();
  2673. // an FL project's insert inputs (REA round 157c): FL's list index on the device open now
  2674. if (prefetcher != nullptr && hasAudioInput())
  2675. {
  2676. auto* device = deviceManager.getCurrentAudioDevice();
  2677. const auto channels = device != nullptr ? device->getInputChannelNames().size() : 0;
  2678. for (auto& t : song.mixer)
  2679. {
  2680. if (t.flInput >= 0 && t.inputChannel < 0)
  2681. {
  2682. const auto source = flInputSource (t.flInput, channels);
  2683. t.inputChannel = source.channel;
  2684. t.inputStereo = source.stereo;
  2685. }
  2686. t.flInput = -1;
  2687. }
  2688. }
  2689. // hardware output targets and hardware inserts: their channels open with the project (the ones the device has)
  2690. if (prefetcher != nullptr)
  2691. openHardwareInsertIo();
  2692. publishSong();
  2693. }
  2694. void AudioEngine::saveUndoStep()
  2695. {
  2696. // Dozens of edits arrive during a drag; only the first one of the click saves the state.
  2697. bool samePress = false;
  2698. if (juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown())
  2699. {
  2700. const auto press = juce::Desktop::getInstance().getMainMouseSource().getLastMouseDownTime();
  2701. samePress = press == lastUndoPress;
  2702. lastUndoPress = press;
  2703. }
  2704. else
  2705. {
  2706. lastUndoPress = {};
  2707. }
  2708. if (! samePress)
  2709. {
  2710. undoStack.push_back (song);
  2711. redoStack.clear();
  2712. if (undoStack.size() > maxUndoSteps)
  2713. {
  2714. undoStack.pop_front();
  2715. if (recordPassMarked)
  2716. ++recordPassTrimmed;
  2717. }
  2718. if (sessionHistory)
  2719. {
  2720. closeSessionStep();
  2721. sessionUndo.push_back ({ song, song });
  2722. sessionRedo.clear();
  2723. if (sessionUndo.size() > maxUndoSteps)
  2724. sessionUndo.pop_front();
  2725. }
  2726. }
  2727. if (sessionHistory)
  2728. sessionAfterOpen = true;
  2729. }
  2730. void AudioEngine::editSong (const std::function<void (Song&)>& edit, bool undoable)
  2731. {
  2732. if (undoable)
  2733. {
  2734. saveUndoStep();
  2735. modified = true;
  2736. }
  2737. const auto lengthsBefore = patternLengths (song);
  2738. const auto auditioned = comp::auditionedTrack (song);
  2739. const auto pluginsBefore = detachNewPluginsOn ? freshPluginCounts (song) : std::map<std::string, int>();
  2740. edit (song);
  2741. if (detachNewPluginsOn)
  2742. detachNewPlugins (pluginsBefore, song);
  2743. comp::checkAudition (song, auditioned);
  2744. followPatternLengths (lengthsBefore, song);
  2745. clipops::updateCrossfades (song); // FL's automatic crossfades follow every edit (round 166e)
  2746. publishSong();
  2747. }
  2748. void AudioEngine::editSongPatternOrder (const std::function<void (Song&)>& edit)
  2749. {
  2750. saveUndoStep();
  2751. modified = true;
  2752. edit (song);
  2753. clipops::updateCrossfades (song);
  2754. publishSong();
  2755. }
  2756. void AudioEngine::editLevels (const std::function<void (Song&)>& edit, bool undoable)
  2757. {
  2758. // A fader or knob drag (round 171c, discussion #10): every mouse move used to go through editSong, i.e. a whole
  2759. // snapshot rebuild per move. While the song played that stalled the message thread and the fader (and the sound)
  2760. // moved in steps of ~0.2 s. Here the edit changes only levels, so the snapshot in use takes the new values through
  2761. // its live levels; the full publish follows once the mouse is released (timerCallback).
  2762. if (publishedLevels == nullptr || ! publishedLevels->matches (song))
  2763. {
  2764. editSong (edit, undoable);
  2765. return;
  2766. }
  2767. if (undoable)
  2768. {
  2769. saveUndoStep();
  2770. modified = true;
  2771. }
  2772. edit (song);
  2773. if (! publishedLevels->matches (song)) // (an edit that was not only levels)
  2774. {
  2775. publishSong();
  2776. return;
  2777. }
  2778. publishedLevels->store (song);
  2779. ++songStamp;
  2780. levelsPending = true;
  2781. ++levelEdits;
  2782. levelsChanged.sendChangeMessage();
  2783. }
  2784. void AudioEngine::flushLevels()
  2785. {
  2786. if (! levelsPending)
  2787. return;
  2788. levelsPending = false;
  2789. publishSong();
  2790. }
  2791. void AudioEngine::editSongStructural (const std::function<void (Song&)>& edit)
  2792. {
  2793. // (PR #37) the live plugin states go into the Song first: the undo step then holds them, and a plugin that can't be
  2794. // matched to its old instance comes back with its current settings. Round 168s: the rebuild matches channels and
  2795. // effect slots by their instance tag (RackState::build), so a moved plugin, duplicates included, keeps its running
  2796. // instance and is not built again (issue #36: no second instance created and the old one torn down for a move).
  2797. capturePluginStates();
  2798. editSong (edit);
  2799. }
  2800. void AudioEngine::closeSessionStep()
  2801. {
  2802. if (sessionAfterOpen && ! sessionUndo.empty())
  2803. sessionUndo.back().second = song;
  2804. sessionAfterOpen = false;
  2805. }
  2806. void AudioEngine::sessionStep (bool redo)
  2807. {
  2808. closeSessionStep();
  2809. auto& from = redo ? sessionRedo : sessionUndo;
  2810. auto& to = redo ? sessionUndo : sessionRedo;
  2811. if (from.empty())
  2812. return;
  2813. auto step = std::move (from.back());
  2814. from.pop_back();
  2815. std::vector<live::Key> skipped;
  2816. // undo: the step's entities back to "before" (where they still are as "after" left them); redo the other way
  2817. auto next = redo ? live::selectiveRevert (song, step.second, step.first, &skipped) : live::selectiveRevert (song, step.first, step.second, &skipped);
  2818. juce::StringArray names;
  2819. for (const auto& k : skipped)
  2820. names.addIfNotAlreadyThere (juce::String::fromUTF8 (live::describe (k, song, [] (const char* s) { return tr (s).toStdString(); }).c_str()));
  2821. to.push_back (std::move (step));
  2822. song = std::move (next);
  2823. modified = true;
  2824. lastUndoPress = {};
  2825. clipops::updateCrossfades (song);
  2826. publishSong();
  2827. if (! names.isEmpty() && onSessionUndoSkipped)
  2828. onSessionUndoSkipped (names);
  2829. }
  2830. void AudioEngine::setSessionHistory (bool on)
  2831. {
  2832. sessionHistory = on;
  2833. sessionAfterOpen = false;
  2834. sessionUndo.clear();
  2835. sessionRedo.clear();
  2836. }
  2837. void AudioEngine::applyRemote (Song remote)
  2838. {
  2839. closeSessionStep();
  2840. lastUndoPress = {}; // (a drag that goes on after this is a new step: its "before" has the remote change)
  2841. song = std::move (remote);
  2842. clipops::updateCrossfades (song);
  2843. publishSong();
  2844. }
  2845. void AudioEngine::undo()
  2846. {
  2847. if (sessionHistory)
  2848. return sessionStep (false);
  2849. if (undoStack.empty())
  2850. return;
  2851. redoStack.push_back (std::move (song));
  2852. song = std::move (undoStack.back());
  2853. undoStack.pop_back();
  2854. comp::setAudition (song, -1); // (not an edit: whatever an old state had auditioned stays out of it)
  2855. modified = true;
  2856. lastUndoPress = {};
  2857. publishSong();
  2858. }
  2859. void AudioEngine::redo()
  2860. {
  2861. if (sessionHistory)
  2862. return sessionStep (true);
  2863. if (redoStack.empty())
  2864. return;
  2865. undoStack.push_back (std::move (song));
  2866. song = std::move (redoStack.back());
  2867. redoStack.pop_back();
  2868. comp::setAudition (song, -1);
  2869. modified = true;
  2870. lastUndoPress = {};
  2871. publishSong();
  2872. }
  2873. namespace
  2874. {
  2875. const Song& historyState (const std::deque<Song>& undo, const Song& current, const std::deque<Song>& redo, int index)
  2876. {
  2877. if (index < (int) undo.size())
  2878. return undo[(std::size_t) index];
  2879. if (index == (int) undo.size())
  2880. return current;
  2881. return redo[redo.size() - 1 - (std::size_t) (index - (int) undo.size() - 1)];
  2882. }
  2883. } // namespace
  2884. ChangeLabel AudioEngine::getHistoryLabel (int index) const
  2885. {
  2886. if (index <= 0 || index >= getHistorySize())
  2887. return { TR_NOOP ("Start"), {} };
  2888. if (sessionHistory) // (a live session: one's own steps, each named by its own before / after)
  2889. {
  2890. const auto i = (std::size_t) index - 1;
  2891. const auto& step = i < sessionUndo.size() ? sessionUndo[i] : sessionRedo[sessionRedo.size() - 1 - (i - sessionUndo.size())];
  2892. return describeChange (step.first, i + 1 == sessionUndo.size() && sessionAfterOpen ? song : step.second);
  2893. }
  2894. return describeChange (historyState (undoStack, song, redoStack, index - 1), historyState (undoStack, song, redoStack, index));
  2895. }
  2896. void AudioEngine::jumpToHistory (int index)
  2897. {
  2898. index = juce::jlimit (0, getHistorySize() - 1, index);
  2899. if (index == getHistoryPosition())
  2900. return;
  2901. if (sessionHistory)
  2902. {
  2903. while (getHistoryPosition() > index && ! sessionUndo.empty())
  2904. sessionStep (false);
  2905. while (getHistoryPosition() < index && ! sessionRedo.empty())
  2906. sessionStep (true);
  2907. return;
  2908. }
  2909. // move through the stacks, then publish once
  2910. while (getHistoryPosition() > index && ! undoStack.empty())
  2911. {
  2912. redoStack.push_back (std::move (song));
  2913. song = std::move (undoStack.back());
  2914. undoStack.pop_back();
  2915. }
  2916. while (getHistoryPosition() < index && ! redoStack.empty())
  2917. {
  2918. undoStack.push_back (std::move (song));
  2919. song = std::move (redoStack.back());
  2920. redoStack.pop_back();
  2921. }
  2922. modified = true;
  2923. lastUndoPress = {};
  2924. publishSong();
  2925. }
  2926. void AudioEngine::setSelectedChannel (int channel)
  2927. {
  2928. channel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), channel);
  2929. setChannelSelection ({ channel }, channel);
  2930. }
  2931. void AudioEngine::setChannelSelection (std::vector<int> channels, int primary)
  2932. {
  2933. const auto count = (int) song.channels.size();
  2934. std::sort (channels.begin(), channels.end());
  2935. channels.erase (std::unique (channels.begin(), channels.end()), channels.end());
  2936. channels.erase (std::remove_if (channels.begin(), channels.end(), [count] (int c) { return c < 0 || c >= count; }), channels.end());
  2937. primary = juce::jlimit (0, juce::jmax (0, count - 1), primary);
  2938. if (std::find (channels.begin(), channels.end(), primary) == channels.end())
  2939. channels.insert (std::lower_bound (channels.begin(), channels.end(), primary), primary);
  2940. if (channels == selectedChannels && primary == selectedChannel)
  2941. {
  2942. publishSelection();
  2943. return;
  2944. }
  2945. selectedChannels = std::move (channels);
  2946. selectedChannel = primary;
  2947. publishSelection();
  2948. sendChangeMessage();
  2949. }
  2950. void AudioEngine::publishSelection()
  2951. {
  2952. liveChannel.store (selectedChannel);
  2953. int extra = 0;
  2954. for (auto c : selectedChannels)
  2955. if (c != selectedChannel && extra < maxLiveChannels)
  2956. extraLiveChannels[(std::size_t) extra++].store (c);
  2957. extraLiveCount.store (extra);
  2958. }
  2959. namespace
  2960. {
  2961. // Whether a drive / network share is there, within a time limit: a disconnected network drive can block a file
  2962. // query for half a minute, and an open probes many paths under the same root (round 112). One probe per root per open.
  2963. bool rootReachable (const std::string& root)
  2964. {
  2965. auto result = std::make_shared<std::atomic<int>> (-1);
  2966. std::thread ([result, root] {
  2967. result->store (platform::localFile (root).isDirectory() ? 1 : 0); // FL's "C:\" spelling on macOS/Linux too
  2968. }).detach();
  2969. const auto started = juce::Time::getMillisecondCounter();
  2970. while (result->load() < 0 && juce::Time::getMillisecondCounter() - started < 2000)
  2971. juce::Thread::sleep (2);
  2972. return result->load() == 1; // still unknown after 2 s: treated as missing (the probe thread finishes on its own)
  2973. }
  2974. std::string userOf (const Song& song, std::size_t track)
  2975. {
  2976. return song.mixer[track].name.empty() ? (track == 0 ? std::string ("Master") : "Insert " + std::to_string (track)) : song.mixer[track].name;
  2977. }
  2978. } // namespace
  2979. namespace
  2980. {
  2981. // Where a Live set's library-relative samples live (Core Library, packs, User Library), newest install first; only
  2982. // folders that exist. Read-only: nothing is ever written there.
  2983. std::vector<std::string> liveLibraryRoots()
  2984. {
  2985. std::vector<std::string> roots;
  2986. auto add = [&roots] (const juce::File& f) {
  2987. if (f.isDirectory())
  2988. roots.push_back (f.getFullPathName().toStdString());
  2989. };
  2990. #if JUCE_WINDOWS
  2991. const juce::File programData ("C:\\ProgramData\\Ableton");
  2992. #elif JUCE_MAC
  2993. const juce::File programData ("/Applications");
  2994. #else
  2995. const juce::File programData;
  2996. #endif
  2997. if (programData.isDirectory())
  2998. {
  2999. auto installs = programData.findChildFiles (juce::File::findDirectories, false, "Live*");
  3000. std::sort (installs.begin(), installs.end(), [] (const juce::File& a, const juce::File& b) { return a.getFileName() > b.getFileName(); });
  3001. for (const auto& install : installs)
  3002. {
  3003. add (install.getChildFile ("Resources").getChildFile ("Core Library"));
  3004. add (install.getChildFile ("Contents").getChildFile ("App-Resources").getChildFile ("Core Library"));
  3005. }
  3006. }
  3007. const auto docs = juce::File::getSpecialLocation (juce::File::userDocumentsDirectory).getChildFile ("Ableton");
  3008. add (docs.getChildFile ("User Library"));
  3009. add (docs.getChildFile ("Factory Packs"));
  3010. const auto music = juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("Ableton");
  3011. add (music.getChildFile ("User Library"));
  3012. add (music.getChildFile ("Factory Packs"));
  3013. return roots;
  3014. }
  3015. } // namespace
  3016. void AudioEngine::prepareFlpImport (const juce::File& file, const std::map<std::string, std::string>& relocations, SampleLibrary& library,
  3017. PreparedFlp& out)
  3018. {
  3019. juce::MemoryBlock data;
  3020. {
  3021. const loadtrace::Scope timing ("read_project");
  3022. if (! file.loadFileAsData (data))
  3023. {
  3024. out.error = utf8 ("could not read the file");
  3025. return;
  3026. }
  3027. }
  3028. try
  3029. {
  3030. loadtrace::stage (0.20, 0.30, TR_NOOP ("Reading the project..."));
  3031. const auto started = std::chrono::steady_clock::now();
  3032. const auto* fileBytes = static_cast<const std::uint8_t*> (data.getData());
  3033. // a Live set (.als, round 175a) takes the same pipeline: samples, plugins, report and Missing files window
  3034. const auto liveSet = file.hasFileExtension ("als");
  3035. // an FL Studio Mobile project (.flm, .songtmpl; round 182c) too
  3036. const auto mobileProject = file.hasFileExtension ("flm;songtmpl");
  3037. std::optional<flp::Project> project;
  3038. if (! liveSet && ! mobileProject)
  3039. project = flp::parseProject ({ fileBytes, data.getSize() });
  3040. loadtrace::add ("parse", loadtrace::msSince (started));
  3041. FlpImportOptions options;
  3042. options.roots = findFlStudioRoots();
  3043. options.projectFolder = file.getParentDirectory().getFullPathName().toStdString();
  3044. // samples on a drive that is not there (unplugged external drive, dead network share): one probe per root
  3045. auto roots = std::make_shared<loadtrace::RootProbe> ([] (const std::string& root) {
  3046. const auto t = std::chrono::steady_clock::now();
  3047. const auto ok = rootReachable (root);
  3048. loadtrace::add ("probe_root", loadtrace::msSince (t));
  3049. return ok;
  3050. });
  3051. options.fileExists = [roots] (const std::string& path) {
  3052. if (! roots->rootAvailable (path))
  3053. return false;
  3054. const auto t = std::chrono::steady_clock::now();
  3055. const auto exists = platform::localFile (path).existsAsFile();
  3056. loadtrace::add ("probe_file", loadtrace::msSince (t));
  3057. return exists;
  3058. };
  3059. options.readFile = [roots] (const std::string& path) {
  3060. if (! roots->rootAvailable (path))
  3061. return std::vector<std::uint8_t> {};
  3062. const auto t = std::chrono::steady_clock::now();
  3063. juce::MemoryBlock data;
  3064. platform::localFile (path).loadFileAsData (data);
  3065. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  3066. loadtrace::add ("read_aux_file", loadtrace::msSince (t));
  3067. return std::vector<std::uint8_t> (bytes, bytes + data.getSize());
  3068. };
  3069. auto decoded = std::make_shared<std::vector<std::shared_ptr<const SampleData>>>();
  3070. options.sampleFrames = [&library, decoded] (const std::string& path) -> std::int64_t {
  3071. const auto sample = library.load (juce::String::fromUTF8 (path.c_str()));
  3072. if (sample != nullptr)
  3073. decoded->push_back (sample); // kept: the rack uses it next (it was decoded twice before)
  3074. return sample != nullptr ? (std::int64_t) sample->frames() : 0;
  3075. };
  3076. options.sampleSeconds = [&library, decoded] (const std::string& path) -> double {
  3077. const auto sample = library.load (juce::String::fromUTF8 (path.c_str()));
  3078. if (sample == nullptr || sample->sampleRate <= 0.0)
  3079. return 0.0;
  3080. decoded->push_back (sample);
  3081. return (double) sample->frames() / sample->sampleRate;
  3082. };
  3083. // WAV that only exists inside the .flp (Slicex): goes to %APPDATA%\LYNX\flp-embedded, keyed by content
  3084. options.saveEmbedded = [] (const std::vector<std::uint8_t>& wav, const std::string& name) -> std::string {
  3085. const auto folder = PluginHost::settingsFolder().getChildFile ("flp-embedded");
  3086. folder.createDirectory();
  3087. const auto hash = juce::String::toHexString ((juce::int64) juce::DefaultHashFunctions::generateHash (
  3088. juce::String::createStringFromData (wav.data(), (int) std::min<std::size_t> (wav.size(), 65536)) + juce::String ((juce::int64) wav.size()),
  3089. 0x7FFFFFFF));
  3090. const auto file = folder.getChildFile (juce::File::createLegalFileName (juce::String::fromUTF8 (name.c_str())) + "-" + hash + ".wav");
  3091. if (! file.existsAsFile() && ! file.replaceWithData (wav.data(), wav.size()))
  3092. return {};
  3093. return file.getFullPathName().toStdString();
  3094. };
  3095. out.report = {};
  3096. options.report = &out.report;
  3097. options.relocations = relocations;
  3098. {
  3099. const auto t = std::chrono::steady_clock::now();
  3100. if (mobileProject)
  3101. {
  3102. FlmImportOptions flmOptions;
  3103. flmOptions.common = options;
  3104. if (! options.roots.factoryData.empty())
  3105. if (const auto root = flmResourceRootIn (options.roots.factoryData); platform::localFile (root).isDirectory())
  3106. flmOptions.resourceRoot = root;
  3107. std::string flmError;
  3108. auto song = importFlm (std::vector<std::uint8_t> (fileBytes, fileBytes + data.getSize()), flmOptions, &flmError);
  3109. if (! song)
  3110. {
  3111. out.error = utf8 (flmError.empty() ? "not a readable FL Studio Mobile project" : flmError.c_str());
  3112. return;
  3113. }
  3114. out.song = std::move (*song);
  3115. }
  3116. else if (liveSet)
  3117. {
  3118. AlsImportOptions alsOptions;
  3119. alsOptions.common = options;
  3120. alsOptions.libraryRoots = liveLibraryRoots();
  3121. alsOptions.sessionOnPlaylist = alsSessionOnPlaylist.load();
  3122. std::string alsError;
  3123. auto song = importAls (std::vector<std::uint8_t> (fileBytes, fileBytes + data.getSize()), alsOptions, &alsError);
  3124. if (! song)
  3125. {
  3126. out.error = utf8 (alsError.empty() ? "not a readable Live set" : alsError.c_str());
  3127. return;
  3128. }
  3129. out.song = std::move (*song);
  3130. }
  3131. else
  3132. {
  3133. out.song = importFlp (*project, options);
  3134. }
  3135. loadtrace::add ("import", loadtrace::msSince (t));
  3136. }
  3137. loadtrace::add ("missing_roots", 0.0, (int) roots->missingRoots().size());
  3138. loadtrace::add ("probe_skipped", 0.0, roots->skipped());
  3139. // the project's third-party plugins, to say which channel/insert used each one that is missing
  3140. for (const auto& c : out.song.channels)
  3141. if (c.plugin.foreign.format != ForeignPlugin::Format::none)
  3142. out.uses.push_back ({ c.plugin.foreign.name, c.name, true });
  3143. for (std::size_t t = 0; t < out.song.mixer.size(); ++t)
  3144. for (const auto& fx : out.song.mixer[t].effects)
  3145. if (fx.kind == EffectKind::plugin && fx.plugin.foreign.format != ForeignPlugin::Format::none)
  3146. out.uses.push_back ({ fx.plugin.foreign.name, userOf (out.song, t), false });
  3147. // (and the ones inside Patchers, REA_rodada141)
  3148. std::function<void (const PatcherDoc&, const std::string&)> patcherUses = [&] (const PatcherDoc& doc, const std::string& user) {
  3149. for (const auto& n : doc.nodes)
  3150. {
  3151. const auto& ref = n.generator ? n.channel.plugin : n.effect.plugin;
  3152. if (ref.foreign.format != ForeignPlugin::Format::none)
  3153. out.uses.push_back ({ ref.foreign.name, user + " (Patcher)", n.generator });
  3154. if (n.generator && n.channel.instrument == InstrumentKind::patcher)
  3155. patcherUses (n.channel.patcher, user);
  3156. if (! n.generator && n.effect.kind == EffectKind::patcher)
  3157. patcherUses (n.effect.patcher, user);
  3158. }
  3159. };
  3160. for (const auto& c : out.song.channels)
  3161. if (c.instrument == InstrumentKind::patcher)
  3162. patcherUses (c.patcher, c.name);
  3163. for (std::size_t t = 0; t < out.song.mixer.size(); ++t)
  3164. for (const auto& fx : out.song.mixer[t].effects)
  3165. if (fx.kind == EffectKind::patcher)
  3166. patcherUses (fx.patcher, userOf (out.song, t));
  3167. // the samples, decoded now (in parallel, off the message thread) so building the rack only finds them ready
  3168. std::vector<std::string> paths;
  3169. auto addPath = [&paths] (const std::string& p) {
  3170. if (! p.empty() && std::find (paths.begin(), paths.end(), p) == paths.end())
  3171. paths.push_back (p);
  3172. };
  3173. for (const auto& c : out.song.channels)
  3174. {
  3175. if (c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip || c.instrument == InstrumentKind::granulizer
  3176. || c.instrument == InstrumentKind::wavetraveller || c.instrument == InstrumentKind::fruityslicer
  3177. || c.instrument == InstrumentKind::slicex
  3178. || c.instrument == InstrumentKind::flkeys || c.instrument == InstrumentKind::directwave)
  3179. addPath (c.samplePath);
  3180. for (const auto& z : c.zones)
  3181. addPath (z.path);
  3182. }
  3183. for (const auto& track : out.song.mixer)
  3184. for (const auto& fx : track.effects)
  3185. addPath (fx.samplePath);
  3186. loadtrace::stage (0.30, 0.55, TR_NOOP ("Reading the samples..."), TR_NOOP ("Reading {0}... {1}/{2}"));
  3187. const auto decodeStarted = std::chrono::steady_clock::now();
  3188. std::atomic<std::size_t> next { 0 }, done { 0 };
  3189. std::mutex keep;
  3190. auto worker = [&] {
  3191. for (auto i = next++; i < paths.size(); i = next++)
  3192. {
  3193. const auto t = std::chrono::steady_clock::now();
  3194. auto sample = library.load (juce::String::fromUTF8 (paths[i].c_str()));
  3195. loadtrace::add ("sample_decode", loadtrace::msSince (t));
  3196. {
  3197. const std::scoped_lock l (keep);
  3198. if (sample != nullptr)
  3199. out.decoded.push_back (std::move (sample));
  3200. }
  3201. const auto n = ++done;
  3202. loadtrace::step ((int) n, (int) paths.size(),
  3203. juce::File::createFileWithoutCheckingPath (juce::String::fromUTF8 (paths[i].c_str())).getFileName().toStdString());
  3204. }
  3205. };
  3206. const auto threads = (std::size_t) juce::jlimit (1, 6, juce::SystemStats::getNumCpus() - 1);
  3207. std::vector<std::thread> pool;
  3208. for (std::size_t i = 1; i < juce::jmin (threads, paths.size()); ++i)
  3209. pool.emplace_back (worker);
  3210. worker();
  3211. for (auto& t : pool)
  3212. t.join();
  3213. for (auto& d : *decoded)
  3214. out.decoded.push_back (std::move (d));
  3215. // pitch-preserving stretch (audio clips that follow the tempo): the stretched copy too, in parallel, with the
  3216. // same ratio the rack asks for (RackState::build) — it was computed on the message thread while building
  3217. struct Stretch
  3218. {
  3219. std::string path;
  3220. double ratio;
  3221. StretchMethod method;
  3222. double semitones;
  3223. StretchMap map;
  3224. std::string variant; // non-empty: the precomputed span is stretched (RackRenderer, round 180d)
  3225. std::shared_ptr<const SampleData> span;
  3226. };
  3227. std::vector<Stretch> stretches;
  3228. for (const auto& c : out.song.channels)
  3229. if ((c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip) && c.zones.empty() && ! c.samplePath.empty()
  3230. && c.sampler.keepPitch && c.sampler.stretchBeats > 0.0f)
  3231. if (const auto data = library.load (juce::String::fromUTF8 (c.samplePath.c_str())); data != nullptr && data->frames() > 0)
  3232. {
  3233. const auto target = c.sampler.stretchBeats * 60.0 / std::max (1.0, out.song.bpm);
  3234. const auto method = c.sampler.stretchMethod;
  3235. const auto semitones = (double) c.sampler.stretchPitch;
  3236. // the same stretch as RackRenderer: the precomputed span when there is one (round 180d), else the file
  3237. const auto clip = c.instrument == InstrumentKind::audioClip;
  3238. auto settings = c.sampler;
  3239. if (clip)
  3240. settings.regionStart = 0.0f, settings.regionEnd = 1.0f;
  3241. const auto precomputes = clip ? c.sampler.precompute.any() : precompute::needed (c.sampler);
  3242. if (precomputes && c.sampler.warp.empty())
  3243. {
  3244. if (std::shared_ptr<const SampleData> span = precompute::apply (*data, settings); span != nullptr && span->frames() > 0)
  3245. {
  3246. const auto ratio = target / ((double) span->frames() / span->sampleRate);
  3247. auto variant = precompute::variantKey (settings, clip);
  3248. if (std::none_of (stretches.begin(), stretches.end(), [&] (const Stretch& x) {
  3249. return x.path == c.samplePath && x.variant == variant && x.ratio == ratio && x.method == method && x.semitones == semitones; }))
  3250. stretches.push_back ({ c.samplePath, ratio, method, semitones, {}, std::move (variant), std::move (span) });
  3251. }
  3252. continue;
  3253. }
  3254. const auto ratio = target / ((double) precompute::stretchedFrames (data, c.sampler, clip) / data->sampleRate);
  3255. // (the same map the rack asks for: RackState::build)
  3256. auto map = warpStretchMap (c.sampler.warp, (double) data->frames(), data->sampleRate, (double) std::llround ((double) data->frames() * ratio));
  3257. if (std::none_of (stretches.begin(), stretches.end(), [&] (const Stretch& x) {
  3258. return x.path == c.samplePath && x.variant.empty() && x.ratio == ratio && x.method == method && x.semitones == semitones && x.map == map; }))
  3259. stretches.push_back ({ c.samplePath, ratio, method, semitones, std::move (map), {}, {} });
  3260. }
  3261. if (! stretches.empty())
  3262. {
  3263. const auto stretchStarted = std::chrono::steady_clock::now();
  3264. std::atomic<std::size_t> nextStretch { 0 };
  3265. auto stretchWorker = [&] {
  3266. for (auto i = nextStretch++; i < stretches.size(); i = nextStretch++)
  3267. if (auto stretched = ! stretches[i].variant.empty()
  3268. ? library.loadStretchedSpan (juce::String::fromUTF8 (stretches[i].path.c_str()), stretches[i].variant,
  3269. stretches[i].span, stretches[i].ratio, stretches[i].method, stretches[i].semitones)
  3270. : library.loadStretched (juce::String::fromUTF8 (stretches[i].path.c_str()), stretches[i].ratio, stretches[i].method, stretches[i].semitones, stretches[i].map))
  3271. {
  3272. const std::scoped_lock l (keep); // held until the rack is built (the cache drops unused lengths)
  3273. out.decoded.push_back (std::move (stretched));
  3274. }
  3275. };
  3276. std::vector<std::thread> helpers;
  3277. for (std::size_t i = 1; i < juce::jmin (threads, stretches.size()); ++i)
  3278. helpers.emplace_back (stretchWorker);
  3279. stretchWorker();
  3280. for (auto& t : helpers)
  3281. t.join();
  3282. loadtrace::add ("stretch_wall", loadtrace::msSince (stretchStarted), (int) stretches.size());
  3283. }
  3284. loadtrace::add ("samples_wall", loadtrace::msSince (decodeStarted), (int) paths.size());
  3285. out.ok = true;
  3286. }
  3287. catch (const flp::Error& e)
  3288. {
  3289. out.error = juce::String::fromUTF8 (e.what());
  3290. }
  3291. }
  3292. void AudioEngine::adoptPrepared (PreparedFlp& prepared)
  3293. {
  3294. if (prepared.adopted)
  3295. return;
  3296. prepared.adopted = true;
  3297. const auto t = std::chrono::steady_clock::now();
  3298. plugins.clearPreloaded();
  3299. plugins.setPreloadRate (transport.sampleRate.load());
  3300. plugins.adoptFlPlugins (prepared.song, &prepared.missing, &prepared.matched, &prepared.withoutState, &prepared.substituted);
  3301. loadtrace::add ("adopt_plugins", loadtrace::msSince (t));
  3302. // the hosted plugins the rack will create, in its order (channels, then inserts)
  3303. for (const auto& c : prepared.song.channels)
  3304. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty())
  3305. prepared.pluginQueue.push_back (c.plugin);
  3306. for (const auto& track : prepared.song.mixer)
  3307. for (std::size_t i = 0; i < track.effects.size() && i < (std::size_t) maxEffectSlots; ++i)
  3308. if (track.effects[i].kind == EffectKind::plugin && ! track.effects[i].plugin.id.empty())
  3309. prepared.pluginQueue.push_back (track.effects[i].plugin);
  3310. }
  3311. bool AudioEngine::preloadNextPlugin (PreparedFlp& prepared)
  3312. {
  3313. adoptPrepared (prepared);
  3314. if (prepared.pluginsDone >= prepared.pluginQueue.size())
  3315. return false;
  3316. const auto total = (int) prepared.pluginQueue.size();
  3317. const auto& ref = prepared.pluginQueue[prepared.pluginsDone];
  3318. auto wanted = 0;
  3319. for (std::size_t i = 0; i <= prepared.pluginsDone; ++i)
  3320. wanted += prepared.pluginQueue[i].id == ref.id && prepared.pluginQueue[i].state == ref.state ? 1 : 0;
  3321. plugins.preload (ref, wanted);
  3322. ++prepared.pluginsDone;
  3323. loadtrace::step ((int) prepared.pluginsDone, total, {});
  3324. return prepared.pluginsDone < prepared.pluginQueue.size();
  3325. }
  3326. bool AudioEngine::finishFlpImport (PreparedFlp&& prepared, bool asEdit)
  3327. {
  3328. if (! prepared.ok)
  3329. return false;
  3330. adoptPrepared (prepared);
  3331. auto& imported = prepared.song;
  3332. importReport = std::move (prepared.report);
  3333. const auto& uses = prepared.uses;
  3334. missingPlugins = prepared.missing;
  3335. matchedPlugins = prepared.matched;
  3336. pluginsWithoutState = prepared.withoutState;
  3337. missingPluginDetails.clear();
  3338. for (const auto& name : prepared.missing)
  3339. {
  3340. MissingPlugin m;
  3341. m.name = name.toStdString();
  3342. for (const auto& u : uses)
  3343. if (u.name == m.name)
  3344. {
  3345. if (std::find (m.usedBy.begin(), m.usedBy.end(), u.user) == m.usedBy.end())
  3346. m.usedBy.push_back (u.user);
  3347. m.replacement = u.instrument ? "Built-in synth (a preset chosen by the channel name)" : "Nothing: the slot was left out of the mixer";
  3348. }
  3349. missingPluginDetails.push_back (std::move (m));
  3350. }
  3351. // missing, played by a LYNX substitute that keeps the original for when it is installed
  3352. for (std::size_t t = 0; t < imported.mixer.size(); ++t)
  3353. for (const auto& fx : imported.mixer[t].effects)
  3354. if (fx.isSubstitute())
  3355. {
  3356. const auto name = substituteOriginalName (fx);
  3357. auto it = std::find_if (missingPluginDetails.begin(), missingPluginDetails.end(),
  3358. [&] (const MissingPlugin& m) { return m.name == name && ! m.replacementArg.empty(); });
  3359. if (it == missingPluginDetails.end())
  3360. it = missingPluginDetails.insert (missingPluginDetails.end(),
  3361. MissingPlugin { name, {}, TR_NOOP ("LYNX SHARE substitute: {0} (the original plugin is used again once it is installed). FL Studio plays a missing plugin's slot unprocessed: a substitute slot's menu › Bypass all LYNX SHARE substitutes of this project does the same"),
  3362. effectInfo (fx.kind).name });
  3363. const auto user = userOf (imported, t);
  3364. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  3365. it->usedBy.push_back (user);
  3366. }
  3367. // found, but the project's settings are in the other format (VST2 <-> VST3): they play their default sound
  3368. for (const auto& line : prepared.withoutState)
  3369. missingPluginDetails.push_back ({ line.toStdString(), {}, TR_NOOP ("Its default settings: the project saved them for the other format (VST2/VST3)") });
  3370. plugins.clearLoadFailures();
  3371. loadtrace::stage (0.90, 0.99, TR_NOOP ("Building the mixer..."));
  3372. {
  3373. const loadtrace::Scope timing ("set_song");
  3374. if (asEdit)
  3375. editSong ([&imported] (Song& s) { s = std::move (imported); });
  3376. else
  3377. {
  3378. stop();
  3379. rewind();
  3380. setSong (std::move (imported));
  3381. }
  3382. }
  3383. plugins.clearPreloaded(); // (any left over: a slot the rack reused, nothing to keep)
  3384. prepared.decoded.clear();
  3385. // installed but failed to load (the rack was just built): silence / bypass, said as loudly as a missing one
  3386. for (const auto& line : plugins.getLoadFailures())
  3387. missingPluginDetails.push_back ({ line.toStdString(), {}, TR_NOOP ("Silence: the plugin is installed but did not load") });
  3388. return true;
  3389. }
  3390. bool AudioEngine::importFlpFile (const juce::File& file, juce::String& error, const std::map<std::string, std::string>& relocations, bool asEdit)
  3391. {
  3392. // a slow plugin module (a Waves shell) starts on its own thread while the samples decode (round 121)
  3393. if (juce::MemoryBlock data; file.loadFileAsData (data))
  3394. try
  3395. {
  3396. PluginHost::newOpen();
  3397. plugins.startModulesFor (flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  3398. }
  3399. catch (const flp::Error&)
  3400. {
  3401. }
  3402. PreparedFlp prepared;
  3403. prepareFlpImport (file, relocations, samples, prepared);
  3404. if (! prepared.ok)
  3405. {
  3406. error = prepared.error;
  3407. return false;
  3408. }
  3409. if (asEdit)
  3410. keepRunningPlugins (prepared);
  3411. loadtrace::stage (0.55, 0.90, TR_NOOP ("Loading plugins..."), TR_NOOP ("Loading {0}... {1}/{2}"));
  3412. while (preloadNextPlugin (prepared))
  3413. {
  3414. }
  3415. return finishFlpImport (std::move (prepared), asEdit);
  3416. }
  3417. void AudioEngine::keepRunningPlugins (PreparedFlp& prepared)
  3418. {
  3419. // The open project imported again (Missing files › Apply): its plugins are already running with these settings,
  3420. // and the rack keeps a slot whose plugin did not change. Creating them all again first (round 151: 71 plugins,
  3421. // 25 s with the window frozen, then a crash inside a plugin as the second copies replaced the first) is skipped
  3422. // for every plugin the song already has with the same settings.
  3423. adoptPrepared (prepared);
  3424. std::vector<const PluginRef*> running;
  3425. for (const auto& c : song.channels)
  3426. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty())
  3427. running.push_back (&c.plugin);
  3428. for (const auto& track : song.mixer)
  3429. for (const auto& fx : track.effects)
  3430. if (fx.kind == EffectKind::plugin && ! fx.plugin.id.empty())
  3431. running.push_back (&fx.plugin);
  3432. auto& queue = prepared.pluginQueue;
  3433. queue.erase (std::remove_if (queue.begin(), queue.end(),
  3434. [&running] (const PluginRef& ref) {
  3435. const auto it = std::find_if (running.begin(), running.end(), [&ref] (const PluginRef* r) { return r != nullptr && *r == ref; });
  3436. if (it == running.end())
  3437. return false;
  3438. *it = nullptr; // each running plugin stands for one queued copy
  3439. return true;
  3440. }),
  3441. queue.end());
  3442. }
  3443. const AutomationDisplay& AudioEngine::getAutomationDisplay()
  3444. {
  3445. const auto now = juce::Time::getMillisecondCounterHiRes();
  3446. // (editors ask from their own frames: once per display frame is enough; round 174e: 5 ms, i.e. every frame at 144
  3447. // Hz, unless a big project's automation takes long to evaluate, then 12 ms as before)
  3448. if (now - automationDisplayAtMs >= (automationDisplayCostMs > 0.5 ? 12.0 : 5.0))
  3449. {
  3450. automationDisplayAtMs = now;
  3451. const auto playing = transport.playing.load (std::memory_order_relaxed);
  3452. automationDisplay.update (song, songStamp, estimatedPositionNow(), playing);
  3453. automationDisplayCostMs = juce::Time::getMillisecondCounterHiRes() - now;
  3454. }
  3455. return automationDisplay;
  3456. }
  3457. RackState::Factories AudioEngine::rackFactories()
  3458. {
  3459. RackState::Factories factories;
  3460. factories.samples = [this] (const std::string& path) {
  3461. const loadtrace::Scope timing ("rack_samples");
  3462. return samples.load (juce::String::fromUTF8 (path.c_str()));
  3463. };
  3464. factories.stretchedSamples = [this] (const std::string& path, double ratio, StretchMethod method, double semitones, const StretchMap& map) {
  3465. const loadtrace::Scope timing ("rack_stretch");
  3466. return samples.loadStretched (juce::String::fromUTF8 (path.c_str()), ratio, method, semitones, map);
  3467. };
  3468. factories.stretchedSpans = [this] (const std::string& path, const std::string& variant, const std::shared_ptr<const SampleData>& span,
  3469. double ratio, StretchMethod method, double semitones) {
  3470. const loadtrace::Scope timing ("rack_stretch");
  3471. return samples.loadStretchedSpan (juce::String::fromUTF8 (path.c_str()), variant, span, ratio, method, semitones);
  3472. };
  3473. factories.pluginInstruments = [this] (const PluginRef& ref, double sr) { return plugins.makeInstrument (ref, sr); };
  3474. factories.pluginEffects = [this] (const PluginRef& ref, double sr) { return plugins.makeEffect (ref, sr); };
  3475. return factories;
  3476. }
  3477. bool AudioEngine::auditionSound (const ChannelDef& channel, const std::vector<int>& keys, double* seconds)
  3478. {
  3479. auto audio = lynx::renderAudition (channel, keys, 0.32, 0.9, song.bpm, transport.sampleRate.load(), rackFactories());
  3480. if (seconds != nullptr)
  3481. *seconds = audio.sampleRate > 0.0 ? (double) audio.left.size() / audio.sampleRate : 0.0;
  3482. if (audio.left.empty())
  3483. return false;
  3484. auto sample = std::make_shared<SampleData>();
  3485. sample->sampleRate = audio.sampleRate;
  3486. sample->left = std::move (audio.left);
  3487. sample->right = std::move (audio.right);
  3488. previewSample (std::move (sample), false, 1.0f);
  3489. return true;
  3490. }
  3491. ClipAudio AudioEngine::renderClipAudio (std::size_t clipIndex)
  3492. {
  3493. return lynx::renderClipAudio (song, clipIndex, transport.sampleRate.load(), rackFactories());
  3494. }
  3495. void AudioEngine::publishSong()
  3496. {
  3497. // Issue #134: a hosted plugin may run the message loop while it is created (a licence or trial box, COM, a splash
  3498. // window), and what that loop dispatches can ask for a publish while this one is still building its rack: the
  3499. // engine's own timer (after a device change to another sample rate it sees the old rate until this publish ends, so
  3500. // it started a second rebuild of every plugin inside the first one's, and another inside each of those, as deep as
  3501. // the plugins kept running the loop), or an edit. The nested one waits: when this publish is done, one more runs
  3502. // with the song as it then is.
  3503. if (publishing)
  3504. {
  3505. publishAgain = true;
  3506. ++nestedPublishes;
  3507. return;
  3508. }
  3509. publishing = true;
  3510. const juce::ScopeGuard published { [this] {
  3511. publishing = false;
  3512. if (std::exchange (publishAgain, false))
  3513. publishSong();
  3514. } };
  3515. ++songStamp;
  3516. ++publishCount;
  3517. // Online Sessions (round 168a): every entity has its stable id after any edit, import or load
  3518. uids::normalize (song);
  3519. // round 174d A3: the Video Player's clock follows the song's tempo map (FL: the song's real time)
  3520. if (std::any_of (song.channels.begin(), song.channels.end(), [] (const ChannelDef& c) { return c.instrument == InstrumentKind::videoplayer; }))
  3521. video::publishTempo (song);
  3522. // pasted / duplicated channels and effect slots get their own instance (round 168s: instances follow their channel)
  3523. song.uniqueInstances();
  3524. // diagnostics (round 149): with LYNX_TRACE_EDITS set, each publish's time goes to %APPDATA%\LYNX\edits.log
  3525. static const bool traceEdits = std::getenv ("LYNX_TRACE_EDITS") != nullptr;
  3526. const auto publishStart = juce::Time::getMillisecondCounterHiRes();
  3527. const juce::ScopeGuard traceEnd { [&] {
  3528. if (traceEdits)
  3529. platform::settingsFile ("edits.log").appendText (juce::String (juce::Time::getMillisecondCounterHiRes() - publishStart, 1) + " ms publish\n");
  3530. } };
  3531. // the Master's hardware output target, read by the device callback
  3532. masterOutChannel.store (song.mixer.empty() ? outputDefault : song.mixer[0].outputChannel, std::memory_order_relaxed);
  3533. masterOutMode.store (song.mixer.empty() ? 0 : (int) song.mixer[0].outputMode, std::memory_order_relaxed);
  3534. song.currentPattern = juce::jlimit (0, juce::jmax (0, (int) song.patterns.size() - 1), song.currentPattern);
  3535. selectedChannel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), selectedChannel);
  3536. {
  3537. const auto count = (int) song.channels.size();
  3538. selectedChannels.erase (std::remove_if (selectedChannels.begin(), selectedChannels.end(), [count] (int c) { return c >= count; }),
  3539. selectedChannels.end());
  3540. if (std::find (selectedChannels.begin(), selectedChannels.end(), selectedChannel) == selectedChannels.end())
  3541. selectedChannels.insert (std::lower_bound (selectedChannels.begin(), selectedChannels.end(), selectedChannel), selectedChannel);
  3542. }
  3543. publishSelection();
  3544. {
  3545. // the channels locked to a MIDI input ("Receive notes from"): built here, swapped in under the lock
  3546. std::vector<NoteLock> locks;
  3547. for (std::size_t c = 0; c < song.channels.size(); ++c)
  3548. if (! song.channels[c].receiveFrom.empty())
  3549. locks.push_back ({ song.channels[c].receiveFrom, song.channels[c].receiveMidiChannel, (int) c });
  3550. // round 190ao: the hosted instruments with their own velocity setting
  3551. std::vector<std::uint16_t> velocities;
  3552. for (std::size_t c = 0; c < song.channels.size(); ++c)
  3553. if (song.channels[c].instrument == InstrumentKind::plugin && song.channels[c].plugin.velocityMode != prefs::pluginVelocityFollow)
  3554. {
  3555. velocities.resize (c + 1, 0);
  3556. velocities[c] = (std::uint16_t) (prefs::clampPluginVelocityMode (song.channels[c].plugin.velocityMode)
  3557. | (prefs::clampFixedVelocity (song.channels[c].plugin.fixedVelocity) << 8));
  3558. }
  3559. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  3560. noteLocks.swap (locks);
  3561. channelVelocity.swap (velocities);
  3562. }
  3563. transport.bpm.store (song.bpm);
  3564. transport.beatsPerBar.store (song.beatsPerBar);
  3565. {
  3566. // time-signature table for the metronome: the start (beatsPerBar/4) and each signature change
  3567. transport.signatureVersion.fetch_add (1, std::memory_order_acq_rel); // odd: writing
  3568. int count = 0;
  3569. transport.signatureTick[0].store (0, std::memory_order_relaxed);
  3570. transport.signatureLength[0].store ((std::int64_t) ppq * juce::jmax (1, song.beatsPerBar), std::memory_order_relaxed);
  3571. ++count;
  3572. for (const auto& m : song.markers())
  3573. if (m.isSignature() && count < Transport::maxSignatures)
  3574. {
  3575. const auto length = juce::jmax<std::int64_t> (1, (std::int64_t) ppq * 4 * m.numerator / juce::jmax (1, m.denominator));
  3576. const auto slot = m.tick <= 0 ? 0 : count++; // at position 0 it replaces the default
  3577. transport.signatureTick[(std::size_t) slot].store (juce::jmax<std::int64_t> (0, m.tick), std::memory_order_relaxed);
  3578. transport.signatureLength[(std::size_t) slot].store (length, std::memory_order_relaxed);
  3579. }
  3580. transport.signatureCount.store (count, std::memory_order_relaxed);
  3581. transport.signatureVersion.fetch_add (1, std::memory_order_acq_rel); // even: ready
  3582. }
  3583. transport.songMode.store (song.mode == PlayMode::song);
  3584. transport.loopStart.store (song.loopPlays() ? (double) song.loopStart : 0.0); // (round 190cg: the loop switch off = the range stays in the Song, playback runs through)
  3585. transport.loopEnd.store (song.loopPlays() ? (double) song.loopEnd : 0.0);
  3586. transport.songEnd.store ((double) song.songLength());
  3587. transport.publishMarkers (makeMarkerPlan (song)); // FL's marker actions (loop, skip, pause, start...)
  3588. transport.songStart.store ((double) song.performanceZoneEnd());
  3589. const loadtrace::Scope buildTiming ("rack_build");
  3590. auto factories = rackFactories();
  3591. // the song's own rack (not the offline clip render, which shares rackFactories()) tells the UI a plugin is being created
  3592. factories.pluginInstruments = [this] (const PluginRef& ref, double sr) {
  3593. if (duringPluginCreation)
  3594. duringPluginCreation();
  3595. return plugins.makeInstrument (ref, sr);
  3596. };
  3597. factories.pluginEffects = [this] (const PluginRef& ref, double sr) {
  3598. if (duringPluginCreation)
  3599. duringPluginCreation();
  3600. return plugins.makeEffect (ref, sr);
  3601. };
  3602. if (rebuildPlugins) // round 190ap: a plugin switched back on (switchPluginOn)
  3603. factories.rebuildPlugin = [this] (const PluginRef& ref) { return rebuildPluginId.empty() || ref.id == rebuildPluginId; };
  3604. const auto buildStart = juce::Time::getMillisecondCounterHiRes();
  3605. const auto tracePhases = traceEdits && ! loadtrace::active(); // the build's phases (an open traces its own)
  3606. if (tracePhases)
  3607. loadtrace::begin ("edit");
  3608. // the parts whose third-party plugin is missing here play their stand-in renders (core/StandIns.h): the audio
  3609. // engine gets that projection of the song, the UI keeps the song itself
  3610. // (no copy of the song for the almost every project that has none)
  3611. std::optional<Song> projectedSong;
  3612. standins::Projected projected;
  3613. // Freeze (round 190ay): a frozen channel whose audio is not on disk (the project moved without it, a freeze brought
  3614. // back by Undo after its files went) plays its instrument: out of date beats silent
  3615. std::optional<Song> thawedSong;
  3616. frozenMissing.clear();
  3617. for (std::size_t i = 0; i < song.channels.size(); ++i)
  3618. if (const auto& f = song.channels[i].freeze; f.on())
  3619. {
  3620. const auto* whole = standins::find (f.stems, 0, false);
  3621. if (whole != nullptr && juce::File (juce::String::fromUTF8 (whole->path.c_str())).existsAsFile())
  3622. continue;
  3623. if (! thawedSong)
  3624. thawedSong = song;
  3625. thawedSong->channels[i].freeze = {};
  3626. frozenMissing.push_back ((int) i);
  3627. }
  3628. const Song& unprojected = thawedSong ? *thawedSong : song;
  3629. if (standins::hasAny (unprojected))
  3630. projectedSong = standins::project (unprojected, [this] (const PluginRef& ref) { return ! plugins.isInstalled (ref); }, &projected);
  3631. const Song& played = projectedSong ? *projectedSong : unprojected;
  3632. {
  3633. // round 190ap: the slots whose plugin is switched off ("Open without third-party plugins"), for their badges
  3634. const auto hold = pluginsOff() || pluginHoldOwner.load() == nullptr ? pluginHoldState() : pluginhold::State();
  3635. channelsOff = pluginhold::channelsOff (song, hold);
  3636. insertsOff = pluginhold::insertsOff (song, hold);
  3637. }
  3638. standInChannels = std::move (projected.channels);
  3639. standInInserts = std::move (projected.inserts);
  3640. if (played.clipGrid)
  3641. {
  3642. if (clipLauncher == nullptr)
  3643. clipLauncher = std::make_unique<launcher::Runtime>();
  3644. factories.clipLauncher = clipLauncher.get();
  3645. }
  3646. // "Low latency while recording" (round 190aq): the live inserts' paths, for this snapshot only (not the song)
  3647. publishedLowLatency = lowLatencyTracksNow();
  3648. factories.lowLatencyTracks = publishedLowLatency;
  3649. auto state = RackState::build (played, &lastPublishedShape, transport.sampleRate.load(), factories);
  3650. if (traceEdits)
  3651. platform::settingsFile ("edits.log").appendText (juce::String (juce::Time::getMillisecondCounterHiRes() - buildStart, 1) + " ms rack build\n"
  3652. + (tracePhases ? juce::String (loadtrace::reportLines()) : juce::String()));
  3653. if (tracePhases)
  3654. loadtrace::end();
  3655. // what the next build needs to reuse instruments and effects
  3656. lastPublishedShape.song.channels = played.channels;
  3657. lastPublishedShape.song.mixer = played.mixer;
  3658. // the tempo too (round 149): a channel that plays a time-stretched copy is kept when its stretch and the tempo
  3659. // did not change; without it every edit rebuilt them (sample reloaded and stretch looked up, ~0.5 s on Thief)
  3660. lastPublishedShape.song.bpm = song.bpm;
  3661. lastPublishedShape.instruments = state->instruments;
  3662. lastPublishedShape.serial = state->serial; // (round 168s: the renderer moves held notes only along this chain)
  3663. lastPublishedShape.effects = state->effects;
  3664. lastPublishedShape.sampleRate = state->sampleRate;
  3665. lastPublishedShape.latencies = state->latencies;
  3666. lastPublishedShape.lowLatencySlots = state->lowLatencySlots; // (currentLatencies() reads them)
  3667. lastPublishedShape.lowLatencySaved = state->lowLatencySaved;
  3668. lastPublishedShape.pdc = state->pdc;
  3669. lastPublishedShape.channelDelays = state->channelDelays;
  3670. lastPublishedShape.sendDelays = state->sendDelays;
  3671. const auto mark = [&] (const char* what) {
  3672. if (traceEdits)
  3673. platform::settingsFile ("edits.log").appendText (juce::String (juce::Time::getMillisecondCounterHiRes() - publishStart, 1) + " ms " + what + "\n");
  3674. };
  3675. mark ("built");
  3676. levelsPending = false;
  3677. publishedLevels = projectedSong ? nullptr : state->live; // (stand-ins: their projection, edits rebuild)
  3678. rackExchange.publish (std::move (state));
  3679. mark ("exchanged");
  3680. if (prefetcher != nullptr)
  3681. prefetcher->update (played, samples);
  3682. mark ("prefetch updated");
  3683. sendChangeMessage();
  3684. }
  3685. std::vector<MidiLink> AudioEngine::getGlobalLinks() const
  3686. {
  3687. std::vector<MidiLink> out;
  3688. for (const auto& l : midiPrefs.globalLinks)
  3689. {
  3690. MidiLink link { l.cc, l.channel, { (AutomationTargetKind) l.kind, l.index, l.slot, l.param } };
  3691. link.port = l.port;
  3692. link.formula = l.formula;
  3693. link.smooth = l.smooth;
  3694. link.smoothing = l.smoothing;
  3695. link.mode = l.mode;
  3696. out.push_back (std::move (link));
  3697. }
  3698. return out;
  3699. }
  3700. std::optional<MidiLink> AudioEngine::globalLinkOf (const AutomationTarget& target) const
  3701. {
  3702. for (const auto& l : getGlobalLinks())
  3703. if (l.target == target)
  3704. return l;
  3705. return std::nullopt;
  3706. }
  3707. void AudioEngine::learnGlobalLink (const AutomationTarget& target)
  3708. {
  3709. learning = target;
  3710. learningGlobal = true;
  3711. sendChangeMessage();
  3712. }
  3713. void AudioEngine::removeGlobalLink (const AutomationTarget& target)
  3714. {
  3715. auto p = midiPrefs;
  3716. p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
  3717. [&] (const prefs::GlobalLink& l) {
  3718. return l.kind == (int) target.kind && l.index == target.index && l.slot == target.slot
  3719. && l.param == target.param;
  3720. }),
  3721. p.globalLinks.end());
  3722. setMidiPrefs (p, saveGlobalLinks);
  3723. }
  3724. void AudioEngine::setTargetLinks (const AutomationTarget& target, std::vector<MidiLink> links, bool removeConflicts)
  3725. {
  3726. editSong ([&] (Song& s) { lynx::setTargetLinks (s.midiLinks, target, std::move (links), removeConflicts); });
  3727. linkSmoothing.clear();
  3728. sendChangeMessage();
  3729. }
  3730. void AudioEngine::setGlobalLink (const AutomationTarget& target, const std::optional<MidiLink>& link)
  3731. {
  3732. auto p = midiPrefs;
  3733. p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
  3734. [&] (const prefs::GlobalLink& l) {
  3735. return l.kind == (int) target.kind && l.index == target.index && l.slot == target.slot
  3736. && l.param == target.param;
  3737. }),
  3738. p.globalLinks.end());
  3739. if (link && link->cc >= 0)
  3740. {
  3741. prefs::GlobalLink g { link->cc, link->channel, (int) target.kind, target.index, target.slot, target.param };
  3742. g.port = link->port;
  3743. g.formula = link->formula;
  3744. g.smooth = link->smooth;
  3745. g.smoothing = link->smoothing;
  3746. g.mode = link->mode;
  3747. p.globalLinks.push_back (std::move (g));
  3748. }
  3749. setMidiPrefs (p, saveGlobalLinks);
  3750. linkSmoothing.clear();
  3751. sendChangeMessage();
  3752. }
  3753. void AudioEngine::injectControllerForTest (int cc, int channel, int value, int port)
  3754. {
  3755. controllerQueue.push ({ cc, channel, value, port });
  3756. applyControllers();
  3757. }
  3758. // The smoothing filters of the links being moved (FL's per-link "Smoothing"): each one walks towards the position its
  3759. // controller last gave, at the timer's pace, until it has arrived.
  3760. void AudioEngine::stepLinkSmoothing (std::vector<std::pair<AutomationTarget, float>>& changes)
  3761. {
  3762. const auto now = juce::Time::getMillisecondCounterHiRes();
  3763. const auto elapsed = linkSmoothingClock > 0.0 ? juce::jlimit (0.0, 250.0, now - linkSmoothingClock) : 0.0;
  3764. linkSmoothingClock = now;
  3765. for (auto& s : linkSmoothing)
  3766. {
  3767. const auto v = s.filter.step (s.target, elapsed, s.link.smoothing);
  3768. const auto mixerTrack = selectedMixerTrackForLinks ? selectedMixerTrackForLinks() : -1;
  3769. changes.push_back ({ linkOmniTarget (s.link, selectedChannel, mixerTrack), v });
  3770. }
  3771. linkSmoothing.erase (std::remove_if (linkSmoothing.begin(), linkSmoothing.end(), [] (const LinkSmoothing& s) { return s.filter.settled (s.target); }),
  3772. linkSmoothing.end());
  3773. if (linkSmoothing.empty())
  3774. linkSmoothingClock = 0.0;
  3775. }
  3776. void AudioEngine::setMultilink (bool on)
  3777. {
  3778. if (on)
  3779. multilink.emplace();
  3780. else
  3781. multilink.reset();
  3782. sendChangeMessage();
  3783. }
  3784. void AudioEngine::multilinkToControllers (bool global)
  3785. {
  3786. if (! multilink)
  3787. return;
  3788. multilink->collecting = false;
  3789. multilink->global = global;
  3790. sendChangeMessage();
  3791. }
  3792. void AudioEngine::learnMidiController (const AutomationTarget& target)
  3793. {
  3794. learning = target;
  3795. learningGlobal = false;
  3796. sendChangeMessage();
  3797. }
  3798. // --- last tweaked parameters and automation recording (REA round 143) --------------------------------------
  3799. void AudioEngine::noteTweaked (const AutomationTarget& target, bool held)
  3800. {
  3801. if (target.kind == AutomationTargetKind::none)
  3802. return;
  3803. if (multilink) // round 177b-4: FL's Multilink queues the moved controls in order
  3804. multilink->add (target);
  3805. // FL [EXEC round 185b, issue #125]: a moved control leaves its automation until playback starts again (stopped: the
  3806. // value stays; playing: the clip no longer drives it). While recording automation the touch rule applies instead.
  3807. const auto recordingAutomation = transport.recording.load() && transport.playing.load() && recordOptions.recordAutomation;
  3808. if (! recordingAutomation && std::find (releasedTargets.begin(), releasedTargets.end(), target) == releasedTargets.end())
  3809. {
  3810. releasedTargets.push_back (target);
  3811. publishReleasedTargets();
  3812. }
  3813. if (! (lastTweaked[0] == target))
  3814. {
  3815. lastTweaked[1] = lastTweaked[0];
  3816. lastTweaked[0] = target;
  3817. }
  3818. const auto now = juce::Time::getMillisecondCounterHiRes();
  3819. auto it = std::find_if (touches.begin(), touches.end(), [&] (const Touch& t) { return t.target == target; });
  3820. if (it == touches.end())
  3821. {
  3822. touches.push_back ({ target, now, held, {} });
  3823. return;
  3824. }
  3825. it->lastMs = now;
  3826. it->held = it->held || held;
  3827. }
  3828. void AudioEngine::publishReleasedTargets()
  3829. {
  3830. if (rackProcessor == nullptr)
  3831. return;
  3832. std::vector<int> slots, one;
  3833. for (const auto& t : releasedTargets)
  3834. {
  3835. RackState::slotsOfTarget (song, t, one);
  3836. for (const auto a : one) // (a link to an internal controller keeps driving it)
  3837. if (a >= (int) song.automations.size() || ! song.automations[(std::size_t) a].isLive())
  3838. slots.push_back (a);
  3839. }
  3840. rackProcessor->getRenderer().setReleasedSlots (slots);
  3841. }
  3842. void AudioEngine::tweakReleased (const AutomationTarget& target)
  3843. {
  3844. for (auto& t : touches)
  3845. if (t.target == target)
  3846. {
  3847. t.held = false;
  3848. t.lastMs = juce::Time::getMillisecondCounterHiRes();
  3849. }
  3850. }
  3851. std::optional<AutomationTarget> AudioEngine::getLastTweaked (int which) const
  3852. {
  3853. if (which < 0 || which > 1 || lastTweaked[(std::size_t) which].kind == AutomationTargetKind::none
  3854. || currentTargetValue (lastTweaked[(std::size_t) which]) < 0.0f)
  3855. return std::nullopt;
  3856. return lastTweaked[(std::size_t) which];
  3857. }
  3858. float AudioEngine::currentTargetValue (const AutomationTarget& t) const
  3859. {
  3860. // a controller's pitch wheel being recorded (any instrument: LYNX's own have no such parameter)
  3861. if (t.kind == AutomationTargetKind::channelParam && midictl::isPitchBend (t.param))
  3862. if (const auto it = liveBends.find (t.index); it != liveBends.end())
  3863. return it->second;
  3864. const auto base = song.targetValue (t);
  3865. if (base < 0.0f || (t.kind != AutomationTargetKind::channelParam && t.kind != AutomationTargetKind::effectParam))
  3866. return base;
  3867. juce::AudioPluginInstance* plugin = nullptr;
  3868. float midiValue = -1.0f;
  3869. if (t.kind == AutomationTargetKind::channelParam)
  3870. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (t.index).get()))
  3871. {
  3872. plugin = &p->getInstance();
  3873. midiValue = midictl::isMidiParam (t.param) ? p->midiControlValue (t.param) : -1.0f;
  3874. }
  3875. if (t.kind == AutomationTargetKind::effectParam)
  3876. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (t.index, t.slot).get()))
  3877. {
  3878. plugin = &p->getInstance();
  3879. midiValue = midictl::isMidiParam (t.param) ? p->midiControlValue (t.param) : -1.0f;
  3880. }
  3881. if (midiValue >= 0.0f)
  3882. return midiValue;
  3883. if (plugin != nullptr && t.param >= 0 && t.param < plugin->getParameters().size())
  3884. return plugin->getParameters()[t.param]->getValue();
  3885. return base;
  3886. }
  3887. std::optional<AutomationTarget> AudioEngine::targetOfPlugin (const juce::AudioPluginInstance& plugin, int param) const
  3888. {
  3889. for (int c = 0; c < (int) song.channels.size(); ++c)
  3890. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (c).get()); p != nullptr && &p->getInstance() == &plugin)
  3891. return AutomationTarget { AutomationTargetKind::channelParam, c, 0, param };
  3892. for (int t = 0; t < (int) song.mixer.size(); ++t)
  3893. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  3894. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (t, s).get()); p != nullptr && &p->getInstance() == &plugin)
  3895. return AutomationTarget { AutomationTargetKind::effectParam, t, s, param };
  3896. return std::nullopt;
  3897. }
  3898. void AudioEngine::takeRecordedBends()
  3899. {
  3900. RecordedEvent e;
  3901. const auto now = juce::Time::getMillisecondCounterHiRes();
  3902. while (bendRecordQueue.pop (e))
  3903. {
  3904. if (! recordOptions.recordAutomation || e.channel < 0 || e.channel >= (int) song.channels.size())
  3905. continue;
  3906. const AutomationTarget target { AutomationTargetKind::channelParam, e.channel, 0, midictl::pitchBendBase + e.key };
  3907. liveBends[e.channel] = e.velocity;
  3908. // the wheel's own moves, at the times they were played (not only the UI's sampling)
  3909. auto it = std::find_if (touches.begin(), touches.end(), [&] (const Touch& t) { return t.target == target; });
  3910. if (it == touches.end())
  3911. {
  3912. touches.push_back ({ target, now, false, {} });
  3913. it = touches.end() - 1;
  3914. }
  3915. it->lastMs = now;
  3916. it->pending.push_back ({ e.tick, e.velocity });
  3917. }
  3918. if (! transport.recording.load() || ! transport.playing.load())
  3919. liveBends.clear();
  3920. }
  3921. void AudioEngine::updateAutomationRecording (bool active)
  3922. {
  3923. const auto now = juce::Time::getMillisecondCounterHiRes();
  3924. const auto recording = active && recordOptions.recordAutomation;
  3925. const auto grid = recordOptions.quantiseAutomation ? recordOptions.quantise : std::int64_t { 0 };
  3926. auto writeFor = [this] (const AutomationTarget& target) -> AutomationWrite& {
  3927. auto it = std::find_if (takeWrites.begin(), takeWrites.end(), [&] (const AutomationWrite& w) { return w.target == target; });
  3928. if (it != takeWrites.end())
  3929. return *it;
  3930. AutomationWrite w;
  3931. w.target = target;
  3932. w.name = nameAutomation ? nameAutomation (target) : std::string ("Automation");
  3933. takeWrites.push_back (w);
  3934. return takeWrites.back();
  3935. };
  3936. // writes what was sampled (one undo step for the whole take); `ended` = the gestures that are over
  3937. auto commit = [&] (const std::vector<AutomationTarget>& ended) {
  3938. if (std::none_of (touches.begin(), touches.end(), [] (const Touch& t) { return ! t.pending.empty(); }))
  3939. return;
  3940. const auto songMode = song.mode == PlayMode::song;
  3941. editSong ([&] (Song& s) {
  3942. for (auto& t : touches)
  3943. if (! t.pending.empty())
  3944. {
  3945. auto& w = writeFor (t.target);
  3946. recordedAutomationPoints += (int) t.pending.size();
  3947. if (songMode)
  3948. commitAutomationPoints (s, w, std::move (t.pending), grid, automationLinear || noteTakeLinear);
  3949. else
  3950. commitEventPoints (s, automationPattern, w, std::move (t.pending), automationLoopLength, grid);
  3951. t.pending.clear();
  3952. }
  3953. }, ! automationTakeHasUndoStep);
  3954. automationTakeHasUndoStep = true;
  3955. for (const auto& target : ended)
  3956. writeFor (target).lastLocal = -1; // the next gesture on it starts a new stretch
  3957. };
  3958. // FL: while recording, the moved control wins over its playing automation at once (REA round 146); the
  3959. // automation of a touched target does not drive it until the gesture ends and its points are written.
  3960. auto overrideTouched = [this] {
  3961. if (rackProcessor == nullptr)
  3962. return;
  3963. std::vector<int> slots, one;
  3964. for (const auto& t : touches)
  3965. {
  3966. RackState::slotsOfTarget (song, t.target, one);
  3967. slots.insert (slots.end(), one.begin(), one.end());
  3968. }
  3969. if (slots.empty() && ! automationOverrideActive)
  3970. return;
  3971. rackProcessor->getRenderer().setOverriddenSlots (slots);
  3972. automationOverrideActive = ! slots.empty();
  3973. };
  3974. // the take's own clips reach the playhead (FL: the clip keeps growing until recording stops, holding the last value)
  3975. auto growClips = [this] (std::int64_t songTick, bool finished) {
  3976. if (song.mode != PlayMode::song || songTick < 0)
  3977. return;
  3978. const auto needed = std::any_of (takeWrites.begin(), takeWrites.end(), [&] (const AutomationWrite& w) {
  3979. if (! w.createdByTake || w.automation < 0)
  3980. return false;
  3981. for (const auto& c : song.playlist)
  3982. if (c.kind == ClipKind::automation && c.automation == w.automation)
  3983. return finished || c.end() < songTick;
  3984. return false;
  3985. });
  3986. if (! needed)
  3987. return;
  3988. editSong ([&] (Song& s) {
  3989. for (const auto& w : takeWrites)
  3990. growTakeClip (s, w, songTick, finished);
  3991. }, ! automationTakeHasUndoStep);
  3992. automationTakeHasUndoStep = true;
  3993. };
  3994. if (! recording)
  3995. {
  3996. commit ({});
  3997. touches.clear();
  3998. overrideTouched();
  3999. if (! active)
  4000. {
  4001. growClips (lastAutomationTick, true);
  4002. takeWrites.clear();
  4003. automationTakeHasUndoStep = false;
  4004. automationLoopLength = 0;
  4005. lastAutomationTick = -1;
  4006. if (std::exchange (automationLinear, false))
  4007. updateLinearSong();
  4008. }
  4009. return;
  4010. }
  4011. if (automationLoopLength <= 0)
  4012. {
  4013. automationPattern = song.currentPattern;
  4014. automationLoopLength = song.patterns.empty() ? ppq * 4
  4015. : song.patterns[(std::size_t) juce::jlimit (0, (int) song.patterns.size() - 1, song.currentPattern)]
  4016. .effectiveLength (song.beatsPerBar);
  4017. }
  4018. const auto tick = estimatedPositionNow();
  4019. // FL's "Record automation" of an internal-controller link (round 190cs): the controller's output, as the link maps
  4020. // it, is written like a hand move for as long as automation is recorded
  4021. for (const auto& a : song.automations)
  4022. {
  4023. if (! a.isLive() || ! a.recordLive)
  4024. continue;
  4025. auto output = -1.0f;
  4026. if (a.source.channel >= 0)
  4027. {
  4028. if (const auto instrument = getChannelInstrument (a.source.channel))
  4029. output = instrument->controlOutput (a.source.output);
  4030. }
  4031. else if (const auto effect = getEffect (a.source.track, a.source.slot))
  4032. output = effect->controlOutput (a.source.output);
  4033. if (output < 0.0f || std::isnan (output))
  4034. continue;
  4035. auto it = std::find_if (touches.begin(), touches.end(), [&] (const Touch& t) { return t.target == a.target; });
  4036. if (it == touches.end())
  4037. {
  4038. touches.push_back ({ a.target, now, false, {} });
  4039. it = touches.end() - 1;
  4040. }
  4041. it->lastMs = now;
  4042. it->liveValue = juce::jlimit (0.0f, 1.0f, a.mapLive (juce::jlimit (0.0f, 1.0f, output)));
  4043. }
  4044. std::vector<AutomationTarget> ended;
  4045. for (auto& t : touches)
  4046. {
  4047. const auto alive = t.held || now - t.lastMs < 350.0;
  4048. const auto value = t.liveValue >= 0.0f ? t.liveValue : currentTargetValue (t.target);
  4049. if (value < 0.0f)
  4050. {
  4051. ended.push_back (t.target);
  4052. continue;
  4053. }
  4054. if (alive)
  4055. t.pending.push_back ({ tick, value });
  4056. else
  4057. ended.push_back (t.target);
  4058. }
  4059. // song mode without a loop region: from the first move on, the song plays on past its end until recording stops
  4060. if (! takeWrites.empty() || ! touches.empty())
  4061. if (! automationLinear && song.mode == PlayMode::song && ! song.loopPlays())
  4062. {
  4063. automationLinear = true;
  4064. updateLinearSong();
  4065. }
  4066. if (song.mode == PlayMode::song)
  4067. lastAutomationTick = songTickForRecorded (song, tick, automationLinear || noteTakeLinear);
  4068. if (! ended.empty() || --automationCommitCountdown <= 0)
  4069. {
  4070. growClips (lastAutomationTick, false);
  4071. commit (ended);
  4072. automationCommitCountdown = 6; // about 5 writes per second while a control keeps moving
  4073. }
  4074. touches.erase (std::remove_if (touches.begin(), touches.end(),
  4075. [&] (const Touch& t) { return std::find (ended.begin(), ended.end(), t.target) != ended.end(); }),
  4076. touches.end());
  4077. overrideTouched();
  4078. }
  4079. void AudioEngine::applyControllers()
  4080. {
  4081. ControllerEvent e;
  4082. // this frame's events in their order (round 190cs: a key or button link in Latch / Inc / Stay mode acts on each
  4083. // press, so presses are not merged); a plain controller still moves its control once, to its last value
  4084. std::vector<ControllerEvent> events;
  4085. std::map<std::tuple<int, int, int>, std::size_t> last; // (number, channel, port) -> its last event this frame
  4086. controllerLearnTick = learning.kind != AutomationTargetKind::none || multilink.has_value();
  4087. while (controllerQueue.pop (e))
  4088. {
  4089. // Auto detect of the Remote control settings window: controllers, and keys as they are pressed
  4090. if (! isNoteLink (e.cc) || e.value > 0)
  4091. controllerSeen = { e.port, e.channel, e.cc, e.value, controllerSeen.serial + 1 };
  4092. if (e.seenOnly)
  4093. continue;
  4094. if (isNoteLink (e.cc)) // (MIDI learn and Multilink take controllers, as before)
  4095. {
  4096. last[{ e.cc, e.channel, e.port }] = events.size();
  4097. events.push_back (e);
  4098. continue;
  4099. }
  4100. if (learning.kind != AutomationTargetKind::none && learningGlobal)
  4101. {
  4102. // "Override global link...": the link goes to the settings, for every project (REA round 146)
  4103. auto p = midiPrefs;
  4104. prefs::GlobalLink g { e.cc, e.channel, (int) learning.kind, learning.index, learning.slot, learning.param };
  4105. g.port = e.port; // (round 190bt: the device's port number, as FL's Auto detect fills it)
  4106. p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
  4107. [&] (const prefs::GlobalLink& l) {
  4108. return l.kind == g.kind && l.index == g.index && l.slot == g.slot && l.param == g.param;
  4109. }),
  4110. p.globalLinks.end());
  4111. p.globalLinks.push_back (g);
  4112. learning = {};
  4113. learningGlobal = false;
  4114. setMidiPrefs (p, saveGlobalLinks);
  4115. }
  4116. else if (learning.kind == AutomationTargetKind::none && multilink)
  4117. {
  4118. // FL's Multilink (round 177b-4): the first message of each controller links the next queued control
  4119. if (const auto link = multilink->controller (e.cc, e.channel))
  4120. {
  4121. if (multilink->global) // "Override global links": as "Override global link...", for every project
  4122. {
  4123. auto p = midiPrefs;
  4124. prefs::GlobalLink g { link->cc, link->channel, (int) link->target.kind, link->target.index, link->target.slot,
  4125. link->target.param };
  4126. g.port = e.port;
  4127. p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
  4128. [&] (const prefs::GlobalLink& l) {
  4129. return l.kind == g.kind && l.index == g.index && l.slot == g.slot && l.param == g.param;
  4130. }),
  4131. p.globalLinks.end());
  4132. p.globalLinks.push_back (g);
  4133. setMidiPrefs (p, saveGlobalLinks);
  4134. }
  4135. else
  4136. editSong ([l = *link, port = e.port] (Song& s) {
  4137. s.midiLinks.erase (std::remove_if (s.midiLinks.begin(), s.midiLinks.end(), [&] (const MidiLink& m) { return m.target == l.target; }),
  4138. s.midiLinks.end());
  4139. MidiLink made { l.cc, l.channel, l.target };
  4140. made.port = port;
  4141. s.midiLinks.push_back (std::move (made));
  4142. });
  4143. if (multilink->complete())
  4144. multilink.reset(); // FL: "the process will auto-close once the number of hardware controls tweaked
  4145. // equals the number of software targets"
  4146. sendChangeMessage();
  4147. }
  4148. }
  4149. else if (learning.kind != AutomationTargetKind::none)
  4150. {
  4151. // MIDI learn: replace the old link for the same target with the new one
  4152. editSong ([t = learning, e] (Song& s) {
  4153. s.midiLinks.erase (std::remove_if (s.midiLinks.begin(), s.midiLinks.end(), [&] (const MidiLink& l) { return l.target == t; }),
  4154. s.midiLinks.end());
  4155. MidiLink made { e.cc, e.channel, t };
  4156. made.port = e.port;
  4157. s.midiLinks.push_back (std::move (made));
  4158. });
  4159. learning = {};
  4160. }
  4161. last[{ e.cc, e.channel, e.port }] = events.size();
  4162. events.push_back (e);
  4163. }
  4164. const auto links = linksWithGlobal (song.midiLinks, getGlobalLinks());
  4165. {
  4166. std::uint64_t bits[2] {}, notes[2] {};
  4167. for (const auto& link : links)
  4168. if (link.cc >= 0 && link.cc < 128)
  4169. bits[link.cc >> 6] |= std::uint64_t { 1 } << (link.cc & 63);
  4170. else if (isNoteLink (link.cc))
  4171. notes[(link.cc - linkNoteBase) >> 6] |= std::uint64_t { 1 } << ((link.cc - linkNoteBase) & 63);
  4172. for (int w = 0; w < 2; ++w)
  4173. {
  4174. linkedCcs[(std::size_t) w].store (bits[w], std::memory_order_relaxed);
  4175. linkedNotes[(std::size_t) w].store (notes[w], std::memory_order_relaxed);
  4176. }
  4177. }
  4178. if ((events.empty() || links.empty()) && linkSmoothing.empty())
  4179. return;
  4180. // one snapshot per frame, outside the undo history (like turning the knob)
  4181. std::vector<std::pair<AutomationTarget, float>> changes;
  4182. const auto mixerTrack = selectedMixerTrackForLinks ? selectedMixerTrackForLinks() : -1;
  4183. std::map<std::tuple<int, int, int, int>, float> moved; // a control's position after this frame's events so far
  4184. for (std::size_t i = 0; i < events.size(); ++i)
  4185. {
  4186. const auto& ev = events[i];
  4187. const auto lastOfKey = last[{ ev.cc, ev.channel, ev.port }] == i;
  4188. for (const auto& link : links)
  4189. {
  4190. // (round 190bt: a link follows the devices with exactly its port number, as FL's controller id does)
  4191. if (link.cc != ev.cc || ! (link.channel < 0 || link.channel == ev.channel) || link.port != ev.port)
  4192. continue;
  4193. const auto absolute = linkformula::linkModeIsAbsolute (link.mode);
  4194. if (absolute && ! lastOfKey)
  4195. continue; // (a controller's earlier values this frame: only the last one moves the control)
  4196. static const linkformula::Formula oneToOne;
  4197. const auto* formula = &oneToOne;
  4198. if (! link.formula.empty()) // FL's mapping formula: Input = the controller's position, the result limited to 0..1
  4199. {
  4200. auto found = linkFormulas.find (link.formula);
  4201. if (found == linkFormulas.end())
  4202. {
  4203. if (linkFormulas.size() > 256)
  4204. linkFormulas.clear();
  4205. found = linkFormulas.emplace (link.formula, linkformula::Formula::compile (link.formula)).first;
  4206. }
  4207. formula = &found->second;
  4208. }
  4209. const auto t = linkOmniTarget (link, selectedChannel, mixerTrack); // "Omni": the selected channel / track
  4210. const std::tuple<int, int, int, int> id { (int) t.kind, t.index, t.slot, t.param };
  4211. // FL's Mode (round 190cs): Latch and Inc start from where the control is now
  4212. auto current = 0.0f;
  4213. if (! absolute)
  4214. {
  4215. if (const auto m = moved.find (id); m != moved.end())
  4216. current = m->second;
  4217. else if (const auto now = currentTargetValue (t); now >= 0.0f)
  4218. current = now;
  4219. }
  4220. const auto mapped = linkformula::linkModeValue (link.mode, *formula, (float) ev.value / 127.0f, current);
  4221. if (! mapped)
  4222. continue; // (a release in Latch / Inc / Stay)
  4223. const auto v = *mapped;
  4224. // takeover: only parameters the song holds (a plugin's own parameters have no value to compare here), and
  4225. // only for links that follow the controller's position
  4226. const auto songHeld = t.kind != AutomationTargetKind::channelParam && t.kind != AutomationTargetKind::effectParam;
  4227. if (midiPrefs.pickup && songHeld && absolute)
  4228. {
  4229. auto& state = pickups[{ ev.cc, ev.channel, (int) t.kind, t.index, t.slot, t.param }];
  4230. if (! prefs::pickupUpdate (state, song.targetValue (t), v))
  4231. continue;
  4232. }
  4233. moved[id] = v;
  4234. noteTweaked (t); // a linked controller's move is a tweak (Last tweaked, automation recording)
  4235. if (link.smooth && link.smoothing != 0)
  4236. {
  4237. auto s = std::find_if (linkSmoothing.begin(), linkSmoothing.end(), [&] (const LinkSmoothing& x) { return x.link == link; });
  4238. if (s == linkSmoothing.end())
  4239. {
  4240. // starts from where the control is (a control the song does not hold starts at the new position)
  4241. LinkSmoothing fresh { link, v, {} };
  4242. if (const auto now = currentTargetValue (t); now >= 0.0f)
  4243. fresh.filter.step (now, 0.0, link.smoothing);
  4244. linkSmoothing.push_back (std::move (fresh));
  4245. }
  4246. else
  4247. s->target = v;
  4248. continue;
  4249. }
  4250. changes.push_back ({ t, v });
  4251. }
  4252. }
  4253. stepLinkSmoothing (changes);
  4254. applyTargetValues (changes);
  4255. }
  4256. void AudioEngine::applyTargetValues (const std::vector<std::pair<AutomationTarget, float>>& changes)
  4257. {
  4258. std::vector<std::pair<AutomationTarget, float>> pluginChanges;
  4259. editSong ([&] (Song& s) {
  4260. for (const auto& [target, v] : changes)
  4261. if (! s.setTargetValue (target, v))
  4262. pluginChanges.push_back ({ target, v });
  4263. }, false);
  4264. // plugin parameters live in the plugin
  4265. for (const auto& [target, v] : pluginChanges)
  4266. {
  4267. if (target.kind == AutomationTargetKind::channelParam)
  4268. {
  4269. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (target.index).get()))
  4270. p->setParameterFromUi (target.param, v);
  4271. // a MIDI Out's controls: the plugins on its port (REA_rodada133 §4)
  4272. if (target.index >= 0 && target.index < (int) song.channels.size()
  4273. && song.channels[(std::size_t) target.index].instrument == InstrumentKind::midiOut)
  4274. {
  4275. const auto port = midictl::parseMidiOut (song.channels[(std::size_t) target.index].pluginState).port;
  4276. for (int c = 0; c < (int) song.channels.size(); ++c)
  4277. if (song.channels[(std::size_t) c].instrument == InstrumentKind::plugin && song.channels[(std::size_t) c].plugin.midiInPort == port)
  4278. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (c).get()))
  4279. p->setParameterFromUi (target.param, v);
  4280. }
  4281. }
  4282. if (target.kind == AutomationTargetKind::effectParam)
  4283. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (target.index, target.slot).get()))
  4284. p->setParameterFromUi (target.param, v);
  4285. }
  4286. }
  4287. void AudioEngine::timerCallback()
  4288. {
  4289. // MIDI inputs: open the enabled devices that appeared (or were not ready) and reopen the ones that came back
  4290. if (prefetcher != nullptr && ++midiCheckTicks >= 60) // every 2 s
  4291. {
  4292. midiCheckTicks = 0;
  4293. enableAllMidiInputs();
  4294. }
  4295. updateRealtimeStats();
  4296. if (++hwTicks >= 5) // (6 times a second)
  4297. {
  4298. hwTicks = 0;
  4299. pumpEdisonRecordings(); // (round 190cd)
  4300. applyHardwareInsertPings();
  4301. }
  4302. rt::promotePending(); // Linux: real-time priority for the audio threads seen since the last tick (round 161)
  4303. updateAudition(); // (round 190ao: the preset audition's note starts and ends here)
  4304. applyControllers();
  4305. controllerIo.pump (controllerLearnTick); // (controller profiles, round 190aw)
  4306. // playback started: the moved controls follow their automation again (the renderer cleared its own mask)
  4307. if (const auto playing = transport.playing.load(); playing != std::exchange (releasedWasPlaying, playing) && playing)
  4308. releasedTargets.clear();
  4309. else if (! releasedTargets.empty())
  4310. publishReleasedTargets(); // (the slots follow the song: an automation added or removed renumbers them)
  4311. if (const auto note = pendingMarkerNote.exchange (-1); note >= 0)
  4312. jumpToMarker (note); // FL's "Song marker jump": note 0 = the first marker
  4313. updateRecording();
  4314. updatePerformanceRecording();
  4315. if (clipLauncher != nullptr)
  4316. {
  4317. updateLauncherRecording();
  4318. updateSlotRecording();
  4319. }
  4320. rackExchange.collectGarbage();
  4321. if (levelsPending && ! juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown())
  4322. flushLevels(); // a level drag ended: the full snapshot catches up (round 171c)
  4323. // Plugins are prepared at a fixed rate; if the device changed rate, recreate them.
  4324. // A plugin whose latency changed (preset change, lookahead) requests a new PDC plan.
  4325. const auto rateChanged = std::abs (transport.sampleRate.load() - lastPublishedShape.sampleRate) > 0.5;
  4326. const auto latencies = lastPublishedShape.currentLatencies();
  4327. if (! publishing && (rateChanged || latencies != lastPublishedShape.latencies)) // (not inside a publish: see publishSong)
  4328. {
  4329. // the plugins made for the new rate start from what the running ones hold now (issue #134: they started from
  4330. // the state of the last save or export, so a device at another rate undid every change made in their windows)
  4331. if (rateChanged)
  4332. capturePluginStates();
  4333. // (diagnostics: which unit's latency moved)
  4334. if (! rateChanged)
  4335. for (std::size_t i = 0; i < latencies.size() && i < lastPublishedShape.latencies.size(); ++i)
  4336. if (latencies[i] != lastPublishedShape.latencies[i])
  4337. {
  4338. lastLatencyChange = juce::String ((int) i) + ": " + juce::String (lastPublishedShape.latencies[i]) + " -> " + juce::String (latencies[i]);
  4339. break;
  4340. }
  4341. ++latencyRepublishes;
  4342. publishSong();
  4343. }
  4344. }
  4345. // Performance mode's recording (FL's "Clips" filter, REA round 146 B5: a launched clip is written to its playlist
  4346. // track): every pass of a launched clip that ended while recording becomes a copy of that clip in the arrangement,
  4347. // on the same track, where the song position was when the pass began.
  4348. void AudioEngine::updatePerformanceRecording()
  4349. {
  4350. auto& live = *performanceLive;
  4351. performanceMidiOn.store (song.performanceMode && song.mode == PlayMode::song && song.performanceZoneEnd() > 0, std::memory_order_relaxed);
  4352. const auto on = transport.recording.load() && transport.playing.load() && song.performanceMode && song.mode == PlayMode::song
  4353. && recordOptions.recordClips;
  4354. if (on && ! live.recording.load (std::memory_order_relaxed))
  4355. perfTakeHasUndoStep = false;
  4356. live.recording.store (on, std::memory_order_relaxed);
  4357. std::vector<Clip> clips;
  4358. perf::RecordedPass pass;
  4359. while (live.recorded.pop (pass))
  4360. if (Clip c; perf::recordedClip (song, pass, c) && c.start >= song.performanceZoneEnd())
  4361. clips.push_back (c);
  4362. if (clips.empty())
  4363. return;
  4364. editSong ([&clips] (Song& s) {
  4365. for (const auto& c : clips)
  4366. {
  4367. // the take replaces what was under it on that track (like FL's recorded clips)
  4368. const auto end = c.end();
  4369. for (auto& o : s.playlist)
  4370. if (o.track == c.track && o.start < end && o.end() > c.start && o.start >= s.performanceZoneEnd())
  4371. {
  4372. if (o.start >= c.start)
  4373. o.length = 0; // removed below
  4374. else
  4375. o.length = c.start - o.start;
  4376. }
  4377. s.playlist.erase (std::remove_if (s.playlist.begin(), s.playlist.end(), [] (const Clip& o) { return o.length <= 0; }),
  4378. s.playlist.end());
  4379. s.playlist.push_back (c);
  4380. }
  4381. }, ! perfTakeHasUndoStep);
  4382. perfTakeHasUndoStep = true;
  4383. }
  4384. // The clip grid's recording (round 181a): while recording, what is launched is written into the Playlist. Every pass that
  4385. // ended becomes a copy of its clip on its track, where the song was when the pass began, replacing what was under it.
  4386. void AudioEngine::updateLauncherRecording()
  4387. {
  4388. auto& runtime = *clipLauncher;
  4389. const auto on = transport.recording.load() && transport.playing.load() && song.clipGrid && song.mode == PlayMode::song && recordOptions.recordClips;
  4390. if (on && ! runtime.recording.load (std::memory_order_relaxed))
  4391. launcherTakeHasUndoStep = false;
  4392. runtime.recording.store (on, std::memory_order_relaxed);
  4393. std::vector<Clip> clips;
  4394. launcher::RecordedPass pass;
  4395. while (runtime.recorded.pop (pass))
  4396. if (Clip c; song.clipGrid && launcher::recordedClip (*song.clipGrid, pass, c))
  4397. clips.push_back (c);
  4398. if (clips.empty())
  4399. return;
  4400. editSong ([&clips] (Song& s) {
  4401. for (const auto& c : clips)
  4402. {
  4403. const auto end = c.end();
  4404. for (auto& o : s.playlist)
  4405. if (o.track == c.track && o.start < end && o.end() > c.start)
  4406. {
  4407. if (o.start >= c.start)
  4408. o.length = 0; // removed below
  4409. else
  4410. o.length = c.start - o.start;
  4411. }
  4412. s.playlist.erase (std::remove_if (s.playlist.begin(), s.playlist.end(), [] (const Clip& o) { return o.length <= 0; }),
  4413. s.playlist.end());
  4414. s.playlist.push_back (c);
  4415. }
  4416. }, ! launcherTakeHasUndoStep);
  4417. launcherTakeHasUndoStep = true;
  4418. }
  4419. void AudioEngine::choosePreferredDriver()
  4420. {
  4421. #if JUCE_LINUX || JUCE_BSD
  4422. std::vector<std::pair<std::string, bool>> types;
  4423. for (auto* type : deviceManager.getAvailableDeviceTypes())
  4424. {
  4425. type->scanForDevices();
  4426. types.emplace_back (type->getTypeName().toStdString(), ! type->getDeviceNames (false).isEmpty());
  4427. }
  4428. const auto best = juce::String (prefs::preferredLinuxDriver (types));
  4429. if (best.isNotEmpty() && best != deviceManager.getCurrentAudioDeviceType())
  4430. {
  4431. deviceManager.setCurrentAudioDeviceType (best, true);
  4432. if (deviceManager.getCurrentAudioDevice() == nullptr) // it would not open: back to what worked
  4433. deviceManager.initialise (0, 2, nullptr, true);
  4434. }
  4435. #endif
  4436. }
  4437. void AudioEngine::chooseSafeBufferSize()
  4438. {
  4439. auto* device = deviceManager.getCurrentAudioDevice();
  4440. if (device == nullptr)
  4441. return;
  4442. std::vector<int> sizes;
  4443. for (auto b : device->getAvailableBufferSizes())
  4444. sizes.push_back (b);
  4445. const auto current = device->getCurrentBufferSizeSamples();
  4446. const auto target = prefs::safeBufferSize (sizes, current, device->getCurrentSampleRate());
  4447. if (target > 0 && target != current)
  4448. {
  4449. auto setup = deviceManager.getAudioDeviceSetup();
  4450. setup.bufferSize = target;
  4451. deviceManager.setAudioDeviceSetup (setup, true);
  4452. }
  4453. }
  4454. bool AudioEngine::showDriverPanel (juce::AudioDeviceManager& devices)
  4455. {
  4456. auto* device = devices.getCurrentAudioDevice();
  4457. if (device == nullptr || ! device->hasControlPanel())
  4458. return false;
  4459. // JUCE's ASIO device: true when the panel stayed open long enough to have changed something (its own selector
  4460. // then closes and restarts the device the same way)
  4461. if (! device->showControlPanel())
  4462. return false;
  4463. auto setup = devices.getAudioDeviceSetup();
  4464. devices.closeAudioDevice(); // deletes `device`
  4465. device = nullptr;
  4466. // 0 = the new device's default, i.e. the preferred size the driver now reports (ASIO4ALL / FL ASIO: its panel's
  4467. // buffer); a driver that keeps no preferred size gets LYNX's usual default
  4468. setup.bufferSize = 0;
  4469. devices.setAudioDeviceSetup (setup, true);
  4470. return true;
  4471. }
  4472. namespace
  4473. {
  4474. // A driver with its own panel, like ASIO4ALL / FL ASIO: the panel sets the preferred buffer size the next device
  4475. // object reads. Every live device is tracked, so a call on a deleted one is caught instead of crashing.
  4476. struct PanelTestState
  4477. {
  4478. std::vector<const void*> alive;
  4479. int preferred = 256;
  4480. int panelResult = 64; // the size the panel picks; 0 = the panel changes nothing (returns false)
  4481. bool calledDeleted = false;
  4482. };
  4483. PanelTestState& panelTest()
  4484. {
  4485. static PanelTestState state;
  4486. return state;
  4487. }
  4488. struct PanelTestDevice final : juce::AudioIODevice
  4489. {
  4490. PanelTestDevice() : juce::AudioIODevice ("Panel test device", "Panel test"), preferred (panelTest().preferred) { panelTest().alive.push_back (this); }
  4491. ~PanelTestDevice() override
  4492. {
  4493. close();
  4494. auto& alive = panelTest().alive;
  4495. alive.erase (std::remove (alive.begin(), alive.end(), (const void*) this), alive.end());
  4496. }
  4497. bool isAlive() const { const auto& a = panelTest().alive; return std::find (a.begin(), a.end(), (const void*) this) != a.end(); }
  4498. juce::StringArray getOutputChannelNames() override { return { "Out 1", "Out 2" }; }
  4499. juce::StringArray getInputChannelNames() override { return {}; }
  4500. juce::Array<double> getAvailableSampleRates() override { return { 44100.0, 48000.0 }; }
  4501. juce::Array<int> getAvailableBufferSizes() override { return { 64, 128, 256, 272, 512 }; }
  4502. int getDefaultBufferSize() override { return preferred; }
  4503. juce::String open (const juce::BigInteger&, const juce::BigInteger& outs, double rate, int size) override
  4504. {
  4505. rateNow = rate;
  4506. sizeNow = size;
  4507. outsNow = outs;
  4508. opened = true;
  4509. return {};
  4510. }
  4511. void close() override { stop(); opened = false; }
  4512. bool isOpen() override { return opened; }
  4513. void start (juce::AudioIODeviceCallback* cb) override
  4514. {
  4515. if (cb != nullptr)
  4516. cb->audioDeviceAboutToStart (this);
  4517. callback = cb;
  4518. }
  4519. void stop() override
  4520. {
  4521. if (auto* cb = std::exchange (callback, nullptr))
  4522. cb->audioDeviceStopped();
  4523. }
  4524. bool isPlaying() override { return callback != nullptr; }
  4525. juce::String getLastError() override { return {}; }
  4526. int getCurrentBufferSizeSamples() override { return sizeNow; }
  4527. double getCurrentSampleRate() override { return rateNow; }
  4528. int getCurrentBitDepth() override { return 32; }
  4529. juce::BigInteger getActiveOutputChannels() const override { return outsNow; }
  4530. juce::BigInteger getActiveInputChannels() const override { return {}; }
  4531. int getOutputLatencyInSamples() override { return 0; }
  4532. int getInputLatencyInSamples() override { return 0; }
  4533. bool hasControlPanel() const override { return true; }
  4534. bool showControlPanel() override
  4535. {
  4536. if (! isAlive())
  4537. {
  4538. panelTest().calledDeleted = true;
  4539. return false;
  4540. }
  4541. if (panelTest().panelResult == 0)
  4542. return false;
  4543. panelTest().preferred = panelTest().panelResult; // what the driver now reports to a new device object
  4544. return true;
  4545. }
  4546. const int preferred;
  4547. double rateNow = 44100.0;
  4548. int sizeNow = 0;
  4549. juce::BigInteger outsNow;
  4550. bool opened = false;
  4551. juce::AudioIODeviceCallback* callback = nullptr;
  4552. };
  4553. struct PanelTestType final : juce::AudioIODeviceType
  4554. {
  4555. PanelTestType() : juce::AudioIODeviceType ("Panel test") {}
  4556. void scanForDevices() override {}
  4557. juce::StringArray getDeviceNames (bool input) const override { return input ? juce::StringArray() : juce::StringArray ("Panel test device"); }
  4558. int getDefaultDeviceIndex (bool input) const override { return input ? -1 : 0; }
  4559. int getIndexOfDevice (juce::AudioIODevice* d, bool input) const override { return d != nullptr && ! input ? 0 : -1; }
  4560. bool hasSeparateInputsAndOutputs() const override { return false; }
  4561. juce::AudioIODevice* createDevice (const juce::String& out, const juce::String&) override
  4562. {
  4563. return out == "Panel test device" ? new PanelTestDevice() : nullptr;
  4564. }
  4565. };
  4566. } // namespace
  4567. juce::String AudioEngine::driverPanelSelfTest()
  4568. {
  4569. auto& state = panelTest();
  4570. state = {};
  4571. juce::AudioDeviceManager devices;
  4572. devices.addAudioDeviceType (std::make_unique<PanelTestType>());
  4573. devices.setCurrentAudioDeviceType ("Panel test", true);
  4574. juce::AudioDeviceManager::AudioDeviceSetup setup;
  4575. setup.outputDeviceName = "Panel test device";
  4576. setup.sampleRate = 44100.0;
  4577. setup.bufferSize = 272; // chosen in LYNX's own buffer box
  4578. setup.useDefaultOutputChannels = true;
  4579. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  4580. return "open: " + error;
  4581. auto* before = devices.getCurrentAudioDevice();
  4582. if (before == nullptr || before->getCurrentBufferSizeSamples() != 272)
  4583. return "open: buffer " + juce::String (before != nullptr ? before->getCurrentBufferSizeSamples() : -1);
  4584. // a panel that changes nothing: the same device keeps running with LYNX's buffer
  4585. state.panelResult = 0;
  4586. if (showDriverPanel (devices) || devices.getCurrentAudioDevice() != before || before->getCurrentBufferSizeSamples() != 272)
  4587. return "unchanged panel reopened the device";
  4588. // the panel picks 64 samples (issue #13's ASIO4ALL setting): reopened, the panel's buffer kept, never the old object
  4589. state.panelResult = 64;
  4590. if (! showDriverPanel (devices))
  4591. return "changed panel did not reopen";
  4592. auto* after = devices.getCurrentAudioDevice();
  4593. if (state.calledDeleted)
  4594. return "called the deleted device";
  4595. if (after == nullptr || ! after->isOpen())
  4596. return "no device after the panel";
  4597. if (after->getCurrentBufferSizeSamples() != 64)
  4598. return "buffer " + juce::String (after->getCurrentBufferSizeSamples()) + " after the panel chose 64";
  4599. if (state.alive.size() != 1)
  4600. return juce::String ((int) state.alive.size()) + " devices alive";
  4601. // and the reopened device can show its panel again (the button pressed twice)
  4602. state.panelResult = 128;
  4603. if (! showDriverPanel (devices) || devices.getCurrentAudioDevice() == nullptr || devices.getCurrentAudioDevice()->getCurrentBufferSizeSamples() != 128
  4604. || state.calledDeleted)
  4605. return "second panel";
  4606. devices.closeAudioDevice();
  4607. return "OK";
  4608. }
  4609. juce::File AudioEngine::glitchLogFile() { return PluginHost::settingsFolder().getChildFile ("audio-glitches.log"); }
  4610. void AudioEngine::updateRealtimeStats()
  4611. {
  4612. // the message thread's pulse: this 30 Hz timer arriving late means the UI is saturated
  4613. {
  4614. const auto now = juce::Time::getMillisecondCounterHiRes();
  4615. if (lastUiPulseMs > 0.0)
  4616. uiPulse.maxGapMs = juce::jmax (uiPulse.maxGapMs, now - lastUiPulseMs);
  4617. lastUiPulseMs = now;
  4618. ++uiPulse.calls;
  4619. }
  4620. // every ~2 s: the share of real time each channel / insert effect took in that window
  4621. if (rackProcessor != nullptr && juce::Time::getMillisecondCounterHiRes() - lastUnitsWindowMs >= 2000.0)
  4622. {
  4623. lastUnitsWindowMs = juce::Time::getMillisecondCounterHiRes();
  4624. auto& renderer = rackProcessor->getRenderer();
  4625. const auto& units = renderer.unitTimes();
  4626. const auto processed = units.processedSamples.load (std::memory_order_relaxed);
  4627. const auto rate = juce::jmax (1.0, transport.sampleRate.load());
  4628. const auto audioNs = (double) (processed - std::min (processed, lastProcessedSamples)) / rate * 1.0e9;
  4629. lastProcessedSamples = processed;
  4630. lastChannelNs.resize (units.channelNs.size(), 0);
  4631. lastEffectNs.resize (units.effectNs.size(), 0);
  4632. std::vector<UnitLoad> loads;
  4633. auto take = [&] (const std::atomic<std::uint64_t>& total, std::uint64_t& last, std::atomic<std::uint64_t>& longest, auto&& name) {
  4634. const auto now = total.load (std::memory_order_relaxed);
  4635. const auto delta = now - std::min (now, last);
  4636. last = now;
  4637. const auto longestNs = const_cast<std::atomic<std::uint64_t>&> (longest).exchange (0, std::memory_order_relaxed);
  4638. if (delta > 0 && audioNs > 0.0)
  4639. loads.push_back ({ name(), (double) delta / audioNs, (double) longestNs * 1.0e-6 });
  4640. };
  4641. auto& mutableUnits = const_cast<RackRenderer::UnitTimes&> (units);
  4642. for (std::size_t c = 0; c < units.channelNs.size(); ++c)
  4643. take (units.channelNs[c], lastChannelNs[c], mutableUnits.channelMaxNs[c], [&] {
  4644. return c < song.channels.size() ? juce::String::fromUTF8 (song.channels[c].name.c_str()) : "Channel " + juce::String ((int) c + 1);
  4645. });
  4646. for (std::size_t k = 0; k < units.effectNs.size(); ++k)
  4647. take (units.effectNs[k], lastEffectNs[k], mutableUnits.effectMaxNs[k], [&] {
  4648. const auto t = k / (std::size_t) maxEffectSlots, slot = k % (std::size_t) maxEffectSlots;
  4649. juce::String effect;
  4650. if (t < song.mixer.size() && slot < song.mixer[t].effects.size())
  4651. {
  4652. const auto& fx = song.mixer[t].effects[slot];
  4653. effect = juce::String::fromUTF8 (fx.plugin.name.empty() ? effectInfo (fx.kind).name : fx.plugin.name.c_str());
  4654. }
  4655. const auto track = t == 0 ? juce::String ("Master") : (t < song.mixer.size() && ! song.mixer[t].name.empty() ? juce::String::fromUTF8 (song.mixer[t].name.c_str())
  4656. : "Insert " + juce::String ((int) t));
  4657. return track + " / " + juce::String ((int) slot + 1) + " " + effect;
  4658. });
  4659. std::sort (loads.begin(), loads.end(), [] (const UnitLoad& a, const UnitLoad& b) { return a.load > b.load; });
  4660. if (loads.size() > 8)
  4661. loads.resize (8);
  4662. if (audioNs > 0.0)
  4663. heaviestUnits = std::move (loads);
  4664. }
  4665. // a line in the glitch log when callbacks ran over their deadline or the device called late
  4666. const auto stats = rtStats.snapshot();
  4667. if ((stats.overBudget > loggedOver || stats.lateCalls > loggedLate) && juce::Time::getMillisecondCounterHiRes() - lastLogMs > 2000.0)
  4668. {
  4669. // (appended by fileJobs: this runs on the message thread, and at a small buffer glitches come every 2 s)
  4670. const auto bar = transport.positionTicks.load() / (double) (ppq * juce::jmax (1, song.beatsPerBar)) + 1.0;
  4671. auto line = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H:%M:%S") + " over deadline +" + juce::String ((juce::int64) (stats.overBudget - loggedOver))
  4672. + ", late calls +" + juce::String ((juce::int64) (stats.lateCalls - loggedLate)) + ", at bar " + juce::String (bar, 2)
  4673. + (transport.playing.load() ? "" : " (stopped)") + "\n" + describeRealtime() + "\n";
  4674. fileJobs.post ([line = std::move (line), file = glitchLogFile()] {
  4675. if (file.getSize() > 1024 * 1024)
  4676. file.moveFileTo (file.withFileExtension ("old.log"));
  4677. file.appendText (line, false, false, "\r\n");
  4678. });
  4679. loggedOver = stats.overBudget;
  4680. loggedLate = stats.lateCalls;
  4681. lastLogMs = juce::Time::getMillisecondCounterHiRes();
  4682. }
  4683. }
  4684. juce::String AudioEngine::describeRealtime (bool withUnits) const
  4685. {
  4686. juce::String text;
  4687. if (auto* device = const_cast<juce::AudioDeviceManager&> (deviceManager).getCurrentAudioDevice())
  4688. {
  4689. const auto rate = device->getCurrentSampleRate();
  4690. const auto buffer = device->getCurrentBufferSizeSamples();
  4691. text << " device: " << device->getTypeName() << " / " << device->getName() << ", " << (int) rate << " Hz, buffer " << buffer
  4692. << " samples (deadline " << juce::String (prefs::bufferLatencyMs (buffer, rate), 2) << " ms), output latency "
  4693. << device->getOutputLatencyInSamples() << " samples, driver dropouts " << device->getXRunCount() << "\n";
  4694. #if JUCE_LINUX
  4695. text << " audio thread: " << (rt::status() == rt::Status::unknown ? juce::String ("not seen yet") : rt::describe()) << "\n";
  4696. #endif
  4697. #if JUCE_WINDOWS
  4698. if (const auto before = deviceThreadPriorityBefore.load (std::memory_order_relaxed); before > -100)
  4699. text << " device thread priority " << before << (deviceThreadPriorityAfter.load (std::memory_order_relaxed) != before
  4700. ? " -> " + juce::String (deviceThreadPriorityAfter.load (std::memory_order_relaxed)) + " (raised to MMCSS Pro Audio)"
  4701. : juce::String (boostDeviceThread ? " (kept)" : " (kept: LYNX_DEVICE_BOOST=0)")) << "\n";
  4702. #endif
  4703. }
  4704. else
  4705. text << " device: none\n";
  4706. const auto s = rtStats.snapshot();
  4707. text << " callbacks " << (juce::int64) s.callbacks << ": over deadline " << (juce::int64) s.overBudget << ", 80-100% " << (juce::int64) s.nearBudget
  4708. << ", late device calls " << (juce::int64) s.lateCalls << ", average load " << juce::String (s.averageLoad * 100.0, 1) << "%, max "
  4709. << juce::String (s.maxLoad * 100.0, 0) << "%, workers " << (workers != nullptr ? workers->workers() : 0) << "\n";
  4710. if (latencyRepublishes > 0)
  4711. text << " latency changes re-planned PDC " << latencyRepublishes << " times (last: unit " << lastLatencyChange << ")\n";
  4712. if (withUnits && heaviestUnits.empty())
  4713. text << " heaviest: not measured yet\n";
  4714. if (withUnits && ! heaviestUnits.empty())
  4715. {
  4716. text << " heaviest:";
  4717. for (std::size_t i = 0; i < heaviestUnits.size() && i < 5; ++i)
  4718. text << (i > 0 ? ";" : "") << " " << heaviestUnits[i].name << " " << juce::String (heaviestUnits[i].load * 100.0, 1) << "% (peak "
  4719. << juce::String (heaviestUnits[i].longestMs, 1) << " ms)";
  4720. text << "\n";
  4721. }
  4722. return text;
  4723. }
  4724. bool AudioEngine::freezeOutOfDate (int channel)
  4725. {
  4726. if (channel < 0 || channel >= (int) song.channels.size() || ! song.channels[(std::size_t) channel].freeze.on())
  4727. return false;
  4728. if (freezeChecks.size() < song.channels.size())
  4729. freezeChecks.resize (song.channels.size());
  4730. auto& check = freezeChecks[(std::size_t) channel];
  4731. if (check.stamp != songStamp)
  4732. {
  4733. check.stamp = songStamp;
  4734. check.outOfDate = sessionpack::freezeSource (song, channel, transport.sampleRate.load()) != song.channels[(std::size_t) channel].freeze.source;
  4735. }
  4736. return check.outOfDate;
  4737. }
  4738. std::shared_ptr<Instrument> AudioEngine::getChannelInstrument (int channel) const
  4739. {
  4740. if (channel < 0 || channel >= (int) lastPublishedShape.instruments.size())
  4741. return nullptr;
  4742. return lastPublishedShape.instruments[(std::size_t) channel];
  4743. }
  4744. std::shared_ptr<Effect> AudioEngine::getEffect (int track, int slot) const
  4745. {
  4746. if (externalEffect)
  4747. return externalEffect();
  4748. const auto& effects = lastPublishedShape.effects;
  4749. if (track < 0 || track >= (int) effects.size() || slot < 0 || slot >= (int) effects[(std::size_t) track].size())
  4750. return nullptr;
  4751. return effects[(std::size_t) track][(std::size_t) slot];
  4752. }
  4753. void AudioEngine::setPluginsRenderMode (bool offline)
  4754. {
  4755. vfx::script::setRealtime (! offline); // (an export waits for every VFX Script answer: exact and repeatable)
  4756. if (! offline)
  4757. midiSync.sendAllNotesOff(); // FL's "Send all notes off": after a render
  4758. // FL's "Notify about rendering mode" off: that plugin is not told (round 149); "Reset plugin when FL Studio
  4759. // resets": reset as the export starts (round 151)
  4760. for (std::size_t i = 0; i < song.channels.size(); ++i)
  4761. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()))
  4762. {
  4763. if (song.channels[i].plugin.notifyRender)
  4764. p->setRenderMode (offline);
  4765. if (offline)
  4766. p->resetForExport();
  4767. }
  4768. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  4769. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  4770. if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()))
  4771. {
  4772. if (song.mixer[t].effects[s].plugin.notifyRender)
  4773. p->setRenderMode (offline);
  4774. if (offline)
  4775. p->resetForExport();
  4776. }
  4777. // the plugins inside Patchers (REA_rodada141)
  4778. std::function<void (patcher::Graph*)> graphMode = [&] (patcher::Graph* graph) {
  4779. if (graph == nullptr)
  4780. return;
  4781. for (int n = 0; n < graph->nodeCount(); ++n)
  4782. {
  4783. auto effect = graph->effectAt (n);
  4784. auto instrument = graph->instrumentAt (n);
  4785. if (auto* p = dynamic_cast<PluginEffect*> (effect.get()))
  4786. p->setRenderMode (offline);
  4787. if (auto* p = dynamic_cast<PluginInstrument*> (instrument.get()))
  4788. p->setRenderMode (offline);
  4789. graphMode (patcher::graphOf (effect.get()));
  4790. graphMode (patcher::graphOf (instrument.get()));
  4791. }
  4792. };
  4793. for (std::size_t i = 0; i < song.channels.size(); ++i)
  4794. graphMode (patcher::graphOf (getChannelInstrument ((int) i).get()));
  4795. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  4796. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  4797. graphMode (patcher::graphOf (getEffect ((int) t, (int) s).get()));
  4798. }
  4799. void AudioEngine::stampWorkTime()
  4800. {
  4801. const auto now = (double) juce::Time::currentTimeMillis();
  4802. if (workSince > 0.0 && now > workSince)
  4803. song.info.workSeconds += (now - workSince) / 1000.0;
  4804. workSince = now;
  4805. }
  4806. double AudioEngine::workSecondsNow() const
  4807. {
  4808. const auto now = (double) juce::Time::currentTimeMillis();
  4809. return song.info.workSeconds + (workSince > 0.0 && now > workSince ? (now - workSince) / 1000.0 : 0.0);
  4810. }
  4811. // FL's Project info › "Reset working time" (round 190bx; its handler stores "now" as the project's start and restarts
  4812. // the clock, without a question): the project counts from this moment on. Not an undo step, as the clock itself.
  4813. void AudioEngine::resetWorkTime()
  4814. {
  4815. const auto now = (double) juce::Time::currentTimeMillis();
  4816. lynx::resetWorkTime (song.info, now / 1000.0);
  4817. workSince = now;
  4818. modified = true;
  4819. sendChangeMessage(); // (the Info page; nothing the audio thread plays changed)
  4820. }
  4821. void AudioEngine::markCreatedNow()
  4822. {
  4823. if (song.info.created <= 0.0)
  4824. song.info.created = (double) juce::Time::currentTimeMillis() / 1000.0;
  4825. }
  4826. void AudioEngine::pumpEdisonRecordings()
  4827. {
  4828. bool finished = false;
  4829. for (const auto& track : song.mixer)
  4830. for (const auto& fx : track.effects)
  4831. if (fx.kind == EffectKind::edison)
  4832. if (const auto session = edisonfx::findSession (fx.instance.id); session != nullptr && session->recording() && ! session->pump())
  4833. finished = true; // (the maximum recording time, or its effect is gone)
  4834. if (finished)
  4835. flushEdisonAudio();
  4836. }
  4837. void AudioEngine::flushEdisonAudio()
  4838. {
  4839. struct Change
  4840. {
  4841. std::uint64_t instance;
  4842. std::string path;
  4843. bool clearState;
  4844. };
  4845. std::vector<Change> changes;
  4846. for (const auto& track : song.mixer)
  4847. for (const auto& fx : track.effects)
  4848. {
  4849. if (fx.kind != EffectKind::edison)
  4850. continue;
  4851. const auto session = edisonfx::findSession (fx.instance.id);
  4852. if (session == nullptr || session->recording())
  4853. continue;
  4854. const auto wasDirty = session->dirty();
  4855. if (wasDirty)
  4856. {
  4857. if (session->document().audio.empty())
  4858. session->save ({});
  4859. else
  4860. {
  4861. auto folder = recordingFolder;
  4862. if (! folder.createDirectory()) // e.g. a read-only project folder: the global recordings folder
  4863. folder = defaultRecordingFolder(), folder.createDirectory();
  4864. const auto name = (recordingStem.isNotEmpty() ? recordingStem + "_" : juce::String())
  4865. + juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S") + "_Edison";
  4866. const auto file = folder.getNonexistentChildFile (name, ".wav", false);
  4867. if (! session->save (file.getFullPathName().toStdString()))
  4868. {
  4869. recordingError = tr ("Could not write {0}", { file.getFullPathName() });
  4870. continue; // (it stays unsaved: the next flush tries again)
  4871. }
  4872. sessionRecordings.push_back (file); // (a file this project may end up not using, like a take)
  4873. }
  4874. }
  4875. // the slot follows its session: after a write here, or one by another engine of the same project
  4876. if (wasDirty || (! session->path().empty() && session->path() != fx.samplePath))
  4877. changes.push_back ({ fx.instance.id, session->path(), wasDirty });
  4878. }
  4879. if (changes.empty())
  4880. return;
  4881. auto apply = [&changes] (Song& s) {
  4882. for (auto& track : s.mixer)
  4883. for (auto& fx : track.effects)
  4884. if (fx.kind == EffectKind::edison)
  4885. for (const auto& c : changes)
  4886. if (c.instance == fx.instance.id)
  4887. {
  4888. fx.samplePath = c.path;
  4889. if (c.clearState)
  4890. fx.state.clear(); // (an imported slot: FL's state held the audio that was replaced)
  4891. }
  4892. };
  4893. const auto differs = std::any_of (changes.begin(), changes.end(), [this] (const Change& c) {
  4894. for (const auto& track : song.mixer)
  4895. for (const auto& fx : track.effects)
  4896. if (fx.kind == EffectKind::edison && fx.instance.id == c.instance)
  4897. return fx.samplePath != c.path || (c.clearState && ! fx.state.empty());
  4898. return false;
  4899. });
  4900. if (differs)
  4901. editSong (apply, false);
  4902. }
  4903. void AudioEngine::capturePluginStates()
  4904. {
  4905. stampWorkTime();
  4906. flushEdisonAudio(); // (round 190cd: an Edison slot's audio is a file of the project)
  4907. // Changes only the saved state (recreates nothing and doesn't enter the undo history).
  4908. for (std::size_t i = 0; i < song.channels.size(); ++i)
  4909. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()))
  4910. if (song.channels[i].plugin.playedBy == 0) // (P5-A1: a plugin shared in a live session keeps no state, only values)
  4911. if (auto state = p->captureState()) // (a plugin that crashed keeps the state saved before)
  4912. song.channels[i].plugin.state = std::move (*state);
  4913. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  4914. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  4915. if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()))
  4916. if (song.mixer[t].effects[s].plugin.playedBy == 0)
  4917. if (auto state = p->captureState())
  4918. song.mixer[t].effects[s].plugin.state = std::move (*state);
  4919. // the plugins inside Patchers (REA_rodada141), nested ones too
  4920. std::function<void (PatcherDoc&, patcher::Graph*)> captureGraph = [&] (PatcherDoc& doc, patcher::Graph* graph) {
  4921. if (graph == nullptr)
  4922. return;
  4923. for (int n = 0; n < (int) doc.nodes.size() && n < graph->nodeCount(); ++n)
  4924. {
  4925. auto& node = doc.nodes[(std::size_t) n];
  4926. if (node.generator)
  4927. {
  4928. auto instrument = graph->instrumentAt (n);
  4929. if (auto* p = dynamic_cast<PluginInstrument*> (instrument.get()))
  4930. if (auto state = p->captureState())
  4931. node.channel.plugin.state = std::move (*state);
  4932. if (node.channel.instrument == InstrumentKind::patcher)
  4933. captureGraph (node.channel.patcher, patcher::graphOf (instrument.get()));
  4934. }
  4935. else
  4936. {
  4937. auto effect = graph->effectAt (n);
  4938. if (auto* p = dynamic_cast<PluginEffect*> (effect.get()))
  4939. if (auto state = p->captureState())
  4940. node.effect.plugin.state = std::move (*state);
  4941. if (node.effect.kind == EffectKind::patcher)
  4942. captureGraph (node.effect.patcher, patcher::graphOf (effect.get()));
  4943. }
  4944. }
  4945. };
  4946. for (std::size_t i = 0; i < song.channels.size(); ++i)
  4947. if (song.channels[i].instrument == InstrumentKind::patcher)
  4948. captureGraph (song.channels[i].patcher, patcher::graphOf (getChannelInstrument ((int) i).get()));
  4949. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  4950. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  4951. if (song.mixer[t].effects[s].kind == EffectKind::patcher)
  4952. captureGraph (song.mixer[t].effects[s].patcher, patcher::graphOf (getEffect ((int) t, (int) s).get()));
  4953. lastPublishedShape.song.channels = song.channels;
  4954. lastPublishedShape.song.mixer = song.mixer;
  4955. }
  4956. bool AudioEngine::auditionPreset (const juce::AudioPluginInstance& plugin)
  4957. {
  4958. auto channel = -1;
  4959. for (std::size_t i = 0; i < song.channels.size() && channel < 0; ++i)
  4960. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()); p != nullptr && &p->getInstance() == &plugin && ! p->hasCrashed())
  4961. channel = (int) i;
  4962. if (! pluginpresets::auditionPlays (true, channel >= 0, transport.playing.load(), transport.recording.load()))
  4963. return false;
  4964. if (auditionChannel >= 0 && auditionSounding) // the last one still sounds: it ends now
  4965. sendLiveNote (auditionChannel, pluginpresets::auditionKey, 0.0f, false);
  4966. auditionChannel = channel;
  4967. auditionSounding = false;
  4968. auditionAtMs = juce::Time::getMillisecondCounterHiRes() + pluginpresets::auditionDelayMs;
  4969. return true;
  4970. }
  4971. bool AudioEngine::auditionChannelSound (int channel)
  4972. {
  4973. if (channel < 0 || channel >= (int) song.channels.size()
  4974. || ! pluginpresets::auditionPlays (true, true, transport.playing.load(), transport.recording.load()))
  4975. return false;
  4976. if (auditionChannel >= 0 && auditionSounding) // the last one still sounds: it ends now
  4977. sendLiveNote (auditionChannel, pluginpresets::auditionKey, 0.0f, false);
  4978. auditionChannel = channel;
  4979. auditionSounding = false;
  4980. auditionAtMs = juce::Time::getMillisecondCounterHiRes() + pluginpresets::auditionDelayMs;
  4981. return true;
  4982. }
  4983. void AudioEngine::updateAudition()
  4984. {
  4985. if (auditionChannel < 0 || juce::Time::getMillisecondCounterHiRes() < auditionAtMs)
  4986. return;
  4987. if (auditionSounding)
  4988. {
  4989. sendLiveNote (auditionChannel, pluginpresets::auditionKey, 0.0f, false);
  4990. auditionChannel = -1;
  4991. auditionSounding = false;
  4992. return;
  4993. }
  4994. // (the song started in between, or the channel went: nothing plays)
  4995. if (transport.playing.load() || auditionChannel >= (int) song.channels.size())
  4996. {
  4997. auditionChannel = -1;
  4998. return;
  4999. }
  5000. sendLiveNote (auditionChannel, pluginpresets::auditionKey, pluginpresets::auditionVelocity, true);
  5001. auditionSounding = true;
  5002. auditionAtMs = juce::Time::getMillisecondCounterHiRes() + pluginpresets::auditionLengthMs;
  5003. }
  5004. namespace
  5005. {
  5006. bool pluginIsDown (Instrument* instrument)
  5007. {
  5008. auto* p = dynamic_cast<PluginInstrument*> (instrument);
  5009. return p != nullptr && (p->hasCrashed() || isSandboxedPluginDead (p->getInstance()));
  5010. }
  5011. bool pluginIsDown (Effect* effect)
  5012. {
  5013. auto* p = dynamic_cast<PluginEffect*> (effect);
  5014. return p != nullptr && (p->hasCrashed() || isSandboxedPluginDead (p->getInstance()));
  5015. }
  5016. } // namespace
  5017. bool AudioEngine::hostedPluginDown (HostedSlot where) const
  5018. {
  5019. return where.track < 0 ? pluginIsDown (getChannelInstrument (where.channel).get()) : pluginIsDown (getEffect (where.track, where.slot).get());
  5020. }
  5021. std::vector<AudioEngine::HostedSlot> AudioEngine::downHostedPlugins (const std::string& named) const
  5022. {
  5023. std::vector<HostedSlot> out;
  5024. for (std::size_t i = 0; i < song.channels.size(); ++i)
  5025. if (song.channels[i].instrument == InstrumentKind::plugin && (named.empty() || song.channels[i].plugin.name == named)
  5026. && hostedPluginDown ({ (int) i, -1, -1 }))
  5027. out.push_back ({ (int) i, -1, -1 });
  5028. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  5029. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  5030. if (const auto& fx = song.mixer[t].effects[s];
  5031. fx.kind == EffectKind::plugin && (named.empty() || fx.plugin.name == named) && hostedPluginDown ({ -1, (int) t, (int) s }))
  5032. out.push_back ({ -1, (int) t, (int) s });
  5033. return out;
  5034. }
  5035. int AudioEngine::reloadHostedPlugins (const std::vector<HostedSlot>& which)
  5036. {
  5037. // the running plugins' current settings (a reloaded one that still runs starts from them); this also brings the
  5038. // last published shape in line with the song
  5039. capturePluginStates();
  5040. std::vector<HostedSlot> asked;
  5041. for (const auto& w : which)
  5042. if (w.track < 0 ? forgetHostedPlugin (lastPublishedShape, w.channel) : forgetHostedPlugin (lastPublishedShape, w.track, w.slot))
  5043. asked.push_back (w);
  5044. if (asked.empty())
  5045. return 0;
  5046. publishSong();
  5047. auto running = 0;
  5048. for (const auto& w : asked)
  5049. {
  5050. const auto loaded = w.track < 0 ? dynamic_cast<PluginInstrument*> (getChannelInstrument (w.channel).get()) != nullptr
  5051. : dynamic_cast<PluginEffect*> (getEffect (w.track, w.slot).get()) != nullptr;
  5052. running += loaded && ! hostedPluginDown (w) ? 1 : 0;
  5053. }
  5054. return running;
  5055. }
  5056. void AudioEngine::audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
  5057. int numInputChannels,
  5058. float* const* outputChannelData,
  5059. int numOutputChannels,
  5060. int numSamples,
  5061. const juce::AudioIODeviceCallbackContext& context)
  5062. {
  5063. // FTZ/DAZ for the whole callback (round 160): the rack had it, but the metronome, the preview player and the
  5064. // hosted plugins' graph nodes around it ran without
  5065. const ScopedFlushDenormals noDenormals;
  5066. rt::noteAudioThread(); // Linux: the message thread asks for real-time priority for this thread once
  5067. #if JUCE_WINDOWS
  5068. // round 174e: a new device thread (first callback, a device restart) gets the workers' real-time class unless the
  5069. // driver already runs it time-critical: the callback waits on the workers, and a normal-priority callback thread
  5070. // lost the CPU to the UI's frames (more late calls while the screen was busy)
  5071. if (const auto id = (unsigned long) GetCurrentThreadId(); id != deviceThreadId.load (std::memory_order_relaxed))
  5072. {
  5073. deviceThreadId.store (id, std::memory_order_relaxed);
  5074. const auto before = GetThreadPriority (GetCurrentThread());
  5075. deviceThreadPriorityBefore.store (before, std::memory_order_relaxed);
  5076. if (boostDeviceThread && before < THREAD_PRIORITY_TIME_CRITICAL)
  5077. raiseAudioThreadPriority();
  5078. deviceThreadPriorityAfter.store (GetThreadPriority (GetCurrentThread()), std::memory_order_relaxed);
  5079. }
  5080. #endif
  5081. // real-time health: how long this callback took against its deadline (the buffer's duration)
  5082. const auto callbackStart = juce::Time::getMillisecondCounterHiRes();
  5083. struct Measure
  5084. {
  5085. ~Measure()
  5086. {
  5087. const auto rate = engine.transport.sampleRate.load (std::memory_order_relaxed);
  5088. if (rate > 0.0)
  5089. engine.rtStats.record (start, juce::Time::getMillisecondCounterHiRes() - start, 1000.0 * samples / rate);
  5090. }
  5091. AudioEngine& engine;
  5092. double start;
  5093. int samples;
  5094. } measure { *this, callbackStart, numSamples };
  5095. // an export renders (round 168s): playback stops and nothing is processed until it ends (not while recording)
  5096. if (offlineRendersRunning().load (std::memory_order_acquire) > 0 && ! transport.recording.load (std::memory_order_relaxed))
  5097. {
  5098. if (transport.playing.load (std::memory_order_relaxed))
  5099. stop();
  5100. for (int ch = 0; ch < numOutputChannels; ++ch)
  5101. if (outputChannelData[ch] != nullptr)
  5102. juce::FloatVectorOperations::clear (outputChannelData[ch], numSamples);
  5103. return;
  5104. }
  5105. if (transport.rewindRequested.exchange (false))
  5106. {
  5107. transport.positionTicks.store (0.0);
  5108. transport.userJumps.fetch_add (1, std::memory_order_relaxed);
  5109. if (transport.resetPluginsOnTransport.load (std::memory_order_relaxed))
  5110. midiSync.requestTransportNotesOff(); // FL: CC 123 to the "Send all notes off" outputs (REA 167l §6)
  5111. }
  5112. if (const auto target = transport.seekRequest.exchange (-1.0); target >= 0.0)
  5113. {
  5114. transport.positionTicks.store (target);
  5115. transport.userJumps.fetch_add (1, std::memory_order_relaxed);
  5116. if (transport.resetPluginsOnTransport.load (std::memory_order_relaxed))
  5117. midiSync.requestTransportNotesOff();
  5118. }
  5119. transport.readMarkers (rtMarkers, rtMarkerVersion); // FL's marker actions (a new table when the song changed)
  5120. // an external MIDI clock moves the transport (round 165f)
  5121. midiSync.beginBlock (transport, callbackStart, numSamples);
  5122. // With the loop region on, the block is split at the loop end and the position jumps back to
  5123. // its start (the nodes see a jump and release their notes, as in FL).
  5124. // the audio editor's input recording (nothing happens unless it chose the input)
  5125. meters.capture.push (AudioCapture::input, numInputChannels > 0 ? inputChannelData[0] : nullptr, numInputChannels > 1 ? inputChannelData[1] : nullptr,
  5126. numSamples);
  5127. std::array<const float*, 64> inputs {};
  5128. std::array<float*, 64> outputs {};
  5129. numInputChannels = juce::jmin (numInputChannels, (int) inputs.size());
  5130. numOutputChannels = juce::jmin (numOutputChannels, (int) outputs.size());
  5131. // count-in: the metronome counts the pre-roll down, then playback starts — to the sample (round 170d: the song
  5132. // started at the next block boundary and the count-in's clicks ran a block early, so the downbeat flammed ~5 ms
  5133. // after the last count-in click and the take's notes were late against it): the block is split where the count-in
  5134. // ends, the part before it counts in (the metronome's clock = the start minus what is left at that sample)
  5135. const auto countInAtStart = transport.countIn.load (std::memory_order_relaxed);
  5136. const auto countingIn = countInAtStart > 0.0 && ! transport.playing.load (std::memory_order_relaxed);
  5137. const auto countInSamples = ! countingIn ? 0
  5138. : (int) juce::jmin ((double) numSamples, std::ceil (countInAtStart / juce::jmax (1.0e-9, transport.ticksPerSample()) - 1.0e-6));
  5139. auto countInNow = countInAtStart;
  5140. for (int done = 0; done < numSamples;)
  5141. {
  5142. auto n = numSamples - done;
  5143. if (countInSamples > done)
  5144. n = juce::jmin (n, countInSamples - done);
  5145. const auto playing = transport.playing.load (std::memory_order_relaxed);
  5146. const auto tps = transport.ticksPerSample();
  5147. // Song mode: the loop region, or else the whole song (back to the start at its end, like FL)
  5148. // (while audio takes record in Song mode without a loop region, the song plays on past its end instead of
  5149. // starting over: the take stays one piece, as in Pro Tools / Nuendo; round 163)
  5150. // (punching on the loop region: the region is not looped either, playback runs on into the post-roll)
  5151. const auto linear = liveInput.linearSong.load (std::memory_order_relaxed);
  5152. const auto throughRegion = liveInput.noLoopRegion.load (std::memory_order_relaxed);
  5153. const auto loop = playbackLoop (transport.songMode.load (std::memory_order_relaxed),
  5154. throughRegion ? 0.0 : transport.loopStart.load (std::memory_order_relaxed),
  5155. throughRegion ? 0.0 : transport.loopEnd.load (std::memory_order_relaxed),
  5156. linear ? 0.0 : transport.songEnd.load (std::memory_order_relaxed),
  5157. transport.songStart.load (std::memory_order_relaxed));
  5158. const auto loopStart = loop.start, loopEnd = loop.end;
  5159. const auto looping = playing && loop.active() && tps > 0.0;
  5160. // without the loop region, the song's end goes back to FL's "Loop" marker (else the start)
  5161. const auto regionOn = ! throughRegion && transport.loopEnd.load (std::memory_order_relaxed) > transport.loopStart.load (std::memory_order_relaxed);
  5162. const auto songWrap = regionOn ? loopStart : juce::jlimit (loopStart, juce::jmax (loopStart, loopEnd - 1.0), (double) rtMarkers.wrapTo);
  5163. if (looping)
  5164. {
  5165. // before the loop, play normally until reaching it; past the end, jump back to the start
  5166. auto position = transport.positionTicks.load (std::memory_order_relaxed);
  5167. if (transportReached (position, loopEnd))
  5168. {
  5169. position = songWrap;
  5170. transport.positionTicks.store (position, std::memory_order_relaxed);
  5171. }
  5172. n = transportSamplesUntil (position, loopEnd, tps, n);
  5173. }
  5174. // FL's marker actions (Song mode): the block ends where the position reaches a marker jump / pause, or a
  5175. // quantized jump the user asked for; it is made after the block (below), like the loop's wrap
  5176. const MarkerJump* markerJump = nullptr;
  5177. const auto pendingAt = transport.pendingJumpAt.load (std::memory_order_relaxed);
  5178. auto pendingDue = false;
  5179. if (playing && tps > 0.0 && transport.songMode.load (std::memory_order_relaxed))
  5180. {
  5181. const auto step = markerStep (rtMarkers, transport.positionTicks.load (std::memory_order_relaxed), n, tps, pendingAt);
  5182. n = step.samples;
  5183. markerJump = step.jump;
  5184. pendingDue = step.userJump;
  5185. }
  5186. for (int ch = 0; ch < numInputChannels; ++ch)
  5187. inputs[(std::size_t) ch] = inputChannelData[ch] != nullptr ? inputChannelData[ch] + done : nullptr;
  5188. // the block's input by device channel, for the inserts (monitoring, meters) and the takes
  5189. liveInput.numChannels = 0;
  5190. for (int c = 0; c < LiveInput::maxChannels; ++c)
  5191. {
  5192. const auto slot = inputSlot[(std::size_t) c];
  5193. liveInput.channels[(std::size_t) c] = slot >= 0 && slot < numInputChannels ? inputs[(std::size_t) slot] : nullptr;
  5194. if (liveInput.channels[(std::size_t) c] != nullptr)
  5195. liveInput.numChannels = c + 1;
  5196. }
  5197. // audio recording: this block's input goes to the takes' streams (without waiting on a lock). Every take gets
  5198. // every block (silence for an input channel missing now), so all of them keep the same timeline (round 163).
  5199. // The lock is held through the render when takes are tapped inside their inserts (round 168x): their part of
  5200. // this block is pushed after the render, and every take must get every block.
  5201. auto takesLocked = false;
  5202. auto tappedTakes = false;
  5203. if (playing && (transport.recording.load (std::memory_order_relaxed) || slotAudioCapture.load (std::memory_order_relaxed)))
  5204. {
  5205. takesLocked = takeLock.tryEnter();
  5206. if (takesLocked && takeCount > 0)
  5207. {
  5208. for (int k = 0; k < takeCount; ++k)
  5209. {
  5210. auto* take = takes[(std::size_t) k];
  5211. if (take->tap >= 0) // filled by the renderer: silence until it writes the tap
  5212. {
  5213. tappedTakes = true;
  5214. if (n <= LiveInput::tapCapacity)
  5215. for (auto& d : liveInput.taps[(std::size_t) take->tap].data)
  5216. std::fill (d.begin(), d.begin() + n, 0.0f);
  5217. continue;
  5218. }
  5219. const std::array<const float*, 2> data { liveInput.channel (take->first, 0), liveInput.channel (take->first + take->channels - 1, 0) };
  5220. if (data[0] == nullptr || data[1] == nullptr)
  5221. take->stream->pushSilence (n);
  5222. else
  5223. take->stream->push (data.data(), n);
  5224. }
  5225. if (takeStartTick.load (std::memory_order_relaxed) < 0.0)
  5226. {
  5227. takeStartTick.store (transport.positionTicks.load (std::memory_order_relaxed));
  5228. // (round 190bv) the clip grid's clock at this sample: its own while it runs, else it starts at the song position
  5229. takeStartClock.store (clipLauncher != nullptr && clipLauncher->running.load (std::memory_order_relaxed)
  5230. ? clipLauncher->clock
  5231. : transport.positionTicks.load (std::memory_order_relaxed),
  5232. std::memory_order_relaxed);
  5233. }
  5234. takeFrames.fetch_add (n, std::memory_order_relaxed);
  5235. takeTicks.store (takeTicks.load (std::memory_order_relaxed) + n * tps, std::memory_order_relaxed);
  5236. }
  5237. if (takesLocked && ! tappedTakes)
  5238. {
  5239. takeLock.exit();
  5240. takesLocked = false;
  5241. }
  5242. }
  5243. for (int ch = 0; ch < numOutputChannels; ++ch)
  5244. outputs[(std::size_t) ch] = outputChannelData[ch] != nullptr ? outputChannelData[ch] + done : nullptr;
  5245. // master sync out (round 165f): this part's clock / MTC messages, time-stamped for the sender thread
  5246. midiSync.subBlock (transport.positionTicks.load (std::memory_order_relaxed), tps, n, done, playing);
  5247. player.audioDeviceIOCallbackWithContext (inputs.data(), numInputChannels, outputs.data(), numOutputChannels, n, context);
  5248. routeOutputs (outputs.data(), numOutputChannels, n);
  5249. if (takesLocked) // the tapped takes' part of this block, now rendered (round 168x)
  5250. {
  5251. for (int k = 0; k < takeCount; ++k)
  5252. if (auto* take = takes[(std::size_t) k]; take->tap >= 0)
  5253. {
  5254. if (n > LiveInput::tapCapacity)
  5255. {
  5256. take->stream->pushSilence (n);
  5257. continue;
  5258. }
  5259. auto& tap = liveInput.taps[(std::size_t) take->tap];
  5260. const auto drop = juce::jmin (n, take->skip - take->skipped); // the effects' latency at the start
  5261. take->skipped += drop;
  5262. if (drop < n)
  5263. {
  5264. const std::array<const float*, 2> data { tap.data[0].data() + drop, tap.data[1].data() + drop };
  5265. take->stream->push (data.data(), n - drop);
  5266. }
  5267. }
  5268. takeLock.exit();
  5269. }
  5270. for (int ch = 0; ch < numOutputChannels; ++ch)
  5271. if (outputs[(std::size_t) ch] != nullptr)
  5272. clipOvers (outputs[(std::size_t) ch], n);
  5273. // oscilloscope: average of both sides into the ring buffer
  5274. if (numOutputChannels > 0 && outputs[0] != nullptr)
  5275. {
  5276. auto w = scopeWrite.load (std::memory_order_relaxed);
  5277. const auto* right = numOutputChannels > 1 && outputs[1] != nullptr ? outputs[1] : outputs[0];
  5278. for (int i = 0; i < n; ++i)
  5279. {
  5280. scope[(std::size_t) w].store (0.5f * (outputs[0][i] + right[i]), std::memory_order_relaxed);
  5281. w = (w + 1) % scopeSize;
  5282. }
  5283. scopeWrite.store (w, std::memory_order_release);
  5284. }
  5285. if (playing)
  5286. {
  5287. auto position = transport.positionTicks.load (std::memory_order_relaxed) + n * tps;
  5288. if (pendingDue && transportReached (position, pendingAt))
  5289. {
  5290. position = transport.pendingJumpTo.load (std::memory_order_relaxed);
  5291. transport.pendingJumpAt.store (-1.0, std::memory_order_relaxed);
  5292. markerEvents.fetch_add (1, std::memory_order_relaxed);
  5293. transport.userJumps.fetch_add (1, std::memory_order_relaxed);
  5294. }
  5295. else if (markerJump != nullptr && transportReached (position, (double) markerJump->at))
  5296. {
  5297. markerEvents.fetch_add (1, std::memory_order_relaxed);
  5298. if (markerJump->kind == MarkerJump::Kind::pause)
  5299. {
  5300. // FL's "Marker pause": playback stops at the marker; Play goes on from there
  5301. position = (double) markerJump->at;
  5302. transport.positionTicks.store (position, std::memory_order_relaxed);
  5303. transport.playing.store (false, std::memory_order_relaxed); // the rest of the block plays stopped
  5304. }
  5305. position = (double) markerJump->to;
  5306. transport.userJumps.fetch_add (1, std::memory_order_relaxed);
  5307. }
  5308. else if (looping && transportReached (position, loopEnd))
  5309. {
  5310. position = songWrap;
  5311. // loop recording: where this pass ends in the takes (round 163)
  5312. if (const auto frames = takeFrames.load (std::memory_order_relaxed); frames > 0 && takeStartTick.load (std::memory_order_relaxed) >= 0.0)
  5313. if (const auto k = takeWrapCount.load (std::memory_order_relaxed); k < (int) takeWraps.size())
  5314. {
  5315. takeWraps[(std::size_t) k].store (frames, std::memory_order_relaxed);
  5316. takeWrapCount.store (k + 1, std::memory_order_release);
  5317. }
  5318. }
  5319. transport.positionTicks.store (position, std::memory_order_relaxed);
  5320. }
  5321. // the count-in's part of the block is over: what is left of it, or playback from here
  5322. // (a compare-exchange: a Stop pressed meanwhile set it to 0 and must win)
  5323. if (countInSamples > done)
  5324. {
  5325. const auto rawLeft = countInAtStart - (done + n) * transport.ticksPerSample();
  5326. const auto left = juce::jmax (0.0, rawLeft);
  5327. const auto ends = done + n >= countInSamples && rawLeft <= 1.0e-6;
  5328. auto expected = countInNow;
  5329. if (transport.countIn.compare_exchange_strong (expected, ends ? 0.0 : left, std::memory_order_relaxed))
  5330. {
  5331. countInNow = ends ? 0.0 : left;
  5332. if (ends)
  5333. transport.playing.store (true, std::memory_order_relaxed);
  5334. }
  5335. }
  5336. done += n;
  5337. }
  5338. // the latency ping (round 163): only its clicks go out (no feedback through a monitored input), listened for on
  5339. // its input
  5340. if (ping.isRunning())
  5341. {
  5342. for (int ch = 0; ch < numOutputChannels; ++ch)
  5343. if (outputChannelData[ch] != nullptr)
  5344. juce::FloatVectorOperations::clear (outputChannelData[ch], numSamples);
  5345. std::array<float*, 2> clickOut {};
  5346. for (std::size_t k = 0; k < 2; ++k)
  5347. if (pingOutputs[k] >= 0 && pingOutputs[k] < numOutputChannels)
  5348. clickOut[k] = outputChannelData[pingOutputs[k]];
  5349. const auto* in = pingInput >= 0 && pingInput < numInputChannels ? inputChannelData[pingInput] : nullptr;
  5350. ping.process (in, clickOut.data(), 2, numSamples);
  5351. }
  5352. // the block is done: the workers sleep until the next one instead of spinning (REA round 116)
  5353. if (workers != nullptr)
  5354. workers->park();
  5355. // the live clock (round 170d): the next block's musical position — during the count-in the metronome's count before
  5356. // the start (the start minus the count-in left)
  5357. {
  5358. const auto tps = transport.ticksPerSample();
  5359. const auto nowPlaying = transport.playing.load (std::memory_order_relaxed);
  5360. const auto left = transport.countIn.load (std::memory_order_relaxed);
  5361. const auto counting = left > 0.0 && ! nowPlaying;
  5362. const auto position = transport.positionTicks.load (std::memory_order_relaxed);
  5363. clockTick.store (counting ? position - left : position, std::memory_order_relaxed);
  5364. clockTicksPerMs.store (tps * transport.sampleRate.load (std::memory_order_relaxed) * 0.001, std::memory_order_relaxed);
  5365. clockRunning.store (nowPlaying || counting, std::memory_order_relaxed);
  5366. }
  5367. if (const auto rate = transport.sampleRate.load (std::memory_order_relaxed); rate > 0.0)
  5368. blockDurationMs.store (1000.0 * numSamples / rate, std::memory_order_relaxed);
  5369. blockTimeMs.store (juce::Time::getMillisecondCounterHiRes(), std::memory_order_release);
  5370. }
  5371. void AudioEngine::audioDeviceAboutToStart (juce::AudioIODevice* device)
  5372. {
  5373. rtStats.deviceRestarted();
  5374. rt::resetForNewDevice();
  5375. transport.sampleRate.store (device->getCurrentSampleRate());
  5376. meters.rollingLog.setSampleRate (device->getCurrentSampleRate()); // (the audio thread isn't running yet: it may allocate)
  5377. midiSync.deviceStarted (device->getCurrentSampleRate(), device->getCurrentBufferSizeSamples(), device->getOutputLatencyInSamples());
  5378. // what is heard comes out one output buffer + the driver's output latency after it was rendered (round 170d, as
  5379. // the MIDI clock output counts it)
  5380. outputCompensationMs.store (1000.0 * (device->getCurrentBufferSizeSamples() + juce::jmax (0, device->getOutputLatencyInSamples()))
  5381. / juce::jmax (1.0, device->getCurrentSampleRate()));
  5382. // FL's fixed size buffers: 2 ms, or the device buffer with "Process maximum size buffers" (REA round 134)
  5383. setFixedPluginBlock (device->getCurrentBufferSizeSamples(), device->getCurrentSampleRate());
  5384. // the callback gets the open input channels only, in order: map device channel -> callback index
  5385. const auto active = device->getActiveInputChannels();
  5386. int slot = 0;
  5387. for (int c = 0; c < LiveInput::maxChannels; ++c)
  5388. inputSlot[(std::size_t) c] = active[c] ? slot++ : -1;
  5389. // the same for the outputs (hardware output targets, REA round 156)
  5390. const auto activeOut = device->getActiveOutputChannels();
  5391. slot = 0;
  5392. for (int c = 0; c < HardwareOutput::maxChannels; ++c)
  5393. outputSlot[(std::size_t) c] = activeOut[c] ? slot++ : -1;
  5394. hwOutput.clear();
  5395. hwOutput.active.store (true);
  5396. player.audioDeviceAboutToStart (device);
  5397. }
  5398. void AudioEngine::audioDeviceStopped()
  5399. {
  5400. hwOutput.active.store (false);
  5401. player.audioDeviceStopped();
  5402. }
  5403. // The Master's own target (its default: the graph's output as it is, on the first open pair) and the inserts'
  5404. // hardware outputs, added into the device channels they chose. A channel that is not open drops its sound.
  5405. void AudioEngine::routeOutputs (float* const* outputs, int numOutputs, int n) noexcept
  5406. {
  5407. const auto slotOf = [this] (int c) { return c >= 0 && c < HardwareOutput::maxChannels ? outputSlot[(std::size_t) c] : -1; };
  5408. if (const auto channel = masterOutChannel.load (std::memory_order_relaxed); channel != outputDefault && numOutputs > 0 && n <= HardwareOutput::capacity)
  5409. {
  5410. auto* l = masterScratch.data();
  5411. auto* r = masterScratch.data() + HardwareOutput::capacity;
  5412. const auto* srcR = numOutputs > 1 && outputs[1] != nullptr ? outputs[1] : outputs[0];
  5413. if (outputs[0] == nullptr)
  5414. return;
  5415. std::copy (outputs[0], outputs[0] + n, l);
  5416. std::copy (srcR, srcR + n, r);
  5417. for (int k = 0; k < std::min (numOutputs, 2); ++k)
  5418. if (outputs[k] != nullptr)
  5419. std::fill (outputs[k], outputs[k] + n, 0.0f);
  5420. const auto mode = (OutputMode) masterOutMode.load (std::memory_order_relaxed);
  5421. const auto [first, count] = outputChannelsOf (channel, mode);
  5422. if (count > 0)
  5423. {
  5424. const auto a = slotOf (first), b = count > 1 ? slotOf (first + 1) : -1;
  5425. if (a >= 0 && a < numOutputs)
  5426. addToOutput (l, r, mode, outputs[a], b >= 0 && b < numOutputs ? outputs[b] : nullptr, n);
  5427. }
  5428. }
  5429. hwOutput.drainInto (outputs, numOutputs, slotOf, n);
  5430. }
  5431. std::vector<std::string> AudioEngine::getOutputChannelNames() const
  5432. {
  5433. std::vector<std::string> names;
  5434. if (auto* device = deviceManager.getCurrentAudioDevice(); device != nullptr)
  5435. for (const auto& n : device->getOutputChannelNames())
  5436. if ((int) names.size() < HardwareOutput::maxChannels)
  5437. names.push_back (n.toStdString());
  5438. return names;
  5439. }
  5440. bool AudioEngine::isOutputChannelOpen (int channel) const
  5441. {
  5442. auto* device = deviceManager.getCurrentAudioDevice();
  5443. return device != nullptr && channel >= 0 && device->getActiveOutputChannels()[channel];
  5444. }
  5445. void AudioEngine::setTrackOutput (int track, int channel, OutputMode mode)
  5446. {
  5447. if (track < 0 || track >= (int) song.mixer.size())
  5448. return;
  5449. if (track > 0 && channel < 0) // an insert without a target: the default (the Master only), nothing saved
  5450. channel = outputDefault;
  5451. editSong ([=] (Song& s) {
  5452. s.mixer[(std::size_t) track].outputChannel = channel;
  5453. s.mixer[(std::size_t) track].outputMode = mode;
  5454. });
  5455. openTargetedOutputs();
  5456. }
  5457. void AudioEngine::openHardwareInsertIo()
  5458. {
  5459. openTargetedOutputs();
  5460. if (hwinsert::returnsFromInput (song) && ! hasAudioInput())
  5461. if (const auto result = openAudioInput(); result.issue != InputIssue::none)
  5462. notify (result.issue, 0, result.detail);
  5463. }
  5464. void AudioEngine::openTargetedOutputs()
  5465. {
  5466. auto* device = deviceManager.getCurrentAudioDevice();
  5467. if (device == nullptr)
  5468. return;
  5469. const auto available = juce::jmin ((int) HardwareOutput::maxChannels, device->getOutputChannelNames().size());
  5470. auto setup = deviceManager.getAudioDeviceSetup();
  5471. auto wanted = device->getActiveOutputChannels();
  5472. const auto before = wanted;
  5473. for (const auto& t : song.mixer)
  5474. {
  5475. const auto [first, count] = outputChannelsOf (t.outputChannel, t.outputMode);
  5476. for (int c = first; c < first + count; ++c)
  5477. if (c < available)
  5478. wanted.setBit (c);
  5479. }
  5480. // the hardware inserts' sends (round 164d; inside Patchers too, round 165c)
  5481. hwinsert::forEachHardwareInsert (song, [&wanted, available] (const EffectSlot& fx, bool) {
  5482. const auto [from, n] = outputChannelsOf (hwinsert::channelOf (fx.params[hwinsert::output]), hwinsert::outputModeOf (fx.params));
  5483. for (int c = from; c < from + n; ++c)
  5484. if (c < available)
  5485. wanted.setBit (c);
  5486. });
  5487. if (wanted == before)
  5488. return;
  5489. setup.useDefaultOutputChannels = false;
  5490. setup.outputChannels = wanted;
  5491. deviceManager.setAudioDeviceSetup (setup, true);
  5492. sendChangeMessage();
  5493. }
  5494. // --- hardware inserts anywhere in the song (round 165c) ------------------------------------------------------------
  5495. namespace
  5496. {
  5497. template <typename F>
  5498. void walkHardwareInserts (const PatcherDoc& doc, AudioEngine::HardwareInsertRef& ref, F&& f)
  5499. {
  5500. for (int n = 0; n < (int) doc.nodes.size(); ++n)
  5501. {
  5502. const auto& node = doc.nodes[(std::size_t) n];
  5503. ref.nodes.push_back (n);
  5504. if (node.generator ? node.channel.instrument == InstrumentKind::patcher : node.effect.kind == EffectKind::patcher)
  5505. walkHardwareInserts (node.generator ? node.channel.patcher : node.effect.patcher, ref, f);
  5506. else if (! node.generator && node.effect.kind == EffectKind::hardwareInsert)
  5507. f (ref);
  5508. ref.nodes.pop_back();
  5509. }
  5510. }
  5511. } // namespace
  5512. std::vector<AudioEngine::HardwareInsertRef> AudioEngine::getHardwareInserts() const
  5513. {
  5514. std::vector<HardwareInsertRef> out;
  5515. auto add = [&out] (const HardwareInsertRef& r) { out.push_back (r); };
  5516. for (int t = 0; t < (int) song.mixer.size(); ++t)
  5517. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  5518. {
  5519. const auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) s];
  5520. HardwareInsertRef ref { false, t, s, {} };
  5521. if (fx.kind == EffectKind::hardwareInsert)
  5522. out.push_back (ref);
  5523. else if (fx.kind == EffectKind::patcher)
  5524. walkHardwareInserts (fx.patcher, ref, add);
  5525. }
  5526. for (int c = 0; c < (int) song.channels.size(); ++c)
  5527. if (song.channels[(std::size_t) c].instrument == InstrumentKind::patcher)
  5528. {
  5529. HardwareInsertRef ref { true, c, 0, {} };
  5530. walkHardwareInserts (song.channels[(std::size_t) c].patcher, ref, add);
  5531. }
  5532. return out;
  5533. }
  5534. EffectSlot* AudioEngine::locateHardwareInsert (Song& s, const HardwareInsertRef& ref)
  5535. {
  5536. PatcherDoc* doc = nullptr;
  5537. if (ref.channel)
  5538. {
  5539. if (ref.index < 0 || ref.index >= (int) s.channels.size() || s.channels[(std::size_t) ref.index].instrument != InstrumentKind::patcher)
  5540. return nullptr;
  5541. doc = &s.channels[(std::size_t) ref.index].patcher;
  5542. }
  5543. else
  5544. {
  5545. if (ref.index < 0 || ref.index >= (int) s.mixer.size() || ref.slot < 0 || ref.slot >= (int) s.mixer[(std::size_t) ref.index].effects.size())
  5546. return nullptr;
  5547. auto& fx = s.mixer[(std::size_t) ref.index].effects[(std::size_t) ref.slot];
  5548. if (ref.nodes.empty())
  5549. return fx.kind == EffectKind::hardwareInsert ? &fx : nullptr;
  5550. if (fx.kind != EffectKind::patcher)
  5551. return nullptr;
  5552. doc = &fx.patcher;
  5553. }
  5554. for (std::size_t k = 0; k < ref.nodes.size(); ++k)
  5555. {
  5556. const auto n = ref.nodes[k];
  5557. if (doc == nullptr || n < 0 || n >= (int) doc->nodes.size())
  5558. return nullptr;
  5559. auto& node = doc->nodes[(std::size_t) n];
  5560. if (k + 1 == ref.nodes.size())
  5561. return ! node.generator && node.effect.kind == EffectKind::hardwareInsert ? &node.effect : nullptr;
  5562. doc = node.generator ? (node.channel.instrument == InstrumentKind::patcher ? &node.channel.patcher : nullptr)
  5563. : (node.effect.kind == EffectKind::patcher ? &node.effect.patcher : nullptr);
  5564. }
  5565. return nullptr;
  5566. }
  5567. std::shared_ptr<Effect> AudioEngine::runningHardwareInsert (const HardwareInsertRef& ref) const
  5568. {
  5569. patcher::Graph* graph = nullptr;
  5570. if (ref.channel)
  5571. graph = patcher::graphOf (getChannelInstrument (ref.index).get());
  5572. else
  5573. {
  5574. auto fx = getEffect (ref.index, ref.slot);
  5575. if (ref.nodes.empty())
  5576. return fx;
  5577. graph = patcher::graphOf (fx.get());
  5578. }
  5579. for (std::size_t k = 0; k < ref.nodes.size() && graph != nullptr; ++k)
  5580. {
  5581. const auto n = ref.nodes[k];
  5582. if (n < 0 || n >= graph->nodeCount())
  5583. return nullptr;
  5584. if (k + 1 == ref.nodes.size())
  5585. return graph->effectAt (n);
  5586. auto* next = patcher::graphOf (graph->effectAt (n).get());
  5587. graph = next != nullptr ? next : patcher::graphOf (graph->instrumentAt (n).get());
  5588. }
  5589. return nullptr;
  5590. }
  5591. std::vector<AudioEngine::HardwareInsertRef> AudioEngine::staleHardwareInserts() const
  5592. {
  5593. std::vector<HardwareInsertRef> out;
  5594. const auto key = currentSetupKey();
  5595. if (key.empty())
  5596. return out;
  5597. for (const auto& ref : getHardwareInserts())
  5598. if (const auto* fx = locateHardwareInsert (const_cast<Song&> (song), ref))
  5599. if (fx->enabled && hwinsert::isRouted (fx->params))
  5600. if (const auto measured = hwinsert::measuredSetup (*fx); ! measured.empty() && measured != key)
  5601. out.push_back (ref);
  5602. return out;
  5603. }
  5604. void AudioEngine::pingHardwareInserts (const std::vector<HardwareInsertRef>& refs)
  5605. {
  5606. if (refs.empty())
  5607. return;
  5608. editSong ([refs] (Song& s) {
  5609. for (const auto& ref : refs)
  5610. if (auto* fx = locateHardwareInsert (s, ref))
  5611. fx->params[hwinsert::ping] = fx->params[hwinsert::ping] >= 0.5f ? 0.0f : 1.0f; // (a momentary value: any change)
  5612. }, false);
  5613. }
  5614. void AudioEngine::applyHardwareInsertPings()
  5615. {
  5616. if (deviceManager.getCurrentAudioDevice() == nullptr)
  5617. return;
  5618. const auto refs = getHardwareInserts();
  5619. const auto key = currentSetupKey();
  5620. // the device setup changed: the inserts measured for the old one (or, measured before LYNX kept the setup, for the
  5621. // one that was running) want a new ping — a notice for the UI, nothing pinged by itself
  5622. if (key != lastSetupKey)
  5623. {
  5624. const auto previous = std::exchange (lastSetupKey, key);
  5625. if (! previous.empty() && ! refs.empty())
  5626. {
  5627. editSong ([refs, previous] (Song& s) {
  5628. for (const auto& ref : refs)
  5629. if (auto* fx = locateHardwareInsert (s, ref); fx != nullptr && hwinsert::measuredSetup (*fx).empty()
  5630. && hwinsert::isRouted (fx->params) && hwinsert::roundTripOf (fx->params[hwinsert::roundTrip]) > 0)
  5631. hwinsert::setMeasuredSetup (*fx, previous);
  5632. }, false);
  5633. hwNotice = staleHardwareInserts();
  5634. if (! hwNotice.empty())
  5635. sendChangeMessage();
  5636. }
  5637. }
  5638. if (std::exchange (checkHardwareInserts, false) && hwNotice.empty())
  5639. {
  5640. hwNotice = staleHardwareInserts();
  5641. if (! hwNotice.empty())
  5642. sendChangeMessage();
  5643. }
  5644. // ping results: each one becomes its slot's round trip once (undoable, saved with the project), with this setup
  5645. for (const auto& ref : refs)
  5646. {
  5647. const auto fx = runningHardwareInsert (ref);
  5648. if (fx == nullptr)
  5649. continue;
  5650. const auto serial = juce::roundToInt (fx->controlOutput (hwinsert::pingSerial) * 1024.0f);
  5651. const auto [it, fresh] = hwPingSerials.try_emplace (fx.get(), serial);
  5652. if (fresh || it->second == serial)
  5653. continue;
  5654. it->second = serial;
  5655. if (std::abs (fx->controlOutput (hwinsert::pingState) - 0.5f) >= 0.01f)
  5656. continue; // (failed: the editor says why; the old round trip stays)
  5657. const auto samples = hwinsert::roundTripOf (fx->controlOutput (hwinsert::pingSamples));
  5658. editSong ([ref, samples, key] (Song& s) {
  5659. if (auto* slot = locateHardwareInsert (s, ref))
  5660. {
  5661. slot->params[hwinsert::roundTrip] = hwinsert::roundTripValue (samples);
  5662. hwinsert::setMeasuredSetup (*slot, key);
  5663. }
  5664. });
  5665. }
  5666. if (hwPingSerials.size() > 4 * refs.size() + 16) // (instances rebuilt meanwhile)
  5667. hwPingSerials.clear();
  5668. }
  5669. // --- real-time bounce (round 165c) ----------------------------------------------------------------------------------
  5670. juce::String AudioEngine::startRealtimeBounce (double startTick)
  5671. {
  5672. auto* device = deviceManager.getCurrentAudioDevice();
  5673. if (device == nullptr || transport.sampleRate.load() <= 0.0)
  5674. return tr ("No audio device is open");
  5675. if (transport.recording.load() || takeCount > 0)
  5676. return tr ("Stop recording first");
  5677. if (ping.isRunning())
  5678. return tr ("A latency ping is running");
  5679. if (bouncing)
  5680. return tr ("A real-time bounce is already running");
  5681. stop();
  5682. bounceReturnTick = transport.positionTicks.load();
  5683. bounceRestoreMode = song.mode != PlayMode::song;
  5684. if (bounceRestoreMode)
  5685. editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  5686. bouncing = true;
  5687. updateLinearSong(); // (plays on past the song's end and through the loop region, like a linear recording)
  5688. bounceStartLatency = getLatencySamples();
  5689. bounceStartXruns = device->getXRunCount();
  5690. meters.bounceTap.setSource (0); // (pushed only while the song plays: the first frame is the start's)
  5691. transport.positionTicks.store (juce::jmax (0.0, startTick));
  5692. transport.seekRequest.store (juce::jmax (0.0, startTick));
  5693. play();
  5694. sendChangeMessage();
  5695. return {};
  5696. }
  5697. int AudioEngine::bounceDropouts() const
  5698. {
  5699. auto* device = deviceManager.getCurrentAudioDevice();
  5700. const auto xruns = device != nullptr ? juce::jmax (0, device->getXRunCount() - bounceStartXruns) : 0;
  5701. return xruns + (meters.bounceTap.droppedFrames() > 0 ? 1 : 0);
  5702. }
  5703. void AudioEngine::finishRealtimeBounce()
  5704. {
  5705. if (! bouncing)
  5706. return;
  5707. stop();
  5708. meters.bounceTap.setSource (AudioCapture::off);
  5709. bouncing = false;
  5710. updateLinearSong();
  5711. if (std::exchange (bounceRestoreMode, false))
  5712. editSong ([] (Song& s) { s.mode = PlayMode::pattern; }, false);
  5713. seek (bounceReturnTick);
  5714. sendChangeMessage();
  5715. }
  5716. } // namespace lynx