Main.cpp 374 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762
  1. #include <juce_gui_basics/juce_gui_basics.h>
  2. #include "platform/Paths.h"
  3. #include "core/LoadTrace.h"
  4. #include "core/Effects.h"
  5. #include "core/MixSuite.h"
  6. #include "core/HardwareInsert.h"
  7. #include "core/EchoSuite.h"
  8. #include "core/LynxTune.h"
  9. #include "core/FlEffects.h"
  10. #include "core/FlpImport.h"
  11. #include "core/NoteEdit.h"
  12. #include "core/MaximusFx.h"
  13. #include "core/Harmor.h"
  14. #include "flp/Flp.h"
  15. #include "core/SynthPresets.h"
  16. #include "core/FlWrapper.h"
  17. #include "engine/AudioEngine.h"
  18. #include "engine/AudioLogger.h"
  19. #include "engine/DllAsioDevice.h"
  20. #include "engine/PipeWireDevice.h"
  21. #include "platform/LinuxRealtime.h"
  22. #include "engine/Exporter.h"
  23. #include "engine/MidiFileIo.h"
  24. #include "engine/PluginHost.h"
  25. #include "engine/PluginSandbox.h"
  26. #include "engine/ProjectFile.h"
  27. #include "engine/SampleLibrary.h"
  28. #include "engine/Text.h"
  29. #include "platform/FileTypes.h"
  30. #include "platform/Package.h"
  31. #include "ui/PatcherEditor.h"
  32. #include "ui/VisualEditors.h"
  33. #include "ui/FlExtraEditors.h"
  34. #include "ui/VisualGl.h"
  35. #include "ui/DanceView.h"
  36. #include "ui/PluginPresetMenu.h"
  37. #include "ui/PluginWindow.h"
  38. #include "ui/ClipProperties.h"
  39. #include "ui/NewProjectDialog.h"
  40. #include "ui/PluginMonitorWindow.h"
  41. #include "ui/TouchKeyboard.h"
  42. #include "ui/AutomationUi.h"
  43. #include "ui/PluginSkin.h"
  44. #include "ui/ChannelSettings.h"
  45. #include "ui/ControllerEditors.h"
  46. #include "ui/NewtoneEditor.h"
  47. #include "core/NewtoneFx.h"
  48. #include "core/FormulaController.h"
  49. #include "core/MidiControls.h"
  50. #include "core/FlSynths.h"
  51. #include "ui/Dialogs.h"
  52. #include "core/RackOps.h"
  53. #include "core/Layer.h"
  54. #include "core/XyController.h"
  55. #include "core/FlCurve.h"
  56. #include "core/ControlSurface.h"
  57. #include "core/VoltageController.h"
  58. #include "ui/Controllers164.h"
  59. #include "ui/ExportDialog.h"
  60. #include "ui/I18n.h"
  61. #include "ui/MainComponent.h"
  62. #include "engine/ProjectPackage.h"
  63. #include "ui/SetupWizard.h"
  64. #include "engine/FlStudio.h"
  65. #include "ui/HistoryPanel.h"
  66. #include "ui/MissingFilesDialog.h"
  67. #include "ui/SettingsDialog.h"
  68. #include "ui/PluginManager.h"
  69. #include "ui/ShortcutManager.h"
  70. #include "ui/NoteToolDialogs.h"
  71. #include "ui/EventEditor.h"
  72. #include "ui/AudioEditor.h"
  73. #include "ui/TempoTapper.h"
  74. #include "core/EventEdit.h"
  75. #include "core/FacetEq.h"
  76. #include "ui/FacetEqEditor.h"
  77. #include "core/RackRenderer.h"
  78. #include "ui/ProEditors.h"
  79. #include "ui/ParametricEqEditor.h"
  80. #include "ui/PluginEditors.h"
  81. #include "core/PluginLayout.h"
  82. #include "core/Vfx.h"
  83. #include "ui/Splash.h"
  84. #include "ui/Theme.h"
  85. #include "ui/ThemeSettings.h"
  86. #include "ui/WaveformView.h"
  87. #include "ui/WindowOwner.h"
  88. #include "ui/Toolbar.h"
  89. #include "ui/ToolWindow.h"
  90. #include "platform/CrashGuard.h"
  91. #include "ui/CrashReporter.h"
  92. #include <atomic>
  93. #include <chrono>
  94. #include <cstdio>
  95. #include <cstdlib>
  96. #include <mutex>
  97. #include <thread>
  98. namespace
  99. {
  100. lynx::AudioEngine* crashEngine = nullptr;
  101. // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
  102. // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
  103. struct StartupTrace
  104. {
  105. using clock = std::chrono::steady_clock;
  106. const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
  107. const bool on = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
  108. juce::String text;
  109. clock::time_point last = t0;
  110. double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
  111. void mark (const char* step)
  112. {
  113. if (! on)
  114. return;
  115. const auto now = clock::now();
  116. const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
  117. text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7) << " " << step << "\n";
  118. last = now;
  119. lynx::platform::settingsFile ("startup.log").replaceWithText (text);
  120. }
  121. };
  122. StartupTrace startupTrace;
  123. void startupMarkHook (const char* step) { startupTrace.mark (step); }
  124. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  125. void onCrash (void* exceptionPointers)
  126. {
  127. const auto folder = lynx::platform::settingsFile ("autosave");
  128. folder.createDirectory();
  129. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  130. // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
  131. // release LYNX.exe has no symbols, so its own frames were missing from the file)
  132. folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
  133. + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
  134. lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
  135. if (crashEngine != nullptr)
  136. {
  137. juce::String error;
  138. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  139. }
  140. }
  141. juce::File sessionsFolder()
  142. {
  143. return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
  144. }
  145. // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
  146. // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
  147. juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
  148. juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
  149. // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
  150. // whether its crash file blames a graphics driver
  151. struct UncleanCause
  152. {
  153. juce::String editorPlugin; // the last steps were that plugin's editor
  154. bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
  155. juce::String driverModule;
  156. };
  157. UncleanCause uncleanCause()
  158. {
  159. UncleanCause cause;
  160. juce::File crashFile;
  161. for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
  162. {
  163. const auto& step = uncleanSteps[i];
  164. if (step.startsWith ("crashed: backtrace in "))
  165. crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
  166. for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
  167. if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
  168. cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
  169. if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
  170. break; // older steps than these did not end the session
  171. }
  172. if (crashFile.existsAsFile())
  173. {
  174. // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
  175. auto text = crashFile.loadFileAsString();
  176. if (text.contains ("--- frames"))
  177. text = text.fromFirstOccurrenceOf ("--- frames", false, false);
  178. auto lines = juce::StringArray::fromLines (text);
  179. int looked = 0;
  180. for (const auto& line : lines)
  181. {
  182. const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
  183. if (module.isEmpty() || ! module.endsWith (".dll"))
  184. continue;
  185. if (++looked > 12)
  186. break;
  187. for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
  188. "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
  189. if (module.startsWith (driver))
  190. {
  191. cause.gpuDriver = true;
  192. cause.driverModule = module;
  193. break;
  194. }
  195. if (cause.gpuDriver)
  196. break;
  197. }
  198. }
  199. return cause;
  200. }
  201. juce::String collectUncleanSessions()
  202. {
  203. juce::String lastStep;
  204. juce::Time newest;
  205. for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
  206. {
  207. const auto text = file.loadFileAsString();
  208. juce::StringPairArray values;
  209. juce::StringArray steps;
  210. for (const auto& line : juce::StringArray::fromLines (text))
  211. {
  212. if (line.startsWith ("step="))
  213. steps.add (line.fromFirstOccurrenceOf ("=", false, false));
  214. else if (line.contains ("="))
  215. values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
  216. }
  217. const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
  218. const auto start = (std::uint64_t) values["start"].getLargeIntValue();
  219. if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
  220. continue; // this run, or another LYNX window still open
  221. lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
  222. .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
  223. file.deleteFile();
  224. if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
  225. {
  226. newest = modified;
  227. lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
  228. uncleanSessionText = text;
  229. uncleanSteps.clear();
  230. for (const auto& step : steps)
  231. uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
  232. }
  233. }
  234. return lastStep;
  235. }
  236. } // namespace
  237. class LynxApplication final : public juce::JUCEApplication
  238. {
  239. public:
  240. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  241. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  242. // the plugin scan runs copies of LYNX as child processes
  243. bool moreThanOneInstanceAllowed() override { return true; }
  244. void initialise (const juce::String& commandLine) override
  245. {
  246. // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
  247. if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
  248. {
  249. relaunched = true;
  250. setApplicationReturnValue (code);
  251. quit();
  252. return;
  253. }
  254. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
  255. juce::SystemStats::setApplicationCrashHandler (onCrash);
  256. // child process of a sandboxed plugin: no window or audio of its own
  257. if (lynx::runPluginSandboxWorker (commandLine))
  258. {
  259. lynx::crashguard::quietCrashReports();
  260. sandboxChild = true;
  261. return;
  262. }
  263. const auto args = juce::StringArray::fromTokens (commandLine, true);
  264. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  265. lynx::i18n::initialise (args);
  266. if (args.contains ("--showcase"))
  267. {
  268. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  269. const auto i = args.indexOf ("--showcase");
  270. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  271. return;
  272. }
  273. if (args.contains ("--sandboxtest"))
  274. {
  275. const auto i = args.indexOf ("--sandboxtest");
  276. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  277. return;
  278. }
  279. if (args.contains ("--rtstress"))
  280. {
  281. // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
  282. // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
  283. // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
  284. // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
  285. const auto i = args.indexOf ("--rtstress");
  286. const auto seconds = args[i + 3].getDoubleValue();
  287. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  288. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  289. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  290. runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
  291. option ("--type"), option ("--device"), option ("--record"));
  292. return;
  293. }
  294. if (args.contains ("--rectest"))
  295. {
  296. // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
  297. // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
  298. // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
  299. // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
  300. // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
  301. // and 1 of post-roll (playback stops by itself after the post-roll).
  302. const auto i = args.indexOf ("--rectest");
  303. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  304. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  305. runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
  306. args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
  307. return;
  308. }
  309. if (args.contains ("--hwinserttest"))
  310. {
  311. // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
  312. // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
  313. // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
  314. // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
  315. // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
  316. // sample as the right side's.
  317. const auto i = args.indexOf ("--hwinserttest");
  318. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  319. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
  320. runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
  321. option ("--buffer").getIntValue());
  322. return;
  323. }
  324. if (args.contains ("--uiperf"))
  325. {
  326. // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
  327. const auto i = args.indexOf ("--uiperf");
  328. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  329. runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  330. return;
  331. }
  332. if (args.contains ("--selftest"))
  333. {
  334. const auto i = args.indexOf ("--selftest");
  335. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  336. return;
  337. }
  338. if (args.contains ("--scan-one"))
  339. {
  340. // child process of the plugin scan (see PluginHost::scan)
  341. const auto i = args.indexOf ("--scan-one");
  342. // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
  343. // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
  344. // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
  345. lynx::crashguard::quietCrashReports();
  346. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  347. lynx::crashguard::exitNow (0);
  348. }
  349. if (args.contains ("--packageinfo"))
  350. {
  351. // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
  352. // workflow runs it inside the installed test package
  353. juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
  354. quit();
  355. return;
  356. }
  357. if (args.contains ("--paths"))
  358. {
  359. // diagnostics: folders LYNX searches
  360. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  361. juce::String report;
  362. report << "programs=" << programs.getFullPathName() << "\n";
  363. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  364. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  365. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  366. quit();
  367. return;
  368. }
  369. if (args.contains ("--fldb"))
  370. {
  371. // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
  372. // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
  373. const auto i = args.indexOf ("--fldb");
  374. const auto fl = lynx::findFlStudio();
  375. lynx::PluginHost host (false);
  376. juce::String report;
  377. report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
  378. for (const auto& f : fl.vstFolders)
  379. report << "flvstfolder=" << f << "\n";
  380. report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
  381. for (const auto& e : host.flPluginDatabase().entries())
  382. report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
  383. const auto suggested = host.suggestedFolders();
  384. for (int k = 0; k < suggested.getNumPaths(); ++k)
  385. report << "folder=" << suggested[k].getFullPathName() << "\n";
  386. if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
  387. {
  388. juce::MemoryBlock data;
  389. project.loadFileAsData (data);
  390. try
  391. {
  392. for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
  393. {
  394. juce::String how;
  395. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  396. const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
  397. report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  398. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
  399. << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
  400. }
  401. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  402. const auto candidates = host.filesToScanFor (uses);
  403. report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
  404. if (args.contains ("--scan"))
  405. {
  406. // the targeted scan an open would run (child processes; the user's plugin list is not touched)
  407. report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
  408. for (const auto& use : uses)
  409. {
  410. juce::String how;
  411. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  412. report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  413. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
  414. }
  415. }
  416. }
  417. catch (const flp::Error& e)
  418. {
  419. report << "error=" << e.what() << "\n";
  420. }
  421. }
  422. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  423. quit();
  424. return;
  425. }
  426. if (args.contains ("--midisync-test"))
  427. {
  428. // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
  429. const auto i = args.indexOf ("--midisync-test");
  430. const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  431. const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  432. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
  433. quit();
  434. return;
  435. }
  436. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  437. {
  438. // diagnostics: driver types and output devices JUCE offers (without opening any)
  439. juce::AudioDeviceManager manager;
  440. juce::String report;
  441. manager.getAvailableDeviceTypes();
  442. if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
  443. manager.addAudioDeviceType (std::move (pipeWire));
  444. #if JUCE_LINUX
  445. report << lynx::describePipeWire() << "\n";
  446. #endif
  447. for (auto* type : manager.getAvailableDeviceTypes())
  448. {
  449. type->scanForDevices();
  450. report << "type=" << type->getTypeName() << "\n";
  451. for (const auto& name : type->getDeviceNames (false))
  452. report << " output=" << name << "\n";
  453. for (const auto& name : type->getDeviceNames (true))
  454. report << " input=" << name << "\n";
  455. }
  456. for (const auto& d : juce::MidiInput::getAvailableDevices())
  457. report << "midi-in=" << d.name << "\n";
  458. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  459. report << "midi-out=" << d.name << "\n";
  460. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  461. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  462. quit();
  463. return;
  464. }
  465. if (args.contains ("--devicetest"))
  466. {
  467. // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
  468. // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
  469. // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
  470. // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
  471. // cable / PipeWire link: the round-trip latency (3 s)
  472. const auto i = args.indexOf ("--devicetest");
  473. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  474. auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
  475. const auto wantInput = inputName.isNotEmpty();
  476. juce::String report;
  477. const juce::File reportFile (args[i + 3].unquoted());
  478. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  479. step ("step=start");
  480. juce::AudioDeviceManager manager;
  481. manager.getAvailableDeviceTypes();
  482. if (auto pipeWire = lynx::makePipeWireDeviceType())
  483. manager.addAudioDeviceType (std::move (pipeWire));
  484. std::unique_ptr<juce::AudioIODevice> device;
  485. for (auto* type : manager.getAvailableDeviceTypes())
  486. if (type->getTypeName() == typeName)
  487. {
  488. type->scanForDevices();
  489. if (wantInput && type->hasSeparateInputsAndOutputs())
  490. {
  491. const auto inputs = type->getDeviceNames (true);
  492. if (inputName == "*" || ! inputs.contains (inputName))
  493. {
  494. const auto index = type->getDefaultDeviceIndex (true);
  495. inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  496. }
  497. for (const auto& n : inputs)
  498. step ("input_device=" + n);
  499. step ("input_chosen=" + inputName);
  500. }
  501. else if (wantInput)
  502. inputName = deviceName;
  503. step ("step=create");
  504. device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
  505. step ("step=created");
  506. }
  507. struct Silence final : juce::AudioIODeviceCallback
  508. {
  509. std::atomic<int> calls { 0 }, inputs { 0 };
  510. std::array<std::atomic<float>, 64> peaks {};
  511. // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
  512. // loopback; the delays in samples
  513. bool roundtrip = false;
  514. int period = 12000;
  515. std::int64_t position = 0, lastClick = -1;
  516. std::vector<int> delays;
  517. void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
  518. const juce::AudioIODeviceCallbackContext&) override
  519. {
  520. for (int c = 0; c < channels; ++c)
  521. if (out[c] != nullptr)
  522. juce::FloatVectorOperations::clear (out[c], n);
  523. if (roundtrip)
  524. {
  525. for (int i = 0; i < n; ++i)
  526. {
  527. if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
  528. {
  529. if (delays.size() < delays.capacity())
  530. delays.push_back ((int) (position + i - lastClick));
  531. lastClick = -1;
  532. }
  533. if ((position + i) % period == 0 && position + i > 0)
  534. {
  535. for (int c = 0; c < channels; ++c)
  536. if (out[c] != nullptr)
  537. out[c][i] = 0.9f;
  538. lastClick = position + i;
  539. }
  540. }
  541. position += n;
  542. }
  543. inputs.store (numIn);
  544. for (int c = 0; c < juce::jmin (numIn, 64); ++c)
  545. if (in[c] != nullptr)
  546. {
  547. const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
  548. const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
  549. if (peak > peaks[(std::size_t) c].load())
  550. peaks[(std::size_t) c].store (peak);
  551. }
  552. ++calls;
  553. }
  554. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  555. void audioDeviceStopped() override {}
  556. } silence;
  557. bool ok = false;
  558. if (device == nullptr)
  559. step ("error=device not found");
  560. else
  561. {
  562. step ("step=open");
  563. juce::BigInteger outputs;
  564. outputs.setRange (0, 2, true);
  565. const auto rates = device->getAvailableSampleRates();
  566. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  567. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  568. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  569. juce::BigInteger inputs;
  570. if (wantInput)
  571. {
  572. const auto names = device->getInputChannelNames();
  573. step ("input_channels=" + juce::String (names.size()));
  574. for (int c = 0; c < names.size(); ++c)
  575. step (" in" + juce::String (c + 1) + "=" + names[c]);
  576. inputs.setRange (0, juce::jmin (64, names.size()), true);
  577. }
  578. // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
  579. const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  580. const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
  581. if (error.isNotEmpty())
  582. step ("error=" + error);
  583. else
  584. {
  585. step ("step=start_callbacks");
  586. silence.roundtrip = args.contains ("--roundtrip");
  587. silence.period = juce::jmax (1, (int) (rate / 4));
  588. silence.delays.reserve (64);
  589. device->start (&silence);
  590. juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
  591. device->stop();
  592. if (silence.roundtrip)
  593. {
  594. auto d = silence.delays;
  595. std::sort (d.begin(), d.end());
  596. report << "roundtrip_clicks=" << (int) d.size() << "\n";
  597. if (! d.empty())
  598. report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
  599. << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
  600. }
  601. report << "rate=" << device->getCurrentSampleRate() << "\n"
  602. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  603. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  604. << "callbacks=" << silence.calls.load() << "\n";
  605. if (wantInput)
  606. {
  607. report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
  608. << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
  609. << "callback_inputs=" << silence.inputs.load() << "\n";
  610. for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
  611. report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
  612. }
  613. ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
  614. device->close();
  615. }
  616. }
  617. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  618. setApplicationReturnValue (ok ? 0 : 1);
  619. quit();
  620. return;
  621. }
  622. if (args.contains ("--scantest"))
  623. {
  624. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  625. const auto i = args.indexOf ("--scantest");
  626. lynx::PluginHost host (false);
  627. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  628. juce::String report;
  629. report << "found=" << found << "\n";
  630. for (const auto& t : host.getKnownPlugins().getTypes())
  631. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  632. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  633. report << " blacklisted: " << f << "\n";
  634. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  635. setApplicationReturnValue (found > 0 ? 0 : 1);
  636. quit();
  637. return;
  638. }
  639. if (args.contains ("--vst2test"))
  640. {
  641. const auto i = args.indexOf ("--vst2test");
  642. runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
  643. return;
  644. }
  645. if (args.contains ("--wrappertest"))
  646. {
  647. const auto i = args.indexOf ("--wrappertest");
  648. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  649. return;
  650. }
  651. if (args.contains ("--plugintest"))
  652. {
  653. const auto i = args.indexOf ("--plugintest");
  654. // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
  655. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  656. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  657. return;
  658. }
  659. if (args.contains ("--editortest"))
  660. {
  661. // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
  662. // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
  663. const auto i = args.indexOf ("--editortest");
  664. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  665. runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  666. return;
  667. }
  668. if (args.contains ("--plugwintest"))
  669. {
  670. // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
  671. // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
  672. // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
  673. // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
  674. const auto i = args.indexOf ("--plugwintest");
  675. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
  676. auto seconds = 15;
  677. for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
  678. if (args[k].containsOnly ("0123456789"))
  679. seconds = args[k].getIntValue();
  680. runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
  681. return;
  682. }
  683. if (args.contains ("--fittest"))
  684. {
  685. // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
  686. // the screen and a big resizable window that grows with a zoom change keep their title bar and close
  687. // button on the screen. The windows show for about two seconds.
  688. const auto i = args.indexOf ("--fittest");
  689. runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
  690. return;
  691. }
  692. if (args.contains ("--windowtest"))
  693. {
  694. // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor and a plugin-like window
  695. // over the main window and checks that each one stays in front, owned by the main window, with the
  696. // keyboard focus (issue #4). The windows appear on screen for a few seconds.
  697. runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
  698. return;
  699. }
  700. if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
  701. {
  702. const auto i = args.indexOf ("--pluginstyle");
  703. if (i + 1 < args.size())
  704. {
  705. const auto name = args[i + 1].unquoted();
  706. lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
  707. }
  708. }
  709. if (args.contains ("--plugui"))
  710. {
  711. // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
  712. // loaded with the FL plugin's Default preset when the FL installation has one
  713. const auto i = args.indexOf ("--plugui");
  714. runPluginEditorSnapshots (args[i + 1].unquoted());
  715. return;
  716. }
  717. if (args.contains ("--editorcpu"))
  718. {
  719. // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
  720. // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
  721. // animates (demo signal) — round 122's check that an idle editor burns no CPU
  722. const auto i = args.indexOf ("--editorcpu");
  723. runEditorCpu (args[i + 1].unquoted());
  724. return;
  725. }
  726. if (args.contains ("--flextrashot"))
  727. {
  728. // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2)
  729. const auto i = args.indexOf ("--flextrashot");
  730. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  731. lynx::AudioEngine shotEngine (false);
  732. const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
  733. setApplicationReturnValue (ok ? 0 : 1);
  734. quit();
  735. return;
  736. }
  737. if (args.contains ("--visualtest"))
  738. {
  739. // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
  740. // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
  741. // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
  742. const auto i = args.indexOf ("--visualtest");
  743. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  744. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
  745. lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
  746. setApplicationReturnValue (ok ? 0 : 1);
  747. quit();
  748. });
  749. return;
  750. }
  751. if (args.contains ("--menu-entry"))
  752. {
  753. // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
  754. // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
  755. const auto i = args.indexOf ("--menu-entry");
  756. const auto on = args[i + 1].unquoted() != "off";
  757. const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
  758. std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX added to the applications menu" : "LYNX removed from the applications menu")
  759. : "only the LYNX AppImage on Linux can do this");
  760. setApplicationReturnValue (ok ? 0 : 1);
  761. quit();
  762. return;
  763. }
  764. if (args.contains ("--send-test-report"))
  765. {
  766. // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
  767. // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
  768. // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
  769. const auto i = args.indexOf ("--send-test-report");
  770. const juce::File out (args[i + 1].unquoted());
  771. lynx::crashreporter::Session session;
  772. session.version = getApplicationVersion();
  773. for (const auto* pattern : { "crash *.txt", "hang *.txt" })
  774. {
  775. auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
  776. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getLastModificationTime() > b.getLastModificationTime(); });
  777. if (! files.isEmpty())
  778. (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
  779. }
  780. session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
  781. auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
  782. input.test = true;
  783. const auto json = lynx::crashreporter::buildJson (input, false);
  784. out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
  785. const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
  786. out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
  787. + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
  788. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  789. quit();
  790. return;
  791. }
  792. if (args.contains ("--symbolize"))
  793. {
  794. // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
  795. // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
  796. const auto i = args.indexOf ("--symbolize");
  797. const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
  798. juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
  799. quit();
  800. return;
  801. }
  802. if (args.contains ("--opentest"))
  803. {
  804. // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
  805. // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
  806. // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
  807. const auto i = args.indexOf ("--opentest");
  808. runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
  809. setApplicationReturnValue (ok ? 0 : 1);
  810. quit();
  811. });
  812. return;
  813. }
  814. if (args.contains ("--fxfuzz"))
  815. {
  816. // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
  817. // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
  818. const auto i = args.indexOf ("--fxfuzz");
  819. const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
  820. // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
  821. const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
  822. setApplicationReturnValue (ok ? 0 : 1);
  823. quit();
  824. return;
  825. }
  826. if (args.contains ("--controllershot"))
  827. {
  828. // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
  829. const auto i = args.indexOf ("--controllershot");
  830. runControllerShot (args[i + 1].unquoted());
  831. quit();
  832. return;
  833. }
  834. if (args.contains ("--danceshot"))
  835. {
  836. // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
  837. // and a demo project with two dance channels (for --snapshot)
  838. const auto i = args.indexOf ("--danceshot");
  839. runDanceShot (args[i + 1].unquoted());
  840. quit();
  841. return;
  842. }
  843. if (args.contains ("--vfxshot"))
  844. {
  845. // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
  846. const auto i = args.indexOf ("--vfxshot");
  847. runVfxShot (args[i + 1].unquoted());
  848. quit();
  849. return;
  850. }
  851. if (args.contains ("--patchershot"))
  852. {
  853. // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
  854. const auto i = args.indexOf ("--patchershot");
  855. runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  856. quit();
  857. return;
  858. }
  859. if (args.contains ("--snapshot"))
  860. {
  861. const auto i = args.indexOf ("--snapshot");
  862. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  863. return;
  864. }
  865. if (args.contains ("--stems"))
  866. {
  867. // LYNX.exe --stems project base.wav: one WAV per insert that has sound (like "Export stems")
  868. const auto i = args.indexOf ("--stems");
  869. juce::String error, report;
  870. int written = 0;
  871. {
  872. lynx::AudioEngine loader (false);
  873. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  874. auto ok = input.hasFileExtension ("flp") ? loader.importFlpFile (input, error) : false;
  875. if (! input.hasFileExtension ("flp"))
  876. if (auto song = lynx::ProjectFile::load (input, error))
  877. {
  878. loader.setSong (std::move (*song));
  879. ok = true;
  880. }
  881. const auto& song = loader.getSong();
  882. for (int t = 1; ok && t < (int) song.mixer.size(); ++t)
  883. {
  884. if (std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  885. continue;
  886. const auto file = base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav");
  887. lynx::ExportSettings settings;
  888. lynx::ExportJob job (lynx::makeBounceSong (song, t), settings, file);
  889. if (job.run ({}, error))
  890. {
  891. ++written;
  892. report << file.getFileName() << " peak=" << job.getPeak() << "\n";
  893. }
  894. }
  895. }
  896. report << "stems=" << written << "\n";
  897. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  898. setApplicationReturnValue (written > 0 ? 0 : 1);
  899. quit();
  900. return;
  901. }
  902. if (args.contains ("--export"))
  903. {
  904. const auto i = args.indexOf ("--export");
  905. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  906. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  907. return;
  908. }
  909. if (args.contains ("--render"))
  910. {
  911. const auto i = args.indexOf ("--render");
  912. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  913. return;
  914. }
  915. // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
  916. uncleanLastStep = collectUncleanSessions();
  917. sessionsFolder().createDirectory();
  918. lynx::crashguard::beginSession (
  919. sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
  920. ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
  921. + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
  922. + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
  923. startHangWatch();
  924. startupTrace.mark ("initialise (normal start)");
  925. if (startupTrace.on)
  926. lynx::startupMark = startupMarkHook;
  927. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  928. lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
  929. startupOptions = lynx::StartupOptions::load();
  930. lynx::registerFileTypes();
  931. startupTrace.mark ("options + file types");
  932. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument.
  933. if (args.size() > 0 && juce::File::isAbsolutePath (args[0].unquoted()))
  934. fileToOpen = juce::File (args[0].unquoted());
  935. // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
  936. // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
  937. // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
  938. if (args.contains ("--opentime"))
  939. {
  940. const auto i = args.indexOf ("--opentime");
  941. const auto project = args[i + 1].unquoted();
  942. fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
  943. openTimeReport = juce::File (args[i + 2].unquoted());
  944. if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
  945. openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
  946. }
  947. if (! startupOptions.splash)
  948. {
  949. startEngine();
  950. createMainWindow();
  951. mainWindow->reveal();
  952. showUncleanNotice();
  953. startupTrace.mark ("window revealed");
  954. openStartupFile();
  955. startupTrace.mark ("startup file opened");
  956. startOpenTimeProbe();
  957. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  958. return;
  959. }
  960. // the splash first, so it is on screen while the audio device opens; the main window is built
  961. // once the pepper has landed (the scene is still for a moment then) and shown when the splash ends
  962. splash = std::make_unique<lynx::SplashScreen>();
  963. startupTrace.mark ("splash made");
  964. splash->showOnDesktop();
  965. startupTrace.mark ("splash on the desktop");
  966. juce::Timer::callAfterDelay (40, [this] {
  967. startEngine();
  968. if (splash == nullptr) // quit meanwhile
  969. return;
  970. splash->setStatus (lynx::tr ("Loading the workspace..."));
  971. splash->startClock();
  972. // the minimum counts from the process start (the audio device took part of it already)
  973. splashDuration = lynx::SplashScreen::remainingDuration (startupTrace.seconds());
  974. splash->setBarDuration (splashDuration);
  975. juce::Timer::callAfterDelay (1050, [this] {
  976. if (splash == nullptr || engine == nullptr)
  977. return;
  978. createMainWindow();
  979. const auto wait = juce::jmax (0.0, splashDuration - splash->getElapsed());
  980. juce::Timer::callAfterDelay ((int) (wait * 1000.0), [this] {
  981. if (splash == nullptr || mainWindow == nullptr)
  982. return;
  983. mainWindow->reveal();
  984. startupTrace.mark ("window revealed (after the splash)");
  985. splash->toFront (false);
  986. splash->finish ([this] { splash = nullptr; });
  987. showUncleanNotice();
  988. openStartupFile();
  989. startupTrace.mark ("startup file opened");
  990. startOpenTimeProbe();
  991. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  992. // first run: language, audio, plugin folders (FL Studio's included) and a background scan
  993. if (! lynx::setupWizardDone() && lynx::platform::testMode())
  994. lynx::platform::testModeLog ("setup wizard");
  995. else if (! lynx::setupWizardDone())
  996. mainWindow->showSetupWizard();
  997. });
  998. });
  999. });
  1000. }
  1001. void startEngine()
  1002. {
  1003. startupTrace.mark ("before the audio engine");
  1004. engine = std::make_unique<lynx::AudioEngine>();
  1005. startupTrace.mark ("audio engine + device");
  1006. crashEngine = engine.get();
  1007. lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
  1008. addDriverFileDeviceType();
  1009. if (startupOptions.sound)
  1010. engine->previewSample (lynx::makeStartupSample());
  1011. startupTrace.mark ("startup sound");
  1012. // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
  1013. // thread, while the splash and the main window come up (round 121)
  1014. if (fileToOpen.hasFileExtension ("flp"))
  1015. if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
  1016. try
  1017. {
  1018. engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  1019. startupTrace.mark ("plugin modules started ahead");
  1020. }
  1021. catch (const flp::Error&)
  1022. {
  1023. }
  1024. }
  1025. void createMainWindow()
  1026. {
  1027. mainWindow = std::make_unique<MainWindow> (getApplicationName(), *engine);
  1028. lynx::setMainWindowForOwnership (mainWindow.get());
  1029. lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
  1030. lynx::startRenderingWatch();
  1031. startupTrace.mark ("main window built");
  1032. }
  1033. // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
  1034. // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
  1035. void showUncleanNotice()
  1036. {
  1037. if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
  1038. {
  1039. if (uncleanLastStep.isNotEmpty())
  1040. lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
  1041. return;
  1042. }
  1043. if (uncleanLastStep.isEmpty())
  1044. {
  1045. lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
  1046. return;
  1047. }
  1048. auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
  1049. "LYNX's autosave folder; details in crash-history.log.",
  1050. { uncleanLastStep });
  1051. uncleanLastStep.clear();
  1052. const auto cause = uncleanCause();
  1053. // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
  1054. // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
  1055. juce::String separatePlugin;
  1056. if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
  1057. separatePlugin = cause.editorPlugin;
  1058. // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
  1059. else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
  1060. {
  1061. lynx::setGpuRenderingEnabled (false);
  1062. message << "\n\n"
  1063. << lynx::tr ("The crash was in the graphics driver ({0}). LYNX now draws its windows without the GPU; you can turn GPU "
  1064. "rendering back on in Options > General settings (after a driver update, for example).",
  1065. { cause.driverModule });
  1066. }
  1067. // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
  1068. // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
  1069. for (int i = uncleanSteps.size(); --i >= 0;)
  1070. {
  1071. if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
  1072. break;
  1073. if (uncleanSteps[i].contains (lynx::visualgl::startNote))
  1074. {
  1075. if (lynx::visualgl::enabled())
  1076. {
  1077. lynx::visualgl::setEnabled (false);
  1078. message << "\n\n"
  1079. << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
  1080. "button turns it back on.");
  1081. }
  1082. break;
  1083. }
  1084. }
  1085. const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
  1086. auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
  1087. const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
  1088. lynx::crashreporter::retryPending();
  1089. if (action == lynx::crashreport::Action::askUser)
  1090. {
  1091. if (separatePlugin.isNotEmpty())
  1092. message << "\n\n"
  1093. << lynx::tr ("It happened while the window of {0} was opening{1}.",
  1094. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
  1095. lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
  1096. devices);
  1097. return;
  1098. }
  1099. if (action == lynx::crashreport::Action::sendSilently)
  1100. {
  1101. const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
  1102. lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
  1103. message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
  1104. }
  1105. if (separatePlugin.isNotEmpty())
  1106. {
  1107. juce::AlertWindow::showOkCancelBox (
  1108. juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX closed unexpectedly"),
  1109. message + "\n\n"
  1110. + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
  1111. "crashes again, only the plugin stops and LYNX keeps running (Plugin wrapper menu: \"Always run in a "
  1112. "separate process\").",
  1113. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
  1114. lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
  1115. juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
  1116. if (result != 0)
  1117. lynx::setPluginAlwaysSeparate (separatePlugin, true);
  1118. }));
  1119. return;
  1120. }
  1121. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX closed unexpectedly"), message);
  1122. }
  1123. // --opentime: after the start-up file was handed to the window
  1124. void startOpenTimeProbe()
  1125. {
  1126. if (openTimeReport == juce::File())
  1127. return;
  1128. struct Probe final : juce::Timer
  1129. {
  1130. LynxApplication& app;
  1131. juce::File report, project;
  1132. int idleSeconds;
  1133. int phase = 0; // 0 loading, 1 settling, 2 idle measurement
  1134. double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
  1135. double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
  1136. Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
  1137. : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
  1138. {
  1139. revealedS = startupTrace.seconds();
  1140. startTimer (250);
  1141. }
  1142. bool loaded() const
  1143. {
  1144. if (project == juce::File())
  1145. return true;
  1146. return app.mainWindow != nullptr
  1147. && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
  1148. }
  1149. void finish (const juce::String& result)
  1150. {
  1151. stopTimer();
  1152. const auto now = startupTrace.seconds();
  1153. const auto cpu = lynx::processCpuSeconds();
  1154. juce::String text;
  1155. text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
  1156. << "window_s=" << juce::String (revealedS, 3) << "\n"
  1157. << "loaded_s=" << juce::String (loadedS, 3) << "\n"
  1158. << "settled_s=" << juce::String (settledS, 3) << "\n"
  1159. << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
  1160. << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
  1161. << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
  1162. << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
  1163. << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
  1164. << "result=" << result << "\n";
  1165. report.replaceWithText (text);
  1166. app.setApplicationReturnValue (result == "OK" ? 0 : 1);
  1167. app.quit();
  1168. }
  1169. void timerCallback() override
  1170. {
  1171. const auto now = startupTrace.seconds();
  1172. const auto cpu = lynx::processCpuSeconds();
  1173. if (phase == 0)
  1174. {
  1175. if (loaded())
  1176. {
  1177. loadedS = now;
  1178. cpuAtLoaded = cpu;
  1179. phase = 1;
  1180. lastCpu = cpu;
  1181. lastT = now;
  1182. }
  1183. else if (now - revealedS > 240.0)
  1184. finish ("TIMEOUT loading");
  1185. return;
  1186. }
  1187. if (phase == 1)
  1188. {
  1189. // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
  1190. const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
  1191. lastCpu = cpu;
  1192. lastT = now;
  1193. if (use < 10.0)
  1194. {
  1195. if (quietSince < 0.0)
  1196. quietSince = now - 0.25;
  1197. if (now - quietSince >= 1.5)
  1198. settledS = quietSince;
  1199. }
  1200. else
  1201. quietSince = -1.0;
  1202. if (settledS >= 0.0 || now - loadedS > 30.0)
  1203. {
  1204. phase = 2;
  1205. idleCpu0 = cpu;
  1206. idleT0 = now;
  1207. }
  1208. return;
  1209. }
  1210. if (now - idleT0 >= (double) idleSeconds)
  1211. finish ("OK");
  1212. }
  1213. };
  1214. perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
  1215. }
  1216. void openStartupFile()
  1217. {
  1218. if (fileToOpen != juce::File() && mainWindow != nullptr)
  1219. mainWindow->openFile (fileToOpen);
  1220. }
  1221. void shutdown() override
  1222. {
  1223. if (relaunched)
  1224. return; // the copy that ran owns the session (its crash notes stay for the next start)
  1225. lynx::crashguard::note ("closing");
  1226. lynx::shutdownPluginSandboxWorker();
  1227. splash = nullptr;
  1228. mainWindow = nullptr; // the UI goes before the engine
  1229. crashEngine = nullptr;
  1230. engine = nullptr;
  1231. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  1232. heartbeat.stopTimer();
  1233. lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
  1234. lynx::crashguard::stopHangWatch();
  1235. lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
  1236. // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
  1237. // teardown runs (some crash in it at exit, round 111)
  1238. if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
  1239. lynx::crashguard::exitNow (getApplicationReturnValue());
  1240. }
  1241. void systemRequestedQuit() override
  1242. {
  1243. if (mainWindow != nullptr)
  1244. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  1245. else
  1246. quit();
  1247. }
  1248. private:
  1249. // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
  1250. // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
  1251. struct Heartbeat final : juce::Timer
  1252. {
  1253. void timerCallback() override { lynx::crashguard::heartbeat(); }
  1254. } heartbeat;
  1255. void startHangWatch()
  1256. {
  1257. const auto folder = lynx::platform::settingsFile ("autosave");
  1258. folder.createDirectory();
  1259. // keep the newest hang files only
  1260. auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
  1261. std::sort (old.begin(), old.end(), [] (const juce::File& a, const juce::File& b) { return a.getLastModificationTime() > b.getLastModificationTime(); });
  1262. for (int i = 20; i < old.size(); ++i)
  1263. old.getReference (i).deleteFile();
  1264. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
  1265. heartbeat.startTimerHz (5);
  1266. }
  1267. bool sandboxChild = false;
  1268. bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
  1269. juce::String uncleanLastStep; // last step of a previous run that ended without closing
  1270. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  1271. // Exit code 0 = audio came out, 1 = silence.
  1272. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  1273. {
  1274. lynx::AudioEngine offline (false);
  1275. const auto peak = offline.renderOffline (2.0, 48000.0);
  1276. const auto audioOk = peak > 0.01f && peak < 10.0f;
  1277. // project format round trip, with accents in the name
  1278. auto original = lynx::Song::makeDefault();
  1279. original.channels[0].name = "Bumbo ação";
  1280. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  1281. original.mode = lynx::PlayMode::song;
  1282. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  1283. original.mixer[3].effects[0].params[1] = 0.25f;
  1284. lynx::Automation automation;
  1285. automation.name = "Pan";
  1286. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  1287. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  1288. original.automations.push_back (automation);
  1289. lynx::Clip automationClip;
  1290. automationClip.kind = lynx::ClipKind::automation;
  1291. automationClip.automation = 0;
  1292. automationClip.track = 4;
  1293. automationClip.length = 3840;
  1294. original.playlist.push_back (automationClip);
  1295. original.loopStart = 960;
  1296. original.loopEnd = 7680;
  1297. original.playlistTracks.resize (3);
  1298. original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
  1299. original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
  1300. original.playlistTracks[1].collapsed = true;
  1301. original.channelGroups = { "Drums", "Keys" };
  1302. original.channels[1].group = 1;
  1303. juce::String error;
  1304. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  1305. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  1306. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  1307. const auto projectOk = reloaded && reloaded->channels.size() == original.channels.size()
  1308. && reloaded->channels[0].name == original.channels[0].name
  1309. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  1310. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  1311. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  1312. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  1313. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  1314. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  1315. && reloaded->automations[0].points[1].tick == 3840
  1316. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  1317. && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
  1318. && reloaded->playlistTracks[1].colour == 0
  1319. && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
  1320. && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
  1321. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  1322. && reloaded->mixer[3].effects.size() == 1
  1323. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  1324. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  1325. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  1326. auto rich = lynx::Song::makeDefault();
  1327. auto& synth = rich.channels[4].synth;
  1328. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  1329. synth.filterType = 2;
  1330. synth.mono = true;
  1331. synth.portaBeats = 0.125f;
  1332. synth.am = true;
  1333. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  1334. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  1335. auto& sampler = rich.channels[0].sampler;
  1336. sampler.cutoff = 1200.0f;
  1337. sampler.resonance = 0.3f;
  1338. sampler.filterType = 1;
  1339. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  1340. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  1341. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  1342. rich.mixer[2].eq.hz[1] = 2200.0f;
  1343. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  1344. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  1345. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  1346. rich.mixer[2].effects.push_back (peqSlot);
  1347. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  1348. utilitySlot.params[1] = 0.2f;
  1349. rich.mixer[2].effects.push_back (utilitySlot);
  1350. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  1351. for (int i = 0; i < 300; ++i)
  1352. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  1353. vocodexSlot.sidechain = 1;
  1354. vocodexSlot.sidechain2 = 2;
  1355. rich.mixer[3].effects.push_back (vocodexSlot);
  1356. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  1357. rich.addMarker ({ 7680, {}, 7, 8 });
  1358. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  1359. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  1360. for (std::size_t i = 0; i < a.size(); ++i)
  1361. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  1362. return false;
  1363. return true;
  1364. };
  1365. const auto richOk = richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  1366. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  1367. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  1368. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  1369. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  1370. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  1371. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  1372. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  1373. && richBack->markers() == rich.markers();
  1374. // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
  1375. bool hwOutOk = false;
  1376. {
  1377. auto song = lynx::Song::makeDefault();
  1378. const auto plain = lynx::ProjectFile::toJson (song);
  1379. song.mixer[0].outputChannel = lynx::outputNone;
  1380. song.mixer[1].outputChannel = 2;
  1381. song.mixer[1].outputMode = lynx::OutputMode::monoRight;
  1382. song.mixer[2].outputChannel = 6;
  1383. song.mixer[3].outputChannel = 4;
  1384. song.mixer[3].outputMode = lynx::OutputMode::monoSum;
  1385. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  1386. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  1387. hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
  1388. && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
  1389. && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
  1390. && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
  1391. && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
  1392. }
  1393. // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
  1394. // original reference byte for byte (.flp record and LYNX plugin state)
  1395. bool substituteOk = false;
  1396. {
  1397. auto song = lynx::Song::makeDefault();
  1398. lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
  1399. vv.format = lynx::ForeignPlugin::Format::vst3;
  1400. const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
  1401. std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
  1402. vv.hasClassId = true;
  1403. vv.name = "ValhallaVintageVerb";
  1404. vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
  1405. for (int i = 0; i < 777; ++i)
  1406. vv.state.push_back ((std::uint8_t) (i * 13 + 1));
  1407. lynx::EffectSlot fromFlp;
  1408. fromFlp.kind = lynx::EffectKind::plugin;
  1409. fromFlp.plugin.foreign = vv;
  1410. lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
  1411. fromLynx.kind = lynx::EffectKind::plugin;
  1412. fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
  1413. fromLynx.plugin.name = "FabFilter Pro-Q 3";
  1414. fromLynx.plugin.state = "AAECAwQFBgcICQ==";
  1415. const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
  1416. song.mixer[1].effects = { fromFlp, fromLynx };
  1417. const auto substitutesOn = lynx::pluginSubstitutesEnabled();
  1418. const auto changed = offline.getPluginHost().applySubstitutes (song);
  1419. auto& fx = song.mixer[1].effects;
  1420. // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
  1421. const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
  1422. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  1423. substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
  1424. && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
  1425. && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
  1426. && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
  1427. && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
  1428. }
  1429. // undo/redo
  1430. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  1431. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  1432. offline.undo();
  1433. const auto afterUndo = offline.getSong().bpm;
  1434. offline.redo();
  1435. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  1436. && offline.isModified();
  1437. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  1438. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  1439. offline.setRecording (true);
  1440. offline.play();
  1441. offline.getTransport().positionTicks.store (960.0);
  1442. offline.sendLiveNote (2, 72, 0.9f, true, true);
  1443. offline.getTransport().positionTicks.store (1920.0);
  1444. offline.sendLiveNote (2, 72, 0.0f, false, true);
  1445. offline.setRecording (false);
  1446. offline.stop();
  1447. const auto& recorded = offline.getSong().patterns[0].notes;
  1448. const auto recordOk = recorded.size() == notesBefore + 1
  1449. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  1450. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  1451. });
  1452. offline.undo();
  1453. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  1454. // MIDI: exporting the pattern and importing it back gives the same notes
  1455. bool midiOk = false;
  1456. {
  1457. auto source = lynx::Song::makeDefault();
  1458. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  1459. source.patterns[0].sortNotes();
  1460. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  1461. juce::String midiError;
  1462. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  1463. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  1464. midiFile.deleteFile();
  1465. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  1466. && std::abs (song->bpm - source.bpm) < 0.01)
  1467. {
  1468. midiOk = true;
  1469. const auto& a = source.patterns[0].notes;
  1470. const auto& b = song->patterns[0].notes;
  1471. for (std::size_t i = 0; i < a.size(); ++i)
  1472. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  1473. }
  1474. }
  1475. // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
  1476. // finds its sample inside the extracted folder
  1477. bool packageOk = false;
  1478. {
  1479. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
  1480. dir.deleteRecursively();
  1481. dir.getChildFile ("src").createDirectory();
  1482. const auto wav = dir.getChildFile ("src/hit.wav");
  1483. {
  1484. juce::WavAudioFormat format;
  1485. juce::AudioBuffer<float> hit (1, 480);
  1486. for (int i = 0; i < 480; ++i)
  1487. hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
  1488. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  1489. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  1490. {
  1491. out.release();
  1492. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  1493. writer->writeFromAudioSampleBuffer (hit, 0, 480);
  1494. }
  1495. }
  1496. auto source = lynx::Song::makeDefault();
  1497. lynx::ChannelDef c;
  1498. c.name = "Hit";
  1499. c.instrument = lynx::InstrumentKind::sampler;
  1500. c.samplePath = wav.getFullPathName().toStdString();
  1501. source.channels.push_back (c);
  1502. lynx::ProjectPackage::Result packed;
  1503. juce::String packageError;
  1504. const auto zip = dir.getChildFile ("Beat.zip");
  1505. if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
  1506. {
  1507. const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
  1508. const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
  1509. if (song && ! song->channels.empty())
  1510. {
  1511. const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
  1512. packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
  1513. }
  1514. }
  1515. dir.deleteRecursively();
  1516. }
  1517. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  1518. juce::String wavpack = "NO_FL";
  1519. {
  1520. const auto roots = lynx::findFlStudioRoots();
  1521. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  1522. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  1523. if (! found.isEmpty())
  1524. {
  1525. lynx::SampleLibrary library;
  1526. const auto sample = library.load (found.getFirst().getFullPathName());
  1527. float peakWv = 0.0f;
  1528. if (sample != nullptr)
  1529. for (std::size_t i = 0; i < sample->frames(); ++i)
  1530. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  1531. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  1532. }
  1533. }
  1534. // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
  1535. const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
  1536. // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
  1537. // generator one plays through the rack
  1538. bool patcherOk = false;
  1539. {
  1540. auto song = lynx::Song::makeDefault();
  1541. song.mixer.resize (4);
  1542. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  1543. lynx::PatchNode reverb, gain;
  1544. reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
  1545. reverb.label = "Room";
  1546. reverb.x = 120.5f;
  1547. reverb.y = 40.0f;
  1548. gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  1549. gain.effect.enabled = false;
  1550. slot.patcher.nodes = { reverb, gain };
  1551. lynx::PatchWire a, b, c, control;
  1552. a.to = 0;
  1553. b.from = 0, b.to = 1, b.gain = 0.5f;
  1554. c.from = 1;
  1555. control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
  1556. slot.patcher.wires = { a, b, c, control };
  1557. slot.patcher.outputTracks = { 3 };
  1558. song.mixer[1].effects = { slot };
  1559. lynx::ChannelDef ch;
  1560. ch.name = "Patched";
  1561. ch.instrument = lynx::InstrumentKind::patcher;
  1562. lynx::PatchNode synth;
  1563. synth.generator = true;
  1564. synth.channel.instrument = lynx::InstrumentKind::synth;
  1565. synth.channel.name = "Synth";
  1566. ch.patcher.nodes = { synth };
  1567. lynx::PatchWire notes, out;
  1568. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  1569. out.from = 0;
  1570. ch.patcher.wires = { notes, out };
  1571. // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
  1572. lynx::PatchNode midiOutNode;
  1573. midiOutNode.generator = true;
  1574. midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
  1575. lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
  1576. ch.patcher.nodes.push_back (midiOutNode);
  1577. lynx::PatchWire portIn, portOut;
  1578. portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
  1579. portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
  1580. portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
  1581. ch.patcher.wires.push_back (portIn);
  1582. ch.patcher.wires.push_back (portOut);
  1583. ch.patcher.fromMidiPorts = { 2, 7 };
  1584. ch.patcher.toMidiPorts = { 9, 11 };
  1585. ch.patcher.fromNotesHidden = true;
  1586. song.channels.push_back (ch);
  1587. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  1588. patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
  1589. && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
  1590. && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
  1591. && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
  1592. && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
  1593. && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
  1594. && back->channels.back().patcher.nodes[0].generator
  1595. && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
  1596. && back->channels.back().patcher.wires == ch.patcher.wires;
  1597. }
  1598. // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
  1599. // the instruments play through the rack
  1600. juce::String nativesResult = "OK";
  1601. int nativesMade = 0, nativesSilent = 0;
  1602. {
  1603. auto song = lynx::Song::makeDefault();
  1604. song.channels.clear();
  1605. song.patterns[0].notes.clear();
  1606. song.mixer.resize (3);
  1607. const auto& fl = lynx::flStudioAccess();
  1608. for (const auto& e : lynx::natives::instrumentEngines())
  1609. if (lynx::natives::available (e, fl))
  1610. if (auto c = lynx::natives::makeChannel (e.kind, fl))
  1611. {
  1612. c->mixerTrack = 1;
  1613. song.channels.push_back (*c);
  1614. }
  1615. for (const auto& e : lynx::natives::effectEngines())
  1616. if (auto fx = lynx::natives::makeSlot (e.kind, fl))
  1617. song.mixer[2].effects.push_back (*fx);
  1618. nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
  1619. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  1620. auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
  1621. && back->mixer[2].effects.size() == song.mixer[2].effects.size();
  1622. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  1623. {
  1624. const auto& a = song.channels[i];
  1625. const auto& b = back->channels[i];
  1626. same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
  1627. && a.modelParams.size() == b.modelParams.size();
  1628. if (! same)
  1629. nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
  1630. }
  1631. for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
  1632. {
  1633. const auto& a = song.mixer[2].effects[i];
  1634. const auto& b = back->mixer[2].effects[i];
  1635. same = a.kind == b.kind && a.state == b.state;
  1636. for (std::size_t p = 0; same && p < a.params.size(); ++p)
  1637. same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
  1638. if (! same)
  1639. nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
  1640. }
  1641. if (! back)
  1642. nativesResult = "ERROR " + error;
  1643. // each instrument plays a note alone (the granulizer needs a sample: it is silent here)
  1644. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  1645. {
  1646. auto one = song;
  1647. one.channels = { song.channels[i] };
  1648. one.channels[0].mixerTrack = 1;
  1649. one.mixer[2].effects.clear();
  1650. one.patterns[0].notes = { { 0, 1920, 0, song.channels[i].instrument == lynx::InstrumentKind::drumaxx ? 48 : 60, 0.8f } };
  1651. lynx::AudioEngine player (false);
  1652. player.setSong (std::move (one));
  1653. player.dispatchPendingMessages();
  1654. if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f) && song.channels[i].instrument != lynx::InstrumentKind::granulizer)
  1655. ++nativesSilent;
  1656. }
  1657. if (nativesSilent > 0 && nativesResult == "OK")
  1658. nativesResult = "SILENT " + juce::String (nativesSilent);
  1659. }
  1660. const auto nativesOk = nativesResult == "OK";
  1661. const auto ok = audioOk && projectOk && richOk && hwOutOk && substituteOk && patcherOk && nativesOk && undoOk && recordOk && recordUndoOk && midiOk && packageOk
  1662. && wavpack != "ERROR" && effectsOk;
  1663. juce::String report;
  1664. report << "connections=" << offline.getNumGraphConnections() << "\n"
  1665. << "peak=" << peak << "\n"
  1666. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  1667. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  1668. << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
  1669. << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
  1670. << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
  1671. << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
  1672. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  1673. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  1674. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  1675. << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
  1676. << "wavpack=" << wavpack << "\n"
  1677. << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
  1678. << "result=" << (ok ? "OK" : "FAILED") << "\n";
  1679. if (reportPath.isNotEmpty())
  1680. juce::File (reportPath).replaceWithText (report);
  1681. setApplicationReturnValue (ok ? 0 : 1);
  1682. quit();
  1683. }
  1684. // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
  1685. // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
  1686. // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
  1687. bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
  1688. {
  1689. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1690. lynx::setNativeEditorDemo (true);
  1691. juce::String report;
  1692. auto allFinite = true;
  1693. {
  1694. lynx::AudioEngine offline (false);
  1695. juce::Random random (111);
  1696. const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
  1697. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  1698. {
  1699. const auto kind = (lynx::EffectKind) k;
  1700. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
  1701. continue;
  1702. const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
  1703. const auto& info = lynx::effectInfo (kind);
  1704. // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
  1705. auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  1706. int dragged = 0; // parameter changes made by the mouse drags
  1707. for (int round = 0; round < rounds; ++round)
  1708. {
  1709. if (round > 0)
  1710. for (std::size_t p = 0; p < info.params.size(); ++p)
  1711. fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
  1712. auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
  1713. song.mixer.resize (2);
  1714. song.mixer[0].name = "Master";
  1715. song.mixer[1].name = "Insert 1";
  1716. song.mixer[1].effects.assign (1, fx);
  1717. for (auto& channel : song.channels)
  1718. channel.mixerTrack = 1;
  1719. offline.setSong (std::move (song));
  1720. offline.dispatchPendingMessages();
  1721. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  1722. for (int page = 0; page < pages; ++page)
  1723. {
  1724. auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  1725. : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  1726. if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
  1727. continue;
  1728. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  1729. const auto paint = [&] {
  1730. juce::Graphics g (image);
  1731. editor->paintEntireComponent (g, false);
  1732. };
  1733. paint();
  1734. // drags from a grid of points, as a user moving every control (plain left button)
  1735. if (round >= 3 && drags)
  1736. {
  1737. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  1738. const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
  1739. for (int y = step / 2; y < editor->getHeight(); y += step)
  1740. for (int x = step / 2; x < editor->getWidth(); x += step)
  1741. {
  1742. auto* target = editor->getComponentAt (x, y);
  1743. if (target == nullptr)
  1744. continue;
  1745. const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
  1746. const auto now = juce::Time::getCurrentTime();
  1747. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
  1748. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
  1749. };
  1750. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  1751. const juce::Component::SafePointer<juce::Component> alive (target);
  1752. target->mouseDown (event (at, down));
  1753. const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
  1754. if (alive != nullptr)
  1755. target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
  1756. if (alive != nullptr)
  1757. target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
  1758. if (alive != nullptr)
  1759. target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
  1760. juce::PopupMenu::dismissAllActiveMenus();
  1761. offline.dispatchPendingMessages();
  1762. }
  1763. paint();
  1764. }
  1765. }
  1766. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  1767. offline.renderOffline (0.05, rate);
  1768. if (round == 0 || round >= 3) // keep what the drags set for the next round
  1769. if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
  1770. {
  1771. const auto& now = offline.getSong().mixer[1].effects[0];
  1772. for (std::size_t p = 0; p < fx.params.size(); ++p)
  1773. dragged += now.params[p] != fx.params[p] ? 1 : 0;
  1774. dragged += now.state != fx.state ? 1 : 0;
  1775. fx = now;
  1776. }
  1777. }
  1778. const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
  1779. allFinite = allFinite && broken == 0;
  1780. report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
  1781. << " (" << dragged << " changes by mouse)\n";
  1782. if (reportPath.isNotEmpty())
  1783. juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
  1784. }
  1785. }
  1786. lynx::setNativeEditorDemo (false);
  1787. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  1788. report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
  1789. if (reportPath.isNotEmpty())
  1790. juce::File (reportPath).replaceWithText (report);
  1791. return allFinite;
  1792. }
  1793. // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
  1794. // native windows are real); one step per timer tick.
  1795. void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
  1796. {
  1797. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1798. struct OpenTest final : juce::Timer
  1799. {
  1800. juce::String reportPath, report;
  1801. bool visible = false, ok = true;
  1802. std::function<void (bool)> done;
  1803. std::unique_ptr<lynx::AudioEngine> engine;
  1804. std::vector<std::pair<juce::String, std::function<void()>>> steps;
  1805. std::size_t next = 0;
  1806. std::atomic<std::int64_t> lastStep { 0 };
  1807. std::atomic<bool> finished { false };
  1808. std::thread watchdog;
  1809. juce::String current;
  1810. std::mutex currentLock;
  1811. int opened = 0, painted = 0;
  1812. // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
  1813. const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
  1814. static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
  1815. void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
  1816. ~OpenTest() override
  1817. {
  1818. finished = true;
  1819. if (watchdog.joinable())
  1820. watchdog.join();
  1821. }
  1822. void start()
  1823. {
  1824. lastStep = now();
  1825. // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
  1826. const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
  1827. folder.deleteRecursively();
  1828. folder.createDirectory();
  1829. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
  1830. watchdog = std::thread ([this] {
  1831. while (! finished)
  1832. {
  1833. std::this_thread::sleep_for (std::chrono::milliseconds (200));
  1834. if (now() - lastStep.load() > timeoutMs)
  1835. {
  1836. juce::String at;
  1837. {
  1838. const std::lock_guard<std::mutex> l (currentLock);
  1839. at = current;
  1840. }
  1841. juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
  1842. lynx::crashguard::exitNow (3);
  1843. }
  1844. }
  1845. });
  1846. startTimer (30);
  1847. }
  1848. // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
  1849. void touchWindows (bool resize, bool large)
  1850. {
  1851. auto& desktop = juce::Desktop::getInstance();
  1852. for (int i = desktop.getNumComponents(); --i >= 0;)
  1853. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
  1854. {
  1855. if (! visible && c->getScreenX() > -3000)
  1856. c->setTopLeftPosition (-6000, -6000);
  1857. if (resize)
  1858. if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
  1859. {
  1860. const auto b = w->getBounds();
  1861. w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
  1862. }
  1863. if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
  1864. {
  1865. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  1866. juce::Graphics g (image);
  1867. c->paintEntireComponent (g, false);
  1868. ++painted;
  1869. // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
  1870. if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
  1871. {
  1872. juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
  1873. if (out.openedOk())
  1874. {
  1875. out.setPosition (0), out.truncate();
  1876. juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  1877. }
  1878. }
  1879. }
  1880. }
  1881. }
  1882. void timerCallback() override
  1883. {
  1884. if (next >= steps.size())
  1885. {
  1886. stopTimer();
  1887. lynx::NativeEffectWindows::closeAll();
  1888. lynx::closeChannelSettings();
  1889. // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
  1890. {
  1891. const auto before = lynx::crashguard::lastHangFile();
  1892. for (const auto until = now() + 7000; now() < until;)
  1893. lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
  1894. for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
  1895. std::this_thread::sleep_for (std::chrono::milliseconds (20));
  1896. lynx::crashguard::stopHangWatch();
  1897. const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
  1898. const auto text = hang.loadFileAsString();
  1899. const auto frames = juce::StringArray::fromLines (text).size() - 2;
  1900. #if JUCE_WINDOWS
  1901. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
  1902. #else
  1903. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
  1904. #endif
  1905. report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
  1906. << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
  1907. ok = ok && hangOk;
  1908. }
  1909. report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
  1910. write();
  1911. finished = true;
  1912. if (done)
  1913. done (ok);
  1914. return;
  1915. }
  1916. auto& [label, fn] = steps[next++];
  1917. {
  1918. const std::lock_guard<std::mutex> l (currentLock);
  1919. current = label;
  1920. }
  1921. fn();
  1922. lastStep = now();
  1923. lynx::crashguard::heartbeat();
  1924. }
  1925. };
  1926. auto* test = new OpenTest();
  1927. test->reportPath = reportPath;
  1928. test->visible = visible;
  1929. test->engine = std::make_unique<lynx::AudioEngine> (false);
  1930. test->done = [test, done] (bool ok) {
  1931. juce::MessageManager::callAsync ([test, done, ok] {
  1932. delete test;
  1933. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  1934. done (ok);
  1935. });
  1936. };
  1937. auto& engine = *test->engine;
  1938. lynx::setNativeEditorDemo (true); // live displays animate without an audio device
  1939. const auto songWith = [] (const lynx::EffectSlot& fx) {
  1940. auto song = lynx::Song::makeDefault();
  1941. song.mixer.resize (2);
  1942. song.mixer[0].name = "Master";
  1943. song.mixer[1].name = "Insert 1";
  1944. song.mixer[1].effects.assign (1, fx);
  1945. for (auto& channel : song.channels)
  1946. channel.mixerTrack = 1;
  1947. return song;
  1948. };
  1949. // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
  1950. // parameters a newer LYNX added after them take their defaults)
  1951. const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
  1952. auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
  1953. if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
  1954. if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
  1955. if (auto* params = (*effects)[0]["params"].getArray())
  1956. params->removeRange ((int) count, params->size());
  1957. juce::String error;
  1958. return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
  1959. };
  1960. auto& steps = test->steps;
  1961. juce::Random random (157);
  1962. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  1963. {
  1964. const auto kind = (lynx::EffectKind) k;
  1965. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  1966. continue;
  1967. const auto& info = lynx::effectInfo (kind);
  1968. const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  1969. const auto n = info.params.size();
  1970. std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
  1971. variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
  1972. for (const auto value : { 0.0f, 1.0f })
  1973. variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
  1974. auto fx = base;
  1975. for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
  1976. return std::optional<lynx::Song> (songWith (fx));
  1977. } });
  1978. const auto seed = random.nextInt64();
  1979. variants.push_back ({ "random", [=] {
  1980. juce::Random r (seed);
  1981. auto fx = base;
  1982. for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
  1983. return std::optional<lynx::Song> (songWith (fx));
  1984. } });
  1985. std::vector<std::size_t> cuts { n / 2 };
  1986. for (const auto c : { (std::size_t) 90, (std::size_t) 114, (std::size_t) 128 }) // (Facet's 90 → 114 params; the 128 → 160 slot)
  1987. if (c < n) cuts.push_back (c);
  1988. for (const auto c : cuts)
  1989. variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
  1990. for (const auto& [variant, makeSong] : variants)
  1991. {
  1992. const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
  1993. steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
  1994. auto song = makeSong();
  1995. if (! song)
  1996. {
  1997. test->report << "FAIL " << label << ": project reader refused the state\n";
  1998. test->ok = false;
  1999. return;
  2000. }
  2001. engine.setSong (std::move (*song));
  2002. engine.dispatchPendingMessages();
  2003. lynx::NativeEffectWindows::open (engine, 1, 0);
  2004. ++test->opened;
  2005. test->touchWindows (false, false);
  2006. } });
  2007. steps.push_back ({ label + ": run", [test, &engine] {
  2008. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  2009. engine.renderOffline (0.03, rate);
  2010. test->touchWindows (false, false);
  2011. } });
  2012. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  2013. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  2014. steps.push_back ({ label + ": close", [test, label] {
  2015. lynx::NativeEffectWindows::closeAll();
  2016. test->report << label << ": OK\n";
  2017. test->write ("(running)\n");
  2018. } });
  2019. }
  2020. }
  2021. // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
  2022. for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
  2023. {
  2024. const auto kind = (lynx::InstrumentKind) k;
  2025. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  2026. continue;
  2027. for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
  2028. {
  2029. if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
  2030. continue;
  2031. const auto label = "instrument " + juce::String (k) + " / " + variant;
  2032. steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
  2033. auto song = lynx::Song::makeDefault();
  2034. auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  2035. lynx::ChannelDef def;
  2036. def.instrument = kind;
  2037. def.name = "Test";
  2038. song.channels.push_back (channel ? *channel : def);
  2039. if (kind == lynx::InstrumentKind::soundfont && variant != "default")
  2040. {
  2041. // a real font when FL's is there; NaN / huge / truncated settings
  2042. const auto& roots = lynx::flStudioAccess().roots;
  2043. if (! roots.data.empty())
  2044. song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  2045. .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
  2046. .getFullPathName().toStdString();
  2047. if (variant == "odd settings")
  2048. song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
  2049. }
  2050. if (old)
  2051. {
  2052. juce::String error;
  2053. if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
  2054. song = std::move (*again);
  2055. }
  2056. const auto index = (int) song.channels.size() - 1;
  2057. engine.setSong (std::move (song));
  2058. engine.dispatchPendingMessages();
  2059. lynx::openChannelSettings (engine, index);
  2060. ++test->opened;
  2061. test->touchWindows (false, false);
  2062. } });
  2063. steps.push_back ({ label + ": run", [test, &engine] {
  2064. engine.renderOffline (0.03, 48000.0);
  2065. test->touchWindows (false, false);
  2066. } });
  2067. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  2068. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  2069. steps.push_back ({ label + ": close", [test, label] {
  2070. lynx::closeChannelSettings();
  2071. test->report << label << ": OK\n";
  2072. test->write ("(running)\n");
  2073. } });
  2074. }
  2075. }
  2076. test->start();
  2077. }
  2078. void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
  2079. {
  2080. struct Test final : juce::Timer
  2081. {
  2082. juce::String reportPath, report;
  2083. std::unique_ptr<lynx::AudioEngine> engine;
  2084. bool instrument = false;
  2085. int phase = 0, ticks = 0, seconds = 15;
  2086. juce::AudioPluginInstance* instance = nullptr;
  2087. juce::AudioProcessorParameter* checked = nullptr;
  2088. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  2089. std::function<void (bool)> done;
  2090. void step (const juce::String& line)
  2091. {
  2092. report << line << "\n";
  2093. juce::File (reportPath).replaceWithText (report);
  2094. }
  2095. juce::AudioPluginInstance* find()
  2096. {
  2097. if (instrument)
  2098. {
  2099. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (0).get()))
  2100. return &p->getInstance();
  2101. }
  2102. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  2103. return &p->getInstance();
  2104. return nullptr;
  2105. }
  2106. void timerCallback() override
  2107. {
  2108. ++ticks;
  2109. if (phase == 0) // waiting for the engine to host the plugin
  2110. {
  2111. instance = find();
  2112. if (instance == nullptr)
  2113. {
  2114. if (ticks > 200)
  2115. {
  2116. step ("result=FAILED (not hosted)");
  2117. stopTimer();
  2118. done (false);
  2119. }
  2120. return;
  2121. }
  2122. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  2123. step ("programs=" + juce::String (instance->getNumPrograms()));
  2124. for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
  2125. step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
  2126. step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
  2127. // preset round trip: save, change the first parameter, load, compare
  2128. juce::AudioProcessorParameter* param = nullptr;
  2129. for (auto* candidate : instance->getParameters())
  2130. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  2131. {
  2132. param = candidate;
  2133. break;
  2134. }
  2135. if (param != nullptr)
  2136. {
  2137. step ("param=" + param->getName (64));
  2138. checked = param;
  2139. const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
  2140. juce::String error;
  2141. const auto before = param->getValue();
  2142. const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
  2143. param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
  2144. const auto changed = param->getValue();
  2145. const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
  2146. step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
  2147. + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
  2148. + (error.isNotEmpty() ? " error=" + error : juce::String()));
  2149. for (const auto* ext : { "fxp", "fxb", "vstpreset" })
  2150. {
  2151. juce::String e2;
  2152. const auto f2 = file.withFileExtension (ext);
  2153. const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
  2154. step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
  2155. f2.deleteFile();
  2156. }
  2157. step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
  2158. }
  2159. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (0))
  2160. : std::shared_ptr<void> (engine->getEffect (1, 0));
  2161. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  2162. { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  2163. if (instrument)
  2164. return song.channels.empty() ? nullptr : &song.channels[0].plugin;
  2165. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  2166. }, instrument });
  2167. owner.reset();
  2168. step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  2169. phase = 1;
  2170. ticks = 0;
  2171. return;
  2172. }
  2173. if (phase == 1 && ticks == 20 && checked != nullptr)
  2174. step ("param_after_1s=" + juce::String (checked->getValue(), 4));
  2175. if (phase == 1 && ticks >= seconds * 20) // remove the plugin from the song
  2176. {
  2177. engine->editSong ([this] (lynx::Song& song) {
  2178. if (instrument)
  2179. song.channels.clear();
  2180. else
  2181. song.mixer[1].effects.clear();
  2182. });
  2183. step ("removed");
  2184. phase = 2;
  2185. ticks = 0;
  2186. return;
  2187. }
  2188. if (phase == 2 && ticks >= 40)
  2189. {
  2190. const auto open = lynx::PluginWindows::isOpen (*instance);
  2191. step ("window_open_after_remove=" + juce::String ((int) open));
  2192. step (open ? "result=FAILED" : "result=OK");
  2193. stopTimer();
  2194. lynx::PluginWindows::closeAll();
  2195. done (! open);
  2196. }
  2197. }
  2198. };
  2199. auto* test = new Test();
  2200. test->reportPath = reportPath;
  2201. test->seconds = seconds;
  2202. test->done = [this, test] (bool ok) {
  2203. setApplicationReturnValue (ok ? 0 : 1);
  2204. juce::MessageManager::callAsync ([this, test] {
  2205. lynx::setMainWindowForOwnership (nullptr);
  2206. test->mainWindow = nullptr;
  2207. test->engine = nullptr;
  2208. delete test;
  2209. quit();
  2210. });
  2211. };
  2212. test->engine = std::make_unique<lynx::AudioEngine> (false);
  2213. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  2214. test->mainWindow->setBounds (20, 20, 300, 200);
  2215. test->mainWindow->setVisible (true);
  2216. lynx::setMainWindowForOwnership (test->mainWindow.get());
  2217. auto& host = test->engine->getPluginHost();
  2218. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  2219. std::optional<juce::PluginDescription> chosen;
  2220. for (const auto& type : host.getKnownPlugins().getTypes())
  2221. if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  2222. && (only.isEmpty() || type.name == only))
  2223. {
  2224. chosen = type;
  2225. break;
  2226. }
  2227. if (! chosen)
  2228. {
  2229. test->step ("result=FAILED (no plugin)");
  2230. test->done (false);
  2231. return;
  2232. }
  2233. test->instrument = chosen->isInstrument;
  2234. lynx::PluginRef ref;
  2235. ref.id = chosen->createIdentifierString().toStdString();
  2236. ref.name = chosen->name.toStdString();
  2237. test->engine->editSong ([&] (lynx::Song& song) {
  2238. if (test->instrument)
  2239. {
  2240. lynx::ChannelDef c;
  2241. c.name = ref.name;
  2242. c.instrument = lynx::InstrumentKind::plugin;
  2243. c.plugin = ref;
  2244. song.channels.push_back (c);
  2245. }
  2246. else
  2247. {
  2248. while (song.mixer.size() < 2)
  2249. song.mixer.emplace_back();
  2250. lynx::EffectSlot slot;
  2251. slot.kind = lynx::EffectKind::plugin;
  2252. slot.plugin = ref;
  2253. song.mixer[1].effects.push_back (slot);
  2254. }
  2255. });
  2256. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  2257. test->startTimerHz (20);
  2258. }
  2259. void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
  2260. {
  2261. struct EditorTest final : juce::Timer
  2262. {
  2263. juce::String reportPath, report;
  2264. std::unique_ptr<lynx::PluginHost> host;
  2265. std::unique_ptr<juce::AudioPluginInstance> plugin;
  2266. std::unique_ptr<juce::DocumentWindow> window;
  2267. std::function<void (bool)> done;
  2268. void step (const juce::String& line)
  2269. {
  2270. report << line << "\n";
  2271. juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
  2272. }
  2273. void timerCallback() override
  2274. {
  2275. stopTimer();
  2276. window = nullptr;
  2277. step ("step=closed");
  2278. plugin = nullptr;
  2279. step ("result=OK");
  2280. done (true);
  2281. }
  2282. };
  2283. auto* test = new EditorTest();
  2284. test->reportPath = reportPath;
  2285. test->done = [this, test] (bool ok)
  2286. {
  2287. setApplicationReturnValue (ok ? 0 : 1);
  2288. juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
  2289. };
  2290. test->host = std::make_unique<lynx::PluginHost> (false);
  2291. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  2292. test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
  2293. for (const auto& type : test->host->getKnownPlugins().getTypes())
  2294. {
  2295. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  2296. || (only.isNotEmpty() && type.name != only))
  2297. continue;
  2298. juce::String error;
  2299. test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
  2300. test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
  2301. break;
  2302. }
  2303. if (test->plugin == nullptr)
  2304. {
  2305. test->step ("result=FAILED");
  2306. test->done (false);
  2307. return;
  2308. }
  2309. lynx::preparePlugin (*test->plugin, 48000.0, 512);
  2310. test->step ("step=create_editor");
  2311. test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
  2312. test->window->setUsingNativeTitleBar (true);
  2313. if (auto* editor = test->plugin->createEditorIfNeeded())
  2314. test->window->setContentOwned (editor, true);
  2315. else
  2316. test->step ("no_editor");
  2317. test->step ("step=show");
  2318. test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
  2319. test->window->setVisible (true);
  2320. test->step ("step=shown");
  2321. test->startTimer (4000);
  2322. }
  2323. void runFitTest (const juce::String& reportPath, int percent)
  2324. {
  2325. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2326. struct FitTest final : juce::Timer
  2327. {
  2328. juce::String path, report;
  2329. bool ok = true;
  2330. int step = 0, percent = 150;
  2331. std::unique_ptr<juce::DocumentWindow> tall, big;
  2332. std::function<void()> done;
  2333. // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
  2334. void check (const juce::String& what, juce::Component& w, bool whole)
  2335. {
  2336. juce::BorderSize<int> frame;
  2337. if (auto* peer = w.getPeer())
  2338. if (const auto f = peer->getFrameSizeIfPresent())
  2339. frame = *f;
  2340. auto outer = frame.addedTo (w.getBounds());
  2341. const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
  2342. const auto area = display != nullptr ? display->userArea : outer;
  2343. #if JUCE_LINUX
  2344. // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
  2345. // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
  2346. const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
  2347. outer = outer.reduced (shadow);
  2348. const auto slack = shadow > 0 ? 4 : 0;
  2349. #else
  2350. const auto slack = 0;
  2351. #endif
  2352. const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
  2353. && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
  2354. report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
  2355. << frame.getLeft() << ") screen=" << area.toString() << "\n";
  2356. ok = ok && passed;
  2357. }
  2358. void start()
  2359. {
  2360. report << "scale=" << percent << "%\n";
  2361. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  2362. // a tool window taller than the screen, centred (its title bar would be above the screen)
  2363. tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
  2364. tall->setUsingNativeTitleBar (true);
  2365. auto* content = new juce::Component();
  2366. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  2367. content->setSize (500, area.getHeight() + 200);
  2368. tall->setContentOwned (content, true);
  2369. tall->setCentrePosition (area.getCentre());
  2370. tall->setVisible (true);
  2371. lynx::keepAboveMainWindow (*tall);
  2372. // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
  2373. startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
  2374. }
  2375. void timerCallback() override
  2376. {
  2377. ++step;
  2378. if (step == 1)
  2379. {
  2380. check ("tall tool window: title bar and close button on the screen", *tall, false);
  2381. tall.reset();
  2382. // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
  2383. auto content = std::make_unique<juce::Component>();
  2384. const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  2385. content->setSize (520, screen.getHeight() + 300);
  2386. lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
  2387. return;
  2388. }
  2389. if (step == 2)
  2390. {
  2391. if (auto* w = lynx::findToolWindow ("fittest-fixed"))
  2392. {
  2393. check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
  2394. const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
  2395. && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
  2396. report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
  2397. ok = ok && scrolls;
  2398. }
  2399. else
  2400. {
  2401. report << "FAIL fixed-size tool window not found\n";
  2402. ok = false;
  2403. }
  2404. lynx::closeAllToolWindows();
  2405. // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
  2406. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  2407. big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
  2408. big->setUsingNativeTitleBar (true);
  2409. big->setResizable (true, false);
  2410. big->setResizeLimits (400, 300, 10000, 10000);
  2411. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  2412. big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
  2413. big->setVisible (true);
  2414. return;
  2415. }
  2416. if (step == 3)
  2417. {
  2418. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  2419. juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
  2420. return;
  2421. }
  2422. if (step == 4)
  2423. {
  2424. check ("resizable window after the zoom change: fits the screen", *big, true);
  2425. big.reset();
  2426. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  2427. juce::File (path).replaceWithText (report);
  2428. stopTimer();
  2429. if (done)
  2430. done();
  2431. }
  2432. }
  2433. };
  2434. static std::unique_ptr<FitTest> test;
  2435. test = std::make_unique<FitTest>();
  2436. test->path = reportPath;
  2437. test->percent = juce::jlimit (50, 300, percent);
  2438. test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
  2439. test->start();
  2440. }
  2441. void runWindowTest (const juce::String& reportPath)
  2442. {
  2443. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2444. struct WindowTest final : juce::Timer
  2445. {
  2446. juce::String reportPath, report;
  2447. bool ok = true;
  2448. int stepIndex = 0;
  2449. std::unique_ptr<lynx::AudioEngine> engine;
  2450. lynx::MainComponent* ui = nullptr;
  2451. std::unique_ptr<juce::DocumentWindow> main, pluginLike;
  2452. juce::TextEditor* pluginField = nullptr;
  2453. std::function<void()> done;
  2454. void line (const juce::String& text)
  2455. {
  2456. report << text << "\n";
  2457. juce::File (reportPath).replaceWithText (report);
  2458. }
  2459. void check (const juce::String& what, bool passed)
  2460. {
  2461. line ((passed ? "ok " : "FAIL ") + what);
  2462. ok = ok && passed;
  2463. }
  2464. bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
  2465. bool focusIn (juce::Component* w)
  2466. {
  2467. auto* f = juce::Component::getCurrentlyFocusedComponent();
  2468. return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
  2469. }
  2470. void timerCallback() override
  2471. {
  2472. switch (stepIndex++)
  2473. {
  2474. case 0:
  2475. line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
  2476. ui->openQuickAddForTest();
  2477. break;
  2478. case 1:
  2479. {
  2480. auto* w = lynx::findToolWindow ("quickadd");
  2481. check ("quick-add palette open", w != nullptr);
  2482. check ("quick-add palette active", w != nullptr && w->isActiveWindow());
  2483. check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  2484. check ("quick-add palette above the main window", isAbove (w));
  2485. auto* f = juce::Component::getCurrentlyFocusedComponent();
  2486. check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
  2487. lynx::closeAllToolWindows();
  2488. lynx::openAudioEditor (*engine);
  2489. break;
  2490. }
  2491. case 2:
  2492. {
  2493. auto* w = lynx::findToolWindow ("audioeditor");
  2494. check ("audio editor open", w != nullptr);
  2495. check ("audio editor active", w != nullptr && w->isActiveWindow());
  2496. check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  2497. check ("audio editor above the main window", isAbove (w));
  2498. lynx::forceForegroundForTest (*main); // the user clicks the main window
  2499. break;
  2500. }
  2501. case 3:
  2502. {
  2503. auto* w = lynx::findToolWindow ("audioeditor");
  2504. check ("audio editor stays above the main window after clicking it", isAbove (w));
  2505. lynx::closeAllToolWindows();
  2506. // a plugin editor's window: its own controls keep the keyboard focus
  2507. pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
  2508. pluginLike->setUsingNativeTitleBar (true);
  2509. auto* field = new juce::TextEditor();
  2510. field->setSize (300, 120);
  2511. pluginLike->setContentOwned (field, true);
  2512. pluginLike->centreWithSize (300, 120);
  2513. pluginLike->setVisible (true);
  2514. lynx::keepAboveMainWindow (*pluginLike);
  2515. pluginLike->toFront (true);
  2516. field->grabKeyboardFocus();
  2517. pluginField = field;
  2518. break;
  2519. }
  2520. case 4:
  2521. check ("plugin window active", pluginLike->isActiveWindow());
  2522. check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
  2523. check ("plugin window above the main window", isAbove (pluginLike.get()));
  2524. pluginLike = nullptr;
  2525. lynx::forceForegroundForTest (*main);
  2526. juce::Component::unfocusAllComponents();
  2527. break;
  2528. case 5:
  2529. check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
  2530. line (ok ? "result=OK" : "result=FAILED");
  2531. stopTimer();
  2532. done();
  2533. break;
  2534. default:
  2535. break;
  2536. }
  2537. }
  2538. };
  2539. auto* test = new WindowTest();
  2540. test->reportPath = reportPath;
  2541. test->engine = std::make_unique<lynx::AudioEngine> (false);
  2542. test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
  2543. test->main->setUsingNativeTitleBar (true);
  2544. test->ui = new lynx::MainComponent (*test->engine, false);
  2545. test->main->setContentOwned (test->ui, true);
  2546. test->main->setResizable (true, true);
  2547. test->main->centreWithSize (1280, 760);
  2548. test->main->setVisible (true);
  2549. lynx::setMainWindowForOwnership (test->main.get());
  2550. lynx::forceForegroundForTest (*test->main);
  2551. test->main->toFront (true);
  2552. test->done = [this, test] {
  2553. setApplicationReturnValue (test->ok ? 0 : 1);
  2554. juce::MessageManager::callAsync ([this, test] {
  2555. lynx::closeAllToolWindows();
  2556. lynx::setMainWindowForOwnership (nullptr);
  2557. test->main = nullptr;
  2558. delete test;
  2559. quit();
  2560. });
  2561. };
  2562. test->startTimer (1500);
  2563. }
  2564. // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
  2565. // instrument (and runs audio through it if it is an effect) and measures the audio.
  2566. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
  2567. {
  2568. juce::String report;
  2569. bool ok = false;
  2570. {
  2571. lynx::AudioEngine offline (false);
  2572. auto& host = offline.getPluginHost();
  2573. const auto added = host.addPluginFile (juce::File (pluginPath));
  2574. report << "plugins_in_file=" << added << "\n";
  2575. juce::PluginDescription instrument, effect;
  2576. bool hasInstrument = false, hasEffect = false;
  2577. for (const auto& type : host.getKnownPlugins().getTypes())
  2578. {
  2579. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  2580. || (only.isNotEmpty() && type.name != only))
  2581. continue;
  2582. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  2583. << ") in " << type.fileOrIdentifier << "\n";
  2584. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  2585. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  2586. }
  2587. auto song = lynx::Song::makeDefault();
  2588. if (hasInstrument)
  2589. {
  2590. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  2591. c.instrument = lynx::InstrumentKind::plugin;
  2592. c.plugin.id = instrument.createIdentifierString().toStdString();
  2593. c.plugin.name = instrument.name.toStdString();
  2594. c.volume = 1.0f;
  2595. for (int i = 0; i < 4; ++i) // one chord per beat
  2596. for (int key : { 60, 64, 67 })
  2597. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  2598. song.patterns[0].sortNotes();
  2599. }
  2600. if (hasEffect)
  2601. {
  2602. lynx::EffectSlot slot;
  2603. slot.kind = lynx::EffectKind::plugin;
  2604. slot.plugin.id = effect.createIdentifierString().toStdString();
  2605. slot.plugin.name = effect.name.toStdString();
  2606. song.mixer[0].effects.push_back (slot);
  2607. }
  2608. const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
  2609. offline.setSong (song);
  2610. // after a render: the rack (and its plugins) is built when the engine is prepared
  2611. const auto peak = offline.renderOffline (3.0, 48000.0);
  2612. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  2613. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
  2614. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  2615. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  2616. if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
  2617. report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
  2618. report << "peak=" << peak << "\n";
  2619. // plugins that crashed inside a call, were caught and switched off (round 111)
  2620. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  2621. for (const auto& c : lynx::pluginCrashes())
  2622. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  2623. offline.capturePluginStates();
  2624. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  2625. report << "state_bytes_base64=" << (int) stateSize << "\n";
  2626. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  2627. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  2628. }
  2629. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  2630. juce::File (reportPath).replaceWithText (report);
  2631. setApplicationReturnValue (ok ? 0 : 1);
  2632. quit();
  2633. }
  2634. // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
  2635. // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
  2636. // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
  2637. void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
  2638. {
  2639. juce::String report;
  2640. bool ok = false;
  2641. {
  2642. lynx::AudioEngine offline (false);
  2643. auto& host = offline.getPluginHost();
  2644. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  2645. std::optional<juce::PluginDescription> vst2;
  2646. for (const auto& type : host.getKnownPlugins().getTypes())
  2647. if (type.pluginFormatName == "VST")
  2648. vst2 = type;
  2649. auto render = [&] (float gain, float& tempoSeen, int& adopted) {
  2650. lynx::FlVst2State state;
  2651. state.flags = 8;
  2652. state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
  2653. std::memcpy (state.chunk.data() + 4, &gain, 4);
  2654. auto song = lynx::Song::makeDefault();
  2655. song.bpm = 137.0;
  2656. auto& f = song.channels[4].plugin.foreign;
  2657. f.format = lynx::ForeignPlugin::Format::vst2;
  2658. f.vst2Id = (std::uint32_t) vst2->uniqueId;
  2659. f.name = "Some other name"; // found by the VST2 ID
  2660. f.state = lynx::writeFlVst2State (state);
  2661. song.channels[4].volume = 1.0f;
  2662. song.patterns[0].notes.clear();
  2663. song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
  2664. for (std::size_t c = 0; c < song.channels.size(); ++c)
  2665. if (c != 4)
  2666. song.channels[c].muted = true;
  2667. adopted = host.adoptFlPlugins (song);
  2668. offline.setSong (song);
  2669. const auto peak = offline.renderOffline (1.0, 48000.0);
  2670. offline.capturePluginStates();
  2671. juce::MemoryBlock saved;
  2672. saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
  2673. lynx::FlVst2State back;
  2674. tempoSeen = 0.0f;
  2675. if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
  2676. && back.chunk.size() >= 12)
  2677. std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
  2678. return peak;
  2679. };
  2680. if (vst2)
  2681. {
  2682. report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
  2683. float tempoA = 0, tempoB = 0;
  2684. int adoptedA = 0, adoptedB = 0;
  2685. const auto quiet = render (0.1f, tempoA, adoptedA);
  2686. const auto loud = render (0.4f, tempoB, adoptedB);
  2687. report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
  2688. << " tempo_seen=" << tempoB * 1000.0f << "\n";
  2689. ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
  2690. && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
  2691. }
  2692. }
  2693. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  2694. juce::File (reportPath).replaceWithText (report);
  2695. setApplicationReturnValue (ok ? 0 : 1);
  2696. quit();
  2697. }
  2698. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  2699. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  2700. // that the plugin comes back with the changed parameter.
  2701. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  2702. {
  2703. juce::String report;
  2704. bool ok = false;
  2705. {
  2706. lynx::AudioEngine offline (false);
  2707. auto& host = offline.getPluginHost();
  2708. host.addPluginFile (juce::File (pluginPath));
  2709. const juce::PluginDescription* vst3 = nullptr;
  2710. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  2711. for (const auto& type : types)
  2712. if (type.pluginFormatName == "VST3" && type.isInstrument)
  2713. vst3 = &type;
  2714. if (vst3 != nullptr)
  2715. {
  2716. juce::String error;
  2717. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  2718. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  2719. if (parameter != nullptr)
  2720. {
  2721. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  2722. parameter->setValueNotifyingHost (target);
  2723. juce::MemoryBlock juceState;
  2724. plugin->getStateInformation (juceState);
  2725. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  2726. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  2727. std::vector<std::uint8_t> flState;
  2728. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  2729. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  2730. put32 (id);
  2731. put32 ((std::uint32_t) data.getSize());
  2732. put32 (0);
  2733. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  2734. };
  2735. put32 (1);
  2736. record (1, juce::MemoryBlock (64, true));
  2737. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  2738. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  2739. juce::MemoryBlock slots;
  2740. const auto paramId = [&] (int i) {
  2741. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  2742. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  2743. };
  2744. const bool reorder = plugin->getParameters().size() >= 3;
  2745. if (reorder)
  2746. {
  2747. for (auto v : { 2u, paramId (2), paramId (0) })
  2748. slots.append (&v, 4);
  2749. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  2750. }
  2751. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  2752. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  2753. if (auto* child = xml->getChildByName (tag))
  2754. {
  2755. juce::MemoryBlock data;
  2756. data.fromBase64Encoding (child->getAllSubText());
  2757. record (id, data);
  2758. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  2759. }
  2760. if (reorder)
  2761. record (4, slots);
  2762. plugin.reset();
  2763. auto song = lynx::Song::makeDefault();
  2764. auto& f = song.channels[4].plugin.foreign;
  2765. f.format = lynx::ForeignPlugin::Format::vst3;
  2766. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  2767. f.state = flState;
  2768. {
  2769. std::vector<std::uint8_t> comp, ctrl;
  2770. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  2771. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  2772. }
  2773. for (int k = 0; k < 3; ++k)
  2774. {
  2775. lynx::Automation a;
  2776. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  2777. song.automations.push_back (a);
  2778. }
  2779. const auto adopted = host.adoptFlPlugins (song);
  2780. report << "adopted=" << adopted << "\n";
  2781. juce::String mapped;
  2782. for (const auto& a : song.automations)
  2783. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  2784. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  2785. report << "slot_positions=" << mapped << "\n";
  2786. const auto slotsOk = ! reorder || mapped == "2,0,1";
  2787. offline.setSong (song);
  2788. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  2789. {
  2790. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  2791. report << "restored_value=" << value << "\n";
  2792. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  2793. }
  2794. }
  2795. }
  2796. }
  2797. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  2798. juce::File (reportPath).replaceWithText (report);
  2799. setApplicationReturnValue (ok ? 0 : 1);
  2800. quit();
  2801. }
  2802. void runShowcase (const juce::String& outputPath, int currentPattern)
  2803. {
  2804. using namespace lynx;
  2805. Song song;
  2806. song.bpm = 124.0;
  2807. song.mixer = Song::defaultMixer();
  2808. const auto presets = synthPresets();
  2809. auto preset = [&] (const char* name) {
  2810. for (const auto& [n, sset] : presets)
  2811. if (n == name)
  2812. return sset;
  2813. return SynthSettings {};
  2814. };
  2815. auto channel = [&] (const char* name, InstrumentKind kind, float volume, int track, std::uint32_t colour) {
  2816. ChannelDef c;
  2817. c.name = name;
  2818. c.instrument = kind;
  2819. c.volume = volume;
  2820. c.mixerTrack = track;
  2821. c.colour = colour;
  2822. song.channels.push_back (c);
  2823. return (int) song.channels.size() - 1;
  2824. };
  2825. const auto kick = channel ("Kick", InstrumentKind::kick, 0.9f, 1, 0xffd9534f);
  2826. const auto clap = channel ("Clap", InstrumentKind::clap, 0.75f, 2, 0xfff0ad4e);
  2827. const auto hat = channel ("Hat", InstrumentKind::hat, 0.6f, 3, 0xfff7d774);
  2828. const auto snare = channel ("Snare", InstrumentKind::snare, 0.7f, 4, 0xffe8835a);
  2829. const auto bass = channel ("Reese Bass", InstrumentKind::synth, 0.8f, 5, 0xff5bc0de);
  2830. song.channels[(std::size_t) bass].synth = preset ("Reese Bass"); // preset name as defined in core/SynthPresets
  2831. const auto pad = channel ("Pad", InstrumentKind::synth, 0.7f, 6, 0xff9b7fd6);
  2832. song.channels[(std::size_t) pad].synth = preset ("Pad");
  2833. const auto pluck = channel ("Pluck", InstrumentKind::synth, 0.72f, 7, 0xff5cb85c);
  2834. song.channels[(std::size_t) pluck].synth = preset ("Pluck");
  2835. const auto lead = channel ("Supersaw", InstrumentKind::synth, 0.6f, 8, 0xff4fc3a1);
  2836. song.channels[(std::size_t) lead].synth = preset ("Supersaw");
  2837. auto addPattern = [&] (const char* name, std::uint32_t colour) {
  2838. auto& p = song.patterns.emplace_back();
  2839. p.name = name;
  2840. p.colour = colour;
  2841. return (int) song.patterns.size() - 1;
  2842. };
  2843. auto note = [&] (int pattern, int ch, double beat, double beats, int key, float velocity = 0.8f) {
  2844. Note n;
  2845. n.channel = ch;
  2846. n.start = (std::int64_t) (beat * ppq);
  2847. n.length = (std::int64_t) (beats * ppq);
  2848. n.key = key;
  2849. n.velocity = velocity;
  2850. song.patterns[(std::size_t) pattern].notes.push_back (n);
  2851. };
  2852. const auto beat = addPattern ("Beat", 0xffd9534f);
  2853. for (int s = 0; s < 16; s += 4)
  2854. song.patterns[(std::size_t) beat].toggleStep (kick, s);
  2855. for (int s : { 4, 12 })
  2856. song.patterns[(std::size_t) beat].toggleStep (clap, s);
  2857. for (int s = 2; s < 16; s += 4)
  2858. song.patterns[(std::size_t) beat].toggleStep (hat, s);
  2859. for (int s : { 7, 15 })
  2860. song.patterns[(std::size_t) beat].toggleStep (snare, s);
  2861. const auto groove = addPattern ("Groove", 0xfff0ad4e);
  2862. for (int s = 0; s < 16; ++s)
  2863. song.patterns[(std::size_t) groove].toggleStep (hat, s);
  2864. for (int s : { 4, 12 })
  2865. song.patterns[(std::size_t) groove].toggleStep (clap, s);
  2866. // Am – F – C – G, one bar each
  2867. const int roots[4] = { 45, 41, 48, 43 };
  2868. const int chords[4][3] = { { 57, 60, 64 }, { 53, 57, 60 }, { 55, 60, 64 }, { 55, 59, 62 } };
  2869. const auto bassline = addPattern ("Bass", 0xff5bc0de);
  2870. for (int bar = 0; bar < 4; ++bar)
  2871. for (int e = 0; e < 8; ++e)
  2872. if (e != 3)
  2873. note (bassline, bass, bar * 4 + e * 0.5, 0.4, roots[bar] - 12 + (e == 6 ? 12 : 0), e % 2 == 0 ? 0.9f : 0.65f);
  2874. const auto chordsPattern = addPattern ("Chords", 0xff9b7fd6);
  2875. for (int bar = 0; bar < 4; ++bar)
  2876. for (int k = 0; k < 3; ++k)
  2877. note (chordsPattern, pad, bar * 4, 3.9, chords[bar][k], 0.7f);
  2878. const auto melody = addPattern ("Melody", 0xff5cb85c);
  2879. const int line[] = { 69, 72, 76, 74, 72, 69, 67, 69, 65, 69, 72, 74, 72, 69, 67, 64,
  2880. 72, 76, 79, 76, 74, 72, 74, 76, 71, 74, 79, 78, 76, 74, 71, 67 };
  2881. for (int k = 0; k < 32; ++k)
  2882. if (k % 8 != 7)
  2883. note (melody, pluck, k * 0.5, k % 4 == 3 ? 0.9 : 0.4, line[k], k % 2 == 0 ? 0.85f : 0.65f);
  2884. const auto hook = addPattern ("Hook", 0xff4fc3a1);
  2885. for (int bar = 0; bar < 4; ++bar)
  2886. for (int k = 0; k < 3; ++k)
  2887. note (hook, lead, bar * 4 + k * 1.5, k == 2 ? 1.0 : 1.4, chords[bar][2] + 12 - k * 3, 0.8f);
  2888. // Playlist: intro, verse, drop, breakdown, final drop
  2889. song.playlistTracks = { { "Drums" }, { "Groove" }, { "Bass" }, { "Chords" }, { "Melody" }, { "Hook" }, { "Automation" } };
  2890. const auto bar = (std::int64_t) ppq * 4;
  2891. auto clip = [&] (int pattern, int track, int fromBar, int bars) {
  2892. const auto length = song.patterns[(std::size_t) pattern].effectiveLength (song.beatsPerBar);
  2893. for (int b = fromBar; b < fromBar + bars;)
  2894. {
  2895. Clip c;
  2896. c.pattern = pattern;
  2897. c.track = track;
  2898. c.start = b * bar;
  2899. c.length = length;
  2900. song.playlist.push_back (c);
  2901. b += (int) std::max<std::int64_t> (1, length / bar);
  2902. }
  2903. };
  2904. clip (chordsPattern, 3, 0, 8);
  2905. clip (melody, 4, 4, 4);
  2906. clip (beat, 0, 8, 16);
  2907. clip (groove, 1, 12, 12);
  2908. clip (bassline, 2, 8, 8);
  2909. clip (melody, 4, 8, 8);
  2910. clip (chordsPattern, 3, 16, 4);
  2911. clip (bassline, 2, 20, 4);
  2912. clip (hook, 5, 20, 4);
  2913. clip (melody, 4, 20, 4);
  2914. song.addMarker ({ 0, "Intro" });
  2915. song.addMarker ({ 8 * bar, "Drop" });
  2916. song.addMarker ({ 16 * bar, "Breakdown" });
  2917. song.addMarker ({ 20 * bar, "Final" });
  2918. // automation: the pad volume opens up during the intro
  2919. Automation a;
  2920. a.name = "Pad Volume";
  2921. a.target = { AutomationTargetKind::mixerVolume, 6, 0, 0 };
  2922. a.points = { { 0, 0.15f, 0.4f }, { 8 * bar, 0.8f, 0.0f } };
  2923. song.automations.push_back (a);
  2924. Clip ac;
  2925. ac.kind = ClipKind::automation;
  2926. ac.automation = 0;
  2927. ac.track = 6;
  2928. ac.start = 0;
  2929. ac.length = 8 * bar;
  2930. song.playlist.push_back (ac);
  2931. // mixer: names, colours and effects (bass compressor sidechained to the kick)
  2932. const char* names[] = { "Master", "Kick", "Clap", "Hat", "Snare", "Bass", "Pad", "Pluck", "Lead" };
  2933. for (int t = 0; t < 9; ++t)
  2934. {
  2935. song.mixer[(std::size_t) t].name = names[t];
  2936. if (t > 0)
  2937. song.mixer[(std::size_t) t].colour = song.channels[(std::size_t) t - 1].colour;
  2938. }
  2939. auto fx = [&] (int track, EffectKind kind) -> EffectSlot& {
  2940. song.mixer[(std::size_t) track].effects.push_back (makeEffectSlot (kind));
  2941. return song.mixer[(std::size_t) track].effects.back();
  2942. };
  2943. {
  2944. // kick EQ: cut below 30 Hz, weight at 60 Hz, remove the "boxiness" at 350 Hz, brightness at 4 kHz
  2945. auto& eq = fx (1, EffectKind::parametricEq);
  2946. auto band = [&] (int b, peq::BandType type, double hz, double db, double q) {
  2947. eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (type);
  2948. eq.params[(std::size_t) peq::param (b, 1)] = peq::hzValue (hz);
  2949. eq.params[(std::size_t) peq::param (b, 2)] = peq::gainValue (db);
  2950. eq.params[(std::size_t) peq::param (b, 3)] = peq::qValue (q);
  2951. };
  2952. band (0, peq::BandType::lowCut, 30.0, 0.0, 0.7);
  2953. band (1, peq::BandType::peak, 62.0, 5.0, 1.2);
  2954. band (2, peq::BandType::peak, 350.0, -6.0, 2.0);
  2955. band (3, peq::BandType::peak, 4200.0, 3.5, 1.5);
  2956. band (4, peq::BandType::highCut, 14000.0, 0.0, 0.7);
  2957. for (int b = 5; b < peq::bands; ++b)
  2958. eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (peq::BandType::off);
  2959. }
  2960. fx (1, EffectKind::distortion).mix = 0.3f;
  2961. auto& comp = fx (5, EffectKind::compressor);
  2962. comp.params[0] = 0.55f;
  2963. comp.params[1] = 0.8f;
  2964. comp.sidechain = 1;
  2965. fx (5, EffectKind::parametricEq);
  2966. fx (6, EffectKind::chorus);
  2967. fx (6, EffectKind::reverb);
  2968. fx (7, EffectKind::delay);
  2969. fx (7, EffectKind::reverb).mix = 0.4f;
  2970. fx (8, EffectKind::effector);
  2971. fx (8, EffectKind::delay);
  2972. fx (0, EffectKind::parametricEq);
  2973. auto& limiter = fx (0, EffectKind::limiter);
  2974. limiter.params = { 11.7f / 12.0f, 0.1f, 0.5f };
  2975. song.mixer[1].volume = 0.78f;
  2976. song.mixer[5].volume = 0.72f;
  2977. song.mixer[6].volume = 0.6f;
  2978. song.mixer[6].pan = -0.2f;
  2979. song.mixer[7].pan = 0.25f;
  2980. song.mode = PlayMode::song;
  2981. song.currentPattern = std::clamp (currentPattern, 0, (int) song.patterns.size() - 1);
  2982. juce::String error;
  2983. const auto ok = ProjectFile::save (song, juce::File (outputPath), error);
  2984. setApplicationReturnValue (ok ? 0 : 1);
  2985. quit();
  2986. }
  2987. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  2988. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  2989. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  2990. // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
  2991. struct TestVoice
  2992. {
  2993. explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
  2994. {
  2995. if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
  2996. instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
  2997. else
  2998. effect = std::move (p);
  2999. }
  3000. void noteOn()
  3001. {
  3002. if (instrument != nullptr)
  3003. instrument->noteOn (60, 0.9f);
  3004. }
  3005. void render (float* l, float* r, int n, float gainLeft, float gainRight)
  3006. {
  3007. if (instrument != nullptr)
  3008. {
  3009. instrument->render (l, r, n, gainLeft, gainRight);
  3010. return;
  3011. }
  3012. const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
  3013. juce::AudioBuffer<float> block (channels, 512);
  3014. juce::MidiBuffer midi;
  3015. for (int done = 0; done < n; done += 512)
  3016. {
  3017. const auto k = juce::jmin (512, n - done);
  3018. block.setSize (channels, k, false, false, true);
  3019. for (int i = 0; i < k; ++i)
  3020. {
  3021. const auto v = 0.25f * (float) std::sin (phase);
  3022. phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
  3023. for (int c = 0; c < channels; ++c)
  3024. block.setSample (c, i, v);
  3025. }
  3026. effect->processBlock (block, midi);
  3027. for (int i = 0; i < k; ++i)
  3028. {
  3029. l[done + i] += gainLeft * block.getSample (0, i);
  3030. r[done + i] += gainRight * block.getSample (1, i);
  3031. }
  3032. }
  3033. }
  3034. std::unique_ptr<lynx::PluginInstrument> instrument;
  3035. std::unique_ptr<juce::AudioPluginInstance> effect;
  3036. double phase = 0.0;
  3037. };
  3038. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  3039. {
  3040. juce::String report;
  3041. bool ok = false;
  3042. lynx::setPluginSandboxAlerts (false);
  3043. const juce::File log (reportPath + ".log");
  3044. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  3045. log.deleteFile();
  3046. {
  3047. lynx::PluginHost host (false);
  3048. host.addPluginFile (juce::File (pluginPath));
  3049. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  3050. // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
  3051. const juce::PluginDescription* instrument = nullptr;
  3052. for (const auto& type : types)
  3053. if (type.isInstrument)
  3054. instrument = &type;
  3055. for (const auto& type : types)
  3056. if (instrument == nullptr && ! type.isInstrument)
  3057. instrument = &type;
  3058. step ("host");
  3059. juce::String error;
  3060. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  3061. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  3062. step ("created");
  3063. if (remote != nullptr)
  3064. {
  3065. auto& proxy = *remote;
  3066. TestVoice voice (std::move (remote));
  3067. std::vector<float> l (48000), r (48000);
  3068. auto peakOf = [&] {
  3069. float peak = 0.0f;
  3070. for (std::size_t k = 0; k < l.size(); ++k)
  3071. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  3072. return peak;
  3073. };
  3074. const auto start = juce::Time::getMillisecondCounterHiRes();
  3075. voice.noteOn();
  3076. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  3077. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  3078. const auto peak = peakOf();
  3079. step ("played");
  3080. if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
  3081. {
  3082. // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
  3083. const auto dead = lynx::isSandboxedPluginDead (proxy);
  3084. std::fill (l.begin(), l.end(), 0.0f);
  3085. std::fill (r.begin(), r.end(), 0.0f);
  3086. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  3087. report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  3088. ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
  3089. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  3090. juce::File (reportPath).replaceWithText (report);
  3091. setApplicationReturnValue (ok ? 0 : 1);
  3092. quit();
  3093. return;
  3094. }
  3095. report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
  3096. << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  3097. if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
  3098. {
  3099. // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
  3100. std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
  3101. juce::Thread::sleep (4000);
  3102. juce::MemoryBlock state;
  3103. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  3104. proxy.getStateInformation (state);
  3105. report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
  3106. editor.reset();
  3107. }
  3108. // parameter -> state -> in-process plugin
  3109. bool stateOk = false;
  3110. if (! proxy.getParameters().isEmpty())
  3111. {
  3112. auto* p = proxy.getParameters()[0];
  3113. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  3114. p->setValue (target);
  3115. std::fill (l.begin(), l.end(), 0.0f);
  3116. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  3117. juce::MemoryBlock state;
  3118. proxy.getStateInformation (state);
  3119. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  3120. {
  3121. local->setStateInformation (state.getData(), (int) state.getSize());
  3122. const auto back = local->getParameters()[0]->getValue();
  3123. // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
  3124. auto control = target;
  3125. if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  3126. {
  3127. a->enableAllBuses();
  3128. a->prepareToPlay (48000.0, 512);
  3129. a->getParameters()[0]->setValue (target);
  3130. juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
  3131. block.clear();
  3132. juce::MidiBuffer none;
  3133. a->processBlock (block, none);
  3134. juce::MemoryBlock direct;
  3135. a->getStateInformation (direct);
  3136. if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  3137. {
  3138. b->setStateInformation (direct.getData(), (int) direct.getSize());
  3139. control = b->getParameters()[0]->getValue();
  3140. }
  3141. a->releaseResources();
  3142. }
  3143. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
  3144. stateOk = std::abs (back - control) < 0.02f;
  3145. }
  3146. }
  3147. step ("state");
  3148. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  3149. lynx::hangSandboxedPluginForTest (proxy);
  3150. juce::Thread::sleep (200);
  3151. std::fill (l.begin(), l.end(), 1.0f);
  3152. std::fill (r.begin(), r.end(), 1.0f);
  3153. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  3154. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  3155. std::fill (l.begin(), l.end(), 0.0f);
  3156. std::fill (r.begin(), r.end(), 0.0f);
  3157. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  3158. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  3159. const auto dead = lynx::isSandboxedPluginDead (proxy);
  3160. const auto hangPeak = peakOf();
  3161. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
  3162. // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
  3163. bool crashOk = false;
  3164. if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
  3165. {
  3166. auto& proxy2 = *second;
  3167. TestVoice voice2 (std::move (second));
  3168. voice2.noteOn();
  3169. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  3170. lynx::crashSandboxedPluginForTest (proxy2);
  3171. const auto crashStart = juce::Time::getMillisecondCounterHiRes();
  3172. while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
  3173. {
  3174. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  3175. juce::Thread::sleep (5);
  3176. }
  3177. const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
  3178. std::fill (l.begin(), l.end(), 0.0f);
  3179. std::fill (r.begin(), r.end(), 0.0f);
  3180. voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  3181. const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
  3182. report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
  3183. crashOk = crashDead && crashMs < 3000.0;
  3184. }
  3185. step ("crash");
  3186. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
  3187. }
  3188. }
  3189. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  3190. juce::File (reportPath).replaceWithText (report);
  3191. setApplicationReturnValue (ok ? 0 : 1);
  3192. quit();
  3193. }
  3194. // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
  3195. // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
  3196. // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
  3197. // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
  3198. // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
  3199. // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
  3200. void runUiPerf (const juce::File& project, const juce::File& report)
  3201. {
  3202. startupOptions = lynx::StartupOptions::load();
  3203. engine = std::make_unique<lynx::AudioEngine>();
  3204. crashEngine = engine.get();
  3205. createMainWindow();
  3206. mainWindow->reveal();
  3207. juce::String error;
  3208. auto ok = false;
  3209. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  3210. if (project.hasFileExtension ("flp"))
  3211. ok = engine->importFlpFile (project, error);
  3212. else if (auto song = lynx::ProjectFile::load (project, error))
  3213. {
  3214. engine->setSong (std::move (*song));
  3215. ok = true;
  3216. }
  3217. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  3218. if (! ok)
  3219. {
  3220. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  3221. setApplicationReturnValue (1);
  3222. quit();
  3223. return;
  3224. }
  3225. struct Step
  3226. {
  3227. juce::String name;
  3228. std::function<void()> setup;
  3229. std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
  3230. int frames;
  3231. };
  3232. struct UiPerf final : juce::Timer
  3233. {
  3234. LynxApplication& app;
  3235. juce::File report;
  3236. juce::String text;
  3237. std::vector<Step> steps;
  3238. std::size_t step = 0;
  3239. int frame = -1;
  3240. std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
  3241. double setupMs = 0.0, wallStart = 0.0;
  3242. double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
  3243. UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r)) {}
  3244. juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
  3245. double paintNow() const
  3246. {
  3247. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  3248. if (auto* p = peer())
  3249. p->performAnyPendingRepaintsNow();
  3250. return juce::Time::getMillisecondCounterHiRes() - t0;
  3251. }
  3252. void timerCallback() override
  3253. {
  3254. if (step >= steps.size())
  3255. {
  3256. stopTimer();
  3257. finish();
  3258. return;
  3259. }
  3260. auto& s = steps[step];
  3261. if (frame < 0)
  3262. {
  3263. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  3264. if (s.setup)
  3265. s.setup();
  3266. paintNow();
  3267. setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
  3268. times.clear();
  3269. rendered.clear();
  3270. wallStart = juce::Time::getMillisecondCounterHiRes();
  3271. cpuStart = lynx::processCpuSeconds();
  3272. frame = 0;
  3273. return;
  3274. }
  3275. if (s.action)
  3276. s.action (frame);
  3277. if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
  3278. times.push_back (ms);
  3279. ++frame;
  3280. if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
  3281. return;
  3282. const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
  3283. const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
  3284. text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
  3285. << " painted frames: " << stats (rendered) << "\n"
  3286. << " timed here (event + paint + blit): " << stats (times)
  3287. << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s)\n";
  3288. juce::File (report).replaceWithText (text);
  3289. ++step;
  3290. frame = -1;
  3291. }
  3292. static juce::String stats (std::vector<double> sorted)
  3293. {
  3294. std::sort (sorted.begin(), sorted.end());
  3295. const auto at = [&sorted] (double q) { return sorted.empty() ? 0.0 : sorted[(std::size_t) juce::jlimit (0, (int) sorted.size() - 1, (int) (q * (double) sorted.size()))]; };
  3296. double sum = 0.0;
  3297. int over = 0;
  3298. for (auto t : sorted)
  3299. {
  3300. sum += t;
  3301. over += t > 16.0 ? 1 : 0;
  3302. }
  3303. return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
  3304. + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
  3305. + " ms, >16 ms " + juce::String (over);
  3306. }
  3307. void finish()
  3308. {
  3309. // the cost of asking where the mouse is (X11: a round trip to the display server)
  3310. const auto q0 = juce::Time::getMillisecondCounterHiRes();
  3311. for (int i = 0; i < 100; ++i)
  3312. juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
  3313. text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
  3314. app.mainWindow->onFrame = nullptr;
  3315. app.engine->stop();
  3316. text << "result=OK\n";
  3317. report.replaceWithText (text);
  3318. app.setApplicationReturnValue (0);
  3319. app.quit();
  3320. }
  3321. };
  3322. auto* ui = &mainWindow->getContent();
  3323. auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
  3324. auto* peer = mainWindow->getPeer();
  3325. if (peer == nullptr || ! target.isShowing())
  3326. return;
  3327. juce::ModifierKeys::currentModifiers = mods;
  3328. const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
  3329. juce::MouseWheelDetails wheel { dx, dy, false, false, false };
  3330. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  3331. juce::ModifierKeys::currentModifiers = {};
  3332. };
  3333. auto run = std::make_unique<UiPerf> (*this, report);
  3334. mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
  3335. run->text << "project: " << project.getFullPathName() << "\n"
  3336. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  3337. << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
  3338. << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  3339. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
  3340. << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
  3341. << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
  3342. const auto none = juce::ModifierKeys();
  3343. run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
  3344. run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
  3345. run->steps.push_back ({ "mixer scroll", {}, [wheelAt, ui, none] (int f) { wheelAt (ui->getMixerForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  3346. run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
  3347. run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
  3348. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  3349. run->steps.push_back ({ "playlist scroll sideways", {},
  3350. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  3351. run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
  3352. run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
  3353. [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  3354. // let the window draw the project first
  3355. perf = std::move (run);
  3356. juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
  3357. }
  3358. // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
  3359. // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
  3360. void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
  3361. const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
  3362. {
  3363. startupOptions = lynx::StartupOptions::load();
  3364. engine = std::make_unique<lynx::AudioEngine>();
  3365. crashEngine = engine.get();
  3366. // the user's saved device stays as it was: this run's choices are undone before quitting
  3367. savedDeviceState = engine->getDeviceManager().createStateXml();
  3368. auto& devices = engine->getDeviceManager();
  3369. const auto driverFile = addDriverFileDeviceType();
  3370. const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
  3371. if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
  3372. devices.setCurrentAudioDeviceType (type, true);
  3373. if (bufferSize > 0 || deviceName.isNotEmpty())
  3374. {
  3375. auto setup = devices.getAudioDeviceSetup();
  3376. if (bufferSize > 0)
  3377. setup.bufferSize = bufferSize;
  3378. if (deviceName.isNotEmpty())
  3379. setup.outputDeviceName = deviceName;
  3380. const auto error = devices.setAudioDeviceSetup (setup, true);
  3381. if (error.isNotEmpty())
  3382. report.replaceWithText ("device error: " + error + "\n");
  3383. }
  3384. createMainWindow();
  3385. if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
  3386. mainWindow->reveal();
  3387. juce::String error;
  3388. auto ok = false;
  3389. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  3390. if (project.hasFileExtension ("flp"))
  3391. ok = engine->importFlpFile (project, error);
  3392. else if (auto song = lynx::ProjectFile::load (project, error))
  3393. {
  3394. engine->setSong (std::move (*song));
  3395. ok = true;
  3396. }
  3397. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  3398. if (! ok)
  3399. {
  3400. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  3401. restoreSavedDeviceState();
  3402. setApplicationReturnValue (1);
  3403. quit();
  3404. return;
  3405. }
  3406. if (recordTo.isNotEmpty())
  3407. engine->setAudioRecordingArmed (true); // opens the input of the driver
  3408. // let the window draw the project, then play from the start with fresh statistics
  3409. juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
  3410. if (engine == nullptr)
  3411. return;
  3412. engine->stop();
  3413. engine->rewind();
  3414. engine->getRtStats().reset();
  3415. engine->takeUiPulse();
  3416. if (recordTo.isNotEmpty())
  3417. engine->setRecording (true);
  3418. // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
  3419. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  3420. if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
  3421. engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
  3422. ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
  3423. engine->play();
  3424. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
  3425. if (engine == nullptr)
  3426. return;
  3427. engine->stop();
  3428. juce::String recording;
  3429. if (engine->getAudioLogger().isLogging())
  3430. {
  3431. recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
  3432. engine->getAudioLogger().stop();
  3433. }
  3434. if (recordTo.isNotEmpty())
  3435. recording = finishStressTake (juce::File (recordTo), seconds);
  3436. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  3437. const auto s = engine->getRtStats().snapshot();
  3438. juce::String text;
  3439. text << "project: " << project.getFullPathName() << "\n"
  3440. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  3441. << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
  3442. << juce::SystemStats::getCpuModel() << "\n"
  3443. << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
  3444. << engine->describeRealtime();
  3445. const auto pulse = engine->takeUiPulse();
  3446. text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
  3447. << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
  3448. text << " load histogram (share of the deadline: callbacks):";
  3449. for (std::size_t b = 0; b < s.histogram.size(); ++b)
  3450. if (s.histogram[b] > 0)
  3451. text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
  3452. text << "\n";
  3453. text << recording;
  3454. // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
  3455. if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
  3456. {
  3457. auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
  3458. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  3459. {
  3460. juce::Graphics g (image);
  3461. g.fillAll (lynx::theme::panel);
  3462. page->paintEntireComponent (g, false);
  3463. }
  3464. const juce::File shot (cli[at + 1].unquoted());
  3465. shot.deleteFile();
  3466. if (auto out = shot.createOutputStream())
  3467. juce::PNGImageFormat().writeImageToStream (image, *out);
  3468. }
  3469. text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
  3470. report.replaceWithText (text);
  3471. restoreSavedDeviceState();
  3472. setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
  3473. quit();
  3474. });
  3475. });
  3476. }
  3477. // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
  3478. // process leaves what was done).
  3479. void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  3480. const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
  3481. {
  3482. engine = std::make_unique<lynx::AudioEngine>();
  3483. savedDeviceState = engine->getDeviceManager().createStateXml();
  3484. auto text = std::make_shared<juce::String>();
  3485. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  3486. auto finish = [this, step] (int code) {
  3487. restoreSavedDeviceState();
  3488. setApplicationReturnValue (code);
  3489. quit();
  3490. };
  3491. auto& devices = engine->getDeviceManager();
  3492. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  3493. devices.setCurrentAudioDeviceType (deviceType, true);
  3494. {
  3495. auto setup = devices.getAudioDeviceSetup();
  3496. if (deviceName.isNotEmpty())
  3497. setup.outputDeviceName = deviceName;
  3498. if (bufferSize > 0)
  3499. setup.bufferSize = bufferSize;
  3500. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  3501. step ("device_error=" + error);
  3502. }
  3503. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  3504. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  3505. // takes go next to the report, not into the user's recordings folder
  3506. engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
  3507. auto* device = devices.getCurrentAudioDevice();
  3508. if (device == nullptr || engine->getInputChannelNames().empty())
  3509. {
  3510. step ("result=ERROR no device / no input");
  3511. finish (1);
  3512. return;
  3513. }
  3514. const auto rate = device->getCurrentSampleRate();
  3515. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
  3516. + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
  3517. // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
  3518. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  3519. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  3520. {
  3521. lynx::takes::WavTakeWriter w;
  3522. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  3523. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  3524. std::vector<float> block (4096);
  3525. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  3526. {
  3527. std::fill (block.begin(), block.end(), 0.0f);
  3528. for (int k = 0; k < (int) block.size(); ++k)
  3529. {
  3530. const auto f = at + k;
  3531. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  3532. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  3533. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  3534. if (rel >= 0 && rel < 5)
  3535. block[(std::size_t) k] = 0.5f * shape[rel];
  3536. }
  3537. const float* d[] { block.data() };
  3538. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  3539. }
  3540. w.close();
  3541. }
  3542. lynx::Song song = lynx::Song::makeDefault();
  3543. song.bpm = 120.0;
  3544. song.mode = lynx::PlayMode::song;
  3545. song.playlist.clear();
  3546. lynx::ChannelDef c;
  3547. c.name = "Clicks";
  3548. c.instrument = lynx::InstrumentKind::audioClip;
  3549. c.samplePath = clickFile.getFullPathName().toStdString();
  3550. c.mixerTrack = 0;
  3551. c.volume = 1.0f;
  3552. song.channels.push_back (c);
  3553. lynx::Clip clip;
  3554. clip.kind = lynx::ClipKind::audio;
  3555. clip.channel = (int) song.channels.size() - 1;
  3556. clip.track = 0;
  3557. clip.start = 0;
  3558. clip.length = (std::int64_t) beats * lynx::ppq;
  3559. song.playlist.push_back (clip);
  3560. if (mode == 1) // loop recording, bars 2-4
  3561. {
  3562. song.loopStart = 4 * lynx::ppq;
  3563. song.loopEnd = 16 * lynx::ppq;
  3564. }
  3565. else if (mode == 2) // punch in/out, bars 3-4
  3566. {
  3567. song.loopStart = 8 * lynx::ppq;
  3568. song.loopEnd = 16 * lynx::ppq;
  3569. }
  3570. if (song.mixer.size() > 1)
  3571. {
  3572. song.mixer[1].name = "Loop In";
  3573. song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
  3574. }
  3575. engine->setSong (std::move (song));
  3576. engine->setInsertInput (1, 0, false);
  3577. juce::ignoreUnused (pdcSamples);
  3578. // 1) the ping
  3579. if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
  3580. step ("ping_error=" + error);
  3581. juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
  3582. if (engine == nullptr)
  3583. return;
  3584. if (engine->isPinging())
  3585. engine->cancelLatencyPing();
  3586. const auto r = engine->finishLatencyPing();
  3587. step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
  3588. + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
  3589. const auto l = engine->currentLatency();
  3590. step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
  3591. // 2) record
  3592. engine->setInsertArmed (1, true);
  3593. auto o = engine->getRecordOptions();
  3594. o.recordAudio = true;
  3595. o.countInBars = 0;
  3596. o.waitForInput = false;
  3597. o.punchLoopRegion = mode == 2;
  3598. o.preRollBars = mode == 2 ? 1 : 0;
  3599. o.postRollBars = mode == 2 ? 1 : 0;
  3600. engine->setRecordOptions (o);
  3601. engine->stop();
  3602. engine->rewind();
  3603. engine->setRecording (true);
  3604. juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
  3605. if (engine == nullptr)
  3606. return;
  3607. engine->startPlayback(); // (as the Play button: pre-roll / punch)
  3608. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
  3609. if (engine == nullptr)
  3610. return;
  3611. if (mode == 2)
  3612. step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
  3613. engine->stop();
  3614. juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
  3615. if (engine == nullptr)
  3616. return;
  3617. engine->setRecording (false);
  3618. const auto& s = engine->getSong();
  3619. const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
  3620. int take = -1;
  3621. for (int ch = 0; ch < (int) s.channels.size(); ++ch)
  3622. if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
  3623. take = ch;
  3624. if (take < 0)
  3625. {
  3626. step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
  3627. finish (1);
  3628. return;
  3629. }
  3630. std::vector<std::vector<float>> audio;
  3631. double takeRate = 0.0;
  3632. const auto& path = s.channels[(std::size_t) take].samplePath;
  3633. lynx::takes::readWav (path, audio, &takeRate);
  3634. const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
  3635. step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
  3636. + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
  3637. // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
  3638. std::vector<juce::int64> peaks;
  3639. if (! audio.empty())
  3640. for (juce::int64 f = 1; f + 1 < frames; ++f)
  3641. {
  3642. const auto x = std::abs (audio[0][(std::size_t) f]);
  3643. if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
  3644. && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
  3645. peaks.push_back (f);
  3646. }
  3647. // every clip of the take: each click inside it against the nearest beat
  3648. int clips = 0, checked = 0, muted = 0;
  3649. double worst = 0.0, sum = 0.0;
  3650. for (const auto& c : s.playlist)
  3651. {
  3652. if (c.kind != lynx::ClipKind::audio || c.channel != take)
  3653. continue;
  3654. ++clips;
  3655. muted += c.muted ? 1 : 0;
  3656. const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
  3657. for (const auto f : peaks)
  3658. {
  3659. const auto intoClip = (double) f - skip;
  3660. if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
  3661. continue;
  3662. const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
  3663. const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
  3664. const auto error = (songTick - beat) / tps;
  3665. worst = std::max (worst, std::abs (error));
  3666. sum += error;
  3667. ++checked;
  3668. }
  3669. step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
  3670. + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
  3671. + (c.muted ? " (muted lane)" : ""));
  3672. }
  3673. step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
  3674. + " muted_lanes=" + juce::String (muted));
  3675. step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
  3676. auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
  3677. if (mode == 2) // one clip, exactly the punch range, its 8 beats
  3678. {
  3679. const auto& sp = engine->getSong();
  3680. bool exact = false;
  3681. for (const auto& c : sp.playlist)
  3682. if (c.kind == lynx::ClipKind::audio && c.channel == take)
  3683. exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
  3684. step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
  3685. ok = ok && clips == 1 && exact && checked == 8;
  3686. }
  3687. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  3688. finish (ok ? 0 : 1);
  3689. });
  3690. });
  3691. });
  3692. });
  3693. }
  3694. // --hwinserttest (round 164d): see the command line above.
  3695. void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  3696. const juce::String& inputName, int bufferSize)
  3697. {
  3698. engine = std::make_unique<lynx::AudioEngine>();
  3699. savedDeviceState = engine->getDeviceManager().createStateXml();
  3700. auto text = std::make_shared<juce::String>();
  3701. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  3702. auto finish = [this] (int code) {
  3703. if (engine != nullptr)
  3704. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  3705. restoreSavedDeviceState();
  3706. setApplicationReturnValue (code);
  3707. quit();
  3708. };
  3709. auto& devices = engine->getDeviceManager();
  3710. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  3711. devices.setCurrentAudioDeviceType (deviceType, true);
  3712. {
  3713. auto setup = devices.getAudioDeviceSetup();
  3714. if (deviceName.isNotEmpty())
  3715. setup.outputDeviceName = deviceName;
  3716. if (bufferSize > 0)
  3717. setup.bufferSize = bufferSize;
  3718. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  3719. step ("device_error=" + error);
  3720. }
  3721. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  3722. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  3723. auto* device = devices.getCurrentAudioDevice();
  3724. if (device == nullptr || engine->getInputChannelNames().empty())
  3725. {
  3726. step ("result=ERROR no device / no input");
  3727. finish (1);
  3728. return;
  3729. }
  3730. const auto rate = device->getCurrentSampleRate();
  3731. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
  3732. // the click track: the ping's pulse on every beat at 120 bpm
  3733. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  3734. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  3735. {
  3736. lynx::takes::WavTakeWriter w;
  3737. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  3738. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  3739. std::vector<float> block (4096);
  3740. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  3741. {
  3742. std::fill (block.begin(), block.end(), 0.0f);
  3743. for (int k = 0; k < (int) block.size(); ++k)
  3744. {
  3745. const auto f = at + k;
  3746. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  3747. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  3748. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  3749. if (rel >= 0 && rel < 5)
  3750. block[(std::size_t) k] = 0.5f * shape[rel];
  3751. }
  3752. const float* d[] { block.data() };
  3753. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  3754. }
  3755. w.close();
  3756. }
  3757. lynx::Song song = lynx::Song::makeDefault();
  3758. song.bpm = 120.0;
  3759. song.mode = lynx::PlayMode::song;
  3760. song.playlist.clear();
  3761. song.channels.clear();
  3762. for (int k = 0; k < 2; ++k)
  3763. {
  3764. lynx::ChannelDef c;
  3765. c.name = k == 0 ? "Wet" : "Dry";
  3766. c.instrument = lynx::InstrumentKind::audioClip;
  3767. c.samplePath = clickFile.getFullPathName().toStdString();
  3768. c.mixerTrack = k + 1;
  3769. c.volume = 1.0f;
  3770. song.channels.push_back (c);
  3771. lynx::Clip clip;
  3772. clip.kind = lynx::ClipKind::audio;
  3773. clip.channel = k;
  3774. clip.track = k;
  3775. clip.start = 0;
  3776. clip.length = (std::int64_t) beats * lynx::ppq;
  3777. song.playlist.push_back (clip);
  3778. }
  3779. song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
  3780. for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
  3781. fx.enabled = false;
  3782. song.mixer[1].pan = -1.0f;
  3783. song.mixer[2].pan = 1.0f;
  3784. auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  3785. hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
  3786. hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
  3787. hw.params[lynx::hwinsert::inputStereo] = 1.0f;
  3788. song.mixer[1].effects.clear();
  3789. song.mixer[1].effects.push_back (hw);
  3790. engine->setSong (std::move (song));
  3791. const auto meter = [this] (int output) {
  3792. const auto* times = engine->getProcessTimes();
  3793. const auto key = (std::size_t) (1 * lynx::maxEffectSlots + 0) * lynx::ProcessTimes::meterOutputs + (std::size_t) output;
  3794. return times != nullptr && key < times->effectMeters.size() ? times->effectMeters[key].load() : 0.0f;
  3795. };
  3796. // 1) the insert's ping (as its Ping button: a momentary value flipped)
  3797. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter] {
  3798. if (engine == nullptr)
  3799. return;
  3800. engine->editSong ([] (lynx::Song& s) { s.mixer[1].effects[0].params[lynx::hwinsert::ping] = 1.0f; });
  3801. juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter] {
  3802. if (engine == nullptr)
  3803. return;
  3804. const auto state = meter (lynx::hwinsert::pingState);
  3805. const auto samples = lynx::hwinsert::roundTripOf (meter (lynx::hwinsert::pingSamples));
  3806. step ("ping_state=" + juce::String (state, 3) + (std::abs (state - 0.5f) < 0.01f ? " (ok)" : " (FAILED)") + " round_trip=" + juce::String (samples)
  3807. + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
  3808. if (std::abs (state - 0.5f) >= 0.01f)
  3809. {
  3810. step ("result=FAILED ping");
  3811. finish (1);
  3812. return;
  3813. }
  3814. engine->editSong ([samples] (lynx::Song& s) { s.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (samples); });
  3815. // 2) play, capturing the Master
  3816. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples] {
  3817. if (engine == nullptr)
  3818. return;
  3819. step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
  3820. // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
  3821. // odd round trip (12345 samples: the project keeps it to the sample)
  3822. {
  3823. auto odd = engine->getSong();
  3824. odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
  3825. juce::String error;
  3826. auto same = true;
  3827. for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
  3828. {
  3829. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
  3830. const auto saved = lynx::ProjectFile::save (*song, file, error);
  3831. const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
  3832. same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  3833. && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
  3834. && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
  3835. && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
  3836. }
  3837. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
  3838. step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
  3839. if (! same)
  3840. {
  3841. step ("result=FAILED project");
  3842. finish (1);
  3843. return;
  3844. }
  3845. }
  3846. auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
  3847. engine->stop();
  3848. engine->rewind();
  3849. engine->getMeters().capture.setSource (0);
  3850. engine->play();
  3851. auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
  3852. auto pull = std::make_shared<std::function<void()>>();
  3853. *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull] {
  3854. if (engine == nullptr)
  3855. return;
  3856. engine->getMeters().capture.pull (*left, *right);
  3857. if (*pulls == 10) // the insert's editor while it plays (next to the report)
  3858. for (const auto scale : { 1.0f, 1.5f })
  3859. {
  3860. auto editor = lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
  3861. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  3862. {
  3863. juce::Graphics g (image);
  3864. g.fillAll (lynx::theme::panel);
  3865. editor->paintEntireComponent (g, false);
  3866. }
  3867. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
  3868. file.deleteFile();
  3869. juce::PNGImageFormat png;
  3870. if (auto stream = file.createOutputStream())
  3871. png.writeImageToStream (image, *stream);
  3872. }
  3873. if (--*pulls > 0)
  3874. {
  3875. juce::Timer::callAfterDelay (200, *pull);
  3876. return;
  3877. }
  3878. engine->stop();
  3879. const auto dropped = engine->getMeters().capture.droppedFrames();
  3880. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  3881. // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
  3882. auto peaksOf = [rate] (const std::vector<float>& x) {
  3883. std::vector<juce::int64> peaks;
  3884. for (std::size_t f = 1; f + 1 < x.size(); ++f)
  3885. if (std::abs (x[f]) > 0.25f && std::abs (x[f]) >= std::abs (x[f - 1]) && std::abs (x[f]) > std::abs (x[f + 1])
  3886. && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
  3887. peaks.push_back ((juce::int64) f);
  3888. return peaks;
  3889. };
  3890. const auto wet = peaksOf (*left), dry = peaksOf (*right);
  3891. int pairs = 0;
  3892. juce::int64 worst = 0;
  3893. double gainSum = 0.0, residual = 0.0, energy = 0.0;
  3894. for (const auto w : wet)
  3895. {
  3896. auto best = std::min_element (dry.begin(), dry.end(), [w] (juce::int64 a, juce::int64 b) { return std::abs (a - w) < std::abs (b - w); });
  3897. if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
  3898. continue;
  3899. ++pairs;
  3900. worst = std::max (worst, std::abs (*best - w));
  3901. gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
  3902. }
  3903. const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
  3904. // dry clicks with no wet click beside them (a dropout of the cable / device), listed
  3905. juce::String unmatched;
  3906. for (const auto d : dry)
  3907. if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
  3908. unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
  3909. if (unmatched.isNotEmpty())
  3910. step ("dry_clicks_without_wet=" + unmatched);
  3911. // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
  3912. for (const auto w : wet)
  3913. for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
  3914. {
  3915. const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
  3916. residual += d * d;
  3917. energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
  3918. }
  3919. const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
  3920. step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
  3921. + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
  3922. step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
  3923. auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
  3924. const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
  3925. step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
  3926. const auto excused = xruns > 0 ? 2 * xruns : 0;
  3927. const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
  3928. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  3929. finish (ok ? 0 : 1);
  3930. };
  3931. juce::Timer::callAfterDelay (200, *pull);
  3932. });
  3933. });
  3934. });
  3935. }
  3936. // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
  3937. // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
  3938. juce::String finishStressTake (const juce::File& target, double seconds)
  3939. {
  3940. juce::String text;
  3941. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  3942. text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
  3943. if (device != nullptr)
  3944. text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
  3945. engine->setRecording (false); // closes the take: a clip of the song
  3946. juce::File take;
  3947. for (const auto& c : engine->getSong().channels)
  3948. if (c.instrument == lynx::InstrumentKind::audioClip)
  3949. take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
  3950. if (! take.existsAsFile())
  3951. return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
  3952. target.deleteFile();
  3953. if (! take.moveFileTo (target))
  3954. take.copyFileTo (target);
  3955. juce::AudioFormatManager formats;
  3956. formats.registerBasicFormats();
  3957. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
  3958. {
  3959. juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
  3960. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
  3961. const auto peak = audio.getMagnitude (0, audio.getNumSamples());
  3962. const auto length = (double) reader->lengthInSamples / reader->sampleRate;
  3963. text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
  3964. << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
  3965. << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
  3966. }
  3967. else
  3968. text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
  3969. return text;
  3970. }
  3971. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  3972. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  3973. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  3974. {
  3975. lynx::AudioEngine offline (false);
  3976. const juce::File input (inputPath);
  3977. juce::String error, report;
  3978. bool ok = false;
  3979. if (input.hasFileExtension ("flp"))
  3980. ok = offline.importFlpFile (input, error);
  3981. else if (auto song = lynx::ProjectFile::load (input, error))
  3982. {
  3983. offline.setSong (std::move (*song));
  3984. ok = true;
  3985. }
  3986. int samplers = 0, samplersLoaded = 0;
  3987. if (ok)
  3988. {
  3989. for (const auto& c : offline.getSong().channels)
  3990. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  3991. {
  3992. ++samplers;
  3993. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  3994. }
  3995. const juce::File output (outputPath);
  3996. output.deleteFile();
  3997. juce::WavAudioFormat wav;
  3998. std::unique_ptr<juce::AudioFormatWriter> writer (
  3999. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  4000. if (writer == nullptr)
  4001. {
  4002. ok = false;
  4003. error = lynx::utf8 ("could not create ") + outputPath;
  4004. }
  4005. else
  4006. {
  4007. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  4008. report << "peak=" << peak << "\n";
  4009. ok = peak > 0.001f;
  4010. }
  4011. }
  4012. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  4013. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  4014. juce::File (outputPath + ".txt").replaceWithText (report);
  4015. setApplicationReturnValue (ok ? 0 : 1);
  4016. quit();
  4017. }
  4018. // LYNX.exe --export project.(flp|lynx) output.(wav|flac|ogg|mp3) [--pattern] [--insert N] [--rate N]
  4019. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail.
  4020. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  4021. {
  4022. juce::String error, report;
  4023. bool ok = false;
  4024. const auto started = juce::Time::getMillisecondCounterHiRes();
  4025. lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
  4026. {
  4027. lynx::AudioEngine loader (false);
  4028. const juce::File input (inputPath);
  4029. // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
  4030. if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
  4031. {
  4032. juce::MemoryBlock data;
  4033. if (input.loadFileAsData (data))
  4034. try
  4035. {
  4036. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  4037. auto& host = loader.getPluginHost();
  4038. const auto listed = std::chrono::steady_clock::now();
  4039. const auto files = host.filesToScanFor (uses);
  4040. lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
  4041. report << "scanned=" << files.joinIntoString (";") << "\n";
  4042. const auto scanned = std::chrono::steady_clock::now();
  4043. host.scanFiles (files, {});
  4044. lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
  4045. }
  4046. catch (const flp::Error&)
  4047. {
  4048. }
  4049. }
  4050. if (input.hasFileExtension ("flp"))
  4051. ok = loader.importFlpFile (input, error);
  4052. else if (auto song = lynx::ProjectFile::load (input, error))
  4053. {
  4054. loader.setSong (std::move (*song));
  4055. ok = true;
  4056. }
  4057. if (ok)
  4058. {
  4059. const juce::File output (outputPath);
  4060. lynx::ExportSettings settings;
  4061. settings.wholeSong = ! patternOnly;
  4062. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  4063. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  4064. : lynx::ExportSettings::Format::wav24;
  4065. // --insert N: only that insert's output (what "Render to audio" records)
  4066. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  4067. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  4068. loader.editSong ([] (lynx::Song& s) {
  4069. for (auto& t : s.mixer)
  4070. t.effects.clear();
  4071. }, false);
  4072. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  4073. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  4074. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  4075. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  4076. // .mp3: the Export window's MP3 (320 kbps); everything else as before
  4077. auto options = settings.toOptions();
  4078. // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
  4079. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
  4080. options.pluginWarmUp = false;
  4081. // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
  4082. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
  4083. if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
  4084. options.sampleRate = rate;
  4085. if (output.hasFileExtension ("mp3"))
  4086. {
  4087. options.format = lynx::exportopts::Format::mp3;
  4088. options.mp3Kbps = 320;
  4089. }
  4090. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
  4091. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  4092. lynx::loadtrace::end();
  4093. int lastPercent = -1;
  4094. ok = job.run ([&lastPercent] (double p) {
  4095. lastPercent = (int) (p * 100.0);
  4096. return true;
  4097. }, error);
  4098. auto joined = [] (const std::map<std::string, int>& items) {
  4099. juce::StringArray names;
  4100. for (const auto& [name, count] : items)
  4101. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  4102. return names.joinIntoString (", ");
  4103. };
  4104. const auto& importReport = loader.getImportReport();
  4105. report << "converted=" << joined (importReport.converted) << "\n"
  4106. << "approximated=" << joined (importReport.approximated) << "\n"
  4107. << "unsupported=" << joined (importReport.unsupported) << "\n"
  4108. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  4109. << "partial_effects=" << joined (importReport.partialEffects) << "\n"
  4110. << "missing_samples=" << importReport.missingSamples << "\n";
  4111. // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
  4112. for (const auto& line : loader.getMatchedPlugins())
  4113. report << "plugin_found=" << line << "\n";
  4114. for (const auto& m : loader.getMissingPluginDetails())
  4115. report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
  4116. << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
  4117. {
  4118. const auto& song = loader.getSong();
  4119. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  4120. {
  4121. const auto& track = song.mixer[t];
  4122. if (track.effects.empty() && track.sends.empty())
  4123. continue;
  4124. report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
  4125. << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
  4126. for (const auto& s : track.sends)
  4127. report << " send>" << s.target << "@" << juce::String (s.level, 3);
  4128. report << " |";
  4129. for (const auto& fx : track.effects)
  4130. report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
  4131. : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
  4132. << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
  4133. << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
  4134. report << "\n";
  4135. }
  4136. }
  4137. report << juce::String (lynx::loadtrace::reportLines());
  4138. lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
  4139. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  4140. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  4141. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  4142. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  4143. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  4144. << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
  4145. << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
  4146. << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
  4147. << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
  4148. << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
  4149. << "song_seconds=" << job.getMusicSeconds() << "\n"
  4150. << "peak=" << job.getPeak() << "\n"
  4151. << "final_progress=" << lastPercent << "\n"
  4152. << "bytes=" << output.getSize() << "\n";
  4153. ok = ok && job.getPeak() > 0.001f;
  4154. }
  4155. }
  4156. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  4157. juce::File (outputPath + ".txt").replaceWithText (report);
  4158. setApplicationReturnValue (ok ? 0 : 1);
  4159. quit();
  4160. }
  4161. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  4162. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  4163. // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
  4164. struct EditorCpuRun final : juce::Timer
  4165. {
  4166. struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
  4167. std::vector<Case> cases;
  4168. std::size_t at = 0;
  4169. int phase = 0;
  4170. double t0 = 0.0, c0 = 0.0;
  4171. juce::String report;
  4172. juce::File out;
  4173. std::unique_ptr<lynx::AudioEngine> engine;
  4174. std::unique_ptr<juce::DocumentWindow> window;
  4175. std::function<void()> done;
  4176. void start()
  4177. {
  4178. engine = std::make_unique<lynx::AudioEngine> (false);
  4179. report << "editor\tmode\tcpu % of one core\n";
  4180. open();
  4181. startTimer (250);
  4182. }
  4183. void open()
  4184. {
  4185. window.reset();
  4186. if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
  4187. const auto& c = cases[at];
  4188. lynx::Song song;
  4189. song.mixer.resize (2);
  4190. song.mixer[0].name = "Master";
  4191. song.mixer[1].name = "Insert 1";
  4192. song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
  4193. engine->setSong (std::move (song));
  4194. engine->dispatchPendingMessages();
  4195. lynx::setNativeEditorDemo (c.demo);
  4196. auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
  4197. : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
  4198. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
  4199. window->setUsingNativeTitleBar (true);
  4200. window->setContentOwned (editor.release(), true);
  4201. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  4202. window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
  4203. window->setVisible (true);
  4204. phase = 0;
  4205. t0 = juce::Time::getMillisecondCounterHiRes();
  4206. }
  4207. void timerCallback() override
  4208. {
  4209. const auto now = juce::Time::getMillisecondCounterHiRes();
  4210. if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
  4211. if (phase == 1 && now - t0 > 8000.0)
  4212. {
  4213. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  4214. const auto& c = cases[at];
  4215. report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
  4216. ++at;
  4217. open();
  4218. }
  4219. }
  4220. };
  4221. std::unique_ptr<EditorCpuRun> editorCpu;
  4222. void runEditorCpu (const juce::String& path)
  4223. {
  4224. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4225. editorCpu = std::make_unique<EditorCpuRun>();
  4226. editorCpu->out = juce::File (path);
  4227. using K = lynx::EffectKind;
  4228. for (const auto demo : { false, true })
  4229. for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
  4230. { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
  4231. { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
  4232. { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
  4233. editorCpu->cases.push_back (c);
  4234. editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
  4235. editorCpu->start();
  4236. }
  4237. void runPluginEditorSnapshots (const juce::String& folder)
  4238. {
  4239. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4240. {
  4241. const juce::File out (folder);
  4242. out.createDirectory();
  4243. lynx::AudioEngine offline (false);
  4244. const auto roots = lynx::findFlStudioRoots();
  4245. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  4246. auto kinds = lynx::plugui::flLayoutKinds();
  4247. kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
  4248. for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
  4249. kinds.push_back (own);
  4250. kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
  4251. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
  4252. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
  4253. kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
  4254. const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
  4255. auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
  4256. auto ridgePasses = 0;
  4257. for (const auto kind : kinds)
  4258. {
  4259. auto fx = lynx::makeEffectSlot (kind);
  4260. juce::String name (lynx::effectInfo (kind).name);
  4261. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  4262. {
  4263. const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
  4264. auto file = dir.getChildFile ("Default.fst");
  4265. if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
  4266. for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
  4267. file = f;
  4268. if (! file.existsAsFile())
  4269. {
  4270. auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
  4271. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
  4272. file = files.isEmpty() ? juce::File() : files[0];
  4273. }
  4274. juce::MemoryBlock data;
  4275. if (file.existsAsFile() && file.loadFileAsData (data))
  4276. {
  4277. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  4278. if (auto loaded = lynx::effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), 130.0); loaded && loaded->kind == kind)
  4279. fx = *loaded;
  4280. }
  4281. name = juce::String::fromUTF8 (plugin.c_str());
  4282. break;
  4283. }
  4284. if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
  4285. {
  4286. juce::MemoryBlock data;
  4287. juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
  4288. lynx::maximusfx::Blob blob;
  4289. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  4290. blob.mix = 600;
  4291. const auto* b = static_cast<const std::uint8_t*> (data.getData());
  4292. blob.state.assign (b, b + data.getSize());
  4293. fx = lynx::makeEffectSlot (kind);
  4294. fx.state = lynx::maximusfx::pack (blob);
  4295. name = "Soundgoodizer";
  4296. }
  4297. if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
  4298. {
  4299. for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
  4300. { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
  4301. { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
  4302. { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
  4303. { "Process order", 0.4783f }, { "De-esser", 1.0f } })
  4304. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  4305. name = "Ridge Strip (Vocal strip)";
  4306. }
  4307. else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
  4308. {
  4309. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
  4310. { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
  4311. { "Filter split", 1.0f }, { "Expander", 1.0f } })
  4312. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  4313. name = "Ridge Strip (E console)";
  4314. }
  4315. else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
  4316. for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
  4317. { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
  4318. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  4319. if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
  4320. {
  4321. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
  4322. { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
  4323. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  4324. name = "Compressor (RComp role)";
  4325. }
  4326. if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
  4327. fx.params[0] = 0.33f;
  4328. if (kind == lynx::EffectKind::ember)
  4329. {
  4330. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
  4331. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
  4332. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
  4333. }
  4334. if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
  4335. for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
  4336. { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
  4337. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  4338. lynx::Song song;
  4339. song.mixer.resize (2);
  4340. song.mixer[0].name = "Master";
  4341. song.mixer[1].name = "Insert 1";
  4342. song.mixer[1].effects.push_back (fx);
  4343. offline.setSong (std::move (song));
  4344. offline.dispatchPendingMessages();
  4345. if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
  4346. {
  4347. auto editor = lynx::makeProEditor (offline, 1, 0, true);
  4348. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  4349. {
  4350. juce::Graphics g (image);
  4351. editor->paintEntireComponent (g, false);
  4352. }
  4353. const auto file = out.getChildFile (name + ".png");
  4354. file.deleteFile();
  4355. juce::PNGImageFormat png;
  4356. if (auto stream = file.createOutputStream())
  4357. png.writeImageToStream (image, *stream);
  4358. continue;
  4359. }
  4360. const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  4361. for (int page = 0; page < pages; ++page)
  4362. {
  4363. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  4364. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  4365. {
  4366. juce::Graphics g (image);
  4367. g.fillAll (lynx::theme::panel);
  4368. editor->paintEntireComponent (g, false);
  4369. }
  4370. const auto file = out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png");
  4371. file.deleteFile();
  4372. juce::PNGImageFormat png;
  4373. if (auto stream = file.createOutputStream())
  4374. png.writeImageToStream (image, *stream);
  4375. }
  4376. }
  4377. // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
  4378. {
  4379. namespace ef = lynx::echosuite::echoform;
  4380. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  4381. fx.params[ef::rhythm] = 1.0f;
  4382. fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
  4383. fx.params[ef::rhythmDecay] = 0.25f;
  4384. fx.params[ef::rhythmTap1 + 2] = 0.45f;
  4385. fx.params[ef::feedback] = 0.25f;
  4386. fx.params[ef::era] = 0.5f;
  4387. for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
  4388. fx.params[(std::size_t) param] = value;
  4389. fx.params[ef::rhythmShape] = 0.5f; // swell
  4390. lynx::Song song;
  4391. song.mixer.resize (2);
  4392. song.mixer[0].name = "Master";
  4393. song.mixer[1].name = "Insert 1";
  4394. song.mixer[1].effects.push_back (fx);
  4395. offline.setSong (std::move (song));
  4396. offline.dispatchPendingMessages();
  4397. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  4398. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  4399. {
  4400. juce::Graphics g (image);
  4401. g.fillAll (lynx::theme::panel);
  4402. editor->paintEntireComponent (g, false);
  4403. }
  4404. const auto file = out.getChildFile ("Echoform-rhythm.png");
  4405. file.deleteFile();
  4406. juce::PNGImageFormat png;
  4407. if (auto stream = file.createOutputStream())
  4408. png.writeImageToStream (image, *stream);
  4409. }
  4410. // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
  4411. {
  4412. namespace ef = lynx::echosuite::echoform;
  4413. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  4414. fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
  4415. fx.params[ef::style] = ef::styleValue (ef::Style::dual);
  4416. lynx::Song song;
  4417. song.mixer.resize (2);
  4418. song.mixer[0].name = "Master";
  4419. song.mixer[1].name = "Insert 1";
  4420. song.mixer[1].effects.push_back (fx);
  4421. offline.setSong (std::move (song));
  4422. offline.dispatchPendingMessages();
  4423. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  4424. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  4425. {
  4426. juce::Graphics g (image);
  4427. g.fillAll (lynx::theme::panel);
  4428. editor->paintEntireComponent (g, false);
  4429. }
  4430. const auto file = out.getChildFile ("Echoform-voicing.png");
  4431. file.deleteFile();
  4432. juce::PNGImageFormat png;
  4433. if (auto stream = file.createOutputStream())
  4434. png.writeImageToStream (image, *stream);
  4435. }
  4436. // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
  4437. {
  4438. auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  4439. fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
  4440. fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
  4441. lynx::Song song;
  4442. song.mixer.resize (2);
  4443. song.mixer[0].name = "Master";
  4444. song.mixer[1].name = "Insert 1";
  4445. song.mixer[1].effects.push_back (fx);
  4446. offline.setSong (std::move (song));
  4447. offline.dispatchPendingMessages();
  4448. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  4449. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  4450. {
  4451. juce::Graphics g (image);
  4452. g.fillAll (lynx::theme::panel);
  4453. editor->paintEntireComponent (g, false);
  4454. }
  4455. const auto file = out.getChildFile ("Auto-pan-tweak.png");
  4456. file.deleteFile();
  4457. juce::PNGImageFormat png;
  4458. if (auto stream = file.createOutputStream())
  4459. png.writeImageToStream (image, *stream);
  4460. }
  4461. // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
  4462. {
  4463. namespace em = lynx::mixsuite::ember;
  4464. auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
  4465. fx.params[em::voicing] = 1.0f;
  4466. fx.params[em::classicDrive] = 0.35f;
  4467. lynx::Song song;
  4468. song.mixer.resize (2);
  4469. song.mixer[0].name = "Master";
  4470. song.mixer[1].name = "Insert 1";
  4471. song.mixer[1].effects.push_back (fx);
  4472. offline.setSong (std::move (song));
  4473. offline.dispatchPendingMessages();
  4474. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  4475. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  4476. {
  4477. juce::Graphics g (image);
  4478. g.fillAll (lynx::theme::panel);
  4479. editor->paintEntireComponent (g, false);
  4480. }
  4481. const auto file = out.getChildFile ("Ember Saturator-classic.png");
  4482. file.deleteFile();
  4483. juce::PNGImageFormat png;
  4484. if (auto stream = file.createOutputStream())
  4485. png.writeImageToStream (image, *stream);
  4486. }
  4487. // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
  4488. {
  4489. auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
  4490. fx.params[14] = 1.0f; // the measured plate voicing
  4491. fx.params[15] = 1.0f; // View = Plate
  4492. lynx::Song song;
  4493. song.mixer.resize (2);
  4494. song.mixer[0].name = "Master";
  4495. song.mixer[1].name = "Insert 1";
  4496. song.mixer[1].effects.push_back (fx);
  4497. offline.setSong (std::move (song));
  4498. offline.dispatchPendingMessages();
  4499. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  4500. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  4501. {
  4502. juce::Graphics g (image);
  4503. g.fillAll (lynx::theme::panel);
  4504. editor->paintEntireComponent (g, false);
  4505. }
  4506. const auto file = out.getChildFile ("Foil Plate-plate.png");
  4507. file.deleteFile();
  4508. juce::PNGImageFormat png;
  4509. if (auto stream = file.createOutputStream())
  4510. png.writeImageToStream (image, *stream);
  4511. }
  4512. // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
  4513. // and LYNX Tune (demo pitch phrase)
  4514. {
  4515. lynx::setNativeEditorDemo (true);
  4516. using namespace lynx::facet;
  4517. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  4518. const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
  4519. { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
  4520. { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
  4521. };
  4522. for (int b = 0; b < 5; ++b)
  4523. {
  4524. eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
  4525. eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
  4526. eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
  4527. eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
  4528. eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
  4529. eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
  4530. }
  4531. eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
  4532. const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
  4533. lynx::Song song;
  4534. song.mixer.resize (2);
  4535. song.mixer[0].name = "Master";
  4536. song.mixer[1].name = "Vocal";
  4537. song.mixer[1].effects.push_back (fx);
  4538. offline.setSong (std::move (song));
  4539. offline.dispatchPendingMessages();
  4540. auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
  4541. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  4542. {
  4543. juce::Graphics g (image);
  4544. g.fillAll (lynx::theme::panel);
  4545. editor->paintEntireComponent (g, false);
  4546. }
  4547. const auto f = out.getChildFile (file);
  4548. f.deleteFile();
  4549. juce::PNGImageFormat png;
  4550. if (auto stream = f.createOutputStream())
  4551. png.writeImageToStream (image, *stream);
  4552. };
  4553. own (eq, "Facet EQ.png", true);
  4554. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
  4555. {
  4556. // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
  4557. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  4558. tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
  4559. tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
  4560. tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
  4561. own (tune, "LYNX Tune-p2.png", false, 1);
  4562. }
  4563. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
  4564. lynx::setNativeEditorDemo (false);
  4565. }
  4566. // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
  4567. const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
  4568. for (auto [folder, preset] : std::vector<std::pair<const char*, const char*>> { { "3x Osc", "Default.fst" }, { "FL Keys", "Grand Piano.fst" }, { "BooBass", "" }, { "Sytrus", "Default.fst" }, { "Harmor", "Default.fst" } })
  4569. {
  4570. juce::MemoryBlock data;
  4571. if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
  4572. {
  4573. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  4574. files.sort();
  4575. for (const auto& f : files)
  4576. {
  4577. juce::MemoryBlock block;
  4578. if (! f.loadFileAsData (block))
  4579. continue;
  4580. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  4581. try
  4582. {
  4583. const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
  4584. if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
  4585. {
  4586. preset = nullptr;
  4587. data = block;
  4588. break;
  4589. }
  4590. }
  4591. catch (const std::exception&)
  4592. {
  4593. }
  4594. }
  4595. }
  4596. auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
  4597. : generators.getChildFile (folder).getChildFile (preset);
  4598. if (! file.existsAsFile())
  4599. {
  4600. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  4601. files.sort();
  4602. file = files.isEmpty() ? juce::File() : files[0];
  4603. }
  4604. if (data.isEmpty() && ! file.loadFileAsData (data))
  4605. continue;
  4606. try
  4607. {
  4608. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  4609. auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
  4610. if (project.channels.empty())
  4611. continue;
  4612. project.channels.front().type = flp::ChannelType::native;
  4613. lynx::FlpImportOptions options;
  4614. options.roots = roots;
  4615. options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
  4616. options.readFile = [] (const std::string& path) {
  4617. juce::MemoryBlock block;
  4618. lynx::platform::localFile (path).loadFileAsData (block);
  4619. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  4620. return std::vector<std::uint8_t> (b, b + block.getSize());
  4621. };
  4622. options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  4623. const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
  4624. f.getParentDirectory().createDirectory();
  4625. f.replaceWithData (wav.data(), wav.size());
  4626. return f.getFullPathName().toStdString();
  4627. };
  4628. auto song = lynx::importFlp (project, options);
  4629. // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
  4630. if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
  4631. {
  4632. song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
  4633. song.channels.front().modelParams.assign (3, 32768.0f);
  4634. }
  4635. if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
  4636. {
  4637. song.channels.front().instrument = lynx::InstrumentKind::flkeys;
  4638. song.channels.front().pluginState = project.channels.front().pluginState;
  4639. }
  4640. offline.setSong (std::move (song));
  4641. offline.dispatchPendingMessages();
  4642. if (offline.getSong().channels.empty())
  4643. continue;
  4644. auto panel = lynx::makeChannelSettingsPanel (offline, 0);
  4645. juce::Image image (juce::Image::ARGB, panel->getWidth(), panel->getHeight(), true);
  4646. {
  4647. juce::Graphics g (image);
  4648. g.fillAll (lynx::theme::panel);
  4649. panel->paintEntireComponent (g, false);
  4650. }
  4651. const auto out2 = out.getChildFile (juce::String (folder) + ".png");
  4652. out2.deleteFile();
  4653. juce::PNGImageFormat png;
  4654. if (auto stream = out2.createOutputStream())
  4655. png.writeImageToStream (image, *stream);
  4656. }
  4657. catch (const std::exception&)
  4658. {
  4659. }
  4660. }
  4661. }
  4662. quit();
  4663. }
  4664. void runDanceShot (const juce::String& prefix)
  4665. {
  4666. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4667. // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
  4668. {
  4669. constexpr int cell = 120, cols = 8;
  4670. juce::Image sheet (juce::Image::ARGB, 130 + cols * cell, lynx::dance::moveCount * cell + 10, true);
  4671. juce::Graphics g (sheet);
  4672. g.fillAll (lynx::theme::colour::bg0);
  4673. for (int m = 0; m < lynx::dance::moveCount; ++m)
  4674. {
  4675. g.setColour (lynx::theme::colour::textSecondary);
  4676. g.setFont (14.0f);
  4677. g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
  4678. for (int k = 0; k < cols; ++k)
  4679. {
  4680. const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
  4681. lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
  4682. }
  4683. }
  4684. savePng (sheet, prefix + "-moves.png");
  4685. }
  4686. lynx::AudioEngine offline (false);
  4687. lynx::Song song;
  4688. song.mixer = lynx::Song::defaultMixer (2);
  4689. for (int d = 0; d < 2; ++d)
  4690. {
  4691. lynx::ChannelDef c;
  4692. c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
  4693. c.instrument = lynx::InstrumentKind::fruitydance;
  4694. lynx::dance::Settings s;
  4695. s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
  4696. s.x = d == 0 ? 520 : 760;
  4697. s.y = 560;
  4698. s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
  4699. s.mirrored = d == 1;
  4700. c.pluginState = lynx::dance::toState (s);
  4701. song.channels.push_back (c);
  4702. }
  4703. song.patterns.emplace_back();
  4704. {
  4705. const juce::File demo (prefix + "-demo.lynx");
  4706. juce::String error;
  4707. lynx::ProjectFile::save (song, demo, error);
  4708. }
  4709. offline.setSong (std::move (song));
  4710. offline.dispatchPendingMessages();
  4711. if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
  4712. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
  4713. if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
  4714. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-frame.png");
  4715. }
  4716. void runControllerShot (const juce::String& prefix)
  4717. {
  4718. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4719. lynx::AudioEngine offline (false);
  4720. lynx::Song song;
  4721. song.mixer = lynx::Song::defaultMixer (2);
  4722. song.mixer[1].name = "Insert 1";
  4723. auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
  4724. lynx::formula::State formula;
  4725. formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
  4726. fx.state = lynx::formula::writeState (formula);
  4727. fx.params[0] = 0.5f;
  4728. fx.params[1] = 0.25f;
  4729. fx.params[2] = 0.5f;
  4730. song.mixer[1].effects.push_back (fx);
  4731. // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
  4732. {
  4733. auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
  4734. xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
  4735. xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
  4736. xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
  4737. song.mixer[1].effects.push_back (xyFx);
  4738. auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
  4739. xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
  4740. song.mixer[1].effects.push_back (xyzFx);
  4741. // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
  4742. xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
  4743. xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
  4744. xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
  4745. xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
  4746. song.mixer[1].effects.push_back (xyzFx);
  4747. auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
  4748. lynx::SurfaceControl c;
  4749. for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
  4750. { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
  4751. { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
  4752. { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
  4753. { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
  4754. { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
  4755. { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
  4756. {
  4757. c.kind = kind;
  4758. c.name = name;
  4759. c.value = v;
  4760. c.valueY = 0.6f;
  4761. c.x = x;
  4762. c.y = y;
  4763. lynx::surface::add (panel, c);
  4764. }
  4765. song.mixer[1].effects.push_back (panel);
  4766. }
  4767. lynx::ChannelDef env;
  4768. env.name = "Envelope Controller";
  4769. env.instrument = lynx::InstrumentKind::controller;
  4770. auto ecData = lynx::defaultEnvelopeController();
  4771. ecData[0].lfoOn = true;
  4772. ecData[0].lfoTempo = true;
  4773. ecData[0].lfoSpeed = 40898;
  4774. ecData[0].maps[lynx::mapKeyboard].count = 2;
  4775. ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  4776. ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  4777. ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
  4778. env.controllerState = lynx::writeEnvelopeController (ecData);
  4779. song.channels.push_back (env);
  4780. lynx::ChannelDef out;
  4781. out.name = "MIDI Out";
  4782. out.instrument = lynx::InstrumentKind::midiOut;
  4783. lynx::midictl::MidiOutSettings settings;
  4784. settings.port = 1;
  4785. lynx::midictl::writeMidiOut (out.pluginState, settings);
  4786. song.channels.push_back (out);
  4787. // a Layer (round 164) over three synths split across the keyboard, crossfading
  4788. for (const auto* name : { "Bass", "Pad", "Lead" })
  4789. {
  4790. lynx::ChannelDef c;
  4791. c.name = name;
  4792. c.instrument = lynx::InstrumentKind::synth;
  4793. song.channels.push_back (c);
  4794. }
  4795. {
  4796. lynx::ChannelDef layer;
  4797. layer.name = "Layer";
  4798. layer.instrument = lynx::InstrumentKind::layer;
  4799. song.channels.push_back (layer);
  4800. const auto self = (int) song.channels.size() - 1;
  4801. lynx::layer::setChildren (song, self, { 2, 3, 4 });
  4802. song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
  4803. song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
  4804. song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
  4805. song.channels[(std::size_t) self].layer.crossfade = true;
  4806. song.channels[(std::size_t) self].layer.fade = 0.35f;
  4807. }
  4808. {
  4809. lynx::ChannelDef dash; // channel 6
  4810. dash.name = "Dashboard";
  4811. dash.instrument = lynx::InstrumentKind::dashboard;
  4812. dash.patcher.surface = lynx::surface::starterControls();
  4813. song.channels.push_back (dash);
  4814. }
  4815. {
  4816. lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
  4817. volt.name = "Voltage Controller";
  4818. volt.instrument = lynx::InstrumentKind::voltage;
  4819. lynx::voltage::Settings v;
  4820. v.enabled = true;
  4821. v.params[9] = 49152;
  4822. v.unipolar[2] = true;
  4823. v.tracks = { 3, 0, 0 };
  4824. v.source[6] = lynx::voltage::Source::clock;
  4825. volt.pluginState = lynx::voltage::write (v);
  4826. song.channels.push_back (volt);
  4827. }
  4828. song.patterns.emplace_back();
  4829. offline.setSong (std::move (song));
  4830. offline.dispatchPendingMessages();
  4831. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  4832. if (c == nullptr)
  4833. return;
  4834. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
  4835. };
  4836. shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
  4837. shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
  4838. shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
  4839. shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
  4840. {
  4841. const auto slotOf = [] (int k) -> lynx::SlotLocator {
  4842. return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
  4843. };
  4844. const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
  4845. shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
  4846. shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
  4847. shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
  4848. shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
  4849. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
  4850. shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
  4851. }
  4852. // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
  4853. if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
  4854. for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
  4855. {
  4856. juce::MemoryBlock bytes;
  4857. if (! file.loadFileAsData (bytes))
  4858. continue;
  4859. const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
  4860. const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
  4861. if (! dash || dash->controls.empty())
  4862. continue;
  4863. offline.editSong ([&] (lynx::Song& s) {
  4864. s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
  4865. s.channels[6].patcher.surface = dash->controls;
  4866. s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
  4867. });
  4868. offline.dispatchPendingMessages();
  4869. const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
  4870. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
  4871. // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
  4872. if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
  4873. {
  4874. std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
  4875. for (auto* child : c.getChildren())
  4876. {
  4877. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
  4878. b->setToggleState (true, juce::sendNotificationSync);
  4879. pressEdit (*child);
  4880. }
  4881. };
  4882. pressEdit (*panel);
  4883. shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
  4884. }
  4885. }
  4886. // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
  4887. if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
  4888. for (int part = 0; part < 7; ++part)
  4889. {
  4890. for (auto* child : ec->getChildren())
  4891. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  4892. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  4893. savePng (ec->createComponentSnapshot (ec->getLocalBounds()), prefix + "-ec-part" + juce::String (part) + ".png");
  4894. }
  4895. lynx::FormulaControllerWindows::open (offline, 1, 0);
  4896. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  4897. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  4898. if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
  4899. savePng (w->getContentComponent()->createComponentSnapshot (w->getContentComponent()->getLocalBounds()), prefix + "-formula-controller.png");
  4900. lynx::FormulaControllerWindows::closeAll();
  4901. }
  4902. void runVfxShot (const juce::String& prefix)
  4903. {
  4904. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4905. lynx::AudioEngine offline (false);
  4906. lynx::MainComponent ui (offline, false);
  4907. ui.setSize (1280, 720);
  4908. auto song = lynx::Song::makeDefault();
  4909. song.channels.clear();
  4910. for (const auto kind : lynx::vfx::allKinds)
  4911. {
  4912. lynx::ChannelDef c;
  4913. lynx::vfx::makeChannel (c, kind);
  4914. if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
  4915. for (const auto& p : lynx::vfx::builtInPresets (kind))
  4916. if (p.name == "Major triad")
  4917. {
  4918. auto st = *lynx::vfx::readState (c.pluginState);
  4919. st.fl = p.fl;
  4920. c.pluginState = lynx::vfx::writeState (st);
  4921. }
  4922. song.channels.push_back (c);
  4923. }
  4924. // a Patcher: its notes through a Color Mapper to three synths
  4925. lynx::ChannelDef patcher;
  4926. patcher.name = "Patcher";
  4927. patcher.instrument = lynx::InstrumentKind::patcher;
  4928. lynx::PatchNode mapper;
  4929. mapper.generator = true;
  4930. lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
  4931. mapper.x = 260.0f;
  4932. patcher.patcher.nodes.push_back (mapper);
  4933. lynx::PatchWire notes;
  4934. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  4935. patcher.patcher.wires.push_back (notes);
  4936. for (int k = 0; k < 3; ++k)
  4937. {
  4938. lynx::PatchNode synth;
  4939. synth.generator = true;
  4940. synth.channel.instrument = lynx::InstrumentKind::synth;
  4941. synth.channel.name = "Synth " + std::to_string (k + 1);
  4942. synth.x = 520.0f, synth.y = (float) k * 90.0f;
  4943. patcher.patcher.nodes.push_back (synth);
  4944. lynx::PatchWire in, out;
  4945. in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
  4946. out.from = 1 + k, out.to = lynx::patchToHost;
  4947. patcher.patcher.wires.push_back (in);
  4948. patcher.patcher.wires.push_back (out);
  4949. }
  4950. patcher.patcher.outputX = 760.0f;
  4951. song.channels.push_back (patcher);
  4952. offline.setSong (std::move (song));
  4953. offline.dispatchPendingMessages();
  4954. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  4955. if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
  4956. {
  4957. offline.dispatchPendingMessages();
  4958. savePng (panel->createComponentSnapshot (panel->getLocalBounds()),
  4959. prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
  4960. }
  4961. // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
  4962. // a Script with FL's "Snap To Scale"
  4963. if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
  4964. {
  4965. const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
  4966. const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
  4967. { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
  4968. { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
  4969. };
  4970. for (const auto& [kind, path] : extra)
  4971. {
  4972. juce::MemoryBlock bytes;
  4973. if (! data.getChildFile (path).loadFileAsData (bytes))
  4974. continue;
  4975. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  4976. const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
  4977. int index = -1;
  4978. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  4979. if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
  4980. index = c;
  4981. if (! fl || index < 0)
  4982. continue;
  4983. offline.editSong ([&] (lynx::Song& s) {
  4984. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  4985. st.fl = *fl;
  4986. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  4987. });
  4988. offline.dispatchPendingMessages();
  4989. if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
  4990. {
  4991. offline.dispatchPendingMessages();
  4992. savePng (panel->createComponentSnapshot (panel->getLocalBounds()),
  4993. prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase() + "-fl.png");
  4994. }
  4995. }
  4996. }
  4997. lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
  4998. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  4999. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  5000. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  5001. {
  5002. auto* content = w->getContentComponent();
  5003. savePng (content->createComponentSnapshot (content->getLocalBounds()), prefix + "-patcher.png");
  5004. delete w;
  5005. break;
  5006. }
  5007. lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
  5008. savePng (image, prefix + "-patcher-menu-" + name + ".png");
  5009. });
  5010. }
  5011. void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
  5012. {
  5013. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5014. lynx::AudioEngine offline (false);
  5015. {
  5016. lynx::MainComponent ui (offline, false);
  5017. ui.setSize (1280, 720);
  5018. if (projectPath.isNotEmpty())
  5019. ui.openFile (juce::File (projectPath));
  5020. else
  5021. {
  5022. auto song = lynx::Song::makeDefault();
  5023. song.mixer.resize (4);
  5024. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  5025. slot.patcher.wires.clear();
  5026. for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
  5027. { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
  5028. {
  5029. lynx::PatchNode n;
  5030. n.effect = lynx::makeEffectSlot (kind);
  5031. n.x = x;
  5032. n.y = y;
  5033. slot.patcher.nodes.push_back (n);
  5034. }
  5035. auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
  5036. lynx::PatchWire w;
  5037. w.kind = kind;
  5038. w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
  5039. slot.patcher.wires.push_back (w);
  5040. };
  5041. wire (lynx::patchFromHost, 0, 0, 0);
  5042. wire (0, 1, 1, 0);
  5043. wire (0, 3, 2, 0, 0.5f);
  5044. wire (1, 0, lynx::patchToHost, 0);
  5045. wire (2, 0, lynx::patchToHost, 0);
  5046. wire (lynx::patchFromHost, 1, 3, 0);
  5047. wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  5048. wire (0, 2, lynx::patchToHost, 1, 0.7f);
  5049. slot.patcher.outputTracks = { 3 };
  5050. slot.patcher.inputX = -20.0f;
  5051. slot.patcher.outputX = 660.0f;
  5052. song.mixer[1].effects = { slot };
  5053. lynx::ChannelDef ch;
  5054. ch.name = "Patcher";
  5055. ch.instrument = lynx::InstrumentKind::patcher;
  5056. lynx::PatchNode synth, chorus;
  5057. synth.generator = true;
  5058. synth.channel.instrument = lynx::InstrumentKind::synth;
  5059. synth.channel.name = "Synth";
  5060. synth.x = 220.0f;
  5061. chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
  5062. chorus.x = 420.0f;
  5063. // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
  5064. // on the notes moving the chorus
  5065. lynx::PatchNode midiOut, envelope;
  5066. midiOut.generator = envelope.generator = true;
  5067. midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
  5068. midiOut.channel.name = "MIDI Out";
  5069. lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
  5070. midiOut.x = 220.0f, midiOut.y = 160.0f;
  5071. envelope.channel.instrument = lynx::InstrumentKind::controller;
  5072. envelope.channel.name = "Envelope Controller";
  5073. envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  5074. envelope.x = 220.0f, envelope.y = 260.0f;
  5075. lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
  5076. osc.generator = true;
  5077. osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  5078. osc.channel.instrument = lynx::InstrumentKind::threeosc;
  5079. osc.channel.name = "3x Osc";
  5080. osc.x = 420.0f, osc.y = 260.0f;
  5081. ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc };
  5082. lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
  5083. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  5084. a.from = 0, a.to = 1;
  5085. b.from = 1;
  5086. portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
  5087. portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
  5088. envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
  5089. envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
  5090. lynx::PatchWire oscNotes, oscOut;
  5091. oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
  5092. oscOut.from = 4;
  5093. ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut };
  5094. ch.patcher.fromMidiPorts = { 1, 5 };
  5095. ch.patcher.toMidiPorts = { 3 };
  5096. ch.patcher.outputX = 640.0f;
  5097. song.channels.push_back (ch);
  5098. // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
  5099. if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
  5100. {
  5101. if (! song.patterns.empty())
  5102. for (int k = 0; k < 4; ++k)
  5103. song.patterns[0].notes.push_back ({ (std::int64_t) k * lynx::ppq, lynx::ppq / 2, (int) song.channels.size() - 1, 60 + 4 * k, 0.8f });
  5104. juce::String error;
  5105. lynx::ProjectFile::save (song, juce::File (save), error);
  5106. }
  5107. offline.setSong (std::move (song));
  5108. }
  5109. offline.dispatchPendingMessages();
  5110. const auto& song = offline.getSong();
  5111. auto shootOpen = [&] (const juce::String& name) {
  5112. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  5113. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  5114. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  5115. {
  5116. auto* c = w->getContentComponent();
  5117. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
  5118. delete w;
  5119. return;
  5120. }
  5121. };
  5122. int shots = 0;
  5123. for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
  5124. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  5125. if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
  5126. {
  5127. lynx::PatcherWindows::openSlot (offline, t, s);
  5128. shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
  5129. ++shots;
  5130. if (shots == 1) // its menus (round 162)
  5131. lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
  5132. savePng (image, prefix + "-menu-" + name + ".png");
  5133. });
  5134. }
  5135. for (int c = 0; c < (int) song.channels.size(); ++c)
  5136. if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
  5137. {
  5138. lynx::PatcherWindows::openChannel (offline, c);
  5139. shootOpen ("-channel" + juce::String (c) + ".png");
  5140. // each built-in generator node's editor, as a double-click opens it (round 164f)
  5141. for (int n = 0; n < (int) song.channels[(std::size_t) c].patcher.nodes.size(); ++n)
  5142. if (const auto& node = song.channels[(std::size_t) c].patcher.nodes[(std::size_t) n]; node.generator && lynx::hasNodeEditor (node.channel))
  5143. if (auto frame = lynx::makeNodeChannelFrame (offline, [c, n] (lynx::Song& sg) -> lynx::ChannelDef* {
  5144. return c < (int) sg.channels.size() && n < (int) sg.channels[(std::size_t) c].patcher.nodes.size()
  5145. ? &sg.channels[(std::size_t) c].patcher.nodes[(std::size_t) n].channel
  5146. : nullptr;
  5147. }))
  5148. {
  5149. offline.dispatchPendingMessages();
  5150. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
  5151. }
  5152. lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
  5153. savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
  5154. });
  5155. }
  5156. }
  5157. }
  5158. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  5159. {
  5160. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5161. // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
  5162. if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
  5163. if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
  5164. lynx::themeui::apply (*spec, false);
  5165. {
  5166. lynx::AudioEngine offline (false);
  5167. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  5168. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  5169. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  5170. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  5171. if (projectPath.isNotEmpty())
  5172. ui.openFile (juce::File (projectPath));
  5173. offline.dispatchPendingMessages(); // change notifications are asynchronous
  5174. ui.waitForBrowserForSnapshot();
  5175. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  5176. // (and a sample hint in the status strip, as when hovering a knob)
  5177. ui.showDesktopForSnapshot (false);
  5178. ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
  5179. offline.dispatchPendingMessages();
  5180. saveSnapshot (ui, prefix + "-desktop.png");
  5181. // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
  5182. {
  5183. const auto size = ui.getBounds();
  5184. ui.showSetupWizard();
  5185. offline.dispatchPendingMessages();
  5186. saveSnapshot (ui, prefix + "-desktop-setup.png");
  5187. ui.setSize (1024, 600);
  5188. offline.dispatchPendingMessages();
  5189. saveSnapshot (ui, prefix + "-desktop-setup-small.png");
  5190. ui.closeSetupWizardForSnapshot();
  5191. ui.setBounds (size);
  5192. offline.dispatchPendingMessages();
  5193. }
  5194. // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
  5195. // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
  5196. {
  5197. const auto size = ui.getBounds();
  5198. for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 } })
  5199. {
  5200. ui.setSize (w, h);
  5201. offline.dispatchPendingMessages();
  5202. saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
  5203. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
  5204. if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
  5205. {
  5206. ui.scrollRackForSnapshot (100000);
  5207. offline.dispatchPendingMessages();
  5208. saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
  5209. ui.scrollRackForSnapshot (0);
  5210. }
  5211. }
  5212. // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
  5213. ui.setSize (1600, 900);
  5214. for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
  5215. {
  5216. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  5217. layout.iconSize = iconSize;
  5218. ui.setToolbarLayoutForSnapshot (layout);
  5219. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
  5220. }
  5221. {
  5222. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  5223. layout.move (lynx::toolbarlayout::Group::windows, -3);
  5224. layout.setShown (lynx::toolbarlayout::Group::record, false);
  5225. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  5226. ui.setToolbarLayoutForSnapshot (layout);
  5227. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
  5228. }
  5229. {
  5230. // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
  5231. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  5232. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  5233. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  5234. ui.setToolbarLayoutForSnapshot (layout);
  5235. ui.setToolbarEditingForSnapshot (true);
  5236. offline.dispatchPendingMessages();
  5237. saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
  5238. ui.setToolbarEditingForSnapshot (false);
  5239. // Ctrl+F11: only the menu and the hint bar
  5240. layout = lynx::toolbarlayout::Layout::makeDefault();
  5241. layout.visible = false;
  5242. ui.setToolbarLayoutForSnapshot (layout);
  5243. saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
  5244. }
  5245. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  5246. // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
  5247. offline.dispatchPendingMessages();
  5248. saveQuickTips (ui, prefix);
  5249. ui.setBounds (size);
  5250. offline.dispatchPendingMessages();
  5251. }
  5252. // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
  5253. // glyphs, and a text too long for one line (two lines)
  5254. {
  5255. const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
  5256. const lynx::ui::Hint hints[] = {
  5257. { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
  5258. { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
  5259. { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  5260. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
  5261. };
  5262. for (int i = 0; i < 3; ++i)
  5263. {
  5264. ui.setHintForSnapshot (hints[i], i == 0);
  5265. saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
  5266. }
  5267. }
  5268. ui.showDesktopForSnapshot (true);
  5269. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  5270. saveSnapshot (ui, prefix + "-desktop-all.png");
  5271. ui.selectTabForSnapshot (0);
  5272. saveSnapshot (ui, prefix + "-rack.png");
  5273. {
  5274. // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
  5275. int found = -1;
  5276. const auto before = offline.getSong().currentPattern;
  5277. {
  5278. const auto& song = offline.getSong();
  5279. for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
  5280. for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
  5281. if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
  5282. found = p;
  5283. }
  5284. if (found >= 0)
  5285. {
  5286. offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
  5287. offline.dispatchPendingMessages();
  5288. saveSnapshot (ui, prefix + "-rack-preview.png");
  5289. offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
  5290. offline.dispatchPendingMessages();
  5291. }
  5292. }
  5293. ui.selectTabForSnapshot (1);
  5294. saveSnapshot (ui, prefix + "-pianoroll.png");
  5295. if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
  5296. saveArea (ui, strip, prefix + "-pianoroll-tools.png");
  5297. // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
  5298. ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
  5299. saveSnapshot (ui, prefix + "-pianoroll-hover.png");
  5300. ui.selectTabForSnapshot (2);
  5301. saveSnapshot (ui, prefix + "-playlist.png");
  5302. if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
  5303. saveArea (ui, strip, prefix + "-playlist-tools.png");
  5304. ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
  5305. saveSnapshot (ui, prefix + "-playlist-hover.png");
  5306. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  5307. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  5308. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  5309. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  5310. offline.dispatchPendingMessages();
  5311. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  5312. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  5313. // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
  5314. {
  5315. int header = -1;
  5316. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
  5317. if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
  5318. header = t;
  5319. if (header >= 0)
  5320. {
  5321. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
  5322. offline.dispatchPendingMessages();
  5323. saveSnapshot (ui, prefix + "-playlist-group-folded.png");
  5324. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
  5325. }
  5326. ui.getPickerForSnapshot().setView (1);
  5327. offline.dispatchPendingMessages();
  5328. saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
  5329. ui.getPickerForSnapshot().setView (0);
  5330. }
  5331. // round 104: the Channel Rack filtered to its first filter group
  5332. if (! offline.getSong().channelGroups.empty())
  5333. {
  5334. ui.selectTabForSnapshot (0);
  5335. ui.getRackForSnapshot().setFilterGroup (0);
  5336. offline.dispatchPendingMessages();
  5337. saveSnapshot (ui, prefix + "-rack-filter.png");
  5338. ui.getRackForSnapshot().setFilterGroup (-1);
  5339. }
  5340. ui.selectTabForSnapshot (3);
  5341. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  5342. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  5343. {
  5344. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  5345. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  5346. offline.dispatchPendingMessages();
  5347. }
  5348. saveSnapshot (ui, prefix + "-mixer.png");
  5349. // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
  5350. {
  5351. const auto size = ui.getBounds();
  5352. for (auto h : { 450, 560, 680, 820 })
  5353. {
  5354. ui.setSize (size.getWidth(), h);
  5355. offline.dispatchPendingMessages();
  5356. saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
  5357. }
  5358. ui.setBounds (size);
  5359. offline.dispatchPendingMessages();
  5360. }
  5361. // standalone windows, with the theme background
  5362. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  5363. juce::Component frame;
  5364. frame.setSize (c->getWidth(), c->getHeight());
  5365. frame.setOpaque (true);
  5366. frame.addAndMakeVisible (*c);
  5367. c->setTopLeftPosition (0, 0);
  5368. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  5369. {
  5370. juce::Graphics g (image);
  5371. g.fillAll (lynx::theme::panel);
  5372. frame.paintEntireComponent (g, false);
  5373. }
  5374. const juce::File file (prefix + name);
  5375. file.deleteFile();
  5376. juce::PNGImageFormat png;
  5377. if (auto out = file.createOutputStream())
  5378. png.writeImageToStream (image, *out);
  5379. };
  5380. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  5381. saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
  5382. saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
  5383. saveSplashFrames (prefix);
  5384. saveIconSheet (prefix + "-icons.png", 1.0f);
  5385. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  5386. saveWindow (lynx::MainComponent::makeHelpContent(), "-help.png");
  5387. saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
  5388. // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
  5389. offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
  5390. offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
  5391. saveMenus (ui, prefix + "-menus.png");
  5392. {
  5393. // the windows' own menus (title bars) and the toolbar's recording menu
  5394. juce::StringArray names;
  5395. std::vector<juce::PopupMenu> menus;
  5396. for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
  5397. { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
  5398. { lynx::workspace::Panel::browser, "Browser" } })
  5399. {
  5400. names.add (name);
  5401. menus.push_back (ui.getPanelMenuForSnapshot (panel));
  5402. }
  5403. names.add ("Recording");
  5404. menus.push_back (ui.getRecordMenuForSnapshot());
  5405. names.add ("Toolbar");
  5406. menus.push_back (ui.getToolbarMenuForSnapshot());
  5407. saveMenus (names, menus, prefix + "-panel-menus.png");
  5408. }
  5409. {
  5410. // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
  5411. std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
  5412. ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
  5413. ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
  5414. saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
  5415. // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
  5416. {
  5417. juce::PopupMenu folder;
  5418. folder.addSectionHeader ("Documents");
  5419. folder.addItem (1, "Expand all");
  5420. folder.addItem (2, "Collapse all");
  5421. folder.addSeparator();
  5422. folder.addItem (3, "Refresh");
  5423. folder.addSectionHeader ("System");
  5424. folder.addItem (4, "Open");
  5425. folder.addItem (5, "Copy the file path");
  5426. folder.addSectionHeader ("Tags");
  5427. folder.addItem (6, "Starred", true, true);
  5428. folder.addSeparator();
  5429. folder.addItem (7, "Add folder...");
  5430. const auto wasCompact = lynx::theme::menus::compact();
  5431. lynx::theme::menus::setCompact (true);
  5432. saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
  5433. lynx::theme::menus::setCompact (false);
  5434. saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
  5435. lynx::theme::menus::setCompact (wasCompact);
  5436. }
  5437. // and the clip menus of the first pattern, audio and automation clips of the project
  5438. juce::StringArray clipNames;
  5439. std::vector<juce::PopupMenu> clipMenus;
  5440. for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
  5441. { lynx::ClipKind::automation, "Automation clip" } })
  5442. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  5443. if (offline.getSong().playlist[(std::size_t) c].kind == kind)
  5444. {
  5445. clipNames.add (name);
  5446. clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
  5447. break;
  5448. }
  5449. if (! clipMenus.empty())
  5450. saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
  5451. }
  5452. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  5453. alert->setOpaque (true);
  5454. saveWindow (std::move (alert), name);
  5455. };
  5456. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  5457. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  5458. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  5459. saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
  5460. saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
  5461. saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
  5462. saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
  5463. saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
  5464. saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
  5465. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
  5466. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
  5467. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
  5468. {
  5469. // the Settings pages, with credits like a project imported from FL would carry
  5470. offline.editSong ([] (lynx::Song& s) {
  5471. s.info = { "Night Drive", "LYNX demo", "Synthwave", "https://lynx-share.com",
  5472. "Made with LYNX.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  5473. }, false);
  5474. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
  5475. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
  5476. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
  5477. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
  5478. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
  5479. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
  5480. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
  5481. saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
  5482. saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
  5483. }
  5484. {
  5485. // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
  5486. saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
  5487. const auto& clips = offline.getSong().playlist;
  5488. for (int i = 0; i < (int) clips.size(); ++i)
  5489. if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
  5490. {
  5491. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
  5492. break;
  5493. }
  5494. for (int i = 0; i < (int) clips.size(); ++i)
  5495. if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
  5496. {
  5497. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
  5498. break;
  5499. }
  5500. if (offline.getSong().arrangements.size() < 2)
  5501. offline.editSong ([] (lynx::Song& s) {
  5502. const auto current = s.currentArrangement;
  5503. s.addArrangement ("Radio edit", true);
  5504. s.addArrangement ("Intro loop");
  5505. s.selectArrangement (current);
  5506. }, false);
  5507. saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
  5508. saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
  5509. saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
  5510. }
  5511. {
  5512. // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
  5513. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
  5514. {
  5515. juce::AudioBuffer<float> line (1, 44100 * 2);
  5516. const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
  5517. double ph = 0.0;
  5518. for (int i = 0; i < line.getNumSamples(); ++i)
  5519. {
  5520. const auto f0 = hz[std::min (4, i / 17640)];
  5521. ph += 2.0 * juce::MathConstants<double>::pi * f0 * (1.0 + 0.004 * std::sin (2.0 * juce::MathConstants<double>::pi * 5.5 * i / 44100.0)) / 44100.0;
  5522. float v = 0.0f;
  5523. for (int h = 1; f0 > 0.0 && h < 8; ++h)
  5524. v += (float) (0.3 / h * std::sin (h * ph));
  5525. line.setSample (0, i, v);
  5526. }
  5527. wav.deleteFile();
  5528. juce::WavAudioFormat format;
  5529. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  5530. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
  5531. {
  5532. out.release();
  5533. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  5534. writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
  5535. }
  5536. }
  5537. if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
  5538. {
  5539. auto notes = lynx::newtonefx::analyseNotes (*sample);
  5540. if (notes.pitches.size() > 1)
  5541. notes.pitches[1].shift = 2.0;
  5542. lynx::newtonefx::WarpMap warp;
  5543. warp.frames = (std::int64_t) sample->frames();
  5544. warp.markers = { { 22050, 33075 } };
  5545. int at = 0;
  5546. offline.editSong ([&] (lynx::Song& song) {
  5547. if (song.mixer.size() < 2)
  5548. song.mixer.resize (2);
  5549. auto& fx = song.mixer[1].effects;
  5550. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  5551. tone.samplePath = wav.getFullPathName().toStdString();
  5552. tone.state = lynx::newtonefx::writeNative (notes);
  5553. auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
  5554. time.samplePath = tone.samplePath;
  5555. time.state = lynx::newtonefx::writeWarp (warp);
  5556. at = (int) fx.size();
  5557. fx.push_back (tone);
  5558. fx.push_back (time);
  5559. }, false);
  5560. saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
  5561. saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
  5562. offline.editSong ([at] (lynx::Song& song) {
  5563. auto& fx = song.mixer[1].effects;
  5564. fx.erase (fx.begin() + at, fx.begin() + at + 2);
  5565. }, false);
  5566. }
  5567. }
  5568. if (! offline.getSong().automations.empty())
  5569. {
  5570. auto editor = lynx::makeAutomationEditor (offline, 0);
  5571. editor->setSize (760, 300);
  5572. saveWindow (std::move (editor), "-automation.png");
  5573. }
  5574. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  5575. // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
  5576. saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
  5577. saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
  5578. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  5579. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  5580. {
  5581. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  5582. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  5583. break;
  5584. }
  5585. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  5586. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  5587. {
  5588. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  5589. break;
  5590. }
  5591. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  5592. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  5593. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  5594. {
  5595. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  5596. break;
  5597. }
  5598. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  5599. {
  5600. int bestTrack = -1, bestSlot = -1;
  5601. double bestShape = -1.0;
  5602. const auto& mixer = offline.getSong().mixer;
  5603. for (int t = 0; t < (int) mixer.size(); ++t)
  5604. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  5605. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  5606. {
  5607. double shape = 0.0;
  5608. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  5609. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  5610. if (shape > bestShape)
  5611. {
  5612. bestShape = shape;
  5613. bestTrack = t;
  5614. bestSlot = s;
  5615. }
  5616. }
  5617. if (bestTrack >= 0)
  5618. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  5619. }
  5620. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  5621. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  5622. saveWindow (std::move (inspector), "-noteinspector.png");
  5623. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  5624. saveWindow (std::move (inspector), "-noteinspector-one.png");
  5625. // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
  5626. {
  5627. auto& roll = ui.getPianoRollForSnapshot();
  5628. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
  5629. { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
  5630. { lynx::NoteTool::flip, "-tool-flip.png" },
  5631. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  5632. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  5633. { lynx::NoteTool::limit, "-tool-limit.png" },
  5634. { lynx::NoteTool::quantize, "-tool-quantize.png" },
  5635. { lynx::NoteTool::chop, "-tool-chop.png" },
  5636. { lynx::NoteTool::flam, "-tool-flam.png" },
  5637. { lynx::NoteTool::lfo, "-tool-lfo.png" },
  5638. { lynx::NoteTool::claw, "-tool-claw.png" },
  5639. { lynx::NoteTool::articulate, "-tool-articulate.png" },
  5640. { lynx::NoteTool::riffMachine, "-tool-riff.png" },
  5641. { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
  5642. for (const auto& [tool, name] : tools)
  5643. saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
  5644. }
  5645. // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
  5646. {
  5647. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
  5648. const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
  5649. offline.editSong ([&] (lynx::Song& s) {
  5650. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
  5651. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
  5652. lynx::prtools::LfoOptions lfo;
  5653. lfo.startSpeed = 7 * 4096; // one beat
  5654. lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
  5655. }, false);
  5656. saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
  5657. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  5658. }
  5659. // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
  5660. // and its menu items (-audioeditor-menu.txt)
  5661. {
  5662. namespace ae = lynx::audioedit;
  5663. ae::Document d;
  5664. d.title = "Drum loop";
  5665. d.audio.sampleRate = 44100.0;
  5666. const auto frames = (std::size_t) (44100 * 2);
  5667. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  5668. std::uint32_t seed = 7;
  5669. for (int hit = 0; hit < 8; ++hit)
  5670. {
  5671. const auto at = (std::size_t) hit * frames / 8;
  5672. const auto kick = hit % 2 == 0;
  5673. double phase = 0.0;
  5674. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  5675. {
  5676. seed = seed * 1664525u + 1013904223u;
  5677. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  5678. const auto t = (double) i / 44100.0;
  5679. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  5680. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  5681. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  5682. d.audio.channels[0][at + i] += v;
  5683. d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
  5684. }
  5685. }
  5686. ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
  5687. ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
  5688. ae::setLoop (d, { 0, (std::int64_t) frames });
  5689. auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
  5690. juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
  5691. saveWindow (std::move (wave), "-audioeditor.png");
  5692. saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
  5693. }
  5694. // the tempo tapper after five steady taps (round 132)
  5695. saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
  5696. // the Channel Rack's piano-roll view (round 132)
  5697. ui.selectTabForSnapshot (0);
  5698. ui.getRackForSnapshot().setPianoRollView (true);
  5699. offline.dispatchPendingMessages();
  5700. saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
  5701. ui.getRackForSnapshot().setPianoRollView (false);
  5702. // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
  5703. ui.selectTabForSnapshot (0);
  5704. ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
  5705. offline.dispatchPendingMessages();
  5706. saveSnapshot (ui, prefix + "-rack-graph.png");
  5707. ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
  5708. saveSnapshot (ui, prefix + "-rack-graph-pan.png");
  5709. ui.getRackForSnapshot().toggleGraphLanes();
  5710. saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
  5711. // the Mixer with three inserts selected and one armed for recording
  5712. ui.selectTabForSnapshot (3);
  5713. if (offline.getSong().mixer.size() > 4)
  5714. {
  5715. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
  5716. offline.setInsertArmed (3, true);
  5717. offline.dispatchPendingMessages();
  5718. saveSnapshot (ui, prefix + "-mixer-multi.png");
  5719. // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
  5720. offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
  5721. ui.getMixerForSnapshot().selectTrack (3);
  5722. offline.dispatchPendingMessages();
  5723. saveSnapshot (ui, prefix + "-mixer-input.png");
  5724. offline.undo();
  5725. offline.setInsertArmed (3, false);
  5726. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
  5727. }
  5728. // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
  5729. if (offline.getSong().mixer.size() > 6)
  5730. {
  5731. int source = -1;
  5732. for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
  5733. if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
  5734. source = t;
  5735. const auto temporary = source < 0;
  5736. if (temporary) // the demo has no sends: add two for the picture
  5737. {
  5738. source = 1;
  5739. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, true, 0.6f); s.setRoute (1, 6, true, 0.3f); s.setRoute (4, 1, true, 0.8f); });
  5740. }
  5741. ui.getMixerForSnapshot().selectTrack (source);
  5742. offline.dispatchPendingMessages();
  5743. saveSnapshot (ui, prefix + "-mixer-sends.png");
  5744. if (temporary)
  5745. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
  5746. ui.getMixerForSnapshot().selectTrack (0);
  5747. }
  5748. // the Playlist with ripple editing on
  5749. ui.selectTabForSnapshot (2);
  5750. ui.getPlaylistForSnapshot().setRipple (true);
  5751. saveSnapshot (ui, prefix + "-playlist-ripple.png");
  5752. ui.getPlaylistForSnapshot().setRipple (false);
  5753. // quick-add palette, and the Browser searching
  5754. saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
  5755. ui.showDesktopForSnapshot (false);
  5756. ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
  5757. offline.dispatchPendingMessages();
  5758. saveSnapshot (ui, prefix + "-browser-search.png");
  5759. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  5760. ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
  5761. offline.dispatchPendingMessages();
  5762. saveSnapshot (ui, prefix + "-browser-tree.png");
  5763. // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
  5764. ui.getBrowserForSnapshot().showProjectForSnapshot();
  5765. offline.dispatchPendingMessages();
  5766. saveSnapshot (ui, prefix + "-browser-project.png");
  5767. ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
  5768. offline.dispatchPendingMessages();
  5769. saveSnapshot (ui, prefix + "-browser-plugins.png");
  5770. ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
  5771. saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
  5772. {
  5773. // round 164: the content filter leaves out the folders with nothing to list (a small library)
  5774. const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
  5775. lib.deleteRecursively();
  5776. for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
  5777. "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
  5778. lib.getChildFile (path).create();
  5779. ui.showDesktopForSnapshot (false);
  5780. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  5781. offline.dispatchPendingMessages();
  5782. saveSnapshot (ui, prefix + "-browser164-all.png");
  5783. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
  5784. offline.dispatchPendingMessages();
  5785. saveSnapshot (ui, prefix + "-browser164-samples.png");
  5786. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
  5787. offline.dispatchPendingMessages();
  5788. saveSnapshot (ui, prefix + "-browser164-projects.png");
  5789. lib.deleteRecursively();
  5790. ui.getBrowserForSnapshot().resetViewForSnapshot();
  5791. }
  5792. // the undo history after a few edits
  5793. offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
  5794. offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
  5795. offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
  5796. offline.undo();
  5797. saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
  5798. // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
  5799. // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
  5800. {
  5801. const juce::File wav (prefix + "-wavedemo.wav");
  5802. writeWaveDemo (wav, offline.getSong().bpm);
  5803. const auto path = wav.getFullPathName();
  5804. const auto pathUtf8 = path.toStdString();
  5805. int samplerChannel = -1, firstTrack = 0;
  5806. offline.editSong ([&] (lynx::Song& s) {
  5807. for (const auto& clip : s.playlist)
  5808. firstTrack = std::max (firstTrack, clip.track + 1);
  5809. lynx::ChannelDef audio;
  5810. audio.name = "Beat (audio)";
  5811. audio.instrument = lynx::InstrumentKind::audioClip;
  5812. audio.samplePath = pathUtf8;
  5813. s.channels.push_back (audio);
  5814. const auto audioChannel = (int) s.channels.size() - 1;
  5815. lynx::ChannelDef sampler = audio;
  5816. sampler.name = "Beat (sampler)";
  5817. sampler.instrument = lynx::InstrumentKind::sampler;
  5818. sampler.sampler.regionStart = 0.06f;
  5819. sampler.sampler.regionEnd = 0.94f;
  5820. s.channels.push_back (sampler);
  5821. samplerChannel = (int) s.channels.size() - 1;
  5822. const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
  5823. const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
  5824. lynx::Clip clip;
  5825. clip.kind = lynx::ClipKind::audio;
  5826. clip.channel = audioChannel;
  5827. clip.track = firstTrack;
  5828. clip.length = whole;
  5829. s.playlist.push_back (clip);
  5830. clip.track = firstTrack + 1; // a slice of it, later in the song
  5831. clip.start = bar;
  5832. clip.offset = bar;
  5833. clip.length = 2 * bar;
  5834. s.playlist.push_back (clip);
  5835. // taller rows for the audio (tracks can be resized: P18)
  5836. if ((int) s.playlistTracks.size() < firstTrack + 2)
  5837. s.playlistTracks.resize ((std::size_t) firstTrack + 2);
  5838. s.playlistTracks[(std::size_t) firstTrack].height = 80;
  5839. s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
  5840. });
  5841. offline.dispatchPendingMessages();
  5842. auto& cache = *lynx::ui::WaveformCache::getInstance();
  5843. cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  5844. cache.waitUntilIdle (30000);
  5845. ui.selectTabForSnapshot (2);
  5846. auto& playlist = ui.getPlaylistForSnapshot();
  5847. playlist.setTimeSelectionForSnapshot (0, 0);
  5848. {
  5849. // the Playlist alone (the floating Channel Rack would cover the clips)
  5850. auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
  5851. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  5852. saveSnapshot (ui, prefix + "-playlist-audio.png");
  5853. playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
  5854. saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
  5855. lynx::ui::WaveformCache::stereo = true;
  5856. saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
  5857. lynx::ui::WaveformCache::stereo = false;
  5858. lynx::ui::WaveformCache::spectral = true;
  5859. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  5860. saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
  5861. lynx::ui::WaveformCache::spectral = false;
  5862. playlist.setViewForSnapshot (40.0, 0, 0);
  5863. saveSnapshot (ui, prefix + "-playlist-audio-far.png");
  5864. // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
  5865. // a fade, a reversed copy), at three zoom levels
  5866. if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
  5867. ! files.isEmpty())
  5868. {
  5869. const auto realTrack = firstTrack + 2;
  5870. std::vector<juce::String> paths;
  5871. for (const auto& f : files)
  5872. if (juce::File (f.trim()).existsAsFile())
  5873. paths.push_back (f.trim());
  5874. offline.editSong ([&] (lynx::Song& s) {
  5875. const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
  5876. const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
  5877. for (std::size_t i = 0; i < paths.size(); ++i)
  5878. {
  5879. lynx::ChannelDef audio;
  5880. audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
  5881. audio.instrument = lynx::InstrumentKind::audioClip;
  5882. audio.samplePath = paths[i].toStdString();
  5883. audio.colour = colours[i % 6];
  5884. audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
  5885. audio.sampler.keepPitch = true;
  5886. s.channels.push_back (audio);
  5887. lynx::Clip clip;
  5888. clip.kind = lynx::ClipKind::audio;
  5889. clip.channel = (int) s.channels.size() - 1;
  5890. clip.track = realTrack + (int) i;
  5891. clip.length = 4 * bar;
  5892. clip.fadeIn = i == 1 ? bar / 2 : 0;
  5893. s.playlist.push_back (clip);
  5894. clip.start = 4 * bar;
  5895. clip.fadeIn = 0;
  5896. clip.fadeOut = i == 0 ? bar : 0;
  5897. s.playlist.push_back (clip);
  5898. }
  5899. if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
  5900. s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
  5901. if (! paths.empty())
  5902. s.playlistTracks[(std::size_t) realTrack].height = 90;
  5903. });
  5904. offline.dispatchPendingMessages();
  5905. for (const auto& path2 : paths)
  5906. cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
  5907. cache.waitUntilIdle (60000);
  5908. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  5909. saveSnapshot (ui, prefix + "-playlist-real.png");
  5910. playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
  5911. saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
  5912. playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
  5913. saveSnapshot (ui, prefix + "-playlist-real-close.png");
  5914. playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
  5915. saveSnapshot (ui, prefix + "-playlist-real-far.png");
  5916. // the clip menu of the first real clip
  5917. if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
  5918. saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
  5919. if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
  5920. saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
  5921. // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
  5922. {
  5923. juce::StringArray log;
  5924. auto clipOf = [&offline] (const std::string& channelName, int nth) {
  5925. const auto& sg = offline.getSong();
  5926. for (int i = 0; i < (int) sg.playlist.size(); ++i)
  5927. {
  5928. const auto& c = sg.playlist[(std::size_t) i];
  5929. if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
  5930. return i;
  5931. }
  5932. return -1;
  5933. };
  5934. std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
  5935. for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
  5936. {
  5937. auto& item = it.getItem();
  5938. if (item.subMenu != nullptr && run (*item.subMenu, text))
  5939. return true;
  5940. if (item.text.startsWith (text) && item.isEnabled && item.action)
  5941. {
  5942. item.action();
  5943. return true;
  5944. }
  5945. }
  5946. return false;
  5947. };
  5948. auto act = [&] (const std::string& name, int nth, const juce::String& text) {
  5949. const auto clip = clipOf (name, nth);
  5950. const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
  5951. offline.dispatchPendingMessages();
  5952. return ok;
  5953. };
  5954. auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
  5955. for (const auto& c : offline.getSong().channels)
  5956. if (c.name == name)
  5957. return &c;
  5958. return nullptr;
  5959. };
  5960. auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
  5961. const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
  5962. if (names.size() >= 4)
  5963. {
  5964. const auto channelsBefore = offline.getSong().channels.size();
  5965. check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
  5966. offline.undo();
  5967. offline.dispatchPendingMessages();
  5968. check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
  5969. act (names[2], 0, lynx::tr ("Reverse"));
  5970. check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
  5971. && channelOf (names[3] + " #2") != nullptr);
  5972. check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
  5973. && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
  5974. const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
  5975. check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
  5976. && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
  5977. const auto clipsBefore = offline.getSong().playlist.size();
  5978. check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
  5979. check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
  5980. check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
  5981. && offline.getSong().playlist.size() == clipsBefore + 2);
  5982. check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
  5983. check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
  5984. }
  5985. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  5986. saveSnapshot (ui, prefix + "-playlist-real-actions.png");
  5987. juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
  5988. }
  5989. }
  5990. }
  5991. saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
  5992. ui.showDesktopForSnapshot (false);
  5993. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  5994. saveSnapshot (ui, prefix + "-browser-preview.png");
  5995. }
  5996. }
  5997. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  5998. quit();
  5999. }
  6000. // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
  6001. // hats and the noise riser = high), to show the spectral waveform colours
  6002. static void writeWaveDemo (const juce::File& file, double bpm)
  6003. {
  6004. constexpr double rate = 44100.0;
  6005. const auto frames = (int) (8.0 * rate);
  6006. juce::AudioBuffer<float> buffer (2, frames);
  6007. buffer.clear();
  6008. auto* l = buffer.getWritePointer (0);
  6009. auto* r = buffer.getWritePointer (1);
  6010. const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
  6011. std::uint32_t noise = 0x9e3779b9u;
  6012. auto white = [&noise] {
  6013. noise ^= noise << 13;
  6014. noise ^= noise >> 17;
  6015. noise ^= noise << 5;
  6016. return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
  6017. };
  6018. float previous = 0.0f;
  6019. for (int i = 0; i < frames; ++i)
  6020. {
  6021. const auto t = i / rate;
  6022. const auto inBeat = std::fmod (t, beat);
  6023. const auto bar = (int) (t / (beat * 4.0));
  6024. float left = 0.0f, right = 0.0f;
  6025. // kick on every beat: a falling sine
  6026. {
  6027. const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
  6028. const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
  6029. left += k;
  6030. right += k;
  6031. }
  6032. // hats on the off-beats: high-passed noise bursts, a little to the right
  6033. {
  6034. const auto h = std::fmod (t + beat * 0.5, beat);
  6035. const auto n = white();
  6036. const auto hp = (n - previous) * 0.5f;
  6037. previous = n;
  6038. const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
  6039. left += hat * 0.6f;
  6040. right += hat;
  6041. }
  6042. // a chord in the second and third bars (mid band)
  6043. if (bar == 1 || bar == 2)
  6044. {
  6045. const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
  6046. float chord = 0.0f;
  6047. for (const auto hz : { 523.25, 659.25, 783.99 })
  6048. chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
  6049. left += chord * 0.09f * std::max (0.0f, env);
  6050. right += chord * 0.09f * std::max (0.0f, env);
  6051. }
  6052. // a white-noise riser over the last two seconds (high band)
  6053. if (t > 6.0)
  6054. {
  6055. const auto rise = (float) ((t - 6.0) / 2.0);
  6056. left += white() * 0.4f * rise * rise;
  6057. right += white() * 0.4f * rise * rise;
  6058. }
  6059. l[i] = left;
  6060. r[i] = right;
  6061. }
  6062. buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
  6063. file.deleteFile();
  6064. juce::WavAudioFormat wav;
  6065. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
  6066. writer->writeFromAudioSampleBuffer (buffer, 0, frames);
  6067. }
  6068. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  6069. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  6070. {
  6071. const auto names = ui.getMenuNamesForSnapshot();
  6072. std::vector<juce::PopupMenu> source;
  6073. for (int m = 0; m < names.size(); ++m)
  6074. source.push_back (ui.getMenuForSnapshot (m));
  6075. saveMenus (names, source, path);
  6076. }
  6077. // menus side by side, each under its name
  6078. static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
  6079. {
  6080. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  6081. struct Laid
  6082. {
  6083. juce::PopupMenu menu;
  6084. int width = 0, height = 0;
  6085. };
  6086. std::vector<Laid> menus;
  6087. const auto border = lf.getPopupMenuBorderSize();
  6088. for (int m = 0; m < names.size(); ++m)
  6089. {
  6090. Laid laid { source[(std::size_t) m] };
  6091. int width = 160, height = 2 * border;
  6092. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  6093. {
  6094. const auto& item = it.getItem();
  6095. int w = 0, h = 0;
  6096. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  6097. if (item.isSectionHeader) h += h / 2; // as JUCE does
  6098. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  6099. w += 90;
  6100. width = juce::jmax (width, w + 10);
  6101. height += h;
  6102. }
  6103. laid.width = width;
  6104. laid.height = height;
  6105. menus.push_back (std::move (laid));
  6106. }
  6107. int totalWidth = 16, totalHeight = 0;
  6108. for (const auto& l : menus)
  6109. {
  6110. totalWidth += l.width + 16;
  6111. totalHeight = juce::jmax (totalHeight, l.height + 32);
  6112. }
  6113. juce::Image image (juce::Image::ARGB, totalWidth, totalHeight, true);
  6114. {
  6115. juce::Graphics g (image);
  6116. g.fillAll (lynx::theme::colour::bg1);
  6117. int x = 16;
  6118. for (int m = 0; m < (int) menus.size(); ++m)
  6119. {
  6120. const auto& l = menus[(std::size_t) m];
  6121. g.setColour (lynx::theme::colour::textSecondary);
  6122. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  6123. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  6124. {
  6125. juce::Graphics::ScopedSaveState state (g);
  6126. g.reduceClipRegion (x, 24, l.width, l.height);
  6127. g.setOrigin (x, 24);
  6128. lf.drawPopupMenuBackground (g, l.width, l.height);
  6129. int y = border;
  6130. bool first = true;
  6131. for (juce::PopupMenu::MenuItemIterator it (l.menu); it.next();)
  6132. {
  6133. const auto& item = it.getItem();
  6134. int w = 0, h = 0;
  6135. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  6136. if (item.isSectionHeader) h += h / 2; // as JUCE does
  6137. const juce::Rectangle<int> r (0, y, l.width, h);
  6138. auto text = item.text, shortcut = item.shortcutKeyDescription;
  6139. if (text.containsChar ('\t'))
  6140. {
  6141. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  6142. text = text.upToFirstOccurrenceOf ("\t", false, false);
  6143. }
  6144. if (item.isSectionHeader)
  6145. lf.drawPopupMenuSectionHeader (g, r, text);
  6146. else
  6147. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  6148. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  6149. first = false;
  6150. y += h;
  6151. }
  6152. }
  6153. x += l.width + 16;
  6154. }
  6155. }
  6156. const juce::File file (path);
  6157. file.deleteFile();
  6158. juce::PNGImageFormat png;
  6159. if (auto out = file.createOutputStream())
  6160. png.writeImageToStream (image, *out);
  6161. }
  6162. static void writePng (const juce::Image& image, const juce::String& path)
  6163. {
  6164. const juce::File file (path);
  6165. file.deleteFile();
  6166. juce::PNGImageFormat png;
  6167. if (auto out = file.createOutputStream())
  6168. png.writeImageToStream (image, *out);
  6169. }
  6170. // the splash screen: one settled frame, and a strip of frames through its animation
  6171. static void saveSplashFrames (const juce::String& prefix)
  6172. {
  6173. lynx::SplashScreen splash;
  6174. splash.setStatus (lynx::tr ("Loading the workspace..."));
  6175. splash.setTimeForSnapshot (1.6);
  6176. writePng (splash.createComponentSnapshot (splash.getLocalBounds()), prefix + "-splash.png");
  6177. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  6178. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  6179. juce::Image strip (juce::Image::ARGB, 4 * (w + 8) + 8, 2 * (h + 8) + 8, true);
  6180. {
  6181. juce::Graphics g (strip);
  6182. g.fillAll (lynx::theme::colour::bg1);
  6183. for (int i = 0; i < 8; ++i)
  6184. {
  6185. splash.setTimeForSnapshot (times[i]);
  6186. const auto frame = splash.createComponentSnapshot (splash.getLocalBounds());
  6187. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  6188. }
  6189. }
  6190. writePng (strip, prefix + "-splash-frames.png");
  6191. }
  6192. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  6193. // colours: at rest, hovered and switched on
  6194. static void saveIconSheet (const juce::String& path, float scale)
  6195. {
  6196. const int sizes[] = { 16, 20, 24 };
  6197. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  6198. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  6199. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  6200. {
  6201. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  6202. g.addTransform (juce::AffineTransform::scale (scale));
  6203. g.fillAll (lynx::theme::colour::bg3);
  6204. g.setFont (lynx::theme::font (lynx::theme::type::small));
  6205. for (int i = 1; i < lynx::iconCount; ++i)
  6206. {
  6207. const auto y = 8 + (i - 1) * cell;
  6208. g.setColour (lynx::theme::colour::textDisabled);
  6209. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  6210. for (int v = 0; v < 3; ++v)
  6211. for (int s = 0; s < 3; ++s)
  6212. {
  6213. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  6214. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  6215. g.setColour (bg);
  6216. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  6217. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  6218. : lynx::theme::colour::textSecondary.brighter (0.25f);
  6219. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  6220. }
  6221. }
  6222. }
  6223. writePng (image, path);
  6224. }
  6225. // a part of a component (e.g. the main toolbar)
  6226. static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
  6227. {
  6228. const juce::File file (path);
  6229. file.deleteFile();
  6230. juce::PNGImageFormat png;
  6231. if (auto out = file.createOutputStream())
  6232. png.writeImageToStream (c.createComponentSnapshot (area), *out);
  6233. }
  6234. static void savePng (const juce::Image& image, const juce::String& path)
  6235. {
  6236. const juce::File file (path);
  6237. file.deleteFile();
  6238. juce::PNGImageFormat png;
  6239. if (auto out = file.createOutputStream())
  6240. png.writeImageToStream (image, *out);
  6241. }
  6242. // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
  6243. // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
  6244. static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
  6245. {
  6246. const auto tips = ui.getQuickTipsForSnapshot();
  6247. const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
  6248. auto image = ui.createComponentSnapshot (top);
  6249. {
  6250. juce::Graphics g (image);
  6251. const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
  6252. lynx::tr ("Window options"), lynx::tr ("Close") };
  6253. std::vector<juce::Rectangle<int>> used;
  6254. for (const auto& [area, tip] : tips)
  6255. {
  6256. const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
  6257. if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
  6258. continue;
  6259. const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
  6260. if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
  6261. continue;
  6262. used.push_back (bubble);
  6263. g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
  6264. g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
  6265. lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
  6266. }
  6267. }
  6268. savePng (image, prefix + "-toolbar-tips.png");
  6269. // the sheet: bubbles in rows
  6270. const int width = 900;
  6271. int x = 12, y = 12;
  6272. std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
  6273. for (const auto& [area, tip] : tips)
  6274. {
  6275. auto r = lynx::ui::quickTipSize (tip);
  6276. if (x + r.getWidth() > width - 12)
  6277. {
  6278. x = 12;
  6279. y += r.getHeight() + 10;
  6280. }
  6281. placed.emplace_back (r.withPosition (x, y), tip);
  6282. x += r.getWidth() + 10;
  6283. }
  6284. juce::Image sheet (juce::Image::ARGB, width, y + 20 + 12, true);
  6285. {
  6286. juce::Graphics g (sheet);
  6287. g.fillAll (lynx::theme::colour::bg3);
  6288. for (const auto& [r, tip] : placed)
  6289. lynx::ui::paintQuickTip (g, r.toFloat(), tip);
  6290. }
  6291. savePng (sheet, prefix + "-tips-sheet.png");
  6292. }
  6293. static void saveSnapshot (juce::Component& c, const juce::String& path)
  6294. {
  6295. const juce::File file (path);
  6296. file.deleteFile();
  6297. juce::PNGImageFormat png;
  6298. if (auto out = file.createOutputStream())
  6299. png.writeImageToStream (c.createComponentSnapshot (c.getLocalBounds()), *out);
  6300. }
  6301. class MainWindow final : public juce::DocumentWindow
  6302. {
  6303. public:
  6304. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  6305. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons)
  6306. {
  6307. setUsingNativeTitleBar (true);
  6308. setIcon (lynx::logoImage());
  6309. content = new lynx::MainComponent (engine);
  6310. setContentOwned (content, true);
  6311. setResizable (true, true);
  6312. setResizeLimits (800, 400, 10000, 10000);
  6313. // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
  6314. // display: the AppImage catalog test runs on an 800x600 screen)
  6315. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  6316. {
  6317. const auto area = display->userArea;
  6318. const auto fit = [] (int design, int available) {
  6319. return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
  6320. };
  6321. setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
  6322. }
  6323. centreWithSize (getWidth(), getHeight());
  6324. }
  6325. // Shows the window (built hidden while the splash screen is up).
  6326. void reveal()
  6327. {
  6328. setVisible (true);
  6329. lynx::applyWindowChrome (*this);
  6330. lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
  6331. toFront (true);
  6332. content->grabKeyboardFocus();
  6333. }
  6334. void openFile (const juce::File& file) { content->openFile (file); }
  6335. lynx::MainComponent& getContent() { return *content; }
  6336. void showSetupWizard() { content->showSetupWizard(); }
  6337. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  6338. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  6339. // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
  6340. std::function<void (double)> onFrame;
  6341. void paint (juce::Graphics& g) override
  6342. {
  6343. if (onFrame)
  6344. frameStart = juce::Time::getMillisecondCounterHiRes();
  6345. DocumentWindow::paint (g);
  6346. }
  6347. void paintOverChildren (juce::Graphics& g) override
  6348. {
  6349. DocumentWindow::paintOverChildren (g);
  6350. if (onFrame && frameStart > 0.0)
  6351. onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
  6352. frameStart = 0.0;
  6353. }
  6354. private:
  6355. lynx::MainComponent* content = nullptr; // owned by the window
  6356. double frameStart = 0.0;
  6357. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  6358. };
  6359. lynx::theme::LookAndFeel lookAndFeel;
  6360. std::unique_ptr<lynx::AudioEngine> engine;
  6361. std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
  6362. // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
  6363. // without registering it, listed as the driver type "ASIO driver file". True when one was added.
  6364. bool addDriverFileDeviceType()
  6365. {
  6366. const auto args = juce::JUCEApplication::getCommandLineParameterArray();
  6367. const auto i = args.indexOf ("--asiodll");
  6368. if (i < 0 || i + 1 >= args.size() || engine == nullptr)
  6369. return false;
  6370. auto& devices = engine->getDeviceManager();
  6371. devices.getAvailableDeviceTypes(); // creates the standard types first
  6372. for (auto* t : devices.getAvailableDeviceTypes())
  6373. if (t->getTypeName() == lynx::dllAsioTypeName)
  6374. return true;
  6375. auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
  6376. if (type == nullptr)
  6377. return false;
  6378. devices.addAudioDeviceType (std::move (type));
  6379. return true;
  6380. }
  6381. void restoreSavedDeviceState()
  6382. {
  6383. if (engine != nullptr)
  6384. engine->restoreAudioDeviceState (savedDeviceState.get());
  6385. }
  6386. std::unique_ptr<MainWindow> mainWindow;
  6387. std::unique_ptr<juce::Timer> perf; // --uiperf
  6388. std::unique_ptr<lynx::SplashScreen> splash;
  6389. double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
  6390. lynx::StartupOptions startupOptions;
  6391. juce::File fileToOpen;
  6392. juce::File openTimeReport; // --opentime
  6393. int openTimeIdleSeconds = 10;
  6394. };
  6395. START_JUCE_APPLICATION (LynxApplication)