AudioEngine.cpp 387 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545
  1. #include "engine/AudioEngine.h"
  2. #include "core/TransistorBass.h"
  3. #include "core/AraRegions.h"
  4. #include "core/RackOps.h"
  5. #include "core/FlPluginDb.h"
  6. #include "core/HarmorResynth.h"
  7. #include "core/BrowserSend.h" // round 190iz (FL's preview length)
  8. #include "core/LiveNote.h"
  9. #include "core/TrackOnly.h" // round 190iu
  10. #include "core/VideoPlayer.h"
  11. #include "core/TempoMap.h"
  12. #include "engine/ProjectFile.h"
  13. #include "engine/RemoteError.h"
  14. #include "engine/RemoteHistory.h"
  15. #include "core/Sha256.h"
  16. #include "core/Comping.h"
  17. #include "core/CountIn.h"
  18. #include "core/EdisonFx.h"
  19. #include "core/FlSettings.h"
  20. #include "core/MixerOps.h" // (round 190mv: keepCurrentLast)
  21. #include "core/LiveSession.h"
  22. #include "core/SessionIds.h"
  23. #include "core/StandIns.h"
  24. #include "engine/SessionPack.h"
  25. #include "core/ClipOps.h"
  26. #include "core/PlaylistOps.h"
  27. #include "core/LayoutStyle.h"
  28. #include "core/DetailChain.h"
  29. #include "core/SessionOps.h"
  30. #include "core/MarkerPlan.h"
  31. #include "core/MidiOut.h"
  32. #include "engine/AudioLogger.h"
  33. #include "core/HardwareInsert.h"
  34. #include "core/Patcher.h"
  35. #include "core/ValueMath.h"
  36. #include "platform/Paths.h"
  37. #include "engine/FlStudio.h"
  38. #include <limits>
  39. #include <map>
  40. #include <thread>
  41. #if defined(__GLIBC__)
  42. #include <malloc.h>
  43. #endif
  44. #include "engine/Text.h"
  45. #include "ui/I18n.h"
  46. #include "core/FlpImport.h"
  47. #include "core/AlsImport.h"
  48. #include "core/DawProject.h" // round 190jf (B22)
  49. #include "core/GeneratorPresets.h"
  50. #include "core/FlmImport.h"
  51. #include "core/BandImport.h" // round 190ic: GarageBand projects
  52. #include "core/BlxImport.h" // round 190jr: BandLab projects (.blx)
  53. #include "engine/ProjectPackage.h"
  54. #include "core/LoadTrace.h"
  55. #include "core/Instruments.h"
  56. #include "core/Denormals.h"
  57. #include "core/Dither.h"
  58. #include "core/GrossBeat.h"
  59. #include "core/ProjectSafety.h"
  60. #include "core/SoftClip.h"
  61. #include "core/Scheduler.h"
  62. #include "engine/ChannelRackProcessor.h"
  63. #include "engine/DllAsioDevice.h"
  64. #include "engine/PipeWireDevice.h"
  65. #include "platform/LinuxRealtime.h"
  66. #include "engine/PowerHints.h"
  67. #include "platform/PowerThrottling.h"
  68. #include "engine/Metronome.h"
  69. #include "core/NoteTools.h"
  70. #include "core/VfxScript.h"
  71. #include "core/SamplePrecompute.h"
  72. #include "engine/PreviewPlayer.h"
  73. #include "engine/RenderStream.h"
  74. #include "engine/PluginSandbox.h"
  75. #include "core/PluginPresets.h"
  76. #include "flp/Flp.h"
  77. #if JUCE_WINDOWS
  78. #include <windows.h>
  79. #elif JUCE_MAC
  80. #include <mach/mach.h>
  81. #include <mach/mach_time.h>
  82. #include <mach/thread_policy.h>
  83. #include <pthread.h>
  84. #include <sys/qos.h>
  85. #include <sys/sysctl.h>
  86. #elif JUCE_LINUX || JUCE_BSD
  87. #include <pthread.h>
  88. #include <sched.h>
  89. #endif
  90. namespace lynx
  91. {
  92. namespace
  93. {
  94. std::unordered_set<std::uint64_t> remoteFreshTargets (const Song& before, const Song& after)
  95. {
  96. std::unordered_set<std::uint64_t> existing, fresh;
  97. for (const auto& channel : before.channels) existing.insert (channel.instance.id);
  98. for (const auto& track : before.mixer)
  99. for (const auto& effect : track.effects) existing.insert (effect.instance.id);
  100. for (const auto& channel : after.channels)
  101. if (! existing.contains (channel.instance.id)) fresh.insert (channel.instance.id);
  102. for (const auto& track : after.mixer)
  103. for (const auto& effect : track.effects)
  104. if (! existing.contains (effect.instance.id)) fresh.insert (effect.instance.id);
  105. return fresh;
  106. }
  107. void adoptCapturedRemoteDevices (Song& model, RackState& published, Song&& captured)
  108. {
  109. // Capturing changes only saved hosted-state bytes. Keep the model and reuse baseline equal to the verified
  110. // running devices without publishing, changing history or capturing a vendor a second time.
  111. remote_history::mirrorCapturedHostedStates (captured, published.song);
  112. model.channels = std::move (captured.channels);
  113. model.mixer = std::move (captured.mixer);
  114. }
  115. }
  116. using IONode = juce::AudioProcessorGraph::AudioGraphIOProcessor;
  117. // The FL Studio installation (registry, else the usual folders) to resolve %FLStudio...%.
  118. FlPathRoots findFlStudioRoots()
  119. {
  120. FlPathRoots roots;
  121. const auto fl = findFlStudio();
  122. if (fl.installDir.isDirectory())
  123. {
  124. roots.factoryData = fl.installDir.getFullPathName().toStdString();
  125. roots.data = fl.installDir.getChildFile ("Data").getFullPathName().toStdString();
  126. }
  127. if (fl.userData.isDirectory())
  128. roots.userData = fl.userData.getFullPathName().toStdString();
  129. // FL's Shared data folder and its Downloads (issue #124: FL Cloud sounds and other samples kept there)
  130. if (fl.sharedData.isDirectory())
  131. {
  132. roots.sharedData = fl.sharedData.getFullPathName().toStdString();
  133. roots.downloadsData = fl.sharedData.getChildFile ("Downloads").getFullPathName().toStdString();
  134. }
  135. roots.home = juce::File::getSpecialLocation (juce::File::userHomeDirectory).getFullPathName().toStdString();
  136. return roots;
  137. }
  138. const natives::FlAccess& flStudioAccess()
  139. {
  140. static const natives::FlAccess cached = [] {
  141. natives::FlAccess access;
  142. access.roots = findFlStudioRoots();
  143. access.fileExists = [] (const std::string& path) { return platform::localFile (path).existsAsFile(); };
  144. access.readFile = [] (const std::string& path) {
  145. juce::MemoryBlock data;
  146. platform::localFile (path).loadFileAsData (data);
  147. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  148. return std::vector<std::uint8_t> (bytes, bytes + data.getSize());
  149. };
  150. access.listPresets = [] (const std::string& folder) {
  151. // round 190gd: a folder's listing is kept for a few seconds. Listing the generators' engines walked FL's whole
  152. // Plugin database\Generators tree once per engine (~40 walks, ~0.5 s of every start and of every Browser /
  153. // Add menu refresh); FL's own preset folders change when FL or the user saves a preset, seconds apart at most
  154. struct Listing
  155. {
  156. std::vector<std::string> files;
  157. juce::uint32 madeMs = 0;
  158. };
  159. static std::mutex lock;
  160. static std::map<std::string, Listing> listings;
  161. const auto now = juce::Time::getMillisecondCounter();
  162. {
  163. const std::scoped_lock l (lock);
  164. if (const auto it = listings.find (folder); it != listings.end() && now - it->second.madeMs < 5000)
  165. return it->second.files;
  166. }
  167. std::vector<std::string> out;
  168. auto files = platform::localFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst;*.tbio;*.gmsynth;*.mrp");
  169. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) {
  170. return a.getFullPathName().compareNatural (b.getFullPathName()) < 0;
  171. });
  172. for (const auto& f : files)
  173. out.push_back (f.getFullPathName().toStdString());
  174. const std::scoped_lock l (lock);
  175. listings[folder] = { out, juce::Time::getMillisecondCounter() };
  176. return out;
  177. };
  178. // (FL Keys' raw wavetables become WAV files of LYNX's settings folder, like an .flp's embedded samples)
  179. access.saveEmbedded = [] (const std::vector<std::uint8_t>& wav, const std::string& name) -> std::string {
  180. const auto folder = PluginHost::settingsFolder().getChildFile ("flp-embedded");
  181. folder.createDirectory();
  182. const auto hash = juce::String::toHexString ((juce::int64) juce::DefaultHashFunctions::generateHash (
  183. juce::String::createStringFromData (wav.data(), (int) std::min<std::size_t> (wav.size(), 65536)) + juce::String ((juce::int64) wav.size()),
  184. 0x7FFFFFFF));
  185. const auto file = folder.getChildFile (juce::File::createLegalFileName (juce::String::fromUTF8 (name.c_str())) + "-" + hash + ".wav");
  186. if (! file.existsAsFile() && ! file.replaceWithData (wav.data(), wav.size()))
  187. return {};
  188. return file.getFullPathName().toStdString();
  189. };
  190. return access;
  191. }();
  192. return cached;
  193. }
  194. // --- engine/PowerHints.h (rollup 0.1.28, REA round 190hb actions 3 and 4) -------------------------------------------
  195. namespace powerhints
  196. {
  197. std::uint32_t keepAwakeBegin() noexcept
  198. {
  199. #if JUCE_WINDOWS
  200. return (std::uint32_t) SetThreadExecutionState (ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
  201. #else
  202. return 0;
  203. #endif
  204. }
  205. void keepAwakeEnd (std::uint32_t previous) noexcept
  206. {
  207. #if JUCE_WINDOWS
  208. // (the state before, or plain ES_CONTINUOUS when there was none: the system may sleep again)
  209. SetThreadExecutionState (previous != 0 ? (EXECUTION_STATE) previous : ES_CONTINUOUS);
  210. #else
  211. (void) previous;
  212. #endif
  213. }
  214. int lowerCurrentThread() noexcept
  215. {
  216. #if JUCE_WINDOWS
  217. const auto before = GetThreadPriority (GetCurrentThread());
  218. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
  219. return before == THREAD_PRIORITY_ERROR_RETURN ? THREAD_PRIORITY_NORMAL : before;
  220. #else
  221. return 0;
  222. #endif
  223. }
  224. void restoreCurrentThread (int previous) noexcept
  225. {
  226. #if JUCE_WINDOWS
  227. SetThreadPriority (GetCurrentThread(), previous);
  228. #else
  229. (void) previous;
  230. #endif
  231. }
  232. void lowerWorkerThread()
  233. {
  234. (void) lowerCurrentThread();
  235. }
  236. void enableCompositorMmcss() noexcept
  237. {
  238. #if JUCE_WINDOWS
  239. if (juce::SystemStats::getEnvironmentVariable ("LYNX_DWM_MMCSS", {}) == "0")
  240. return;
  241. using EnableMmcss = HRESULT (WINAPI*) (BOOL);
  242. if (auto* dwm = LoadLibraryW (L"dwmapi.dll"))
  243. if (auto enable = (EnableMmcss) (void*) GetProcAddress (dwm, "DwmEnableMMCSS"))
  244. enable (TRUE);
  245. #endif
  246. }
  247. } // namespace powerhints
  248. namespace
  249. {
  250. #if JUCE_WINDOWS
  251. // what the audio threads reached (round toolchain190gt, REA 190hc: LYNX's were seen at dynamic priority 15 in some runs
  252. // and 24-25 in others, Live's always at 26): threads raised, how many joined MMCSS at CRITICAL, their thread priority
  253. std::atomic<int> rtThreadsRaised { 0 }, rtThreadsMmcss { 0 }, rtThreadsCritical { 0 };
  254. std::atomic<int> rtPriorityMin { 1000 }, rtPriorityMax { -1000 };
  255. // The process priority class (round toolchain190gt, REA 190hb): Windows' WinMM driver (wdmaud2.drv) raises a process
  256. // that opens a WinMM device to HIGH (and asks REALTIME), FL's and LYNX's alike, so the UI, decoders, prefetch and plugin
  257. // scans ran above every normal program; FL itself asks ABOVE_NORMAL. LYNX_PRIORITY_CLASS=above asks ABOVE_NORMAL when a
  258. // device starts (and again 2 s later, after the MIDI ports), relying on MMCSS for the audio threads. Default: left as
  259. // Windows sets it — measured with --rtstress (Exoplanet, 10 ms buffer, 3 x 3000 callbacks each, loaded PC): HIGH 0
  260. // callbacks over the deadline, ABOVE_NORMAL 1, the same average load; a 64-sample run was not possible on this PC.
  261. std::atomic<unsigned long> priorityClassFound { 0 }, priorityClassNow { 0 };
  262. void choosePriorityClass() noexcept
  263. {
  264. static const auto keep = juce::SystemStats::getEnvironmentVariable ("LYNX_PRIORITY_CLASS", {}) != "above";
  265. const auto found = GetPriorityClass (GetCurrentProcess());
  266. if (priorityClassFound.load (std::memory_order_relaxed) == 0 || found != ABOVE_NORMAL_PRIORITY_CLASS)
  267. priorityClassFound.store (found, std::memory_order_relaxed);
  268. if (! keep && found != ABOVE_NORMAL_PRIORITY_CLASS)
  269. SetPriorityClass (GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
  270. priorityClassNow.store (GetPriorityClass (GetCurrentProcess()), std::memory_order_relaxed);
  271. }
  272. juce::String priorityClassName (unsigned long c)
  273. {
  274. switch (c)
  275. {
  276. case IDLE_PRIORITY_CLASS: return "idle";
  277. case BELOW_NORMAL_PRIORITY_CLASS: return "below normal";
  278. case NORMAL_PRIORITY_CLASS: return "normal";
  279. case ABOVE_NORMAL_PRIORITY_CLASS: return "above normal";
  280. case HIGH_PRIORITY_CLASS: return "high";
  281. case REALTIME_PRIORITY_CLASS: return "realtime";
  282. default: return c == 0 ? juce::String ("not seen") : juce::String::toHexString ((juce::int64) c);
  283. }
  284. }
  285. #endif
  286. // Audio workers with real-time priority (MMCSS "Pro Audio" on Windows, like the driver; QoS class on macOS; SCHED_FIFO
  287. // on Linux when allowed).
  288. void raiseAudioThreadPriority()
  289. {
  290. #if JUCE_WINDOWS
  291. using AvSet = void* (__stdcall*) (const wchar_t*, unsigned long*);
  292. static const auto avSet = [] () -> AvSet {
  293. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  294. return reinterpret_cast<AvSet> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadCharacteristicsW")));
  295. return nullptr;
  296. }();
  297. // FL's audio worker threads raise their MMCSS priority to "high" (FLEngine_x64.dll, REA round 87); Live's to "critical"
  298. // (REA round 190hc: its 22 audio threads sat at dynamic priority 26 in every snapshot), which LYNX uses since round
  299. // toolchain190gt
  300. using AvPriority = int (__stdcall*) (void*, int);
  301. static const auto avPriority = [] () -> AvPriority {
  302. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  303. return reinterpret_cast<AvPriority> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadPriority")));
  304. return nullptr;
  305. }();
  306. unsigned long task = 0;
  307. if (auto* handle = avSet != nullptr ? avSet (L"Pro Audio", &task) : nullptr)
  308. {
  309. rtThreadsMmcss.fetch_add (1, std::memory_order_relaxed);
  310. if (avPriority != nullptr && avPriority (handle, 2 /* AVRT_PRIORITY_CRITICAL */) != 0)
  311. rtThreadsCritical.fetch_add (1, std::memory_order_relaxed);
  312. else if (avPriority != nullptr)
  313. avPriority (handle, 1 /* AVRT_PRIORITY_HIGH */);
  314. }
  315. else
  316. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  317. // and full speed while LYNX is in the background (no EcoQoS: platform/PowerThrottling.h, round toolchain190gt)
  318. power::optOutOfPowerThrottling();
  319. const auto reached = GetThreadPriority (GetCurrentThread());
  320. rtThreadsRaised.fetch_add (1, std::memory_order_relaxed);
  321. for (auto low = rtPriorityMin.load(); reached < low && ! rtPriorityMin.compare_exchange_weak (low, reached);) {}
  322. for (auto high = rtPriorityMax.load(); reached > high && ! rtPriorityMax.compare_exchange_weak (high, reached);) {}
  323. #elif JUCE_MAC
  324. // the highest quality-of-service class: scheduled like the UI's own interactive work, on the performance cores
  325. pthread_set_qos_class_self_np (QOS_CLASS_USER_INTERACTIVE, 0);
  326. #elif JUCE_LINUX || JUCE_BSD
  327. // real-time FIFO scheduling when the user may have it (audio group / rtkit limits, as JACK and PipeWire set up);
  328. // below the usual JACK/PipeWire audio thread priorities. Without the permission the thread stays as it is.
  329. sched_param param {};
  330. param.sched_priority = juce::jlimit (sched_get_priority_min (SCHED_FIFO), sched_get_priority_max (SCHED_FIFO), 70);
  331. if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &param) != 0)
  332. rt::noteAudioThread (false); // RealtimeKit / the portal may grant it (round 161)
  333. #endif
  334. }
  335. #if JUCE_MAC
  336. // The calling thread becomes a time-constraint (real-time) thread with the device's buffer as its period: about half of
  337. // it to compute, the whole of it as the deadline. Apple's audio workgroups take only such threads (os_workgroup_join
  338. // fails with EINVAL before; research round 190gs B1).
  339. void becomeTimeConstraintThread (double blockMs) noexcept
  340. {
  341. mach_timebase_info_data_t timebase {};
  342. if (mach_timebase_info (&timebase) != KERN_SUCCESS || timebase.numer == 0)
  343. return;
  344. const auto ticks = [&] (double ms) { return (uint32_t) (ms * 1.0e6 * (double) timebase.denom / (double) timebase.numer); };
  345. const auto period = juce::jlimit (0.5, 50.0, blockMs); // (above 50 ms the kernel refuses the policy)
  346. thread_time_constraint_policy_data_t policy { ticks (period), ticks (0.5 * period), ticks (period), 1 };
  347. thread_policy_set (pthread_mach_thread_np (pthread_self()), THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t) &policy,
  348. THREAD_TIME_CONSTRAINT_POLICY_COUNT);
  349. }
  350. #endif
  351. // The render-ahead thread (round 190gq, core/RenderAhead.h): the workers' priority, except on macOS, where it is not
  352. // deadline work and must never join the device's Audio Workgroup (round 190gt joins the real-time workers): the
  353. // interactive QoS class only.
  354. void raiseRenderAheadThreadPriority()
  355. {
  356. #if JUCE_MAC
  357. pthread_set_qos_class_self_np (QOS_CLASS_USER_INTERACTIVE, 0);
  358. #else
  359. raiseAudioThreadPriority();
  360. #endif
  361. }
  362. // Round 190gq (190gs Q7): the cores that give a block its full speed — physical cores (SMT siblings share one core's
  363. // units), and on hybrid CPUs only the performance class (a block waits for its slowest worker). 0 = unknown.
  364. int performanceCores()
  365. {
  366. #if JUCE_WINDOWS
  367. DWORD bytes = 0;
  368. GetLogicalProcessorInformationEx (RelationProcessorCore, nullptr, &bytes);
  369. if (bytes == 0)
  370. return 0;
  371. std::vector<std::uint8_t> buffer (bytes);
  372. if (! GetLogicalProcessorInformationEx (RelationProcessorCore, reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX> (buffer.data()), &bytes))
  373. return 0;
  374. int best = -1, count = 0;
  375. for (DWORD at = 0; at < bytes;)
  376. {
  377. const auto* info = reinterpret_cast<const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*> (buffer.data() + at);
  378. if (info->Relationship == RelationProcessorCore)
  379. {
  380. const auto cls = (int) info->Processor.EfficiencyClass; // (higher = faster; all 0 on a non-hybrid CPU)
  381. if (cls > best)
  382. {
  383. best = cls;
  384. count = 0;
  385. }
  386. if (cls == best)
  387. ++count;
  388. }
  389. if (info->Size == 0)
  390. break;
  391. at += info->Size;
  392. }
  393. return count;
  394. #elif JUCE_MAC
  395. int perf = 0;
  396. auto size = sizeof (perf);
  397. if (sysctlbyname ("hw.perflevel0.physicalcpu", &perf, &size, nullptr, 0) == 0 && perf > 0)
  398. return perf;
  399. int physical = 0;
  400. size = sizeof (physical);
  401. return sysctlbyname ("hw.physicalcpu", &physical, &size, nullptr, 0) == 0 ? physical : 0;
  402. #elif JUCE_LINUX || JUCE_BSD
  403. // sysfs: one (package, core) pair per physical core; on an Intel hybrid CPU only the cpu_core PMU's CPUs
  404. std::vector<std::pair<int, int>> cores;
  405. const juce::File root ("/sys/devices/system/cpu");
  406. juce::String hybrid = juce::File ("/sys/devices/cpu_core/cpus").loadFileAsString().trim(); // e.g. "0-15"
  407. auto inHybridSet = [&hybrid] (int cpu) {
  408. if (hybrid.isEmpty())
  409. return true;
  410. for (const auto& range : juce::StringArray::fromTokens (hybrid, ",", {}))
  411. {
  412. const auto from = range.upToFirstOccurrenceOf ("-", false, false).getIntValue();
  413. const auto to = range.contains ("-") ? range.fromFirstOccurrenceOf ("-", false, false).getIntValue() : from;
  414. if (cpu >= from && cpu <= to)
  415. return true;
  416. }
  417. return false;
  418. };
  419. for (int cpu = 0; cpu < 1024; ++cpu)
  420. {
  421. const auto dir = root.getChildFile ("cpu" + juce::String (cpu));
  422. if (! dir.isDirectory())
  423. break;
  424. const auto core = dir.getChildFile ("topology/core_id").loadFileAsString().trim();
  425. const auto package = dir.getChildFile ("topology/physical_package_id").loadFileAsString().trim();
  426. if (core.isEmpty() || ! inHybridSet (cpu))
  427. continue;
  428. const std::pair<int, int> id { package.getIntValue(), core.getIntValue() };
  429. if (std::find (cores.begin(), cores.end(), id) == cores.end())
  430. cores.push_back (id);
  431. }
  432. return (int) cores.size();
  433. #else
  434. return 0;
  435. #endif
  436. }
  437. int workerCount()
  438. {
  439. // diagnostics: LYNX_WORKERS=n fixes the number of extra threads
  440. if (const auto forced = juce::SystemStats::getEnvironmentVariable ("LYNX_WORKERS", {}); forced.isNotEmpty())
  441. return juce::jlimit (0, 31, forced.getIntValue());
  442. // round 190gq (190gs Q7): the audio thread and the workers on the performance cores, one per physical core, the
  443. // audio thread's own included (the SMT siblings and the slower cores are left to the UI and the rest). Before:
  444. // logical CPUs − 2 (7 workers on 6 cores / 12 threads). Unknown topology: as before.
  445. if (const auto cores = performanceCores(); cores > 0)
  446. return juce::jlimit (0, 7, cores - 1);
  447. const auto cores = (int) std::thread::hardware_concurrency();
  448. return juce::jlimit (0, 7, cores - 2);
  449. }
  450. juce::File midiSettingsFile() { return PluginHost::settingsFolder().getChildFile ("midi-settings.txt"); }
  451. juce::File audioDeviceFile() { return PluginHost::settingsFolder().getChildFile ("audio-device.xml"); }
  452. } // namespace
  453. // Saves the audio device setup whenever it changes (Settings › Audio, the setup wizard, a driver's own panel), so
  454. // the next start opens the same device.
  455. struct AudioEngine::DeviceStateSaver final : public juce::ChangeListener
  456. {
  457. explicit DeviceStateSaver (AudioEngine& e) : engine (e) { engine.deviceManager.addChangeListener (this); }
  458. ~DeviceStateSaver() override { engine.deviceManager.removeChangeListener (this); }
  459. void changeListenerCallback (juce::ChangeBroadcaster*) override { engine.saveAudioDeviceState(); }
  460. AudioEngine& engine;
  461. };
  462. // written by fileJobs: the write ends with FlushFileBuffers on Windows, which took 2 s on a busy disk and froze the UI
  463. // after every device change (issue #13). In order, so the newest setup is the one left on disk.
  464. void AudioEngine::saveAudioDeviceState()
  465. {
  466. if (auto xml = deviceManager.createStateXml())
  467. fileJobs.post ([text = xml->toString(), file = audioDeviceFile()] { file.replaceWithText (text); });
  468. }
  469. void AudioEngine::restoreAudioDeviceState (const juce::XmlElement* state)
  470. {
  471. deviceStateSaver = nullptr;
  472. fileJobs.post ([text = state != nullptr ? state->toString() : juce::String(), restore = state != nullptr, file = audioDeviceFile()] {
  473. if (restore)
  474. file.replaceWithText (text);
  475. else
  476. file.deleteFile();
  477. });
  478. fileJobs.waitIdle(); // (after the saves still queued, and done when this returns)
  479. }
  480. namespace
  481. {
  482. AudioEngine::RecordingSettings loadRecordingSettings();
  483. }
  484. struct AudioEngine::Drainer final : juce::TimeSliceClient
  485. {
  486. explicit Drainer (AudioEngine& e) : engine (e) {}
  487. int useTimeSlice() override
  488. {
  489. std::vector<std::shared_ptr<Take>> list;
  490. {
  491. const juce::ScopedLock lock (engine.drainLock);
  492. list = engine.draining;
  493. }
  494. for (auto& take : list)
  495. {
  496. const juce::ScopedLock lock (take->drainMutex);
  497. take->drain();
  498. }
  499. return list.empty() ? 50 : 5;
  500. }
  501. AudioEngine& engine;
  502. };
  503. namespace
  504. {
  505. // the engine whose project the plugin hold is for (round 190ap): the hold ends when that engine opens another project
  506. std::atomic<const AudioEngine*> pluginHoldOwner { nullptr };
  507. } // namespace
  508. AudioEngine::AudioEngine (bool openAudioDevice, int workerThreads, bool userPluginList, bool deferDeviceOpen)
  509. // (an engine without an audio device renders offline — exports, bounces, freezes: its workers run below normal
  510. // priority as FL's export threads do, rollup 0.1.28 / REA 190hb; the live engine's workers get the audio priority)
  511. : workers (std::make_unique<WorkerPool> (workerThreads >= 0 ? workerThreads : workerCount(),
  512. openAudioDevice ? std::function<void()> (raiseAudioThreadPriority)
  513. : std::function<void()> (powerhints::lowerWorkerThread))),
  514. plugins (userPluginList),
  515. song (Song::makeDefault())
  516. {
  517. // Harmor's resynthesis (round natives190kj): the sample a part names, found as FL finds it (path variables, then the
  518. // file re-rooted to this PC's FL folders) and decoded by the core (WAV, FL's Ogg-in-WAV, Ogg Vorbis, WavPack)
  519. harmor::setSampleLoader ([] (const std::string& saved, harmor::SampleData& out) {
  520. const auto& fl = flStudioAccess();
  521. const auto path = locateFlSample (saved, fl.roots, {}, fl.fileExists);
  522. return ! path.empty() && fl.readFile && harmor::readWavMono (fl.readFile (path), out);
  523. });
  524. boostDeviceThread = juce::SystemStats::getEnvironmentVariable ("LYNX_DEVICE_BOOST", {}) != "0";
  525. inputSlot.fill (-1);
  526. outputSlot.fill (-1);
  527. // VFX Script (round 165d): the audio thread waits a bounded time for the Python thread (exports wait for it)
  528. vfx::script::setRealtime (openAudioDevice);
  529. const auto mark = [] (const char* step) { if (startupMark != nullptr) startupMark (step); };
  530. mark (" engine: workers + default song");
  531. if (juce::JUCEApplicationBase::getInstance() != nullptr) // issue #36: retired racks are freed from their own message
  532. rackExchange.dispose = [this] (const RackState* rack) { rackDisposer.add (rack); };
  533. publishSong();
  534. buildInitialGraph();
  535. mark (" engine: graph");
  536. if (openAudioDevice)
  537. {
  538. player.setProcessor (&graph);
  539. // the settings that do not need the device (the window reads them; round 190go: built before the device opens)
  540. if (rackProcessor != nullptr)
  541. rackProcessor->setProfiling (true); // per-unit CPU for the CPU meter and the glitch log (both renderers: 190gq)
  542. midiPrefs = midiPrefsShared = prefs::MidiPrefs::fromText (midiSettingsFile().loadFileAsString().toStdString());
  543. performanceMidiChannel.store (midiPrefs.performanceChannel);
  544. controllerIo.loadProfiles (controllerProfilesFolder());
  545. recordingSettings = loadRecordingSettings();
  546. saveGlobalLinks = true;
  547. devicePending = midiPending = true;
  548. if (! deferDeviceOpen)
  549. {
  550. this->openAudioDevice();
  551. openMidiDevices();
  552. }
  553. }
  554. startTimerHz (30); // recording and collection of retired snapshots
  555. }
  556. void AudioEngine::openAudioDevice()
  557. {
  558. if (! std::exchange (devicePending, false))
  559. return;
  560. const auto mark = [] (const char* step) { if (startupMark != nullptr) startupMark (step); };
  561. // LYNX ASIO without installation: lynx-asio.dll next to LYNX.exe, when it is not registered (REA round 106)
  562. deviceManager.getAvailableDeviceTypes(); // the standard types first (round 190hd: its own trace line)
  563. mark (" engine: standard device types (the prewarmed ASIO device handed over)");
  564. if (auto lynxAsio = makeBuiltInLynxAsioType())
  565. deviceManager.addAudioDeviceType (std::move (lynxAsio));
  566. // LYNX's own PipeWire client on Linux (round 161), listed when a PipeWire daemon answers
  567. if (auto pipeWire = makePipeWireDeviceType())
  568. {
  569. deviceManager.getAvailableDeviceTypes();
  570. deviceManager.addAudioDeviceType (std::move (pipeWire));
  571. }
  572. mark (" engine: device types");
  573. // 0 inputs, 2 outputs; the device of the last session (Settings › Audio) if it is still there, else the default.
  574. const auto saved = juce::XmlDocument::parse (audioDeviceFile());
  575. // (round 190go) the MIDI ports the saved setup names open with the MIDI devices (openMidiDevices: LYNX's MIDI
  576. // settings decide which inputs are open anyway), not on the audio device's way: JUCE opened them here (~0.1-0.2 s)
  577. if (saved != nullptr)
  578. {
  579. savedMidiOutput = { saved->getStringAttribute ("defaultMidiOutput"), saved->getStringAttribute ("defaultMidiOutputDevice") };
  580. saved->removeAttribute ("defaultMidiOutput");
  581. saved->removeAttribute ("defaultMidiOutputDevice");
  582. saved->deleteAllChildElementsWithTagName ("MIDIINPUT");
  583. }
  584. auto fresh = saved == nullptr;
  585. auto failed = deviceManager.initialise (0, 2, saved.get(), true).isNotEmpty();
  586. // (round 190hd) a device made ahead without JUCE's start / stop at init that then failed: once more the usual way
  587. if (failed && saved != nullptr && asioPrewarmQuickInit())
  588. failed = deviceManager.initialise (0, 2, saved.get(), true).isNotEmpty();
  589. if (failed && saved != nullptr)
  590. {
  591. deviceManager.initialise (0, 2, nullptr, true);
  592. fresh = true;
  593. }
  594. if (fresh)
  595. {
  596. choosePreferredDriver(); // Linux: PipeWire, then JACK, then ALSA
  597. chooseSafeBufferSize(); // no saved setup: a buffer with room for heavy projects (Settings › Audio changes it)
  598. }
  599. mark (" engine: device opened");
  600. deviceManager.addAudioCallback (this);
  601. deviceStateSaver = std::make_unique<DeviceStateSaver> (*this);
  602. prefetcher = std::make_unique<StreamPrefetcher> (transport);
  603. prefetcher->update (song, samples);
  604. // a project set while the device was not open yet (round 190go: the start-up song, built with the window): its
  605. // inputs, FL insert inputs, hardware outputs and inserts open now, as they do when a project is opened
  606. if (followProjectOnDevice())
  607. publishSong();
  608. mark (" engine: callback + settings");
  609. }
  610. void AudioEngine::prewarmAudioDevice()
  611. {
  612. prewarmAsioDevice (audioDeviceFile());
  613. }
  614. void AudioEngine::openMidiDevices()
  615. {
  616. if (! std::exchange (midiPending, false))
  617. return;
  618. midiOpen = true;
  619. // the default MIDI output of the last session (see openAudioDevice), by its id, else by its name (as JUCE does)
  620. if (savedMidiOutput.name.isNotEmpty() || savedMidiOutput.identifier.isNotEmpty())
  621. for (const auto& out : juce::MidiOutput::getAvailableDevices())
  622. if (out.identifier == savedMidiOutput.identifier || (savedMidiOutput.identifier.isEmpty() && out.name == savedMidiOutput.name))
  623. {
  624. deviceManager.setDefaultMidiOutputDevice (out.identifier);
  625. break;
  626. }
  627. enableAllMidiInputs();
  628. configureMidiOutputs();
  629. midiSync.sendAllNotesOff(); // FL's "Send all notes off": on init and after a render
  630. if (! platform::testMode()) // (round 190gl: Link on as it was left; never in a test run, which must not join a session)
  631. applyLinkPrefs();
  632. deviceManager.addMidiInputDeviceCallback ({}, this); // {} = all inputs enabled
  633. midiDevicesChanged = juce::MidiDeviceListConnection::make ([this] { enableAllMidiInputs(); });
  634. if (startupMark != nullptr)
  635. startupMark (" engine: MIDI inputs");
  636. }
  637. AudioLogger& AudioEngine::getAudioLogger()
  638. {
  639. if (audioLogger == nullptr)
  640. audioLogger = std::make_unique<AudioLogger> (meters.logTap);
  641. return *audioLogger;
  642. }
  643. AudioEngine::~AudioEngine()
  644. {
  645. if (rackProcessor != nullptr) // (round 190gq: the render-ahead thread stops before the snapshots are freed)
  646. rackProcessor->haltRenderAhead();
  647. if (pluginHoldOwner.load() == this) // (round 190ap: the hold goes with its project's engine)
  648. {
  649. pluginHoldOwner.store (nullptr);
  650. endPluginHold();
  651. }
  652. previewAlive->store (false); // (round 190aq: a preview still being prepared ends without touching the engine)
  653. previewJobs.stop();
  654. stopTimer();
  655. rackExchange.dispose = nullptr; // (from here the racks are freed at once)
  656. rackDisposer.flush();
  657. audioLogger.reset(); // closes the log file
  658. // the takes in progress are closed as they are (complete WAVs); their journals stay, so the next start offers to
  659. // put them on the Playlist (round 163)
  660. {
  661. const juce::SpinLock::ScopedLockType lock (takeLock);
  662. takes.fill (nullptr);
  663. takeCount = 0;
  664. }
  665. {
  666. const juce::ScopedLock lock (drainLock);
  667. draining.clear();
  668. }
  669. if (drainer != nullptr)
  670. recordThread.removeTimeSliceClient (drainer.get());
  671. for (auto& take : openTakes)
  672. {
  673. take->stream->finish();
  674. const juce::ScopedLock lock (take->drainMutex);
  675. take->drain();
  676. take->writer.close();
  677. }
  678. openTakes.clear();
  679. recordThread.stopThread (2000);
  680. prefetcher = nullptr;
  681. midiDevicesChanged = {};
  682. deviceStateSaver = nullptr;
  683. deviceManager.removeMidiInputDeviceCallback ({}, this);
  684. deviceManager.removeAudioCallback (this);
  685. player.setProcessor (nullptr);
  686. graph.clear(); // the nodes reference rackExchange and transport
  687. }
  688. void AudioEngine::buildInitialGraph()
  689. {
  690. // The output node inherits the graph's channel count at the moment it is created.
  691. // Without this the graph still has 0 outputs and JUCE silently rejects the connections.
  692. graph.setPlayConfigDetails (0, 2, transport.sampleRate.load(), 512);
  693. auto output = graph.addNode (std::make_unique<IONode> (IONode::audioOutputNode));
  694. auto rack = graph.addNode (std::make_unique<ChannelRackProcessor> (transport, rackExchange, liveEvents, midiEvents, meters, workers.get(),
  695. raiseRenderAheadThreadPriority));
  696. rackProcessor = dynamic_cast<ChannelRackProcessor*> (rack->getProcessor());
  697. if (rackProcessor != nullptr)
  698. {
  699. rackProcessor->setRenderAheadTargets (&renderAheadTargets); // (round 190gq)
  700. rackProcessor->setLiveInput (&liveInput);
  701. rackProcessor->setHardwareOutput (&hwOutput);
  702. rackProcessor->setPerformance (performanceLive.get());
  703. rackProcessor->getRenderer().reserveFor (lastPublishedShape); // (round 190gn: a song published before the graph)
  704. rackProcessor->getRenderer().setHardwareMidiPorts (hardwareMidiPorts); // (round 190jl)
  705. rackProcessor->getRenderer().setOwnNoteChannels (ownNoteChannels); // (round 190ks)
  706. rackProcessor->getRenderer().setCurrentSource (currentSource); // (round 190mv)
  707. // FL's own metronome sounds from its install (Data\System), LYNX's stand-ins without it (round 165z-a2)
  708. const auto& flData = flStudioAccess().roots.data;
  709. rackProcessor->setMetronome (std::make_unique<Metronome> (transport, flData.empty() ? juce::File() : platform::localFile (flData)));
  710. }
  711. auto previewOwned = std::make_unique<PreviewPlayer>();
  712. preview = previewOwned.get();
  713. preview->setTransport (&transport); // (round 190aq: "Preview in time" starts on its beats)
  714. preview->setVolume (controls::previewGain (previewVolume));
  715. preview->setEditorVolume (controls::previewGain (editorVolume));
  716. auto previewNode = graph.addNode (std::move (previewOwned));
  717. for (int channel = 0; channel < 2; ++channel)
  718. {
  719. graph.addConnection ({ { rack->nodeID, channel }, { output->nodeID, channel } });
  720. graph.addConnection ({ { previewNode->nodeID, channel }, { output->nodeID, channel } });
  721. }
  722. jassert (graph.getConnections().size() == 4);
  723. }
  724. std::atomic<int>& AudioEngine::offlineRendersRunning() noexcept
  725. {
  726. static std::atomic<int> count { 0 };
  727. return count;
  728. }
  729. RenderStream::Setup AudioEngine::streamSetup (const RenderOptions& options, int latency)
  730. {
  731. RenderStream::Setup setup;
  732. setup.trim = (std::int64_t) juce::jmax (0, options.trimSamples + (options.trimPdc ? latency : 0));
  733. setup.musicSamples = (std::int64_t) (options.seconds * options.sampleRate) + setup.trim;
  734. // (round 190gh: an exact length renders that much after the trim, the tail's silence does not end it)
  735. setup.totalSamples = options.exactSamples > 0 ? setup.trim + options.exactSamples
  736. : setup.musicSamples + (std::int64_t) (juce::jmax (0.0, options.tailSeconds) * options.sampleRate);
  737. setup.exact = options.exactSamples > 0;
  738. setup.sampleRate = options.sampleRate;
  739. setup.keepOvers = options.keepOvers;
  740. setup.ditherBits = options.ditherBits;
  741. setup.ditherShaping = options.ditherShaping;
  742. setup.output = options.output;
  743. setup.capture = options.capture;
  744. return setup;
  745. }
  746. float AudioEngine::renderOffline (const RenderOptions& options)
  747. {
  748. offlineRendersRunning().fetch_add (1, std::memory_order_acq_rel);
  749. const juce::ScopeGuard rendered { [] { offlineRendersRunning().fetch_sub (1, std::memory_order_acq_rel); } };
  750. // (round 190mp: FL's Half speed is a listening state: an export renders at the song's own speed)
  751. const auto speedBefore = transport.playSpeed.exchange (1.0, std::memory_order_relaxed);
  752. const juce::ScopeGuard speedBack { [this, speedBefore] { transport.playSpeed.store (speedBefore, std::memory_order_relaxed); } };
  753. const auto sampleRate = options.sampleRate;
  754. const auto& progress = options.progress;
  755. auto* shared = options.shared;
  756. constexpr int blockSize = renderBlockSize;
  757. // "HQ for all plugins" (REA round 134): engines with FL render-quality settings use them (Sytrus) and HQ switches
  758. // are forced on; without it the export keeps the playback quality
  759. setOfflineRendering (options.hqAllPlugins);
  760. setRenderInProgress (true); // (whatever the quality: LYNX Soundfont waits for a font that is still loading, issue #138)
  761. setHqForAllPlugins (options.hqAllPlugins);
  762. setPluginsRenderMode (true); // and hosted plugins are told an export is running (FL: "notify about rendering mode")
  763. transport.sampleRate.store (sampleRate);
  764. // round 164c: JUCE's graph builds its render sequence on the message thread. Prepared from the Export window's
  765. // thread it rebuilt later (asynchronously) and rendered silence until then: the first ~0.05–2 s of the song were
  766. // lost (the transport kept moving). It is prepared on the message thread, and the render waits for that.
  767. {
  768. auto prepareGraph = [this, sampleRate] {
  769. graph.setPlayConfigDetails (0, 2, sampleRate, blockSize);
  770. graph.prepareToPlay (sampleRate, blockSize);
  771. };
  772. auto* mm = juce::MessageManager::getInstanceWithoutCreating();
  773. if (mm == nullptr || mm->isThisTheMessageThread())
  774. prepareGraph();
  775. else
  776. {
  777. struct Handshake
  778. {
  779. juce::WaitableEvent done;
  780. std::atomic<bool> abandoned { false };
  781. };
  782. auto handshake = std::make_shared<Handshake>();
  783. juce::MessageManager::callAsync ([prepareGraph, handshake] {
  784. if (handshake->abandoned.load())
  785. return;
  786. prepareGraph();
  787. handshake->done.signal();
  788. });
  789. if (! handshake->done.wait (10000)) // (a message thread that is blocked: as before)
  790. {
  791. handshake->abandoned = true;
  792. prepareGraph();
  793. }
  794. }
  795. }
  796. if (rackProcessor != nullptr)
  797. {
  798. rackProcessor->setMetering (false); // nobody looks at the meters during the render
  799. rackProcessor->setMetronomeAllowed (options.includeMetronome);
  800. }
  801. lastRenderStats = {};
  802. // FL's init list first (play() would do it at the first block), so the plugins settle on those values too
  803. resetToInitialValues();
  804. // round 190kx: an ARA plugin renders what it has analysed: the render waits (at most 3 minutes) until its analysis of
  805. // the clips is done (a live engine's has long been; a fresh export engine's instances analyse now)
  806. if (araHost != nullptr)
  807. {
  808. const auto onMessageThread = juce::MessageManager::existsAndIsCurrentThread();
  809. const auto start = juce::Time::getMillisecondCounterHiRes();
  810. juce::Thread::sleep (onMessageThread ? 0 : 300); // (the heartbeat's first look)
  811. while (araHost->analysing() && juce::Time::getMillisecondCounterHiRes() - start < 180000.0)
  812. juce::Thread::sleep (50);
  813. lastRenderStats.araWaitMs = juce::Time::getMillisecondCounterHiRes() - start;
  814. }
  815. int latency = getLatencySamples();
  816. if (options.pluginWarmUp)
  817. lastRenderStats.warmUp = warmUpPlugins (options.warmUp, sampleRate, blockSize, progress, latency);
  818. play();
  819. juce::AudioBuffer<float> buffer (2, blockSize);
  820. juce::MidiBuffer midi;
  821. // what is done after the graph (round 190gj: RenderStream, the same code as the single-pass stems' files), with the
  822. // PDC trim of the latency the plugins report once they have settled
  823. auto setup = streamSetup (options, latency);
  824. lastRenderStats.trimmedSamples = (int) setup.trim;
  825. const auto musicSamples = setup.musicSamples;
  826. const auto totalSamples = setup.totalSamples;
  827. if (shared != nullptr)
  828. {
  829. setup.output = nullptr;
  830. setup.capture = nullptr;
  831. }
  832. RenderStream stream (std::move (setup));
  833. bool cancelled = lastRenderStats.warmUp.cancelled;
  834. if (shared != nullptr && ! cancelled)
  835. shared->start (latency);
  836. vfx::script::setSongEnded (false);
  837. for (std::int64_t done = 0; ! cancelled;)
  838. {
  839. const auto n = shared != nullptr ? juce::jmin (blockSize, shared->nextBlock (done)) : stream.blockAt (done, blockSize);
  840. if (n <= 0)
  841. break;
  842. // the tail: the song has ended (VFX Script sees the transport stopped, like FL's render; round 167e)
  843. if (done >= musicSamples)
  844. vfx::script::setSongEnded (true);
  845. juce::AudioBuffer<float> view (buffer.getArrayOfWritePointers(), 2, n);
  846. view.clear();
  847. const auto before = juce::Time::getMillisecondCounterHiRes();
  848. graph.processBlock (view, midi);
  849. const auto afterGraph = juce::Time::getMillisecondCounterHiRes();
  850. lastRenderStats.graphMs += afterGraph - before;
  851. if (shared != nullptr)
  852. shared->block (view, done, n);
  853. else
  854. stream.block (view, done, n);
  855. transport.positionTicks.store (transport.positionTicks.load() + n * transport.ticksPerSample());
  856. // in the tail: half a second of silence ends it
  857. if (stream.endedBySilence())
  858. break;
  859. // (a shared render reports its own progress, and is cancelled by ending its blocks)
  860. if (shared == nullptr && progress && (done / blockSize) % 32 == 0
  861. && ! progress ((double) done / (double) juce::jmax<std::int64_t> (1, totalSamples)))
  862. {
  863. cancelled = true;
  864. break;
  865. }
  866. done += n;
  867. if (stream.hasEnded())
  868. break;
  869. }
  870. lastRenderStats.writeMs = stream.getWriteMs();
  871. const auto peak = stream.getPeak();
  872. stop();
  873. vfx::script::setSongEnded (false);
  874. if (rackProcessor != nullptr)
  875. {
  876. rackProcessor->setMetering (true);
  877. rackProcessor->setMetronomeAllowed (true);
  878. }
  879. graph.releaseResources();
  880. setPluginsRenderMode (false);
  881. setOfflineRendering (false);
  882. setRenderInProgress (false);
  883. setHqForAllPlugins (false);
  884. return cancelled ? -1.0f : peak;
  885. }
  886. warmup::Result AudioEngine::warmUpPlugins (const warmup::Settings& settings, double sampleRate, int blockSize,
  887. const std::function<bool (double)>& progress, int& latency)
  888. {
  889. // the hosted plugins, collected once: the timer may republish the song meanwhile (the instances stay the same)
  890. std::vector<juce::AudioPluginInstance*> hosted;
  891. forEachHostedPlugin ([&hosted] (juce::AudioPluginInstance& p, bool) { hosted.push_back (&p); });
  892. if (hosted.empty())
  893. return {}; // LYNX's own engines are ready as soon as they are created: nothing to wait for
  894. // Issue #138 (round 190hn): a hosted instrument gets at least `hostedInstrumentSeconds` of audio. The export's
  895. // instances are new ones (FL renders with the instances that have been playing since the project opened), and a
  896. // hardware emulator boots its firmware in the audio it processes, not in wall time: gearmulator's JE-8086 holds MIDI
  897. // back for its first ~0.8 s of emulated time ("the firmware drops what arrives while it boots") and then plays the
  898. // restored patch in at MIDI speed. A second of warm-up left a short note at tick 0 meeting a synth still loading its
  899. // patch: a silent export, the same note a bar later fine. (Plugins that are ready at once only cost the time it
  900. // takes them to process the extra silence, a few ms for most.)
  901. constexpr double hostedInstrumentSeconds = 3.0;
  902. auto wait = settings;
  903. // Round 190jb: a unit lent by the live engine (it renders with the instances that play, as FL) has booted long ago;
  904. // when every hosted plugin of the render is one, the warm-up only lets the start's values settle (FL has none)
  905. auto lent = [this] (const void* unit) { return std::find (lentUnits.begin(), lentUnits.end(), unit) != lentUnits.end(); };
  906. auto allLent = true;
  907. for (std::size_t i = 0; i < song.channels.size(); ++i)
  908. if (const auto kind = song.channels[i].instrument; kind == InstrumentKind::plugin || kind == InstrumentKind::patcher)
  909. allLent = allLent && lent (getChannelInstrument ((int) i).get());
  910. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  911. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  912. if (const auto kind = song.mixer[t].effects[s].kind; kind == EffectKind::plugin || kind == EffectKind::patcher)
  913. allLent = allLent && lent (getEffect ((int) t, (int) s).get());
  914. if (allLent)
  915. {
  916. wait.minAudioSeconds = 0.0;
  917. wait.minWallSeconds = 0.0;
  918. wait.stableWallSeconds = juce::jmin (wait.stableWallSeconds, 0.05);
  919. wait.maxWallSeconds = juce::jmin (wait.maxWallSeconds, 2.0);
  920. }
  921. else if (std::any_of (song.channels.begin(), song.channels.end(), [] (const ChannelDef& c) { return c.instrument == InstrumentKind::plugin; }))
  922. wait.minAudioSeconds = juce::jmax (wait.minAudioSeconds, hostedInstrumentSeconds);
  923. // keeps the units alive whatever the timer publishes during the warm-up
  924. std::vector<std::shared_ptr<Instrument>> keepInstruments;
  925. std::vector<std::shared_ptr<Effect>> keepEffects;
  926. for (std::size_t i = 0; i < song.channels.size(); ++i)
  927. keepInstruments.push_back (getChannelInstrument ((int) i));
  928. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  929. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  930. keepEffects.push_back (getEffect ((int) t, (int) s));
  931. juce::AudioBuffer<float> buffer (2, blockSize);
  932. juce::MidiBuffer midi;
  933. int blocks = 0;
  934. // transport stopped at the start position: no note plays, and the automation / pattern events at that position
  935. // reach the plugins (the rack evaluates them every block), so they settle on the values the song starts with
  936. const auto result = warmup::run (
  937. wait, sampleRate,
  938. [&]() -> int {
  939. if (progress && ++blocks % 32 == 0 && ! progress (0.0))
  940. return -1;
  941. buffer.clear();
  942. midi.clear();
  943. graph.processBlock (buffer, midi);
  944. return blockSize;
  945. },
  946. [&hosted] {
  947. warmup::Hash h;
  948. for (auto* p : hosted)
  949. {
  950. h.add ((std::uint64_t) (std::int64_t) p->getLatencySamples());
  951. for (auto* param : p->getParameters())
  952. h.addValue (param->getValue());
  953. }
  954. return h.value;
  955. },
  956. [] { return juce::Time::getMillisecondCounterHiRes() * 0.001; },
  957. [] (double s) { juce::Thread::sleep (juce::jlimit (1, 20, (int) std::lround (s * 1000.0))); });
  958. // a latency that changed (reported late) gets its PDC plan before the render, on the message thread as the
  959. // timer does it (renders from the Export window run on a thread of their own)
  960. auto republish = [this] {
  961. if (lastPublishedShape.currentLatencies() != lastPublishedShape.latencies)
  962. {
  963. ++latencyRepublishes;
  964. publishSong();
  965. }
  966. return getLatencySamples();
  967. };
  968. auto* mm = juce::MessageManager::getInstanceWithoutCreating();
  969. if (mm == nullptr || mm->isThisTheMessageThread())
  970. latency = republish();
  971. else
  972. {
  973. struct Reply
  974. {
  975. juce::WaitableEvent done;
  976. std::atomic<int> latency { 0 };
  977. };
  978. auto reply = std::make_shared<Reply>();
  979. reply->latency = getLatencySamples();
  980. juce::MessageManager::callAsync ([this, reply, republish] {
  981. reply->latency = republish();
  982. reply->done.signal();
  983. });
  984. reply->done.wait (3000);
  985. latency = reply->latency.load();
  986. }
  987. // LYNX's own units start the render from a clean state, as without the warm-up (free-running LFOs, the delay
  988. // compensation's lines); the hosted plugins are not reset: they keep what they settled on (a reset re-activates
  989. // them, which is what they had to settle from)
  990. if (rackProcessor != nullptr)
  991. rackProcessor->prepareToPlay (sampleRate, blockSize);
  992. return result;
  993. }
  994. void AudioEngine::forEachHostedPlugin (const std::function<void (juce::AudioPluginInstance&, bool notifyRender)>& visit) const
  995. {
  996. for (std::size_t i = 0; i < song.channels.size(); ++i)
  997. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()); p != nullptr && ! p->hasCrashed())
  998. visit (p->getInstance(), song.channels[i].plugin.notifyRender);
  999. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  1000. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  1001. if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()); p != nullptr && ! p->hasCrashed())
  1002. visit (p->getInstance(), song.mixer[t].effects[s].plugin.notifyRender);
  1003. std::function<void (patcher::Graph*)> inGraph = [&] (patcher::Graph* graph) {
  1004. if (graph == nullptr)
  1005. return;
  1006. for (int n = 0; n < graph->nodeCount(); ++n)
  1007. {
  1008. auto effect = graph->effectAt (n);
  1009. auto instrument = graph->instrumentAt (n);
  1010. if (auto* p = dynamic_cast<PluginEffect*> (effect.get()); p != nullptr && ! p->hasCrashed())
  1011. visit (p->getInstance(), true);
  1012. if (auto* p = dynamic_cast<PluginInstrument*> (instrument.get()); p != nullptr && ! p->hasCrashed())
  1013. visit (p->getInstance(), true);
  1014. inGraph (patcher::graphOf (effect.get()));
  1015. inGraph (patcher::graphOf (instrument.get()));
  1016. }
  1017. };
  1018. for (std::size_t i = 0; i < song.channels.size(); ++i)
  1019. inGraph (patcher::graphOf (getChannelInstrument ((int) i).get()));
  1020. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  1021. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  1022. inGraph (patcher::graphOf (getEffect ((int) t, (int) s).get()));
  1023. }
  1024. void AudioEngine::getPublishedLatencies (std::vector<int>& channels, std::vector<std::vector<int>>& slots) const
  1025. {
  1026. // RackState::latencies: the instruments, then the slots of every insert in order (buildPdc's layout)
  1027. const auto& shape = lastPublishedShape;
  1028. channels.clear();
  1029. slots.assign (shape.effects.size(), {});
  1030. auto next = shape.latencies.begin();
  1031. for (std::size_t c = 0; c < shape.instruments.size() && next != shape.latencies.end(); ++c)
  1032. channels.push_back (*next++);
  1033. for (std::size_t t = 0; t < shape.effects.size(); ++t)
  1034. for (std::size_t s = 0; s < shape.effects[t].size() && next != shape.latencies.end(); ++s)
  1035. slots[t].push_back (*next++);
  1036. }
  1037. void AudioEngine::setRenderTaps (RackRenderer::RenderTaps* taps) noexcept
  1038. {
  1039. if (rackProcessor != nullptr)
  1040. rackProcessor->getRenderer().setRenderTaps (taps);
  1041. }
  1042. ProcessTimes* AudioEngine::getProcessTimes() noexcept
  1043. {
  1044. if (externalTimes != nullptr)
  1045. return externalTimes;
  1046. return rackProcessor != nullptr ? &rackProcessor->processTimes() : nullptr;
  1047. }
  1048. bool AudioEngine::previewClipThroughChannel (std::size_t clipIndex)
  1049. {
  1050. if (clipIndex >= song.playlist.size())
  1051. return false;
  1052. const auto& c = song.playlist[clipIndex];
  1053. if (c.kind != ClipKind::audio || c.channel < 0 || c.channel >= (int) song.channels.size() || c.length <= 0)
  1054. return false;
  1055. stopClipPreview(); // (the next preview replaces the last)
  1056. const auto rate = transport.sampleRate.load() > 0.0 ? transport.sampleRate.load() : 44100.0;
  1057. auto e = audioClipNote (song, c, clipIndex, ticksPerSample (std::max (song.bpm, 1.0), rate));
  1058. e.sampleOffset = 0;
  1059. if (! liveEvents.push (e))
  1060. return false;
  1061. clipPreviewChannel = c.channel;
  1062. clipPreviewKey = e.key;
  1063. const auto serial = ++clipPreviewSerial;
  1064. // FL stops it at the clip's end (mouse-up and clicks elsewhere don't): the note's off then
  1065. const auto ms = (int) std::ceil ((double) c.length * 60000.0 / (std::max (song.bpm, 1.0) * ppq)) + 10;
  1066. juce::Timer::callAfterDelay (ms, [this, serial, alive = previewAlive] {
  1067. if (alive->load() && serial == clipPreviewSerial)
  1068. stopClipPreview();
  1069. });
  1070. return true;
  1071. }
  1072. void AudioEngine::stopClipPreview() noexcept
  1073. {
  1074. // (the live note queue has one producer, the UI thread: play() / stop() called from the audio or a MIDI thread leave it
  1075. // to the preview's own end)
  1076. if (clipPreviewKey < 0 || ! juce::MessageManager::existsAndIsCurrentThread())
  1077. return;
  1078. NoteEvent e;
  1079. e.type = NoteEvent::Type::off;
  1080. e.channel = clipPreviewChannel;
  1081. e.key = clipPreviewKey;
  1082. liveEvents.push (e);
  1083. clipPreviewChannel = clipPreviewKey = -1;
  1084. ++clipPreviewSerial;
  1085. }
  1086. void AudioEngine::play() noexcept
  1087. {
  1088. preparePlay();
  1089. transport.playing.store (true);
  1090. }
  1091. void AudioEngine::preparePlay() noexcept
  1092. {
  1093. stopClipPreview(); // (live check 190ew PL-3: transport start ends a clip preview)
  1094. if (! transport.playing.load())
  1095. {
  1096. resetToInitialValues();
  1097. // Performance mode: the song plays from its Start marker (the zone before it is launched, not played)
  1098. if (const auto zone = song.mode == PlayMode::song ? song.performanceZoneEnd() : 0; zone > 0 && transport.positionTicks.load() < (double) zone)
  1099. seek ((double) zone);
  1100. // FL's "Start" marker: Play from the song's beginning starts at the marker (Song mode)
  1101. if (song.mode == PlayMode::song && transport.seekRequest.load() < 0.0 && transport.positionTicks.load() <= 0.0)
  1102. if (const auto start = transport.markerStart.load(); start > 0)
  1103. transport.seekRequest.store ((double) start);
  1104. }
  1105. }
  1106. // FL resets its "initialized controls" whenever the song position is set in song mode (playing starts, a jump):
  1107. // FUN_011e7470 plays the song's init list (PTR_DAT_015dfc48) before the pattern events (REA round 146).
  1108. void AudioEngine::resetToInitialValues() noexcept
  1109. {
  1110. if (song.initialValues.empty() || song.mode != PlayMode::song)
  1111. return;
  1112. try
  1113. {
  1114. auto differs = false;
  1115. for (const auto& v : song.initialValues)
  1116. {
  1117. const auto now = currentTargetValue (v.target);
  1118. differs = differs || (now >= 0.0f && std::abs (now - v.value) > 1.0e-6f);
  1119. }
  1120. if (! differs)
  1121. return;
  1122. std::vector<Song::InitialValue> plugins;
  1123. editSong ([&plugins] (Song& s) { s.applyInitialValues ([&plugins] (const AutomationTarget& t, float v) { plugins.push_back ({ t, v }); }); },
  1124. false);
  1125. for (const auto& v : plugins)
  1126. {
  1127. if (v.target.kind == AutomationTargetKind::channelParam)
  1128. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (v.target.index).get()))
  1129. p->setParameterFromUi (v.target.param, v.value);
  1130. if (v.target.kind == AutomationTargetKind::effectParam)
  1131. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (v.target.index, v.target.slot).get()))
  1132. p->setParameterFromUi (v.target.param, v.value);
  1133. }
  1134. }
  1135. catch (...)
  1136. {
  1137. }
  1138. }
  1139. void AudioEngine::stop() noexcept
  1140. {
  1141. stopClipPreview(); // (live check 190ew PL-3: and transport stop)
  1142. waitingForInput.store (false);
  1143. transport.countIn.store (0.0);
  1144. transport.linkWaiting.store (false); // (round 190gl: a start waiting for the Link session's phase is cancelled)
  1145. transport.playing.store (false);
  1146. }
  1147. std::vector<char> AudioEngine::lowLatencyTracksNow() const
  1148. {
  1149. return recordOptions.lowLatencyRecording ? lowlatency::bypassTracks (song, armedInserts) : std::vector<char> {};
  1150. }
  1151. void AudioEngine::refreshLowLatency()
  1152. {
  1153. if (lowLatencyTracksNow() != publishedLowLatency)
  1154. publishSong();
  1155. }
  1156. int AudioEngine::lowLatencyBypassedLatency (int track, int slot) const noexcept
  1157. {
  1158. const auto& saved = lastPublishedShape.lowLatencySaved;
  1159. return isSlotLowLatencyBypassed (track, slot) && (std::size_t) track < saved.size() && (std::size_t) slot < saved[(std::size_t) track].size()
  1160. ? saved[(std::size_t) track][(std::size_t) slot]
  1161. : 0;
  1162. }
  1163. int AudioEngine::lowLatencyBypassedCount() const noexcept
  1164. {
  1165. int count = 0;
  1166. for (const auto mask : lastPublishedShape.lowLatencySlots)
  1167. for (auto m = (unsigned) mask; m != 0; m &= m - 1)
  1168. ++count;
  1169. return count;
  1170. }
  1171. void AudioEngine::setRecordOptions (const RecordOptions& options)
  1172. {
  1173. recordOptions = options;
  1174. recordOptions.countInBars = juce::jlimit (0, countin::maxBars, options.countInBars);
  1175. recordOptions.countInLength = countin::lengthFor (recordOptions.countInBars, options.countInLength); // (issue #152)
  1176. recordOptions.preRollBars = juce::jlimit (0, 8, options.preRollBars);
  1177. recordOptions.postRollBars = juce::jlimit (0, 8, options.postRollBars);
  1178. recordOptions.catchWindow = juce::jlimit<std::int64_t> (0, ppq, options.catchWindow);
  1179. compensatePlayed.store (options.compensateOutput);
  1180. notesStartWait.store (! options.waitRespectFilter || options.recordNotes);
  1181. updateLinearSong();
  1182. refreshLowLatency(); // (round 190aq: the option switched while an insert is live)
  1183. sendChangeMessage();
  1184. }
  1185. void AudioEngine::startPlayback()
  1186. {
  1187. if (! transport.recording.load())
  1188. {
  1189. // FL's Wait for input with "Only when recording" off (round 190ld): Play alone waits for the first note too
  1190. if (recordOptions.waitForInput && ! recordOptions.waitOnlyWhenRecording && ! transport.playing.load())
  1191. {
  1192. preparePlay();
  1193. waitingForInput.store (true);
  1194. sendChangeMessage();
  1195. return;
  1196. }
  1197. play();
  1198. return;
  1199. }
  1200. // pre-roll and punch (round 163): playback starts before the range the take keeps; post-roll stops it after
  1201. activePunch.reset();
  1202. punchStopAt = -1;
  1203. auto startAt = (std::int64_t) transport.positionTicks.load();
  1204. if (audioArmed && recordOptions.recordAudio)
  1205. {
  1206. const auto here = (std::int64_t) std::llround (transport.positionTicks.load());
  1207. const auto punching = recordOptions.punchLoopRegion && song.mode == PlayMode::song && song.hasLoop()
  1208. && (recordOptions.punchIn || recordOptions.punchOut);
  1209. const auto ends = recordloop::punchEnds (here, song.loopStart, song.loopEnd, punching, recordOptions.punchIn, recordOptions.punchOut,
  1210. std::numeric_limits<std::int64_t>::max() / 4); // (round 190lx: in / out each on its own)
  1211. const auto in = ends.in, out = ends.out;
  1212. // (seconds: the ADR window's pre-roll, round 174d)
  1213. auto secondsBack = [this] (std::int64_t at, double seconds) {
  1214. const auto from = std::max (0.0, song.secondsForTicks (at) - seconds);
  1215. return std::max<std::int64_t> (0, at - (std::int64_t) std::llround (videotrack::ticksForSeconds (song, from)));
  1216. };
  1217. auto secondsOn = [this] (std::int64_t at, double seconds) {
  1218. return std::max<std::int64_t> (0, (std::int64_t) std::llround (videotrack::ticksForSeconds (song, song.secondsForTicks (at) + seconds)) - at);
  1219. };
  1220. const auto pre = recordOptions.preRollSeconds >= 0.0 ? secondsBack (in, recordOptions.preRollSeconds)
  1221. : recordOptions.preRollBars > 0 ? countInLength (song, recordOptions.preRollBars, std::max<std::int64_t> (0, in - 1)) : 0;
  1222. if (punching || pre > 0)
  1223. {
  1224. activePunch = PunchRange { in, out };
  1225. if (ends.stopsAtOut)
  1226. punchStopAt = out + (recordOptions.postRollSeconds >= 0.0 ? secondsOn (out, recordOptions.postRollSeconds)
  1227. : recordOptions.postRollBars > 0 ? countInLength (song, recordOptions.postRollBars, out) : 0);
  1228. startAt = std::max<std::int64_t> (0, in - pre);
  1229. transport.seekRequest.store ((double) startAt);
  1230. }
  1231. updateLinearSong();
  1232. }
  1233. if (recordOptions.waitForInput)
  1234. {
  1235. waitingForInput.store (true);
  1236. sendChangeMessage();
  1237. return;
  1238. }
  1239. // (round 190gl: as the reference DAW, no count-in while Link is on: the start waits for the session's phase instead)
  1240. if (recordOptions.countInBars > 0 && ! abletonLink.isEnabled())
  1241. {
  1242. // the notes played during the count-in belong to this take (round 170d)
  1243. const auto length = countInLength (song, recordOptions.countInBars, startAt);
  1244. takeCatch = {};
  1245. takeCatch.start = startAt;
  1246. takeCatch.window = recordOptions.catchWindow;
  1247. takeCatch.songMode = song.mode == PlayMode::song;
  1248. if (! song.patterns.empty())
  1249. takeCatch.wrap = countInWrap (length, song.patterns[(std::size_t) juce::jlimit (0, (int) song.patterns.size() - 1, song.currentPattern)]
  1250. .effectiveLength (song.meter()));
  1251. transport.countIn.store ((double) length);
  1252. sendChangeMessage();
  1253. return;
  1254. }
  1255. play();
  1256. }
  1257. void AudioEngine::startOnInput() noexcept
  1258. {
  1259. if (! notesStartWait.load (std::memory_order_relaxed)) // (round 190ld: FL's "Respect recording filter")
  1260. return;
  1261. if (waitingForInput.exchange (false))
  1262. transport.playing.store (true);
  1263. }
  1264. void AudioEngine::setInsertArmed (int track, bool armed)
  1265. {
  1266. const auto it = std::find (armedInserts.begin(), armedInserts.end(), track);
  1267. const auto wasArmed = it != armedInserts.end();
  1268. if (armed == wasArmed || track <= 0)
  1269. return;
  1270. if (armed && isInsertRecordSafe (track)) // record safe (round 163): never armed by accident
  1271. {
  1272. notify (InputIssue::recordSafe, track);
  1273. return;
  1274. }
  1275. if (armed)
  1276. armedInserts.push_back (track);
  1277. else
  1278. armedInserts.erase (it);
  1279. if (track < maxMixerTracks)
  1280. liveInput.armed[(std::size_t) track].store (armed);
  1281. if (armed && ! audioArmed)
  1282. setAudioRecordingArmed (true);
  1283. else if (! armed && armedInserts.empty() && audioArmed)
  1284. setAudioRecordingArmed (false);
  1285. refreshLowLatency(); // (round 190aq: "Low latency while recording" follows the arm switches)
  1286. sendChangeMessage();
  1287. }
  1288. bool AudioEngine::isInsertArmed (int track) const noexcept
  1289. {
  1290. return std::find (armedInserts.begin(), armedInserts.end(), track) != armedInserts.end();
  1291. }
  1292. void AudioEngine::rewind() noexcept { transport.rewindRequested.store (true); }
  1293. void AudioEngine::jumpTo (double tick) noexcept
  1294. {
  1295. tick = juce::jmax (0.0, tick);
  1296. const auto quantize = quantizeSongJumps.load();
  1297. if (! transport.playing.load() || quantize <= 0 || song.mode != PlayMode::song)
  1298. {
  1299. seek (tick);
  1300. return;
  1301. }
  1302. // the jump waits for the next beat / bar(s) (FL's "Quantize song jumps"); the audio thread makes it there
  1303. const auto at = (double) markers::quantizedJumpTick (song, transport.positionTicks.load(), quantize);
  1304. transport.pendingJumpTo.store (tick);
  1305. transport.pendingJumpAt.store (at);
  1306. }
  1307. void AudioEngine::jumpToMarker (int index) noexcept
  1308. {
  1309. const auto& list = song.markers();
  1310. if (index < 0 || index >= (int) list.size())
  1311. return;
  1312. if (song.mode != PlayMode::song)
  1313. editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  1314. jumpTo ((double) list[(std::size_t) index].tick);
  1315. }
  1316. void AudioEngine::jumpToNextMarker (bool forward) noexcept
  1317. {
  1318. // from where the song is (or where a quantized jump is going)
  1319. const auto pending = transport.pendingJumpAt.load() >= 0.0 ? transport.pendingJumpTo.load() : -1.0;
  1320. const auto here = pending >= 0.0 ? pending : transport.positionTicks.load();
  1321. const auto& list = song.markers();
  1322. int best = -1;
  1323. for (int i = 0; i < (int) list.size(); ++i)
  1324. {
  1325. const auto t = (double) list[(std::size_t) i].tick;
  1326. if (forward ? t > here + 0.5 : t < here - 0.5)
  1327. {
  1328. if (forward)
  1329. {
  1330. best = i;
  1331. break;
  1332. }
  1333. best = i;
  1334. }
  1335. }
  1336. if (best >= 0)
  1337. jumpToMarker (best);
  1338. else if (! forward)
  1339. jumpTo (0.0);
  1340. }
  1341. void AudioEngine::seek (double ticks) noexcept
  1342. {
  1343. transport.pendingJumpAt.store (-1.0); // a direct seek replaces a quantized jump still waiting
  1344. if (transport.playing.load())
  1345. resetToInitialValues(); // a jump while the song plays (FL sets the position the same way)
  1346. transport.seekRequest.store (juce::jmax (0.0, ticks));
  1347. }
  1348. void AudioEngine::copyScope (float* destination, int count) const noexcept
  1349. {
  1350. count = juce::jmin (count, scopeSize);
  1351. auto r = (scopeWrite.load (std::memory_order_acquire) - count + scopeSize) % scopeSize;
  1352. for (int i = 0; i < count; ++i)
  1353. {
  1354. destination[i] = scope[(std::size_t) r].load (std::memory_order_relaxed);
  1355. r = (r + 1) % scopeSize;
  1356. }
  1357. }
  1358. void AudioEngine::copyScopeSide (float* destination, int count) const noexcept
  1359. {
  1360. count = juce::jmin (count, scopeSize);
  1361. auto r = (scopeWrite.load (std::memory_order_acquire) - count + scopeSize) % scopeSize;
  1362. for (int i = 0; i < count; ++i)
  1363. {
  1364. destination[i] = scopeSide[(std::size_t) r].load (std::memory_order_relaxed);
  1365. r = (r + 1) % scopeSize;
  1366. }
  1367. }
  1368. void AudioEngine::previewFile (const juce::File& file)
  1369. {
  1370. previewFile (file, 0.0, true);
  1371. }
  1372. void AudioEngine::setPreviewRange (const SampleData* sample)
  1373. {
  1374. if (preview == nullptr)
  1375. return;
  1376. if (sample == nullptr || (previewFull && previewStartFraction <= 0.0))
  1377. {
  1378. preview->setBrowserRange (0, 0, false);
  1379. return;
  1380. }
  1381. const auto r = browserpreview::range ((std::int64_t) sample->frames(), sample->sampleRate, previewStartFraction, previewFull);
  1382. preview->setBrowserRange (r.start, r.capped ? r.end : 0, r.capped);
  1383. }
  1384. void AudioEngine::previewFile (const juce::File& file, double startFraction, bool full)
  1385. {
  1386. previewStartFraction = startFraction; // (round 190iz: kept for the in-time preview prepared on the worker)
  1387. previewFull = full || fullSamplePreview;
  1388. ++previewSerial; // (a preview still being prepared is dropped)
  1389. previewTiming = {};
  1390. if (preview == nullptr)
  1391. return;
  1392. auto sample = file.existsAsFile() ? samples.load (file.getFullPathName()) : nullptr;
  1393. if (! previewInTime || sample == nullptr)
  1394. {
  1395. setPreviewRange (sample.get());
  1396. preview->playBrowser (std::move (sample)); // FL's preview: the file as it is, at once
  1397. return;
  1398. }
  1399. // "Preview in time" (round 190aq, core/PreviewTempo.h): the file's tempo from its ACID beats or its name (cheap,
  1400. // here), else from LYNX's tempo detection (on the worker); a file that can have none plays as it always did
  1401. const auto path = file.getFullPathName();
  1402. const auto name = file.getFileName().toStdString();
  1403. const auto external = transport.overrideBpm(); // (an external clock's or the Link session's tempo)
  1404. const auto projectBpm = external > 0.0 ? external : transport.bpm.load (std::memory_order_relaxed);
  1405. auto found = previewtempo::quick (*sample, name);
  1406. auto known = found.bpm > 0.0;
  1407. if (! known)
  1408. if (const auto it = previewTempos.find (path); it != previewTempos.end())
  1409. {
  1410. found = it->second;
  1411. known = true;
  1412. }
  1413. if (! known && ! previewtempo::worthDetecting (*sample))
  1414. {
  1415. setPreviewRange (sample.get());
  1416. preview->playBrowser (std::move (sample));
  1417. return;
  1418. }
  1419. PreviewTiming timing;
  1420. timing.path = path;
  1421. timing.projectBpm = projectBpm;
  1422. timing.fileBpm = found.bpm;
  1423. timing.source = found.source;
  1424. timing.ratio = previewtempo::stretchRatio (found.bpm, projectBpm);
  1425. timing.inTime = found.bpm > 0.0;
  1426. if (known)
  1427. {
  1428. if (found.bpm <= 0.0) // (analysed before: no tempo)
  1429. {
  1430. setPreviewRange (sample.get());
  1431. preview->playBrowser (std::move (sample));
  1432. return;
  1433. }
  1434. if (timing.ratio == 1.0) // already at the project's tempo: only the start waits for the beat
  1435. {
  1436. startPreviewInTime (path, std::move (sample), timing);
  1437. return;
  1438. }
  1439. for (const auto& s : previewStretches)
  1440. if (s.path == path && s.ratio == timing.ratio && s.sample != nullptr)
  1441. {
  1442. startPreviewInTime (path, s.sample, timing);
  1443. return;
  1444. }
  1445. }
  1446. // the tempo detection and / or the stretch, off the message thread; what was playing stops now
  1447. preview->playBrowser (nullptr);
  1448. timing.pending = true;
  1449. previewTiming = timing;
  1450. const auto started = juce::Time::getMillisecondCounterHiRes();
  1451. previewJobs.post ([this, alive = previewAlive, serial = previewSerial, path, sample, timing, known, started]() mutable {
  1452. if (! alive->load())
  1453. return;
  1454. auto found = previewtempo::Found { timing.fileBpm, timing.source };
  1455. if (! known)
  1456. found = previewtempo::detect (*sample);
  1457. timing.fileBpm = found.bpm;
  1458. timing.source = found.source;
  1459. timing.inTime = found.bpm > 0.0;
  1460. timing.ratio = previewtempo::stretchRatio (found.bpm, timing.projectBpm);
  1461. std::shared_ptr<const SampleData> out = sample;
  1462. if (timing.inTime && timing.ratio != 1.0)
  1463. if (auto stretched = timeStretch (*sample, timing.ratio, StretchMethod::general); stretched != nullptr && stretched->frames() > 1)
  1464. out = std::move (stretched);
  1465. timing.prepareMs = juce::Time::getMillisecondCounterHiRes() - started;
  1466. {
  1467. const std::lock_guard<std::mutex> lock (previewResultLock);
  1468. previewResults.push_back ({ serial, path, sample, out, timing, found, ! known });
  1469. }
  1470. juce::MessageManager::callAsync ([this, alive] {
  1471. if (alive->load())
  1472. takePreviewResults();
  1473. });
  1474. });
  1475. }
  1476. // The prepared previews, on the message thread: the tempo and the stretch are kept for the next click on the same
  1477. // file, and the newest one plays unless another file was clicked meanwhile.
  1478. void AudioEngine::takePreviewResults()
  1479. {
  1480. std::vector<PreviewResult> results;
  1481. {
  1482. const std::lock_guard<std::mutex> lock (previewResultLock);
  1483. results.swap (previewResults);
  1484. }
  1485. for (auto& r : results)
  1486. {
  1487. if (r.detected)
  1488. {
  1489. if (previewTempos.size() > 512)
  1490. previewTempos.clear();
  1491. previewTempos[r.path] = r.found;
  1492. }
  1493. if (r.out != r.sample)
  1494. {
  1495. if (previewStretches.size() >= 6)
  1496. previewStretches.erase (previewStretches.begin());
  1497. previewStretches.push_back ({ r.path, r.timing.ratio, r.out });
  1498. }
  1499. if (r.serial != previewSerial || preview == nullptr)
  1500. continue; // another file was clicked meanwhile (or the preview was stopped)
  1501. lastPreviewPrepareMs = r.timing.prepareMs;
  1502. if (! r.timing.inTime)
  1503. {
  1504. previewTiming = {};
  1505. setPreviewRange (r.out.get());
  1506. preview->playBrowser (r.out); // no tempo found: as it is
  1507. continue;
  1508. }
  1509. startPreviewInTime (r.path, r.out, r.timing);
  1510. }
  1511. }
  1512. void AudioEngine::finishPreviewJobs()
  1513. {
  1514. previewJobs.waitIdle();
  1515. takePreviewResults();
  1516. }
  1517. void AudioEngine::startPreviewInTime (const juce::String& path, std::shared_ptr<const SampleData> sample, const PreviewTiming& timing)
  1518. {
  1519. previewTiming = timing;
  1520. previewTiming.path = path;
  1521. previewTiming.pending = false;
  1522. previewTiming.inTime = true;
  1523. previewTiming.frames = sample != nullptr ? sample->frames() : 0;
  1524. previewHandedAtMs = juce::Time::getMillisecondCounterHiRes();
  1525. preview->setSyncLatency (getLatencySamples());
  1526. setPreviewRange (sample.get());
  1527. preview->playBrowser (std::move (sample), 0.8f, true);
  1528. }
  1529. int AudioEngine::getPreviewBeatStarts() const noexcept { return preview != nullptr ? preview->beatStarts() : 0; }
  1530. double AudioEngine::getPreviewInTimeProgress() const noexcept
  1531. {
  1532. if (previewTiming.pending)
  1533. return 0.0;
  1534. if (! previewTiming.inTime || preview == nullptr)
  1535. return -1.0;
  1536. const auto position = preview->getPlayPosition();
  1537. if (position < 0.0) // (the audio thread takes the sample at its next block)
  1538. return juce::Time::getMillisecondCounterHiRes() - previewHandedAtMs < 200.0 ? 0.0 : -1.0;
  1539. return previewTiming.frames > 1 ? juce::jlimit (0.0, 1.0, position / (double) (previewTiming.frames - 1)) : 0.0;
  1540. }
  1541. void AudioEngine::setInputScale (int scale, int root) noexcept
  1542. {
  1543. inputScaleRoot.store (root);
  1544. inputScale.store (scale);
  1545. }
  1546. int AudioEngine::snapInputKey (int key) const noexcept
  1547. {
  1548. const auto scale = inputScale.load();
  1549. return scale > 0 ? notetools::snapToScale (key, inputScaleRoot.load(), scale) : key;
  1550. }
  1551. void AudioEngine::previewSample (std::shared_ptr<const SampleData> sample, bool loop, float gain, bool audioEditor)
  1552. {
  1553. if (preview != nullptr)
  1554. preview->play (std::move (sample), loop, gain, audioEditor);
  1555. }
  1556. void AudioEngine::previewScrub (std::shared_ptr<const SampleData> sample, std::int64_t startFrame)
  1557. {
  1558. if (preview != nullptr)
  1559. preview->playScrub (std::move (sample), startFrame, 1.0f);
  1560. }
  1561. void AudioEngine::setPreviewScrubSpeed (double speed) noexcept
  1562. {
  1563. if (preview != nullptr)
  1564. preview->setScrubSpeed (speed);
  1565. }
  1566. void AudioEngine::setEditorVolume (double volume) noexcept
  1567. {
  1568. editorVolume = controls::clampUtilityVolume (volume);
  1569. if (preview != nullptr)
  1570. preview->setEditorVolume (controls::previewGain (editorVolume));
  1571. }
  1572. void AudioEngine::setPreviewVolume (double volume) noexcept
  1573. {
  1574. previewVolume = controls::clampUtilityVolume (volume);
  1575. if (preview != nullptr)
  1576. preview->setVolume (controls::previewGain (previewVolume));
  1577. }
  1578. double AudioEngine::getPreviewPosition() const noexcept
  1579. {
  1580. return preview != nullptr ? preview->getPlayPosition() : -1.0;
  1581. }
  1582. void AudioEngine::markHeldKey (int midiChannel, int key, bool on) noexcept
  1583. {
  1584. if (key < 0 || key > 127 || midiChannel < 0 || midiChannel > 15)
  1585. return;
  1586. if (on) // round 190ee: Edison's "Last hit" (the region menu's Trigger note)
  1587. lastHitKey.store (key, std::memory_order_relaxed);
  1588. auto& count = heldKeyCount[midiChannel][(std::size_t) key];
  1589. auto before = count.load();
  1590. std::uint8_t after = 0;
  1591. do
  1592. after = on ? (std::uint8_t) std::min (255, before + 1) : (std::uint8_t) (before > 0 ? before - 1 : 0);
  1593. while (! count.compare_exchange_weak (before, after));
  1594. const auto bit = std::uint64_t { 1 } << (key & 63);
  1595. if (after > 0)
  1596. heldKeyBits[midiChannel][key >> 6].fetch_or (bit);
  1597. else
  1598. heldKeyBits[midiChannel][key >> 6].fetch_and (~bit);
  1599. }
  1600. void AudioEngine::markLiveNote (int key, int velocity127, bool on) noexcept
  1601. {
  1602. if (key < 0 || key > 127)
  1603. return;
  1604. auto& v = liveNoteVelocities[(std::size_t) key];
  1605. if (on)
  1606. v.store ((std::uint8_t) std::clamp (velocity127, 0, 127), std::memory_order_relaxed);
  1607. liveNote.store (livenote::pack (liveNote.load (std::memory_order_relaxed), key, (int) v.load (std::memory_order_relaxed), on), std::memory_order_relaxed);
  1608. }
  1609. void AudioEngine::logPlayedNote (int channel, int key, float velocity, bool on, double tick, bool recorded)
  1610. {
  1611. if (channel < 0)
  1612. return;
  1613. const auto ms = juce::Time::getMillisecondCounterHiRes();
  1614. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1615. if (on)
  1616. scoreLog.noteOn (ms, channel, key, velocity, tick, recorded);
  1617. else
  1618. scoreLog.noteOff (ms, channel, key);
  1619. if (stepEditOn.load (std::memory_order_relaxed) && stepEditQueue.size() < 512)
  1620. stepEditQueue.push_back ({ channel, key, velocity, on });
  1621. }
  1622. void AudioEngine::logPlayedNoteForTest (double ms, int channel, int key, float velocity, bool on, double tick)
  1623. {
  1624. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1625. if (on)
  1626. scoreLog.noteOn (ms, channel, key, velocity, tick, false);
  1627. else
  1628. scoreLog.noteOff (ms, channel, key);
  1629. }
  1630. void AudioEngine::setStepEdit (bool on) noexcept
  1631. {
  1632. stepEditOn.store (on, std::memory_order_relaxed);
  1633. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1634. stepEditQueue.clear();
  1635. }
  1636. std::vector<stepedit::Played> AudioEngine::takeStepEditNotes()
  1637. {
  1638. std::vector<stepedit::Played> out;
  1639. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1640. out.swap (stepEditQueue);
  1641. return out;
  1642. }
  1643. std::vector<scorelog::Entry> AudioEngine::scoreLogSnapshot() const
  1644. {
  1645. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1646. return scoreLog.snapshot();
  1647. }
  1648. bool AudioEngine::scoreLogEmpty() const
  1649. {
  1650. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1651. return scoreLog.size() == 0;
  1652. }
  1653. void AudioEngine::clearScoreLog()
  1654. {
  1655. const juce::SpinLock::ScopedLockType lock (scoreLogLock);
  1656. scoreLog.clear();
  1657. }
  1658. NoteMask AudioEngine::soundingKeys (int channel) const noexcept
  1659. {
  1660. return rackProcessor != nullptr ? rackProcessor->soundingKeys (channel) : NoteMask {};
  1661. }
  1662. std::uint32_t AudioEngine::noteStrikes (int channel) const noexcept
  1663. {
  1664. return rackProcessor != nullptr ? rackProcessor->noteStrikes (channel) : 0u;
  1665. }
  1666. std::vector<int> AudioEngine::heldInputKeys() const
  1667. {
  1668. std::vector<int> keys;
  1669. std::uint64_t all[2] {};
  1670. for (const auto& channel : heldKeyBits)
  1671. for (int word = 0; word < 2; ++word)
  1672. all[word] |= channel[word].load();
  1673. for (int word = 0; word < 2; ++word)
  1674. for (int b = 0; b < 64; ++b)
  1675. if ((all[word] >> b & 1u) != 0)
  1676. keys.push_back (word * 64 + b);
  1677. return keys;
  1678. }
  1679. std::array<std::uint64_t, 2> AudioEngine::heldInputKeyBits (int midiChannel) const noexcept
  1680. {
  1681. if (midiChannel < 0 || midiChannel > 15)
  1682. return {};
  1683. return { heldKeyBits[midiChannel][0].load (std::memory_order_relaxed), heldKeyBits[midiChannel][1].load (std::memory_order_relaxed) };
  1684. }
  1685. RollingAudioLog& AudioEngine::getRollingLog() noexcept
  1686. {
  1687. return meters.rollingLog;
  1688. }
  1689. void AudioEngine::sendLiveNote (int channel, int key, float velocity, bool on, bool record)
  1690. {
  1691. if (record) // played notes (the PC keyboard) follow the scale snap; previews don't
  1692. {
  1693. markHeldKey (0, key, on); // (FL sends the typing keyboard as MIDI channel 1)
  1694. markLiveNote (key, juce::roundToInt (velocity * 127.0f), on); // (the hint bar's "Note on", round 190ih)
  1695. // the note-off stops the key its note-on started, even if the snap changed in between
  1696. const auto requested = key;
  1697. if (on)
  1698. {
  1699. key = snapInputKey (key);
  1700. playedKeys.on (channel, requested, key);
  1701. startOnInput();
  1702. }
  1703. else
  1704. key = playedKeys.off (channel, requested, snapInputKey (key));
  1705. }
  1706. NoteEvent e;
  1707. e.type = on ? NoteEvent::Type::on : NoteEvent::Type::off;
  1708. e.channel = channel;
  1709. e.key = key;
  1710. e.velocity = velocity;
  1711. liveEvents.push (e);
  1712. // (round 170d: recorded during the count-in too, at the audio clock's position)
  1713. const auto now = juce::Time::getMillisecondCounterHiRes();
  1714. const auto taking = record && transport.recording.load() && (transport.playing.load() || isCountingIn());
  1715. if (record)
  1716. logPlayedNote (channel, key, velocity, on, transport.playing.load() ? recordTickFor (now) : -1.0, taking);
  1717. if (taking)
  1718. uiRecorded.push_back ({ recordTickFor (now), channel, key, velocity, on });
  1719. if (record && slotTaking.load (std::memory_order_relaxed)) // a slot of the clip grid records (round 190bv)
  1720. uiSlotRecorded.push_back ({ recordTickFor (now), channel, key, velocity, on });
  1721. }
  1722. void AudioEngine::sendGuiNote (int channel, int key, float velocity, bool on)
  1723. {
  1724. key = juce::jlimit (0, 127, key);
  1725. if (on)
  1726. startOnInput(); // ("Wait for input": a pad hit starts the take, as a played key does)
  1727. markLiveNote (key, juce::roundToInt (velocity * 127.0f), on);
  1728. NoteEvent e;
  1729. e.type = on ? NoteEvent::Type::on : NoteEvent::Type::off;
  1730. e.channel = channel;
  1731. e.key = key;
  1732. e.velocity = velocity;
  1733. liveEvents.push (e);
  1734. const auto now = juce::Time::getMillisecondCounterHiRes();
  1735. const auto taking = transport.recording.load() && (transport.playing.load() || isCountingIn());
  1736. logPlayedNote (channel, key, velocity, on, transport.playing.load() ? recordTickFor (now) : -1.0, taking);
  1737. if (taking)
  1738. uiRecorded.push_back ({ recordTickFor (now), channel, key, velocity, on });
  1739. if (slotTaking.load (std::memory_order_relaxed))
  1740. uiSlotRecorded.push_back ({ recordTickFor (now), channel, key, velocity, on });
  1741. }
  1742. void AudioEngine::panic()
  1743. {
  1744. NoteEvent e;
  1745. e.type = NoteEvent::Type::choke;
  1746. e.channel = -1; // every channel
  1747. liveEvents.push (e);
  1748. midiSync.requestPortNotesOff(); // (round 190jl: the hardware MIDI outputs' notes end too)
  1749. for (auto& channel : heldKeyCount)
  1750. for (auto& c : channel)
  1751. c.store (0);
  1752. for (auto& channel : heldKeyBits)
  1753. for (auto& w : channel)
  1754. w.store (0);
  1755. }
  1756. void AudioEngine::stopSound()
  1757. {
  1758. panic();
  1759. midiSync.requestTransportNotesOff(); // (FL's "Stop sound": CC 123 to the "Send all notes off" outputs; REA midiout190jl, 0xf1de20)
  1760. NoteEvent e;
  1761. e.type = NoteEvent::Type::choke;
  1762. e.channel = RackRenderer::stopSoundChannel; // and every effect / plugin reset
  1763. liveEvents.push (e);
  1764. }
  1765. double AudioEngine::songPlayheadTicks() const noexcept
  1766. {
  1767. const auto tick = juce::jmax (0.0, transport.positionTicks.load (std::memory_order_relaxed));
  1768. if (song.loopPlays() || liveInput.linearSong.load (std::memory_order_relaxed))
  1769. return tick;
  1770. return std::fmod (tick, (double) juce::jmax<std::int64_t> (1, song.songLength()));
  1771. }
  1772. double AudioEngine::playheadAdvanceTicks() const noexcept
  1773. {
  1774. if (! transport.playing.load (std::memory_order_relaxed) || ! clockRunning.load (std::memory_order_relaxed))
  1775. return 0.0;
  1776. const auto since = juce::Time::getMillisecondCounterHiRes() - blockTimeMs.load (std::memory_order_acquire);
  1777. return juce::jlimit (0.0, juce::jmax (0.0, blockDurationMs.load (std::memory_order_relaxed)), since) * clockTicksPerMs.load (std::memory_order_relaxed);
  1778. }
  1779. LiveClock AudioEngine::liveClock() const noexcept
  1780. {
  1781. LiveClock c;
  1782. c.timeMs = blockTimeMs.load (std::memory_order_acquire);
  1783. c.tick = clockTick.load (std::memory_order_relaxed);
  1784. c.ticksPerMs = clockTicksPerMs.load (std::memory_order_relaxed);
  1785. c.running = clockRunning.load (std::memory_order_relaxed);
  1786. return c;
  1787. }
  1788. double AudioEngine::heardLatencyMs() const noexcept
  1789. {
  1790. const auto rate = transport.sampleRate.load (std::memory_order_relaxed);
  1791. return outputCompensationMs.load (std::memory_order_relaxed)
  1792. + (rate > 0.0 ? 1000.0 * std::max (0, masterPdcSamples.load (std::memory_order_relaxed)) / rate : 0.0);
  1793. }
  1794. double AudioEngine::recordTickFor (double eventMs) const noexcept
  1795. {
  1796. const auto clock = liveClock();
  1797. // (stopped, or no callback since Play / the count-in started: the transport's own position, as before)
  1798. if (! clock.running)
  1799. return transport.positionTicks.load (std::memory_order_relaxed)
  1800. - (transport.playing.load (std::memory_order_relaxed) ? 0.0 : transport.countIn.load (std::memory_order_relaxed));
  1801. // (round 190hq: the Master's delay compensation too — a note is recorded where the song was heard)
  1802. return liveTickAt (clock, eventMs, compensatePlayed.load (std::memory_order_relaxed) ? heardLatencyMs() : 0.0);
  1803. }
  1804. CaptureResult AudioEngine::captureMidi()
  1805. {
  1806. CaptureOptions o;
  1807. o.afterMs = lastCaptureMs;
  1808. o.nowMs = juce::Time::getMillisecondCounterHiRes();
  1809. o.gapMs = 2.0 * (double) song.barTicks() / ppq * 60000.0 / juce::jmax (1.0, song.bpm); // two bars of silence end a phrase
  1810. o.playhead = (std::int64_t) std::llround (songPlayheadTicks());
  1811. o.mode = recordOptions.mode;
  1812. o.quantize.grid = recordOptions.quantise;
  1813. o.quantize.starts = recordOptions.quantiseStarts;
  1814. o.quantize.end = recordOptions.noteEnd;
  1815. o.quantize.stepSequencer = recordOptions.toStepSequencer;
  1816. o.placeClip = recordOptions.placeSongClip;
  1817. const auto log = scoreLogSnapshot();
  1818. if (capturePhrase (song, log, o).empty()) // (nothing to capture: no undo step)
  1819. return {};
  1820. CaptureResult result;
  1821. editSong ([&] (Song& s) { result = lynx::captureMidi (s, log, o); });
  1822. if (result.newestMs > lastCaptureMs)
  1823. lastCaptureMs = result.newestMs;
  1824. return result;
  1825. }
  1826. CaptureResult AudioEngine::captureMidiToSlot (int track, int scene, int& placed, bool& into)
  1827. {
  1828. placed = -1;
  1829. into = false;
  1830. CaptureOptions o;
  1831. o.afterMs = lastCaptureMs;
  1832. o.nowMs = juce::Time::getMillisecondCounterHiRes();
  1833. o.gapMs = 2.0 * (double) song.barTicks() / ppq * 60000.0 / juce::jmax (1.0, song.bpm);
  1834. const auto log = scoreLogSnapshot();
  1835. const auto phrase = capturePhrase (song, log, o);
  1836. if (phrase.empty() || track < 0 || track >= launcher::maxTracks)
  1837. return {};
  1838. CaptureResult result;
  1839. result.played = phrase.front().startTick >= 0.0;
  1840. for (const auto& e : phrase)
  1841. result.newestMs = juce::jmax (result.newestMs, e.startMs);
  1842. const auto channel = detailchain::forTrack (song, track).channel;
  1843. const auto running = transport.playing.load();
  1844. // round 190em: into the clip the track plays (Live writes there, no new clip)
  1845. const auto playingRow = clipLauncher != nullptr ? clipLauncher->tracks[(std::size_t) track].playing.load (std::memory_order_relaxed) : -1;
  1846. if (running && result.played && playingRow >= 0 && song.clipGrid)
  1847. if (const auto* clip = launcher::clipAt (*song.clipGrid, track, playingRow); clip != nullptr && clip->kind == ClipKind::pattern)
  1848. {
  1849. const auto shift = clipLauncher->clockMinusSong.load (std::memory_order_relaxed)
  1850. - clipLauncher->tracks[(std::size_t) track].anchor.load (std::memory_order_relaxed);
  1851. auto notes = session::clipTimeNotes (phrase, o.nowMs, song.bpm, shift);
  1852. session::setNotesChannel (notes, channel);
  1853. result.notes = (int) notes.size();
  1854. auto ok = false;
  1855. editSong ([&] (Song& s) { ok = session::captureIntoClip (s, track, playingRow, notes); });
  1856. if (ok)
  1857. {
  1858. placed = playingRow;
  1859. into = true;
  1860. if (result.newestMs > lastCaptureMs)
  1861. lastCaptureMs = result.newestMs;
  1862. return result;
  1863. }
  1864. }
  1865. // a new clip; played while stopped, the tempo comes from the phrase
  1866. const auto bpm = running ? song.bpm : session::phraseTempo (phrase, song.bpm);
  1867. std::int64_t length = 0;
  1868. auto notes = session::phraseNotes (phrase, o.nowMs, bpm, song.meter(), length);
  1869. session::setNotesChannel (notes, channel);
  1870. result.notes = (int) notes.size();
  1871. const auto row = session::captureSlot (song, track, scene);
  1872. editSong ([&] (Song& s) {
  1873. if (! running)
  1874. s.bpm = bpm;
  1875. if (session::placeRecordedPattern (s, track, row, std::move (notes), length, {}) >= 0)
  1876. {
  1877. placed = row;
  1878. if (auto* slot = launcher::settingsAt (*s.clipGrid, track, row))
  1879. slot->blankName = true; // (Live's captured clip has no name; the pattern keeps LYNX's default one)
  1880. }
  1881. });
  1882. if (placed < 0)
  1883. return {};
  1884. launcherCommand ({ launcher::Command::Type::launch, track, row }); // (launched at once; a stopped transport starts)
  1885. if (result.newestMs > lastCaptureMs)
  1886. lastCaptureMs = result.newestMs;
  1887. return result;
  1888. }
  1889. double AudioEngine::estimatedPositionNow() const noexcept
  1890. {
  1891. // the position only moves block by block; interpolate by the time since the last block
  1892. auto tick = transport.positionTicks.load (std::memory_order_relaxed);
  1893. if (transport.playing.load (std::memory_order_relaxed))
  1894. {
  1895. const auto elapsedMs = juce::jlimit (0.0, 100.0, juce::Time::getMillisecondCounterHiRes() - blockTimeMs.load());
  1896. tick += elapsedMs * 0.001 * transport.sampleRate.load() * transport.ticksPerSample();
  1897. }
  1898. return tick;
  1899. }
  1900. AudioEngine::LiveRecording AudioEngine::liveRecording() const
  1901. {
  1902. LiveRecording live;
  1903. if (! isLiveRecording())
  1904. return live;
  1905. live.punch = activePunch;
  1906. // the note take
  1907. if (recorder.isActive() && song.currentPattern >= 0 && song.currentPattern < (int) song.patterns.size())
  1908. {
  1909. const auto now = transport.playing.load() ? estimatedPositionNow() : lastPlayingTick;
  1910. auto preview = recorder.preview (song, now);
  1911. live.notes = true;
  1912. live.pattern = song.currentPattern;
  1913. live.held = std::move (preview.notes);
  1914. if (song.mode == PlayMode::song && preview.origin >= 0)
  1915. {
  1916. // the take's clip (placed with its first finished note) or, before it, where it will be placed
  1917. const Clip* clip = nullptr;
  1918. for (const auto& c : song.playlist)
  1919. if (c.kind == ClipKind::pattern && c.pattern == song.currentPattern && c.start - c.offset == preview.origin
  1920. && (clip == nullptr || c.end() > clip->end()))
  1921. clip = &c;
  1922. live.track = clip != nullptr ? clip->track : patternClipTrack (song, song.barAt (preview.origin).tick);
  1923. live.from = clip != nullptr ? clip->start : preview.origin;
  1924. live.origin = preview.origin;
  1925. auto to = preview.reach;
  1926. for (const auto& n : live.held)
  1927. to = std::max (to, preview.origin + n.start + n.length);
  1928. if (! preview.fromClip && noteTakeLinear)
  1929. to = std::max (to, (std::int64_t) now); // (a linear take: the region follows the playhead)
  1930. live.to = std::max (live.from, to);
  1931. }
  1932. }
  1933. // the audio takes
  1934. const auto startTick = takeStartTick.load();
  1935. const auto frames = takeFrames.load();
  1936. if (! openTakes.empty() && startTick >= 0.0 && frames > 0)
  1937. {
  1938. const auto wraps = takeWrapCount.load();
  1939. const auto lastWrap = song.mode == PlayMode::song && song.loopPlays() && wraps > 0 ? (std::int64_t) takeWraps[(std::size_t) wraps - 1].load() : -1;
  1940. const auto span = liverec::audioSpan (startTick, frames, takeTicksPerSample, takeLatency, lastWrap, song.loopStart);
  1941. if (liveTakeTracks.size() != openTakes.size())
  1942. {
  1943. // the tracks takes::placeTakeClips will pick (each file's insert, one track each)
  1944. liveTakeTracks.clear();
  1945. const auto from = (std::int64_t) span.start, to = from + std::max<std::int64_t> (1, (std::int64_t) span.length);
  1946. for (const auto& take : openTakes)
  1947. {
  1948. auto track = takes::takeTrack (song, take->track > 0 ? take->track : -1, from, to);
  1949. for (const auto used : liveTakeTracks)
  1950. if (used >= track)
  1951. track = used + 1;
  1952. liveTakeTracks.push_back (track);
  1953. }
  1954. }
  1955. if (span.valid())
  1956. for (std::size_t k = 0; k < openTakes.size(); ++k)
  1957. {
  1958. LiveRecording::Audio a;
  1959. a.track = liveTakeTracks[k];
  1960. a.span = span;
  1961. a.peaks = openTakes[k]->peaks;
  1962. a.name = openTakes[k]->file.getFileNameWithoutExtension();
  1963. live.audio.push_back (std::move (a));
  1964. }
  1965. }
  1966. return live;
  1967. }
  1968. void AudioEngine::updateAudioRecording()
  1969. {
  1970. // (round 190bv: a slot of the clip grid recording audio runs the armed inserts' takes too)
  1971. const auto wantTake = audioArmed && recordOptions.recordAudio && (transport.recording.load() || slotAudioWanted);
  1972. const auto open = takeCount > 0;
  1973. // the files are ready before Play: the very first block gets recorded
  1974. if (wantTake && ! open && recordingError.isEmpty())
  1975. startAudioTake();
  1976. // post-roll over: playback stops (the take is closed below on the next tick)
  1977. if (open && punchStopAt >= 0 && transport.playing.load() && transport.positionTicks.load() >= (double) punchStopAt)
  1978. {
  1979. punchStopAt = -1;
  1980. stop();
  1981. }
  1982. // the first samples arrived: the journals that let a crash be recovered (round 163)
  1983. if (open && ! journalsWritten && takeStartTick.load() >= 0.0)
  1984. writeJournals();
  1985. // a file that could not be written (disk full, drive gone): say it once, the take stops there
  1986. for (auto& take : openTakes)
  1987. if (take->failed.load() && recordingError.isEmpty())
  1988. {
  1989. recordingError = take->writer.error().empty() ? juce::String ("could not write ") + take->file.getFullPathName()
  1990. : juce::String::fromUTF8 (take->writer.error().c_str()) + ": " + take->file.getFullPathName();
  1991. notify (InputIssue::failed, take->track, recordingError);
  1992. }
  1993. // playback stopped (or recording turned off) with something recorded: close the takes
  1994. if (open && (! wantTake || (! transport.playing.load() && takeFrames.load() > 0)))
  1995. finishAudioTake();
  1996. }
  1997. bool AudioEngine::Take::drain()
  1998. {
  1999. if (stream == nullptr || failed.load())
  2000. return false;
  2001. const auto n = 8192;
  2002. if (scratch.size() < (std::size_t) (2 * n))
  2003. scratch.resize ((std::size_t) (2 * n));
  2004. auto any = false;
  2005. for (;;)
  2006. {
  2007. float* out[] = { scratch.data(), scratch.data() + n };
  2008. const auto got = stream->pull (out, n);
  2009. if (got <= 0)
  2010. break;
  2011. any = true;
  2012. const float* in[] = { out[0], out[1] };
  2013. if (! writer.write (in, got))
  2014. {
  2015. failed.store (true);
  2016. break;
  2017. }
  2018. peaks->append (in, stream->channels(), got);
  2019. }
  2020. return any;
  2021. }
  2022. namespace
  2023. {
  2024. juce::File recordingSettingsFile() { return PluginHost::settingsFolder().getChildFile ("recording.txt"); }
  2025. juce::File inProgressFile() { return PluginHost::settingsFolder().getChildFile ("recordings-in-progress.txt"); }
  2026. AudioEngine::RecordingSettings loadRecordingSettings()
  2027. {
  2028. AudioEngine::RecordingSettings s;
  2029. for (const auto& raw : juce::StringArray::fromLines (recordingSettingsFile().loadFileAsString()))
  2030. {
  2031. const auto key = raw.upToFirstOccurrenceOf ("=", false, false).trim();
  2032. const auto value = raw.fromFirstOccurrenceOf ("=", false, false);
  2033. if (key == "format")
  2034. s.format = value.trim() == "float32" ? takes::SampleFormat::float32 : value.trim() == "pcm16" ? takes::SampleFormat::pcm16 : takes::SampleFormat::pcm24;
  2035. else if (key == "trackTakeNames")
  2036. s.trackTakeNames = value.getIntValue() != 0;
  2037. else if (key == "manualOffset")
  2038. s.manualOffset = juce::jlimit (-48000, 48000, value.getIntValue());
  2039. else if (key == "useMeasured")
  2040. s.useMeasured = value.getIntValue() != 0;
  2041. else if (key == "pingOutput")
  2042. s.pingOutput = juce::jlimit (0, 63, value.getIntValue());
  2043. else if (key == "pingInput")
  2044. s.pingInput = juce::jlimit (0, 63, value.getIntValue());
  2045. else if (key == "measured") // measured=<samples>\t<setup key>
  2046. s.measured[value.fromFirstOccurrenceOf ("\t", false, false).toStdString()] = value.upToFirstOccurrenceOf ("\t", false, false).getIntValue();
  2047. }
  2048. return s;
  2049. }
  2050. } // namespace
  2051. void AudioEngine::setRecordingSettings (const RecordingSettings& settings)
  2052. {
  2053. // round 190bj (issue B3): takes whose files are ready but empty (made when the previous take ended, the track still
  2054. // armed) take the new sample format too; one that has samples keeps its own
  2055. if (settings.format != recordingSettings.format)
  2056. for (auto& take : openTakes)
  2057. {
  2058. const juce::ScopedLock lock (take->drainMutex);
  2059. take->writer.changeFormat (settings.format);
  2060. }
  2061. recordingSettings = settings;
  2062. juce::String text;
  2063. text << "format=" << (settings.format == takes::SampleFormat::float32 ? "float32" : settings.format == takes::SampleFormat::pcm16 ? "pcm16" : "pcm24") << "\n"
  2064. << "trackTakeNames=" << (settings.trackTakeNames ? 1 : 0) << "\n"
  2065. << "manualOffset=" << settings.manualOffset << "\n"
  2066. << "useMeasured=" << (settings.useMeasured ? 1 : 0) << "\n"
  2067. << "pingOutput=" << settings.pingOutput << "\n"
  2068. << "pingInput=" << settings.pingInput << "\n";
  2069. for (const auto& [key, samples] : settings.measured)
  2070. text << "measured=" << samples << "\t" << juce::String::fromUTF8 (key.c_str()) << "\n";
  2071. if (deviceStateSaver != nullptr) // (a headless engine — tests, export — keeps the user's file as it is)
  2072. recordingSettingsFile().replaceWithText (text);
  2073. sendChangeMessage();
  2074. }
  2075. std::string AudioEngine::currentSetupKey() const
  2076. {
  2077. auto* device = deviceManager.getCurrentAudioDevice();
  2078. if (device == nullptr)
  2079. return {};
  2080. const auto setup = deviceManager.getAudioDeviceSetup();
  2081. return takes::setupKey (device->getTypeName().toStdString(), setup.outputDeviceName.toStdString(), setup.inputDeviceName.toStdString(),
  2082. device->getCurrentSampleRate(), device->getCurrentBufferSizeSamples());
  2083. }
  2084. takes::Latency AudioEngine::currentLatency() const
  2085. {
  2086. takes::Latency l;
  2087. if (auto* device = deviceManager.getCurrentAudioDevice())
  2088. {
  2089. l.driverInput = device->getInputLatencyInSamples();
  2090. l.driverOutput = device->getOutputLatencyInSamples();
  2091. }
  2092. if (recordingSettings.useMeasured)
  2093. if (const auto it = recordingSettings.measured.find (currentSetupKey()); it != recordingSettings.measured.end())
  2094. l.measured = it->second;
  2095. l.manual = recordingSettings.manualOffset;
  2096. l.pdc = getLatencySamples();
  2097. return l;
  2098. }
  2099. juce::String AudioEngine::startLatencyPing()
  2100. {
  2101. auto* device = deviceManager.getCurrentAudioDevice();
  2102. if (device == nullptr)
  2103. return TR_NOOP ("no audio device is open");
  2104. if (transport.playing.load() || isCountingIn())
  2105. return TR_NOOP ("stop playback first");
  2106. if (! hasAudioInput())
  2107. if (const auto r = openAudioInput(); r.issue != InputIssue::none)
  2108. return TR_NOOP ("no audio input is open");
  2109. device = deviceManager.getCurrentAudioDevice();
  2110. if (device == nullptr)
  2111. return TR_NOOP ("no audio device is open");
  2112. const auto in = recordingSettings.pingInput, out = recordingSettings.pingOutput;
  2113. if (! device->getActiveInputChannels()[in])
  2114. return TR_NOOP ("the input channel is not open");
  2115. if (! device->getActiveOutputChannels()[out])
  2116. return TR_NOOP ("the output channel is not open");
  2117. // device channel -> the callback's index (only open channels are passed)
  2118. const auto slotOf = [] (const juce::BigInteger& active, int c) {
  2119. if (! active[c])
  2120. return -1;
  2121. int slot = 0;
  2122. for (int k = 0; k < c; ++k)
  2123. slot += active[k] ? 1 : 0;
  2124. return slot;
  2125. };
  2126. pingInput = slotOf (device->getActiveInputChannels(), in);
  2127. pingOutputs = { slotOf (device->getActiveOutputChannels(), out), slotOf (device->getActiveOutputChannels(), out + 1) };
  2128. const auto rate = device->getCurrentSampleRate() > 0.0 ? device->getCurrentSampleRate() : 48000.0;
  2129. ping.start (8, juce::jmax (4096, (int) (rate / 4.0)), 0.5f);
  2130. return {};
  2131. }
  2132. takes::LatencyPing::Result AudioEngine::finishLatencyPing()
  2133. {
  2134. auto r = ping.result();
  2135. if (r.ok)
  2136. {
  2137. auto s = recordingSettings;
  2138. s.measured[currentSetupKey()] = r.samples;
  2139. setRecordingSettings (s);
  2140. }
  2141. return r;
  2142. }
  2143. void AudioEngine::setInsertRecordSafe (int track, bool safe)
  2144. {
  2145. if (track <= 0 || track >= (int) song.mixer.size() || song.mixer[(std::size_t) track].recordSafe == safe)
  2146. return;
  2147. if (safe && isInsertArmed (track))
  2148. setInsertArmed (track, false);
  2149. editSong ([track, safe] (Song& s) { s.mixer[(std::size_t) track].recordSafe = safe; });
  2150. }
  2151. void AudioEngine::startAudioTake()
  2152. {
  2153. auto* device = deviceManager.getCurrentAudioDevice();
  2154. if (device == nullptr)
  2155. return;
  2156. const auto names = getInputChannelNames();
  2157. const auto deviceChannels = (int) names.size();
  2158. const auto active = device->getActiveInputChannels();
  2159. if (deviceChannels == 0 || active.isZero())
  2160. {
  2161. recordingError = "no audio input is open";
  2162. notify (InputIssue::noInputOpen);
  2163. return;
  2164. }
  2165. // one take per armed insert that has an input source; without armed inserts (Settings' "Record input audio"),
  2166. // the first two input channels into a new insert
  2167. // round 168x (issue #41): FL's "Record" position of each insert. "External input only" records the device input;
  2168. // the other positions tap the insert (stereo, after the render) and need no input of their own; LYNX's "also the
  2169. // dry input" adds the device input as a second take
  2170. struct Wanted
  2171. {
  2172. int track, first, channels;
  2173. RecordSource point = RecordSource::externalInput;
  2174. bool dry = false; // the second, dry take of "also record the dry input (LYNX)"
  2175. };
  2176. std::vector<Wanted> wanted;
  2177. std::vector<int> withoutInput;
  2178. for (const auto t : armedInserts)
  2179. {
  2180. if (t <= 0 || t >= (int) song.mixer.size() || (int) wanted.size() >= maxTakes)
  2181. continue;
  2182. const auto& mt = song.mixer[(std::size_t) t];
  2183. const auto [first, count] = inputChannelsOf (mt, deviceChannels);
  2184. if (mt.recordSource != RecordSource::externalInput)
  2185. {
  2186. wanted.push_back ({ t, 0, 2, mt.recordSource, false });
  2187. if (mt.recordDryToo && count > 0 && (int) wanted.size() < maxTakes && (int) wanted.size() < LiveInput::maxTaps)
  2188. wanted.push_back ({ t, first, count, RecordSource::externalInput, true });
  2189. continue;
  2190. }
  2191. if (count == 0)
  2192. withoutInput.push_back (t);
  2193. else
  2194. wanted.push_back ({ t, first, count });
  2195. }
  2196. if (armedInserts.empty())
  2197. {
  2198. // Settings' / Options' "Record input audio" with no insert armed: the first two input channels. Round 190ir
  2199. // (Discord report 2026-11-15, "how do i stop it from creating new inserts every time i record"): each take used
  2200. // to get a new free insert (and so a new track). They now go through one insert: the first that listens to the
  2201. // device's first input already (the one an earlier take of this switch was given, or the user's), else a free
  2202. // insert that gets that input.
  2203. auto target = -1;
  2204. for (int t = 1; t < (int) song.mixer.size() && target < 0; ++t)
  2205. if (song.mixer[(std::size_t) t].inputChannel == 0 && ! song.mixer[(std::size_t) t].recordSafe)
  2206. target = t;
  2207. if (target < 0)
  2208. if (const auto free = song.nextFreeInsert(); free > 0 && free < (int) song.mixer.size())
  2209. {
  2210. setInsertInput (free, 0, deviceChannels > 1);
  2211. target = free;
  2212. }
  2213. if (target > 0)
  2214. {
  2215. // the device input itself, as before (the insert is not armed, so it may not be processing its input): the
  2216. // clip plays through that insert and its track becomes the insert's audio track, so the next take lands there
  2217. const auto [first, count] = inputChannelsOf (song.mixer[(std::size_t) target], deviceChannels);
  2218. if (count > 0)
  2219. wanted.push_back ({ target, first, count });
  2220. }
  2221. if (wanted.empty()) // (no insert could take it: the old way, a new insert for the take)
  2222. wanted.push_back ({ 0, 0, juce::jmin (2, deviceChannels) });
  2223. }
  2224. if (wanted.empty())
  2225. {
  2226. recordingError = "the armed inserts have no audio input";
  2227. notify (InputIssue::armedWithoutInput, withoutInput.empty() ? 0 : withoutInput.front());
  2228. return;
  2229. }
  2230. if (! withoutInput.empty())
  2231. notify (InputIssue::insertWithoutInput, withoutInput.front());
  2232. auto folder = recordingFolder;
  2233. if (! folder.createDirectory()) // e.g. a read-only project folder: the global recordings folder
  2234. folder = defaultRecordingFolder(), folder.createDirectory();
  2235. takeSampleRate = device->getCurrentSampleRate();
  2236. takeLatency = takes::compensation (currentLatency(), recordOptions.latencyCompensation);
  2237. takeTicksPerSample = transport.ticksPerSample();
  2238. const auto format = recordingSettings.format;
  2239. // room on the drive (round 163): under 30 s refuse, under 10 minutes warn
  2240. {
  2241. int channels = 0;
  2242. for (const auto& w : wanted)
  2243. channels += w.channels;
  2244. const auto minutes = takes::minutesLeft (folder.getBytesFreeOnVolume(), takeSampleRate, channels, format);
  2245. if (minutes < 0.5)
  2246. {
  2247. recordingError = "the recordings drive is full";
  2248. notify (InputIssue::lowDisk, 0, juce::String (minutes, 1));
  2249. return;
  2250. }
  2251. if (minutes < 10.0)
  2252. notify (InputIssue::lowDisk, 0, juce::String (minutes, 1));
  2253. }
  2254. const auto now = juce::Time::getCurrentTime();
  2255. std::vector<std::shared_ptr<Take>> made;
  2256. int tapsUsed = 0;
  2257. for (const auto& w : wanted)
  2258. {
  2259. juce::String insert;
  2260. if (w.track > 0)
  2261. insert = song.mixer[(std::size_t) w.track].name.empty() ? "Insert " + juce::String (w.track)
  2262. : juce::String::fromUTF8 (song.mixer[(std::size_t) w.track].name.c_str());
  2263. if (w.dry)
  2264. insert += " DI"; // the dry take of "also record the dry input (LYNX)"
  2265. juce::File file;
  2266. auto recordTo = w.track > 0 ? juce::String::fromUTF8 (song.mixer[(std::size_t) w.track].recordTo.c_str()) : juce::String();
  2267. if (w.dry && recordTo.isNotEmpty())
  2268. recordTo = juce::File (recordTo).getSiblingFile (juce::File (recordTo).getFileNameWithoutExtension() + " DI.wav").getFullPathName();
  2269. if (recordTo.isNotEmpty() && juce::File::isAbsolutePath (recordTo))
  2270. {
  2271. // FL's "Record <insert> to" file (round 167a): that file; LYNX never overwrites an earlier take, the next
  2272. // ones get "_2", "_3"... (its own choice)
  2273. const auto target = juce::File (recordTo).withFileExtension (".wav");
  2274. target.getParentDirectory().createDirectory();
  2275. const auto unique = safety::uniqueName (target.getFileNameWithoutExtension().toStdString(), [&target, &made] (const std::string& n) {
  2276. const auto f = target.getSiblingFile (juce::String::fromUTF8 (n.c_str()) + ".wav");
  2277. return f.exists() || std::any_of (made.begin(), made.end(), [&f] (const std::shared_ptr<Take>& t) { return t->file == f; });
  2278. });
  2279. file = target.getSiblingFile (juce::String::fromUTF8 (unique.c_str()) + ".wav");
  2280. }
  2281. else if (recordingSettings.trackTakeNames)
  2282. {
  2283. // "<Insert>_Take<N>.wav", N raised until the name is free (round 163)
  2284. for (int n = 1; n < 100000; ++n)
  2285. {
  2286. file = folder.getChildFile (juce::File::createLegalFileName (juce::String::fromUTF8 (takes::takeName (insert.toStdString(), n).c_str())) + ".wav");
  2287. if (! file.exists() && std::none_of (made.begin(), made.end(), [&file] (const std::shared_ptr<Take>& t) { return t->file == file; }))
  2288. break;
  2289. }
  2290. }
  2291. else
  2292. {
  2293. // FL's name (REA round 134): "<project>_<yyyy-mm-dd hh-mm-ss>_<insert name>", "_2", "_3"... when taken
  2294. const auto name = juce::File::createLegalFileName (juce::String::fromUTF8 (
  2295. safety::recordingName (recordingStem.toStdString(), now.getYear(), now.getMonth() + 1, now.getDayOfMonth(), now.getHours(),
  2296. now.getMinutes(), now.getSeconds(), insert.toStdString()).c_str()));
  2297. const auto unique = safety::uniqueName (name.toStdString(), [&folder] (const std::string& n) {
  2298. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ".wav").exists();
  2299. });
  2300. file = folder.getChildFile (juce::String::fromUTF8 (unique.c_str()) + ".wav");
  2301. }
  2302. auto take = std::make_shared<Take>();
  2303. take->track = w.track;
  2304. take->first = w.first;
  2305. take->channels = w.channels;
  2306. take->file = file;
  2307. if (w.point != RecordSource::externalInput && tapsUsed < LiveInput::maxTaps)
  2308. {
  2309. take->tap = tapsUsed++;
  2310. // the effects' latency up to the tap: the slots' (the planned output latency minus the input alignment and
  2311. // the manual track latency, which delays nothing inside the insert)
  2312. if (w.point >= RecordSource::postEffects)
  2313. take->skip = insertEffectsLatency (getPdcPlan(), song, w.track, takeSampleRate);
  2314. auto& slot = liveInput.taps[(std::size_t) take->tap];
  2315. slot.point.store ((int) w.point);
  2316. slot.track.store (w.track);
  2317. }
  2318. // FL (round 190ev, REA_rodada190ev §2): "External input only" plays back through the recording insert, as does any
  2319. // take of an insert a Playlist audio track is linked to; a take that holds the insert's processing (Post EQ, the
  2320. // default) goes where the insert goes (Master, usually). It used to play through a new free insert.
  2321. take->playThrough = takes::playbackInsert (song, w.track, w.point);
  2322. // ~22 s at 48 kHz of room between the audio thread and the disk
  2323. take->stream = std::make_unique<takes::TakeStream> (w.channels, 1 << 20);
  2324. if (! take->writer.open (file.getFullPathName().toStdString(), takeSampleRate, w.channels, format))
  2325. {
  2326. recordingError = utf8 ("could not create ") + file.getFullPathName();
  2327. continue;
  2328. }
  2329. made.push_back (std::move (take));
  2330. }
  2331. if (recordingError.isNotEmpty())
  2332. notify (InputIssue::failed, 0, recordingError);
  2333. takeStartTick.store (-1.0);
  2334. takeFrames.store (0);
  2335. takeTicks.store (0.0);
  2336. takeWrapCount.store (0);
  2337. lostFrames = 0;
  2338. journalsWritten = false;
  2339. openTakes = made;
  2340. {
  2341. const juce::ScopedLock lock (drainLock);
  2342. draining = made;
  2343. }
  2344. if (drainer == nullptr)
  2345. drainer = std::make_unique<Drainer> (*this);
  2346. if (! recordThread.isThreadRunning())
  2347. recordThread.startThread (juce::Thread::Priority::high);
  2348. recordThread.addTimeSliceClient (drainer.get());
  2349. liveInput.tapCount.store (tapsUsed);
  2350. const juce::SpinLock::ScopedLockType lock (takeLock);
  2351. takeCount = 0;
  2352. for (auto& take : made)
  2353. takes[(std::size_t) takeCount++] = take.get();
  2354. updateLinearSong();
  2355. }
  2356. void AudioEngine::writeJournals()
  2357. {
  2358. journalsWritten = true;
  2359. juce::StringArray list (juce::StringArray::fromLines (inProgressFile().loadFileAsString()));
  2360. list.removeEmptyStrings();
  2361. int k = 0;
  2362. for (const auto& take : openTakes)
  2363. {
  2364. takes::Journal j;
  2365. j.wav = take->file.getFullPathName().toStdString();
  2366. j.firstTick = takeStartTick.load();
  2367. j.ticksPerSample = takeTicksPerSample;
  2368. j.sampleRate = takeSampleRate;
  2369. j.latency = takeLatency;
  2370. j.insert = take->playThrough;
  2371. j.playlistTrack = -1;
  2372. j.project = recordingStem.toStdString();
  2373. const auto journal = journalFor (take->file);
  2374. journal.replaceWithText (juce::String::fromUTF8 (takes::journalText (j).c_str()));
  2375. list.addIfNotAlreadyThere (journal.getFullPathName());
  2376. ++k;
  2377. }
  2378. if (deviceStateSaver != nullptr)
  2379. inProgressFile().replaceWithText (list.joinIntoString ("\n"));
  2380. }
  2381. void AudioEngine::finishAudioTake()
  2382. {
  2383. liveTakeTracks.clear();
  2384. {
  2385. const juce::SpinLock::ScopedLockType lock (takeLock);
  2386. takes.fill (nullptr);
  2387. takeCount = 0;
  2388. }
  2389. liveInput.linearSong.store (false);
  2390. liveInput.noLoopRegion.store (false);
  2391. std::vector<std::shared_ptr<Take>> done;
  2392. done.swap (openTakes);
  2393. {
  2394. const juce::ScopedLock lock (drainLock);
  2395. draining.clear();
  2396. }
  2397. // the recording taps are free again (the audio thread let go of the takes under takeLock above)
  2398. liveInput.tapCount.store (0);
  2399. for (auto& tap : liveInput.taps)
  2400. tap.track.store (-1);
  2401. std::vector<std::shared_ptr<Take>> kept;
  2402. for (auto& take : done)
  2403. {
  2404. if (take->tap >= 0 && take->skipped > 0) // a tapped take: the frames it dropped at its start close it
  2405. take->stream->pushSilence (take->skipped);
  2406. take->stream->finish(); // the audio thread let go of it (takeLock above)
  2407. const juce::ScopedLock lock (take->drainMutex);
  2408. take->drain();
  2409. lostFrames += take->stream->lostFrames();
  2410. take->writer.close();
  2411. if (take->file.existsAsFile())
  2412. {
  2413. sessionRecordings.push_back (take->file);
  2414. kept.push_back (take);
  2415. }
  2416. }
  2417. if (recordOptions.disarmOnStop) // LYNX's "Disarm the inserts when recording stops" (not FL's "Disarm on stop")
  2418. for (const auto t : std::vector<int> (armedInserts))
  2419. setInsertArmed (t, false);
  2420. // the journals go once the takes are on the Playlist (or thrown away)
  2421. const auto dropJournals = [this, &done] {
  2422. juce::StringArray list (juce::StringArray::fromLines (inProgressFile().loadFileAsString()));
  2423. for (const auto& take : done)
  2424. {
  2425. journalFor (take->file).deleteFile();
  2426. list.removeString (journalFor (take->file).getFullPathName());
  2427. }
  2428. list.removeEmptyStrings();
  2429. if (deviceStateSaver != nullptr)
  2430. {
  2431. if (list.isEmpty())
  2432. inProgressFile().deleteFile();
  2433. else
  2434. inProgressFile().replaceWithText (list.joinIntoString ("\n"));
  2435. }
  2436. };
  2437. const auto frames = takeFrames.exchange (0);
  2438. const auto startTick = takeStartTick.exchange (-1.0);
  2439. const auto ticks = takeTicks.exchange (0.0);
  2440. const auto keepPunch = activePunch;
  2441. activePunch.reset();
  2442. punchStopAt = -1;
  2443. std::vector<double> wraps;
  2444. for (int k = 0, count = takeWrapCount.exchange (0); k < count; ++k)
  2445. wraps.push_back ((double) takeWraps[(std::size_t) k].load() * takeTicksPerSample);
  2446. // (round 190bv) takes made for slots of the clip grid go into those slots, not onto the Playlist
  2447. if (std::any_of (slotTakes.begin(), slotTakes.end(), [] (const SlotTake& t) { return t.audio; }) && frames > 0 && startTick >= 0.0
  2448. && ! discardAudioTakes)
  2449. {
  2450. std::vector<std::pair<juce::File, int>> files;
  2451. for (const auto& take : kept)
  2452. files.push_back ({ take->file, take->track });
  2453. const auto used = placeSlotAudio (files, takeTicksPerSample, takeLatency);
  2454. if (! used)
  2455. for (auto& take : done)
  2456. {
  2457. take->file.deleteFile();
  2458. forgetRecordings ({ take->file });
  2459. }
  2460. dropJournals();
  2461. return;
  2462. }
  2463. if (frames <= 0 || startTick < 0.0 || discardAudioTakes) // (Cancel recording drops the takes, round 187a)
  2464. {
  2465. for (auto& take : done)
  2466. {
  2467. take->file.deleteFile();
  2468. forgetRecordings ({ take->file });
  2469. }
  2470. dropJournals();
  2471. return;
  2472. }
  2473. if (lostFrames > 0)
  2474. notify (InputIssue::framesLost, 0, juce::String (lostFrames));
  2475. // round 190ir (Discord report: "it isnt picking up my audio input"): takes that hold nothing but digital silence
  2476. // (exact zeros: not a quiet room, which always has some noise) mean the input delivers nothing: another input
  2477. // channel than the one the microphone is on, a muted interface, or the OS's microphone privacy (Windows) /
  2478. // permission (macOS). Said once the take is placed, so the user knows why the clip is flat.
  2479. if (! kept.empty() && std::all_of (kept.begin(), kept.end(), [] (const std::shared_ptr<Take>& t) { return t->peaks == nullptr || t->peaks->maxPeak() <= 0.0f; }))
  2480. notify (InputIssue::silentTake, kept.front()->track);
  2481. // what came into the interface corresponds to what was heard one latency earlier; the clip lands on that
  2482. // song position to the sample (round 163: sub-tick rest in the source offset)
  2483. const auto placement = takes::place (startTick, ticks, takeTicksPerSample, takeLatency);
  2484. std::vector<takes::Part> parts;
  2485. if (keepPunch.has_value()) // pre-roll / punch in-out: only the range (the rest stays in the file)
  2486. parts = takes::punch (placement, { *keepPunch });
  2487. else if (song.mode == PlayMode::song && song.loopPlays())
  2488. // 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),
  2489. // round 163's option drops one a 1/16 note long or less
  2490. parts = takes::loopPasses (placement, song.loopStart, song.loopEnd, recordOptions.lastLoopPassPlays ? ppq / 4 : 0, wraps);
  2491. else if (recordOptions.recordingMarkers && song.mode == PlayMode::song)
  2492. parts = takes::punch (placement, punchRanges (song.markers())); // FL's "Enable recording markers"
  2493. else
  2494. parts = takes::punch (placement, {});
  2495. if (parts.empty()) // the whole take was outside the ranges
  2496. {
  2497. for (auto& take : done)
  2498. {
  2499. take->file.deleteFile();
  2500. forgetRecordings ({ take->file });
  2501. }
  2502. dropJournals();
  2503. return;
  2504. }
  2505. std::vector<takes::TakeFile> made;
  2506. for (const auto& take : kept)
  2507. made.push_back ({ take->file.getFullPathName().toStdString(), take->file.getFileNameWithoutExtension().toStdString(), take->playThrough,
  2508. take->track > 0 ? take->track : -1 });
  2509. // FL: Loop record over a loop region, without a punch
  2510. const auto loopRecorded = recordOptions.loopRecord && ! keepPunch.has_value() && song.mode == PlayMode::song && song.loopPlays();
  2511. const takes::TakeOptions takeOptions { loopRecorded, recordOptions.mode == RecordMode::overdub, recordOptions.lastLoopPassPlays };
  2512. editSong ([made, parts, takeOptions] (Song& s) { takes::placeTakeClips (s, made, parts, takeOptions); });
  2513. dropJournals();
  2514. }
  2515. std::vector<takes::Journal> AudioEngine::recoverInterruptedTakes (const std::vector<juce::File>& folders)
  2516. {
  2517. // the journals listed as in progress, and any journal left in the given folders
  2518. juce::StringArray journals (juce::StringArray::fromLines (inProgressFile().loadFileAsString()));
  2519. auto where = folders;
  2520. where.push_back (defaultRecordingFolder());
  2521. for (const auto& folder : where)
  2522. for (const auto& f : folder.findChildFiles (juce::File::findFiles, false, "*.lynxrec"))
  2523. journals.addIfNotAlreadyThere (f.getFullPathName());
  2524. journals.removeEmptyStrings();
  2525. std::vector<takes::Journal> out;
  2526. for (const auto& path : journals)
  2527. {
  2528. const juce::File journal (path);
  2529. takes::Journal j;
  2530. if (! journal.existsAsFile() || ! takes::parseJournal (journal.loadFileAsString().toStdString(), j))
  2531. continue;
  2532. // (a take being recorded by this very session is not "interrupted")
  2533. if (std::any_of (openTakes.begin(), openTakes.end(), [&journal, this] (const std::shared_ptr<Take>& t) { return journalFor (t->file) == journal; }))
  2534. continue;
  2535. std::int64_t frames = 0;
  2536. if (! takes::repairWav (j.wav, &frames) || frames <= 0)
  2537. continue;
  2538. out.push_back (j);
  2539. }
  2540. return out;
  2541. }
  2542. int AudioEngine::placeRecoveredTakes (const std::vector<takes::Journal>& recovered)
  2543. {
  2544. struct One
  2545. {
  2546. takes::TakeFile file;
  2547. std::vector<takes::Part> parts;
  2548. };
  2549. std::vector<One> placed;
  2550. for (const auto& j : recovered)
  2551. {
  2552. std::int64_t frames = 0;
  2553. if (! takes::repairWav (j.wav, &frames) || frames <= 0)
  2554. continue;
  2555. const auto placement = takes::place (j.firstTick, (double) frames * j.ticksPerSample, j.ticksPerSample, j.latency);
  2556. if (! placement.valid())
  2557. continue;
  2558. const juce::File wav (juce::String::fromUTF8 (j.wav.c_str()));
  2559. placed.push_back ({ { j.wav, wav.getFileNameWithoutExtension().toStdString(), j.insert }, takes::punch (placement, {}) });
  2560. }
  2561. if (! placed.empty())
  2562. editSong ([placed] (Song& s) {
  2563. for (const auto& p : placed)
  2564. takes::placeTakeClips (s, { p.file }, p.parts);
  2565. });
  2566. forgetInterruptedTakes (recovered);
  2567. return (int) placed.size();
  2568. }
  2569. void AudioEngine::forgetInterruptedTakes (const std::vector<takes::Journal>& recovered)
  2570. {
  2571. juce::StringArray list (juce::StringArray::fromLines (inProgressFile().loadFileAsString()));
  2572. for (const auto& j : recovered)
  2573. {
  2574. const auto journal = journalFor (juce::File (juce::String::fromUTF8 (j.wav.c_str())));
  2575. journal.deleteFile();
  2576. list.removeString (journal.getFullPathName());
  2577. }
  2578. list.removeEmptyStrings();
  2579. if (deviceStateSaver != nullptr)
  2580. {
  2581. if (list.isEmpty())
  2582. inProgressFile().deleteFile();
  2583. else
  2584. inProgressFile().replaceWithText (list.joinIntoString ("\n"));
  2585. }
  2586. }
  2587. juce::File AudioEngine::defaultRecordingFolder()
  2588. {
  2589. return juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("LYNX/Recordings");
  2590. }
  2591. void AudioEngine::setRecordingTarget (const juce::File& folder, const juce::String& projectStem)
  2592. {
  2593. recordingFolder = folder == juce::File() ? defaultRecordingFolder() : folder;
  2594. recordingStem = projectStem;
  2595. }
  2596. void AudioEngine::forgetRecordings (const std::vector<juce::File>& files)
  2597. {
  2598. sessionRecordings.erase (std::remove_if (sessionRecordings.begin(), sessionRecordings.end(),
  2599. [&files] (const juce::File& f) { return std::find (files.begin(), files.end(), f) != files.end(); }),
  2600. sessionRecordings.end());
  2601. }
  2602. std::vector<std::string> AudioEngine::getInputChannelNames() const
  2603. {
  2604. std::vector<std::string> names;
  2605. if (auto* device = deviceManager.getCurrentAudioDevice(); device != nullptr && ! device->getActiveInputChannels().isZero())
  2606. for (const auto& n : device->getInputChannelNames())
  2607. if ((int) names.size() < LiveInput::maxChannels)
  2608. names.push_back (n.toStdString());
  2609. return names;
  2610. }
  2611. bool AudioEngine::hasAudioInput() const
  2612. {
  2613. auto* device = deviceManager.getCurrentAudioDevice();
  2614. return device != nullptr && ! device->getActiveInputChannels().isZero();
  2615. }
  2616. void AudioEngine::notify (InputIssue issue, int track, const juce::String& detail)
  2617. {
  2618. recordingNotice = { issue, track, detail };
  2619. sendChangeMessage();
  2620. }
  2621. AudioEngine::RecordingNotice AudioEngine::openAudioInput (const juce::String& deviceName)
  2622. {
  2623. auto* type = deviceManager.getCurrentDeviceTypeObject();
  2624. if (type == nullptr || deviceManager.getCurrentAudioDevice() == nullptr)
  2625. return { InputIssue::noDevice, 0, {} };
  2626. auto setup = deviceManager.getAudioDeviceSetup();
  2627. int count = 0;
  2628. if (type->hasSeparateInputsAndOutputs())
  2629. {
  2630. // Windows Audio / DirectSound: the input is a device of its own
  2631. const auto inputs = type->getDeviceNames (true);
  2632. auto name = deviceName.isNotEmpty() ? deviceName : setup.inputDeviceName;
  2633. if (name.isEmpty())
  2634. name = releasedInputDevice; // the one releaseAudioInputIfUnused closed
  2635. if (! inputs.contains (name))
  2636. {
  2637. const auto index = type->getDefaultDeviceIndex (true);
  2638. name = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  2639. }
  2640. if (name.isEmpty())
  2641. return { InputIssue::noInputDevice, 0, {} };
  2642. auto* current = deviceManager.getCurrentAudioDevice();
  2643. if (name == setup.inputDeviceName && ! current->getActiveInputChannels().isZero())
  2644. count = current->getInputChannelNames().size();
  2645. else if (std::unique_ptr<juce::AudioIODevice> probe (type->createDevice ({}, name)); probe != nullptr)
  2646. count = probe->getInputChannelNames().size();
  2647. setup.inputDeviceName = name;
  2648. }
  2649. else
  2650. {
  2651. // ASIO: one device does both; its input channels come in pairs in the mixer
  2652. count = deviceManager.getCurrentAudioDevice()->getInputChannelNames().size();
  2653. setup.inputDeviceName = setup.outputDeviceName;
  2654. }
  2655. if (count <= 0)
  2656. count = 2;
  2657. count = juce::jmin (count, (int) LiveInput::maxChannels);
  2658. juce::BigInteger wanted;
  2659. wanted.setRange (0, count, true);
  2660. if (! setup.useDefaultInputChannels && setup.inputChannels == wanted && ! deviceManager.getCurrentAudioDevice()->getActiveInputChannels().isZero())
  2661. return {};
  2662. setup.useDefaultInputChannels = false;
  2663. setup.inputChannels = wanted;
  2664. const auto error = deviceManager.setAudioDeviceSetup (setup, true);
  2665. sendChangeMessage();
  2666. if (error.isNotEmpty())
  2667. return { InputIssue::failed, 0, error };
  2668. if (! hasAudioInput())
  2669. return { InputIssue::noInputDevice, 0, {} };
  2670. return {};
  2671. }
  2672. bool AudioEngine::audioInputNeeded() const
  2673. {
  2674. if (audioArmed || ! armedInserts.empty() || hwinsert::returnsFromInput (song))
  2675. return true;
  2676. return std::any_of (song.mixer.begin(), song.mixer.end(), [] (const MixerTrack& t) { return t.inputChannel >= 0 || t.flInput >= 0; });
  2677. }
  2678. void AudioEngine::releaseAudioInputIfUnused()
  2679. {
  2680. if (! hasAudioInput() || audioInputNeeded())
  2681. return;
  2682. auto* type = deviceManager.getCurrentDeviceTypeObject();
  2683. auto setup = deviceManager.getAudioDeviceSetup();
  2684. setup.useDefaultInputChannels = false;
  2685. setup.inputChannels.clear();
  2686. // a driver with separate input devices (Windows Audio) keeps capturing while an input device is set, even with
  2687. // no channel active: the device goes too (its name is remembered for the next openAudioInput)
  2688. if (type != nullptr && type->hasSeparateInputsAndOutputs() && setup.inputDeviceName.isNotEmpty())
  2689. {
  2690. releasedInputDevice = setup.inputDeviceName;
  2691. setup.inputDeviceName = {};
  2692. }
  2693. deviceManager.setAudioDeviceSetup (setup, true);
  2694. sendChangeMessage();
  2695. }
  2696. void AudioEngine::setInsertInput (int track, int channel, bool stereo)
  2697. {
  2698. if (track < 0 || track >= (int) song.mixer.size()) // (the Master too: REA round 143)
  2699. return;
  2700. editSong ([=] (Song& s) {
  2701. s.mixer[(std::size_t) track].inputChannel = channel;
  2702. s.mixer[(std::size_t) track].inputStereo = stereo;
  2703. });
  2704. recordingError = {};
  2705. if (channel >= 0 && ! hasAudioInput())
  2706. if (const auto result = openAudioInput(); result.issue != InputIssue::none)
  2707. notify (result.issue, track, result.detail);
  2708. }
  2709. void AudioEngine::setInsertMonitor (int track, InputMonitor mode)
  2710. {
  2711. if (track >= 0 && track < (int) song.mixer.size())
  2712. editSong ([=] (Song& s) { s.mixer[(std::size_t) track].monitor = mode; });
  2713. }
  2714. void AudioEngine::setInsertRecordSource (int track, RecordSource source)
  2715. {
  2716. if (track > 0 && track < (int) song.mixer.size() && song.mixer[(std::size_t) track].recordSource != source)
  2717. editSong ([=] (Song& s) { s.mixer[(std::size_t) track].recordSource = source; });
  2718. }
  2719. void AudioEngine::setInsertRecordDryToo (int track, bool on)
  2720. {
  2721. if (track > 0 && track < (int) song.mixer.size() && song.mixer[(std::size_t) track].recordDryToo != on)
  2722. editSong ([=] (Song& s) { s.mixer[(std::size_t) track].recordDryToo = on; });
  2723. }
  2724. void AudioEngine::handleIncomingMidiMessage (juce::MidiInput* source, const juce::MidiMessage& m)
  2725. {
  2726. // MIDI thread: queues and atomics only (and a short copy of the device settings)
  2727. prefs::MidiInputPrefs device;
  2728. auto velocityCurve = prefs::VelocityCurve::linear;
  2729. auto locked = -1; // a channel that "receives notes from" this device (FL's channel lock)
  2730. auto jumpChannel = 0;
  2731. std::uint8_t inputSource = 0; // round 190jl: NoteEvent::source (0 = unknown)
  2732. const auto deviceName = source != nullptr ? source->getName().toStdString() : std::string();
  2733. {
  2734. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  2735. const auto& name = deviceName;
  2736. device = midiPrefsShared.input (name);
  2737. velocityCurve = midiPrefsShared.velocity;
  2738. const auto midiChannel = m.getChannel();
  2739. for (const auto& l : noteLocks)
  2740. if (l.device == name && (l.midiChannel == 0 || l.midiChannel == midiChannel))
  2741. {
  2742. locked = l.channel;
  2743. if (l.midiChannel != 0)
  2744. break; // a lock on this very MIDI channel wins over one on any channel
  2745. }
  2746. jumpChannel = midiPrefsShared.songMarkerJumpChannel;
  2747. for (std::size_t k = 0; k < midiSourceNames.size(); ++k) // (round 190jl: the input's source number)
  2748. if (midiSourceNames[k] == name)
  2749. {
  2750. inputSource = (std::uint8_t) (k + 1);
  2751. break;
  2752. }
  2753. }
  2754. if (locked >= 0)
  2755. device.target = locked;
  2756. if (! device.enabled)
  2757. return;
  2758. // the external clock LYNX follows (round 165f): clock, start / stop / continue, song position
  2759. if (m.getRawDataSize() > 0 && (m.getRawData()[0] >= 0xf2) && source != nullptr && midiSync.handleInput (source->getName(), m))
  2760. return;
  2761. midiActivity.fetch_add (1, std::memory_order_relaxed); // the toolbar's MIDI input light
  2762. if (m.getRawDataSize() > 0 && prefs::midiMeansPlaying (m.getRawData()[0]))
  2763. midiPlayed.fetch_add (1, std::memory_order_relaxed); // what holds a backup back (not clock or active sensing)
  2764. // FL's "Song marker jump (MIDI channel)": notes on that channel move the song to a marker instead of playing
  2765. if (jumpChannel > 0 && m.getChannel() == jumpChannel && m.isNoteOnOrOff())
  2766. {
  2767. if (m.isNoteOn())
  2768. pendingMarkerNote.store (m.getNoteNumber());
  2769. return;
  2770. }
  2771. // FL's playlist live mode channel (round 165m): its notes launch the performance clips instead of playing
  2772. if (const auto pc = performanceMidiChannel.load (std::memory_order_relaxed);
  2773. pc != 0 && m.getChannel() == pc && m.isNoteOnOrOff() && performanceMidiOn.load (std::memory_order_relaxed))
  2774. {
  2775. perf::Command c;
  2776. if (performanceMidi.note (m.getNoteNumber(), m.isNoteOn(), c))
  2777. performanceLive->midiCommands.push (c);
  2778. return;
  2779. }
  2780. // FL's note links (round 190cs; controller number 256 + key): a linked key moves its control instead of playing
  2781. if (m.isNoteOnOrOff())
  2782. {
  2783. const auto key = m.getNoteNumber();
  2784. const auto value = m.isNoteOn() ? (int) m.getVelocity() : 0;
  2785. if ((linkedNotes[(std::size_t) (key >> 6)].load (std::memory_order_relaxed) >> (key & 63) & 1u) != 0
  2786. || mapCaptureNotes.load (std::memory_order_relaxed)) // (round 190ef: MIDI Map Mode takes every key)
  2787. {
  2788. controllerQueue.push ({ linkNoteBase + key, m.getChannel() - 1, value, device.port });
  2789. return;
  2790. }
  2791. if (value > 0) // (and offered to the link window's Auto detect)
  2792. controllerQueue.push ({ linkNoteBase + key, m.getChannel() - 1, value, device.port, true });
  2793. }
  2794. // a controller profile's buttons, knobs and faders (round 190aw): to the message thread, not into the instruments.
  2795. // Controllers linked by hand stay with their links.
  2796. if (source != nullptr && controllerIo.take (deviceName, m.getRawData(), m.getRawDataSize(), linkedCcs))
  2797. {
  2798. if (m.isController()) // (still offered to MIDI learn)
  2799. controllerQueue.push ({ m.getControllerNumber(), m.getChannel() - 1, m.getControllerValue(), device.port });
  2800. return;
  2801. }
  2802. // issue #108: an MPE controller (the device's MPE setting). Its member channels' pitch bend, CC 74 and pressure
  2803. // belong to the notes on them: a sounding note's expression goes to the channels its note on reached, a note on /
  2804. // off carries the note's own values (played, and recorded as the note's fine pitch, Mod X and Mod Y). Everything
  2805. // else (the master channel, other controllers) is handled as from any controller. No channel filter in this mode.
  2806. mpe::InEvent mpeEvents[mpe::Input::maxEvents];
  2807. const mpe::InEvent* mpeNote = nullptr;
  2808. if (device.mpe)
  2809. {
  2810. if (const mpe::Zone zone { true, device.mpeMembers, (float) device.mpeBendRange }; ! (zone == mpeZone))
  2811. {
  2812. mpeZone = zone;
  2813. mpeInput.setZone (zone);
  2814. }
  2815. const auto count = mpeInput.feed (m.getRawData(), m.getRawDataSize(), mpeEvents);
  2816. if (count == 0)
  2817. return; // (the zone's own configuration)
  2818. if (mpeEvents[0].type == mpe::InEvent::Type::expr)
  2819. {
  2820. // MPE stage 2 (issue #108): while a take records, each change also goes into the held note's curves
  2821. const auto taking = transport.recording.load() && (transport.playing.load() || isCountingIn());
  2822. auto tick = 0.0;
  2823. if (taking)
  2824. {
  2825. const auto now = juce::Time::getMillisecondCounterHiRes();
  2826. const auto stamped = m.getTimeStamp() * 1000.0;
  2827. tick = recordTickFor (std::abs (stamped - now) < 1000.0 ? stamped : now);
  2828. }
  2829. for (int k = 0; k < count; ++k)
  2830. {
  2831. const auto& x = mpeEvents[k];
  2832. InputHeldNotes::Target to[InputHeldNotes::maxTargets];
  2833. const auto n = midiHeld.targetsOf (x.key, to);
  2834. for (int i = 0; i < n; ++i)
  2835. {
  2836. NoteEvent e;
  2837. e.type = NoteEvent::Type::voiceProp;
  2838. e.expression = true;
  2839. e.channel = to[i].channel;
  2840. e.key = to[i].key;
  2841. e.prop = (std::uint8_t) (x.expr == mpe::Expr::pitch ? vfx::Prop::pitch : x.expr == mpe::Expr::timbre ? vfx::Prop::modX : vfx::Prop::modY);
  2842. e.velocity = x.expr == mpe::Expr::pressure ? mpe::modYOfPressure (x.value) : x.value;
  2843. if (e.channel >= 0)
  2844. midiEvents.push (e);
  2845. if (taking && e.channel >= 0)
  2846. {
  2847. RecordedEvent r { tick, e.channel, e.key, 0.0f, false };
  2848. r.lane = (std::int8_t) (x.expr == mpe::Expr::pitch ? NoteCurveLane::pitch : x.expr == mpe::Expr::timbre ? NoteCurveLane::timbre
  2849. : NoteCurveLane::pressure);
  2850. r.value = x.value;
  2851. midiRecordQueue.push (r);
  2852. }
  2853. }
  2854. }
  2855. return;
  2856. }
  2857. if (mpeEvents[0].type != mpe::InEvent::Type::plain)
  2858. mpeNote = &mpeEvents[0];
  2859. }
  2860. else if (device.midiChannel != 0 && m.getChannel() != device.midiChannel)
  2861. return;
  2862. // the pitch wheel, the mod wheel and the other controllers play into the channels the notes go to (round 162,
  2863. // issue #9: they did nothing unless linked): hosted plugins get the MIDI message, LYNX's instruments bend by the
  2864. // channel's pitch range. A CC with a MIDI link only moves its parameter.
  2865. const auto recordBend = transport.recording.load() && transport.playing.load();
  2866. const auto bendTick = recordBend ? estimatedPositionNow() : 0.0;
  2867. auto playControl = [this, &device, &m, recordBend, bendTick, inputSource] (int control, float value) {
  2868. NoteEvent e;
  2869. e.source = inputSource;
  2870. e.type = NoteEvent::Type::control;
  2871. e.key = control;
  2872. e.velocity = value;
  2873. auto send = [&] {
  2874. midiEvents.push (e);
  2875. // recording: the wheel is written too (the channel's pitch bend lane / automation clip, like FL)
  2876. if (recordBend && control == NoteEvent::controlPitchBend)
  2877. bendRecordQueue.push ({ bendTick, e.channel, juce::jlimit (0, 15, m.getChannel() - 1), (value + 1.0f) * 0.5f, true });
  2878. };
  2879. const auto extra = juce::jlimit (0, maxLiveChannels, extraLiveCount.load());
  2880. if (device.target >= 0)
  2881. {
  2882. e.channel = device.target;
  2883. send();
  2884. return;
  2885. }
  2886. for (int i = -1; i < extra; ++i)
  2887. {
  2888. e.channel = i < 0 ? liveChannel.load() : extraLiveChannels[(std::size_t) i].load();
  2889. if (e.channel >= 0)
  2890. send();
  2891. }
  2892. };
  2893. if (m.isController())
  2894. {
  2895. const auto cc = m.getControllerNumber();
  2896. controllerQueue.push ({ cc, m.getChannel() - 1, m.getControllerValue(), device.port });
  2897. // FL's "Foot pedal controls note off" (round 187a [DECOMP FUN_00fdb260]): with it on, CC 64 / CC 66 hold the
  2898. // played channels' notes and don't reach the plugins
  2899. if (const auto mode = PedalHold::modeFor (cc, m.getControllerValue()); mode >= 0 && footPedalNoteOff.load (std::memory_order_relaxed))
  2900. {
  2901. const auto now = juce::Time::getMillisecondCounterHiRes();
  2902. const auto stamped = m.getTimeStamp() * 1000.0;
  2903. const auto tick = recordTickFor (std::abs (stamped - now) < 1000.0 ? stamped : now);
  2904. const auto taking = transport.recording.load() && (transport.playing.load() || isCountingIn());
  2905. auto pedal = [&] (int channel) {
  2906. pedalHold.setMode (channel, mode, [&] (int key) {
  2907. NoteEvent e;
  2908. e.source = inputSource;
  2909. e.type = NoteEvent::Type::off;
  2910. e.channel = channel;
  2911. e.key = key;
  2912. midiEvents.push (e);
  2913. logPlayedNote (channel, key, 0.0f, false, transport.playing.load() ? tick : -1.0, taking);
  2914. if (taking) // (the recorded note lasts until the pedal comes up, as in FL)
  2915. midiRecordQueue.push ({ tick, channel, key, 0.0f, false });
  2916. });
  2917. };
  2918. if (device.target >= 0)
  2919. pedal (device.target);
  2920. else
  2921. {
  2922. const auto extra = juce::jlimit (0, maxLiveChannels, extraLiveCount.load());
  2923. for (int i = -1; i < extra; ++i)
  2924. if (const auto channel = i < 0 ? liveChannel.load() : extraLiveChannels[(std::size_t) i].load(); channel >= 0)
  2925. pedal (channel);
  2926. }
  2927. return;
  2928. }
  2929. // (120…127 are channel mode messages: All Sound / Notes Off, reset…)
  2930. if (cc >= 0 && cc < 120 && (linkedCcs[(std::size_t) (cc >> 6)].load (std::memory_order_relaxed) >> (cc & 63) & 1u) == 0)
  2931. playControl (cc, (float) m.getControllerValue() / 127.0f);
  2932. return;
  2933. }
  2934. if (m.isPitchWheel())
  2935. {
  2936. playControl (NoteEvent::controlPitchBend, juce::jlimit (-1.0f, 1.0f, (float) (m.getPitchWheelValue() - 8192) / 8192.0f));
  2937. return;
  2938. }
  2939. if (m.isChannelPressure())
  2940. {
  2941. playControl (NoteEvent::controlPressure, (float) m.getChannelPressureValue() / 127.0f);
  2942. return;
  2943. }
  2944. if (m.isProgramChange()) // (round 165c: the selected channel's plugin / VFX Sequencer, as FL passes it on)
  2945. {
  2946. playControl (NoteEvent::controlProgram, (float) m.getProgramChangeNumber() / 127.0f);
  2947. return;
  2948. }
  2949. if (! m.isNoteOnOrOff())
  2950. return;
  2951. const auto on = m.isNoteOn();
  2952. markHeldKey (m.getChannel() - 1, m.getNoteNumber(), on);
  2953. markLiveNote (m.getNoteNumber(), (int) m.getVelocity(), on);
  2954. if (on)
  2955. startOnInput();
  2956. // a note-off goes to the channels and key its note-on reached (the selection or the scale snap may have
  2957. // changed while the key was down); a repeated note-on first stops what the previous one started
  2958. InputHeldNotes::Target targets[InputHeldNotes::maxTargets], stale[InputHeldNotes::maxTargets];
  2959. auto count = 0;
  2960. auto staleCount = 0;
  2961. if (on)
  2962. {
  2963. const auto key = snapInputKey (m.getNoteNumber());
  2964. const auto extra = juce::jlimit (0, maxLiveChannels, extraLiveCount.load());
  2965. // the primary selected channel, then the other selected ones (or the device's own channel)
  2966. if (device.target >= 0)
  2967. targets[count++] = { device.target, key };
  2968. else
  2969. for (int i = -1; i < extra && count < InputHeldNotes::maxTargets; ++i)
  2970. targets[count++] = { i < 0 ? liveChannel.load() : extraLiveChannels[(std::size_t) i].load(), key };
  2971. staleCount = midiHeld.noteOn (m.getNoteNumber(), targets, count, stale);
  2972. }
  2973. else
  2974. count = midiHeld.noteOff (m.getNoteNumber(), targets);
  2975. // the time the device stamped the message with (JUCE: getMillisecondCounterHiRes / 1000), not when this thread got
  2976. // to it; a stamp from elsewhere (0, another clock) falls back to now (round 170d)
  2977. const auto now = juce::Time::getMillisecondCounterHiRes();
  2978. const auto stamped = m.getTimeStamp() * 1000.0;
  2979. const auto eventMs = std::abs (stamped - now) < 1000.0 ? stamped : now;
  2980. const auto taking = transport.recording.load() && (transport.playing.load() || isCountingIn());
  2981. const auto tick = recordTickFor (eventMs);
  2982. auto push = [this, taking, tick, mpeNote, inputSource] (const InputHeldNotes::Target& t, bool noteOn, float velocity) {
  2983. NoteEvent e;
  2984. e.source = inputSource;
  2985. e.type = noteOn ? NoteEvent::Type::on : NoteEvent::Type::off;
  2986. e.channel = t.channel;
  2987. e.key = t.key;
  2988. e.velocity = velocity;
  2989. if (mpeNote != nullptr && noteOn) // issue #108: the note starts at its own bend, timbre and pressure
  2990. {
  2991. e.expression = true;
  2992. e.cents = mpeNote->cents;
  2993. e.modX = mpeNote->timbre;
  2994. e.modY = mpe::modYOfPressure (mpeNote->pressure);
  2995. }
  2996. midiEvents.push (e);
  2997. logPlayedNote (e.channel, e.key, e.velocity, noteOn, transport.playing.load() ? tick : -1.0, taking);
  2998. // (round 170d: during the count-in too; the time is the device's, against the audio clock)
  2999. if (taking && mpeNote != nullptr) // (the "on": its bend and timbre; the "off": its peak pressure)
  3000. midiRecordQueue.push ({ tick, e.channel, e.key, e.velocity, noteOn, true, mpe::finePitchOfCents (mpeNote->cents), mpeNote->timbre,
  3001. mpe::modYOfPressure (mpeNote->pressure), -1, mpeNote->cents });
  3002. else if (taking)
  3003. midiRecordQueue.push ({ tick, e.channel, e.key, e.velocity, noteOn });
  3004. if (slotTaking.load (std::memory_order_relaxed)) // a slot of the clip grid records (round 190bv)
  3005. slotRecordQueue.push ({ tick, e.channel, e.key, e.velocity, noteOn });
  3006. };
  3007. for (int i = 0; i < staleCount; ++i)
  3008. push (stale[i], false, 0.0f);
  3009. // round 190ao: a hosted instrument with its own velocity setting answers with it instead of the MIDI settings' curve
  3010. std::uint16_t ownVelocity[InputHeldNotes::maxTargets] {};
  3011. if (on)
  3012. {
  3013. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  3014. for (int i = 0; i < count; ++i)
  3015. if (targets[i].channel >= 0 && targets[i].channel < (int) channelVelocity.size())
  3016. ownVelocity[i] = channelVelocity[(std::size_t) targets[i].channel];
  3017. }
  3018. for (int i = 0; i < count; ++i)
  3019. {
  3020. // the foot pedal (round 187a): a held note struck again is released first; a note-off it holds waits for it
  3021. if (on && pedalHold.noteOn (targets[i].channel, targets[i].key))
  3022. push (targets[i], false, 0.0f);
  3023. if (! on && pedalHold.noteOff (targets[i].channel, targets[i].key))
  3024. continue;
  3025. push (targets[i], on, on ? prefs::mapPluginVelocity (m.getFloatVelocity(), ownVelocity[i] & 0xff, ownVelocity[i] >> 8, velocityCurve) : 0.0f);
  3026. }
  3027. }
  3028. std::function<juce::Array<juce::MidiDeviceInfo> (bool inputs)>& AudioEngine::midiDeviceListOverride()
  3029. {
  3030. static std::function<juce::Array<juce::MidiDeviceInfo> (bool)> lists;
  3031. return lists;
  3032. }
  3033. void AudioEngine::enableAllMidiInputs()
  3034. {
  3035. const auto& stand = midiDeviceListOverride();
  3036. const auto inputs = stand ? stand (true) : juce::MidiInput::getAvailableDevices();
  3037. const auto outputs = stand ? stand (false) : juce::MidiOutput::getAvailableDevices();
  3038. // (a device turned off in the MIDI settings is closed, so other programs can use it)
  3039. std::vector<prefs::MidiPort> available;
  3040. std::vector<std::string> open;
  3041. for (const auto& device : inputs)
  3042. {
  3043. available.push_back ({ device.identifier.toStdString(), device.name.toStdString() });
  3044. if (deviceManager.isMidiInputDeviceEnabled (device.identifier))
  3045. open.push_back (device.identifier.toStdString());
  3046. }
  3047. // round 190gh (B8): an input that was open and is no longer listed (unplugged) is closed at once
  3048. for (const auto& id : lastMidiInputIds)
  3049. if (std::none_of (available.begin(), available.end(), [&id] (const prefs::MidiPort& p) { return p.id == id; })
  3050. && deviceManager.isMidiInputDeviceEnabled (juce::String (id)))
  3051. open.push_back (id);
  3052. const auto plan = prefs::planMidiInputs (midiPrefs, available, lastMidiInputIds, open);
  3053. for (const auto* list : { &plan.close, &plan.gone })
  3054. for (const auto& id : *list)
  3055. deviceManager.setMidiInputDeviceEnabled (juce::String (id), false);
  3056. for (const auto& id : plan.reopen) // it went away and came back: the old handle may be dead
  3057. deviceManager.setMidiInputDeviceEnabled (juce::String (id), false);
  3058. for (const auto* list : { &plan.reopen, &plan.open })
  3059. for (const auto& id : *list)
  3060. deviceManager.setMidiInputDeviceEnabled (juce::String (id), true);
  3061. lastMidiInputIds.clear();
  3062. for (const auto& port : available)
  3063. lastMidiInputIds.push_back (port.id);
  3064. {
  3065. // (round 190jl: each input's source number, for the MIDI Out channels' echo guard; the outputs learn a new one
  3066. // from configureMidiOutputs, which follows every list change)
  3067. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  3068. for (const auto& port : available)
  3069. if (midiSourceNames.size() < 63 && std::find (midiSourceNames.begin(), midiSourceNames.end(), port.name) == midiSourceNames.end())
  3070. midiSourceNames.push_back (port.name);
  3071. }
  3072. // round 190gh (B8): what was plugged in or out since the last check (inputs and outputs)
  3073. std::vector<prefs::MidiPort> ports;
  3074. for (const auto& port : available)
  3075. ports.push_back ({ "in:" + port.id, port.name });
  3076. for (const auto& device : outputs)
  3077. ports.push_back ({ "out:" + device.identifier.toStdString(), device.name.toStdString() });
  3078. const auto change = prefs::diffMidiDevices (lastMidiPorts, ports);
  3079. const auto firstList = ! std::exchange (midiPortsKnown, true);
  3080. lastMidiPorts = std::move (ports);
  3081. // the devices that run a controller profile (round 190aw)
  3082. std::vector<std::string> names;
  3083. for (const auto& port : available)
  3084. names.push_back (port.name);
  3085. controllerIo.configure (midiPrefs, names, true);
  3086. if (change.changed && ! firstList)
  3087. {
  3088. ++midiDeviceListVersion;
  3089. controllerIo.devicesChanged(); // (feedback ports: an output that came back under another identifier)
  3090. configureMidiOutputs(); // (sync / notes-off / port outputs: closed when gone, opened again by name)
  3091. juce::StringArray added, removed;
  3092. for (const auto& n : change.added)
  3093. added.add (juce::String::fromUTF8 (n.c_str()));
  3094. for (const auto& n : change.removed)
  3095. removed.add (juce::String::fromUTF8 (n.c_str()));
  3096. if (onMidiDevicesChanged && (! added.isEmpty() || ! removed.isEmpty()))
  3097. onMidiDevicesChanged (added, removed);
  3098. sendChangeMessage();
  3099. }
  3100. }
  3101. void AudioEngine::setControllerSurface (controller::Surface* surface) { controllerIo.setSurface (surface); }
  3102. juce::File AudioEngine::controllerProfilesFolder() { return PluginHost::settingsFolder().getChildFile ("Controllers"); }
  3103. void AudioEngine::reloadControllerProfiles()
  3104. {
  3105. controllerIo.loadProfiles (controllerProfilesFolder());
  3106. if (midiOpen)
  3107. enableAllMidiInputs();
  3108. sendChangeMessage();
  3109. }
  3110. void AudioEngine::reconnectMidiInputs()
  3111. {
  3112. if (! midiOpen) // (only with an audio device: the real app, once its MIDI devices are open)
  3113. return;
  3114. for (const auto& device : juce::MidiInput::getAvailableDevices())
  3115. if (deviceManager.isMidiInputDeviceEnabled (device.identifier))
  3116. deviceManager.setMidiInputDeviceEnabled (device.identifier, false);
  3117. enableAllMidiInputs();
  3118. }
  3119. void AudioEngine::configureMidiOutputs()
  3120. {
  3121. std::vector<std::string> sources;
  3122. {
  3123. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  3124. sources = midiSourceNames;
  3125. }
  3126. midiSync.configure (midiPrefs, true, false, sources);
  3127. // round 190jl: the MIDI Out channels on these ports send to the devices (FL's Options › MIDI › Output "Port")
  3128. hardwareMidiPorts = midiSync.hardwarePorts();
  3129. if (rackProcessor != nullptr)
  3130. rackProcessor->getRenderer().setHardwareMidiPorts (hardwareMidiPorts);
  3131. publishRenderAheadTargets(); // (those channels render live: their notes are timed with the device's blocks)
  3132. }
  3133. void AudioEngine::setMidiPrefs (const prefs::MidiPrefs& p, bool save)
  3134. {
  3135. midiPrefs = p;
  3136. {
  3137. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  3138. midiPrefsShared = p;
  3139. }
  3140. publishRenderAheadTargets(); // (round 190gq: a MIDI input's own target channel is played live)
  3141. performanceMidiChannel.store (p.performanceChannel);
  3142. footPedalNoteOff.store (p.footPedalNoteOff);
  3143. if (! p.pickup)
  3144. pickups.clear();
  3145. if (midiOpen) // (only with an audio device: the real app, once its MIDI devices are open; they open with these)
  3146. {
  3147. enableAllMidiInputs();
  3148. configureMidiOutputs();
  3149. applyLinkPrefs();
  3150. }
  3151. if (save)
  3152. midiSettingsFile().replaceWithText (juce::String (p.toText()));
  3153. sendChangeMessage();
  3154. }
  3155. // --- Ableton Link (round 190gl) -----------------------------------------------------------------------------------
  3156. void AudioEngine::applyLinkPrefs()
  3157. {
  3158. abletonLink.setStartStopSync (midiPrefs.linkStartStopSync);
  3159. if (midiPrefs.link == abletonLink.isEnabled())
  3160. return;
  3161. if (! midiPrefs.link && abletonLink.tempoChangedByPeer())
  3162. {
  3163. // the reference DAW has one tempo: leaving the session, the project keeps the tempo a peer set last (not over
  3164. // tempo automation, which sets it anyway)
  3165. const auto session = abletonLink.sessionTempo();
  3166. if (session > 0.0 && std::abs (session - song.bpm) > 1.0e-6 && ! transport.songTempoMap.load())
  3167. editSong ([session] (Song& s) { s.bpm = session; });
  3168. }
  3169. abletonLink.setEnabled (midiPrefs.link, song.bpm);
  3170. }
  3171. void AudioEngine::setLinkEnabled (bool on)
  3172. {
  3173. if (midiPrefs.link == on && abletonLink.isEnabled() == on)
  3174. return;
  3175. auto p = midiPrefs;
  3176. p.link = on;
  3177. setMidiPrefs (p);
  3178. }
  3179. void AudioEngine::setLinkStartStopSync (bool on)
  3180. {
  3181. if (midiPrefs.linkStartStopSync == on)
  3182. return;
  3183. auto p = midiPrefs;
  3184. p.linkStartStopSync = on;
  3185. setMidiPrefs (p);
  3186. }
  3187. int AudioEngine::restretchAll()
  3188. {
  3189. // (round 190mp) the file read again and its stretched copies dropped, then the rack built anew: the copies come from
  3190. // the file as it is now (an edit made elsewhere included), at the tempo of the song now
  3191. const auto count = lynx::restretchableChannels (song);
  3192. if (count == 0)
  3193. return 0;
  3194. for (const auto& c : song.channels)
  3195. if ((c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip) && ! c.samplePath.empty()
  3196. && c.sampler.keepPitch && c.sampler.stretchBeats > 0.0f)
  3197. samples.forget (juce::String::fromUTF8 (c.samplePath.c_str()));
  3198. lastPublishedShape.song.bpm = -1.0; // (no stretched channel is kept from the last rack: each one is built again)
  3199. publishSong();
  3200. return count;
  3201. }
  3202. double AudioEngine::shownTempo() const noexcept
  3203. {
  3204. const auto session = abletonLink.isEnabled() ? abletonLink.sessionTempo() : 0.0;
  3205. return session > 0.0 ? session : song.bpm;
  3206. }
  3207. void AudioEngine::setUndoLevels (int levels)
  3208. {
  3209. maxUndoSteps = (std::size_t) prefs::clampUndoLevels (levels);
  3210. while (undoStack.size() > maxUndoSteps)
  3211. undoStack.pop_front();
  3212. }
  3213. juce::StringArray AudioEngine::getActiveMidiInputs() const
  3214. {
  3215. juce::StringArray names;
  3216. for (const auto& device : juce::MidiInput::getAvailableDevices())
  3217. if (deviceManager.isMidiInputDeviceEnabled (device.identifier))
  3218. names.add (device.name);
  3219. return names;
  3220. }
  3221. void AudioEngine::setAudioRecordingArmed (bool armed)
  3222. {
  3223. audioArmed = armed;
  3224. recordingError = {};
  3225. if (armed)
  3226. {
  3227. // opens the input of the current driver (every channel, so each insert can pick its own)
  3228. if (! hasAudioInput())
  3229. if (const auto result = openAudioInput(); result.issue != InputIssue::none)
  3230. {
  3231. recordingError = "no audio input";
  3232. notify (result.issue, 0, result.detail);
  3233. }
  3234. if (! recordThread.isThreadRunning())
  3235. recordThread.startThread();
  3236. }
  3237. sendChangeMessage();
  3238. }
  3239. void AudioEngine::setRecording (bool shouldRecord)
  3240. {
  3241. if (shouldRecord && ! transport.recording.load())
  3242. recordingError = {}; // a new attempt
  3243. transport.recording.store (shouldRecord);
  3244. liveInput.recording.store (shouldRecord);
  3245. updateRecording();
  3246. sendChangeMessage();
  3247. }
  3248. bool AudioEngine::cancelRecording()
  3249. {
  3250. if (! transport.recording.load())
  3251. return false;
  3252. // FL [DECOMP 0xf1d7e0]: the recorded-event buffers are emptied, every disk-recording take is dropped and its track
  3253. // re-armed, the record button is released; playback is not stopped. LYNX writes a take into the song as it goes, so
  3254. // the pass's edits are undone instead (one undo step per take; a step the user made while recording goes too).
  3255. updateRecording(); // (what was played up to now, and the start of this pass if the timer hasn't seen it yet)
  3256. const auto armed = armedInserts;
  3257. const auto inPass = recordPassActive && recordPassMarked; // (record on but stopped: the last pass is already kept)
  3258. discardAudioTakes = true;
  3259. setRecording (false); // (the takes close here: the notes still held are committed, the audio files deleted)
  3260. discardAudioTakes = false;
  3261. for (const auto t : armed)
  3262. if (std::find (armedInserts.begin(), armedInserts.end(), t) == armedInserts.end())
  3263. setInsertArmed (t, true);
  3264. if (inPass && ! sessionHistory)
  3265. {
  3266. const auto made = undoStack.size() + recordPassTrimmed;
  3267. const auto steps = made > recordPassUndoBase ? made - recordPassUndoBase : 0;
  3268. for (std::size_t i = 0; i < steps && ! undoStack.empty(); ++i)
  3269. {
  3270. undo();
  3271. if (! redoStack.empty())
  3272. redoStack.pop_back(); // (nothing to redo: the pass is gone)
  3273. }
  3274. }
  3275. recordPassMarked = false;
  3276. sendChangeMessage();
  3277. return true;
  3278. }
  3279. void AudioEngine::updateRecording()
  3280. {
  3281. const auto playing = transport.playing.load();
  3282. // FL's "Disarm on stop" (round 166e): the record switch goes off once playback stops after recording
  3283. if (recordSwitch.update (playing, transport.recording.load(), recordOptions.recordOffOnStop))
  3284. {
  3285. transport.recording.store (false);
  3286. liveInput.recording.store (false);
  3287. sendChangeMessage();
  3288. }
  3289. // (round 170d: a take starts with its count-in, so the notes played during it are kept)
  3290. const auto counting = isCountingIn();
  3291. const auto active = transport.recording.load() && (playing || counting);
  3292. // a recording pass starts: what Cancel recording goes back to (round 187a)
  3293. if (active && ! recordPassActive)
  3294. {
  3295. recordPassMarked = true;
  3296. recordPassUndoBase = undoStack.size();
  3297. recordPassTrimmed = 0;
  3298. }
  3299. recordPassActive = active;
  3300. // (rollup 0.1.28, REA 190hb action 3: no sleep in the middle of a take; this timer runs on the message thread)
  3301. if (active && ! awakeForRecording)
  3302. awakeForRecording = powerhints::keepAwakeBegin();
  3303. else if (! active && awakeForRecording)
  3304. powerhints::keepAwakeEnd (*std::exchange (awakeForRecording, std::nullopt));
  3305. if (playing)
  3306. lastPlayingTick = estimatedPositionNow();
  3307. else if (counting && takeCatch.start >= 0)
  3308. lastPlayingTick = (double) takeCatch.start;
  3309. // the take starts when playing with recording on, or at the first recorded event
  3310. // (which is only queued in that situation, even if this timer hasn't seen it yet)
  3311. auto beginTake = [this] (double at) {
  3312. if (recorder.isActive())
  3313. return;
  3314. const auto& pattern = std::as_const (song).activePattern();
  3315. recorder.begin (pattern.effectiveLength (song.meter()));
  3316. // Pattern mode with Loop record off (round 170e5, FL's "never" play end [DECOMP 0x11d4800]): the pattern plays
  3317. // once from the start of this pass and on past its end; the notes stay where they were played, so it grows
  3318. if (recordloop::patternLinear (song.mode, recordOptions.loopRecord))
  3319. {
  3320. const auto origin = recordloop::patternOrigin (at, pattern.effectiveLength (song.meter()));
  3321. recorder.setPatternOrigin (origin);
  3322. liveInput.patternOrigin.store (origin);
  3323. }
  3324. takeHasUndoStep = false;
  3325. takeClearedChannels.clear();
  3326. // Song mode without a loop region: while recording, the song plays on past its end until recording stops (FL,
  3327. // round 168k [EXEC]: a 1-bar song recorded from bar 1 counted on to bar 8 instead of going back to bar 1), so
  3328. // the notes stay where they were played
  3329. // (Loop record off, round 170e3: through the loop region as well)
  3330. if (recordloop::notesLinear (song.mode, song.loopPlays(), recordOptions.loopRecord))
  3331. {
  3332. noteTakeLinear = true;
  3333. recorder.setLinear (true);
  3334. updateLinearSong();
  3335. }
  3336. };
  3337. if (active)
  3338. beginTake (lastPlayingTick);
  3339. RecordedEvent e;
  3340. // FL's "Enable recording markers" (song mode): a note that starts outside the Start / Stop recording ranges is
  3341. // not recorded (its release finds no held note and is ignored too)
  3342. const auto punch = activePunch.has_value() ? std::vector<PunchRange> { *activePunch } // pre-roll / punch in-out (round 163)
  3343. : recordOptions.recordingMarkers && song.mode == PlayMode::song ? punchRanges (song.markers()) : std::vector<PunchRange> {};
  3344. auto outsidePunch = [this, &punch] (const RecordedEvent& ev) {
  3345. if (punch.empty() || ! ev.on)
  3346. return false;
  3347. auto tick = ev.tick;
  3348. if (! song.loopPlays() && ! noteTakeLinear)
  3349. tick = std::fmod (std::max (0.0, tick), (double) std::max<std::int64_t> (1, song.songLength()));
  3350. return ! inPunchRanges (punch, tick);
  3351. };
  3352. while (midiRecordQueue.pop (e))
  3353. {
  3354. if (e.lane >= 0) // (an MPE note's expression: into its held note, issue #108)
  3355. {
  3356. if (recordOptions.recordNotes)
  3357. recorder.add (song, e);
  3358. continue;
  3359. }
  3360. // (count-in notes: onto the start within the catch window, else at their real time; round 170d)
  3361. if (! recordOptions.recordNotes || ! catchEarlyNote (e, takeCatch) || outsidePunch (e)) // recording filter: notes off
  3362. continue;
  3363. beginTake (std::min (lastPlayingTick, e.tick));
  3364. recorder.add (song, e);
  3365. }
  3366. takeRecordedPluginNotes(); // GitHub #198 (round 190ks): the notes plugin windows played
  3367. for (auto ui : uiRecorded)
  3368. {
  3369. if (! recordOptions.recordNotes || ! catchEarlyNote (ui, takeCatch) || outsidePunch (ui))
  3370. continue;
  3371. beginTake (std::min (lastPlayingTick, ui.tick));
  3372. recorder.add (song, ui);
  3373. }
  3374. uiRecorded.clear();
  3375. updateAudioRecording();
  3376. takeRecordedBends();
  3377. updateAutomationRecording (active);
  3378. if (! active && recorder.isActive())
  3379. recorder.end (song, lastPlayingTick);
  3380. if (! active && ! counting)
  3381. takeCatch = {}; // the take is over: its catch with it
  3382. auto notes = recorder.takeFinished();
  3383. if (! recorder.isActive() && std::exchange (noteTakeLinear, false))
  3384. updateLinearSong();
  3385. if (! recorder.isActive() && liveInput.patternOrigin.load (std::memory_order_relaxed) >= 0.0)
  3386. liveInput.patternOrigin.store (-1.0); // the take is over: the pattern loops again
  3387. if (notes.empty())
  3388. return;
  3389. // the whole take is a single undo step: overdub or replace, quantised to the record grid; in song mode the notes
  3390. // go where they were played and a clip of the pattern is placed from the bar of the take's first note (FL; round
  3391. // 168k: they used to fold into the pattern's first bars)
  3392. const auto options = recordOptions;
  3393. editSong ([&] (Song& s) {
  3394. TakeQuantize q;
  3395. q.grid = options.quantise;
  3396. q.starts = options.quantiseStarts;
  3397. q.end = options.noteEnd;
  3398. q.stepSequencer = options.toStepSequencer;
  3399. commitNoteBatch (s, recorder, std::move (notes), options.mode, q, takeClearedChannels, options.placeSongClip, ! takeHasUndoStep);
  3400. }, ! takeHasUndoStep);
  3401. takeHasUndoStep = true;
  3402. }
  3403. void AudioEngine::launcherCommand (const launcher::Command& command)
  3404. {
  3405. if (clipLauncher == nullptr || ! song.clipGrid)
  3406. return;
  3407. using T = launcher::Command::Type;
  3408. const auto starts = command.type == T::launch || command.type == T::launchScene || command.type == T::record;
  3409. if (! transport.playing.load() && ! starts && command.type != T::backToArrangement && command.type != T::trackBackToArrangement && command.type != T::reset
  3410. && command.type != T::recordEnd) // (a recordEnd while stopped cancels a recording that never began)
  3411. return;
  3412. if (starts && song.mode != PlayMode::song) // the grid plays with the song
  3413. editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  3414. // a scene with its own tempo and bar length: the song takes them when it is launched
  3415. if (command.type == T::launchScene && command.scene >= 0 && command.scene < (int) song.clipGrid->scenes.size())
  3416. if (const auto& scene = song.clipGrid->scenes[(std::size_t) command.scene]; scene.tempo > 0.0 || scene.beatsPerBar > 0)
  3417. editSong ([tempo = scene.tempo, bar = scene.beatsPerBar, unit = scene.beatUnit] (Song& s) {
  3418. if (tempo > 0.0)
  3419. {
  3420. s.bpm = tempo;
  3421. // round 190hq (Live-exact): the scene's tempo wins over the Playlist's tempo automation / tempo
  3422. // markers until Back to Playlist
  3423. s.sceneTempoHold = tempomap::tempoAutomation (s) >= 0 || tempomap::hasTempoEvents (s);
  3424. }
  3425. if (bar > 0)
  3426. {
  3427. // round 190fg: the song takes the scene's meter as it is (6 / 8: six eighths a bar; it was 3/4)
  3428. s.beatsPerBar = bar;
  3429. s.beatUnit = session::sceneBeatUnit (unit);
  3430. }
  3431. }, false);
  3432. if (command.type == T::backToArrangement && song.sceneTempoHold) // (round 190hq: the tempo map plays again)
  3433. editSong ([] (Song& s) { s.sceneTempoHold = false; }, false);
  3434. if (starts && ! transport.playing.load() && ! isCountingIn())
  3435. {
  3436. // a recording into a slot counts in first, as the record options say (round 190bv)
  3437. if (command.type == T::record && recordOptions.countInBars > 0 && ! abletonLink.isEnabled())
  3438. transport.countIn.store ((double) countInLength (song, recordOptions.countInBars, (std::int64_t) transport.positionTicks.load()));
  3439. else
  3440. play();
  3441. sendChangeMessage();
  3442. }
  3443. clipLauncher->commands.push (command);
  3444. }
  3445. void AudioEngine::setSongWithPluginsOff (Song newSong)
  3446. {
  3447. holdPlugins();
  3448. pluginHoldOwner.store (nullptr); // (so the setSong below does not end it)
  3449. setSong (std::move (newSong));
  3450. pluginHoldOwner.store (this);
  3451. }
  3452. bool AudioEngine::pluginsOff() const { return pluginsHeld() && pluginHoldOwner.load() == this; }
  3453. std::vector<pluginhold::Use> AudioEngine::hostedPluginUses() const
  3454. {
  3455. return pluginhold::uses (song, pluginsOff() ? pluginHoldState() : pluginhold::State());
  3456. }
  3457. int AudioEngine::switchPluginOn (const std::string& id)
  3458. {
  3459. if (! pluginsOff())
  3460. return 0;
  3461. // the plugins already running keep what was set in them since the last save (a Patcher that holds one of them and
  3462. // the plugin switched on now is built again from the project)
  3463. capturePluginStates();
  3464. if (id.empty())
  3465. endPluginHold();
  3466. else
  3467. releasePlugin (id);
  3468. const auto slots = pluginhold::slotsOf (song, id);
  3469. if (! id.empty() && pluginhold::countOff (song, pluginHoldState()) == 0)
  3470. endPluginHold(); // the last one: the mode is over
  3471. if (! pluginsHeld())
  3472. pluginHoldOwner.store (nullptr);
  3473. plugins.clearLoadFailures();
  3474. // this one build creates the plugin's slots anew (they hold the silent placeholders of when it was off)
  3475. rebuildPluginId = id;
  3476. rebuildPlugins = true;
  3477. publishSong();
  3478. rebuildPlugins = false;
  3479. rebuildPluginId.clear();
  3480. return slots;
  3481. }
  3482. namespace
  3483. {
  3484. // the sample files a song's channels and effects read (the instruments that load their channel's sample, zones,
  3485. // effects with a sample): what RackState::build asks the sample provider for
  3486. std::vector<std::string> songSamplePaths (const Song& song)
  3487. {
  3488. std::vector<std::string> paths;
  3489. auto addPath = [&paths] (const std::string& p) {
  3490. if (! p.empty() && std::find (paths.begin(), paths.end(), p) == paths.end())
  3491. paths.push_back (p);
  3492. };
  3493. for (const auto& c : song.channels)
  3494. {
  3495. if (c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip || c.instrument == InstrumentKind::granulizer
  3496. || c.instrument == InstrumentKind::wavetraveller || c.instrument == InstrumentKind::fruityslicer
  3497. || c.instrument == InstrumentKind::slicex
  3498. || c.instrument == InstrumentKind::flkeys || c.instrument == InstrumentKind::directwave)
  3499. addPath (c.samplePath);
  3500. for (const auto& z : c.zones)
  3501. addPath (z.path);
  3502. }
  3503. for (const auto& track : song.mixer)
  3504. for (const auto& fx : track.effects)
  3505. addPath (fx.samplePath);
  3506. return paths;
  3507. }
  3508. // Round perfgate190id (community slice B12, the big-project gate): the samples of a song decoded in parallel (as an
  3509. // .flp import does, round 112), so the rack build that follows finds them decoded instead of decoding them one by one
  3510. // on the message thread. Keep the result alive until the song is published.
  3511. std::vector<std::shared_ptr<const SampleData>> decodeSamplesInParallel (SampleLibrary& samples, const Song& forSong)
  3512. {
  3513. std::vector<std::shared_ptr<const SampleData>> decoded;
  3514. const auto paths = songSamplePaths (forSong);
  3515. if (paths.size() < 2) // (one file: the rack build decodes it as fast)
  3516. return decoded;
  3517. const loadtrace::Scope timing ("samples_parallel");
  3518. std::atomic<std::size_t> next { 0 };
  3519. std::mutex keep;
  3520. auto worker = [&] {
  3521. for (auto i = next++; i < paths.size(); i = next++)
  3522. if (auto sample = samples.load (juce::String::fromUTF8 (paths[i].c_str())))
  3523. {
  3524. const std::scoped_lock l (keep);
  3525. decoded.push_back (std::move (sample));
  3526. }
  3527. };
  3528. const auto threads = (std::size_t) juce::jlimit (1, 6, juce::SystemStats::getNumCpus() - 1);
  3529. std::vector<std::thread> pool;
  3530. for (std::size_t i = 1; i < juce::jmin (threads, paths.size()); ++i)
  3531. pool.emplace_back (worker);
  3532. worker();
  3533. for (auto& t : pool)
  3534. t.join();
  3535. #if defined(__GLIBC__)
  3536. malloc_trim (0); // (the workers' malloc arenas keep their freed decode buffers otherwise: +27 MB on big200)
  3537. #endif
  3538. return decoded;
  3539. }
  3540. } // namespace
  3541. void AudioEngine::setSong (Song newSong)
  3542. {
  3543. // round 190ap: another project in the engine that was opened without third-party plugins: the mode ends
  3544. if (pluginHoldOwner.load() == this)
  3545. {
  3546. pluginHoldOwner.store (nullptr);
  3547. endPluginHold();
  3548. }
  3549. if (clipLauncher != nullptr)
  3550. clipLauncher->commands.push ({ launcher::Command::Type::reset });
  3551. if (araHost != nullptr) // round 190kx: another project: its own ARA documents (made again from its archives)
  3552. araHost->reset();
  3553. undoStack.clear();
  3554. redoStack.clear();
  3555. sessionUndo.clear();
  3556. sessionRedo.clear();
  3557. sessionAfterOpen = false;
  3558. song = std::move (newSong);
  3559. workSince = (double) juce::Time::currentTimeMillis();
  3560. flsettings::forgetSolos(); // (round 190bx: a solo's remembered mute states belong to the project that had it)
  3561. clipops::updateCrossfades (song);
  3562. selectedChannel = 0;
  3563. selectedChannels = { 0 };
  3564. modified = false;
  3565. checkHardwareInserts = true; // (a project measured on another setup: the notice, round 165c)
  3566. // arming isn't saved: a new project starts disarmed; its inserts' audio inputs open the device input
  3567. for (const auto t : std::vector<int> (armedInserts))
  3568. setInsertArmed (t, false);
  3569. followProjectOnDevice();
  3570. // (round perfgate190id: a .lynx with 24 one-minute takes froze the window for 5-50 s while the rack build decoded
  3571. // them one after the other into the stream cache)
  3572. const auto decoded = parallelSampleDecode ? decodeSamplesInParallel (samples, song) : std::vector<std::shared_ptr<const SampleData>> {};
  3573. publishSong();
  3574. }
  3575. bool AudioEngine::followProjectOnDevice()
  3576. {
  3577. if (prefetcher == nullptr) // (only with an audio device: the real app; see openAudioDevice)
  3578. return false;
  3579. if (! hasAudioInput() && std::any_of (song.mixer.begin(), song.mixer.end(), [] (const MixerTrack& t) { return t.inputChannel >= 0 || t.flInput >= 0; }))
  3580. openAudioInput();
  3581. // an FL project's insert inputs (REA round 157c): FL's list index on the device open now
  3582. auto changed = false;
  3583. if (hasAudioInput())
  3584. {
  3585. auto* device = deviceManager.getCurrentAudioDevice();
  3586. const auto channels = device != nullptr ? device->getInputChannelNames().size() : 0;
  3587. for (auto& t : song.mixer)
  3588. {
  3589. changed = changed || t.flInput >= 0;
  3590. if (t.flInput >= 0 && t.inputChannel < 0)
  3591. {
  3592. const auto source = flInputSource (t.flInput, channels);
  3593. t.inputChannel = source.channel;
  3594. t.inputStereo = source.stereo;
  3595. }
  3596. t.flInput = -1;
  3597. }
  3598. }
  3599. // hardware output targets and hardware inserts: their channels open with the project (the ones the device has)
  3600. openHardwareInsertIo();
  3601. return changed;
  3602. }
  3603. void AudioEngine::saveUndoStep()
  3604. {
  3605. const auto remote = nextRemoteHistoryStep;
  3606. nextRemoteHistoryStep = false;
  3607. // Dozens of edits arrive during a drag; only the first one of the click saves the state.
  3608. bool samePress = false;
  3609. const auto buttonDown = juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown();
  3610. if (gestureOpen && gestureRealMouse && ! buttonDown && ! gestureEnding)
  3611. gestureOpen = false; // (its mouseUp never came: the gesture is over)
  3612. if (gestureOpen) // (round 190jv: one step per gesture, whatever input source drives it)
  3613. {
  3614. samePress = gestureSaved;
  3615. gestureSaved = true;
  3616. lastUndoPress = buttonDown ? juce::Desktop::getInstance().getMainMouseSource().getLastMouseDownTime() : juce::Time();
  3617. }
  3618. else if (buttonDown)
  3619. {
  3620. const auto press = juce::Desktop::getInstance().getMainMouseSource().getLastMouseDownTime();
  3621. samePress = press == lastUndoPress;
  3622. lastUndoPress = press;
  3623. }
  3624. else
  3625. {
  3626. lastUndoPress = {};
  3627. gestureSaved = false;
  3628. }
  3629. const auto nowMs = juce::Time::getMillisecondCounterHiRes();
  3630. if (! samePress && tweakSkipsStep (buttonDown, nowMs)) // (round 190mv: "Undo knob tweaks" off)
  3631. samePress = true;
  3632. if (! samePress)
  3633. {
  3634. undoStack.push_back ({ song, remote });
  3635. lastPushSize = undoStack.size();
  3636. lastPushMs = nowMs;
  3637. lastPushPress = buttonDown ? juce::Desktop::getInstance().getMainMouseSource().getLastMouseDownTime() : juce::Time();
  3638. redoStack.clear();
  3639. if (undoStack.size() > maxUndoSteps)
  3640. {
  3641. undoStack.pop_front();
  3642. if (recordPassMarked)
  3643. ++recordPassTrimmed;
  3644. }
  3645. if (sessionHistory)
  3646. {
  3647. closeSessionStep();
  3648. sessionUndo.push_back ({ song, song, remote });
  3649. sessionRedo.clear();
  3650. if (sessionUndo.size() > maxUndoSteps)
  3651. sessionUndo.pop_front();
  3652. }
  3653. }
  3654. if (sessionHistory)
  3655. sessionAfterOpen = true;
  3656. }
  3657. // round 190mv (DF-134): FL's "Undo knob tweaks" off. The tweak and its edit come within one press (a drag) or one
  3658. // event (a wheel step, a click on a switch), in either order.
  3659. bool AudioEngine::tweakSkipsStep (bool buttonDown, double nowMs) const noexcept
  3660. {
  3661. if (flsettings::options().undoKnobTweaks.load() || sessionHistory)
  3662. return false;
  3663. if (buttonDown)
  3664. return tweakPress != juce::Time() && tweakPress == juce::Desktop::getInstance().getMainMouseSource().getLastMouseDownTime();
  3665. return nowMs - tweakMs < 60.0;
  3666. }
  3667. float AudioEngine::tapperMuteGain (double left, double total) noexcept
  3668. {
  3669. if (! (left > 0.0) || ! (total > 0.0))
  3670. return 1.0f;
  3671. const auto c = std::cos (juce::MathConstants<double>::halfPi * juce::jlimit (0.0, 1.0, left / total));
  3672. return (float) (0.01 + 0.99 * std::pow (c, 18.0));
  3673. }
  3674. void AudioEngine::setCurrentTrackSource (int track)
  3675. {
  3676. const auto changed = track != currentSource;
  3677. currentSource = track;
  3678. if (rackProcessor != nullptr)
  3679. rackProcessor->getRenderer().setCurrentSource (track);
  3680. // round 190my (DF-82, REA 190mv: FUN_010ff3b0 adds C's latency to its target's): a Current track with latency moves
  3681. // that latency to the newly selected track's PDC — the plan is made again (nothing to do while C adds none)
  3682. if (changed && lastPublishedShape.pdc.currentLatency > 0)
  3683. publishSong();
  3684. }
  3685. void AudioEngine::controlTweakedForUndo()
  3686. {
  3687. if (flsettings::options().undoKnobTweaks.load() || sessionHistory)
  3688. return;
  3689. const auto buttonDown = juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown();
  3690. const auto press = buttonDown ? juce::Desktop::getInstance().getMainMouseSource().getLastMouseDownTime() : juce::Time();
  3691. const auto nowMs = juce::Time::getMillisecondCounterHiRes();
  3692. tweakPress = press;
  3693. tweakMs = nowMs;
  3694. // the edit came first and saved a step for this press / event: take it back (the project stays changed)
  3695. const auto samePush = buttonDown ? (press != juce::Time() && lastPushPress == press) : (lastPushPress == juce::Time() && nowMs - lastPushMs < 60.0);
  3696. if (samePush && lastPushSize > 0 && undoStack.size() == lastPushSize)
  3697. {
  3698. undoStack.pop_back();
  3699. lastPushSize = 0;
  3700. modified = true;
  3701. sendChangeMessage(); // (the Edit menu / history show one step less)
  3702. }
  3703. }
  3704. void AudioEngine::beginUndoGesture() noexcept
  3705. {
  3706. // (a gesture that is still open lost its mouseUp: this press starts a new one)
  3707. gestureOpen = true;
  3708. gestureSaved = false;
  3709. gestureEnding = false;
  3710. gestureRealMouse = juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown();
  3711. }
  3712. void AudioEngine::endUndoGesture() noexcept
  3713. {
  3714. gestureOpen = false;
  3715. gestureSaved = false;
  3716. gestureEnding = false;
  3717. }
  3718. void AudioEngine::editSong (const std::function<void (Song&)>& edit, bool undoable)
  3719. {
  3720. if (undoable)
  3721. {
  3722. saveUndoStep();
  3723. modified = true;
  3724. }
  3725. const auto lengthsBefore = patternLengths (song);
  3726. const auto auditioned = comp::auditionedTrack (song);
  3727. const auto pluginsBefore = detachNewPluginsOn ? freshPluginCounts (song) : std::map<std::string, int>();
  3728. // LYNX's "Link Playlist tracks to mixer tracks" (rounds 190gz, 190ib): each instrument's home track and the linked
  3729. // tracks' names before the edit
  3730. const auto linkBefore = autolink::snapshot (song);
  3731. const auto namesBefore = trackmodes::linkedNames (song); // (round 190ns, issue #235: FL's audio track ⇄ mixer track)
  3732. const auto channelsBefore = song.channels.size(); // (round 190iu: Track-only mode, core/TrackOnly.h)
  3733. edit (song);
  3734. song.keepOnePattern(); // (round 190ea: what follows, and every listener, may read the current pattern)
  3735. mixerops::keepCurrentLast (song); // (round 190mv: FL's Current track stays the last mixer track)
  3736. if (trackonly::active() && song.channels.size() > channelsBefore) // each new instrument gets its own instrument track
  3737. trackonly::follow (song, channelsBefore);
  3738. trackmodes::followLinkedNames (song, namesBefore); // FL: an audio track and its mixer track keep one name and colour
  3739. if (song.linkTracksToMixer && linkBefore.on) // new content goes through its track's insert; renames follow the link
  3740. autolink::followNewContent (song, linkBefore);
  3741. if (detachNewPluginsOn)
  3742. detachNewPlugins (pluginsBefore, song);
  3743. comp::checkAudition (song, auditioned);
  3744. followPatternLengths (lengthsBefore, song);
  3745. clipops::updateCrossfades (song); // FL's automatic crossfades follow every edit (round 166e)
  3746. publishSong();
  3747. }
  3748. bool AudioEngine::setChannelAra (int channel, const std::string& pluginId, const std::string& pluginName)
  3749. {
  3750. if (channel < 0 || channel >= (int) song.channels.size() || song.channels[(std::size_t) channel].instrument != InstrumentKind::audioClip)
  3751. return false;
  3752. editSong ([&] (Song& s) {
  3753. auto& c = s.channels[(std::size_t) channel];
  3754. c.ara = pluginId.empty() ? AraLink {} : AraLink { pluginId, pluginName };
  3755. if (pluginId.empty() && ! ara::anyAraChannel (s))
  3756. s.araDocuments.clear(); // (the last one: no document is kept)
  3757. });
  3758. return true;
  3759. }
  3760. void AudioEngine::editSongPatternOrder (const std::function<void (Song&)>& edit)
  3761. {
  3762. saveUndoStep();
  3763. modified = true;
  3764. edit (song);
  3765. clipops::updateCrossfades (song);
  3766. publishSong();
  3767. }
  3768. void AudioEngine::editLevels (const std::function<void (Song&)>& edit, bool undoable)
  3769. {
  3770. // A fader or knob drag (round 171c, discussion #10): every mouse move used to go through editSong, i.e. a whole
  3771. // snapshot rebuild per move. While the song played that stalled the message thread and the fader (and the sound)
  3772. // moved in steps of ~0.2 s. Here the edit changes only levels, so the snapshot in use takes the new values through
  3773. // its live levels; the full publish follows once the mouse is released (timerCallback).
  3774. renderAheadTargets.tweaked(); // (round 190gq: the part rendered ahead hears a drag within about a block)
  3775. if (publishedLevels == nullptr || ! publishedLevels->matches (song))
  3776. {
  3777. editSong (edit, undoable);
  3778. return;
  3779. }
  3780. if (undoable)
  3781. {
  3782. saveUndoStep();
  3783. modified = true;
  3784. }
  3785. edit (song);
  3786. if (! publishedLevels->matches (song)) // (an edit that was not only levels)
  3787. {
  3788. publishSong();
  3789. return;
  3790. }
  3791. publishedLevels->store (song);
  3792. ++songStamp;
  3793. levelsPending = true;
  3794. ++levelEdits;
  3795. levelsChanged.sendChangeMessage();
  3796. }
  3797. void AudioEngine::flushLevels()
  3798. {
  3799. if (! levelsPending)
  3800. return;
  3801. levelsPending = false;
  3802. publishSong();
  3803. }
  3804. void AudioEngine::editSongStructural (const std::function<void (Song&)>& edit)
  3805. {
  3806. // (PR #37) the live plugin states go into the Song first: the undo step then holds them, and a plugin that can't be
  3807. // matched to its old instance comes back with its current settings. Round 168s: the rebuild matches channels and
  3808. // effect slots by their instance tag (RackState::build), so a moved plugin, duplicates included, keeps its running
  3809. // instance and is not built again (issue #36: no second instance created and the old one torn down for a move).
  3810. capturePluginStates();
  3811. editSong (edit);
  3812. }
  3813. void AudioEngine::closeSessionStep()
  3814. {
  3815. if (sessionAfterOpen && ! sessionUndo.empty())
  3816. sessionUndo.back().second = song;
  3817. sessionAfterOpen = false;
  3818. }
  3819. void AudioEngine::sessionStep (bool redo)
  3820. {
  3821. closeSessionStep();
  3822. auto& from = redo ? sessionRedo : sessionUndo;
  3823. auto& to = redo ? sessionUndo : sessionRedo;
  3824. if (from.empty()) return;
  3825. const auto remote = from.back().remote;
  3826. bool movementMayHaveBegun = false;
  3827. try
  3828. {
  3829. std::optional<Song> before;
  3830. if (remote)
  3831. {
  3832. before = song;
  3833. capturePluginStatesInto (*before, false);
  3834. if (remoteHistoryApiStep && ! checkRemoteHistory (from.back().deviceHash, *before)) return;
  3835. }
  3836. // Prepare the pending after-state, selective result and all conflict labels before touching either stack.
  3837. auto step = from.back();
  3838. if (remote)
  3839. {
  3840. // API calls passed the device fence; native history intentionally restores without that refusal.
  3841. // Capture this endpoint while keeping metadata for selective conflicts in the remaining entities.
  3842. auto& outgoing = redo ? step.first : step.second;
  3843. outgoing.channels = before->channels;
  3844. outgoing.mixer = before->mixer;
  3845. }
  3846. const auto& current = before ? *before : song;
  3847. std::vector<live::Key> skipped;
  3848. auto next = redo ? live::selectiveRevert (current, step.second, step.first, &skipped)
  3849. : live::selectiveRevert (current, step.first, step.second, &skipped);
  3850. const auto savedTargetHash = remote ? remoteDeviceStateHashOf (next) : juce::String();
  3851. juce::StringArray names;
  3852. for (const auto& key : skipped)
  3853. names.addIfNotAlreadyThere (juce::String::fromUTF8 (live::describe (key, song, [] (const char* s) { return tr (s).toStdString(); }).c_str()));
  3854. const auto fresh = remote ? remoteFreshTargets (*before, next) : std::unordered_set<std::uint64_t>();
  3855. const juce::ScopedValueSetter<std::unordered_set<std::uint64_t>> freshPolicy (remoteFreshInstances, fresh);
  3856. if (remoteHistoryApiStep && remoteHistoryCancelled && remoteHistoryCancelled())
  3857. {
  3858. failRemoteHistory (false);
  3859. remoteHistoryError = tr ("Remote history operation cancelled before changing history.");
  3860. return;
  3861. }
  3862. movementMayHaveBegun = true;
  3863. to.push_back (std::move (step));
  3864. from.pop_back();
  3865. sessionAfterOpen = false;
  3866. song = std::move (next);
  3867. modified = true;
  3868. lastUndoPress = {};
  3869. gestureSaved = false;
  3870. clipops::updateCrossfades (song);
  3871. levelsPending = false;
  3872. publishSong();
  3873. const auto fence = finishRemoteHistory (before);
  3874. if (remote && ! remoteHistoryFailed)
  3875. {
  3876. auto& incoming = redo ? to.back().second : to.back().first;
  3877. incoming.channels = song.channels;
  3878. incoming.mixer = song.mixer;
  3879. remote_history::acceptRestoredState (to.back(), from.empty() ? nullptr : &from.back(), savedTargetHash, fence);
  3880. }
  3881. if (! names.isEmpty() && onSessionUndoSkipped) onSessionUndoSkipped (names);
  3882. }
  3883. catch (...)
  3884. {
  3885. if (! remote) throw;
  3886. failRemoteHistory (movementMayHaveBegun);
  3887. }
  3888. }
  3889. void AudioEngine::setSessionHistory (bool on)
  3890. {
  3891. sessionHistory = on;
  3892. sessionAfterOpen = false;
  3893. sessionUndo.clear();
  3894. sessionRedo.clear();
  3895. }
  3896. void AudioEngine::applyRemote (Song remote)
  3897. {
  3898. closeSessionStep();
  3899. lastUndoPress = {}; // (a drag that goes on after this is a new step: its "before" has the remote change)
  3900. gestureSaved = false;
  3901. song = std::move (remote);
  3902. clipops::updateCrossfades (song);
  3903. publishSong();
  3904. }
  3905. void AudioEngine::historyStep (bool redo)
  3906. {
  3907. auto& from = redo ? redoStack : undoStack;
  3908. auto& to = redo ? undoStack : redoStack;
  3909. if (from.empty()) return;
  3910. const auto remote = from.back().remote;
  3911. bool movementMayHaveBegun = false;
  3912. try
  3913. {
  3914. std::optional<Song> before;
  3915. if (remote)
  3916. {
  3917. before = song;
  3918. capturePluginStatesInto (*before, false);
  3919. if (remoteHistoryApiStep && ! checkRemoteHistory (from.back().deviceHash, *before)) return;
  3920. }
  3921. const auto savedTargetHash = remote ? remoteDeviceStateHashOf (from.back().song) : juce::String();
  3922. // The model's saved blob can differ from the running vendor's normalized blob. Redo must restore the
  3923. // actual state we are leaving, captured before any history movement, rather than the stale model bytes.
  3924. std::optional<HistoryEntry> inverse;
  3925. if (remote) inverse.emplace (HistoryEntry { *before, true });
  3926. const auto fresh = remote ? remoteFreshTargets (*before, from.back().song) : std::unordered_set<std::uint64_t>();
  3927. const juce::ScopedValueSetter<std::unordered_set<std::uint64_t>> freshPolicy (remoteFreshInstances, fresh);
  3928. if (remoteHistoryApiStep && remoteHistoryCancelled && remoteHistoryCancelled())
  3929. {
  3930. failRemoteHistory (false);
  3931. remoteHistoryError = tr ("Remote history operation cancelled before changing history.");
  3932. return;
  3933. }
  3934. // Moving song into a temporary may already change the live model even if push_back throws.
  3935. movementMayHaveBegun = true;
  3936. if (remote) to.push_back (std::move (*inverse));
  3937. else to.push_back ({ std::move (song), false });
  3938. song = std::move (from.back().song);
  3939. from.pop_back();
  3940. comp::setAudition (song, -1); // an old history state must not resume a comp audition
  3941. modified = true;
  3942. levelsPending = false;
  3943. lastUndoPress = {};
  3944. gestureSaved = false;
  3945. publishSong();
  3946. const auto fence = finishRemoteHistory (before);
  3947. if (remote && ! remoteHistoryFailed)
  3948. remote_history::acceptRestoredState (to.back(), from.empty() ? nullptr : &from.back(),
  3949. savedTargetHash, fence);
  3950. }
  3951. catch (...)
  3952. {
  3953. if (! remote) throw;
  3954. failRemoteHistory (movementMayHaveBegun);
  3955. }
  3956. }
  3957. void AudioEngine::undo()
  3958. {
  3959. remoteHistoryFailed = false;
  3960. remoteHistoryUncertain = false;
  3961. remoteHistoryError.clear();
  3962. remoteHistoryCode = "changed";
  3963. if (sessionHistory) sessionStep (false); else historyStep (false);
  3964. }
  3965. void AudioEngine::redo()
  3966. {
  3967. remoteHistoryFailed = false;
  3968. remoteHistoryUncertain = false;
  3969. remoteHistoryError.clear();
  3970. remoteHistoryCode = "changed";
  3971. if (sessionHistory) sessionStep (true); else historyStep (true);
  3972. }
  3973. namespace
  3974. {
  3975. template <typename Entries>
  3976. const Song& historyState (const Entries& undo, const Song& current, const Entries& redo, int index)
  3977. {
  3978. if (index < (int) undo.size())
  3979. return undo[(std::size_t) index].song;
  3980. if (index == (int) undo.size())
  3981. return current;
  3982. return redo[redo.size() - 1 - (std::size_t) (index - (int) undo.size() - 1)].song;
  3983. }
  3984. } // namespace
  3985. ChangeLabel AudioEngine::getHistoryLabel (int index) const
  3986. {
  3987. if (index <= 0 || index >= getHistorySize())
  3988. return { TR_NOOP ("Start"), {} };
  3989. if (sessionHistory) // (a live session: one's own steps, each named by its own before / after)
  3990. {
  3991. const auto i = (std::size_t) index - 1;
  3992. const auto& step = i < sessionUndo.size() ? sessionUndo[i] : sessionRedo[sessionRedo.size() - 1 - (i - sessionUndo.size())];
  3993. return describeChange (step.first, i + 1 == sessionUndo.size() && sessionAfterOpen ? song : step.second);
  3994. }
  3995. return describeChange (historyState (undoStack, song, redoStack, index - 1), historyState (undoStack, song, redoStack, index));
  3996. }
  3997. void AudioEngine::jumpToHistory (int index)
  3998. {
  3999. index = juce::jlimit (0, getHistorySize() - 1, index);
  4000. if (index == getHistoryPosition())
  4001. return;
  4002. if (sessionHistory)
  4003. {
  4004. while (getHistoryPosition() != index)
  4005. {
  4006. const auto previous = getHistoryPosition();
  4007. if (previous > index) undo(); else redo();
  4008. if (remoteHistoryFailed || getHistoryPosition() == previous) return;
  4009. }
  4010. return;
  4011. }
  4012. bool remote = false;
  4013. const auto position = getHistoryPosition();
  4014. if (index < position)
  4015. for (int i = index; i < position; ++i) remote = remote || undoStack[(std::size_t) i].remote;
  4016. else
  4017. for (int i = 0; i < index - position; ++i) remote = remote || redoStack[redoStack.size() - 1 - (std::size_t) i].remote;
  4018. if (remote)
  4019. {
  4020. while (getHistoryPosition() > index)
  4021. {
  4022. const auto previous = getHistoryPosition();
  4023. undo();
  4024. if (remoteHistoryFailed || getHistoryPosition() == previous) return;
  4025. }
  4026. while (getHistoryPosition() < index)
  4027. {
  4028. const auto previous = getHistoryPosition();
  4029. redo();
  4030. if (remoteHistoryFailed || getHistoryPosition() == previous) return;
  4031. }
  4032. return;
  4033. }
  4034. // move through the stacks, then publish once
  4035. while (getHistoryPosition() > index && ! undoStack.empty())
  4036. {
  4037. redoStack.push_back ({ std::move (song), undoStack.back().remote });
  4038. song = std::move (undoStack.back().song);
  4039. undoStack.pop_back();
  4040. }
  4041. while (getHistoryPosition() < index && ! redoStack.empty())
  4042. {
  4043. undoStack.push_back ({ std::move (song), redoStack.back().remote });
  4044. song = std::move (redoStack.back().song);
  4045. redoStack.pop_back();
  4046. }
  4047. modified = true;
  4048. lastUndoPress = {};
  4049. gestureSaved = false;
  4050. levelsPending = false;
  4051. publishSong();
  4052. }
  4053. void AudioEngine::setSelectedChannel (int channel)
  4054. {
  4055. channel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), channel);
  4056. setChannelSelection ({ channel }, channel);
  4057. }
  4058. void AudioEngine::setChannelSelection (std::vector<int> channels, int primary)
  4059. {
  4060. const auto count = (int) song.channels.size();
  4061. std::sort (channels.begin(), channels.end());
  4062. channels.erase (std::unique (channels.begin(), channels.end()), channels.end());
  4063. channels.erase (std::remove_if (channels.begin(), channels.end(), [count] (int c) { return c < 0 || c >= count; }), channels.end());
  4064. primary = juce::jlimit (0, juce::jmax (0, count - 1), primary);
  4065. if (std::find (channels.begin(), channels.end(), primary) == channels.end())
  4066. channels.insert (std::lower_bound (channels.begin(), channels.end(), primary), primary);
  4067. if (channels == selectedChannels && primary == selectedChannel)
  4068. {
  4069. publishSelection();
  4070. return;
  4071. }
  4072. selectedChannels = std::move (channels);
  4073. selectedChannel = primary;
  4074. publishSelection();
  4075. sendChangeMessage();
  4076. }
  4077. void AudioEngine::publishSelection()
  4078. {
  4079. liveChannel.store (selectedChannel);
  4080. int extra = 0;
  4081. for (auto c : selectedChannels)
  4082. if (c != selectedChannel && extra < maxLiveChannels)
  4083. extraLiveChannels[(std::size_t) extra++].store (c);
  4084. extraLiveCount.store (extra);
  4085. publishRenderAheadTargets();
  4086. }
  4087. // Render-ahead (round 190gq, core/RenderAhead.h): the channels notes are played into live stay real-time — the selected
  4088. // channels (the typing keyboard, a MIDI input on "the selected channels"), each MIDI input's own target channel, the
  4089. // channels locked to a MIDI input ("Receive notes from")
  4090. void AudioEngine::publishRenderAheadTargets()
  4091. {
  4092. std::array<int, renderahead::Targets::maxChannels> channels {};
  4093. int count = 0;
  4094. auto add = [&] (int c) {
  4095. if (c < 0 || count >= (int) channels.size() || std::find (channels.begin(), channels.begin() + count, c) != channels.begin() + count)
  4096. return;
  4097. channels[(std::size_t) count++] = c;
  4098. };
  4099. add (selectedChannel);
  4100. for (const auto c : selectedChannels)
  4101. add (c);
  4102. for (const auto& input : midiPrefs.inputs)
  4103. if (input.enabled)
  4104. add (input.target);
  4105. for (std::size_t c = 0; c < song.channels.size(); ++c)
  4106. if (! song.channels[c].receiveFrom.empty())
  4107. add ((int) c);
  4108. // round 190jl: a MIDI Out channel (or a plugin's output port) that sends to a hardware MIDI output
  4109. if ((hardwareMidiPorts[0] | hardwareMidiPorts[1] | hardwareMidiPorts[2] | hardwareMidiPorts[3]) != 0)
  4110. for (std::size_t c = 0; c < song.channels.size(); ++c)
  4111. {
  4112. const auto& ch = song.channels[c];
  4113. const auto port = ch.instrument == InstrumentKind::midiOut ? midiout::stateOf (ch.pluginState).port
  4114. : ch.instrument == InstrumentKind::plugin ? ch.plugin.midiOutPort : -1;
  4115. if (port >= 0 && port < 256 && (hardwareMidiPorts[(std::size_t) port >> 6] >> (port & 63) & 1u) != 0)
  4116. add ((int) c);
  4117. }
  4118. // hosted plugin editors on screen: their channel or insert
  4119. std::array<int, renderahead::Targets::maxTracks> tracks {};
  4120. int trackCount = 0;
  4121. for (const auto& e : openEditors)
  4122. {
  4123. if (e.track >= 0 && trackCount < (int) tracks.size())
  4124. tracks[(std::size_t) trackCount++] = e.track;
  4125. if (e.find)
  4126. if (const auto* ref = e.find (song))
  4127. for (std::size_t c = 0; c < song.channels.size(); ++c)
  4128. if (&song.channels[c].plugin == ref)
  4129. add ((int) c);
  4130. }
  4131. renderAheadTargets.publish (channels.data(), count, tracks.data(), trackCount);
  4132. publishOwnNoteChannels(); // (round 190ks: the same editors)
  4133. }
  4134. // GitHub #198 (round 190ks): the channels whose hosted plugin's window is open — what it plays from there is recorded
  4135. // (core/RackRenderer.h ownNotes). Their channel index is looked up at each publish, as the render-ahead's.
  4136. void AudioEngine::publishOwnNoteChannels()
  4137. {
  4138. std::array<std::uint64_t, RackRenderer::ownNoteWords> mask {};
  4139. for (const auto& e : openEditors)
  4140. if (e.track < 0 && e.find)
  4141. if (const auto* ref = e.find (song))
  4142. for (std::size_t c = 0; c < song.channels.size() && c < (std::size_t) RackRenderer::maxChannels; ++c)
  4143. if (&song.channels[c].plugin == ref && song.channels[c].instrument == InstrumentKind::plugin
  4144. && song.channels[c].plugin.recordOwnNotes)
  4145. mask[c >> 6] |= std::uint64_t { 1 } << (c & 63);
  4146. if (mask == ownNoteChannels)
  4147. return;
  4148. ownNoteChannels = mask;
  4149. if (rackProcessor != nullptr)
  4150. rackProcessor->getRenderer().setOwnNoteChannels (ownNoteChannels);
  4151. }
  4152. void AudioEngine::takePluginNotes (int done) noexcept
  4153. {
  4154. if (rackProcessor == nullptr)
  4155. return;
  4156. auto& rack = rackProcessor->getRenderer();
  4157. const auto count = rack.takeOwnNotes (ownNotesTaken.data(), (int) ownNotesTaken.size());
  4158. if (count == 0)
  4159. return;
  4160. // (as a played note: a take while recording and playing or counting in; a clip slot that records)
  4161. const auto take = transport.recording.load (std::memory_order_relaxed)
  4162. && (transport.playing.load (std::memory_order_relaxed) || isCountingIn());
  4163. const auto slot = slotTaking.load (std::memory_order_relaxed);
  4164. if (! take && ! slot)
  4165. return;
  4166. const auto clock = liveClock();
  4167. const auto rate = juce::jmax (1.0, transport.sampleRate.load (std::memory_order_relaxed));
  4168. for (int k = 0; k < count; ++k)
  4169. {
  4170. const auto& o = ownNotesTaken[(std::size_t) k];
  4171. // the click reached the plugin by this block: recorded where the song was heard then, as a played note
  4172. const auto eventMs = clock.timeMs + 1000.0 * (double) (done + o.sample) / rate;
  4173. PluginRecorded r;
  4174. r.event = { recordTickFor (eventMs), (int) o.channel, (int) o.key, o.velocity, o.velocity > 0.0f };
  4175. r.take = take;
  4176. r.slot = slot;
  4177. pluginRecordQueue.push (r);
  4178. }
  4179. }
  4180. void AudioEngine::takeRecordedPluginNotes()
  4181. {
  4182. PluginRecorded r;
  4183. while (pluginRecordQueue.pop (r))
  4184. {
  4185. if (r.take)
  4186. uiRecorded.push_back (r.event); // (with the typing keyboard's: the same filter, punch and count-in catch)
  4187. if (r.slot)
  4188. uiSlotRecorded.push_back (r.event);
  4189. }
  4190. }
  4191. namespace
  4192. {
  4193. // Whether a drive / network share is there, within a time limit: a disconnected network drive can block a file
  4194. // query for half a minute, and an open probes many paths under the same root (round 112). One probe per root per open.
  4195. bool rootReachable (const std::string& root)
  4196. {
  4197. auto result = std::make_shared<std::atomic<int>> (-1);
  4198. std::thread ([result, root] {
  4199. result->store (platform::localFile (root).isDirectory() ? 1 : 0); // FL's "C:\" spelling on macOS/Linux too
  4200. }).detach();
  4201. const auto started = juce::Time::getMillisecondCounter();
  4202. while (result->load() < 0 && juce::Time::getMillisecondCounter() - started < 2000)
  4203. juce::Thread::sleep (2);
  4204. return result->load() == 1; // still unknown after 2 s: treated as missing (the probe thread finishes on its own)
  4205. }
  4206. std::string userOf (const Song& song, std::size_t track)
  4207. {
  4208. return song.mixer[track].name.empty() ? (track == 0 ? std::string ("Master") : "Insert " + std::to_string (track)) : song.mixer[track].name;
  4209. }
  4210. } // namespace
  4211. namespace
  4212. {
  4213. // Round 190fn (O1): the FL Studio Mobile resources folders of Settings › Files (flm-resources.txt, one per line), each
  4214. // taken down to the folder "@R@" paths start from; only folders that exist.
  4215. std::vector<std::string> flmResourceFolders()
  4216. {
  4217. std::vector<std::string> out;
  4218. const auto file = PluginHost::settingsFolder().getChildFile ("flm-resources.txt");
  4219. if (! file.existsAsFile())
  4220. return out;
  4221. juce::StringArray lines;
  4222. lines.addLines (file.loadFileAsString());
  4223. const auto exists = [] (const std::string& p) { return platform::localFile (p).exists(); };
  4224. for (auto line : lines)
  4225. {
  4226. line = line.trim();
  4227. if (line.isEmpty() || ! platform::localFile (line.toStdString()).isDirectory())
  4228. continue;
  4229. out.push_back (flmResourceRootFrom (line.toStdString(), exists));
  4230. }
  4231. return out;
  4232. }
  4233. // Where a Live set's library-relative samples live (Core Library, packs, User Library), newest install first; only
  4234. // folders that exist. Read-only: nothing is ever written there.
  4235. std::vector<std::string> liveLibraryRoots()
  4236. {
  4237. std::vector<std::string> roots;
  4238. auto add = [&roots] (const juce::File& f) {
  4239. if (f.isDirectory())
  4240. roots.push_back (f.getFullPathName().toStdString());
  4241. };
  4242. #if JUCE_WINDOWS
  4243. const juce::File programData ("C:\\ProgramData\\Ableton");
  4244. #elif JUCE_MAC
  4245. const juce::File programData ("/Applications");
  4246. #else
  4247. const juce::File programData;
  4248. #endif
  4249. if (programData.isDirectory())
  4250. {
  4251. auto installs = programData.findChildFiles (juce::File::findDirectories, false, "Live*");
  4252. std::sort (installs.begin(), installs.end(), [] (const juce::File& a, const juce::File& b) { return a.getFileName() > b.getFileName(); });
  4253. for (const auto& install : installs)
  4254. {
  4255. add (install.getChildFile ("Resources").getChildFile ("Core Library"));
  4256. add (install.getChildFile ("Contents").getChildFile ("App-Resources").getChildFile ("Core Library"));
  4257. }
  4258. }
  4259. const auto docs = juce::File::getSpecialLocation (juce::File::userDocumentsDirectory).getChildFile ("Ableton");
  4260. add (docs.getChildFile ("User Library"));
  4261. add (docs.getChildFile ("Factory Packs"));
  4262. const auto music = juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("Ableton");
  4263. add (music.getChildFile ("User Library"));
  4264. add (music.getChildFile ("Factory Packs"));
  4265. return roots;
  4266. }
  4267. } // namespace
  4268. void AudioEngine::prepareFlpImport (const juce::File& file, const std::map<std::string, std::string>& relocations, SampleLibrary& library,
  4269. PreparedFlp& out)
  4270. {
  4271. juce::MemoryBlock data;
  4272. // a GarageBand project (round 190ic): a .band package folder, read file by file by its import
  4273. const auto bandFolder = ProjectPackage::garageBandPackage (file);
  4274. {
  4275. const loadtrace::Scope timing ("read_project");
  4276. if (bandFolder == juce::File() && ! file.loadFileAsData (data))
  4277. {
  4278. out.error = utf8 ("could not read the file");
  4279. return;
  4280. }
  4281. }
  4282. try
  4283. {
  4284. loadtrace::stage (0.20, 0.30, TR_NOOP ("Reading the project..."));
  4285. const auto started = std::chrono::steady_clock::now();
  4286. const auto* fileBytes = static_cast<const std::uint8_t*> (data.getData());
  4287. // a Live set (.als, round 175a) takes the same pipeline: samples, plugins, report and Missing files window
  4288. const auto liveSet = file.hasFileExtension ("als");
  4289. // an FL Studio Mobile project (.flm, .songtmpl; round 182c) too
  4290. const auto mobileProject = file.hasFileExtension ("flm;songtmpl");
  4291. const auto garageBand = bandFolder != juce::File();
  4292. // a DAWproject (.dawproject, round 190jf B22) too
  4293. const auto dawProject = file.hasFileExtension ("dawproject");
  4294. // a BandLab project (.blx, round 190jr): its revision JSON, the samples beside it
  4295. const auto bandLab = file.hasFileExtension ("blx");
  4296. std::optional<flp::Project> project;
  4297. if (! liveSet && ! mobileProject && ! garageBand && ! dawProject && ! bandLab)
  4298. project = flp::parseProject ({ fileBytes, data.getSize() });
  4299. loadtrace::add ("parse", loadtrace::msSince (started));
  4300. FlpImportOptions options;
  4301. options.roots = findFlStudioRoots();
  4302. options.projectFolder = file.getParentDirectory().getFullPathName().toStdString();
  4303. options.flmResourceRoots = flmResourceFolders(); // round 190fn (O1): FL Studio Mobile Rack generators in an .flp
  4304. // samples on a drive that is not there (unplugged external drive, dead network share): one probe per root
  4305. auto roots = std::make_shared<loadtrace::RootProbe> ([] (const std::string& root) {
  4306. const auto t = std::chrono::steady_clock::now();
  4307. const auto ok = rootReachable (root);
  4308. loadtrace::add ("probe_root", loadtrace::msSince (t));
  4309. return ok;
  4310. });
  4311. options.fileExists = [roots] (const std::string& path) {
  4312. if (! roots->rootAvailable (path))
  4313. return false;
  4314. const auto t = std::chrono::steady_clock::now();
  4315. const auto exists = platform::localFile (path).existsAsFile();
  4316. loadtrace::add ("probe_file", loadtrace::msSince (t));
  4317. return exists;
  4318. };
  4319. options.readFile = [roots] (const std::string& path) {
  4320. if (! roots->rootAvailable (path))
  4321. return std::vector<std::uint8_t> {};
  4322. const auto t = std::chrono::steady_clock::now();
  4323. juce::MemoryBlock data;
  4324. platform::localFile (path).loadFileAsData (data);
  4325. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  4326. loadtrace::add ("read_aux_file", loadtrace::msSince (t));
  4327. return std::vector<std::uint8_t> (bytes, bytes + data.getSize());
  4328. };
  4329. auto decoded = std::make_shared<std::vector<std::shared_ptr<const SampleData>>>();
  4330. options.sampleFrames = [&library, decoded] (const std::string& path) -> std::int64_t {
  4331. const auto sample = library.load (juce::String::fromUTF8 (path.c_str()));
  4332. if (sample != nullptr)
  4333. decoded->push_back (sample); // kept: the rack uses it next (it was decoded twice before)
  4334. return sample != nullptr ? (std::int64_t) sample->frames() : 0;
  4335. };
  4336. options.sampleSeconds = [&library, decoded] (const std::string& path) -> double {
  4337. const auto sample = library.load (juce::String::fromUTF8 (path.c_str()));
  4338. if (sample == nullptr || sample->sampleRate <= 0.0)
  4339. return 0.0;
  4340. decoded->push_back (sample);
  4341. return (double) sample->frames() / sample->sampleRate;
  4342. };
  4343. // WAV that only exists inside the .flp (Slicex): goes to %APPDATA%\LYNX\flp-embedded, keyed by content
  4344. options.saveEmbedded = [] (const std::vector<std::uint8_t>& wav, const std::string& name) -> std::string {
  4345. const auto folder = PluginHost::settingsFolder().getChildFile ("flp-embedded");
  4346. folder.createDirectory();
  4347. const auto hash = juce::String::toHexString ((juce::int64) juce::DefaultHashFunctions::generateHash (
  4348. juce::String::createStringFromData (wav.data(), (int) std::min<std::size_t> (wav.size(), 65536)) + juce::String ((juce::int64) wav.size()),
  4349. 0x7FFFFFFF));
  4350. const auto file = folder.getChildFile (juce::File::createLegalFileName (juce::String::fromUTF8 (name.c_str())) + "-" + hash + ".wav");
  4351. if (! file.existsAsFile() && ! file.replaceWithData (wav.data(), wav.size()))
  4352. return {};
  4353. return file.getFullPathName().toStdString();
  4354. };
  4355. out.report = {};
  4356. options.report = &out.report;
  4357. options.relocations = relocations;
  4358. {
  4359. const auto t = std::chrono::steady_clock::now();
  4360. if (mobileProject)
  4361. {
  4362. FlmImportOptions flmOptions;
  4363. flmOptions.common = options;
  4364. if (! options.roots.factoryData.empty())
  4365. if (const auto root = flmResourceRootIn (options.roots.factoryData); platform::localFile (root).isDirectory())
  4366. flmOptions.resourceRoot = root;
  4367. // round 190fn (O1): the user's own FL Studio Mobile "Resources" folders (Settings › Files), searched first
  4368. flmOptions.userResourceRoots = options.flmResourceRoots;
  4369. std::string flmError;
  4370. auto song = importFlm (std::vector<std::uint8_t> (fileBytes, fileBytes + data.getSize()), flmOptions, &flmError);
  4371. if (! song)
  4372. {
  4373. out.error = utf8 (flmError.empty() ? "not a readable FL Studio Mobile project" : flmError.c_str());
  4374. return;
  4375. }
  4376. out.song = std::move (*song);
  4377. }
  4378. else if (garageBand)
  4379. {
  4380. BandImportOptions bandOptions;
  4381. bandOptions.common = options;
  4382. bandOptions.packageFolder = bandFolder.getFullPathName().toStdString();
  4383. std::string bandError;
  4384. auto song = importBandPackage (bandOptions, &bandError);
  4385. if (! song)
  4386. {
  4387. out.error = utf8 (bandError.empty() ? "not a readable GarageBand project" : bandError.c_str());
  4388. return;
  4389. }
  4390. out.song = std::move (*song);
  4391. }
  4392. else if (dawProject)
  4393. {
  4394. DawProjectImportOptions dawOptions;
  4395. dawOptions.common = options;
  4396. // LYNX's own devices with every field (the project file's JSON); a file from the core writer still opens
  4397. dawOptions.nativeInstrument = [] (const std::string&, const std::vector<std::uint8_t>& bytes) -> std::optional<ChannelDef> {
  4398. if (auto c = ProjectFile::channelFromStateBytes (bytes))
  4399. return c;
  4400. if (const auto preset = genpresets::fromText (std::string (bytes.begin(), bytes.end())))
  4401. return genpresets::newChannel (*preset);
  4402. return std::nullopt;
  4403. };
  4404. dawOptions.nativeEffect = [] (const std::string&, const std::vector<std::uint8_t>& bytes) -> std::optional<EffectSlot> {
  4405. if (auto e = ProjectFile::effectFromStateBytes (bytes))
  4406. return e;
  4407. return dawproject::effectFromStateText (std::string (bytes.begin(), bytes.end()));
  4408. };
  4409. std::string dawError;
  4410. auto song = importDawProject (std::vector<std::uint8_t> (fileBytes, fileBytes + data.getSize()), dawOptions, &dawError);
  4411. if (! song)
  4412. {
  4413. out.error = utf8 (dawError.empty() ? "not a readable DAWproject file" : dawError.c_str());
  4414. return;
  4415. }
  4416. out.song = std::move (*song);
  4417. }
  4418. else if (bandLab)
  4419. {
  4420. BlxImportOptions blxOptions;
  4421. blxOptions.common = options;
  4422. const auto folder = file.getParentDirectory();
  4423. blxOptions.folder = folder.getFullPathName().toStdString();
  4424. // the files beside the .blx (its Audio / MIDI folders), for the samples by id or name; a .blx left in a
  4425. // big folder (Downloads, the Desktop) is not walked past a few thousand files
  4426. {
  4427. juce::RangedDirectoryIterator it (folder, true, "*", juce::File::findFiles);
  4428. int seen = 0;
  4429. for (const auto& entry : it)
  4430. {
  4431. if (++seen > 5000)
  4432. break;
  4433. blxOptions.files.push_back (entry.getFile().getRelativePathFrom (folder).replaceCharacter ('\\', '/').toStdString());
  4434. }
  4435. }
  4436. std::string blxError;
  4437. auto song = importBlxBytes (std::vector<std::uint8_t> (fileBytes, fileBytes + data.getSize()), blxOptions, &blxError);
  4438. if (! song)
  4439. {
  4440. out.error = utf8 (blxError.empty() ? "not a readable BandLab project" : blxError.c_str());
  4441. return;
  4442. }
  4443. if (song->info.title.empty())
  4444. song->info.title = file.getFileNameWithoutExtension().toStdString();
  4445. out.song = std::move (*song);
  4446. }
  4447. else if (liveSet)
  4448. {
  4449. AlsImportOptions alsOptions;
  4450. alsOptions.common = options;
  4451. alsOptions.libraryRoots = liveLibraryRoots();
  4452. alsOptions.sessionOnPlaylist = alsSessionOnPlaylist.load();
  4453. std::string alsError;
  4454. auto song = importAls (std::vector<std::uint8_t> (fileBytes, fileBytes + data.getSize()), alsOptions, &alsError);
  4455. if (! song)
  4456. {
  4457. out.error = utf8 (alsError.empty() ? "not a readable Live set" : alsError.c_str());
  4458. return;
  4459. }
  4460. out.song = std::move (*song);
  4461. }
  4462. else
  4463. {
  4464. out.song = importFlp (*project, options);
  4465. }
  4466. loadtrace::add ("import", loadtrace::msSince (t));
  4467. }
  4468. loadtrace::add ("missing_roots", 0.0, (int) roots->missingRoots().size());
  4469. loadtrace::add ("probe_skipped", 0.0, roots->skipped());
  4470. // the project's third-party plugins, to say which channel/insert used each one that is missing
  4471. for (const auto& c : out.song.channels)
  4472. if (c.plugin.foreign.format != ForeignPlugin::Format::none)
  4473. out.uses.push_back ({ c.plugin.foreign.name, c.name, true });
  4474. for (std::size_t t = 0; t < out.song.mixer.size(); ++t)
  4475. for (const auto& fx : out.song.mixer[t].effects)
  4476. if (fx.kind == EffectKind::plugin && fx.plugin.foreign.format != ForeignPlugin::Format::none)
  4477. out.uses.push_back ({ fx.plugin.foreign.name, userOf (out.song, t), false });
  4478. // (and the ones inside Patchers, REA_rodada141)
  4479. std::function<void (const PatcherDoc&, const std::string&)> patcherUses = [&] (const PatcherDoc& doc, const std::string& user) {
  4480. for (const auto& n : doc.nodes)
  4481. {
  4482. const auto& ref = n.generator ? n.channel.plugin : n.effect.plugin;
  4483. if (ref.foreign.format != ForeignPlugin::Format::none)
  4484. out.uses.push_back ({ ref.foreign.name, user + " (Patcher)", n.generator });
  4485. if (n.generator && n.channel.instrument == InstrumentKind::patcher)
  4486. patcherUses (n.channel.patcher, user);
  4487. if (! n.generator && n.effect.kind == EffectKind::patcher)
  4488. patcherUses (n.effect.patcher, user);
  4489. }
  4490. };
  4491. for (const auto& c : out.song.channels)
  4492. if (c.instrument == InstrumentKind::patcher)
  4493. patcherUses (c.patcher, c.name);
  4494. for (std::size_t t = 0; t < out.song.mixer.size(); ++t)
  4495. for (const auto& fx : out.song.mixer[t].effects)
  4496. if (fx.kind == EffectKind::patcher)
  4497. patcherUses (fx.patcher, userOf (out.song, t));
  4498. // the samples, decoded now (in parallel, off the message thread) so building the rack only finds them ready
  4499. std::vector<std::string> paths;
  4500. auto addPath = [&paths] (const std::string& p) {
  4501. if (! p.empty() && std::find (paths.begin(), paths.end(), p) == paths.end())
  4502. paths.push_back (p);
  4503. };
  4504. for (const auto& c : out.song.channels)
  4505. {
  4506. if (c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip || c.instrument == InstrumentKind::granulizer
  4507. || c.instrument == InstrumentKind::wavetraveller || c.instrument == InstrumentKind::fruityslicer
  4508. || c.instrument == InstrumentKind::slicex
  4509. || c.instrument == InstrumentKind::flkeys || c.instrument == InstrumentKind::directwave)
  4510. addPath (c.samplePath);
  4511. for (const auto& z : c.zones)
  4512. addPath (z.path);
  4513. }
  4514. for (const auto& track : out.song.mixer)
  4515. for (const auto& fx : track.effects)
  4516. addPath (fx.samplePath);
  4517. loadtrace::stage (0.30, 0.55, TR_NOOP ("Reading the samples..."), TR_NOOP ("Reading {0}... {1}/{2}"));
  4518. const auto decodeStarted = std::chrono::steady_clock::now();
  4519. std::atomic<std::size_t> next { 0 }, done { 0 };
  4520. std::mutex keep;
  4521. auto worker = [&] {
  4522. for (auto i = next++; i < paths.size(); i = next++)
  4523. {
  4524. const auto t = std::chrono::steady_clock::now();
  4525. auto sample = library.load (juce::String::fromUTF8 (paths[i].c_str()));
  4526. loadtrace::add ("sample_decode", loadtrace::msSince (t));
  4527. {
  4528. const std::scoped_lock l (keep);
  4529. if (sample != nullptr)
  4530. out.decoded.push_back (std::move (sample));
  4531. }
  4532. const auto n = ++done;
  4533. loadtrace::step ((int) n, (int) paths.size(),
  4534. juce::File::createFileWithoutCheckingPath (juce::String::fromUTF8 (paths[i].c_str())).getFileName().toStdString());
  4535. }
  4536. };
  4537. const auto threads = (std::size_t) juce::jlimit (1, 6, juce::SystemStats::getNumCpus() - 1);
  4538. std::vector<std::thread> pool;
  4539. for (std::size_t i = 1; i < juce::jmin (threads, paths.size()); ++i)
  4540. pool.emplace_back (worker);
  4541. worker();
  4542. for (auto& t : pool)
  4543. t.join();
  4544. for (auto& d : *decoded)
  4545. out.decoded.push_back (std::move (d));
  4546. // pitch-preserving stretch (audio clips that follow the tempo): the stretched copy too, in parallel, with the
  4547. // same ratio the rack asks for (RackState::build) — it was computed on the message thread while building
  4548. struct Stretch
  4549. {
  4550. std::string path;
  4551. double ratio;
  4552. StretchMethod method;
  4553. double semitones;
  4554. StretchMap map;
  4555. std::string variant; // non-empty: the precomputed span is stretched (RackRenderer, round 180d)
  4556. std::shared_ptr<const SampleData> span;
  4557. StretchOptions options; // (round 190fm)
  4558. };
  4559. std::vector<Stretch> stretches;
  4560. for (const auto& c : out.song.channels)
  4561. if ((c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip) && c.zones.empty() && ! c.samplePath.empty()
  4562. && c.sampler.keepPitch && c.sampler.stretchBeats > 0.0f)
  4563. if (const auto data = library.load (juce::String::fromUTF8 (c.samplePath.c_str())); data != nullptr && data->frames() > 0)
  4564. {
  4565. const auto target = c.sampler.stretchBeats * 60.0 / std::max (1.0, out.song.bpm);
  4566. const auto method = c.sampler.stretchMethod;
  4567. const auto semitones = (double) c.sampler.stretchPitch;
  4568. const auto options = stretchOptionsOf (c.sampler);
  4569. // the same stretch as RackRenderer: the precomputed span when there is one (round 180d), else the file
  4570. const auto clip = c.instrument == InstrumentKind::audioClip;
  4571. auto settings = c.sampler;
  4572. if (clip)
  4573. settings.regionStart = 0.0f, settings.regionEnd = 1.0f;
  4574. const auto precomputes = clip ? c.sampler.precompute.any() : precompute::needed (c.sampler);
  4575. if (precomputes && c.sampler.warp.empty())
  4576. {
  4577. if (std::shared_ptr<const SampleData> span = precompute::apply (*data, settings); span != nullptr && span->frames() > 0)
  4578. {
  4579. const auto ratio = target / ((double) span->frames() / span->sampleRate);
  4580. auto variant = precompute::variantKey (settings, clip);
  4581. if (std::none_of (stretches.begin(), stretches.end(), [&] (const Stretch& x) {
  4582. return x.path == c.samplePath && x.variant == variant && x.ratio == ratio && x.method == method && x.semitones == semitones && x.options == options; }))
  4583. stretches.push_back ({ c.samplePath, ratio, method, semitones, {}, std::move (variant), std::move (span), options });
  4584. }
  4585. continue;
  4586. }
  4587. const auto ratio = target / ((double) precompute::stretchedFrames (data, c.sampler, clip) / data->sampleRate);
  4588. // (the same map the rack asks for: RackState::build)
  4589. auto map = warpStretchMap (c.sampler.warp, (double) data->frames(), data->sampleRate, (double) std::llround ((double) data->frames() * ratio));
  4590. if (std::none_of (stretches.begin(), stretches.end(), [&] (const Stretch& x) {
  4591. return x.path == c.samplePath && x.variant.empty() && x.ratio == ratio && x.method == method && x.semitones == semitones && x.map == map && x.options == options; }))
  4592. stretches.push_back ({ c.samplePath, ratio, method, semitones, std::move (map), {}, {}, options });
  4593. }
  4594. if (! stretches.empty())
  4595. {
  4596. const auto stretchStarted = std::chrono::steady_clock::now();
  4597. std::atomic<std::size_t> nextStretch { 0 };
  4598. auto stretchWorker = [&] {
  4599. for (auto i = nextStretch++; i < stretches.size(); i = nextStretch++)
  4600. if (auto stretched = ! stretches[i].variant.empty()
  4601. ? library.loadStretchedSpan (juce::String::fromUTF8 (stretches[i].path.c_str()), stretches[i].variant,
  4602. stretches[i].span, stretches[i].ratio, stretches[i].method, stretches[i].semitones,
  4603. stretches[i].options)
  4604. : library.loadStretched (juce::String::fromUTF8 (stretches[i].path.c_str()), stretches[i].ratio, stretches[i].method, stretches[i].semitones, stretches[i].map,
  4605. stretches[i].options))
  4606. {
  4607. const std::scoped_lock l (keep); // held until the rack is built (the cache drops unused lengths)
  4608. out.decoded.push_back (std::move (stretched));
  4609. }
  4610. };
  4611. std::vector<std::thread> helpers;
  4612. for (std::size_t i = 1; i < juce::jmin (threads, stretches.size()); ++i)
  4613. helpers.emplace_back (stretchWorker);
  4614. stretchWorker();
  4615. for (auto& t : helpers)
  4616. t.join();
  4617. loadtrace::add ("stretch_wall", loadtrace::msSince (stretchStarted), (int) stretches.size());
  4618. }
  4619. loadtrace::add ("samples_wall", loadtrace::msSince (decodeStarted), (int) paths.size());
  4620. out.ok = true;
  4621. }
  4622. catch (const flp::Error& e)
  4623. {
  4624. out.error = juce::String::fromUTF8 (e.what());
  4625. }
  4626. }
  4627. void AudioEngine::adoptPrepared (PreparedFlp& prepared)
  4628. {
  4629. if (prepared.adopted)
  4630. return;
  4631. prepared.adopted = true;
  4632. const auto t = std::chrono::steady_clock::now();
  4633. plugins.clearPreloaded();
  4634. plugins.setPreloadRate (transport.sampleRate.load());
  4635. plugins.adoptFlPlugins (prepared.song, &prepared.missing, &prepared.matched, &prepared.withoutState, &prepared.substituted);
  4636. loadtrace::add ("adopt_plugins", loadtrace::msSince (t));
  4637. // the hosted plugins the rack will create, in its order (channels, then inserts)
  4638. for (const auto& c : prepared.song.channels)
  4639. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty())
  4640. prepared.pluginQueue.push_back (c.plugin);
  4641. for (const auto& track : prepared.song.mixer)
  4642. for (std::size_t i = 0; i < track.effects.size() && i < (std::size_t) maxEffectSlots; ++i)
  4643. if (track.effects[i].kind == EffectKind::plugin && ! track.effects[i].plugin.id.empty())
  4644. prepared.pluginQueue.push_back (track.effects[i].plugin);
  4645. }
  4646. bool AudioEngine::preloadNextPlugin (PreparedFlp& prepared)
  4647. {
  4648. adoptPrepared (prepared);
  4649. if (prepared.pluginsDone >= prepared.pluginQueue.size())
  4650. return false;
  4651. const auto total = (int) prepared.pluginQueue.size();
  4652. const auto& ref = prepared.pluginQueue[prepared.pluginsDone];
  4653. auto wanted = 0;
  4654. for (std::size_t i = 0; i <= prepared.pluginsDone; ++i)
  4655. wanted += prepared.pluginQueue[i].id == ref.id && prepared.pluginQueue[i].state == ref.state ? 1 : 0;
  4656. plugins.preload (ref, wanted);
  4657. ++prepared.pluginsDone;
  4658. loadtrace::step ((int) prepared.pluginsDone, total, {});
  4659. return prepared.pluginsDone < prepared.pluginQueue.size();
  4660. }
  4661. bool AudioEngine::finishFlpImport (PreparedFlp&& prepared, bool asEdit)
  4662. {
  4663. if (! prepared.ok)
  4664. return false;
  4665. adoptPrepared (prepared);
  4666. auto& imported = prepared.song;
  4667. importReport = std::move (prepared.report);
  4668. const auto& uses = prepared.uses;
  4669. missingPlugins = prepared.missing;
  4670. matchedPlugins = prepared.matched;
  4671. pluginsWithoutState = prepared.withoutState;
  4672. missingPluginDetails.clear();
  4673. for (const auto& name : prepared.missing)
  4674. {
  4675. MissingPlugin m;
  4676. m.name = name.toStdString();
  4677. for (const auto& u : uses)
  4678. if (u.name == m.name)
  4679. {
  4680. if (std::find (m.usedBy.begin(), m.usedBy.end(), u.user) == m.usedBy.end())
  4681. m.usedBy.push_back (u.user);
  4682. m.replacement = u.instrument ? "Built-in synth (a preset chosen by the channel name)" : "Nothing: the slot was left out of the mixer";
  4683. }
  4684. missingPluginDetails.push_back (std::move (m));
  4685. }
  4686. // missing, played by a LYNX substitute that keeps the original for when it is installed
  4687. for (std::size_t t = 0; t < imported.mixer.size(); ++t)
  4688. for (const auto& fx : imported.mixer[t].effects)
  4689. if (fx.isSubstitute())
  4690. {
  4691. const auto name = substituteOriginalName (fx);
  4692. auto it = std::find_if (missingPluginDetails.begin(), missingPluginDetails.end(),
  4693. [&] (const MissingPlugin& m) { return m.name == name && ! m.replacementArg.empty(); });
  4694. if (it == missingPluginDetails.end())
  4695. it = missingPluginDetails.insert (missingPluginDetails.end(),
  4696. 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"),
  4697. effectInfo (fx.kind).name });
  4698. const auto user = userOf (imported, t);
  4699. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  4700. it->usedBy.push_back (user);
  4701. }
  4702. // found, but the project's settings are in the other format (VST2 <-> VST3): they play their default sound
  4703. for (const auto& line : prepared.withoutState)
  4704. missingPluginDetails.push_back ({ line.toStdString(), {}, TR_NOOP ("Its default settings: the project saved them for the other format (VST2/VST3)") });
  4705. plugins.clearLoadFailures();
  4706. loadtrace::stage (0.90, 0.99, TR_NOOP ("Building the mixer..."));
  4707. {
  4708. const loadtrace::Scope timing ("set_song");
  4709. if (asEdit)
  4710. editSong ([&imported] (Song& s) { s = std::move (imported); });
  4711. else
  4712. {
  4713. stop();
  4714. rewind();
  4715. setSong (std::move (imported));
  4716. }
  4717. }
  4718. plugins.clearPreloaded(); // (any left over: a slot the rack reused, nothing to keep)
  4719. prepared.decoded.clear();
  4720. // installed but failed to load (the rack was just built): silence / bypass, said as loudly as a missing one
  4721. for (const auto& line : plugins.getLoadFailures())
  4722. missingPluginDetails.push_back ({ line.toStdString(), {}, TR_NOOP ("Silence: the plugin is installed but did not load") });
  4723. return true;
  4724. }
  4725. bool AudioEngine::importFlpFile (const juce::File& file, juce::String& error, const std::map<std::string, std::string>& relocations, bool asEdit)
  4726. {
  4727. // a slow plugin module (a Waves shell) starts on its own thread while the samples decode (round 121)
  4728. if (juce::MemoryBlock data; file.loadFileAsData (data))
  4729. try
  4730. {
  4731. PluginHost::newOpen();
  4732. plugins.startModulesFor (flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  4733. }
  4734. catch (const flp::Error&)
  4735. {
  4736. }
  4737. PreparedFlp prepared;
  4738. prepareFlpImport (file, relocations, samples, prepared);
  4739. if (! prepared.ok)
  4740. {
  4741. error = prepared.error;
  4742. return false;
  4743. }
  4744. if (asEdit)
  4745. keepRunningPlugins (prepared);
  4746. loadtrace::stage (0.55, 0.90, TR_NOOP ("Loading plugins..."), TR_NOOP ("Loading {0}... {1}/{2}"));
  4747. while (preloadNextPlugin (prepared))
  4748. {
  4749. }
  4750. return finishFlpImport (std::move (prepared), asEdit);
  4751. }
  4752. void AudioEngine::keepRunningPlugins (PreparedFlp& prepared)
  4753. {
  4754. // The open project imported again (Missing files › Apply): its plugins are already running with these settings,
  4755. // and the rack keeps a slot whose plugin did not change. Creating them all again first (round 151: 71 plugins,
  4756. // 25 s with the window frozen, then a crash inside a plugin as the second copies replaced the first) is skipped
  4757. // for every plugin the song already has with the same settings.
  4758. adoptPrepared (prepared);
  4759. std::vector<const PluginRef*> running;
  4760. for (const auto& c : song.channels)
  4761. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty())
  4762. running.push_back (&c.plugin);
  4763. for (const auto& track : song.mixer)
  4764. for (const auto& fx : track.effects)
  4765. if (fx.kind == EffectKind::plugin && ! fx.plugin.id.empty())
  4766. running.push_back (&fx.plugin);
  4767. auto& queue = prepared.pluginQueue;
  4768. queue.erase (std::remove_if (queue.begin(), queue.end(),
  4769. [&running] (const PluginRef& ref) {
  4770. const auto it = std::find_if (running.begin(), running.end(), [&ref] (const PluginRef* r) { return r != nullptr && *r == ref; });
  4771. if (it == running.end())
  4772. return false;
  4773. *it = nullptr; // each running plugin stands for one queued copy
  4774. return true;
  4775. }),
  4776. queue.end());
  4777. }
  4778. const AutomationDisplay& AudioEngine::getAutomationDisplay()
  4779. {
  4780. const auto now = juce::Time::getMillisecondCounterHiRes();
  4781. // (editors ask from their own frames: once per display frame is enough; round 174e: 5 ms, i.e. every frame at 144
  4782. // Hz, unless a big project's automation takes long to evaluate, then 12 ms as before)
  4783. if (now - automationDisplayAtMs >= (automationDisplayCostMs > 0.5 ? 12.0 : 5.0))
  4784. {
  4785. automationDisplayAtMs = now;
  4786. const auto playing = transport.playing.load (std::memory_order_relaxed);
  4787. automationDisplay.update (song, songStamp, estimatedPositionNow(), playing);
  4788. automationDisplayCostMs = juce::Time::getMillisecondCounterHiRes() - now;
  4789. }
  4790. return automationDisplay;
  4791. }
  4792. RackState::Factories AudioEngine::rackFactories()
  4793. {
  4794. RackState::Factories factories;
  4795. factories.samples = [this] (const std::string& path) {
  4796. const loadtrace::Scope timing ("rack_samples");
  4797. return samples.load (juce::String::fromUTF8 (path.c_str()));
  4798. };
  4799. factories.stretchedSamples = [this] (const std::string& path, double ratio, StretchMethod method, double semitones, const StretchMap& map,
  4800. const StretchOptions& options) {
  4801. const loadtrace::Scope timing ("rack_stretch");
  4802. return samples.loadStretched (juce::String::fromUTF8 (path.c_str()), ratio, method, semitones, map, options);
  4803. };
  4804. factories.stretchedSpans = [this] (const std::string& path, const std::string& variant, const std::shared_ptr<const SampleData>& span,
  4805. double ratio, StretchMethod method, double semitones, const StretchOptions& options) {
  4806. const loadtrace::Scope timing ("rack_stretch");
  4807. return samples.loadStretchedSpan (juce::String::fromUTF8 (path.c_str()), variant, span, ratio, method, semitones, options);
  4808. };
  4809. factories.pluginInstruments = [this] (const PluginRef& ref, double sr) { return plugins.makeInstrument (ref, sr); };
  4810. factories.pluginEffects = [this] (const PluginRef& ref, double sr) { return plugins.makeEffect (ref, sr); };
  4811. return factories;
  4812. }
  4813. bool AudioEngine::auditionSound (const ChannelDef& channel, const std::vector<int>& keys, double* seconds)
  4814. {
  4815. auto audio = lynx::renderAudition (channel, keys, 0.32, 0.9, song.bpm, transport.sampleRate.load(), rackFactories());
  4816. if (seconds != nullptr)
  4817. *seconds = audio.sampleRate > 0.0 ? (double) audio.left.size() / audio.sampleRate : 0.0;
  4818. if (audio.left.empty())
  4819. return false;
  4820. auto sample = std::make_shared<SampleData>();
  4821. sample->sampleRate = audio.sampleRate;
  4822. sample->left = std::move (audio.left);
  4823. sample->right = std::move (audio.right);
  4824. previewSample (std::move (sample), false, 1.0f);
  4825. return true;
  4826. }
  4827. ClipAudio AudioEngine::renderClipAudio (std::size_t clipIndex)
  4828. {
  4829. return lynx::renderClipAudio (song, clipIndex, transport.sampleRate.load(), rackFactories());
  4830. }
  4831. void AudioEngine::publishSong()
  4832. {
  4833. // Issue #134: a hosted plugin may run the message loop while it is created (a licence or trial box, COM, a splash
  4834. // window), and what that loop dispatches can ask for a publish while this one is still building its rack: the
  4835. // engine's own timer (after a device change to another sample rate it sees the old rate until this publish ends, so
  4836. // it started a second rebuild of every plugin inside the first one's, and another inside each of those, as deep as
  4837. // the plugins kept running the loop), or an edit. The nested one waits: when this publish is done, one more runs
  4838. // with the song as it then is.
  4839. if (publishing)
  4840. {
  4841. publishAgain = true;
  4842. ++nestedPublishes;
  4843. return;
  4844. }
  4845. publishing = true;
  4846. const juce::ScopeGuard published { [this] {
  4847. publishing = false;
  4848. if (std::exchange (publishAgain, false))
  4849. publishSong();
  4850. } };
  4851. ++songStamp;
  4852. ++publishCount;
  4853. if (! openEditors.empty()) // (round 190ks: a channel moved or its option changed: its index / mark follows)
  4854. publishOwnNoteChannels();
  4855. // round 190jl: a MIDI Out channel added, or moved to a port a hardware output has, renders live
  4856. if ((hardwareMidiPorts[0] | hardwareMidiPorts[1] | hardwareMidiPorts[2] | hardwareMidiPorts[3]) != 0)
  4857. publishRenderAheadTargets();
  4858. // round 190ea: FL's invariant, at the one place every song state passes (new / opened / imported project, edit, undo,
  4859. // redo, a live session's remote change): at least one pattern and the current one in range. A Song built without a
  4860. // pattern used to crash the docked Piano roll (its listener read the current pattern of an empty list).
  4861. song.keepOnePattern();
  4862. // Online Sessions (round 168a): every entity has its stable id after any edit, import or load
  4863. uids::normalize (song);
  4864. // round 174d A3: the Video Player's clock follows the song's tempo map (FL: the song's real time)
  4865. if (std::any_of (song.channels.begin(), song.channels.end(), [] (const ChannelDef& c) { return c.instrument == InstrumentKind::videoplayer; }))
  4866. video::publishTempo (song);
  4867. // pasted / duplicated channels and effect slots get their own instance (round 168s: instances follow their channel)
  4868. song.uniqueInstances();
  4869. // diagnostics (round 149): with LYNX_TRACE_EDITS set, each publish's time goes to %APPDATA%\LYNX\edits.log
  4870. static const bool traceEdits = std::getenv ("LYNX_TRACE_EDITS") != nullptr;
  4871. const auto publishStart = juce::Time::getMillisecondCounterHiRes();
  4872. const juce::ScopeGuard traceEnd { [&] {
  4873. if (traceEdits)
  4874. platform::settingsFile ("edits.log").appendText (juce::String (juce::Time::getMillisecondCounterHiRes() - publishStart, 1) + " ms publish\n");
  4875. } };
  4876. // the Master's hardware output target, read by the device callback
  4877. masterOutChannel.store (song.mixer.empty() ? outputDefault : song.mixer[0].outputChannel, std::memory_order_relaxed);
  4878. masterOutMode.store (song.mixer.empty() ? 0 : (int) song.mixer[0].outputMode, std::memory_order_relaxed);
  4879. selectedChannel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), selectedChannel);
  4880. {
  4881. const auto count = (int) song.channels.size();
  4882. selectedChannels.erase (std::remove_if (selectedChannels.begin(), selectedChannels.end(), [count] (int c) { return c >= count; }),
  4883. selectedChannels.end());
  4884. if (std::find (selectedChannels.begin(), selectedChannels.end(), selectedChannel) == selectedChannels.end())
  4885. selectedChannels.insert (std::lower_bound (selectedChannels.begin(), selectedChannels.end(), selectedChannel), selectedChannel);
  4886. }
  4887. publishSelection();
  4888. {
  4889. // the channels locked to a MIDI input ("Receive notes from"): built here, swapped in under the lock
  4890. std::vector<NoteLock> locks;
  4891. for (std::size_t c = 0; c < song.channels.size(); ++c)
  4892. if (! song.channels[c].receiveFrom.empty())
  4893. locks.push_back ({ song.channels[c].receiveFrom, song.channels[c].receiveMidiChannel, (int) c });
  4894. // round 190ao: the hosted instruments with their own velocity setting
  4895. std::vector<std::uint16_t> velocities;
  4896. for (std::size_t c = 0; c < song.channels.size(); ++c)
  4897. if (song.channels[c].instrument == InstrumentKind::plugin && song.channels[c].plugin.velocityMode != prefs::pluginVelocityFollow)
  4898. {
  4899. velocities.resize (c + 1, 0);
  4900. velocities[c] = (std::uint16_t) (prefs::clampPluginVelocityMode (song.channels[c].plugin.velocityMode)
  4901. | (prefs::clampFixedVelocity (song.channels[c].plugin.fixedVelocity) << 8));
  4902. }
  4903. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  4904. noteLocks.swap (locks);
  4905. channelVelocity.swap (velocities);
  4906. }
  4907. transport.bpm.store (song.bpm);
  4908. transport.beatsPerBar.store (song.beatsPerBar);
  4909. transport.beatUnit.store (meterUnit (song.beatUnit));
  4910. transport.projectBpm.store (song.bpm); // (round 190gl: what the Link session sees as the project's own tempo)
  4911. transport.linkQuantum.store (linksync::quantumBeats (song.clipGrid.has_value() ? song.clipGrid->globalQuant : LaunchQuant::bar, song.meter()));
  4912. {
  4913. // time-signature table for the metronome: the start (the song's meter) and each signature change
  4914. transport.signatureVersion.fetch_add (1, std::memory_order_acq_rel); // odd: writing
  4915. int count = 0;
  4916. transport.signatureTick[0].store (0, std::memory_order_relaxed);
  4917. transport.signatureLength[0].store (song.barTicks(), std::memory_order_relaxed);
  4918. transport.signatureBeat[0].store (song.beatTicks(), std::memory_order_relaxed);
  4919. ++count;
  4920. for (const auto& m : song.markers())
  4921. if (m.isSignature() && count < Transport::maxSignatures)
  4922. {
  4923. const auto length = juce::jmax<std::int64_t> (1, (std::int64_t) ppq * 4 * m.numerator / juce::jmax (1, m.denominator));
  4924. const auto beat = juce::jmax<std::int64_t> (1, length / juce::jmax (1, m.numerator)); // (round 190fg: its own beats)
  4925. const auto slot = m.tick <= 0 ? 0 : count++; // at position 0 it replaces the default
  4926. transport.signatureTick[(std::size_t) slot].store (juce::jmax<std::int64_t> (0, m.tick), std::memory_order_relaxed);
  4927. transport.signatureLength[(std::size_t) slot].store (length, std::memory_order_relaxed);
  4928. transport.signatureBeat[(std::size_t) slot].store (beat, std::memory_order_relaxed);
  4929. }
  4930. transport.signatureCount.store (count, std::memory_order_relaxed);
  4931. transport.signatureVersion.fetch_add (1, std::memory_order_acq_rel); // even: ready
  4932. }
  4933. transport.songMode.store (song.mode == PlayMode::song);
  4934. 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)
  4935. transport.loopEnd.store (song.loopPlays() ? (double) song.loopEnd : 0.0);
  4936. transport.songEnd.store ((double) song.songLength());
  4937. transport.publishMarkers (makeMarkerPlan (song)); // FL's marker actions (loop, skip, pause, start...)
  4938. transport.songStart.store ((double) song.performanceZoneEnd());
  4939. const loadtrace::Scope buildTiming ("rack_build");
  4940. auto factories = rackFactories();
  4941. // the song's own rack (not the offline clip render, which shares rackFactories()) tells the UI a plugin is being created
  4942. factories.pluginInstruments = [this] (const PluginRef& ref, double sr) {
  4943. if (duringPluginCreation)
  4944. duringPluginCreation();
  4945. return plugins.makeInstrument (ref, sr);
  4946. };
  4947. factories.pluginEffects = [this] (const PluginRef& ref, double sr) {
  4948. if (duringPluginCreation)
  4949. duringPluginCreation();
  4950. return plugins.makeEffect (ref, sr);
  4951. };
  4952. factories.freshInstances = std::exchange (remoteFreshInstances, {});
  4953. factories.liveInstrument = liveInstrumentSource; // (round 190jb: an export engine renders with the live plugins)
  4954. factories.liveEffect = liveEffectSource;
  4955. if (rebuildPlugins) // round 190ap: a plugin switched back on (switchPluginOn)
  4956. factories.rebuildPlugin = [this] (const PluginRef& ref) { return rebuildPluginId.empty() || ref.id == rebuildPluginId; };
  4957. const auto buildStart = juce::Time::getMillisecondCounterHiRes();
  4958. const auto tracePhases = traceEdits && ! loadtrace::active(); // the build's phases (an open traces its own)
  4959. if (tracePhases)
  4960. loadtrace::begin ("edit");
  4961. // the parts whose third-party plugin is missing here play their stand-in renders (core/StandIns.h): the audio
  4962. // engine gets that projection of the song, the UI keeps the song itself
  4963. // (no copy of the song for the almost every project that has none)
  4964. std::optional<Song> projectedSong;
  4965. standins::Projected projected;
  4966. // Freeze (round 190ay): a frozen channel whose audio is not on disk (the project moved without it, a freeze brought
  4967. // back by Undo after its files went) plays its instrument: out of date beats silent
  4968. std::optional<Song> thawedSong;
  4969. frozenMissing.clear();
  4970. for (std::size_t i = 0; i < song.channels.size(); ++i)
  4971. if (const auto& f = song.channels[i].freeze; f.on())
  4972. {
  4973. const auto* whole = standins::find (f.stems, 0, false);
  4974. if (whole != nullptr && juce::File (juce::String::fromUTF8 (whole->path.c_str())).existsAsFile())
  4975. continue;
  4976. if (! thawedSong)
  4977. thawedSong = song;
  4978. thawedSong->channels[i].freeze = {};
  4979. frozenMissing.push_back ((int) i);
  4980. }
  4981. const Song& unprojected = thawedSong ? *thawedSong : song;
  4982. if (standins::hasAny (unprojected))
  4983. projectedSong = standins::project (unprojected, [this] (const PluginRef& ref) { return ! plugins.isInstalled (ref); }, &projected);
  4984. const Song& played = projectedSong ? *projectedSong : unprojected;
  4985. {
  4986. // round 190ap: the slots whose plugin is switched off ("Open without third-party plugins"), for their badges
  4987. const auto hold = pluginsOff() || pluginHoldOwner.load() == nullptr ? pluginHoldState() : pluginhold::State();
  4988. channelsOff = pluginhold::channelsOff (song, hold);
  4989. insertsOff = pluginhold::insertsOff (song, hold);
  4990. }
  4991. standInChannels = std::move (projected.channels);
  4992. standInInserts = std::move (projected.inserts);
  4993. if (played.clipGrid)
  4994. {
  4995. if (clipLauncher == nullptr)
  4996. clipLauncher = std::make_unique<launcher::Runtime>();
  4997. factories.clipLauncher = clipLauncher.get();
  4998. }
  4999. // "Low latency while recording" (round 190aq): the live inserts' paths, for this snapshot only (not the song)
  5000. publishedLowLatency = lowLatencyTracksNow();
  5001. factories.lowLatencyTracks = publishedLowLatency;
  5002. // round 190kx: ARA. The host is made the first time the song has an audio clip channel edited in an ARA plugin (a song
  5003. // without one never makes it); an export engine that renders with the live plugins borrows the live instances instead
  5004. if ((araHost != nullptr || ara::anyAraChannel (played)) && ! liveInstrumentSource && AraHost::available())
  5005. {
  5006. if (araHost == nullptr)
  5007. {
  5008. araHost = std::make_unique<AraHost> (plugins, [this] (const std::string& path) { return samples.load (juce::String::fromUTF8 (path.c_str())); });
  5009. araHost->onPlaybackRequest = [this] (int request, double seconds) {
  5010. if (request == 0)
  5011. play();
  5012. else if (request == 1)
  5013. stop();
  5014. else
  5015. seek (std::max (0.0, seconds / ara::secondsPerTick (song)));
  5016. };
  5017. }
  5018. araHost->sync (played, transport.sampleRate.load());
  5019. factories.araInstrument = [this] (const ChannelDef& c, double rate) { return araHost->instrumentFor (c, rate); };
  5020. }
  5021. factories.currentSource = currentSource; // (round 190my: FL's Current track's latency in the PDC plan)
  5022. auto state = RackState::build (played, &lastPublishedShape, transport.sampleRate.load(), factories);
  5023. if (traceEdits)
  5024. platform::settingsFile ("edits.log").appendText (juce::String (juce::Time::getMillisecondCounterHiRes() - buildStart, 1) + " ms rack build\n"
  5025. + (tracePhases ? juce::String (loadtrace::reportLines()) : juce::String()));
  5026. if (tracePhases)
  5027. loadtrace::end();
  5028. // what the next build needs to reuse instruments and effects
  5029. lastPublishedShape.song.channels = played.channels;
  5030. lastPublishedShape.song.mixer = played.mixer;
  5031. // the tempo too (round 149): a channel that plays a time-stretched copy is kept when its stretch and the tempo
  5032. // did not change; without it every edit rebuilt them (sample reloaded and stretch looked up, ~0.5 s on Thief)
  5033. lastPublishedShape.song.bpm = song.bpm;
  5034. lastPublishedShape.instruments = state->instruments;
  5035. lastPublishedShape.serial = state->serial; // (round 168s: the renderer moves held notes only along this chain)
  5036. lastPublishedShape.effects = state->effects;
  5037. lastPublishedShape.sampleRate = state->sampleRate;
  5038. lastPublishedShape.latencies = state->latencies;
  5039. lastPublishedShape.lowLatencySlots = state->lowLatencySlots; // (currentLatencies() reads them)
  5040. lastPublishedShape.lowLatencySaved = state->lowLatencySaved;
  5041. lastPublishedShape.pdc = state->pdc;
  5042. lastPublishedShape.channelDelays = state->channelDelays;
  5043. lastPublishedShape.sendDelays = state->sendDelays;
  5044. lastPublishedShape.sideLines = state->sideLines; // (round 190hq: the side inputs' lines carry over as the sends' do)
  5045. // round 190hq (B13): what the Master hears is this much later than what the rack renders (the clocks LYNX sends and
  5046. // follows, Link and played notes count it, as they count the output buffer)
  5047. masterPdcSamples.store (state->pdc.total, std::memory_order_relaxed);
  5048. lastPublishedShape.shifterStock = state->shifterStock; // (round 190gn: the next build keeps the rack's shifter stock)
  5049. const auto mark = [&] (const char* what) {
  5050. if (traceEdits)
  5051. platform::settingsFile ("edits.log").appendText (juce::String (juce::Time::getMillisecondCounterHiRes() - publishStart, 1) + " ms " + what + "\n");
  5052. };
  5053. mark ("built");
  5054. levelsPending = false;
  5055. publishedLevels = projectedSong ? nullptr : state->live; // (stand-ins: their projection, edits rebuild)
  5056. // round 190gn (A6): the renderer's channel / insert buffers hold this song before it can play it
  5057. if (rackProcessor != nullptr)
  5058. rackProcessor->getRenderer().reserveFor (*state);
  5059. rackExchange.publish (std::move (state));
  5060. mark ("exchanged");
  5061. if (prefetcher != nullptr)
  5062. prefetcher->update (played, samples);
  5063. mark ("prefetch updated");
  5064. sendChangeMessage();
  5065. }
  5066. std::vector<MidiLink> AudioEngine::getGlobalLinks() const
  5067. {
  5068. std::vector<MidiLink> out;
  5069. for (const auto& l : midiPrefs.globalLinks)
  5070. {
  5071. MidiLink link { l.cc, l.channel, { (AutomationTargetKind) l.kind, l.index, l.slot, l.param } };
  5072. link.port = l.port;
  5073. link.formula = l.formula;
  5074. link.smooth = l.smooth;
  5075. link.smoothing = l.smoothing;
  5076. link.mode = l.mode;
  5077. link.min = l.min;
  5078. link.max = l.max;
  5079. out.push_back (std::move (link));
  5080. }
  5081. return out;
  5082. }
  5083. std::optional<MidiLink> AudioEngine::globalLinkOf (const AutomationTarget& target) const
  5084. {
  5085. for (const auto& l : getGlobalLinks())
  5086. if (l.target == target)
  5087. return l;
  5088. return std::nullopt;
  5089. }
  5090. void AudioEngine::learnGlobalLink (const AutomationTarget& target)
  5091. {
  5092. learning = target;
  5093. learningGlobal = true;
  5094. sendChangeMessage();
  5095. }
  5096. void AudioEngine::removeGlobalLink (const AutomationTarget& target)
  5097. {
  5098. auto p = midiPrefs;
  5099. p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
  5100. [&] (const prefs::GlobalLink& l) {
  5101. return l.kind == (int) target.kind && l.index == target.index && l.slot == target.slot
  5102. && l.param == target.param;
  5103. }),
  5104. p.globalLinks.end());
  5105. setMidiPrefs (p, saveGlobalLinks);
  5106. }
  5107. void AudioEngine::setTargetLinks (const AutomationTarget& target, std::vector<MidiLink> links, bool removeConflicts)
  5108. {
  5109. editSong ([&] (Song& s) { lynx::setTargetLinks (s.midiLinks, target, std::move (links), removeConflicts); });
  5110. linkSmoothing.clear();
  5111. sendChangeMessage();
  5112. }
  5113. void AudioEngine::setGlobalLink (const AutomationTarget& target, const std::optional<MidiLink>& link)
  5114. {
  5115. auto p = midiPrefs;
  5116. p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
  5117. [&] (const prefs::GlobalLink& l) {
  5118. return l.kind == (int) target.kind && l.index == target.index && l.slot == target.slot
  5119. && l.param == target.param;
  5120. }),
  5121. p.globalLinks.end());
  5122. if (link && link->cc >= 0)
  5123. {
  5124. prefs::GlobalLink g { link->cc, link->channel, (int) target.kind, target.index, target.slot, target.param };
  5125. g.port = link->port;
  5126. g.formula = link->formula;
  5127. g.smooth = link->smooth;
  5128. g.smoothing = link->smoothing;
  5129. g.mode = link->mode;
  5130. g.min = link->min;
  5131. g.max = link->max;
  5132. p.globalLinks.push_back (std::move (g));
  5133. }
  5134. setMidiPrefs (p, saveGlobalLinks);
  5135. linkSmoothing.clear();
  5136. sendChangeMessage();
  5137. }
  5138. bool AudioEngine::moveMappingScope (const remotemap::Row& row, bool toEveryProject)
  5139. {
  5140. auto p = midiPrefs;
  5141. if (! remotemap::canMove (song, p, row, toEveryProject))
  5142. return false;
  5143. auto moved = false;
  5144. editSong ([&] (Song& s) { moved = toEveryProject ? remotemap::moveToEveryProject (s, p, row) : remotemap::moveToThisProject (s, p, row); });
  5145. if (moved)
  5146. setMidiPrefs (p, saveGlobalLinks);
  5147. linkSmoothing.clear();
  5148. sendChangeMessage();
  5149. return moved;
  5150. }
  5151. bool AudioEngine::editGlobalMappingRow (const remotemap::Row& row, const std::function<bool (prefs::MidiPrefs&)>& edit)
  5152. {
  5153. if (! row.global)
  5154. return false;
  5155. auto p = midiPrefs;
  5156. if (! edit (p))
  5157. return false;
  5158. setMidiPrefs (p, saveGlobalLinks);
  5159. return true;
  5160. }
  5161. void AudioEngine::setMapMode (remotemap::Mode mode)
  5162. {
  5163. mapMode = mode;
  5164. mapCaptured.reset();
  5165. mapCaptureNotes.store (mode == remotemap::Mode::midi, std::memory_order_relaxed);
  5166. }
  5167. void AudioEngine::injectControllerForTest (int cc, int channel, int value, int port)
  5168. {
  5169. controllerQueue.push ({ cc, channel, value, port });
  5170. applyControllers();
  5171. }
  5172. // The smoothing filters of the links being moved (FL's per-link "Smoothing"): each one walks towards the position its
  5173. // controller last gave, at the timer's pace, until it has arrived.
  5174. void AudioEngine::stepLinkSmoothing (std::vector<std::pair<AutomationTarget, float>>& changes)
  5175. {
  5176. const auto now = juce::Time::getMillisecondCounterHiRes();
  5177. const auto elapsed = linkSmoothingClock > 0.0 ? juce::jlimit (0.0, 250.0, now - linkSmoothingClock) : 0.0;
  5178. linkSmoothingClock = now;
  5179. for (auto& s : linkSmoothing)
  5180. {
  5181. const auto v = s.filter.step (s.target, elapsed, s.link.smoothing);
  5182. const auto mixerTrack = selectedMixerTrackForLinks ? selectedMixerTrackForLinks() : -1;
  5183. changes.push_back ({ linkOmniTarget (s.link, selectedChannel, mixerTrack), v });
  5184. }
  5185. linkSmoothing.erase (std::remove_if (linkSmoothing.begin(), linkSmoothing.end(), [] (const LinkSmoothing& s) { return s.filter.settled (s.target); }),
  5186. linkSmoothing.end());
  5187. if (linkSmoothing.empty())
  5188. linkSmoothingClock = 0.0;
  5189. }
  5190. void AudioEngine::setMultilink (bool on)
  5191. {
  5192. if (on)
  5193. multilink.emplace();
  5194. else
  5195. multilink.reset();
  5196. sendChangeMessage();
  5197. }
  5198. void AudioEngine::multilinkToControllers (bool global)
  5199. {
  5200. if (! multilink)
  5201. return;
  5202. multilink->collecting = false;
  5203. multilink->global = global;
  5204. sendChangeMessage();
  5205. }
  5206. void AudioEngine::learnMidiController (const AutomationTarget& target)
  5207. {
  5208. learning = target;
  5209. learningGlobal = false;
  5210. sendChangeMessage();
  5211. }
  5212. // --- last tweaked parameters and automation recording (REA round 143) --------------------------------------
  5213. void AudioEngine::noteTweaked (const AutomationTarget& target, bool held)
  5214. {
  5215. if (target.kind == AutomationTargetKind::none)
  5216. return;
  5217. if (multilink) // round 177b-4: FL's Multilink queues the moved controls in order
  5218. multilink->add (target);
  5219. // FL [EXEC round 185b, issue #125]: a moved control leaves its automation until playback starts again (stopped: the
  5220. // value stays; playing: the clip no longer drives it). While recording automation the touch rule applies instead.
  5221. const auto recordingAutomation = transport.recording.load() && transport.playing.load() && recordOptions.recordAutomation;
  5222. if (! recordingAutomation && std::find (releasedTargets.begin(), releasedTargets.end(), target) == releasedTargets.end())
  5223. {
  5224. releasedTargets.push_back (target);
  5225. publishReleasedTargets();
  5226. }
  5227. if (! (lastTweaked[0] == target))
  5228. {
  5229. lastTweaked[1] = lastTweaked[0];
  5230. lastTweaked[0] = target;
  5231. }
  5232. const auto now = juce::Time::getMillisecondCounterHiRes();
  5233. auto it = std::find_if (touches.begin(), touches.end(), [&] (const Touch& t) { return t.target == target; });
  5234. if (it == touches.end())
  5235. {
  5236. touches.push_back ({ target, now, held, {} });
  5237. return;
  5238. }
  5239. it->lastMs = now;
  5240. it->held = it->held || held;
  5241. }
  5242. void AudioEngine::publishReleasedTargets()
  5243. {
  5244. if (rackProcessor == nullptr)
  5245. return;
  5246. std::vector<int> slots, one;
  5247. for (const auto& t : releasedTargets)
  5248. {
  5249. RackState::slotsOfTarget (song, t, one);
  5250. for (const auto a : one) // (a link to an internal controller keeps driving it)
  5251. if (a >= (int) song.automations.size() || ! song.automations[(std::size_t) a].isLive())
  5252. slots.push_back (a);
  5253. }
  5254. rackProcessor->setReleasedSlots (slots);
  5255. }
  5256. void AudioEngine::tweakReleased (const AutomationTarget& target)
  5257. {
  5258. for (auto& t : touches)
  5259. if (t.target == target)
  5260. {
  5261. t.held = false;
  5262. t.lastMs = juce::Time::getMillisecondCounterHiRes();
  5263. }
  5264. }
  5265. std::optional<AutomationTarget> AudioEngine::getLastTweaked (int which) const
  5266. {
  5267. if (which < 0 || which > 1 || lastTweaked[(std::size_t) which].kind == AutomationTargetKind::none
  5268. || currentTargetValue (lastTweaked[(std::size_t) which]) < 0.0f)
  5269. return std::nullopt;
  5270. return lastTweaked[(std::size_t) which];
  5271. }
  5272. float AudioEngine::currentTargetValue (const AutomationTarget& t) const
  5273. {
  5274. // a controller's pitch wheel being recorded (any instrument: LYNX's own have no such parameter)
  5275. if (t.kind == AutomationTargetKind::channelParam && midictl::isPitchBend (t.param))
  5276. if (const auto it = liveBends.find (t.index); it != liveBends.end())
  5277. return it->second;
  5278. const auto base = song.targetValue (t);
  5279. if (base < 0.0f || (t.kind != AutomationTargetKind::channelParam && t.kind != AutomationTargetKind::effectParam))
  5280. return base;
  5281. juce::AudioPluginInstance* plugin = nullptr;
  5282. float midiValue = -1.0f;
  5283. if (t.kind == AutomationTargetKind::channelParam)
  5284. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (t.index).get()))
  5285. {
  5286. plugin = &p->getInstance();
  5287. midiValue = midictl::isMidiParam (t.param) ? p->midiControlValue (t.param) : -1.0f;
  5288. }
  5289. if (t.kind == AutomationTargetKind::effectParam)
  5290. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (t.index, t.slot).get()))
  5291. {
  5292. plugin = &p->getInstance();
  5293. midiValue = midictl::isMidiParam (t.param) ? p->midiControlValue (t.param) : -1.0f;
  5294. }
  5295. if (midiValue >= 0.0f)
  5296. return midiValue;
  5297. if (plugin != nullptr && t.param >= 0 && t.param < plugin->getParameters().size())
  5298. return plugin->getParameters()[t.param]->getValue();
  5299. return base;
  5300. }
  5301. std::optional<AutomationTarget> AudioEngine::targetOfPlugin (const juce::AudioPluginInstance& plugin, int param) const
  5302. {
  5303. for (int c = 0; c < (int) song.channels.size(); ++c)
  5304. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (c).get()); p != nullptr && &p->getInstance() == &plugin)
  5305. return AutomationTarget { AutomationTargetKind::channelParam, c, 0, param };
  5306. for (int t = 0; t < (int) song.mixer.size(); ++t)
  5307. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  5308. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (t, s).get()); p != nullptr && &p->getInstance() == &plugin)
  5309. return AutomationTarget { AutomationTargetKind::effectParam, t, s, param };
  5310. return std::nullopt;
  5311. }
  5312. void AudioEngine::takeRecordedBends()
  5313. {
  5314. RecordedEvent e;
  5315. const auto now = juce::Time::getMillisecondCounterHiRes();
  5316. while (bendRecordQueue.pop (e))
  5317. {
  5318. if (! recordOptions.recordAutomation || e.channel < 0 || e.channel >= (int) song.channels.size())
  5319. continue;
  5320. const AutomationTarget target { AutomationTargetKind::channelParam, e.channel, 0, midictl::pitchBendBase + e.key };
  5321. liveBends[e.channel] = e.velocity;
  5322. // the wheel's own moves, at the times they were played (not only the UI's sampling)
  5323. auto it = std::find_if (touches.begin(), touches.end(), [&] (const Touch& t) { return t.target == target; });
  5324. if (it == touches.end())
  5325. {
  5326. touches.push_back ({ target, now, false, {} });
  5327. it = touches.end() - 1;
  5328. }
  5329. it->lastMs = now;
  5330. it->pending.push_back ({ e.tick, e.velocity });
  5331. }
  5332. if (! transport.recording.load() || ! transport.playing.load())
  5333. liveBends.clear();
  5334. }
  5335. void AudioEngine::updateAutomationRecording (bool active)
  5336. {
  5337. const auto now = juce::Time::getMillisecondCounterHiRes();
  5338. // round 190mx (GitHub #198, Live's Session automation): Session Record (a clip slot recording, or overdubbing the
  5339. // playing clips) writes the moved parameters into those clips' envelopes (updateSlotRecording places them)
  5340. const auto sessionMode = ! active && transport.playing.load() && isSessionRecording();
  5341. const auto recording = (active || sessionMode) && recordOptions.recordAutomation;
  5342. const auto grid = recordOptions.quantiseAutomation ? recordOptions.quantise : std::int64_t { 0 };
  5343. auto writeFor = [this] (const AutomationTarget& target) -> AutomationWrite& {
  5344. auto it = std::find_if (takeWrites.begin(), takeWrites.end(), [&] (const AutomationWrite& w) { return w.target == target; });
  5345. if (it != takeWrites.end())
  5346. return *it;
  5347. AutomationWrite w;
  5348. w.target = target;
  5349. w.name = nameAutomation ? nameAutomation (target) : std::string ("Automation");
  5350. takeWrites.push_back (w);
  5351. return takeWrites.back();
  5352. };
  5353. // writes what was sampled (one undo step for the whole take); `ended` = the gestures that are over
  5354. auto commit = [&] (const std::vector<AutomationTarget>& ended, bool toSession) {
  5355. if (std::none_of (touches.begin(), touches.end(), [] (const Touch& t) { return ! t.pending.empty(); }))
  5356. return;
  5357. if (toSession) // (round 190mx: the session's clips take them when they exist; updateSlotRecording)
  5358. {
  5359. for (auto& t : touches)
  5360. if (! t.pending.empty())
  5361. {
  5362. recordedAutomationPoints += (int) t.pending.size();
  5363. routeSessionAutomation (t.target, std::move (t.pending));
  5364. t.pending.clear();
  5365. }
  5366. return;
  5367. }
  5368. const auto songMode = song.mode == PlayMode::song;
  5369. // round 190mx (GitHub #198): where Song mode writes depends on the layout. Clip-launch (Live's Arrangement
  5370. // automation): the parameter's lane under its track. Pattern (FL, live check 190mx): a generator's own parameter
  5371. // goes into the current pattern as event data, as in Pattern mode; the other targets make automation clips.
  5372. const auto style = layoutstyle::current();
  5373. editSong ([&] (Song& s) {
  5374. for (auto& t : touches)
  5375. if (! t.pending.empty())
  5376. {
  5377. auto& w = writeFor (t.target);
  5378. recordedAutomationPoints += (int) t.pending.size();
  5379. switch (recordedAutomationDestination (songMode, (int) style, t.target))
  5380. {
  5381. case AutomationDestination::lane:
  5382. commitLanePoints (s, w, std::move (t.pending), grid, automationLinear || noteTakeLinear);
  5383. break;
  5384. case AutomationDestination::automationClip:
  5385. commitAutomationPoints (s, w, std::move (t.pending), grid, automationLinear || noteTakeLinear);
  5386. break;
  5387. case AutomationDestination::patternEvents:
  5388. commitEventPoints (s, automationPattern, w, std::move (t.pending), automationLoopLength, grid);
  5389. break;
  5390. }
  5391. t.pending.clear();
  5392. }
  5393. }, ! automationTakeHasUndoStep);
  5394. automationTakeHasUndoStep = true;
  5395. for (const auto& target : ended)
  5396. writeFor (target).lastLocal = -1; // the next gesture on it starts a new stretch
  5397. };
  5398. // FL: while recording, the moved control wins over its playing automation at once (REA round 146); the
  5399. // automation of a touched target does not drive it until the gesture ends and its points are written.
  5400. auto overrideTouched = [this] {
  5401. if (rackProcessor == nullptr)
  5402. return;
  5403. std::vector<int> slots, one;
  5404. for (const auto& t : touches)
  5405. {
  5406. RackState::slotsOfTarget (song, t.target, one);
  5407. slots.insert (slots.end(), one.begin(), one.end());
  5408. }
  5409. if (slots.empty() && ! automationOverrideActive)
  5410. return;
  5411. rackProcessor->setOverriddenSlots (slots);
  5412. automationOverrideActive = ! slots.empty();
  5413. };
  5414. // the take's own clips reach the playhead (FL: the clip keeps growing until recording stops, holding the last value)
  5415. auto growClips = [this] (std::int64_t songTick, bool finished) {
  5416. if (song.mode != PlayMode::song || songTick < 0)
  5417. return;
  5418. const auto needed = std::any_of (takeWrites.begin(), takeWrites.end(), [&] (const AutomationWrite& w) {
  5419. if (! w.createdByTake || w.automation < 0)
  5420. return false;
  5421. for (const auto& c : song.playlist)
  5422. if (c.kind == ClipKind::automation && c.automation == w.automation)
  5423. return finished || c.end() < songTick;
  5424. return false;
  5425. });
  5426. if (! needed)
  5427. return;
  5428. editSong ([&] (Song& s) {
  5429. for (const auto& w : takeWrites)
  5430. growTakeClip (s, w, songTick, finished);
  5431. }, ! automationTakeHasUndoStep);
  5432. automationTakeHasUndoStep = true;
  5433. };
  5434. if (! recording)
  5435. {
  5436. commit ({}, std::exchange (sessionAutomationPass, false));
  5437. touches.clear();
  5438. overrideTouched();
  5439. if (! active)
  5440. {
  5441. growClips (lastAutomationTick, true);
  5442. takeWrites.clear();
  5443. automationTakeHasUndoStep = false;
  5444. automationLoopLength = 0;
  5445. lastAutomationTick = -1;
  5446. if (std::exchange (automationLinear, false))
  5447. updateLinearSong();
  5448. }
  5449. return;
  5450. }
  5451. if (automationLoopLength <= 0)
  5452. {
  5453. automationPattern = song.currentPattern;
  5454. automationLoopLength = song.patterns.empty() ? ppq * 4
  5455. : song.patterns[(std::size_t) juce::jlimit (0, (int) song.patterns.size() - 1, song.currentPattern)]
  5456. .effectiveLength (song.meter());
  5457. }
  5458. const auto tick = sessionMode ? slotClockNow() : estimatedPositionNow(); // (the session's clips run on the launcher's clock)
  5459. // FL's "Record automation" of an internal-controller link (round 190cs): the controller's output, as the link maps
  5460. // it, is written like a hand move for as long as automation is recorded
  5461. for (const auto& a : song.automations)
  5462. {
  5463. if (! a.isLive() || ! a.recordLive)
  5464. continue;
  5465. auto output = -1.0f;
  5466. if (a.source.channel >= 0)
  5467. {
  5468. if (const auto instrument = getChannelInstrument (a.source.channel))
  5469. output = instrument->controlOutput (a.source.output);
  5470. }
  5471. else if (const auto effect = getEffect (a.source.track, a.source.slot))
  5472. output = effect->controlOutput (a.source.output);
  5473. if (output < 0.0f || std::isnan (output))
  5474. continue;
  5475. auto it = std::find_if (touches.begin(), touches.end(), [&] (const Touch& t) { return t.target == a.target; });
  5476. if (it == touches.end())
  5477. {
  5478. touches.push_back ({ a.target, now, false, {} });
  5479. it = touches.end() - 1;
  5480. }
  5481. it->lastMs = now;
  5482. it->liveValue = juce::jlimit (0.0f, 1.0f, a.mapLive (juce::jlimit (0.0f, 1.0f, output)));
  5483. }
  5484. std::vector<AutomationTarget> ended;
  5485. for (auto& t : touches)
  5486. {
  5487. const auto alive = t.held || now - t.lastMs < 350.0;
  5488. const auto value = t.liveValue >= 0.0f ? t.liveValue : currentTargetValue (t.target);
  5489. if (value < 0.0f)
  5490. {
  5491. ended.push_back (t.target);
  5492. continue;
  5493. }
  5494. if (alive)
  5495. t.pending.push_back ({ tick, value });
  5496. else
  5497. ended.push_back (t.target);
  5498. }
  5499. // song mode without a loop region: from the first move on, the song plays on past its end until recording stops
  5500. if (! sessionMode && (! takeWrites.empty() || ! touches.empty()))
  5501. if (! automationLinear && song.mode == PlayMode::song && ! song.loopPlays())
  5502. {
  5503. automationLinear = true;
  5504. updateLinearSong();
  5505. }
  5506. if (song.mode == PlayMode::song && ! sessionMode)
  5507. lastAutomationTick = songTickForRecorded (song, tick, automationLinear || noteTakeLinear);
  5508. if (! ended.empty() || --automationCommitCountdown <= 0)
  5509. {
  5510. if (! sessionMode)
  5511. growClips (lastAutomationTick, false);
  5512. commit (ended, sessionMode);
  5513. automationCommitCountdown = 6; // about 5 writes per second while a control keeps moving
  5514. }
  5515. touches.erase (std::remove_if (touches.begin(), touches.end(),
  5516. [&] (const Touch& t) { return std::find (ended.begin(), ended.end(), t.target) != ended.end(); }),
  5517. touches.end());
  5518. overrideTouched();
  5519. sessionAutomationPass = sessionMode;
  5520. }
  5521. void AudioEngine::applyControllers()
  5522. {
  5523. ControllerEvent e;
  5524. // this frame's events in their order (round 190cs: a key or button link in Latch / Inc / Stay mode acts on each
  5525. // press, so presses are not merged); a plain controller still moves its control once, to its last value
  5526. std::vector<ControllerEvent> events;
  5527. std::map<std::tuple<int, int, int>, std::size_t> last; // (number, channel, port) -> its last event this frame
  5528. controllerLearnTick = learning.kind != AutomationTargetKind::none || multilink.has_value();
  5529. while (controllerQueue.pop (e))
  5530. {
  5531. // Auto detect of the Remote control settings window: controllers, and keys as they are pressed
  5532. if (! isNoteLink (e.cc) || e.value > 0)
  5533. controllerSeen = { e.port, e.channel, e.cc, e.value, controllerSeen.serial + 1 };
  5534. // round 190ef: in MIDI Map Mode a controller moved or a key pressed is caught for the selected control; nothing
  5535. // acts ("MIDI-mappings won't function while you're in MIDI Map Mode", the reference's lesson)
  5536. if (mapMode == remotemap::Mode::midi)
  5537. {
  5538. if (! isNoteLink (e.cc) || e.value > 0)
  5539. mapCaptured = remotemap::MidiControl { e.channel, e.cc, e.port };
  5540. continue;
  5541. }
  5542. if (e.seenOnly)
  5543. continue;
  5544. if (isNoteLink (e.cc)) // (MIDI learn and Multilink take controllers, as before)
  5545. {
  5546. last[{ e.cc, e.channel, e.port }] = events.size();
  5547. events.push_back (e);
  5548. continue;
  5549. }
  5550. if (learning.kind != AutomationTargetKind::none && learningGlobal)
  5551. {
  5552. // "Override global link...": the link goes to the settings, for every project (REA round 146)
  5553. auto p = midiPrefs;
  5554. prefs::GlobalLink g { e.cc, e.channel, (int) learning.kind, learning.index, learning.slot, learning.param };
  5555. g.port = e.port; // (round 190bt: the device's port number, as FL's Auto detect fills it)
  5556. p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
  5557. [&] (const prefs::GlobalLink& l) {
  5558. return l.kind == g.kind && l.index == g.index && l.slot == g.slot && l.param == g.param;
  5559. }),
  5560. p.globalLinks.end());
  5561. p.globalLinks.push_back (g);
  5562. learning = {};
  5563. learningGlobal = false;
  5564. setMidiPrefs (p, saveGlobalLinks);
  5565. }
  5566. else if (learning.kind == AutomationTargetKind::none && multilink)
  5567. {
  5568. // FL's Multilink (round 177b-4): the first message of each controller links the next queued control
  5569. if (const auto link = multilink->controller (e.cc, e.channel))
  5570. {
  5571. if (multilink->global) // "Override global links": as "Override global link...", for every project
  5572. {
  5573. auto p = midiPrefs;
  5574. prefs::GlobalLink g { link->cc, link->channel, (int) link->target.kind, link->target.index, link->target.slot,
  5575. link->target.param };
  5576. g.port = e.port;
  5577. p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
  5578. [&] (const prefs::GlobalLink& l) {
  5579. return l.kind == g.kind && l.index == g.index && l.slot == g.slot && l.param == g.param;
  5580. }),
  5581. p.globalLinks.end());
  5582. p.globalLinks.push_back (g);
  5583. setMidiPrefs (p, saveGlobalLinks);
  5584. }
  5585. else
  5586. editSong ([l = *link, port = e.port] (Song& s) {
  5587. s.midiLinks.erase (std::remove_if (s.midiLinks.begin(), s.midiLinks.end(), [&] (const MidiLink& m) { return m.target == l.target; }),
  5588. s.midiLinks.end());
  5589. MidiLink made { l.cc, l.channel, l.target };
  5590. made.port = port;
  5591. s.midiLinks.push_back (std::move (made));
  5592. });
  5593. if (multilink->complete())
  5594. multilink.reset(); // FL: "the process will auto-close once the number of hardware controls tweaked
  5595. // equals the number of software targets"
  5596. sendChangeMessage();
  5597. }
  5598. }
  5599. else if (learning.kind != AutomationTargetKind::none)
  5600. {
  5601. // MIDI learn: replace the old link for the same target with the new one
  5602. editSong ([t = learning, e] (Song& s) {
  5603. s.midiLinks.erase (std::remove_if (s.midiLinks.begin(), s.midiLinks.end(), [&] (const MidiLink& l) { return l.target == t; }),
  5604. s.midiLinks.end());
  5605. MidiLink made { e.cc, e.channel, t };
  5606. made.port = e.port;
  5607. s.midiLinks.push_back (std::move (made));
  5608. });
  5609. learning = {};
  5610. }
  5611. last[{ e.cc, e.channel, e.port }] = events.size();
  5612. events.push_back (e);
  5613. }
  5614. const auto links = linksWithGlobal (song.midiLinks, getGlobalLinks());
  5615. // round 190hp: the Map Mode's mappings kept for every project that act here (the project's own win)
  5616. const auto globalMappings = midiPrefs.globalMappings.empty() ? std::vector<RemoteMapping> {} : remotemap::activeGlobalMappings (song, midiPrefs);
  5617. {
  5618. std::uint64_t bits[2] {}, notes[2] {};
  5619. for (const auto& link : links)
  5620. if (link.cc >= 0 && link.cc < 128)
  5621. bits[link.cc >> 6] |= std::uint64_t { 1 } << (link.cc & 63);
  5622. else if (isNoteLink (link.cc))
  5623. notes[(link.cc - linkNoteBase) >> 6] |= std::uint64_t { 1 } << ((link.cc - linkNoteBase) & 63);
  5624. remotemap::usedNumbers (song, bits, notes); // (round 190ef: the MIDI mappings of slots, scenes, transport)
  5625. remotemap::usedNumbers (globalMappings, bits, notes); // (round 190hp: and those for every project)
  5626. for (int w = 0; w < 2; ++w)
  5627. {
  5628. linkedCcs[(std::size_t) w].store (bits[w], std::memory_order_relaxed);
  5629. linkedNotes[(std::size_t) w].store (notes[w], std::memory_order_relaxed);
  5630. }
  5631. }
  5632. if (mapMode == remotemap::Mode::midi)
  5633. return;
  5634. // round 190ef: the MIDI mappings of clip slots, scenes, track stop buttons and transport switches (presses and releases)
  5635. if (! song.remoteMappings.empty() || ! globalMappings.empty())
  5636. for (const auto& ev : events)
  5637. {
  5638. auto& previous = remoteValues.try_emplace ({ ev.cc, ev.channel, ev.port }, -1).first->second;
  5639. const auto fires = remotemap::midiFires (song, globalMappings, ev.channel, ev.cc, ev.value, previous, ev.port);
  5640. previous = ev.value;
  5641. if (! fires.empty()) // round 190ld: the MIDI light's "handled" colour
  5642. ++midiProjectLinked;
  5643. if (onRemoteFire != nullptr)
  5644. for (const auto& f : fires)
  5645. onRemoteFire (f);
  5646. }
  5647. if ((events.empty() || links.empty()) && linkSmoothing.empty())
  5648. return;
  5649. // one snapshot per frame, outside the undo history (like turning the knob)
  5650. std::vector<std::pair<AutomationTarget, float>> changes;
  5651. const auto mixerTrack = selectedMixerTrackForLinks ? selectedMixerTrackForLinks() : -1;
  5652. std::map<std::tuple<int, int, int, int>, float> moved; // a control's position after this frame's events so far
  5653. for (std::size_t i = 0; i < events.size(); ++i)
  5654. {
  5655. const auto& ev = events[i];
  5656. const auto lastOfKey = last[{ ev.cc, ev.channel, ev.port }] == i;
  5657. for (const auto& link : links)
  5658. {
  5659. // (round 190bt: a link follows the devices with exactly its port number, as FL's controller id does)
  5660. if (link.cc != ev.cc || ! (link.channel < 0 || link.channel == ev.channel) || link.port != ev.port)
  5661. continue;
  5662. // round 190ld (FL's Sync indicator): a project link (the list's first part) or a global one took it
  5663. if (&link - links.data() < (std::ptrdiff_t) song.midiLinks.size())
  5664. ++midiProjectLinked;
  5665. else
  5666. ++midiGlobalLinked;
  5667. const auto absolute = linkformula::linkModeIsAbsolute (link.mode);
  5668. if (absolute && ! lastOfKey)
  5669. continue; // (a controller's earlier values this frame: only the last one moves the control)
  5670. static const linkformula::Formula oneToOne;
  5671. const auto* formula = &oneToOne;
  5672. if (! link.formula.empty()) // FL's mapping formula: Input = the controller's position, the result limited to 0..1
  5673. {
  5674. auto found = linkFormulas.find (link.formula);
  5675. if (found == linkFormulas.end())
  5676. {
  5677. if (linkFormulas.size() > 256)
  5678. linkFormulas.clear();
  5679. found = linkFormulas.emplace (link.formula, linkformula::Formula::compile (link.formula)).first;
  5680. }
  5681. formula = &found->second;
  5682. }
  5683. const auto t = linkOmniTarget (link, selectedChannel, mixerTrack); // "Omni": the selected channel / track
  5684. const std::tuple<int, int, int, int> id { (int) t.kind, t.index, t.slot, t.param };
  5685. // FL's Mode (round 190cs): Latch and Inc start from where the control is now
  5686. auto current = 0.0f;
  5687. if (! absolute)
  5688. {
  5689. if (const auto m = moved.find (id); m != moved.end())
  5690. current = m->second;
  5691. else if (const auto now = currentTargetValue (t); now >= 0.0f)
  5692. current = now;
  5693. }
  5694. const auto mapped = linkformula::linkModeValue (link.mode, *formula, (float) ev.value / 127.0f, current);
  5695. if (! mapped)
  5696. continue; // (a release in Latch / Inc / Stay)
  5697. // round 190ef: the mapping's Min / Max (the reference's range; 0 / 1 keeps the position as it was)
  5698. const auto v = absolute ? remotemap::applyRange (*mapped, link.min, link.max) : *mapped;
  5699. // takeover: only parameters the song holds (a plugin's own parameters have no value to compare here), and
  5700. // only for links that follow the controller's position
  5701. const auto songHeld = t.kind != AutomationTargetKind::channelParam && t.kind != AutomationTargetKind::effectParam;
  5702. if (midiPrefs.pickup && songHeld && absolute)
  5703. {
  5704. auto& state = pickups[{ ev.cc, ev.channel, (int) t.kind, t.index, t.slot, t.param }];
  5705. if (! prefs::pickupUpdate (state, song.targetValue (t), v))
  5706. continue;
  5707. }
  5708. moved[id] = v;
  5709. noteTweaked (t); // a linked controller's move is a tweak (Last tweaked, automation recording)
  5710. if (link.smooth && link.smoothing != 0)
  5711. {
  5712. auto s = std::find_if (linkSmoothing.begin(), linkSmoothing.end(), [&] (const LinkSmoothing& x) { return x.link == link; });
  5713. if (s == linkSmoothing.end())
  5714. {
  5715. // starts from where the control is (a control the song does not hold starts at the new position)
  5716. LinkSmoothing fresh { link, v, {} };
  5717. if (const auto now = currentTargetValue (t); now >= 0.0f)
  5718. fresh.filter.step (now, 0.0, link.smoothing);
  5719. linkSmoothing.push_back (std::move (fresh));
  5720. }
  5721. else
  5722. s->target = v;
  5723. continue;
  5724. }
  5725. changes.push_back ({ t, v });
  5726. }
  5727. }
  5728. stepLinkSmoothing (changes);
  5729. applyTargetValues (changes);
  5730. }
  5731. void AudioEngine::applyTargetValues (const std::vector<std::pair<AutomationTarget, float>>& changes)
  5732. {
  5733. std::vector<std::pair<AutomationTarget, float>> pluginChanges;
  5734. editSong ([&] (Song& s) {
  5735. for (const auto& [target, v] : changes)
  5736. if (! s.setTargetValue (target, v))
  5737. pluginChanges.push_back ({ target, v });
  5738. }, false);
  5739. // plugin parameters live in the plugin
  5740. for (const auto& [target, v] : pluginChanges)
  5741. {
  5742. if (target.kind == AutomationTargetKind::channelParam)
  5743. {
  5744. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (target.index).get()))
  5745. p->setParameterFromUi (target.param, v);
  5746. // a MIDI Out's controls: the plugins on its port (REA_rodada133 §4)
  5747. if (target.index >= 0 && target.index < (int) song.channels.size()
  5748. && song.channels[(std::size_t) target.index].instrument == InstrumentKind::midiOut)
  5749. {
  5750. const auto port = midictl::parseMidiOut (song.channels[(std::size_t) target.index].pluginState).port;
  5751. for (int c = 0; c < (int) song.channels.size(); ++c)
  5752. if (song.channels[(std::size_t) c].instrument == InstrumentKind::plugin && song.channels[(std::size_t) c].plugin.midiInPort == port)
  5753. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (c).get()))
  5754. p->setParameterFromUi (target.param, v);
  5755. }
  5756. }
  5757. if (target.kind == AutomationTargetKind::effectParam)
  5758. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (target.index, target.slot).get()))
  5759. p->setParameterFromUi (target.param, v);
  5760. }
  5761. }
  5762. void AudioEngine::timerCallback()
  5763. {
  5764. // MIDI inputs: open the enabled devices that appeared (or were not ready) and reopen the ones that came back
  5765. if (midiOpen && ++midiCheckTicks >= 60) // every 2 s
  5766. {
  5767. midiCheckTicks = 0;
  5768. enableAllMidiInputs();
  5769. }
  5770. updateRealtimeStats();
  5771. // round 190gn (A1): the racks' pitch-shifter stocks back to their reserve (a voice took one: a live keyboard on a
  5772. // keep-pitch channel); nothing to do, and no allocation, when none was taken
  5773. shifterstock::topUpAll();
  5774. if (++hwTicks >= 5) // (6 times a second)
  5775. {
  5776. hwTicks = 0;
  5777. pumpEdisonRecordings(); // (round 190cd)
  5778. applyHardwareInsertPings();
  5779. }
  5780. rt::promotePending(); // Linux: real-time priority for the audio threads seen since the last tick (round 161)
  5781. updateAudition(); // (round 190ao: the preset audition's note starts and ends here)
  5782. applyControllers();
  5783. pumpGrossBeatPicks();
  5784. controllerIo.pump (controllerLearnTick); // (controller profiles, round 190aw)
  5785. // playback started: the moved controls follow their automation again (the renderer cleared its own mask)
  5786. if (const auto playing = transport.playing.load(); playing != std::exchange (releasedWasPlaying, playing) && playing)
  5787. releasedTargets.clear();
  5788. else if (! releasedTargets.empty())
  5789. publishReleasedTargets(); // (the slots follow the song: an automation added or removed renumbers them)
  5790. if (const auto note = pendingMarkerNote.exchange (-1); note >= 0)
  5791. jumpToMarker (note); // FL's "Song marker jump": note 0 = the first marker
  5792. updateRecording();
  5793. updatePerformanceRecording();
  5794. if (clipLauncher != nullptr)
  5795. {
  5796. updateLauncherRecording();
  5797. updateSlotRecording();
  5798. }
  5799. rackExchange.collectGarbage();
  5800. if (levelsPending && ! juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown())
  5801. flushLevels(); // a level drag ended: the full snapshot catches up (round 171c)
  5802. // Plugins are prepared at a fixed rate; if the device changed rate, recreate them.
  5803. // A plugin whose latency changed (preset change, lookahead) requests a new PDC plan.
  5804. const auto rateChanged = std::abs (transport.sampleRate.load() - lastPublishedShape.sampleRate) > 0.5;
  5805. const auto latencies = lastPublishedShape.currentLatencies();
  5806. if (! publishing && (rateChanged || latencies != lastPublishedShape.latencies)) // (not inside a publish: see publishSong)
  5807. {
  5808. // the plugins made for the new rate start from what the running ones hold now (issue #134: they started from
  5809. // the state of the last save or export, so a device at another rate undid every change made in their windows)
  5810. if (rateChanged)
  5811. capturePluginStates();
  5812. // (diagnostics: which unit's latency moved)
  5813. if (! rateChanged)
  5814. for (std::size_t i = 0; i < latencies.size() && i < lastPublishedShape.latencies.size(); ++i)
  5815. if (latencies[i] != lastPublishedShape.latencies[i])
  5816. {
  5817. lastLatencyChange = juce::String ((int) i) + ": " + juce::String (lastPublishedShape.latencies[i]) + " -> " + juce::String (latencies[i]);
  5818. break;
  5819. }
  5820. ++latencyRepublishes;
  5821. publishSong();
  5822. }
  5823. }
  5824. // Performance mode's recording (FL's "Clips" filter, REA round 146 B5: a launched clip is written to its playlist
  5825. // track): every pass of a launched clip that ended while recording becomes a copy of that clip in the arrangement,
  5826. // on the same track, where the song position was when the pass began.
  5827. void AudioEngine::updatePerformanceRecording()
  5828. {
  5829. auto& live = *performanceLive;
  5830. performanceMidiOn.store (song.performanceMode && song.mode == PlayMode::song && song.performanceZoneEnd() > 0, std::memory_order_relaxed);
  5831. const auto on = transport.recording.load() && transport.playing.load() && song.performanceMode && song.mode == PlayMode::song
  5832. && recordOptions.recordClips;
  5833. if (on && ! live.recording.load (std::memory_order_relaxed))
  5834. perfTakeHasUndoStep = false;
  5835. live.recording.store (on, std::memory_order_relaxed);
  5836. std::vector<Clip> clips;
  5837. perf::RecordedPass pass;
  5838. while (live.recorded.pop (pass))
  5839. if (Clip c; perf::recordedClip (song, pass, c) && c.start >= song.performanceZoneEnd())
  5840. clips.push_back (c);
  5841. if (clips.empty())
  5842. return;
  5843. editSong ([&clips] (Song& s) {
  5844. for (const auto& c : clips)
  5845. {
  5846. // the take replaces what was under it on that track (like FL's recorded clips)
  5847. const auto end = c.end();
  5848. for (auto& o : s.playlist)
  5849. if (o.track == c.track && o.start < end && o.end() > c.start && o.start >= s.performanceZoneEnd())
  5850. {
  5851. if (o.start >= c.start)
  5852. o.length = 0; // removed below
  5853. else
  5854. o.length = c.start - o.start;
  5855. }
  5856. s.playlist.erase (std::remove_if (s.playlist.begin(), s.playlist.end(), [] (const Clip& o) { return o.length <= 0; }),
  5857. s.playlist.end());
  5858. s.playlist.push_back (c);
  5859. }
  5860. }, ! perfTakeHasUndoStep);
  5861. perfTakeHasUndoStep = true;
  5862. }
  5863. // The clip grid's recording (round 181a): while recording, what is launched is written into the Playlist. Every pass that
  5864. // ended becomes a copy of its clip on its track, where the song was when the pass began, replacing what was under it.
  5865. void AudioEngine::updateLauncherRecording()
  5866. {
  5867. auto& runtime = *clipLauncher;
  5868. const auto on = transport.recording.load() && transport.playing.load() && song.clipGrid && song.mode == PlayMode::song && recordOptions.recordClips;
  5869. if (on && ! runtime.recording.load (std::memory_order_relaxed))
  5870. launcherTakeHasUndoStep = false;
  5871. runtime.recording.store (on, std::memory_order_relaxed);
  5872. std::vector<Clip> clips;
  5873. launcher::RecordedPass pass;
  5874. while (runtime.recorded.pop (pass))
  5875. if (Clip c; song.clipGrid && launcher::recordedClip (*song.clipGrid, pass, c))
  5876. clips.push_back (c);
  5877. if (clips.empty())
  5878. return;
  5879. editSong ([&clips] (Song& s) {
  5880. for (const auto& c : clips)
  5881. {
  5882. const auto end = c.end();
  5883. for (auto& o : s.playlist)
  5884. if (o.track == c.track && o.start < end && o.end() > c.start)
  5885. {
  5886. if (o.start >= c.start)
  5887. o.length = 0; // removed below
  5888. else
  5889. o.length = c.start - o.start;
  5890. }
  5891. s.playlist.erase (std::remove_if (s.playlist.begin(), s.playlist.end(), [] (const Clip& o) { return o.length <= 0; }),
  5892. s.playlist.end());
  5893. s.playlist.push_back (c);
  5894. }
  5895. }, ! launcherTakeHasUndoStep);
  5896. launcherTakeHasUndoStep = true;
  5897. }
  5898. void AudioEngine::choosePreferredDriver()
  5899. {
  5900. #if JUCE_LINUX || JUCE_BSD
  5901. std::vector<std::pair<std::string, bool>> types;
  5902. for (auto* type : deviceManager.getAvailableDeviceTypes())
  5903. {
  5904. type->scanForDevices();
  5905. types.emplace_back (type->getTypeName().toStdString(), ! type->getDeviceNames (false).isEmpty());
  5906. }
  5907. const auto best = juce::String (prefs::preferredLinuxDriver (types));
  5908. if (best.isNotEmpty() && best != deviceManager.getCurrentAudioDeviceType())
  5909. {
  5910. deviceManager.setCurrentAudioDeviceType (best, true);
  5911. if (deviceManager.getCurrentAudioDevice() == nullptr) // it would not open: back to what worked
  5912. deviceManager.initialise (0, 2, nullptr, true);
  5913. }
  5914. #endif
  5915. }
  5916. void AudioEngine::chooseSafeBufferSize()
  5917. {
  5918. auto* device = deviceManager.getCurrentAudioDevice();
  5919. if (device == nullptr)
  5920. return;
  5921. std::vector<int> sizes;
  5922. for (auto b : device->getAvailableBufferSizes())
  5923. sizes.push_back (b);
  5924. const auto current = device->getCurrentBufferSizeSamples();
  5925. const auto target = prefs::safeBufferSize (sizes, current, device->getCurrentSampleRate());
  5926. if (target > 0 && target != current)
  5927. {
  5928. auto setup = deviceManager.getAudioDeviceSetup();
  5929. setup.bufferSize = target;
  5930. deviceManager.setAudioDeviceSetup (setup, true);
  5931. }
  5932. }
  5933. bool AudioEngine::showDriverPanel (juce::AudioDeviceManager& devices)
  5934. {
  5935. auto* device = devices.getCurrentAudioDevice();
  5936. if (device == nullptr || ! device->hasControlPanel())
  5937. return false;
  5938. // JUCE's ASIO device: true when the panel stayed open long enough to have changed something (its own selector
  5939. // then closes and restarts the device the same way)
  5940. if (! device->showControlPanel())
  5941. return false;
  5942. auto setup = devices.getAudioDeviceSetup();
  5943. devices.closeAudioDevice(); // deletes `device`
  5944. device = nullptr;
  5945. // 0 = the new device's default, i.e. the preferred size the driver now reports (ASIO4ALL / FL ASIO: its panel's
  5946. // buffer); a driver that keeps no preferred size gets LYNX's usual default
  5947. setup.bufferSize = 0;
  5948. devices.setAudioDeviceSetup (setup, true);
  5949. return true;
  5950. }
  5951. namespace
  5952. {
  5953. // A driver with its own panel, like ASIO4ALL / FL ASIO: the panel sets the preferred buffer size the next device
  5954. // object reads. Every live device is tracked, so a call on a deleted one is caught instead of crashing.
  5955. struct PanelTestState
  5956. {
  5957. std::vector<const void*> alive;
  5958. int preferred = 256;
  5959. int panelResult = 64; // the size the panel picks; 0 = the panel changes nothing (returns false)
  5960. bool calledDeleted = false;
  5961. };
  5962. PanelTestState& panelTest()
  5963. {
  5964. static PanelTestState state;
  5965. return state;
  5966. }
  5967. struct PanelTestDevice final : juce::AudioIODevice
  5968. {
  5969. PanelTestDevice() : juce::AudioIODevice ("Panel test device", "Panel test"), preferred (panelTest().preferred) { panelTest().alive.push_back (this); }
  5970. ~PanelTestDevice() override
  5971. {
  5972. close();
  5973. auto& alive = panelTest().alive;
  5974. alive.erase (std::remove (alive.begin(), alive.end(), (const void*) this), alive.end());
  5975. }
  5976. bool isAlive() const { const auto& a = panelTest().alive; return std::find (a.begin(), a.end(), (const void*) this) != a.end(); }
  5977. juce::StringArray getOutputChannelNames() override { return { "Out 1", "Out 2" }; }
  5978. juce::StringArray getInputChannelNames() override { return {}; }
  5979. juce::Array<double> getAvailableSampleRates() override { return { 44100.0, 48000.0 }; }
  5980. juce::Array<int> getAvailableBufferSizes() override { return { 64, 128, 256, 272, 512 }; }
  5981. int getDefaultBufferSize() override { return preferred; }
  5982. juce::String open (const juce::BigInteger&, const juce::BigInteger& outs, double rate, int size) override
  5983. {
  5984. rateNow = rate;
  5985. sizeNow = size;
  5986. outsNow = outs;
  5987. opened = true;
  5988. return {};
  5989. }
  5990. void close() override { stop(); opened = false; }
  5991. bool isOpen() override { return opened; }
  5992. void start (juce::AudioIODeviceCallback* cb) override
  5993. {
  5994. if (cb != nullptr)
  5995. cb->audioDeviceAboutToStart (this);
  5996. callback = cb;
  5997. }
  5998. void stop() override
  5999. {
  6000. if (auto* cb = std::exchange (callback, nullptr))
  6001. cb->audioDeviceStopped();
  6002. }
  6003. bool isPlaying() override { return callback != nullptr; }
  6004. juce::String getLastError() override { return {}; }
  6005. int getCurrentBufferSizeSamples() override { return sizeNow; }
  6006. double getCurrentSampleRate() override { return rateNow; }
  6007. int getCurrentBitDepth() override { return 32; }
  6008. juce::BigInteger getActiveOutputChannels() const override { return outsNow; }
  6009. juce::BigInteger getActiveInputChannels() const override { return {}; }
  6010. int getOutputLatencyInSamples() override { return 0; }
  6011. int getInputLatencyInSamples() override { return 0; }
  6012. bool hasControlPanel() const override { return true; }
  6013. bool showControlPanel() override
  6014. {
  6015. if (! isAlive())
  6016. {
  6017. panelTest().calledDeleted = true;
  6018. return false;
  6019. }
  6020. if (panelTest().panelResult == 0)
  6021. return false;
  6022. panelTest().preferred = panelTest().panelResult; // what the driver now reports to a new device object
  6023. return true;
  6024. }
  6025. const int preferred;
  6026. double rateNow = 44100.0;
  6027. int sizeNow = 0;
  6028. juce::BigInteger outsNow;
  6029. bool opened = false;
  6030. juce::AudioIODeviceCallback* callback = nullptr;
  6031. };
  6032. struct PanelTestType final : juce::AudioIODeviceType
  6033. {
  6034. PanelTestType() : juce::AudioIODeviceType ("Panel test") {}
  6035. void scanForDevices() override {}
  6036. juce::StringArray getDeviceNames (bool input) const override { return input ? juce::StringArray() : juce::StringArray ("Panel test device"); }
  6037. int getDefaultDeviceIndex (bool input) const override { return input ? -1 : 0; }
  6038. int getIndexOfDevice (juce::AudioIODevice* d, bool input) const override { return d != nullptr && ! input ? 0 : -1; }
  6039. bool hasSeparateInputsAndOutputs() const override { return false; }
  6040. juce::AudioIODevice* createDevice (const juce::String& out, const juce::String&) override
  6041. {
  6042. return out == "Panel test device" ? new PanelTestDevice() : nullptr;
  6043. }
  6044. };
  6045. } // namespace
  6046. juce::String AudioEngine::driverPanelSelfTest()
  6047. {
  6048. auto& state = panelTest();
  6049. state = {};
  6050. juce::AudioDeviceManager devices;
  6051. devices.addAudioDeviceType (std::make_unique<PanelTestType>());
  6052. devices.setCurrentAudioDeviceType ("Panel test", true);
  6053. juce::AudioDeviceManager::AudioDeviceSetup setup;
  6054. setup.outputDeviceName = "Panel test device";
  6055. setup.sampleRate = 44100.0;
  6056. setup.bufferSize = 272; // chosen in LYNX's own buffer box
  6057. setup.useDefaultOutputChannels = true;
  6058. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  6059. return "open: " + error;
  6060. auto* before = devices.getCurrentAudioDevice();
  6061. if (before == nullptr || before->getCurrentBufferSizeSamples() != 272)
  6062. return "open: buffer " + juce::String (before != nullptr ? before->getCurrentBufferSizeSamples() : -1);
  6063. // a panel that changes nothing: the same device keeps running with LYNX's buffer
  6064. state.panelResult = 0;
  6065. if (showDriverPanel (devices) || devices.getCurrentAudioDevice() != before || before->getCurrentBufferSizeSamples() != 272)
  6066. return "unchanged panel reopened the device";
  6067. // the panel picks 64 samples (issue #13's ASIO4ALL setting): reopened, the panel's buffer kept, never the old object
  6068. state.panelResult = 64;
  6069. if (! showDriverPanel (devices))
  6070. return "changed panel did not reopen";
  6071. auto* after = devices.getCurrentAudioDevice();
  6072. if (state.calledDeleted)
  6073. return "called the deleted device";
  6074. if (after == nullptr || ! after->isOpen())
  6075. return "no device after the panel";
  6076. if (after->getCurrentBufferSizeSamples() != 64)
  6077. return "buffer " + juce::String (after->getCurrentBufferSizeSamples()) + " after the panel chose 64";
  6078. if (state.alive.size() != 1)
  6079. return juce::String ((int) state.alive.size()) + " devices alive";
  6080. // and the reopened device can show its panel again (the button pressed twice)
  6081. state.panelResult = 128;
  6082. if (! showDriverPanel (devices) || devices.getCurrentAudioDevice() == nullptr || devices.getCurrentAudioDevice()->getCurrentBufferSizeSamples() != 128
  6083. || state.calledDeleted)
  6084. return "second panel";
  6085. devices.closeAudioDevice();
  6086. return "OK";
  6087. }
  6088. juce::File AudioEngine::glitchLogFile() { return PluginHost::settingsFolder().getChildFile ("audio-glitches.log"); }
  6089. void AudioEngine::updateRealtimeStats()
  6090. {
  6091. // the message thread's pulse: this 30 Hz timer arriving late means the UI is saturated
  6092. {
  6093. const auto now = juce::Time::getMillisecondCounterHiRes();
  6094. if (lastUiPulseMs > 0.0)
  6095. uiPulse.maxGapMs = juce::jmax (uiPulse.maxGapMs, now - lastUiPulseMs);
  6096. lastUiPulseMs = now;
  6097. ++uiPulse.calls;
  6098. }
  6099. // every ~2 s: the share of real time each channel / insert effect took in that window
  6100. if (rackProcessor != nullptr && juce::Time::getMillisecondCounterHiRes() - lastUnitsWindowMs >= 2000.0)
  6101. {
  6102. lastUnitsWindowMs = juce::Time::getMillisecondCounterHiRes();
  6103. auto& renderer = rackProcessor->getRenderer();
  6104. const auto& units = renderer.unitTimes();
  6105. const auto processed = units.processedSamples.load (std::memory_order_relaxed);
  6106. const auto rate = juce::jmax (1.0, transport.sampleRate.load());
  6107. const auto audioNs = (double) (processed - std::min (processed, lastProcessedSamples)) / rate * 1.0e9;
  6108. lastProcessedSamples = processed;
  6109. lastChannelNs.resize (units.channelNs.size(), 0);
  6110. lastEffectNs.resize (units.effectNs.size(), 0);
  6111. std::vector<UnitLoad> loads;
  6112. auto take = [&] (const std::atomic<std::uint64_t>& total, std::uint64_t& last, std::atomic<std::uint64_t>& longest, auto&& name) {
  6113. const auto now = total.load (std::memory_order_relaxed);
  6114. const auto delta = now - std::min (now, last);
  6115. last = now;
  6116. const auto longestNs = const_cast<std::atomic<std::uint64_t>&> (longest).exchange (0, std::memory_order_relaxed);
  6117. if (delta > 0 && audioNs > 0.0)
  6118. loads.push_back ({ name(), (double) delta / audioNs, (double) longestNs * 1.0e-6 });
  6119. };
  6120. auto& mutableUnits = const_cast<RackRenderer::UnitTimes&> (units);
  6121. for (std::size_t c = 0; c < units.channelNs.size(); ++c)
  6122. take (units.channelNs[c], lastChannelNs[c], mutableUnits.channelMaxNs[c], [&] {
  6123. return c < song.channels.size() ? juce::String::fromUTF8 (song.channels[c].name.c_str()) : "Channel " + juce::String ((int) c + 1);
  6124. });
  6125. for (std::size_t k = 0; k < units.effectNs.size(); ++k)
  6126. take (units.effectNs[k], lastEffectNs[k], mutableUnits.effectMaxNs[k], [&] {
  6127. const auto t = k / (std::size_t) maxEffectSlots, slot = k % (std::size_t) maxEffectSlots;
  6128. juce::String effect;
  6129. if (t < song.mixer.size() && slot < song.mixer[t].effects.size())
  6130. {
  6131. const auto& fx = song.mixer[t].effects[slot];
  6132. effect = juce::String::fromUTF8 (fx.plugin.name.empty() ? effectInfo (fx.kind).name : fx.plugin.name.c_str());
  6133. }
  6134. 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())
  6135. : "Insert " + juce::String ((int) t));
  6136. return track + " / " + juce::String ((int) slot + 1) + " " + effect;
  6137. });
  6138. std::sort (loads.begin(), loads.end(), [] (const UnitLoad& a, const UnitLoad& b) { return a.load > b.load; });
  6139. if (loads.size() > 8)
  6140. loads.resize (8);
  6141. if (audioNs > 0.0)
  6142. heaviestUnits = std::move (loads);
  6143. }
  6144. // round 190gg (B5): the dropout log (how many, the last one's time and cause)
  6145. const auto stats = rtStats.snapshot();
  6146. {
  6147. dropouts::Poll poll;
  6148. poll.nowMs = juce::Time::getMillisecondCounterHiRes();
  6149. poll.overBudget = stats.overBudget;
  6150. poll.lateCalls = stats.lateCalls;
  6151. auto* device = deviceManager.getCurrentAudioDevice();
  6152. poll.deviceXruns = device != nullptr ? device->getXRunCount() : -1;
  6153. poll.windowMaxLoad = rtStats.takeDropoutWindowMaxLoad();
  6154. poll.lastOverSlowest = stats.lastOverSlowest;
  6155. poll.lastOverLoad = stats.lastOverLoad;
  6156. dropoutLog.update (poll);
  6157. }
  6158. // a line in the glitch log when callbacks ran over their deadline or the device called late
  6159. if ((stats.overBudget > loggedOver || stats.lateCalls > loggedLate) && juce::Time::getMillisecondCounterHiRes() - lastLogMs > 2000.0)
  6160. {
  6161. // (appended by fileJobs: this runs on the message thread, and at a small buffer glitches come every 2 s)
  6162. const auto bar = transport.positionTicks.load() / (double) song.barTicks() + 1.0;
  6163. auto line = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H:%M:%S") + " over deadline +" + juce::String ((juce::int64) (stats.overBudget - loggedOver))
  6164. + ", late calls +" + juce::String ((juce::int64) (stats.lateCalls - loggedLate)) + ", at bar " + juce::String (bar, 2)
  6165. + (transport.playing.load() ? "" : " (stopped)") + "\n" + describeRealtime() + "\n";
  6166. fileJobs.post ([line = std::move (line), file = glitchLogFile()] {
  6167. if (file.getSize() > 1024 * 1024)
  6168. file.moveFileTo (file.withFileExtension ("old.log"));
  6169. file.appendText (line, false, false, "\r\n");
  6170. });
  6171. loggedOver = stats.overBudget;
  6172. loggedLate = stats.lateCalls;
  6173. lastLogMs = juce::Time::getMillisecondCounterHiRes();
  6174. }
  6175. }
  6176. juce::String AudioEngine::unitDisplayName (std::uint32_t unit) const
  6177. {
  6178. if (unit == 0)
  6179. return {};
  6180. if (dropouts::isChannel (unit))
  6181. {
  6182. const auto c = (std::size_t) dropouts::channelOf (unit);
  6183. return c < song.channels.size() ? juce::String::fromUTF8 (song.channels[c].name.c_str()) : "Channel " + juce::String ((int) c + 1);
  6184. }
  6185. const auto k = dropouts::effectKeyOf (unit);
  6186. const auto t = k / (std::size_t) maxEffectSlots, slot = k % (std::size_t) maxEffectSlots;
  6187. juce::String effect;
  6188. if (t < song.mixer.size() && slot < song.mixer[t].effects.size())
  6189. {
  6190. const auto& fx = song.mixer[t].effects[slot];
  6191. effect = juce::String::fromUTF8 (fx.plugin.name.empty() ? effectInfo (fx.kind).name : fx.plugin.name.c_str());
  6192. }
  6193. 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())
  6194. : "Insert " + juce::String ((int) t));
  6195. return track + " / " + juce::String ((int) slot + 1) + " " + effect;
  6196. }
  6197. AudioEngine::DropoutInfo AudioEngine::dropoutInfo() const
  6198. {
  6199. DropoutInfo d;
  6200. d.count = dropoutLog.count();
  6201. d.processing = dropoutLog.processing();
  6202. d.system = dropoutLog.system();
  6203. d.secondsAgo = dropoutLog.secondsSince (juce::Time::getMillisecondCounterHiRes());
  6204. d.cause = dropoutLog.cause();
  6205. d.load = dropoutLog.load();
  6206. if (const auto slowest = dropoutLog.slowest(); slowest != 0)
  6207. {
  6208. d.slowest = unitDisplayName (dropouts::unitOf (slowest));
  6209. d.slowestMs = (double) dropouts::nanosecondsOf (slowest) * 1.0e-6;
  6210. }
  6211. if (auto* device = const_cast<LynxDeviceManager&> (deviceManager).getCurrentAudioDevice())
  6212. if (device->getCurrentSampleRate() > 0.0)
  6213. d.bufferMs = 1000.0 * device->getCurrentBufferSizeSamples() / device->getCurrentSampleRate();
  6214. return d;
  6215. }
  6216. const renderahead::Stats* AudioEngine::renderAheadStats() const noexcept
  6217. {
  6218. return rackProcessor != nullptr ? &rackProcessor->renderAheadStats() : nullptr;
  6219. }
  6220. void AudioEngine::setEditorOpen (const void* key, std::function<PluginRef* (Song&)> find, int track, bool open)
  6221. {
  6222. openEditors.erase (std::remove_if (openEditors.begin(), openEditors.end(), [key] (const OpenEditor& e) { return e.key == key; }), openEditors.end());
  6223. if (open)
  6224. openEditors.push_back ({ key, std::move (find), track });
  6225. publishRenderAheadTargets();
  6226. }
  6227. void AudioEngine::setRenderAheadAlways (bool always) noexcept
  6228. {
  6229. if (rackProcessor != nullptr)
  6230. rackProcessor->setRenderAheadAlways (always);
  6231. }
  6232. juce::String AudioEngine::describeRealtime (bool withUnits) const
  6233. {
  6234. juce::String text;
  6235. if (auto* device = const_cast<LynxDeviceManager&> (deviceManager).getCurrentAudioDevice())
  6236. {
  6237. const auto rate = device->getCurrentSampleRate();
  6238. const auto buffer = device->getCurrentBufferSizeSamples();
  6239. text << " device: " << device->getTypeName() << " / " << device->getName() << ", " << (int) rate << " Hz, buffer " << buffer
  6240. << " samples (deadline " << juce::String (prefs::bufferLatencyMs (buffer, rate), 2) << " ms), output latency "
  6241. << device->getOutputLatencyInSamples() << " samples, driver dropouts " << device->getXRunCount() << "\n";
  6242. #if JUCE_LINUX
  6243. text << " audio thread: " << (rt::status() == rt::Status::unknown ? juce::String ("not seen yet") : rt::describe()) << "\n";
  6244. #endif
  6245. #if JUCE_WINDOWS
  6246. if (const auto before = deviceThreadPriorityBefore.load (std::memory_order_relaxed); before > -100)
  6247. text << " device thread priority " << before << (deviceThreadPriorityAfter.load (std::memory_order_relaxed) != before
  6248. ? " -> " + juce::String (deviceThreadPriorityAfter.load (std::memory_order_relaxed)) + " (raised to MMCSS Pro Audio)"
  6249. : juce::String (boostDeviceThread ? " (kept)" : " (kept: LYNX_DEVICE_BOOST=0)")) << "\n";
  6250. if (const auto raised = rtThreadsRaised.load (std::memory_order_relaxed); raised > 0)
  6251. text << " audio threads raised " << raised << ": MMCSS Pro Audio " << rtThreadsMmcss.load (std::memory_order_relaxed)
  6252. << " (critical " << rtThreadsCritical.load (std::memory_order_relaxed) << "), thread priority "
  6253. << rtPriorityMin.load (std::memory_order_relaxed) << ".." << rtPriorityMax.load (std::memory_order_relaxed) << "\n";
  6254. text << " process priority class " << priorityClassName (priorityClassNow.load (std::memory_order_relaxed)) << " (found "
  6255. << priorityClassName (priorityClassFound.load (std::memory_order_relaxed)) << ")\n";
  6256. #endif
  6257. }
  6258. else
  6259. text << " device: none\n";
  6260. const auto s = rtStats.snapshot();
  6261. text << " callbacks " << (juce::int64) s.callbacks << ": over deadline " << (juce::int64) s.overBudget << ", 80-100% " << (juce::int64) s.nearBudget
  6262. << ", late device calls " << (juce::int64) s.lateCalls << ", average load " << juce::String (s.averageLoad * 100.0, 1) << "%, max "
  6263. << juce::String (s.maxLoad * 100.0, 0) << "%, workers " << (workers != nullptr ? workers->workers() : 0) << "\n";
  6264. if (const auto d = dropoutInfo(); d.count > 0) // (round 190gg)
  6265. text << " dropouts " << (juce::int64) d.count << " (processing " << (juce::int64) d.processing << ", driver / system " << (juce::int64) d.system
  6266. << "), the last " << d.secondsAgo << " s ago: " << (d.cause == dropouts::Cause::system ? "driver / system late" : "processing")
  6267. << ", load " << juce::String (d.load * 100.0, 0) << "%"
  6268. << (d.slowest.isNotEmpty() ? ", slowest " + d.slowest + " " + juce::String (d.slowestMs, 2) + " ms" : juce::String()) << "\n";
  6269. if (latencyRepublishes > 0)
  6270. text << " latency changes re-planned PDC " << latencyRepublishes << " times (last: unit " << lastLatencyChange << ")\n";
  6271. if (rackProcessor != nullptr) // (round 190gq: Options › Audio settings › "Render ahead")
  6272. {
  6273. const auto& r = rackProcessor->renderAheadStats();
  6274. auto n = [] (const std::atomic<std::uint64_t>& v) { return juce::String ((juce::int64) v.load (std::memory_order_relaxed)); };
  6275. text << " render ahead: " << (renderAheadOption().load() ? "on" : "off") << ", " << (r.engaged.load() ? "running" : "not running")
  6276. << ", window " << r.window.load() << " samples; blocks " << n (r.blocks) << ": from the ring " << n (r.fromRing) << ", waited "
  6277. << n (r.waited) << ", rendered in the callback " << n (r.inline_) << "; dropped " << n (r.flushes) << ", drained " << n (r.drains)
  6278. << ", started " << n (r.engagements) << ", states taken at once " << n (r.statesSwapped) << ", channels joined live " << n (r.promoted)
  6279. << ", partition changes " << n (r.partitionChanges) << ", boundary mismatches " << n (r.splitMismatches) << "; ahead "
  6280. << r.aheadChannels.load() << " channels / " << r.aheadTracks.load() << " inserts, boundary " << r.boundary.load() << "\n";
  6281. // (perfgate190id) the engagement rule's probes: how often, what they kept, and the last one's measurements
  6282. text << " render ahead probes " << n (r.probes) << ": kept on " << n (r.keptOn) << " (for fewer overruns " << n (r.keptForOverruns)
  6283. << "), kept off " << n (r.keptOff) << "; last probe CPU " << juce::String (r.probeCpuOff.load(), 1) << "% off / "
  6284. << juce::String (r.probeCpuOn.load(), 1) << "% on, overruns " << juce::String (r.probeOverOff.load(), 0) << " / "
  6285. << juce::String (r.probeOverOn.load(), 0) << " per minute\n";
  6286. }
  6287. if (withUnits && heaviestUnits.empty())
  6288. text << " heaviest: not measured yet\n";
  6289. if (withUnits && ! heaviestUnits.empty())
  6290. {
  6291. text << " heaviest:";
  6292. for (std::size_t i = 0; i < heaviestUnits.size() && i < 5; ++i)
  6293. text << (i > 0 ? ";" : "") << " " << heaviestUnits[i].name << " " << juce::String (heaviestUnits[i].load * 100.0, 1) << "% (peak "
  6294. << juce::String (heaviestUnits[i].longestMs, 1) << " ms)";
  6295. text << "\n";
  6296. }
  6297. return text;
  6298. }
  6299. bool AudioEngine::freezeOutOfDate (int channel)
  6300. {
  6301. if (channel < 0 || channel >= (int) song.channels.size() || ! song.channels[(std::size_t) channel].freeze.on())
  6302. return false;
  6303. if (freezeChecks.size() < song.channels.size())
  6304. freezeChecks.resize (song.channels.size());
  6305. auto& check = freezeChecks[(std::size_t) channel];
  6306. if (check.stamp != songStamp)
  6307. {
  6308. check.stamp = songStamp;
  6309. check.outOfDate = sessionpack::freezeSource (song, channel, transport.sampleRate.load()) != song.channels[(std::size_t) channel].freeze.source;
  6310. }
  6311. return check.outOfDate;
  6312. }
  6313. std::shared_ptr<Instrument> AudioEngine::getChannelInstrument (int channel) const
  6314. {
  6315. if (channel < 0 || channel >= (int) lastPublishedShape.instruments.size())
  6316. return nullptr;
  6317. return lastPublishedShape.instruments[(std::size_t) channel];
  6318. }
  6319. std::shared_ptr<Effect> AudioEngine::getEffect (int track, int slot) const
  6320. {
  6321. if (externalEffect)
  6322. return externalEffect();
  6323. const auto& effects = lastPublishedShape.effects;
  6324. if (track < 0 || track >= (int) effects.size() || slot < 0 || slot >= (int) effects[(std::size_t) track].size())
  6325. return nullptr;
  6326. return effects[(std::size_t) track][(std::size_t) slot];
  6327. }
  6328. bool AudioEngine::holdForExport (int timeoutMs)
  6329. {
  6330. if (exportHold.load (std::memory_order_acquire))
  6331. return true;
  6332. // (a recording or a real-time export plays on through the device: their plugins can't be lent)
  6333. if (transport.recording.load() || bouncing || isCountingIn())
  6334. return false;
  6335. // FL stops playback for its render (REA_rodada155 / 190jb)
  6336. if (transport.playing.load())
  6337. stop();
  6338. exportHold.store (true, std::memory_order_seq_cst);
  6339. // the block in progress ends; every later one outputs silence without the rack
  6340. const auto until = juce::Time::getMillisecondCounterHiRes() + juce::jmax (0, timeoutMs);
  6341. while (callbackBusy.load (std::memory_order_seq_cst))
  6342. {
  6343. if (juce::Time::getMillisecondCounterHiRes() > until)
  6344. {
  6345. exportHold.store (false, std::memory_order_seq_cst);
  6346. return false;
  6347. }
  6348. juce::Thread::sleep (1);
  6349. }
  6350. // the part rendered ahead stops too (its thread may be in a block of its own)
  6351. if (rackProcessor != nullptr)
  6352. rackProcessor->haltRenderAhead();
  6353. return true;
  6354. }
  6355. void AudioEngine::releaseAfterExport()
  6356. {
  6357. if (! exportHold.load (std::memory_order_acquire))
  6358. return;
  6359. if (rackProcessor != nullptr)
  6360. rackProcessor->resumeRenderAhead();
  6361. exportHold.store (false, std::memory_order_seq_cst);
  6362. // the export's rack gave the lent units its own routes (a plugin's outputs, Connections, its side input): this
  6363. // song's come back with a build of it
  6364. publishSong();
  6365. }
  6366. void AudioEngine::setLiveUnits (LiveInstrumentSource instrument, LiveEffectSource effect)
  6367. {
  6368. lentUnits.clear();
  6369. if (instrument)
  6370. liveInstrumentSource = [this, instrument = std::move (instrument)] (const ChannelDef& c, double rate) {
  6371. auto unit = instrument (c, rate);
  6372. if (unit != nullptr)
  6373. lentUnits.push_back (unit.get());
  6374. return unit;
  6375. };
  6376. else
  6377. liveInstrumentSource = nullptr;
  6378. if (effect)
  6379. liveEffectSource = [this, effect = std::move (effect)] (const EffectSlot& e, double rate) {
  6380. auto unit = effect (e, rate);
  6381. if (unit != nullptr)
  6382. lentUnits.push_back (unit.get());
  6383. return unit;
  6384. };
  6385. else
  6386. liveEffectSource = nullptr;
  6387. }
  6388. void AudioEngine::setPluginsRenderMode (bool offline)
  6389. {
  6390. vfx::script::setRealtime (! offline); // (an export waits for every VFX Script answer: exact and repeatable)
  6391. if (! offline)
  6392. midiSync.sendAllNotesOff(); // FL's "Send all notes off": after a render
  6393. // FL's "Notify about rendering mode" off: that plugin is not told (round 149); "Reset plugin when FL Studio
  6394. // resets": reset as the export starts (round 151)
  6395. for (std::size_t i = 0; i < song.channels.size(); ++i)
  6396. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()))
  6397. {
  6398. if (song.channels[i].plugin.notifyRender)
  6399. p->setRenderMode (offline);
  6400. if (offline)
  6401. p->resetForExport();
  6402. }
  6403. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  6404. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  6405. if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()))
  6406. {
  6407. if (song.mixer[t].effects[s].plugin.notifyRender)
  6408. p->setRenderMode (offline);
  6409. if (offline)
  6410. p->resetForExport();
  6411. }
  6412. // the plugins inside Patchers (REA_rodada141)
  6413. std::function<void (patcher::Graph*)> graphMode = [&] (patcher::Graph* graph) {
  6414. if (graph == nullptr)
  6415. return;
  6416. for (int n = 0; n < graph->nodeCount(); ++n)
  6417. {
  6418. auto effect = graph->effectAt (n);
  6419. auto instrument = graph->instrumentAt (n);
  6420. if (auto* p = dynamic_cast<PluginEffect*> (effect.get()))
  6421. p->setRenderMode (offline);
  6422. if (auto* p = dynamic_cast<PluginInstrument*> (instrument.get()))
  6423. p->setRenderMode (offline);
  6424. graphMode (patcher::graphOf (effect.get()));
  6425. graphMode (patcher::graphOf (instrument.get()));
  6426. }
  6427. };
  6428. for (std::size_t i = 0; i < song.channels.size(); ++i)
  6429. graphMode (patcher::graphOf (getChannelInstrument ((int) i).get()));
  6430. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  6431. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  6432. graphMode (patcher::graphOf (getEffect ((int) t, (int) s).get()));
  6433. }
  6434. void AudioEngine::stampWorkTime()
  6435. {
  6436. const auto now = (double) juce::Time::currentTimeMillis();
  6437. if (workSince > 0.0 && now > workSince)
  6438. song.info.workSeconds += (now - workSince) / 1000.0;
  6439. workSince = now;
  6440. }
  6441. double AudioEngine::workSecondsNow() const
  6442. {
  6443. const auto now = (double) juce::Time::currentTimeMillis();
  6444. return song.info.workSeconds + (workSince > 0.0 && now > workSince ? (now - workSince) / 1000.0 : 0.0);
  6445. }
  6446. // FL's Project info › "Reset working time" (round 190bx; its handler stores "now" as the project's start and restarts
  6447. // the clock, without a question): the project counts from this moment on. Not an undo step, as the clock itself.
  6448. void AudioEngine::resetWorkTime()
  6449. {
  6450. const auto now = (double) juce::Time::currentTimeMillis();
  6451. lynx::resetWorkTime (song.info, now / 1000.0);
  6452. workSince = now;
  6453. modified = true;
  6454. sendChangeMessage(); // (the Info page; nothing the audio thread plays changed)
  6455. }
  6456. void AudioEngine::markCreatedNow()
  6457. {
  6458. if (song.info.created <= 0.0)
  6459. song.info.created = (double) juce::Time::currentTimeMillis() / 1000.0;
  6460. }
  6461. void AudioEngine::markCreatedFrom (const juce::File& file)
  6462. {
  6463. if (song.info.created <= 0.0)
  6464. if (const auto born = platform::fileBirthSeconds (file); born > 0.0)
  6465. song.info.created = born;
  6466. }
  6467. void AudioEngine::pumpGrossBeatPicks()
  6468. {
  6469. std::vector<std::pair<AutomationTarget, float>> changes;
  6470. const auto& effects = lastPublishedShape.effects;
  6471. for (std::size_t t = 0; t < song.mixer.size() && t < effects.size(); ++t)
  6472. for (std::size_t s = 0; s < song.mixer[t].effects.size() && s < effects[t].size(); ++s)
  6473. {
  6474. const auto& fx = song.mixer[t].effects[s];
  6475. if (fx.kind != EffectKind::grossBeat)
  6476. continue;
  6477. auto* picks = grossbeat::midiPicksOf (effects[t][s].get());
  6478. if (picks == nullptr)
  6479. continue;
  6480. const auto serial = picks->serial.load (std::memory_order_acquire);
  6481. if (serial == picks->taken.load (std::memory_order_relaxed))
  6482. continue;
  6483. picks->taken.store (serial, std::memory_order_relaxed);
  6484. for (const auto& [param, value] : grossbeat::paramsForPicks (*picks, fx.params))
  6485. {
  6486. AutomationTarget target;
  6487. target.kind = AutomationTargetKind::effectParam;
  6488. target.index = (int) t;
  6489. target.slot = (int) s;
  6490. target.param = param;
  6491. changes.push_back ({ target, value });
  6492. }
  6493. }
  6494. if (! changes.empty())
  6495. applyTargetValues (changes);
  6496. }
  6497. void AudioEngine::pumpEdisonRecordings()
  6498. {
  6499. bool finished = false;
  6500. for (const auto& track : song.mixer)
  6501. for (const auto& fx : track.effects)
  6502. if (fx.kind == EffectKind::edison)
  6503. if (const auto session = edisonfx::findSession (fx.instance.id); session != nullptr && session->recording() && ! session->pump())
  6504. finished = true; // (the maximum recording time, or its effect is gone)
  6505. if (finished)
  6506. flushEdisonAudio();
  6507. }
  6508. void AudioEngine::flushEdisonAudio()
  6509. {
  6510. struct Change
  6511. {
  6512. std::uint64_t instance;
  6513. std::string path;
  6514. bool clearState;
  6515. };
  6516. std::vector<Change> changes;
  6517. for (const auto& track : song.mixer)
  6518. for (const auto& fx : track.effects)
  6519. {
  6520. if (fx.kind != EffectKind::edison)
  6521. continue;
  6522. const auto session = edisonfx::findSession (fx.instance.id);
  6523. if (session == nullptr || session->recording())
  6524. continue;
  6525. const auto wasDirty = session->dirty();
  6526. if (wasDirty)
  6527. {
  6528. if (session->document().audio.empty())
  6529. session->save ({});
  6530. else
  6531. {
  6532. auto folder = recordingFolder;
  6533. if (! folder.createDirectory()) // e.g. a read-only project folder: the global recordings folder
  6534. folder = defaultRecordingFolder(), folder.createDirectory();
  6535. const auto name = (recordingStem.isNotEmpty() ? recordingStem + "_" : juce::String())
  6536. + juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S") + "_Edison";
  6537. const auto file = folder.getNonexistentChildFile (name, ".wav", false);
  6538. if (! session->save (file.getFullPathName().toStdString()))
  6539. {
  6540. recordingError = tr ("Could not write {0}", { file.getFullPathName() });
  6541. continue; // (it stays unsaved: the next flush tries again)
  6542. }
  6543. sessionRecordings.push_back (file); // (a file this project may end up not using, like a take)
  6544. }
  6545. }
  6546. // the slot follows its session: after a write here, or one by another engine of the same project
  6547. if (wasDirty || (! session->path().empty() && session->path() != fx.samplePath))
  6548. changes.push_back ({ fx.instance.id, session->path(), wasDirty });
  6549. }
  6550. if (changes.empty())
  6551. return;
  6552. auto apply = [&changes] (Song& s) {
  6553. for (auto& track : s.mixer)
  6554. for (auto& fx : track.effects)
  6555. if (fx.kind == EffectKind::edison)
  6556. for (const auto& c : changes)
  6557. if (c.instance == fx.instance.id)
  6558. {
  6559. fx.samplePath = c.path;
  6560. if (c.clearState)
  6561. fx.state.clear(); // (an imported slot: FL's state held the audio that was replaced)
  6562. }
  6563. };
  6564. const auto differs = std::any_of (changes.begin(), changes.end(), [this] (const Change& c) {
  6565. for (const auto& track : song.mixer)
  6566. for (const auto& fx : track.effects)
  6567. if (fx.kind == EffectKind::edison && fx.instance.id == c.instance)
  6568. return fx.samplePath != c.path || (c.clearState && ! fx.state.empty());
  6569. return false;
  6570. });
  6571. if (differs)
  6572. editSong (apply, false);
  6573. }
  6574. void AudioEngine::capturePluginStatesInto (Song& target, bool requireAll)
  6575. {
  6576. // round 190kx: the ARA plugins' documents (their edits) as they are now; a document not made here (its plugin is
  6577. // missing) keeps what the project had
  6578. if (araHost != nullptr && ara::anyAraChannel (target))
  6579. for (auto& doc : araHost->archives())
  6580. {
  6581. auto it = std::find_if (target.araDocuments.begin(), target.araDocuments.end(), [&doc] (const AraDocumentArchive& a) { return a.pluginId == doc.pluginId; });
  6582. if (it != target.araDocuments.end())
  6583. *it = std::move (doc);
  6584. else
  6585. target.araDocuments.push_back (std::move (doc));
  6586. }
  6587. const auto capture = [requireAll] (auto* plugin) {
  6588. auto state = plugin->captureState();
  6589. if (! state && requireAll) throw RemoteError ("failed", "Cannot capture a live device; no project changes were made");
  6590. return state;
  6591. };
  6592. // round 190mc (discussion #202): a Transistor Bass whose notes chose another program (its sequencer on, FL's AF)
  6593. // saves that program, as FL does, whether or not its page showed it
  6594. for (std::size_t i = 0; i < target.channels.size(); ++i)
  6595. if (target.channels[i].instrument == InstrumentKind::transistorbass)
  6596. if (const auto instrument = getChannelInstrument ((int) i))
  6597. if (const auto selected = instrument->selectedProgram(); selected >= 0)
  6598. if (const auto prog = transistorBassProgram (target.channels[i].pluginState); prog && prog->program != selected)
  6599. transistorBassSelectProgram (target.channels[i].pluginState, selected);
  6600. // Changes only the saved state (recreates nothing and doesn't enter the undo history).
  6601. for (std::size_t i = 0; i < target.channels.size(); ++i)
  6602. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()))
  6603. if (target.channels[i].plugin.playedBy == 0) // (P5-A1: a plugin shared in a live session keeps no state, only values)
  6604. if (auto state = capture (p)) // (a plugin that crashed keeps the state saved before)
  6605. target.channels[i].plugin.state = std::move (*state);
  6606. for (std::size_t t = 0; t < target.mixer.size(); ++t)
  6607. for (std::size_t s = 0; s < target.mixer[t].effects.size(); ++s)
  6608. if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()))
  6609. if (target.mixer[t].effects[s].plugin.playedBy == 0)
  6610. if (auto state = capture (p))
  6611. target.mixer[t].effects[s].plugin.state = std::move (*state);
  6612. // the plugins inside Patchers (REA_rodada141), nested ones too
  6613. std::function<void (PatcherDoc&, patcher::Graph*)> captureGraph = [&] (PatcherDoc& doc, patcher::Graph* graph) {
  6614. if (graph == nullptr)
  6615. return;
  6616. for (int n = 0; n < (int) doc.nodes.size() && n < graph->nodeCount(); ++n)
  6617. {
  6618. auto& node = doc.nodes[(std::size_t) n];
  6619. if (node.generator)
  6620. {
  6621. auto instrument = graph->instrumentAt (n);
  6622. if (auto* p = dynamic_cast<PluginInstrument*> (instrument.get()))
  6623. if (auto state = capture (p))
  6624. node.channel.plugin.state = std::move (*state);
  6625. if (node.channel.instrument == InstrumentKind::patcher)
  6626. captureGraph (node.channel.patcher, patcher::graphOf (instrument.get()));
  6627. }
  6628. else
  6629. {
  6630. auto effect = graph->effectAt (n);
  6631. if (auto* p = dynamic_cast<PluginEffect*> (effect.get()))
  6632. if (auto state = capture (p))
  6633. node.effect.plugin.state = std::move (*state);
  6634. if (node.effect.kind == EffectKind::patcher)
  6635. captureGraph (node.effect.patcher, patcher::graphOf (effect.get()));
  6636. }
  6637. }
  6638. };
  6639. for (std::size_t i = 0; i < target.channels.size(); ++i)
  6640. if (target.channels[i].instrument == InstrumentKind::patcher)
  6641. captureGraph (target.channels[i].patcher, patcher::graphOf (getChannelInstrument ((int) i).get()));
  6642. for (std::size_t t = 0; t < target.mixer.size(); ++t)
  6643. for (std::size_t s = 0; s < target.mixer[t].effects.size(); ++s)
  6644. if (target.mixer[t].effects[s].kind == EffectKind::patcher)
  6645. captureGraph (target.mixer[t].effects[s].patcher, patcher::graphOf (getEffect ((int) t, (int) s).get()));
  6646. }
  6647. void AudioEngine::capturePluginStates()
  6648. {
  6649. stampWorkTime();
  6650. flushEdisonAudio(); // (round 190cd: an Edison slot's audio is a file of the project)
  6651. capturePluginStatesInto (song, false);
  6652. lastPublishedShape.song.channels = song.channels;
  6653. lastPublishedShape.song.mixer = song.mixer;
  6654. }
  6655. Song AudioEngine::snapshotForRemoteControl()
  6656. {
  6657. if (getTransport().playing.load() || isRecording())
  6658. throw RemoteError ("busy", "Stop playback and recording before capturing opaque device state");
  6659. // The model belongs to the message thread. Live state capture runs beside processing (no lock, as on JUCE's own
  6660. // hosts); only a restore holds a hosted plugin's callback lock. Do not stop the audio callback while copying.
  6661. auto snapshot = song;
  6662. capturePluginStatesInto (snapshot, false);
  6663. return snapshot;
  6664. }
  6665. juce::String AudioEngine::remoteDeviceStateHash()
  6666. {
  6667. return remoteDeviceStateHashOf (snapshotForRemoteControl());
  6668. }
  6669. juce::String AudioEngine::remoteDeviceStateHashOf (const Song& snapshot)
  6670. {
  6671. Song devices;
  6672. devices.channels = snapshot.channels;
  6673. devices.mixer = snapshot.mixer;
  6674. const auto json = ProjectFile::toJsonExact (devices).toStdString();
  6675. return juce::String (sha256Hex (reinterpret_cast<const std::uint8_t*> (json.data()), json.size()));
  6676. }
  6677. bool AudioEngine::auditionPreset (const juce::AudioPluginInstance& plugin)
  6678. {
  6679. auto channel = -1;
  6680. for (std::size_t i = 0; i < song.channels.size() && channel < 0; ++i)
  6681. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()); p != nullptr && &p->getInstance() == &plugin && ! p->hasCrashed())
  6682. channel = (int) i;
  6683. if (! pluginpresets::auditionPlays (true, channel >= 0, transport.playing.load(), transport.recording.load()))
  6684. return false;
  6685. if (auditionChannel >= 0 && auditionSounding) // the last one still sounds: it ends now
  6686. sendLiveNote (auditionChannel, pluginpresets::auditionKey, 0.0f, false);
  6687. auditionChannel = channel;
  6688. auditionSounding = false;
  6689. auditionAtMs = juce::Time::getMillisecondCounterHiRes() + pluginpresets::auditionDelayMs;
  6690. return true;
  6691. }
  6692. bool AudioEngine::auditionChannelSound (int channel)
  6693. {
  6694. if (channel < 0 || channel >= (int) song.channels.size()
  6695. || ! pluginpresets::auditionPlays (true, true, transport.playing.load(), transport.recording.load()))
  6696. return false;
  6697. if (auditionChannel >= 0 && auditionSounding) // the last one still sounds: it ends now
  6698. sendLiveNote (auditionChannel, pluginpresets::auditionKey, 0.0f, false);
  6699. auditionChannel = channel;
  6700. auditionSounding = false;
  6701. auditionAtMs = juce::Time::getMillisecondCounterHiRes() + pluginpresets::auditionDelayMs;
  6702. return true;
  6703. }
  6704. void AudioEngine::updateAudition()
  6705. {
  6706. if (auditionChannel < 0 || juce::Time::getMillisecondCounterHiRes() < auditionAtMs)
  6707. return;
  6708. if (auditionSounding)
  6709. {
  6710. sendLiveNote (auditionChannel, pluginpresets::auditionKey, 0.0f, false);
  6711. auditionChannel = -1;
  6712. auditionSounding = false;
  6713. return;
  6714. }
  6715. // (the song started in between, or the channel went: nothing plays)
  6716. if (transport.playing.load() || auditionChannel >= (int) song.channels.size())
  6717. {
  6718. auditionChannel = -1;
  6719. return;
  6720. }
  6721. sendLiveNote (auditionChannel, pluginpresets::auditionKey, pluginpresets::auditionVelocity, true);
  6722. auditionSounding = true;
  6723. auditionAtMs = juce::Time::getMillisecondCounterHiRes() + pluginpresets::auditionLengthMs;
  6724. }
  6725. namespace
  6726. {
  6727. void preserveRemoteTags (const Song& before, Song& after)
  6728. {
  6729. std::function<void (const PatcherDoc&, PatcherDoc&)> graph;
  6730. graph = [&] (const PatcherDoc& old, PatcherDoc& next) {
  6731. for (std::size_t i = 0; i < std::min (old.nodes.size(), next.nodes.size()); ++i)
  6732. {
  6733. const auto& prior = old.nodes[i];
  6734. auto& node = next.nodes[i];
  6735. if (node.generator != prior.generator) continue;
  6736. if (node.generator)
  6737. {
  6738. node.channel.instance = prior.channel.instance;
  6739. graph (prior.channel.patcher, node.channel.patcher);
  6740. }
  6741. else
  6742. {
  6743. node.effect.instance = prior.effect.instance;
  6744. graph (prior.effect.patcher, node.effect.patcher);
  6745. }
  6746. }
  6747. };
  6748. for (auto& channel : after.channels)
  6749. if (channel.uid != 0)
  6750. for (const auto& prior : before.channels)
  6751. if (channel.uid == prior.uid && channel.instrument == prior.instrument && channel.plugin.id == prior.plugin.id
  6752. && ! (channel.plugin.state.empty() && ! prior.plugin.state.empty()))
  6753. {
  6754. channel.instance = prior.instance;
  6755. graph (prior.patcher, channel.patcher);
  6756. break;
  6757. }
  6758. for (std::size_t t = 0; t < std::min (before.mixer.size(), after.mixer.size()); ++t)
  6759. {
  6760. const auto& old = before.mixer[t].effects;
  6761. auto& next = after.mixer[t].effects;
  6762. std::vector<bool> used (old.size(), false);
  6763. std::vector<int> match (next.size(), -1);
  6764. // Keep tags already carried through an edit; parsed project documents need value matching.
  6765. for (std::size_t i = 0; i < next.size(); ++i)
  6766. for (std::size_t j = 0; j < old.size(); ++j)
  6767. if (! used[j] && next[i].instance.id == old[j].instance.id)
  6768. { match[i] = (int) j; used[j] = true; break; }
  6769. for (std::size_t i = 0; i < next.size(); ++i)
  6770. if (match[i] < 0)
  6771. for (std::size_t j = 0; j < old.size(); ++j)
  6772. if (! used[j] && next[i] == old[j])
  6773. { match[i] = (int) j; used[j] = true; break; }
  6774. for (std::size_t i = 0; i < next.size(); ++i)
  6775. if (match[i] < 0 && i < old.size() && ! used[i] && next[i].kind == old[i].kind && next[i].plugin.id == old[i].plugin.id
  6776. && ! (next[i].plugin.state.empty() && ! old[i].plugin.state.empty()))
  6777. { match[i] = (int) i; used[i] = true; }
  6778. for (std::size_t i = 0; i < next.size(); ++i)
  6779. if (match[i] >= 0)
  6780. {
  6781. const auto& prior = old[(std::size_t) match[i]];
  6782. next[i].instance = prior.instance;
  6783. graph (prior.patcher, next[i].patcher);
  6784. }
  6785. }
  6786. }
  6787. void validateRemoteStates (const Song& song)
  6788. {
  6789. const auto check = [] (const PluginRef& ref) {
  6790. if (ref.state.empty()) return;
  6791. juce::MemoryBlock bytes;
  6792. if (! bytes.fromBase64Encoding (juce::String::fromUTF8 (ref.state.c_str())))
  6793. throw RemoteError ("invalid", "Hosted device state must use the native base64 encoding");
  6794. };
  6795. std::function<void (const PatcherDoc&)> graph;
  6796. graph = [&] (const PatcherDoc& doc) {
  6797. for (const auto& node : doc.nodes)
  6798. if (node.generator)
  6799. {
  6800. if (node.channel.instrument == InstrumentKind::plugin) check (node.channel.plugin);
  6801. graph (node.channel.patcher);
  6802. }
  6803. else
  6804. {
  6805. if (node.effect.kind == EffectKind::plugin) check (node.effect.plugin);
  6806. graph (node.effect.patcher);
  6807. }
  6808. };
  6809. for (const auto& channel : song.channels)
  6810. {
  6811. if (channel.instrument == InstrumentKind::plugin) check (channel.plugin);
  6812. graph (channel.patcher);
  6813. }
  6814. for (const auto& track : song.mixer)
  6815. for (const auto& effect : track.effects)
  6816. {
  6817. if (effect.kind == EffectKind::plugin) check (effect.plugin);
  6818. graph (effect.patcher);
  6819. }
  6820. }
  6821. }
  6822. void AudioEngine::syncRemotePluginStates (const Song& before)
  6823. {
  6824. std::map<std::uint64_t, std::string> previous;
  6825. std::function<void (const PatcherDoc&)> collectGraph;
  6826. collectGraph = [&] (const PatcherDoc& doc) {
  6827. for (const auto& node : doc.nodes)
  6828. if (node.generator)
  6829. {
  6830. previous[node.channel.instance.id] = node.channel.plugin.state;
  6831. collectGraph (node.channel.patcher);
  6832. }
  6833. else
  6834. {
  6835. previous[node.effect.instance.id] = node.effect.plugin.state;
  6836. collectGraph (node.effect.patcher);
  6837. }
  6838. };
  6839. for (const auto& channel : before.channels)
  6840. {
  6841. previous[channel.instance.id] = channel.plugin.state;
  6842. collectGraph (channel.patcher);
  6843. }
  6844. for (const auto& track : before.mixer)
  6845. for (const auto& effect : track.effects)
  6846. {
  6847. previous[effect.instance.id] = effect.plugin.state;
  6848. collectGraph (effect.patcher);
  6849. }
  6850. const auto apply = [&] (auto* plugin, std::uint64_t identity, const std::string& desired) {
  6851. const auto old = previous.find (identity);
  6852. // A new instance was loaded with its target state by the normal factory. An unchanged
  6853. // instance needs no state call: saving bytes must never reset unrelated GUI state.
  6854. if (old == previous.end() || old->second == desired) return;
  6855. const auto current = plugin->captureState();
  6856. if (! current || (*current != desired && ! plugin->restoreState (desired)))
  6857. throw RemoteError ("uncertain", "The project changed but a running device could not restore its state; inspect it before further history actions", true);
  6858. };
  6859. std::function<void (const PatcherDoc&, patcher::Graph*)> graph;
  6860. graph = [&] (const PatcherDoc& doc, patcher::Graph* live) {
  6861. if (live == nullptr) return;
  6862. for (int i = 0; i < (int) doc.nodes.size() && i < live->nodeCount(); ++i)
  6863. {
  6864. const auto& node = doc.nodes[(std::size_t) i];
  6865. if (node.generator)
  6866. {
  6867. auto instance = live->instrumentAt (i);
  6868. if (auto* p = dynamic_cast<PluginInstrument*> (instance.get())) apply (p, node.channel.instance.id, node.channel.plugin.state);
  6869. if (node.channel.instrument == InstrumentKind::patcher) graph (node.channel.patcher, patcher::graphOf (instance.get()));
  6870. }
  6871. else
  6872. {
  6873. auto instance = live->effectAt (i);
  6874. if (auto* p = dynamic_cast<PluginEffect*> (instance.get())) apply (p, node.effect.instance.id, node.effect.plugin.state);
  6875. if (node.effect.kind == EffectKind::patcher) graph (node.effect.patcher, patcher::graphOf (instance.get()));
  6876. }
  6877. }
  6878. };
  6879. for (std::size_t i = 0; i < song.channels.size(); ++i)
  6880. {
  6881. auto instance = getChannelInstrument ((int) i);
  6882. if (auto* p = dynamic_cast<PluginInstrument*> (instance.get())) apply (p, song.channels[i].instance.id, song.channels[i].plugin.state);
  6883. if (song.channels[i].instrument == InstrumentKind::patcher) graph (song.channels[i].patcher, patcher::graphOf (instance.get()));
  6884. }
  6885. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  6886. for (std::size_t i = 0; i < song.mixer[t].effects.size(); ++i)
  6887. {
  6888. auto instance = getEffect ((int) t, (int) i);
  6889. if (auto* p = dynamic_cast<PluginEffect*> (instance.get())) apply (p, song.mixer[t].effects[i].instance.id, song.mixer[t].effects[i].plugin.state);
  6890. if (song.mixer[t].effects[i].kind == EffectKind::patcher) graph (song.mixer[t].effects[i].patcher, patcher::graphOf (instance.get()));
  6891. }
  6892. }
  6893. void AudioEngine::failRemoteHistory (bool uncertain)
  6894. {
  6895. remoteHistoryFailed = true;
  6896. remoteHistoryUncertain = uncertain;
  6897. remoteHistoryCode = uncertain ? "uncertain" : "failed";
  6898. remoteHistoryError = uncertain
  6899. ? tr ("The history operation did not finish; the project or its history may have changed. Inspect before further undo/redo.")
  6900. : tr ("The history operation could not be prepared. No history step was moved; inspect the device before retrying.");
  6901. try { juce::Logger::writeToLog (remoteHistoryError); } catch (...) {}
  6902. }
  6903. bool AudioEngine::checkRemoteHistory (const juce::String& expected, const Song& current)
  6904. {
  6905. if (expected.isNotEmpty() && expected == remoteDeviceStateHashOf (current)) return true;
  6906. remoteHistoryFailed = true;
  6907. remoteHistoryUncertain = false;
  6908. remoteHistoryCode = "changed";
  6909. remoteHistoryError = tr ("A device changed after this remote edit. Undo/redo was refused to preserve those changes.");
  6910. juce::Logger::writeToLog (remoteHistoryError);
  6911. return false;
  6912. }
  6913. juce::String AudioEngine::finishRemoteHistory (const std::optional<Song>& before)
  6914. {
  6915. if (! before) return {};
  6916. try
  6917. {
  6918. syncRemotePluginStates (*before);
  6919. auto current = song;
  6920. capturePluginStatesInto (current, false);
  6921. const auto fence = remoteDeviceStateHashOf (current);
  6922. adoptCapturedRemoteDevices (song, lastPublishedShape, std::move (current));
  6923. return fence;
  6924. }
  6925. catch (...)
  6926. {
  6927. failRemoteHistory (true);
  6928. return {};
  6929. }
  6930. }
  6931. bool AudioEngine::editSongRemoteTransaction (const std::function<void (Song&)>& stage, const std::function<bool()>& cancelled, bool preserveRuntimeIdentity)
  6932. {
  6933. if (getTransport().playing.load() || isRecording() || juce::ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  6934. throw RemoteError ("busy", "Stop playback/recording and finish the current gesture before remote edits");
  6935. // Staging, serialization and publication stay off the audio-device lock. A hosted state restore holds only that
  6936. // plugin's callback lock (the audio side skips the block meanwhile); capture takes no lock.
  6937. auto before = snapshotForRemoteControl();
  6938. auto next = before;
  6939. if (cancelled && cancelled()) throw RemoteError ("failed", "Remote operation cancelled before committing changes");
  6940. stage (next); // all parsing, validation and allocations happen before history is changed
  6941. if (cancelled && cancelled()) throw RemoteError ("failed", "Remote operation cancelled before committing changes");
  6942. if (ProjectFile::toJsonExact (before) == ProjectFile::toJsonExact (next)) return false;
  6943. validateRemoteStates (next);
  6944. if (preserveRuntimeIdentity) preserveRemoteTags (before, next);
  6945. const auto capturedBefore = before;
  6946. const auto fresh = remoteFreshTargets (capturedBefore, next);
  6947. try
  6948. {
  6949. song = std::move (before); // capture live state in the owned undo step, without adding a separate step
  6950. remote_history::mirrorCapturedHostedStates (song, lastPublishedShape.song);
  6951. lastUndoPress = {};
  6952. gestureSaved = false;
  6953. levelsPending = false;
  6954. const juce::ScopedValueSetter<bool> remoteStep (nextRemoteHistoryStep, true);
  6955. const juce::ScopedValueSetter<std::unordered_set<std::uint64_t>> freshPolicy (remoteFreshInstances, fresh);
  6956. editSong ([&] (Song& current) { current = std::move (next); });
  6957. syncRemotePluginStates (capturedBefore);
  6958. auto committed = song;
  6959. capturePluginStatesInto (committed, false);
  6960. const auto fence = remoteDeviceStateHashOf (committed);
  6961. adoptCapturedRemoteDevices (song, lastPublishedShape, std::move (committed));
  6962. if (! undoStack.empty()) undoStack.back().deviceHash = fence;
  6963. if (sessionHistory && ! sessionUndo.empty()) sessionUndo.back().deviceHash = fence;
  6964. remoteHistoryError.clear();
  6965. }
  6966. catch (...)
  6967. {
  6968. throw RemoteError ("uncertain", "The project edit ran but its device state could not be verified; inspect before retrying", true);
  6969. }
  6970. return true;
  6971. }
  6972. void AudioEngine::undoRemoteControl (const std::function<bool()>& cancelled)
  6973. {
  6974. if (getTransport().playing.load() || isRecording() || juce::ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  6975. throw RemoteError ("busy", "Stop playback/recording and finish the current gesture before remote undo");
  6976. if (cancelled && cancelled()) throw RemoteError ("failed", "Remote undo cancelled before changing history");
  6977. const juce::ScopedValueSetter<bool> apiStep (remoteHistoryApiStep, true);
  6978. const juce::ScopedValueSetter<std::function<bool()>> cancellation (remoteHistoryCancelled, cancelled);
  6979. try { undo(); }
  6980. catch (...) { throw RemoteError ("uncertain", "Native undo did not finish; its history or project may have changed. Inspect before retrying", true); }
  6981. if (remoteHistoryFailed) throw RemoteError (remoteHistoryCode, remoteHistoryError.toStdString(), remoteHistoryUncertain);
  6982. }
  6983. void AudioEngine::redoRemoteControl (const std::function<bool()>& cancelled)
  6984. {
  6985. if (getTransport().playing.load() || isRecording() || juce::ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  6986. throw RemoteError ("busy", "Stop playback/recording and finish the current gesture before remote redo");
  6987. if (cancelled && cancelled()) throw RemoteError ("failed", "Remote redo cancelled before changing history");
  6988. const juce::ScopedValueSetter<bool> apiStep (remoteHistoryApiStep, true);
  6989. const juce::ScopedValueSetter<std::function<bool()>> cancellation (remoteHistoryCancelled, cancelled);
  6990. try { redo(); }
  6991. catch (...) { throw RemoteError ("uncertain", "Native redo did not finish; its history or project may have changed. Inspect before retrying", true); }
  6992. if (remoteHistoryFailed) throw RemoteError (remoteHistoryCode, remoteHistoryError.toStdString(), remoteHistoryUncertain);
  6993. }
  6994. namespace
  6995. {
  6996. bool pluginIsDown (Instrument* instrument)
  6997. {
  6998. auto* p = dynamic_cast<PluginInstrument*> (instrument);
  6999. return p != nullptr && (p->hasCrashed() || isSandboxedPluginDead (p->getInstance()));
  7000. }
  7001. bool pluginIsDown (Effect* effect)
  7002. {
  7003. auto* p = dynamic_cast<PluginEffect*> (effect);
  7004. return p != nullptr && (p->hasCrashed() || isSandboxedPluginDead (p->getInstance()));
  7005. }
  7006. } // namespace
  7007. bool AudioEngine::hostedPluginDown (HostedSlot where) const
  7008. {
  7009. return where.track < 0 ? pluginIsDown (getChannelInstrument (where.channel).get()) : pluginIsDown (getEffect (where.track, where.slot).get());
  7010. }
  7011. std::vector<AudioEngine::HostedSlot> AudioEngine::downHostedPlugins (const std::string& named) const
  7012. {
  7013. std::vector<HostedSlot> out;
  7014. for (std::size_t i = 0; i < song.channels.size(); ++i)
  7015. if (song.channels[i].instrument == InstrumentKind::plugin && (named.empty() || song.channels[i].plugin.name == named)
  7016. && hostedPluginDown ({ (int) i, -1, -1 }))
  7017. out.push_back ({ (int) i, -1, -1 });
  7018. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  7019. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  7020. if (const auto& fx = song.mixer[t].effects[s];
  7021. fx.kind == EffectKind::plugin && (named.empty() || fx.plugin.name == named) && hostedPluginDown ({ -1, (int) t, (int) s }))
  7022. out.push_back ({ -1, (int) t, (int) s });
  7023. return out;
  7024. }
  7025. int AudioEngine::reloadHostedPlugins (const std::vector<HostedSlot>& which)
  7026. {
  7027. // the running plugins' current settings (a reloaded one that still runs starts from them); this also brings the
  7028. // last published shape in line with the song
  7029. capturePluginStates();
  7030. std::vector<HostedSlot> asked;
  7031. for (const auto& w : which)
  7032. if (w.track < 0 ? forgetHostedPlugin (lastPublishedShape, w.channel) : forgetHostedPlugin (lastPublishedShape, w.track, w.slot))
  7033. asked.push_back (w);
  7034. if (asked.empty())
  7035. return 0;
  7036. publishSong();
  7037. auto running = 0;
  7038. for (const auto& w : asked)
  7039. {
  7040. const auto loaded = w.track < 0 ? dynamic_cast<PluginInstrument*> (getChannelInstrument (w.channel).get()) != nullptr
  7041. : dynamic_cast<PluginEffect*> (getEffect (w.track, w.slot).get()) != nullptr;
  7042. running += loaded && ! hostedPluginDown (w) ? 1 : 0;
  7043. }
  7044. return running;
  7045. }
  7046. void AudioEngine::audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
  7047. int numInputChannels,
  7048. float* const* outputChannelData,
  7049. int numOutputChannels,
  7050. int numSamples,
  7051. const juce::AudioIODeviceCallbackContext& context)
  7052. {
  7053. // FTZ/DAZ for the whole callback (round 160): the rack had it, but the metronome, the preview player and the
  7054. // hosted plugins' graph nodes around it ran without
  7055. const ScopedFlushDenormals noDenormals;
  7056. rt::noteAudioThread(); // Linux: the message thread asks for real-time priority for this thread once
  7057. #if JUCE_WINDOWS
  7058. // round 174e: a new device thread (first callback, a device restart) gets the workers' real-time class unless the
  7059. // driver already runs it time-critical: the callback waits on the workers, and a normal-priority callback thread
  7060. // lost the CPU to the UI's frames (more late calls while the screen was busy)
  7061. if (const auto id = (unsigned long) GetCurrentThreadId(); id != deviceThreadId.load (std::memory_order_relaxed))
  7062. {
  7063. deviceThreadId.store (id, std::memory_order_relaxed);
  7064. WorkerPool::nameCurrentThread ("LYNX audio device"); // (round 190kb: per-thread CPU lists)
  7065. const auto before = GetThreadPriority (GetCurrentThread());
  7066. deviceThreadPriorityBefore.store (before, std::memory_order_relaxed);
  7067. if (boostDeviceThread && before < THREAD_PRIORITY_TIME_CRITICAL)
  7068. raiseAudioThreadPriority();
  7069. else
  7070. power::optOutOfPowerThrottling(); // (a driver's own time-critical thread too: no EcoQoS, round toolchain190gt)
  7071. deviceThreadPriorityAfter.store (GetThreadPriority (GetCurrentThread()), std::memory_order_relaxed);
  7072. }
  7073. #endif
  7074. // real-time health: how long this callback took against its deadline (the buffer's duration)
  7075. const auto callbackStart = juce::Time::getMillisecondCounterHiRes();
  7076. struct Measure
  7077. {
  7078. ~Measure()
  7079. {
  7080. const auto rate = engine.transport.sampleRate.load (std::memory_order_relaxed);
  7081. // round 190gg: with the block's slowest channel / effect call (named if the block missed its deadline)
  7082. const auto slowest = engine.rackProcessor != nullptr ? engine.rackProcessor->getRenderer().takeBlockSlowest() : 0;
  7083. if (rate > 0.0)
  7084. engine.rtStats.record (start, juce::Time::getMillisecondCounterHiRes() - start, 1000.0 * samples / rate, slowest);
  7085. }
  7086. AudioEngine& engine;
  7087. double start;
  7088. int samples;
  7089. } measure { *this, callbackStart, numSamples };
  7090. // round 190jb: an export may hold this engine (holdForExport: it renders with these plugins). The flag below says the
  7091. // callback is inside its block; the hold is read after it is set (both sequentially consistent), so holdForExport,
  7092. // which sets the hold and then waits for the flag to drop, knows no block of this engine runs the rack any more.
  7093. callbackBusy.store (true, std::memory_order_seq_cst);
  7094. struct LeaveBlock
  7095. {
  7096. std::atomic<bool>& busy;
  7097. ~LeaveBlock() { busy.store (false, std::memory_order_seq_cst); }
  7098. } leaveBlock { callbackBusy };
  7099. // an export renders (round 168s): playback stops and nothing is processed until it ends (not while recording; with
  7100. // the export hold of round 190jb, whatever happens)
  7101. if (exportHold.load (std::memory_order_seq_cst)
  7102. || (offlineRendersRunning().load (std::memory_order_acquire) > 0 && ! transport.recording.load (std::memory_order_relaxed)))
  7103. {
  7104. if (transport.playing.load (std::memory_order_relaxed))
  7105. stop();
  7106. for (int ch = 0; ch < numOutputChannels; ++ch)
  7107. if (outputChannelData[ch] != nullptr)
  7108. juce::FloatVectorOperations::clear (outputChannelData[ch], numSamples);
  7109. return;
  7110. }
  7111. // the position the UI asked for (Rewind, a seek). Round 190hn: `playing` is read BEFORE the requests are taken. A
  7112. // start from the UI stores its position request first and `playing` after it (seek, then play(); the real-time
  7113. // export's startRealtimeBounce). When the start landed between this check and the loop's `playing` check below, the
  7114. // first block played from the old position and the request was taken one block later, as a jump back to the start:
  7115. // a real-time export one block late (the first block twice; the 0.1.29 macOS release self-test), a stutter at the
  7116. // start of playback. If `playing` turns on after this check, the requests are taken again before the first block
  7117. // that plays (the loop below).
  7118. auto requestsTakenWhilePlaying = transport.playing.load (std::memory_order_acquire);
  7119. auto takePositionRequests = [this] {
  7120. if (transport.rewindRequested.exchange (false))
  7121. {
  7122. transport.positionTicks.store (0.0);
  7123. transport.userJumps.fetch_add (1, std::memory_order_relaxed);
  7124. if (transport.resetPluginsOnTransport.load (std::memory_order_relaxed))
  7125. midiSync.requestTransportNotesOff(); // FL: CC 123 to the "Send all notes off" outputs (REA 167l §6)
  7126. }
  7127. if (const auto target = transport.seekRequest.exchange (-1.0); target >= 0.0)
  7128. {
  7129. transport.positionTicks.store (target);
  7130. transport.userJumps.fetch_add (1, std::memory_order_relaxed);
  7131. if (transport.resetPluginsOnTransport.load (std::memory_order_relaxed))
  7132. midiSync.requestTransportNotesOff();
  7133. }
  7134. };
  7135. takePositionRequests();
  7136. // (round 190hn, the export parity self-test only: the UI's start lands here, after the requests were taken)
  7137. if (auto* hook = afterPositionRequests.load (std::memory_order_acquire); hook != nullptr)
  7138. hook (afterPositionRequestsContext);
  7139. transport.readMarkers (rtMarkers, rtMarkerVersion); // FL's marker actions (a new table when the song changed)
  7140. // an external MIDI clock moves the transport (round 165f)
  7141. midiSync.setRackLatencyMs (heardLatencyMs() - outputCompensationMs.load (std::memory_order_relaxed)); // (round 190hq)
  7142. midiSync.beginBlock (transport, callbackStart, numSamples);
  7143. // Ableton Link (round 190gl): the session's tempo and phase move the transport; a Play waiting for the session's
  7144. // phase starts at `linkStart` (a sample of this block; -1 = none), to the sample like the count-in's end
  7145. const auto linkStart = abletonLink.beginBlock (transport, numSamples, heardLatencyMs()); // (round 190hq: + the Master's PDC)
  7146. // With the loop region on, the block is split at the loop end and the position jumps back to
  7147. // its start (the nodes see a jump and release their notes, as in FL).
  7148. // the audio editor's input recording (nothing happens unless it chose the input)
  7149. meters.capture.push (AudioCapture::input, numInputChannels > 0 ? inputChannelData[0] : nullptr, numInputChannels > 1 ? inputChannelData[1] : nullptr,
  7150. numSamples);
  7151. std::array<const float*, 64> inputs {};
  7152. std::array<float*, 64> outputs {};
  7153. numInputChannels = juce::jmin (numInputChannels, (int) inputs.size());
  7154. numOutputChannels = juce::jmin (numOutputChannels, (int) outputs.size());
  7155. // count-in: the metronome counts the pre-roll down, then playback starts — to the sample (round 170d: the song
  7156. // started at the next block boundary and the count-in's clicks ran a block early, so the downbeat flammed ~5 ms
  7157. // after the last count-in click and the take's notes were late against it): the block is split where the count-in
  7158. // ends, the part before it counts in (the metronome's clock = the start minus what is left at that sample)
  7159. const auto countInAtStart = transport.countIn.load (std::memory_order_relaxed);
  7160. const auto countingIn = countInAtStart > 0.0 && ! transport.playing.load (std::memory_order_relaxed);
  7161. const auto countInSamples = ! countingIn ? 0
  7162. : (int) juce::jmin ((double) numSamples, std::ceil (countInAtStart / juce::jmax (1.0e-9, transport.ticksPerSample()) - 1.0e-6));
  7163. auto countInNow = countInAtStart;
  7164. for (int done = 0; done < numSamples;)
  7165. {
  7166. auto n = numSamples - done;
  7167. if (countInSamples > done)
  7168. n = juce::jmin (n, countInSamples - done);
  7169. if (linkStart > done) // (the part before the Link start plays stopped)
  7170. n = juce::jmin (n, linkStart - done);
  7171. else if (linkStart >= 0 && done == linkStart)
  7172. transport.playing.store (true, std::memory_order_relaxed);
  7173. const auto playing = transport.playing.load (std::memory_order_acquire);
  7174. // (round 190hn) playback started after the requests were taken: the start's position request (stored before
  7175. // `playing`, so it is visible now) applies before this part plays, not one block late
  7176. if (playing && ! std::exchange (requestsTakenWhilePlaying, true))
  7177. takePositionRequests();
  7178. const auto tps = transport.ticksPerSample();
  7179. // Song mode: the loop region, or else the whole song (back to the start at its end, like FL)
  7180. // (while audio takes record in Song mode without a loop region, the song plays on past its end instead of
  7181. // starting over: the take stays one piece, as in Pro Tools / Nuendo; round 163)
  7182. // (punching on the loop region: the region is not looped either, playback runs on into the post-roll)
  7183. const auto linear = liveInput.linearSong.load (std::memory_order_relaxed);
  7184. const auto throughRegion = liveInput.noLoopRegion.load (std::memory_order_relaxed);
  7185. const auto loop = playbackLoop (transport.songMode.load (std::memory_order_relaxed),
  7186. throughRegion ? 0.0 : transport.loopStart.load (std::memory_order_relaxed),
  7187. throughRegion ? 0.0 : transport.loopEnd.load (std::memory_order_relaxed),
  7188. linear ? 0.0 : transport.songEnd.load (std::memory_order_relaxed),
  7189. transport.songStart.load (std::memory_order_relaxed));
  7190. const auto loopStart = loop.start, loopEnd = loop.end;
  7191. const auto looping = playing && loop.active() && tps > 0.0;
  7192. // without the loop region, the song's end goes back to FL's "Loop" marker (else the start)
  7193. const auto regionOn = ! throughRegion && transport.loopEnd.load (std::memory_order_relaxed) > transport.loopStart.load (std::memory_order_relaxed);
  7194. const auto songWrap = regionOn ? loopStart : juce::jlimit (loopStart, juce::jmax (loopStart, loopEnd - 1.0), (double) rtMarkers.wrapTo);
  7195. if (looping)
  7196. {
  7197. // before the loop, play normally until reaching it; past the end, jump back to the start
  7198. auto position = transport.positionTicks.load (std::memory_order_relaxed);
  7199. if (transportReached (position, loopEnd))
  7200. {
  7201. position = songWrap;
  7202. transport.positionTicks.store (position, std::memory_order_relaxed);
  7203. }
  7204. n = transportSamplesUntil (position, loopEnd, tps, n);
  7205. }
  7206. // FL's marker actions (Song mode): the block ends where the position reaches a marker jump / pause, or a
  7207. // quantized jump the user asked for; it is made after the block (below), like the loop's wrap
  7208. const MarkerJump* markerJump = nullptr;
  7209. const auto pendingAt = transport.pendingJumpAt.load (std::memory_order_relaxed);
  7210. auto pendingDue = false;
  7211. if (playing && tps > 0.0 && transport.songMode.load (std::memory_order_relaxed))
  7212. {
  7213. const auto step = markerStep (rtMarkers, transport.positionTicks.load (std::memory_order_relaxed), n, tps, pendingAt);
  7214. n = step.samples;
  7215. markerJump = step.jump;
  7216. pendingDue = step.userJump;
  7217. }
  7218. for (int ch = 0; ch < numInputChannels; ++ch)
  7219. inputs[(std::size_t) ch] = inputChannelData[ch] != nullptr ? inputChannelData[ch] + done : nullptr;
  7220. // the block's input by device channel, for the inserts (monitoring, meters) and the takes
  7221. liveInput.numChannels = 0;
  7222. for (int c = 0; c < LiveInput::maxChannels; ++c)
  7223. {
  7224. const auto slot = inputSlot[(std::size_t) c];
  7225. liveInput.channels[(std::size_t) c] = slot >= 0 && slot < numInputChannels ? inputs[(std::size_t) slot] : nullptr;
  7226. if (liveInput.channels[(std::size_t) c] != nullptr)
  7227. liveInput.numChannels = c + 1;
  7228. }
  7229. // round 190ke: the Simple tuner's input (only while the tuner shows: one relaxed load otherwise)
  7230. if (const auto tf = tunerFirst.load (std::memory_order_acquire); tf >= 0 && tf < LiveInput::maxChannels && n > 0)
  7231. {
  7232. const auto* a = liveInput.channels[(std::size_t) tf];
  7233. const auto* b = tunerCount.load (std::memory_order_relaxed) > 1 && tf + 1 < LiveInput::maxChannels ? liveInput.channels[(std::size_t) tf + 1] : nullptr;
  7234. if (a != nullptr)
  7235. {
  7236. tunerTapData->sampleRate.store (transport.sampleRate.load (std::memory_order_relaxed), std::memory_order_relaxed);
  7237. std::array<float, 256> mono;
  7238. for (int at = 0; at < n; at += (int) mono.size())
  7239. {
  7240. const auto count = juce::jmin ((int) mono.size(), n - at);
  7241. for (int i = 0; i < count; ++i)
  7242. mono[(std::size_t) i] = b != nullptr ? 0.5f * (a[at + i] + b[at + i]) : a[at + i];
  7243. tunerTapData->write (mono.data(), mono.data(), count);
  7244. }
  7245. }
  7246. }
  7247. // audio recording: this block's input goes to the takes' streams (without waiting on a lock). Every take gets
  7248. // every block (silence for an input channel missing now), so all of them keep the same timeline (round 163).
  7249. // The lock is held through the render when takes are tapped inside their inserts (round 168x): their part of
  7250. // this block is pushed after the render, and every take must get every block.
  7251. auto takesLocked = false;
  7252. auto tappedTakes = false;
  7253. if (playing && (transport.recording.load (std::memory_order_relaxed) || slotAudioCapture.load (std::memory_order_relaxed)))
  7254. {
  7255. takesLocked = takeLock.tryEnter();
  7256. if (takesLocked && takeCount > 0)
  7257. {
  7258. for (int k = 0; k < takeCount; ++k)
  7259. {
  7260. auto* take = takes[(std::size_t) k];
  7261. if (take->tap >= 0) // filled by the renderer: silence until it writes the tap
  7262. {
  7263. tappedTakes = true;
  7264. if (n <= LiveInput::tapCapacity)
  7265. for (auto& d : liveInput.taps[(std::size_t) take->tap].data)
  7266. std::fill (d.begin(), d.begin() + n, 0.0f);
  7267. continue;
  7268. }
  7269. const std::array<const float*, 2> data { liveInput.channel (take->first, 0), liveInput.channel (take->first + take->channels - 1, 0) };
  7270. if (data[0] == nullptr || data[1] == nullptr)
  7271. take->stream->pushSilence (n);
  7272. else
  7273. take->stream->push (data.data(), n);
  7274. }
  7275. if (takeStartTick.load (std::memory_order_relaxed) < 0.0)
  7276. {
  7277. takeStartTick.store (transport.positionTicks.load (std::memory_order_relaxed));
  7278. // (round 190bv) the clip grid's clock at this sample: its own while it runs, else it starts at the song position
  7279. takeStartClock.store (clipLauncher != nullptr && clipLauncher->running.load (std::memory_order_relaxed)
  7280. ? clipLauncher->clock
  7281. : transport.positionTicks.load (std::memory_order_relaxed),
  7282. std::memory_order_relaxed);
  7283. }
  7284. takeFrames.fetch_add (n, std::memory_order_relaxed);
  7285. takeTicks.store (takeTicks.load (std::memory_order_relaxed) + n * tps, std::memory_order_relaxed);
  7286. }
  7287. if (takesLocked && ! tappedTakes)
  7288. {
  7289. takeLock.exit();
  7290. takesLocked = false;
  7291. }
  7292. }
  7293. for (int ch = 0; ch < numOutputChannels; ++ch)
  7294. outputs[(std::size_t) ch] = outputChannelData[ch] != nullptr ? outputChannelData[ch] + done : nullptr;
  7295. // master sync out (round 165f): this part's clock / MTC messages, time-stamped for the sender thread
  7296. midiSync.subBlock (transport.positionTicks.load (std::memory_order_relaxed), tps, n, done, playing);
  7297. // (round 190gq: render-ahead follows the device callback's blocks while the rack runs inside it)
  7298. transport.callbackSamples.store (numSamples, std::memory_order_relaxed);
  7299. transport.callbackOffset.store (done, std::memory_order_relaxed);
  7300. transport.callbackPlaying.store (playing, std::memory_order_relaxed); // (round 190hn: the rack plays what this part plays)
  7301. transport.inDeviceCallback.store (true, std::memory_order_relaxed);
  7302. player.audioDeviceIOCallbackWithContext (inputs.data(), numInputChannels, outputs.data(), numOutputChannels, n, context);
  7303. transport.inDeviceCallback.store (false, std::memory_order_relaxed);
  7304. routeOutputs (outputs.data(), numOutputChannels, n);
  7305. // round 190jl: what the MIDI Out channels on a hardware output's port played in this part, timed like the clock
  7306. if (rackProcessor != nullptr && midiSync.hasPorts())
  7307. {
  7308. const auto count = rackProcessor->getRenderer().takeHardwareMidi (hardwareMidiTaken.data(), (int) hardwareMidiTaken.size());
  7309. for (int k = 0; k < count; ++k)
  7310. {
  7311. const auto& h = hardwareMidiTaken[(std::size_t) k];
  7312. midiSync.channelMessage (h.port, done + h.sample, h.bytes.data(), h.size, h.source);
  7313. }
  7314. // the transport stopped: every note the port devices still sound ends ("Send all notes off": CC 123 too).
  7315. // Round 190mh: from the state this part was PLAYED with (`playing`, what the rack saw), not a fresh read of
  7316. // the transport: a stop that lands while the rack renders a part used to ask here already, so the notes-off
  7317. // marker went into the queue (next block's beginBlock) BEFORE the rack's own note off of the next, stopped
  7318. // part, and the held note got two note offs (the macOS CI flake "extra notes after the stop")
  7319. if (hardwareMidiWasPlaying && ! playing)
  7320. midiSync.requestPortNotesOff();
  7321. }
  7322. hardwareMidiWasPlaying = playing;
  7323. takePluginNotes (done); // GitHub #198 (round 190ks): what plugin windows played in this part
  7324. if (takesLocked) // the tapped takes' part of this block, now rendered (round 168x)
  7325. {
  7326. for (int k = 0; k < takeCount; ++k)
  7327. if (auto* take = takes[(std::size_t) k]; take->tap >= 0)
  7328. {
  7329. if (n > LiveInput::tapCapacity)
  7330. {
  7331. take->stream->pushSilence (n);
  7332. continue;
  7333. }
  7334. auto& tap = liveInput.taps[(std::size_t) take->tap];
  7335. const auto drop = juce::jmin (n, take->skip - take->skipped); // the effects' latency at the start
  7336. take->skipped += drop;
  7337. if (drop < n)
  7338. {
  7339. const std::array<const float*, 2> data { tap.data[0].data() + drop, tap.data[1].data() + drop };
  7340. take->stream->push (data.data(), n - drop);
  7341. }
  7342. }
  7343. takeLock.exit();
  7344. }
  7345. // round 190ld: the Finish dock's loudness-matched "Hear without" (the device's output only)
  7346. if (const auto want = listenGain.load (std::memory_order_relaxed); want != 1.0f || listenGainNow != 1.0f)
  7347. {
  7348. for (int ch = 0; ch < numOutputChannels; ++ch)
  7349. if (auto* out = outputs[(std::size_t) ch]; out != nullptr)
  7350. {
  7351. if (want == listenGainNow)
  7352. juce::FloatVectorOperations::multiply (out, want, n);
  7353. else
  7354. for (int i = 0; i < n; ++i)
  7355. out[i] *= listenGainNow + (want - listenGainNow) * (float) (i + 1) / (float) n;
  7356. }
  7357. listenGainNow = want;
  7358. }
  7359. // round 190my (DF-17): the tempo tapper's mute (FL's curve, counted in song ticks while playing; stop ends it)
  7360. if (const auto left = muteTicksLeft.load (std::memory_order_relaxed); left > 0.0)
  7361. {
  7362. auto expected = left; // (the UI may have started a new count meanwhile: it wins)
  7363. if (! transport.playing.load (std::memory_order_relaxed))
  7364. muteTicksLeft.compare_exchange_strong (expected, 0.0, std::memory_order_relaxed);
  7365. else
  7366. {
  7367. const auto total = juce::jmax (left, muteTicksTotal.load (std::memory_order_relaxed));
  7368. const auto tpsNow = transport.ticksPerSample();
  7369. // (the gain moves along the curve within the block: from its start to its end, linearly)
  7370. const auto rest = juce::jmax (0.0, left - n * tpsNow);
  7371. const auto g0 = tapperMuteGain (left, total), g1 = tapperMuteGain (rest, total);
  7372. for (int ch = 0; ch < numOutputChannels; ++ch)
  7373. if (auto* out = outputs[(std::size_t) ch]; out != nullptr)
  7374. for (int i = 0; i < n; ++i)
  7375. out[i] *= g0 + (g1 - g0) * (float) i / (float) n;
  7376. muteTicksLeft.compare_exchange_strong (expected, rest, std::memory_order_relaxed);
  7377. }
  7378. }
  7379. for (int ch = 0; ch < numOutputChannels; ++ch)
  7380. if (outputs[(std::size_t) ch] != nullptr)
  7381. clipOvers (outputs[(std::size_t) ch], n);
  7382. // oscilloscope: average of both sides into the ring buffer
  7383. if (numOutputChannels > 0 && outputs[0] != nullptr)
  7384. {
  7385. auto w = scopeWrite.load (std::memory_order_relaxed);
  7386. const auto* right = numOutputChannels > 1 && outputs[1] != nullptr ? outputs[1] : outputs[0];
  7387. float peakL = 0.0f, peakR = 0.0f;
  7388. for (int i = 0; i < n; ++i)
  7389. {
  7390. scope[(std::size_t) w].store (0.5f * (outputs[0][i] + right[i]), std::memory_order_relaxed);
  7391. scopeSide[(std::size_t) w].store (0.5f * (outputs[0][i] - right[i]), std::memory_order_relaxed);
  7392. w = (w + 1) % scopeSize;
  7393. peakL = juce::jmax (peakL, std::abs (outputs[0][i]));
  7394. peakR = juce::jmax (peakR, std::abs (right[i]));
  7395. }
  7396. scopeWrite.store (w, std::memory_order_release);
  7397. // the toolbar's stereo bars (round 190kn): the loudest sample of each side since the UI's last read
  7398. for (int ch = 0; ch < 2; ++ch)
  7399. {
  7400. const auto v = ch == 0 ? peakL : peakR;
  7401. auto& slot = outputPeak[(std::size_t) ch];
  7402. auto current = slot.load (std::memory_order_relaxed);
  7403. while (v > current && ! slot.compare_exchange_weak (current, v, std::memory_order_relaxed))
  7404. {
  7405. }
  7406. }
  7407. }
  7408. if (playing)
  7409. {
  7410. auto position = transport.positionTicks.load (std::memory_order_relaxed) + n * tps;
  7411. if (pendingDue && transportReached (position, pendingAt))
  7412. {
  7413. position = transport.pendingJumpTo.load (std::memory_order_relaxed);
  7414. transport.pendingJumpAt.store (-1.0, std::memory_order_relaxed);
  7415. markerEvents.fetch_add (1, std::memory_order_relaxed);
  7416. transport.userJumps.fetch_add (1, std::memory_order_relaxed);
  7417. }
  7418. else if (markerJump != nullptr && transportReached (position, (double) markerJump->at))
  7419. {
  7420. markerEvents.fetch_add (1, std::memory_order_relaxed);
  7421. if (markerJump->kind == MarkerJump::Kind::pause)
  7422. {
  7423. // FL's "Marker pause": playback stops at the marker; Play goes on from there
  7424. position = (double) markerJump->at;
  7425. transport.positionTicks.store (position, std::memory_order_relaxed);
  7426. transport.playing.store (false, std::memory_order_relaxed); // the rest of the block plays stopped
  7427. }
  7428. position = (double) markerJump->to;
  7429. transport.userJumps.fetch_add (1, std::memory_order_relaxed);
  7430. }
  7431. else if (looping && transportReached (position, loopEnd))
  7432. {
  7433. position = songWrap;
  7434. // loop recording: where this pass ends in the takes (round 163)
  7435. if (const auto frames = takeFrames.load (std::memory_order_relaxed); frames > 0 && takeStartTick.load (std::memory_order_relaxed) >= 0.0)
  7436. if (const auto k = takeWrapCount.load (std::memory_order_relaxed); k < (int) takeWraps.size())
  7437. {
  7438. takeWraps[(std::size_t) k].store (frames, std::memory_order_relaxed);
  7439. takeWrapCount.store (k + 1, std::memory_order_release);
  7440. }
  7441. }
  7442. transport.positionTicks.store (position, std::memory_order_relaxed);
  7443. }
  7444. // the count-in's part of the block is over: what is left of it, or playback from here
  7445. // (a compare-exchange: a Stop pressed meanwhile set it to 0 and must win)
  7446. if (countInSamples > done)
  7447. {
  7448. const auto rawLeft = countInAtStart - (done + n) * transport.ticksPerSample();
  7449. const auto left = juce::jmax (0.0, rawLeft);
  7450. const auto ends = done + n >= countInSamples && rawLeft <= 1.0e-6;
  7451. auto expected = countInNow;
  7452. if (transport.countIn.compare_exchange_strong (expected, ends ? 0.0 : left, std::memory_order_relaxed))
  7453. {
  7454. countInNow = ends ? 0.0 : left;
  7455. if (ends)
  7456. transport.playing.store (true, std::memory_order_relaxed);
  7457. }
  7458. }
  7459. done += n;
  7460. }
  7461. // the latency ping (round 163): only its clicks go out (no feedback through a monitored input), listened for on
  7462. // its input
  7463. if (ping.isRunning())
  7464. {
  7465. for (int ch = 0; ch < numOutputChannels; ++ch)
  7466. if (outputChannelData[ch] != nullptr)
  7467. juce::FloatVectorOperations::clear (outputChannelData[ch], numSamples);
  7468. std::array<float*, 2> clickOut {};
  7469. for (std::size_t k = 0; k < 2; ++k)
  7470. if (pingOutputs[k] >= 0 && pingOutputs[k] < numOutputChannels)
  7471. clickOut[k] = outputChannelData[pingOutputs[k]];
  7472. const auto* in = pingInput >= 0 && pingInput < numInputChannels ? inputChannelData[pingInput] : nullptr;
  7473. ping.process (in, clickOut.data(), 2, numSamples);
  7474. }
  7475. // the block is done: the workers sleep until the next one instead of spinning (REA round 116) — unless render-ahead
  7476. // runs: its thread hands them blocks between the callbacks and parks them itself (round 190gq)
  7477. if (workers != nullptr && (rackProcessor == nullptr || ! rackProcessor->renderAheadOwnsWorkers()))
  7478. workers->park();
  7479. // the live clock (round 170d): the next block's musical position — during the count-in the metronome's count before
  7480. // the start (the start minus the count-in left)
  7481. {
  7482. const auto tps = transport.ticksPerSample();
  7483. const auto nowPlaying = transport.playing.load (std::memory_order_relaxed);
  7484. const auto left = transport.countIn.load (std::memory_order_relaxed);
  7485. const auto counting = left > 0.0 && ! nowPlaying;
  7486. const auto position = transport.positionTicks.load (std::memory_order_relaxed);
  7487. clockTick.store (counting ? position - left : position, std::memory_order_relaxed);
  7488. clockTicksPerMs.store (tps * transport.sampleRate.load (std::memory_order_relaxed) * 0.001, std::memory_order_relaxed);
  7489. clockRunning.store (nowPlaying || counting, std::memory_order_relaxed);
  7490. }
  7491. if (const auto rate = transport.sampleRate.load (std::memory_order_relaxed); rate > 0.0)
  7492. blockDurationMs.store (1000.0 * numSamples / rate, std::memory_order_relaxed);
  7493. blockTimeMs.store (juce::Time::getMillisecondCounterHiRes(), std::memory_order_release);
  7494. }
  7495. void AudioEngine::audioDeviceAboutToStart (juce::AudioIODevice* device)
  7496. {
  7497. rtStats.deviceRestarted();
  7498. rt::resetForNewDevice();
  7499. transport.sampleRate.store (device->getCurrentSampleRate());
  7500. meters.rollingLog.setSampleRate (device->getCurrentSampleRate()); // (the audio thread isn't running yet: it may allocate)
  7501. midiSync.deviceStarted (device->getCurrentSampleRate(), device->getCurrentBufferSizeSamples(), device->getOutputLatencyInSamples());
  7502. abletonLink.deviceStarted (device->getCurrentSampleRate()); // (round 190gl: the Link session's sample clock starts over)
  7503. // what is heard comes out one output buffer + the driver's output latency after it was rendered (round 170d, as
  7504. // the MIDI clock output counts it)
  7505. outputCompensationMs.store (1000.0 * (device->getCurrentBufferSizeSamples() + juce::jmax (0, device->getOutputLatencyInSamples()))
  7506. / juce::jmax (1.0, device->getCurrentSampleRate()));
  7507. // FL's fixed size buffers: 2 ms, or the device buffer with "Process maximum size buffers" (REA round 134)
  7508. setFixedPluginBlock (device->getCurrentBufferSizeSamples(), device->getCurrentSampleRate());
  7509. // the callback gets the open input channels only, in order: map device channel -> callback index
  7510. const auto active = device->getActiveInputChannels();
  7511. int slot = 0;
  7512. for (int c = 0; c < LiveInput::maxChannels; ++c)
  7513. inputSlot[(std::size_t) c] = active[c] ? slot++ : -1;
  7514. // the same for the outputs (hardware output targets, REA round 156)
  7515. const auto activeOut = device->getActiveOutputChannels();
  7516. slot = 0;
  7517. for (int c = 0; c < HardwareOutput::maxChannels; ++c)
  7518. outputSlot[(std::size_t) c] = activeOut[c] ? slot++ : -1;
  7519. hwOutput.clear();
  7520. hwOutput.active.store (true);
  7521. player.audioDeviceAboutToStart (device);
  7522. joinDeviceWorkgroup (device);
  7523. if (! processFullSpeed) // (Windows: the process stays out of EcoQoS while a device is open, round toolchain190gt)
  7524. {
  7525. processFullSpeed = true;
  7526. power::holdProcessFullSpeed (true);
  7527. }
  7528. #if JUCE_WINDOWS
  7529. choosePriorityClass();
  7530. juce::Timer::callAfterDelay (2000, [] { choosePriorityClass(); }); // (after the MIDI ports: WinMM raises it again)
  7531. #endif
  7532. }
  7533. void AudioEngine::audioDeviceStopped()
  7534. {
  7535. hwOutput.active.store (false);
  7536. player.audioDeviceStopped();
  7537. joinDeviceWorkgroup (nullptr);
  7538. if (processFullSpeed)
  7539. {
  7540. processFullSpeed = false;
  7541. power::holdProcessFullSpeed (false);
  7542. }
  7543. }
  7544. // macOS (round toolchain190gt): the render workers join the device's audio workgroup (os_workgroup, macOS 11+), so the
  7545. // scheduler runs them with the device's I/O thread as one real-time job with the buffer's deadline: on Apple silicon,
  7546. // on the performance cores. Each worker joins on its own thread (WorkerPool::setThreadRefresh) the next time it wakes,
  7547. // first becoming a time-constraint thread. A stopped device: the workers leave. LYNX_WORKGROUP=0 turns it off.
  7548. // Elsewhere this does nothing (Windows: MMCSS "Pro Audio" and no EcoQoS; Linux: SCHED_FIFO / RealtimeKit, round 161).
  7549. struct AudioEngine::DeviceWorkgroup
  7550. {
  7551. juce::SpinLock lock;
  7552. juce::AudioWorkgroup workgroup; // (empty: no device, or one without a workgroup)
  7553. double blockMs = 0.0;
  7554. };
  7555. void AudioEngine::joinDeviceWorkgroup ([[maybe_unused]] juce::AudioIODevice* device)
  7556. {
  7557. #if JUCE_MAC
  7558. static const auto off = juce::SystemStats::getEnvironmentVariable ("LYNX_WORKGROUP", {}) == "0";
  7559. if (off || workers == nullptr || workers->workers() == 0)
  7560. return;
  7561. auto wanted = device != nullptr ? device->getWorkgroup() : juce::AudioWorkgroup {};
  7562. if (deviceWorkgroup == nullptr)
  7563. {
  7564. if (! wanted)
  7565. return;
  7566. deviceWorkgroup = std::make_shared<DeviceWorkgroup>();
  7567. // (the pool keeps the holder alive as long as its workers can run the refresh)
  7568. workers->setThreadRefresh ([holder = deviceWorkgroup] {
  7569. struct Joined
  7570. {
  7571. juce::AudioWorkgroup workgroup; // (retained while joined: the token leaves it before it is released)
  7572. juce::WorkgroupToken token;
  7573. };
  7574. thread_local Joined joined;
  7575. juce::AudioWorkgroup next;
  7576. double blockMs = 0.0;
  7577. {
  7578. const juce::SpinLock::ScopedLockType sl (holder->lock);
  7579. next = holder->workgroup;
  7580. blockMs = holder->blockMs;
  7581. }
  7582. if (next == joined.workgroup && (! next || static_cast<bool> (joined.token)))
  7583. return;
  7584. joined.token.reset();
  7585. joined.workgroup = next;
  7586. if (! next)
  7587. return;
  7588. becomeTimeConstraintThread (blockMs);
  7589. next.join (joined.token);
  7590. });
  7591. }
  7592. {
  7593. const juce::SpinLock::ScopedLockType sl (deviceWorkgroup->lock);
  7594. deviceWorkgroup->workgroup = std::move (wanted);
  7595. deviceWorkgroup->blockMs = device != nullptr ? 1000.0 * device->getCurrentBufferSizeSamples() / juce::jmax (1.0, device->getCurrentSampleRate())
  7596. : 0.0;
  7597. }
  7598. workers->requestThreadRefresh();
  7599. #endif
  7600. }
  7601. // The Master's own target (its default: the graph's output as it is, on the first open pair) and the inserts'
  7602. // hardware outputs, added into the device channels they chose. A channel that is not open drops its sound.
  7603. void AudioEngine::routeOutputs (float* const* outputs, int numOutputs, int n) noexcept
  7604. {
  7605. const auto slotOf = [this] (int c) { return c >= 0 && c < HardwareOutput::maxChannels ? outputSlot[(std::size_t) c] : -1; };
  7606. if (const auto channel = masterOutChannel.load (std::memory_order_relaxed); channel != outputDefault && numOutputs > 0 && n <= HardwareOutput::capacity)
  7607. {
  7608. auto* l = masterScratch.data();
  7609. auto* r = masterScratch.data() + HardwareOutput::capacity;
  7610. const auto* srcR = numOutputs > 1 && outputs[1] != nullptr ? outputs[1] : outputs[0];
  7611. if (outputs[0] == nullptr)
  7612. return;
  7613. std::copy (outputs[0], outputs[0] + n, l);
  7614. std::copy (srcR, srcR + n, r);
  7615. for (int k = 0; k < std::min (numOutputs, 2); ++k)
  7616. if (outputs[k] != nullptr)
  7617. std::fill (outputs[k], outputs[k] + n, 0.0f);
  7618. const auto mode = (OutputMode) masterOutMode.load (std::memory_order_relaxed);
  7619. const auto [first, count] = outputChannelsOf (channel, mode);
  7620. if (count > 0)
  7621. {
  7622. const auto a = slotOf (first), b = count > 1 ? slotOf (first + 1) : -1;
  7623. if (a >= 0 && a < numOutputs)
  7624. addToOutput (l, r, mode, outputs[a], b >= 0 && b < numOutputs ? outputs[b] : nullptr, n);
  7625. }
  7626. }
  7627. hwOutput.drainInto (outputs, numOutputs, slotOf, n);
  7628. }
  7629. std::vector<std::string> AudioEngine::getOutputChannelNames() const
  7630. {
  7631. std::vector<std::string> names;
  7632. if (auto* device = deviceManager.getCurrentAudioDevice(); device != nullptr)
  7633. for (const auto& n : device->getOutputChannelNames())
  7634. if ((int) names.size() < HardwareOutput::maxChannels)
  7635. names.push_back (n.toStdString());
  7636. return names;
  7637. }
  7638. bool AudioEngine::isOutputChannelOpen (int channel) const
  7639. {
  7640. auto* device = deviceManager.getCurrentAudioDevice();
  7641. return device != nullptr && channel >= 0 && device->getActiveOutputChannels()[channel];
  7642. }
  7643. void AudioEngine::setTrackOutput (int track, int channel, OutputMode mode)
  7644. {
  7645. if (track < 0 || track >= (int) song.mixer.size())
  7646. return;
  7647. if (track > 0 && channel < 0) // an insert without a target: the default (the Master only), nothing saved
  7648. channel = outputDefault;
  7649. editSong ([=] (Song& s) {
  7650. s.mixer[(std::size_t) track].outputChannel = channel;
  7651. s.mixer[(std::size_t) track].outputMode = mode;
  7652. });
  7653. openTargetedOutputs();
  7654. }
  7655. void AudioEngine::openHardwareInsertIo()
  7656. {
  7657. openTargetedOutputs();
  7658. if (hwinsert::returnsFromInput (song) && ! hasAudioInput())
  7659. if (const auto result = openAudioInput(); result.issue != InputIssue::none)
  7660. notify (result.issue, 0, result.detail);
  7661. }
  7662. void AudioEngine::openTargetedOutputs()
  7663. {
  7664. auto* device = deviceManager.getCurrentAudioDevice();
  7665. if (device == nullptr)
  7666. return;
  7667. const auto available = juce::jmin ((int) HardwareOutput::maxChannels, device->getOutputChannelNames().size());
  7668. auto setup = deviceManager.getAudioDeviceSetup();
  7669. auto wanted = device->getActiveOutputChannels();
  7670. const auto before = wanted;
  7671. for (const auto& t : song.mixer)
  7672. {
  7673. const auto [first, count] = outputChannelsOf (t.outputChannel, t.outputMode);
  7674. for (int c = first; c < first + count; ++c)
  7675. if (c < available)
  7676. wanted.setBit (c);
  7677. }
  7678. // the hardware inserts' sends (round 164d; inside Patchers too, round 165c)
  7679. hwinsert::forEachHardwareInsert (song, [&wanted, available] (const EffectSlot& fx, bool) {
  7680. const auto [from, n] = outputChannelsOf (hwinsert::channelOf (fx.params[hwinsert::output]), hwinsert::outputModeOf (fx.params));
  7681. for (int c = from; c < from + n; ++c)
  7682. if (c < available)
  7683. wanted.setBit (c);
  7684. });
  7685. if (wanted == before)
  7686. return;
  7687. setup.useDefaultOutputChannels = false;
  7688. setup.outputChannels = wanted;
  7689. deviceManager.setAudioDeviceSetup (setup, true);
  7690. sendChangeMessage();
  7691. }
  7692. // --- hardware inserts anywhere in the song (round 165c) ------------------------------------------------------------
  7693. namespace
  7694. {
  7695. template <typename F>
  7696. void walkHardwareInserts (const PatcherDoc& doc, AudioEngine::HardwareInsertRef& ref, F&& f)
  7697. {
  7698. for (int n = 0; n < (int) doc.nodes.size(); ++n)
  7699. {
  7700. const auto& node = doc.nodes[(std::size_t) n];
  7701. ref.nodes.push_back (n);
  7702. if (node.generator ? node.channel.instrument == InstrumentKind::patcher : node.effect.kind == EffectKind::patcher)
  7703. walkHardwareInserts (node.generator ? node.channel.patcher : node.effect.patcher, ref, f);
  7704. else if (! node.generator && node.effect.kind == EffectKind::hardwareInsert)
  7705. f (ref);
  7706. ref.nodes.pop_back();
  7707. }
  7708. }
  7709. } // namespace
  7710. std::vector<AudioEngine::HardwareInsertRef> AudioEngine::getHardwareInserts() const
  7711. {
  7712. std::vector<HardwareInsertRef> out;
  7713. auto add = [&out] (const HardwareInsertRef& r) { out.push_back (r); };
  7714. for (int t = 0; t < (int) song.mixer.size(); ++t)
  7715. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  7716. {
  7717. const auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) s];
  7718. HardwareInsertRef ref { false, t, s, {} };
  7719. if (fx.kind == EffectKind::hardwareInsert)
  7720. out.push_back (ref);
  7721. else if (fx.kind == EffectKind::patcher)
  7722. walkHardwareInserts (fx.patcher, ref, add);
  7723. }
  7724. for (int c = 0; c < (int) song.channels.size(); ++c)
  7725. if (song.channels[(std::size_t) c].instrument == InstrumentKind::patcher)
  7726. {
  7727. HardwareInsertRef ref { true, c, 0, {} };
  7728. walkHardwareInserts (song.channels[(std::size_t) c].patcher, ref, add);
  7729. }
  7730. return out;
  7731. }
  7732. EffectSlot* AudioEngine::locateHardwareInsert (Song& s, const HardwareInsertRef& ref)
  7733. {
  7734. PatcherDoc* doc = nullptr;
  7735. if (ref.channel)
  7736. {
  7737. if (ref.index < 0 || ref.index >= (int) s.channels.size() || s.channels[(std::size_t) ref.index].instrument != InstrumentKind::patcher)
  7738. return nullptr;
  7739. doc = &s.channels[(std::size_t) ref.index].patcher;
  7740. }
  7741. else
  7742. {
  7743. 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())
  7744. return nullptr;
  7745. auto& fx = s.mixer[(std::size_t) ref.index].effects[(std::size_t) ref.slot];
  7746. if (ref.nodes.empty())
  7747. return fx.kind == EffectKind::hardwareInsert ? &fx : nullptr;
  7748. if (fx.kind != EffectKind::patcher)
  7749. return nullptr;
  7750. doc = &fx.patcher;
  7751. }
  7752. for (std::size_t k = 0; k < ref.nodes.size(); ++k)
  7753. {
  7754. const auto n = ref.nodes[k];
  7755. if (doc == nullptr || n < 0 || n >= (int) doc->nodes.size())
  7756. return nullptr;
  7757. auto& node = doc->nodes[(std::size_t) n];
  7758. if (k + 1 == ref.nodes.size())
  7759. return ! node.generator && node.effect.kind == EffectKind::hardwareInsert ? &node.effect : nullptr;
  7760. doc = node.generator ? (node.channel.instrument == InstrumentKind::patcher ? &node.channel.patcher : nullptr)
  7761. : (node.effect.kind == EffectKind::patcher ? &node.effect.patcher : nullptr);
  7762. }
  7763. return nullptr;
  7764. }
  7765. std::shared_ptr<Effect> AudioEngine::runningHardwareInsert (const HardwareInsertRef& ref) const
  7766. {
  7767. patcher::Graph* graph = nullptr;
  7768. if (ref.channel)
  7769. graph = patcher::graphOf (getChannelInstrument (ref.index).get());
  7770. else
  7771. {
  7772. auto fx = getEffect (ref.index, ref.slot);
  7773. if (ref.nodes.empty())
  7774. return fx;
  7775. graph = patcher::graphOf (fx.get());
  7776. }
  7777. for (std::size_t k = 0; k < ref.nodes.size() && graph != nullptr; ++k)
  7778. {
  7779. const auto n = ref.nodes[k];
  7780. if (n < 0 || n >= graph->nodeCount())
  7781. return nullptr;
  7782. if (k + 1 == ref.nodes.size())
  7783. return graph->effectAt (n);
  7784. auto* next = patcher::graphOf (graph->effectAt (n).get());
  7785. graph = next != nullptr ? next : patcher::graphOf (graph->instrumentAt (n).get());
  7786. }
  7787. return nullptr;
  7788. }
  7789. std::vector<AudioEngine::HardwareInsertRef> AudioEngine::staleHardwareInserts() const
  7790. {
  7791. std::vector<HardwareInsertRef> out;
  7792. const auto key = currentSetupKey();
  7793. if (key.empty())
  7794. return out;
  7795. for (const auto& ref : getHardwareInserts())
  7796. if (const auto* fx = locateHardwareInsert (const_cast<Song&> (song), ref))
  7797. if (fx->enabled && hwinsert::isRouted (fx->params))
  7798. if (const auto measured = hwinsert::measuredSetup (*fx); ! measured.empty() && measured != key)
  7799. out.push_back (ref);
  7800. return out;
  7801. }
  7802. void AudioEngine::pingHardwareInserts (const std::vector<HardwareInsertRef>& refs)
  7803. {
  7804. if (refs.empty())
  7805. return;
  7806. editSong ([refs] (Song& s) {
  7807. for (const auto& ref : refs)
  7808. if (auto* fx = locateHardwareInsert (s, ref))
  7809. fx->params[hwinsert::ping] = fx->params[hwinsert::ping] >= 0.5f ? 0.0f : 1.0f; // (a momentary value: any change)
  7810. }, false);
  7811. }
  7812. void AudioEngine::applyHardwareInsertPings()
  7813. {
  7814. if (deviceManager.getCurrentAudioDevice() == nullptr)
  7815. return;
  7816. const auto refs = getHardwareInserts();
  7817. const auto key = currentSetupKey();
  7818. // the device setup changed: the inserts measured for the old one (or, measured before LYNX kept the setup, for the
  7819. // one that was running) want a new ping — a notice for the UI, nothing pinged by itself
  7820. if (key != lastSetupKey)
  7821. {
  7822. const auto previous = std::exchange (lastSetupKey, key);
  7823. if (! previous.empty() && ! refs.empty())
  7824. {
  7825. editSong ([refs, previous] (Song& s) {
  7826. for (const auto& ref : refs)
  7827. if (auto* fx = locateHardwareInsert (s, ref); fx != nullptr && hwinsert::measuredSetup (*fx).empty()
  7828. && hwinsert::isRouted (fx->params) && hwinsert::roundTripOf (fx->params[hwinsert::roundTrip]) > 0)
  7829. hwinsert::setMeasuredSetup (*fx, previous);
  7830. }, false);
  7831. hwNotice = staleHardwareInserts();
  7832. if (! hwNotice.empty())
  7833. sendChangeMessage();
  7834. }
  7835. }
  7836. if (std::exchange (checkHardwareInserts, false) && hwNotice.empty())
  7837. {
  7838. hwNotice = staleHardwareInserts();
  7839. if (! hwNotice.empty())
  7840. sendChangeMessage();
  7841. }
  7842. // ping results: each one becomes its slot's round trip once (undoable, saved with the project), with this setup
  7843. for (const auto& ref : refs)
  7844. {
  7845. const auto fx = runningHardwareInsert (ref);
  7846. if (fx == nullptr)
  7847. continue;
  7848. const auto serial = juce::roundToInt (fx->controlOutput (hwinsert::pingSerial) * 1024.0f);
  7849. const auto [it, fresh] = hwPingSerials.try_emplace (fx.get(), serial);
  7850. if (fresh || it->second == serial)
  7851. continue;
  7852. it->second = serial;
  7853. if (std::abs (fx->controlOutput (hwinsert::pingState) - 0.5f) >= 0.01f)
  7854. continue; // (failed: the editor says why; the old round trip stays)
  7855. const auto samples = hwinsert::roundTripOf (fx->controlOutput (hwinsert::pingSamples));
  7856. editSong ([ref, samples, key] (Song& s) {
  7857. if (auto* slot = locateHardwareInsert (s, ref))
  7858. {
  7859. slot->params[hwinsert::roundTrip] = hwinsert::roundTripValue (samples);
  7860. hwinsert::setMeasuredSetup (*slot, key);
  7861. }
  7862. });
  7863. }
  7864. if (hwPingSerials.size() > 4 * refs.size() + 16) // (instances rebuilt meanwhile)
  7865. hwPingSerials.clear();
  7866. }
  7867. // --- real-time bounce (round 165c) ----------------------------------------------------------------------------------
  7868. juce::String AudioEngine::startRealtimeBounce (double startTick)
  7869. {
  7870. auto* device = deviceManager.getCurrentAudioDevice();
  7871. if (device == nullptr || transport.sampleRate.load() <= 0.0)
  7872. return tr ("No audio device is open");
  7873. if (transport.recording.load() || takeCount > 0)
  7874. return tr ("Stop recording first");
  7875. if (ping.isRunning())
  7876. return tr ("A latency ping is running");
  7877. if (bouncing)
  7878. return tr ("A real-time bounce is already running");
  7879. stop();
  7880. bounceReturnTick = transport.positionTicks.load();
  7881. bounceRestoreMode = song.mode != PlayMode::song;
  7882. if (bounceRestoreMode)
  7883. editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  7884. bouncing = true;
  7885. updateLinearSong(); // (plays on past the song's end and through the loop region, like a linear recording)
  7886. bounceStartLatency = getLatencySamples();
  7887. bounceStartXruns = device->getXRunCount();
  7888. meters.bounceTap.setSource (0); // (pushed only while the song plays: the first frame is the start's)
  7889. transport.positionTicks.store (juce::jmax (0.0, startTick));
  7890. transport.seekRequest.store (juce::jmax (0.0, startTick));
  7891. play();
  7892. sendChangeMessage();
  7893. return {};
  7894. }
  7895. int AudioEngine::bounceDropouts() const
  7896. {
  7897. auto* device = deviceManager.getCurrentAudioDevice();
  7898. const auto xruns = device != nullptr ? juce::jmax (0, device->getXRunCount() - bounceStartXruns) : 0;
  7899. return xruns + (meters.bounceTap.droppedFrames() > 0 ? 1 : 0);
  7900. }
  7901. void AudioEngine::finishRealtimeBounce()
  7902. {
  7903. if (! bouncing)
  7904. return;
  7905. stop();
  7906. meters.bounceTap.setSource (AudioCapture::off);
  7907. bouncing = false;
  7908. updateLinearSong();
  7909. if (std::exchange (bounceRestoreMode, false))
  7910. editSong ([] (Song& s) { s.mode = PlayMode::pattern; }, false);
  7911. seek (bounceReturnTick);
  7912. sendChangeMessage();
  7913. }
  7914. } // namespace lynx