Main.cpp 586 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522
  1. #include <juce_gui_basics/juce_gui_basics.h>
  2. #include "engine/FileSort.h"
  3. #include "platform/Paths.h"
  4. #include "core/PlaylistOps.h"
  5. #include "core/Drumaxx.h"
  6. #include "core/PatternBlocks.h"
  7. #include "core/LoadTrace.h"
  8. #include "core/Patcher.h"
  9. #include "core/Patcherize.h"
  10. #include "core/Performance.h"
  11. #include "core/VideoPlayer.h"
  12. #include "core/Effects.h"
  13. #include "core/MixSuite.h"
  14. #include "core/HardwareInsert.h"
  15. #include "core/EchoSuite.h"
  16. #include "core/LynxTune.h"
  17. #include "core/FlEffects.h"
  18. #include "core/FlpImport.h"
  19. #include "core/NoteEdit.h"
  20. #include "core/MaximusFx.h"
  21. #include "core/Harmor.h"
  22. #include "flp/Flp.h"
  23. #include "core/SynthPresets.h"
  24. #include "core/FlWrapper.h"
  25. #include "engine/AudioEngine.h"
  26. #include "engine/Metronome.h"
  27. #include "engine/AudioLogger.h"
  28. #include "engine/DllAsioDevice.h"
  29. #include "engine/PipeWireDevice.h"
  30. #include "platform/LinuxRealtime.h"
  31. #include "engine/Exporter.h"
  32. #include "engine/FlStudioExport.h"
  33. #include "engine/MidiFileIo.h"
  34. #include "engine/PluginHost.h"
  35. #include "engine/PluginSandbox.h"
  36. #include "engine/Bridge32Test.h"
  37. #include "engine/ProjectFile.h"
  38. #include "core/Sha256.h"
  39. #include "engine/SessionPack.h"
  40. #include "engine/LiveTest.h"
  41. #include "core/SessionIds.h"
  42. #include "core/SessionParts.h"
  43. #include "engine/SampleLibrary.h"
  44. #include "engine/Text.h"
  45. #include "platform/FileTypes.h"
  46. #include "platform/Package.h"
  47. #include "ui/VideoPlayerView.h"
  48. #include "ui/PatcherEditor.h"
  49. #include "ui/VisualEditors.h"
  50. #include "ui/FlExtraEditors.h"
  51. #include "ui/VisualGl.h"
  52. #include "ui/DanceView.h"
  53. #include "ui/PluginPresetMenu.h"
  54. #include "ui/PluginWindow.h"
  55. #include "ui/PluginThumbs.h"
  56. #include "ui/ClipProperties.h"
  57. #include "ui/NewProjectDialog.h"
  58. #include "ui/PluginMonitorWindow.h"
  59. #include "ui/TouchKeyboard.h"
  60. #include "ui/AutomationUi.h"
  61. #include "ui/PluginSkin.h"
  62. #include "ui/ChannelSettings.h"
  63. #include "core/LynxBanks.h"
  64. #include "core/NativeEngines.h"
  65. #include "ui/ControllerEditors.h"
  66. #include "ui/NewtoneEditor.h"
  67. #include "core/NewtoneFx.h"
  68. #include "core/FormulaController.h"
  69. #include "core/MidiControls.h"
  70. #include "core/FlSynths.h"
  71. #include "core/SoundFont.h"
  72. #include "core/Sfz.h"
  73. #include "ui/Dialogs.h"
  74. #include "ui/FileChoosers.h"
  75. #include "ui/TrackIcons.h"
  76. #include "core/RackOps.h"
  77. #include "core/Layer.h"
  78. #include "core/XyController.h"
  79. #include "core/FlCurve.h"
  80. #include "core/ControlSurface.h"
  81. #include "core/VoltageController.h"
  82. #include "ui/Controllers164.h"
  83. #include "ui/ExportDialog.h"
  84. #include "ui/QuickAddPalette.h"
  85. #include "ui/I18n.h"
  86. #include "ui/MainComponent.h"
  87. #include "ui/FrameProbe.h"
  88. #include "ui/UiTrace.h"
  89. #include "core/MixerOps.h"
  90. #include "ui/QuickPick.h"
  91. #include "core/NoteTools.h"
  92. #include "engine/ProjectPackage.h"
  93. #include "ui/SetupWizard.h"
  94. #include "engine/FlStudio.h"
  95. #include "ui/HistoryPanel.h"
  96. #include "ui/MissingFilesDialog.h"
  97. #include "ui/SettingsDialog.h"
  98. #include "ui/PluginManager.h"
  99. #include "ui/ShortcutManager.h"
  100. #include "ui/NoteToolDialogs.h"
  101. #include "ui/EventEditor.h"
  102. #include "ui/AudioEditor.h"
  103. #include "ui/TempoTapper.h"
  104. #include "core/EventEdit.h"
  105. #include "core/FacetEq.h"
  106. #include "ui/FacetEqEditor.h"
  107. #include "core/RackRenderer.h"
  108. #include "ui/ProEditors.h"
  109. #include "ui/ParametricEqEditor.h"
  110. #include "ui/PluginEditors.h"
  111. #include "core/PluginLayout.h"
  112. #include "core/EffectPresets.h"
  113. #include "core/Vfx.h"
  114. #include "ui/Splash.h"
  115. #include "ui/Theme.h"
  116. #include "ui/ThemeSettings.h"
  117. #include "ui/WaveformView.h"
  118. #include "ui/WindowOwner.h"
  119. #include "ui/Toolbar.h"
  120. #include "ui/ToolWindow.h"
  121. #include "platform/CrashGuard.h"
  122. #include "ui/CrashReporter.h"
  123. #include "ui/Updater.h"
  124. #include "ui/StemExtract.h"
  125. #include <atomic>
  126. #include <chrono>
  127. #include <cstdio>
  128. #include <cstdlib>
  129. #include <mutex>
  130. #include <thread>
  131. namespace
  132. {
  133. lynx::AudioEngine* crashEngine = nullptr;
  134. // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
  135. // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
  136. struct StartupTrace
  137. {
  138. using clock = std::chrono::steady_clock;
  139. const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
  140. const bool on = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
  141. juce::String text;
  142. clock::time_point last = t0;
  143. double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
  144. void mark (const char* step)
  145. {
  146. if (! on)
  147. return;
  148. const auto now = clock::now();
  149. const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
  150. text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7) << " " << step << "\n";
  151. last = now;
  152. lynx::platform::settingsFile ("startup.log").replaceWithText (text);
  153. }
  154. };
  155. StartupTrace startupTrace;
  156. void startupMarkHook (const char* step) { startupTrace.mark (step); }
  157. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  158. void onCrash (void* exceptionPointers)
  159. {
  160. const auto folder = lynx::platform::settingsFile ("autosave");
  161. folder.createDirectory();
  162. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  163. // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
  164. // release LYNX.exe has no symbols, so its own frames were missing from the file)
  165. folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
  166. + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
  167. lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
  168. if (crashEngine != nullptr)
  169. {
  170. juce::String error;
  171. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  172. }
  173. }
  174. juce::File sessionsFolder()
  175. {
  176. return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
  177. }
  178. // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
  179. // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
  180. juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
  181. juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
  182. // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
  183. // whether its crash file blames a graphics driver
  184. struct UncleanCause
  185. {
  186. juce::String editorPlugin; // the last steps were that plugin's editor
  187. bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
  188. juce::String driverModule;
  189. };
  190. UncleanCause uncleanCause()
  191. {
  192. UncleanCause cause;
  193. juce::File crashFile;
  194. for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
  195. {
  196. const auto& step = uncleanSteps[i];
  197. if (step.startsWith ("crashed: backtrace in "))
  198. crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
  199. for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
  200. if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
  201. cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
  202. if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
  203. break; // older steps than these did not end the session
  204. }
  205. // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
  206. // likely cause when the session then ended without a word: offer it a separate process too
  207. for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
  208. if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
  209. cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
  210. if (crashFile.existsAsFile())
  211. {
  212. // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
  213. auto text = crashFile.loadFileAsString();
  214. if (text.contains ("--- frames"))
  215. text = text.fromFirstOccurrenceOf ("--- frames", false, false);
  216. auto lines = juce::StringArray::fromLines (text);
  217. int looked = 0;
  218. for (const auto& line : lines)
  219. {
  220. const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
  221. if (module.isEmpty() || ! module.endsWith (".dll"))
  222. continue;
  223. if (++looked > 12)
  224. break;
  225. for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
  226. "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
  227. if (module.startsWith (driver))
  228. {
  229. cause.gpuDriver = true;
  230. cause.driverModule = module;
  231. break;
  232. }
  233. if (cause.gpuDriver)
  234. break;
  235. }
  236. }
  237. return cause;
  238. }
  239. juce::String collectUncleanSessions()
  240. {
  241. juce::String lastStep;
  242. juce::Time newest;
  243. for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
  244. {
  245. const auto text = file.loadFileAsString();
  246. juce::StringPairArray values;
  247. juce::StringArray steps;
  248. for (const auto& line : juce::StringArray::fromLines (text))
  249. {
  250. if (line.startsWith ("step="))
  251. steps.add (line.fromFirstOccurrenceOf ("=", false, false));
  252. else if (line.contains ("="))
  253. values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
  254. }
  255. const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
  256. const auto start = (std::uint64_t) values["start"].getLargeIntValue();
  257. if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
  258. continue; // this run, or another LYNX window still open
  259. lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
  260. .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
  261. file.deleteFile();
  262. if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
  263. {
  264. newest = modified;
  265. lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
  266. uncleanSessionText = text;
  267. uncleanSteps.clear();
  268. for (const auto& step : steps)
  269. uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
  270. }
  271. }
  272. return lastStep;
  273. }
  274. } // namespace
  275. // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
  276. // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
  277. // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
  278. // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
  279. // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
  280. // the mouse is released.
  281. struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
  282. private juce::HighResolutionTimer
  283. {
  284. ~UiPerfDrag() override { stopTimer(); }
  285. void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
  286. {
  287. window = &windowIn;
  288. engine = engineIn;
  289. track = trackIn;
  290. railInWindow = window->getLocalArea (&strips, rail);
  291. watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
  292. visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
  293. const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
  294. x = (float) railInWindow.getCentreX();
  295. startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
  296. amplitude = 0.4f * (float) railInWindow.getHeight();
  297. centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
  298. t0 = juce::Time::getMillisecondCounterHiRes();
  299. inject (x, startY, false);
  300. juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  301. inject (x, startY, true);
  302. active = true;
  303. startTimer (8);
  304. }
  305. // message thread
  306. void framePainted (double now, juce::Rectangle<int> area)
  307. {
  308. if (pending.empty() || ! area.intersects (watch))
  309. return;
  310. for (const auto t : pending)
  311. latencies.push_back (now - t);
  312. pending.clear();
  313. ++framesOverFader;
  314. }
  315. // the moves end; as in the reporter's clip, the song is stopped while the button is still down
  316. juce::String stop()
  317. {
  318. stopTimer();
  319. active = false;
  320. valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
  321. engine->stop();
  322. juce::String text;
  323. text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
  324. << " folded into the next (the message thread still busy with the previous one)\n"
  325. << " move waited for the message thread: " << describe (queueDelays) << "\n"
  326. << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
  327. << " frames over the fader\n";
  328. return text;
  329. }
  330. juce::String release()
  331. {
  332. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  333. juce::ModifierKeys::currentModifiers = {};
  334. inject (x, lastY, false);
  335. return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
  336. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  337. }
  338. juce::String released() const
  339. {
  340. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  341. return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
  342. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  343. }
  344. private:
  345. juce::Component* window = nullptr;
  346. lynx::AudioEngine* engine = nullptr;
  347. int track = 1;
  348. juce::Rectangle<int> railInWindow, watch;
  349. bool visible = false;
  350. float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
  351. double t0 = 0.0;
  352. std::atomic<bool> active { false }, posted { false };
  353. std::atomic<int> dropped { 0 };
  354. int moves = 0, framesOverFader = 0;
  355. float valueAtRelease = 0.0f;
  356. std::vector<double> pending, latencies, queueDelays;
  357. static juce::String describe (std::vector<double> v)
  358. {
  359. if (v.empty())
  360. return "none";
  361. std::sort (v.begin(), v.end());
  362. const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
  363. return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
  364. + juce::String (v.back(), 1) + " ms";
  365. }
  366. void inject (float px, float py, bool down)
  367. {
  368. lastY = py;
  369. if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
  370. {
  371. const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
  372. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
  373. down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
  374. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
  375. juce::Time::currentTimeMillis());
  376. }
  377. }
  378. void hiResTimerCallback() override
  379. {
  380. if (! active.load())
  381. return;
  382. if (posted.exchange (true))
  383. {
  384. ++dropped;
  385. return;
  386. }
  387. const auto postedAt = juce::Time::getMillisecondCounterHiRes();
  388. juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
  389. self->posted = false;
  390. if (! self->active.load())
  391. return;
  392. const auto now = juce::Time::getMillisecondCounterHiRes();
  393. self->queueDelays.push_back (now - postedAt);
  394. // up and down ~1.3 times a second, like the reporter's hand
  395. const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
  396. self->inject (self->x, y, true);
  397. self->pending.push_back (postedAt);
  398. ++self->moves;
  399. });
  400. }
  401. };
  402. class LynxApplication final : public juce::JUCEApplication
  403. {
  404. public:
  405. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  406. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  407. // the plugin scan runs copies of LYNX as child processes
  408. bool moreThanOneInstanceAllowed() override { return true; }
  409. void initialise (const juce::String& commandLine) override
  410. {
  411. // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
  412. if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
  413. {
  414. updateHelper = true;
  415. quit();
  416. return;
  417. }
  418. // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
  419. if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
  420. {
  421. relaunched = true;
  422. setApplicationReturnValue (code);
  423. quit();
  424. return;
  425. }
  426. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
  427. juce::SystemStats::setApplicationCrashHandler (onCrash);
  428. // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
  429. lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
  430. juce::AudioFormatManager formats;
  431. formats.registerBasicFormats();
  432. std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
  433. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
  434. return false;
  435. const auto frames = (int) reader->lengthInSamples;
  436. juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
  437. if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
  438. return false;
  439. out.channels.clear();
  440. for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
  441. out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
  442. out.sampleRate = reader->sampleRate;
  443. out.loopStart = out.loopEnd = -1;
  444. return true;
  445. });
  446. // child process of a sandboxed plugin: no window or audio of its own
  447. if (lynx::runPluginSandboxWorker (commandLine))
  448. {
  449. lynx::crashguard::quietCrashReports();
  450. sandboxChild = true;
  451. return;
  452. }
  453. const auto args = juce::StringArray::fromTokens (commandLine, true);
  454. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  455. lynx::i18n::initialise (args);
  456. lookAndFeel.applyLanguageFont (lynx::i18n::current());
  457. if (args.contains ("--showcase"))
  458. {
  459. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  460. const auto i = args.indexOf ("--showcase");
  461. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  462. return;
  463. }
  464. if (args.contains ("--sandboxtest"))
  465. {
  466. const auto i = args.indexOf ("--sandboxtest");
  467. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  468. return;
  469. }
  470. if (args.contains ("--bridge32test"))
  471. {
  472. // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
  473. // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
  474. const auto i = args.indexOf ("--bridge32test");
  475. const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
  476. setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
  477. quit();
  478. return;
  479. }
  480. if (args.contains ("--rtstress"))
  481. {
  482. // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
  483. // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
  484. // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
  485. // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
  486. const auto i = args.indexOf ("--rtstress");
  487. const auto seconds = args[i + 3].getDoubleValue();
  488. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  489. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  490. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  491. runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
  492. option ("--type"), option ("--device"), option ("--record"));
  493. return;
  494. }
  495. if (args.contains ("--cliplooptest"))
  496. {
  497. // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
  498. // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
  499. // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
  500. // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
  501. // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
  502. const auto i = args.indexOf ("--cliplooptest");
  503. runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
  504. return;
  505. }
  506. if (args.contains ("--countinrectest"))
  507. {
  508. // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
  509. // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
  510. // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
  511. // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
  512. // it (a chord 15 ms early, a note in the count-in, one 3 ms after beat 2, one a bar for 6 bars) through
  513. // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
  514. const auto i = args.indexOf ("--countinrectest");
  515. runCountInRecordTest (juce::File (args[i + 1].unquoted()));
  516. return;
  517. }
  518. if (args.contains ("--bendrectest"))
  519. {
  520. // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
  521. // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
  522. // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
  523. // automation clip (song mode) of the channel's pitch bend must follow the sweep.
  524. const auto i = args.indexOf ("--bendrectest");
  525. const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
  526. runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
  527. return;
  528. }
  529. if (args.contains ("--rectest"))
  530. {
  531. // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
  532. // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
  533. // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
  534. // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
  535. // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
  536. // and 1 of post-roll (playback stops by itself after the post-roll).
  537. const auto i = args.indexOf ("--rectest");
  538. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  539. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  540. runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
  541. args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
  542. return;
  543. }
  544. if (args.contains ("--hwinserttest"))
  545. {
  546. // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
  547. // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
  548. // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
  549. // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
  550. // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
  551. // sample as the right side's.
  552. const auto i = args.indexOf ("--hwinserttest");
  553. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  554. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
  555. // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
  556. // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
  557. runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
  558. option ("--buffer").getIntValue(), args.contains ("--patcher"),
  559. args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
  560. return;
  561. }
  562. if (args.contains ("--uiperf"))
  563. {
  564. // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
  565. const auto i = args.indexOf ("--uiperf");
  566. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  567. runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  568. return;
  569. }
  570. if (args.contains ("--livetest"))
  571. {
  572. // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
  573. setApplicationReturnValue (lynx::livetest::run (args));
  574. quit();
  575. return;
  576. }
  577. if (args.contains ("--selftest"))
  578. {
  579. const auto i = args.indexOf ("--selftest");
  580. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  581. return;
  582. }
  583. if (args.contains ("--scan-one"))
  584. {
  585. // child process of the plugin scan (see PluginHost::scan)
  586. const auto i = args.indexOf ("--scan-one");
  587. // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
  588. // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
  589. // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
  590. lynx::crashguard::quietCrashReports();
  591. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  592. lynx::crashguard::exitNow (0);
  593. }
  594. if (args.contains ("--packageinfo"))
  595. {
  596. // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
  597. // workflow runs it inside the installed test package
  598. juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
  599. quit();
  600. return;
  601. }
  602. if (args.contains ("--paths"))
  603. {
  604. // diagnostics: folders LYNX searches
  605. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  606. juce::String report;
  607. report << "programs=" << programs.getFullPathName() << "\n";
  608. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  609. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  610. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  611. quit();
  612. return;
  613. }
  614. if (args.contains ("--fldb"))
  615. {
  616. // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
  617. // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
  618. const auto i = args.indexOf ("--fldb");
  619. const auto fl = lynx::findFlStudio();
  620. lynx::PluginHost host (false);
  621. juce::String report;
  622. report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
  623. for (const auto& f : fl.vstFolders)
  624. report << "flvstfolder=" << f << "\n";
  625. report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
  626. for (const auto& e : host.flPluginDatabase().entries())
  627. report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
  628. const auto suggested = host.suggestedFolders();
  629. for (int k = 0; k < suggested.getNumPaths(); ++k)
  630. report << "folder=" << suggested[k].getFullPathName() << "\n";
  631. if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
  632. {
  633. juce::MemoryBlock data;
  634. project.loadFileAsData (data);
  635. try
  636. {
  637. for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
  638. {
  639. juce::String how;
  640. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  641. const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
  642. report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  643. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
  644. << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
  645. }
  646. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  647. const auto candidates = host.filesToScanFor (uses);
  648. report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
  649. if (args.contains ("--scan"))
  650. {
  651. // the targeted scan an open would run (child processes; the user's plugin list is not touched)
  652. report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
  653. for (const auto& use : uses)
  654. {
  655. juce::String how;
  656. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  657. report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  658. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
  659. }
  660. }
  661. }
  662. catch (const flp::Error& e)
  663. {
  664. report << "error=" << e.what() << "\n";
  665. }
  666. }
  667. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  668. quit();
  669. return;
  670. }
  671. if (args.contains ("--midisync-test"))
  672. {
  673. // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
  674. const auto i = args.indexOf ("--midisync-test");
  675. const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  676. const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  677. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
  678. quit();
  679. return;
  680. }
  681. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  682. {
  683. // diagnostics: driver types and output devices JUCE offers (without opening any)
  684. juce::AudioDeviceManager manager;
  685. juce::String report;
  686. manager.getAvailableDeviceTypes();
  687. if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
  688. manager.addAudioDeviceType (std::move (pipeWire));
  689. #if JUCE_LINUX
  690. report << lynx::describePipeWire() << "\n";
  691. #endif
  692. for (auto* type : manager.getAvailableDeviceTypes())
  693. {
  694. type->scanForDevices();
  695. report << "type=" << type->getTypeName() << "\n";
  696. for (const auto& name : type->getDeviceNames (false))
  697. report << " output=" << name << "\n";
  698. for (const auto& name : type->getDeviceNames (true))
  699. report << " input=" << name << "\n";
  700. }
  701. for (const auto& d : juce::MidiInput::getAvailableDevices())
  702. report << "midi-in=" << d.name << "\n";
  703. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  704. report << "midi-out=" << d.name << "\n";
  705. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  706. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  707. quit();
  708. return;
  709. }
  710. if (args.contains ("--devicetest"))
  711. {
  712. // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
  713. // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
  714. // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
  715. // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
  716. // cable / PipeWire link: the round-trip latency (3 s)
  717. const auto i = args.indexOf ("--devicetest");
  718. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  719. auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
  720. const auto wantInput = inputName.isNotEmpty();
  721. juce::String report;
  722. const juce::File reportFile (args[i + 3].unquoted());
  723. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  724. step ("step=start");
  725. juce::AudioDeviceManager manager;
  726. manager.getAvailableDeviceTypes();
  727. if (auto pipeWire = lynx::makePipeWireDeviceType())
  728. manager.addAudioDeviceType (std::move (pipeWire));
  729. std::unique_ptr<juce::AudioIODevice> device;
  730. for (auto* type : manager.getAvailableDeviceTypes())
  731. if (type->getTypeName() == typeName)
  732. {
  733. type->scanForDevices();
  734. if (wantInput && type->hasSeparateInputsAndOutputs())
  735. {
  736. const auto inputs = type->getDeviceNames (true);
  737. if (inputName == "*" || ! inputs.contains (inputName))
  738. {
  739. const auto index = type->getDefaultDeviceIndex (true);
  740. inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  741. }
  742. for (const auto& n : inputs)
  743. step ("input_device=" + n);
  744. step ("input_chosen=" + inputName);
  745. }
  746. else if (wantInput)
  747. inputName = deviceName;
  748. step ("step=create");
  749. device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
  750. step ("step=created");
  751. }
  752. struct Silence final : juce::AudioIODeviceCallback
  753. {
  754. std::atomic<int> calls { 0 }, inputs { 0 };
  755. std::array<std::atomic<float>, 64> peaks {};
  756. // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
  757. // loopback; the delays in samples
  758. bool roundtrip = false;
  759. int period = 12000;
  760. std::int64_t position = 0, lastClick = -1;
  761. std::vector<int> delays;
  762. void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
  763. const juce::AudioIODeviceCallbackContext&) override
  764. {
  765. for (int c = 0; c < channels; ++c)
  766. if (out[c] != nullptr)
  767. juce::FloatVectorOperations::clear (out[c], n);
  768. if (roundtrip)
  769. {
  770. for (int i = 0; i < n; ++i)
  771. {
  772. if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
  773. {
  774. if (delays.size() < delays.capacity())
  775. delays.push_back ((int) (position + i - lastClick));
  776. lastClick = -1;
  777. }
  778. if ((position + i) % period == 0 && position + i > 0)
  779. {
  780. for (int c = 0; c < channels; ++c)
  781. if (out[c] != nullptr)
  782. out[c][i] = 0.9f;
  783. lastClick = position + i;
  784. }
  785. }
  786. position += n;
  787. }
  788. inputs.store (numIn);
  789. for (int c = 0; c < juce::jmin (numIn, 64); ++c)
  790. if (in[c] != nullptr)
  791. {
  792. const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
  793. const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
  794. if (peak > peaks[(std::size_t) c].load())
  795. peaks[(std::size_t) c].store (peak);
  796. }
  797. ++calls;
  798. }
  799. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  800. void audioDeviceStopped() override {}
  801. } silence;
  802. bool ok = false;
  803. if (device == nullptr)
  804. step ("error=device not found");
  805. else
  806. {
  807. step ("step=open");
  808. juce::BigInteger outputs;
  809. outputs.setRange (0, 2, true);
  810. const auto rates = device->getAvailableSampleRates();
  811. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  812. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  813. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  814. juce::BigInteger inputs;
  815. if (wantInput)
  816. {
  817. const auto names = device->getInputChannelNames();
  818. step ("input_channels=" + juce::String (names.size()));
  819. for (int c = 0; c < names.size(); ++c)
  820. step (" in" + juce::String (c + 1) + "=" + names[c]);
  821. inputs.setRange (0, juce::jmin (64, names.size()), true);
  822. }
  823. // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
  824. const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  825. const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
  826. if (error.isNotEmpty())
  827. step ("error=" + error);
  828. else
  829. {
  830. step ("step=start_callbacks");
  831. silence.roundtrip = args.contains ("--roundtrip");
  832. silence.period = juce::jmax (1, (int) (rate / 4));
  833. silence.delays.reserve (64);
  834. device->start (&silence);
  835. juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
  836. device->stop();
  837. if (silence.roundtrip)
  838. {
  839. auto d = silence.delays;
  840. std::sort (d.begin(), d.end());
  841. report << "roundtrip_clicks=" << (int) d.size() << "\n";
  842. if (! d.empty())
  843. report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
  844. << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
  845. }
  846. report << "rate=" << device->getCurrentSampleRate() << "\n"
  847. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  848. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  849. << "callbacks=" << silence.calls.load() << "\n";
  850. if (wantInput)
  851. {
  852. report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
  853. << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
  854. << "callback_inputs=" << silence.inputs.load() << "\n";
  855. for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
  856. report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
  857. }
  858. ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
  859. device->close();
  860. }
  861. }
  862. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  863. setApplicationReturnValue (ok ? 0 : 1);
  864. quit();
  865. return;
  866. }
  867. if (args.contains ("--scantest"))
  868. {
  869. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  870. const auto i = args.indexOf ("--scantest");
  871. lynx::PluginHost host (false);
  872. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  873. juce::String report;
  874. report << "found=" << found << "\n";
  875. for (const auto& t : host.getKnownPlugins().getTypes())
  876. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  877. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  878. report << " blacklisted: " << f << "\n";
  879. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  880. setApplicationReturnValue (found > 0 ? 0 : 1);
  881. quit();
  882. return;
  883. }
  884. if (args.contains ("--vst2test"))
  885. {
  886. const auto i = args.indexOf ("--vst2test");
  887. runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
  888. return;
  889. }
  890. if (args.contains ("--wrappertest"))
  891. {
  892. const auto i = args.indexOf ("--wrappertest");
  893. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  894. return;
  895. }
  896. if (args.contains ("--plugintest"))
  897. {
  898. const auto i = args.indexOf ("--plugintest");
  899. // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
  900. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  901. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  902. return;
  903. }
  904. if (args.contains ("--claprestarttest"))
  905. {
  906. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
  907. const auto i = args.indexOf ("--claprestarttest");
  908. runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  909. return;
  910. }
  911. if (args.contains ("--editortest"))
  912. {
  913. // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
  914. // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
  915. const auto i = args.indexOf ("--editortest");
  916. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  917. runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  918. return;
  919. }
  920. if (args.contains ("--editorcrashtest"))
  921. {
  922. // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
  923. // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
  924. // that editor, record the trace and keep running its message loop.
  925. const auto i = args.indexOf ("--editorcrashtest");
  926. runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  927. return;
  928. }
  929. if (args.contains ("--plugwintest"))
  930. {
  931. // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
  932. // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
  933. // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
  934. // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
  935. const auto i = args.indexOf ("--plugwintest");
  936. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
  937. auto seconds = 15;
  938. for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
  939. if (args[k].containsOnly ("0123456789"))
  940. seconds = args[k].getIntValue();
  941. runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
  942. return;
  943. }
  944. if (args.contains ("--fittest"))
  945. {
  946. // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
  947. // the screen and a big resizable window that grows with a zoom change keep their title bar and close
  948. // button on the screen. The windows show for about two seconds.
  949. const auto i = args.indexOf ("--fittest");
  950. runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
  951. return;
  952. }
  953. if (args.contains ("--windowtest"))
  954. {
  955. // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
  956. // over the main window and checks that each one stays in front, owned by the main window, with the
  957. // keyboard focus (issue #4). The windows appear on screen for a few seconds.
  958. runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
  959. return;
  960. }
  961. if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
  962. {
  963. const auto i = args.indexOf ("--pluginstyle");
  964. if (i + 1 < args.size())
  965. {
  966. const auto name = args[i + 1].unquoted();
  967. lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
  968. }
  969. }
  970. if (args.contains ("--gfxprobe"))
  971. {
  972. // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
  973. // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
  974. // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
  975. // "no clip" and flooded the whole component (Facet EQ's blank pink window).
  976. const auto i = args.indexOf ("--gfxprobe");
  977. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
  978. quit();
  979. return;
  980. }
  981. if (args.contains ("--steppertest"))
  982. {
  983. // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
  984. // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
  985. const auto i = args.indexOf ("--steppertest");
  986. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  987. juce::String report;
  988. int fails = 0, count = 0, skips = 0;
  989. {
  990. lynx::AudioEngine offline (false);
  991. auto kinds = lynx::plugui::flLayoutKinds();
  992. for (const auto own : lynx::plugui::ownLayoutKinds())
  993. kinds.push_back (own);
  994. // FL's Default preset when the installation has one (the state-backed controls need FL's state)
  995. const auto roots = lynx::findFlStudioRoots();
  996. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  997. for (const auto kind : kinds)
  998. {
  999. auto fx = lynx::makeEffectSlot (kind);
  1000. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1001. {
  1002. juce::MemoryBlock data;
  1003. const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
  1004. if (file.existsAsFile() && file.loadFileAsData (data))
  1005. {
  1006. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  1007. if (auto loaded = lynx::effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), 130.0); loaded && loaded->kind == kind)
  1008. fx = *loaded;
  1009. }
  1010. break;
  1011. }
  1012. lynx::Song song;
  1013. song.mixer.resize (2);
  1014. song.mixer[0].name = "Master";
  1015. song.mixer[1].name = "Insert 1";
  1016. song.mixer[1].effects.push_back (fx);
  1017. offline.setSong (std::move (song));
  1018. offline.dispatchPendingMessages();
  1019. const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
  1020. for (const auto& line : juce::StringArray::fromLines (lines))
  1021. if (line.isNotEmpty())
  1022. {
  1023. ++count;
  1024. fails += line.contains (": FAIL") ? 1 : 0;
  1025. skips += line.contains (": SKIP") ? 1 : 0;
  1026. }
  1027. report << lines;
  1028. juce::PopupMenu::dismissAllActiveMenus();
  1029. offline.dispatchPendingMessages();
  1030. }
  1031. }
  1032. report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
  1033. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1034. quit();
  1035. return;
  1036. }
  1037. if (args.contains ("--plugui"))
  1038. {
  1039. // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
  1040. // loaded with the FL plugin's Default preset when the FL installation has one
  1041. const auto i = args.indexOf ("--plugui");
  1042. runPluginEditorSnapshots (args[i + 1].unquoted());
  1043. return;
  1044. }
  1045. if (args.contains ("--parityshot"))
  1046. {
  1047. // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
  1048. // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
  1049. // of the third-party parity pictures (round tp172b)
  1050. const auto i = args.indexOf ("--parityshot");
  1051. runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1052. quit();
  1053. return;
  1054. }
  1055. if (args.contains ("--design168rshot"))
  1056. {
  1057. // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
  1058. // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
  1059. // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
  1060. const auto i = args.indexOf ("--design168rshot");
  1061. if (i + 2 < args.size() && args[i + 2] == "generated")
  1062. lynx::plugui::showGeneratedLayoutsOnly (true);
  1063. runDesign168rShots (args[i + 1].unquoted());
  1064. quit();
  1065. return;
  1066. }
  1067. if (args.contains ("--eq166fshot"))
  1068. {
  1069. // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
  1070. // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
  1071. // its spectrum over the source's), each fed by the demo song rendered offline
  1072. const auto i = args.indexOf ("--eq166fshot");
  1073. runEq166fShots (args[i + 1].unquoted());
  1074. quit();
  1075. return;
  1076. }
  1077. if (args.contains ("--editorcpu"))
  1078. {
  1079. // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
  1080. // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
  1081. // animates (demo signal) — round 122's check that an idle editor burns no CPU
  1082. const auto i = args.indexOf ("--editorcpu");
  1083. runEditorCpu (args[i + 1].unquoted());
  1084. return;
  1085. }
  1086. if (args.contains ("--precomputeshot"))
  1087. {
  1088. // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
  1089. // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
  1090. const auto i = args.indexOf ("--precomputeshot");
  1091. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1092. lynx::AudioEngine shotEngine (false);
  1093. const juce::File input (args[i + 1].unquoted());
  1094. const auto prefix = args[i + 2].unquoted();
  1095. juce::String error;
  1096. bool ok = false;
  1097. if (input.hasFileExtension ("flp"))
  1098. ok = shotEngine.importFlpFile (input, error);
  1099. else if (auto song = lynx::ProjectFile::load (input, error))
  1100. shotEngine.setSong (std::move (*song)), ok = true;
  1101. shotEngine.dispatchPendingMessages();
  1102. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  1103. if (c == nullptr)
  1104. return false;
  1105. if (c->getWidth() <= 0)
  1106. c->setSize (520, 600);
  1107. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
  1108. return true;
  1109. };
  1110. ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
  1111. ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
  1112. setApplicationReturnValue (ok ? 0 : 1);
  1113. quit();
  1114. return;
  1115. }
  1116. if (args.contains ("--pluginthumbs"))
  1117. {
  1118. // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
  1119. // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
  1120. // the background when pictures are missing. One line per plugin on stdout.
  1121. const auto i = args.indexOf ("--pluginthumbs");
  1122. lynx::crashguard::quietCrashReports();
  1123. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1124. juce::StringArray only;
  1125. if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
  1126. only.addTokens (args[i + 2].unquoted(), ",", "");
  1127. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1128. const auto drawn = lynx::pluginthumbs::renderNative (juce::File (args[i + 1].unquoted()), only, [] (const juce::String& line) {
  1129. std::printf ("%s\n", line.toRawUTF8());
  1130. std::fflush (stdout);
  1131. });
  1132. std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
  1133. setApplicationReturnValue (0);
  1134. quit();
  1135. return;
  1136. }
  1137. if (args.contains ("--artshot"))
  1138. {
  1139. // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
  1140. // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
  1141. // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
  1142. const auto i = args.indexOf ("--artshot");
  1143. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1144. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1145. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1146. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1147. setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
  1148. quit();
  1149. return;
  1150. }
  1151. if (args.contains ("--artgui"))
  1152. {
  1153. // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
  1154. // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
  1155. // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
  1156. // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
  1157. const auto i = args.indexOf ("--artgui");
  1158. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1159. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1160. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1161. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1162. runArtGui (juce::File (args[i + 1].unquoted()), mode);
  1163. return;
  1164. }
  1165. if (args.contains ("--instrumentshot"))
  1166. {
  1167. // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
  1168. // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
  1169. // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
  1170. const auto i = args.indexOf ("--instrumentshot");
  1171. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1172. const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
  1173. setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
  1174. quit();
  1175. return;
  1176. }
  1177. if (args.contains ("--flextrashot"))
  1178. {
  1179. // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
  1180. const auto i = args.indexOf ("--flextrashot");
  1181. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1182. lynx::AudioEngine shotEngine (false);
  1183. const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
  1184. setApplicationReturnValue (ok ? 0 : 1);
  1185. quit();
  1186. return;
  1187. }
  1188. if (args.contains ("--visualtest"))
  1189. {
  1190. // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
  1191. // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
  1192. // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
  1193. const auto i = args.indexOf ("--visualtest");
  1194. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1195. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
  1196. lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
  1197. setApplicationReturnValue (ok ? 0 : 1);
  1198. quit();
  1199. });
  1200. return;
  1201. }
  1202. if (args.contains ("--menu-entry"))
  1203. {
  1204. // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
  1205. // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
  1206. const auto i = args.indexOf ("--menu-entry");
  1207. const auto on = args[i + 1].unquoted() != "off";
  1208. const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
  1209. std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
  1210. : "only the LYNX SHARE AppImage on Linux can do this");
  1211. setApplicationReturnValue (ok ? 0 : 1);
  1212. quit();
  1213. return;
  1214. }
  1215. if (args.contains ("--send-test-report"))
  1216. {
  1217. // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
  1218. // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
  1219. // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
  1220. const auto i = args.indexOf ("--send-test-report");
  1221. const juce::File out (args[i + 1].unquoted());
  1222. lynx::crashreporter::Session session;
  1223. session.version = getApplicationVersion();
  1224. for (const auto* pattern : { "crash *.txt", "hang *.txt" })
  1225. {
  1226. auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
  1227. lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
  1228. if (! files.isEmpty())
  1229. (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
  1230. }
  1231. session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
  1232. auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
  1233. input.test = true;
  1234. const auto json = lynx::crashreporter::buildJson (input, false);
  1235. out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
  1236. const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
  1237. out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
  1238. + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
  1239. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  1240. quit();
  1241. return;
  1242. }
  1243. if (args.contains ("--symbolize"))
  1244. {
  1245. // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
  1246. // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
  1247. const auto i = args.indexOf ("--symbolize");
  1248. const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
  1249. juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
  1250. quit();
  1251. return;
  1252. }
  1253. if (args.contains ("--opentest"))
  1254. {
  1255. // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
  1256. // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
  1257. // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
  1258. const auto i = args.indexOf ("--opentest");
  1259. runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
  1260. setApplicationReturnValue (ok ? 0 : 1);
  1261. quit();
  1262. });
  1263. return;
  1264. }
  1265. if (args.contains ("--fxfuzz"))
  1266. {
  1267. // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
  1268. // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
  1269. const auto i = args.indexOf ("--fxfuzz");
  1270. const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
  1271. // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
  1272. const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
  1273. setApplicationReturnValue (ok ? 0 : 1);
  1274. quit();
  1275. return;
  1276. }
  1277. if (args.contains ("--controllershot"))
  1278. {
  1279. // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
  1280. const auto i = args.indexOf ("--controllershot");
  1281. runControllerShot (args[i + 1].unquoted());
  1282. quit();
  1283. return;
  1284. }
  1285. if (args.contains ("--edisonshot"))
  1286. {
  1287. // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
  1288. // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
  1289. const auto i = args.indexOf ("--edisonshot");
  1290. runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1291. quit();
  1292. return;
  1293. }
  1294. if (args.contains ("--danceshot"))
  1295. {
  1296. // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
  1297. // and a demo project with two dance channels (for --snapshot)
  1298. const auto i = args.indexOf ("--danceshot");
  1299. runDanceShot (args[i + 1].unquoted());
  1300. quit();
  1301. return;
  1302. }
  1303. if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
  1304. {
  1305. // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
  1306. // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
  1307. const auto i = args.indexOf ("--videoshot");
  1308. runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1309. return;
  1310. }
  1311. if (args.contains ("--vfxshot"))
  1312. {
  1313. // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
  1314. const auto i = args.indexOf ("--vfxshot");
  1315. runVfxShot (args[i + 1].unquoted());
  1316. quit();
  1317. return;
  1318. }
  1319. if (args.contains ("--patchershot"))
  1320. {
  1321. // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
  1322. const auto i = args.indexOf ("--patchershot");
  1323. runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1324. quit();
  1325. return;
  1326. }
  1327. if (args.contains ("--feat166shot"))
  1328. {
  1329. // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
  1330. // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
  1331. // its end, and the time a full repaint takes)
  1332. const auto i = args.indexOf ("--feat166shot");
  1333. runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1334. quit();
  1335. return;
  1336. }
  1337. if (args.contains ("--perfshot"))
  1338. {
  1339. // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
  1340. // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
  1341. // for --patchershot (round 165m)
  1342. const auto i = args.indexOf ("--perfshot");
  1343. runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1344. quit();
  1345. return;
  1346. }
  1347. if (args.contains ("--typeaheadtest"))
  1348. {
  1349. // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
  1350. // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
  1351. const auto i = args.indexOf ("--typeaheadtest");
  1352. runTypeAheadTest (juce::File (args[i + 1].unquoted()));
  1353. return;
  1354. }
  1355. if (args.contains ("--choosertest"))
  1356. {
  1357. // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
  1358. // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
  1359. // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
  1360. const auto i = args.indexOf ("--choosertest");
  1361. runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1362. return;
  1363. }
  1364. if (args.contains ("--snapshot"))
  1365. {
  1366. const auto i = args.indexOf ("--snapshot");
  1367. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1368. return;
  1369. }
  1370. if (args.contains ("--stemsplit"))
  1371. {
  1372. // LYNX.exe --stemsplit input.wav folder: the stem separation of the clip menu, without the window
  1373. const auto i = args.indexOf ("--stemsplit");
  1374. lynx::AudioEngine loader (false);
  1375. const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1376. juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  1377. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  1378. quit();
  1379. return;
  1380. }
  1381. if (args.contains ("--stems"))
  1382. {
  1383. // LYNX.exe --stems project base.wav: one WAV per insert that has sound (like "Export stems")
  1384. const auto i = args.indexOf ("--stems");
  1385. juce::String error, report;
  1386. int written = 0;
  1387. {
  1388. lynx::AudioEngine loader (false);
  1389. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  1390. auto ok = input.hasFileExtension ("flp") ? loader.importFlpFile (input, error) : false;
  1391. if (! input.hasFileExtension ("flp"))
  1392. if (auto song = lynx::ProjectFile::load (input, error))
  1393. {
  1394. loader.setSong (std::move (*song));
  1395. ok = true;
  1396. }
  1397. const auto& song = loader.getSong();
  1398. for (int t = 1; ok && t < (int) song.mixer.size(); ++t)
  1399. {
  1400. if (std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  1401. continue;
  1402. const auto file = base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav");
  1403. lynx::ExportSettings settings;
  1404. lynx::ExportJob job (lynx::makeBounceSong (song, t), settings, file);
  1405. if (job.run ({}, error))
  1406. {
  1407. ++written;
  1408. report << file.getFileName() << " peak=" << job.getPeak() << "\n";
  1409. }
  1410. }
  1411. }
  1412. report << "stems=" << written << "\n";
  1413. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  1414. setApplicationReturnValue (written > 0 ? 0 : 1);
  1415. quit();
  1416. return;
  1417. }
  1418. if (args.contains ("--export-flp"))
  1419. {
  1420. const auto i = args.indexOf ("--export-flp");
  1421. runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
  1422. return;
  1423. }
  1424. if (args.contains ("--export"))
  1425. {
  1426. const auto i = args.indexOf ("--export");
  1427. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  1428. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  1429. return;
  1430. }
  1431. if (args.contains ("--render"))
  1432. {
  1433. const auto i = args.indexOf ("--render");
  1434. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  1435. return;
  1436. }
  1437. // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
  1438. uncleanLastStep = collectUncleanSessions();
  1439. sessionsFolder().createDirectory();
  1440. lynx::crashguard::beginSession (
  1441. sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
  1442. ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
  1443. + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
  1444. + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
  1445. startHangWatch();
  1446. startupTrace.mark ("initialise (normal start)");
  1447. if (startupTrace.on)
  1448. lynx::startupMark = startupMarkHook;
  1449. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1450. lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
  1451. startupOptions = lynx::StartupOptions::load();
  1452. lynx::registerFileTypes();
  1453. startupTrace.mark ("options + file types");
  1454. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument.
  1455. if (args.size() > 0 && juce::File::isAbsolutePath (args[0].unquoted()))
  1456. fileToOpen = juce::File (args[0].unquoted());
  1457. // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
  1458. // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
  1459. // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
  1460. if (args.contains ("--opentime"))
  1461. {
  1462. const auto i = args.indexOf ("--opentime");
  1463. const auto project = args[i + 1].unquoted();
  1464. fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
  1465. openTimeReport = juce::File (args[i + 2].unquoted());
  1466. if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
  1467. openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
  1468. }
  1469. if (! startupOptions.splash)
  1470. {
  1471. startEngine();
  1472. createMainWindow();
  1473. mainWindow->reveal();
  1474. showUncleanNotice();
  1475. startupTrace.mark ("window revealed");
  1476. openStartupFile();
  1477. startupTrace.mark ("startup file opened");
  1478. startOpenTimeProbe();
  1479. startUpdateCheck();
  1480. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  1481. return;
  1482. }
  1483. // the splash first, so it is on screen while the audio device opens; the main window is built
  1484. // once the pepper has landed (the scene is still for a moment then) and shown when the splash ends
  1485. splash = std::make_unique<lynx::SplashScreen>();
  1486. startupTrace.mark ("splash made");
  1487. splash->showOnDesktop();
  1488. startupTrace.mark ("splash on the desktop");
  1489. juce::Timer::callAfterDelay (40, [this] {
  1490. startEngine();
  1491. if (splash == nullptr) // quit meanwhile
  1492. return;
  1493. splash->setStatus (lynx::tr ("Loading the workspace..."));
  1494. splash->startClock();
  1495. // the minimum counts from the process start (the audio device took part of it already)
  1496. splashDuration = lynx::SplashScreen::remainingDuration (startupTrace.seconds());
  1497. splash->setBarDuration (splashDuration);
  1498. juce::Timer::callAfterDelay (1050, [this] {
  1499. if (splash == nullptr || engine == nullptr)
  1500. return;
  1501. createMainWindow();
  1502. const auto wait = juce::jmax (0.0, splashDuration - splash->getElapsed());
  1503. juce::Timer::callAfterDelay ((int) (wait * 1000.0), [this] {
  1504. if (splash == nullptr || mainWindow == nullptr)
  1505. return;
  1506. mainWindow->reveal();
  1507. startupTrace.mark ("window revealed (after the splash)");
  1508. splash->toFront (false);
  1509. splash->finish ([this] { splash = nullptr; });
  1510. showUncleanNotice();
  1511. openStartupFile();
  1512. startupTrace.mark ("startup file opened");
  1513. startOpenTimeProbe();
  1514. startUpdateCheck();
  1515. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  1516. // first run: language, audio, plugin folders (FL Studio's included) and a background scan
  1517. if (! lynx::setupWizardDone() && lynx::platform::testMode())
  1518. lynx::platform::testModeLog ("setup wizard");
  1519. else if (! lynx::setupWizardDone())
  1520. mainWindow->showSetupWizard();
  1521. });
  1522. });
  1523. });
  1524. }
  1525. void startEngine()
  1526. {
  1527. startupTrace.mark ("before the audio engine");
  1528. engine = std::make_unique<lynx::AudioEngine>();
  1529. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  1530. startupTrace.mark ("audio engine + device");
  1531. crashEngine = engine.get();
  1532. lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
  1533. addDriverFileDeviceType();
  1534. if (startupOptions.sound)
  1535. {
  1536. // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
  1537. std::shared_ptr<const lynx::SampleData> sound;
  1538. if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
  1539. sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
  1540. engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
  1541. }
  1542. startupTrace.mark ("startup sound");
  1543. // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
  1544. // thread, while the splash and the main window come up (round 121)
  1545. if (fileToOpen.hasFileExtension ("flp"))
  1546. if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
  1547. try
  1548. {
  1549. engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  1550. startupTrace.mark ("plugin modules started ahead");
  1551. }
  1552. catch (const flp::Error&)
  1553. {
  1554. }
  1555. }
  1556. void createMainWindow()
  1557. {
  1558. mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
  1559. lynx::setMainWindowForOwnership (mainWindow.get());
  1560. lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
  1561. lynx::startRenderingWatch();
  1562. startupTrace.mark ("main window built");
  1563. }
  1564. // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
  1565. // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
  1566. void showUncleanNotice()
  1567. {
  1568. if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
  1569. {
  1570. if (uncleanLastStep.isNotEmpty())
  1571. lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
  1572. return;
  1573. }
  1574. if (uncleanLastStep.isEmpty())
  1575. {
  1576. lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
  1577. return;
  1578. }
  1579. auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
  1580. "LYNX SHARE's autosave folder; details in crash-history.log.",
  1581. { uncleanLastStep });
  1582. uncleanLastStep.clear();
  1583. const auto cause = uncleanCause();
  1584. // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
  1585. // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
  1586. juce::String separatePlugin;
  1587. if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
  1588. separatePlugin = cause.editorPlugin;
  1589. // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
  1590. else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
  1591. {
  1592. lynx::setGpuRenderingEnabled (false);
  1593. message << "\n\n"
  1594. << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
  1595. "rendering back on in Options > General settings (after a driver update, for example).",
  1596. { cause.driverModule });
  1597. }
  1598. // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
  1599. // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
  1600. for (int i = uncleanSteps.size(); --i >= 0;)
  1601. {
  1602. if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
  1603. break;
  1604. if (uncleanSteps[i].contains (lynx::visualgl::startNote))
  1605. {
  1606. if (lynx::visualgl::enabled())
  1607. {
  1608. lynx::visualgl::setEnabled (false);
  1609. message << "\n\n"
  1610. << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
  1611. "button turns it back on.");
  1612. }
  1613. break;
  1614. }
  1615. }
  1616. const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
  1617. auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
  1618. const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
  1619. lynx::crashreporter::retryPending();
  1620. if (action == lynx::crashreport::Action::askUser)
  1621. {
  1622. if (separatePlugin.isNotEmpty())
  1623. message << "\n\n"
  1624. << lynx::tr ("It happened while the window of {0} was opening{1}.",
  1625. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
  1626. lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
  1627. devices);
  1628. return;
  1629. }
  1630. if (action == lynx::crashreport::Action::sendSilently)
  1631. {
  1632. const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
  1633. lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
  1634. message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
  1635. }
  1636. if (separatePlugin.isNotEmpty())
  1637. {
  1638. juce::AlertWindow::showOkCancelBox (
  1639. juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
  1640. message + "\n\n"
  1641. + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
  1642. "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
  1643. "separate process\").",
  1644. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
  1645. lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
  1646. juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
  1647. if (result != 0)
  1648. lynx::setPluginAlwaysSeparate (separatePlugin, true);
  1649. }));
  1650. return;
  1651. }
  1652. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
  1653. }
  1654. // --opentime: after the start-up file was handed to the window
  1655. void startOpenTimeProbe()
  1656. {
  1657. if (openTimeReport == juce::File())
  1658. return;
  1659. struct Probe final : juce::Timer
  1660. {
  1661. LynxApplication& app;
  1662. juce::File report, project;
  1663. int idleSeconds;
  1664. int phase = 0; // 0 loading, 1 settling, 2 idle measurement
  1665. double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
  1666. double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
  1667. Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
  1668. : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
  1669. {
  1670. revealedS = startupTrace.seconds();
  1671. startTimer (250);
  1672. }
  1673. bool loaded() const
  1674. {
  1675. if (project == juce::File())
  1676. return true;
  1677. return app.mainWindow != nullptr
  1678. && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
  1679. }
  1680. void finish (const juce::String& result)
  1681. {
  1682. stopTimer();
  1683. const auto now = startupTrace.seconds();
  1684. const auto cpu = lynx::processCpuSeconds();
  1685. juce::String text;
  1686. text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
  1687. << "window_s=" << juce::String (revealedS, 3) << "\n"
  1688. << "loaded_s=" << juce::String (loadedS, 3) << "\n"
  1689. << "settled_s=" << juce::String (settledS, 3) << "\n"
  1690. << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
  1691. << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
  1692. << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
  1693. << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
  1694. << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
  1695. << "result=" << result << "\n";
  1696. report.replaceWithText (text);
  1697. app.setApplicationReturnValue (result == "OK" ? 0 : 1);
  1698. app.quit();
  1699. }
  1700. void timerCallback() override
  1701. {
  1702. const auto now = startupTrace.seconds();
  1703. const auto cpu = lynx::processCpuSeconds();
  1704. if (phase == 0)
  1705. {
  1706. if (loaded())
  1707. {
  1708. loadedS = now;
  1709. cpuAtLoaded = cpu;
  1710. phase = 1;
  1711. lastCpu = cpu;
  1712. lastT = now;
  1713. }
  1714. else if (now - revealedS > 240.0)
  1715. finish ("TIMEOUT loading");
  1716. return;
  1717. }
  1718. if (phase == 1)
  1719. {
  1720. // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
  1721. const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
  1722. lastCpu = cpu;
  1723. lastT = now;
  1724. if (use < 10.0)
  1725. {
  1726. if (quietSince < 0.0)
  1727. quietSince = now - 0.25;
  1728. if (now - quietSince >= 1.5)
  1729. settledS = quietSince;
  1730. }
  1731. else
  1732. quietSince = -1.0;
  1733. if (settledS >= 0.0 || now - loadedS > 30.0)
  1734. {
  1735. phase = 2;
  1736. idleCpu0 = cpu;
  1737. idleT0 = now;
  1738. }
  1739. return;
  1740. }
  1741. if (now - idleT0 >= (double) idleSeconds)
  1742. finish ("OK");
  1743. }
  1744. };
  1745. perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
  1746. }
  1747. // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
  1748. // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
  1749. void startUpdateCheck()
  1750. {
  1751. if (openTimeReport != juce::File())
  1752. return;
  1753. lynx::updater::afterStart();
  1754. juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
  1755. }
  1756. void openStartupFile()
  1757. {
  1758. if (fileToOpen != juce::File() && mainWindow != nullptr)
  1759. mainWindow->openFile (fileToOpen);
  1760. }
  1761. void shutdown() override
  1762. {
  1763. if (relaunched || updateHelper)
  1764. return; // the copy that ran owns the session (its crash notes stay for the next start)
  1765. lynx::crashguard::note ("closing");
  1766. lynx::shutdownPluginSandboxWorker();
  1767. splash = nullptr;
  1768. lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
  1769. if (mainWindow != nullptr && mainWindow->isVisible())
  1770. mainWindow->saveState();
  1771. mainWindow = nullptr; // the UI goes before the engine
  1772. lynx::updater::shutdown(); // (a check or download in flight stops)
  1773. crashEngine = nullptr;
  1774. engine = nullptr;
  1775. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  1776. heartbeat.stopTimer();
  1777. lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
  1778. lynx::crashguard::stopHangWatch();
  1779. lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
  1780. // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
  1781. // teardown runs (some crash in it at exit, round 111)
  1782. if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
  1783. lynx::crashguard::exitNow (getApplicationReturnValue());
  1784. }
  1785. void systemRequestedQuit() override
  1786. {
  1787. if (mainWindow != nullptr)
  1788. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  1789. else
  1790. quit();
  1791. }
  1792. private:
  1793. // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
  1794. // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
  1795. struct Heartbeat final : juce::Timer
  1796. {
  1797. void timerCallback() override { lynx::crashguard::heartbeat(); }
  1798. } heartbeat;
  1799. void startHangWatch()
  1800. {
  1801. const auto folder = lynx::platform::settingsFile ("autosave");
  1802. folder.createDirectory();
  1803. // keep the newest hang files only
  1804. auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
  1805. lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
  1806. for (int i = 20; i < old.size(); ++i)
  1807. old.getReference (i).deleteFile();
  1808. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
  1809. heartbeat.startTimerHz (5);
  1810. }
  1811. bool sandboxChild = false;
  1812. bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
  1813. bool updateHelper = false; // --apply-update (round 166b)
  1814. juce::String uncleanLastStep; // last step of a previous run that ended without closing
  1815. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  1816. // Exit code 0 = audio came out, 1 = silence.
  1817. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  1818. {
  1819. lynx::AudioEngine offline (false);
  1820. const auto peak = offline.renderOffline (2.0, 48000.0);
  1821. const auto audioOk = peak > 0.01f && peak < 10.0f;
  1822. // project format round trip, with accents in the name
  1823. auto original = lynx::Song::makeDefault();
  1824. original.channels[0].name = "Bumbo ação";
  1825. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  1826. original.mode = lynx::PlayMode::song;
  1827. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  1828. original.mixer[3].effects[0].params[1] = 0.25f;
  1829. lynx::Automation automation;
  1830. automation.name = "Pan";
  1831. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  1832. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  1833. original.automations.push_back (automation);
  1834. lynx::Clip automationClip;
  1835. automationClip.kind = lynx::ClipKind::automation;
  1836. automationClip.automation = 0;
  1837. automationClip.track = 4;
  1838. automationClip.length = 3840;
  1839. original.playlist.push_back (automationClip);
  1840. original.loopStart = 960;
  1841. original.loopEnd = 7680;
  1842. original.playlistTracks.resize (3);
  1843. original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
  1844. original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
  1845. original.playlistTracks[1].collapsed = true;
  1846. original.channelGroups = { "Drums", "Keys" };
  1847. original.channels[1].group = 1;
  1848. juce::String error;
  1849. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  1850. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  1851. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  1852. const auto projectOk = reloaded && reloaded->channels.size() == original.channels.size()
  1853. && reloaded->channels[0].name == original.channels[0].name
  1854. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  1855. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  1856. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  1857. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  1858. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  1859. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  1860. && reloaded->automations[0].points[1].tick == 3840
  1861. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  1862. && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
  1863. && reloaded->playlistTracks[1].colour == 0
  1864. && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
  1865. && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
  1866. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  1867. && reloaded->mixer[3].effects.size() == 1
  1868. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  1869. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  1870. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  1871. auto rich = lynx::Song::makeDefault();
  1872. auto& synth = rich.channels[4].synth;
  1873. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  1874. synth.filterType = 2;
  1875. synth.mono = true;
  1876. synth.portaBeats = 0.125f;
  1877. synth.am = true;
  1878. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  1879. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  1880. auto& sampler = rich.channels[0].sampler;
  1881. sampler.cutoff = 1200.0f;
  1882. sampler.resonance = 0.3f;
  1883. sampler.filterType = 1;
  1884. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  1885. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  1886. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  1887. rich.mixer[2].eq.hz[1] = 2200.0f;
  1888. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  1889. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  1890. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  1891. rich.mixer[2].effects.push_back (peqSlot);
  1892. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  1893. utilitySlot.params[1] = 0.2f;
  1894. rich.mixer[2].effects.push_back (utilitySlot);
  1895. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  1896. for (int i = 0; i < 300; ++i)
  1897. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  1898. vocodexSlot.sidechain = 1;
  1899. vocodexSlot.sidechain2 = 2;
  1900. rich.mixer[3].effects.push_back (vocodexSlot);
  1901. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  1902. rich.addMarker ({ 7680, {}, 7, 8 });
  1903. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  1904. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  1905. for (std::size_t i = 0; i < a.size(); ++i)
  1906. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  1907. return false;
  1908. return true;
  1909. };
  1910. const auto richOk = richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  1911. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  1912. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  1913. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  1914. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  1915. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  1916. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  1917. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  1918. && richBack->markers() == rich.markers();
  1919. // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
  1920. bool hwOutOk = false;
  1921. {
  1922. auto song = lynx::Song::makeDefault();
  1923. const auto plain = lynx::ProjectFile::toJson (song);
  1924. song.mixer[0].outputChannel = lynx::outputNone;
  1925. song.mixer[1].outputChannel = 2;
  1926. song.mixer[1].outputMode = lynx::OutputMode::monoRight;
  1927. song.mixer[2].outputChannel = 6;
  1928. song.mixer[3].outputChannel = 4;
  1929. song.mixer[3].outputMode = lynx::OutputMode::monoSum;
  1930. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  1931. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  1932. hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
  1933. && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
  1934. && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
  1935. && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
  1936. && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
  1937. }
  1938. // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
  1939. // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
  1940. bool flp168jOk = false;
  1941. {
  1942. auto song = lynx::Song::makeDefault();
  1943. const auto plain = lynx::ProjectFile::toJson (song);
  1944. song.channels[0].icon = 75;
  1945. song.mixer[2].icon = 71;
  1946. song.playlistTracks.resize (3);
  1947. song.playlistTracks[2].icon = 30;
  1948. song.autoPdc = false;
  1949. song.compensateAutomations = false;
  1950. song.timeSignatureMode = true;
  1951. song.scaleHighlight = { 10, 5 };
  1952. song.dataFolder = "D:\\Projects\\data";
  1953. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  1954. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  1955. flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
  1956. && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
  1957. && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
  1958. && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
  1959. && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
  1960. && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
  1961. }
  1962. // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
  1963. // them has neither in its file and loads with the option off
  1964. bool blocksOk = false;
  1965. {
  1966. auto song = lynx::Song::makeDefault();
  1967. const auto plain = lynx::ProjectFile::toJson (song);
  1968. song.patternBlocksOn = true;
  1969. lynx::patternblocks::place (song, 0, 0);
  1970. lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
  1971. song.addArrangement ("Second");
  1972. lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
  1973. song.selectArrangement (0);
  1974. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  1975. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  1976. blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2
  1977. && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
  1978. && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
  1979. && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
  1980. && ! plain.contains ("patternBlocks");
  1981. }
  1982. // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
  1983. // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
  1984. bool polyOk = false;
  1985. {
  1986. auto song = lynx::Song::makeDefault();
  1987. lynx::ChannelDef osc;
  1988. osc.instrument = lynx::InstrumentKind::threeosc;
  1989. osc.misc.mono = osc.misc.porta = true;
  1990. osc.misc.portaBeats = 0.25f;
  1991. song.channels.push_back (osc);
  1992. auto old = osc;
  1993. old.misc = {};
  1994. old.synth.mono = old.synth.porta = true;
  1995. old.synth.portaBeats = 0.5f;
  1996. song.channels.push_back (old);
  1997. old.maxPolyphony = 1;
  1998. song.channels.push_back (old);
  1999. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2000. const auto n = song.channels.size();
  2001. polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
  2002. && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
  2003. && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
  2004. && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
  2005. && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
  2006. }
  2007. // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
  2008. bool latencyOk = false;
  2009. {
  2010. auto song = lynx::Song::makeDefault();
  2011. const auto plain = lynx::ProjectFile::toJson (song);
  2012. song.mixer[1].latencyMs = -20.0f;
  2013. song.mixer[2].latencyMs = 12.5f;
  2014. song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
  2015. song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  2016. song.mixer[3].compensateMasterLatency = false;
  2017. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2018. latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
  2019. && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
  2020. && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
  2021. && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
  2022. && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
  2023. }
  2024. // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
  2025. // original reference byte for byte (.flp record and LYNX plugin state)
  2026. bool substituteOk = false;
  2027. {
  2028. auto song = lynx::Song::makeDefault();
  2029. lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
  2030. vv.format = lynx::ForeignPlugin::Format::vst3;
  2031. const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
  2032. std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
  2033. vv.hasClassId = true;
  2034. vv.name = "ValhallaVintageVerb";
  2035. vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
  2036. for (int i = 0; i < 777; ++i)
  2037. vv.state.push_back ((std::uint8_t) (i * 13 + 1));
  2038. lynx::EffectSlot fromFlp;
  2039. fromFlp.kind = lynx::EffectKind::plugin;
  2040. fromFlp.plugin.foreign = vv;
  2041. lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
  2042. fromLynx.kind = lynx::EffectKind::plugin;
  2043. fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
  2044. fromLynx.plugin.name = "FabFilter Pro-Q 3";
  2045. fromLynx.plugin.state = "AAECAwQFBgcICQ==";
  2046. const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
  2047. song.mixer[1].effects = { fromFlp, fromLynx };
  2048. const auto substitutesOn = lynx::pluginSubstitutesEnabled();
  2049. const auto changed = offline.getPluginHost().applySubstitutes (song);
  2050. auto& fx = song.mixer[1].effects;
  2051. // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
  2052. const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
  2053. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2054. substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
  2055. && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
  2056. && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
  2057. && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
  2058. && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
  2059. }
  2060. // undo/redo
  2061. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  2062. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  2063. offline.undo();
  2064. const auto afterUndo = offline.getSong().bpm;
  2065. offline.redo();
  2066. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  2067. && offline.isModified();
  2068. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  2069. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  2070. offline.setRecording (true);
  2071. offline.play();
  2072. offline.getTransport().positionTicks.store (960.0);
  2073. offline.sendLiveNote (2, 72, 0.9f, true, true);
  2074. offline.getTransport().positionTicks.store (1920.0);
  2075. offline.sendLiveNote (2, 72, 0.0f, false, true);
  2076. offline.setRecording (false);
  2077. offline.stop();
  2078. const auto& recorded = offline.getSong().patterns[0].notes;
  2079. const auto recordOk = recorded.size() == notesBefore + 1
  2080. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  2081. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  2082. });
  2083. offline.undo();
  2084. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  2085. // MIDI: exporting the pattern and importing it back gives the same notes
  2086. bool midiOk = false;
  2087. {
  2088. auto source = lynx::Song::makeDefault();
  2089. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  2090. source.patterns[0].sortNotes();
  2091. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  2092. juce::String midiError;
  2093. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  2094. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  2095. midiFile.deleteFile();
  2096. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  2097. && std::abs (song->bpm - source.bpm) < 0.01)
  2098. {
  2099. midiOk = true;
  2100. const auto& a = source.patterns[0].notes;
  2101. const auto& b = song->patterns[0].notes;
  2102. for (std::size_t i = 0; i < a.size(); ++i)
  2103. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  2104. }
  2105. }
  2106. // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
  2107. // finds its sample inside the extracted folder
  2108. bool packageOk = false;
  2109. {
  2110. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
  2111. dir.deleteRecursively();
  2112. dir.getChildFile ("src").createDirectory();
  2113. const auto wav = dir.getChildFile ("src/hit.wav");
  2114. {
  2115. juce::WavAudioFormat format;
  2116. juce::AudioBuffer<float> hit (1, 480);
  2117. for (int i = 0; i < 480; ++i)
  2118. hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
  2119. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  2120. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  2121. {
  2122. out.release();
  2123. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  2124. writer->writeFromAudioSampleBuffer (hit, 0, 480);
  2125. }
  2126. }
  2127. auto source = lynx::Song::makeDefault();
  2128. lynx::ChannelDef c;
  2129. c.name = "Hit";
  2130. c.instrument = lynx::InstrumentKind::sampler;
  2131. c.samplePath = wav.getFullPathName().toStdString();
  2132. source.channels.push_back (c);
  2133. lynx::ProjectPackage::Result packed;
  2134. juce::String packageError;
  2135. const auto zip = dir.getChildFile ("Beat.zip");
  2136. if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
  2137. {
  2138. const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
  2139. const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
  2140. if (song && ! song->channels.empty())
  2141. {
  2142. const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
  2143. packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
  2144. }
  2145. }
  2146. dir.deleteRecursively();
  2147. }
  2148. // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
  2149. // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
  2150. juce::String sessionResult = "ERROR";
  2151. {
  2152. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
  2153. dir.deleteRecursively();
  2154. dir.getChildFile ("src").createDirectory();
  2155. const auto wav = dir.getChildFile ("src/hit.wav");
  2156. {
  2157. juce::WavAudioFormat format;
  2158. juce::AudioBuffer<float> hit (1, 4800);
  2159. for (int i = 0; i < 4800; ++i)
  2160. hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
  2161. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  2162. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  2163. {
  2164. out.release();
  2165. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  2166. writer->writeFromAudioSampleBuffer (hit, 0, 4800);
  2167. }
  2168. }
  2169. auto host = lynx::Song::makeDefault();
  2170. host.mode = lynx::PlayMode::song;
  2171. const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
  2172. wav.copyFileTo (copyOfWav);
  2173. for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
  2174. {
  2175. lynx::ChannelDef c;
  2176. c.name = name;
  2177. c.instrument = lynx::InstrumentKind::sampler;
  2178. c.samplePath = file.getFullPathName().toStdString();
  2179. host.channels.push_back (c);
  2180. }
  2181. const auto hitChannel = (int) host.channels.size() - 2;
  2182. lynx::Note hitNote;
  2183. hitNote.channel = hitChannel;
  2184. hitNote.length = 480;
  2185. host.patterns[0].notes.push_back (hitNote);
  2186. host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.beatsPerBar), 0 });
  2187. lynx::uids::normalize (host);
  2188. const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
  2189. juce::String e;
  2190. std::vector<lynx::sessionpack::Rendered> rendered;
  2191. // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
  2192. const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
  2193. const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
  2194. && rendered.size() == 1 && rendered[0].standIns.size() == 2
  2195. && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
  2196. if (renderedOk)
  2197. lynx::sessionpack::apply (host, rendered);
  2198. lynx::sessionpack::Manifest m;
  2199. m.projectName = "Selftest";
  2200. m.from = *host.session.find (lynx::session::hostTag);
  2201. m.to = *host.session.find (2);
  2202. lynx::sessionpack::WriteResult written;
  2203. const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
  2204. const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
  2205. && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
  2206. auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
  2207. bool openOk = false, mergeOk = false;
  2208. if (opened && opened->corrupt.isEmpty())
  2209. {
  2210. const auto& g = opened->song;
  2211. const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
  2212. openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
  2213. && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
  2214. && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
  2215. // the guest adds a channel and a pattern of his own, sends his part back
  2216. auto copy = g;
  2217. lynx::ChannelDef mine;
  2218. mine.name = "Ana's hit";
  2219. mine.instrument = lynx::InstrumentKind::sampler;
  2220. mine.samplePath = sample.getFullPathName().toStdString();
  2221. copy.channels.push_back (mine);
  2222. lynx::Pattern p;
  2223. p.name = "Ana";
  2224. lynx::Note note;
  2225. note.channel = (int) copy.channels.size() - 1;
  2226. note.length = 240;
  2227. note.key = 64;
  2228. p.notes.push_back (note);
  2229. copy.patterns.push_back (p);
  2230. lynx::uids::normalize (copy);
  2231. // its uids survive a save and a load
  2232. const auto saved = dir.getChildFile ("guest.lynx");
  2233. auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
  2234. lynx::sessionpack::Manifest back;
  2235. back.part = true;
  2236. back.from = *copy.session.self();
  2237. const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
  2238. lynx::sessionpack::WriteResult partWritten;
  2239. auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
  2240. ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
  2241. : false;
  2242. auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
  2243. if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
  2244. {
  2245. const auto report = lynx::parts::merge (host, partOpened->song, 2);
  2246. const auto& added = host.channels.back();
  2247. mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
  2248. && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
  2249. && host.channels[(std::size_t) hitChannel].name == "Hit";
  2250. }
  2251. }
  2252. // a crafted package whose project points at a file elsewhere on this computer: opening it must not
  2253. // reach that file, or merging would copy it into the project and the next package would send it on
  2254. if (mergeOk)
  2255. {
  2256. const auto secret = dir.getChildFile ("secret.wav");
  2257. wav.copyFileTo (secret);
  2258. auto evil = lynx::Song::makeDefault();
  2259. lynx::ChannelDef c;
  2260. c.instrument = lynx::InstrumentKind::sampler;
  2261. c.samplePath = secret.getFullPathName().toStdString();
  2262. evil.channels.push_back (c);
  2263. lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
  2264. keys.instrument = lynx::InstrumentKind::flkeys;
  2265. keys.zones.push_back ({});
  2266. keys.zones.back().path = c.samplePath;
  2267. evil.channels.push_back (keys);
  2268. lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
  2269. patch.instrument = lynx::InstrumentKind::patcher;
  2270. patch.patcher.nodes.resize (2);
  2271. patch.patcher.nodes[0].generator = true;
  2272. patch.patcher.nodes[0].channel = c;
  2273. patch.patcher.nodes[1].effect.samplePath = c.samplePath;
  2274. evil.channels.push_back (patch);
  2275. evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
  2276. const auto evilProject = dir.getChildFile ("evil.lynx");
  2277. lynx::sessionpack::Manifest em;
  2278. em.part = true;
  2279. juce::ZipFile::Builder b;
  2280. const auto json = lynx::sessionpack::manifestToJson (em);
  2281. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  2282. const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
  2283. bool zipped = false;
  2284. if (lynx::ProjectFile::save (evil, evilProject, e))
  2285. {
  2286. b.addFile (evilProject, 0, "project.lynx");
  2287. juce::FileOutputStream out (evilPack);
  2288. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  2289. }
  2290. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
  2291. const auto media = dir.getChildFile ("Session media/Evil");
  2292. mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
  2293. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  2294. return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
  2295. || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
  2296. })
  2297. && evilOpened->song.channels.back().patcher.nodes.size() == 2
  2298. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
  2299. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
  2300. && evilOpened->song.mixer[1].recordTo.empty()
  2301. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  2302. if (! mergeOk && e.isEmpty())
  2303. e = "a received package reached a file outside it";
  2304. }
  2305. // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
  2306. // media entry outside the package (it must not even be read: "/dev/zero" would never end)
  2307. if (mergeOk)
  2308. {
  2309. const auto secret = dir.getChildFile ("secret.wav");
  2310. const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
  2311. const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
  2312. const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
  2313. auto evil = lynx::Song::makeDefault();
  2314. for (const auto& path : { climb, dotted })
  2315. {
  2316. lynx::ChannelDef c;
  2317. c.instrument = lynx::InstrumentKind::sampler;
  2318. c.samplePath = path.toStdString();
  2319. evil.channels.push_back (c);
  2320. }
  2321. juce::MemoryBlock secretBytes;
  2322. secret.loadFileAsData (secretBytes);
  2323. lynx::sessionpack::Manifest em;
  2324. em.part = true;
  2325. em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
  2326. "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
  2327. const auto evilProject = dir.getChildFile ("evil2.lynx");
  2328. juce::ZipFile::Builder b;
  2329. const auto json = lynx::sessionpack::manifestToJson (em);
  2330. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  2331. const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
  2332. bool zipped = false;
  2333. if (lynx::ProjectFile::save (evil, evilProject, e))
  2334. {
  2335. b.addFile (evilProject, 0, "project.lynx");
  2336. juce::FileOutputStream out (evilPack);
  2337. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  2338. }
  2339. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
  2340. const auto media = dir.getChildFile ("Session media/Evil2");
  2341. mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
  2342. && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
  2343. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  2344. const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
  2345. return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
  2346. })
  2347. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  2348. if (! mergeOk && e.isEmpty())
  2349. e = "a received package climbed out of its folder";
  2350. }
  2351. if (! packOk && e.isEmpty())
  2352. e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
  2353. + written.missing.joinIntoString (";");
  2354. sessionResult = mergeOk ? juce::String ("OK")
  2355. : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
  2356. dir.deleteRecursively();
  2357. }
  2358. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  2359. juce::String wavpack = "NO_FL";
  2360. {
  2361. const auto roots = lynx::findFlStudioRoots();
  2362. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  2363. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  2364. if (! found.isEmpty())
  2365. {
  2366. lynx::SampleLibrary library;
  2367. const auto sample = library.load (found.getFirst().getFullPathName());
  2368. float peakWv = 0.0f;
  2369. if (sample != nullptr)
  2370. for (std::size_t i = 0; i < sample->frames(); ++i)
  2371. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  2372. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  2373. }
  2374. }
  2375. // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
  2376. const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
  2377. // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
  2378. // generator one plays through the rack
  2379. bool patcherOk = false;
  2380. {
  2381. auto song = lynx::Song::makeDefault();
  2382. song.mixer.resize (4);
  2383. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  2384. lynx::PatchNode reverb, gain;
  2385. reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
  2386. reverb.label = "Room";
  2387. reverb.x = 120.5f;
  2388. reverb.y = 40.0f;
  2389. gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  2390. gain.effect.enabled = false;
  2391. slot.patcher.nodes = { reverb, gain };
  2392. lynx::PatchWire a, b, c, control;
  2393. a.to = 0;
  2394. b.from = 0, b.to = 1, b.gain = 0.5f;
  2395. c.from = 1;
  2396. control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
  2397. slot.patcher.wires = { a, b, c, control };
  2398. slot.patcher.outputTracks = { 3 };
  2399. song.mixer[1].effects = { slot };
  2400. lynx::ChannelDef ch;
  2401. ch.name = "Patched";
  2402. ch.instrument = lynx::InstrumentKind::patcher;
  2403. lynx::PatchNode synth;
  2404. synth.generator = true;
  2405. synth.channel.instrument = lynx::InstrumentKind::synth;
  2406. synth.channel.name = "Synth";
  2407. ch.patcher.nodes = { synth };
  2408. lynx::PatchWire notes, out;
  2409. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  2410. out.from = 0;
  2411. ch.patcher.wires = { notes, out };
  2412. // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
  2413. lynx::PatchNode midiOutNode;
  2414. midiOutNode.generator = true;
  2415. midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
  2416. lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
  2417. ch.patcher.nodes.push_back (midiOutNode);
  2418. lynx::PatchWire portIn, portOut;
  2419. portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
  2420. portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
  2421. portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
  2422. ch.patcher.wires.push_back (portIn);
  2423. ch.patcher.wires.push_back (portOut);
  2424. ch.patcher.fromMidiPorts = { 2, 7 };
  2425. ch.patcher.toMidiPorts = { 9, 11 };
  2426. ch.patcher.fromNotesHidden = true;
  2427. song.channels.push_back (ch);
  2428. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2429. patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
  2430. && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
  2431. && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
  2432. && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
  2433. && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
  2434. && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
  2435. && back->channels.back().patcher.nodes[0].generator
  2436. && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
  2437. && back->channels.back().patcher.wires == ch.patcher.wires;
  2438. }
  2439. // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
  2440. // the instruments play through the rack
  2441. juce::String nativesResult = "OK";
  2442. int nativesMade = 0, nativesSilent = 0;
  2443. {
  2444. auto song = lynx::Song::makeDefault();
  2445. song.channels.clear();
  2446. song.patterns[0].notes.clear();
  2447. song.mixer.resize (3);
  2448. const auto& fl = lynx::flStudioAccess();
  2449. for (const auto& e : lynx::natives::instrumentEngines())
  2450. if (lynx::natives::available (e, fl))
  2451. if (auto c = lynx::natives::makeChannel (e.kind, fl))
  2452. {
  2453. c->mixerTrack = 1;
  2454. song.channels.push_back (*c);
  2455. }
  2456. for (const auto& e : lynx::natives::effectEngines())
  2457. if (auto fx = lynx::natives::makeSlot (e.kind, fl))
  2458. song.mixer[2].effects.push_back (*fx);
  2459. nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
  2460. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2461. auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
  2462. && back->mixer[2].effects.size() == song.mixer[2].effects.size();
  2463. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  2464. {
  2465. const auto& a = song.channels[i];
  2466. const auto& b = back->channels[i];
  2467. same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
  2468. && a.modelParams.size() == b.modelParams.size();
  2469. if (! same)
  2470. nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
  2471. }
  2472. for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
  2473. {
  2474. const auto& a = song.mixer[2].effects[i];
  2475. const auto& b = back->mixer[2].effects[i];
  2476. same = a.kind == b.kind && a.state == b.state;
  2477. for (std::size_t p = 0; same && p < a.params.size(); ++p)
  2478. same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
  2479. if (! same)
  2480. nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
  2481. }
  2482. if (! back)
  2483. nativesResult = "ERROR " + error;
  2484. // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
  2485. // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
  2486. // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
  2487. const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
  2488. {
  2489. juce::WavAudioFormat format;
  2490. juce::AudioBuffer<float> tone (1, 48000);
  2491. for (int i = 0; i < 48000; ++i)
  2492. tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
  2493. toneWav.deleteFile();
  2494. std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
  2495. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  2496. {
  2497. out.release();
  2498. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  2499. writer->writeFromAudioSampleBuffer (tone, 0, 48000);
  2500. }
  2501. }
  2502. juce::StringArray silentNames;
  2503. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  2504. {
  2505. auto one = song;
  2506. one.channels = { song.channels[i] };
  2507. one.channels[0].mixerTrack = 1;
  2508. const auto kind = song.channels[i].instrument;
  2509. if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
  2510. one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
  2511. one.mixer[2].effects.clear();
  2512. // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
  2513. // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
  2514. auto key = 60;
  2515. if (kind == lynx::InstrumentKind::drumaxx)
  2516. {
  2517. const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
  2518. key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
  2519. }
  2520. one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
  2521. lynx::AudioEngine player (false);
  2522. player.setSong (std::move (one));
  2523. player.dispatchPendingMessages();
  2524. if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
  2525. {
  2526. ++nativesSilent;
  2527. silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
  2528. }
  2529. }
  2530. toneWav.deleteFile();
  2531. if (nativesSilent > 0 && nativesResult == "OK")
  2532. nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
  2533. }
  2534. const auto nativesOk = nativesResult == "OK";
  2535. // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
  2536. // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
  2537. // insert 2 (muted: silent); never in an export
  2538. juce::String metronomeResult = "OK";
  2539. int metronomeFlSounds = 0;
  2540. float metronomeMaster = 0.0f;
  2541. {
  2542. const auto& flData = lynx::flStudioAccess().roots.data;
  2543. const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
  2544. for (const auto& s : sounds)
  2545. metronomeFlSounds += s.fromFl ? 1 : 0;
  2546. auto renderClick = [] (int track, bool muteInsert, bool include) {
  2547. auto song = lynx::Song::makeDefault();
  2548. song.channels.clear();
  2549. song.playlist.clear();
  2550. for (auto& p : song.patterns)
  2551. p.notes.clear();
  2552. song.mixer[0].effects.clear(); // (the default Master limiter)
  2553. song.mixer[2].muted = muteInsert;
  2554. lynx::AudioEngine player (false);
  2555. player.setSong (std::move (song));
  2556. player.dispatchPendingMessages();
  2557. auto& t = player.getTransport();
  2558. t.metronome = true;
  2559. t.metronomeSound = 1; // Tick
  2560. t.metronomeTrack = track;
  2561. lynx::AudioEngine::RenderOptions o;
  2562. o.seconds = 0.25;
  2563. o.sampleRate = 44100.0;
  2564. o.pluginWarmUp = false;
  2565. o.includeMetronome = include;
  2566. return player.renderOffline (o);
  2567. };
  2568. metronomeMaster = renderClick (0, false, true);
  2569. const auto insert = renderClick (2, false, true);
  2570. const auto muted = renderClick (2, true, true);
  2571. const auto exported = renderClick (0, false, false);
  2572. // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
  2573. const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
  2574. if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
  2575. metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
  2576. else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
  2577. metronomeResult = "ERROR insert " + juce::String (insert, 4);
  2578. else if (muted > 1.0e-4f)
  2579. metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
  2580. else if (exported > 1.0e-4f)
  2581. metronomeResult = "ERROR in export " + juce::String (exported, 4);
  2582. }
  2583. const auto metronomeOk = metronomeResult == "OK";
  2584. // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
  2585. const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
  2586. // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
  2587. // through it, the invite code's keys)
  2588. const auto liveResult = lynx::livetest::selfTest (&rich);
  2589. // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
  2590. // mask...), at odd values, through a project save and reload: the same floats back
  2591. juce::String effectParamsResult = "OK";
  2592. {
  2593. auto song = lynx::Song::makeDefault();
  2594. song.mixer.resize (1);
  2595. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  2596. {
  2597. const auto kind = (lynx::EffectKind) k;
  2598. if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
  2599. continue;
  2600. auto fx = lynx::makeEffectSlot (kind);
  2601. for (std::size_t i = 0; i < fx.params.size(); ++i)
  2602. {
  2603. auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
  2604. fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
  2605. }
  2606. if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
  2607. fx.params[3] = 0.0f;
  2608. song.mixer.emplace_back();
  2609. song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
  2610. song.mixer.back().effects.push_back (fx);
  2611. }
  2612. // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
  2613. // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
  2614. {
  2615. auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  2616. for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
  2617. lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
  2618. {
  2619. lynx::PatchNode node;
  2620. node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  2621. if (kind == lynx::EffectKind::peakController)
  2622. node.effect.params[7] = 32750.0f / 65336.0f;
  2623. node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
  2624. patch.patcher.nodes.push_back (node);
  2625. }
  2626. song.mixer.emplace_back();
  2627. song.mixer.back().name = "Patcher";
  2628. song.mixer.back().effects.push_back (patch);
  2629. }
  2630. juce::String why;
  2631. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  2632. if (back && back->mixer.size() == song.mixer.size())
  2633. {
  2634. const auto& a = song.mixer.back().effects[0].patcher.nodes;
  2635. const auto& b = back->mixer.back().effects[0].patcher.nodes;
  2636. for (std::size_t n = 0; n < a.size(); ++n)
  2637. if (n >= b.size() || ! (a[n].effect == b[n].effect))
  2638. effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
  2639. }
  2640. if (! back || back->mixer.size() != song.mixer.size())
  2641. effectParamsResult = "ERROR load " + why;
  2642. else
  2643. for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
  2644. if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
  2645. {
  2646. effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
  2647. break;
  2648. }
  2649. }
  2650. // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
  2651. const auto artResult = lynx::skin::artSelfTest();
  2652. // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
  2653. const auto sidechainResult = lynx::pluginSidechainSelfTest();
  2654. // round 177b: automation lanes come back from a project (track, automation, height, folded)
  2655. juce::String lanesResult = "OK";
  2656. {
  2657. auto song = lynx::Song::makeDefault();
  2658. const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
  2659. song.playlistTracks[3].lanes[0].height = 72;
  2660. song.playlistTracks[3].lanesFolded = true;
  2661. // (the same round's clip LFO and modulators ride along)
  2662. auto& lfo = song.automations[(std::size_t) lane].lfo;
  2663. lfo.on = true;
  2664. lfo.level = -40;
  2665. lfo.speed = 30000;
  2666. lfo.flags = 1 | 4;
  2667. lfo.phase = 123456789u;
  2668. lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
  2669. lynx::Modulator mod;
  2670. mod.name = "LFO 1";
  2671. mod.shape = lynx::ModShape::square;
  2672. mod.sync = false;
  2673. mod.hz = 2.5;
  2674. mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  2675. song.modulators.push_back (mod);
  2676. juce::String why;
  2677. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  2678. if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
  2679. || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
  2680. || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
  2681. || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
  2682. lanesResult = "ERROR " + why;
  2683. }
  2684. const auto ok = audioOk && projectOk && richOk && hwOutOk && flp168jOk && blocksOk && polyOk && latencyOk && substituteOk && patcherOk && nativesOk && undoOk && recordOk && recordUndoOk && midiOk && packageOk
  2685. && sessionResult == "OK" && liveResult.startsWith ("OK")
  2686. && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
  2687. && sidechainResult == "OK" && lanesResult == "OK";
  2688. juce::String report;
  2689. report << "connections=" << offline.getNumGraphConnections() << "\n"
  2690. << "peak=" << peak << "\n"
  2691. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  2692. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  2693. << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
  2694. << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
  2695. << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
  2696. << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
  2697. << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
  2698. << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
  2699. << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
  2700. << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
  2701. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  2702. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  2703. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  2704. << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
  2705. << "online_session=" << sessionResult << "\n"
  2706. << "live_session=" << liveResult << "\n"
  2707. << "wavpack=" << wavpack << "\n"
  2708. << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
  2709. << "effect_params_saved=" << effectParamsResult << "\n"
  2710. << "driver_panel=" << driverPanel << "\n"
  2711. << "plugin_art=" << artResult << "\n"
  2712. << "plugin_sidechain=" << sidechainResult << "\n"
  2713. << "lanes_saved=" << lanesResult << "\n"
  2714. << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
  2715. << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n"
  2716. << "result=" << (ok ? "OK" : "FAILED") << "\n";
  2717. if (reportPath.isNotEmpty())
  2718. juce::File (reportPath).replaceWithText (report);
  2719. setApplicationReturnValue (ok ? 0 : 1);
  2720. quit();
  2721. }
  2722. // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
  2723. // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
  2724. // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
  2725. bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
  2726. {
  2727. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2728. lynx::setNativeEditorDemo (true);
  2729. juce::String report;
  2730. auto allFinite = true;
  2731. {
  2732. lynx::AudioEngine offline (false);
  2733. juce::Random random (111);
  2734. const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
  2735. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  2736. {
  2737. const auto kind = (lynx::EffectKind) k;
  2738. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
  2739. continue;
  2740. const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
  2741. const auto& info = lynx::effectInfo (kind);
  2742. // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
  2743. auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  2744. int dragged = 0; // parameter changes made by the mouse drags
  2745. for (int round = 0; round < rounds; ++round)
  2746. {
  2747. if (round > 0)
  2748. for (std::size_t p = 0; p < info.params.size(); ++p)
  2749. fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
  2750. auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
  2751. song.mixer.resize (2);
  2752. song.mixer[0].name = "Master";
  2753. song.mixer[1].name = "Insert 1";
  2754. song.mixer[1].effects.assign (1, fx);
  2755. for (auto& channel : song.channels)
  2756. channel.mixerTrack = 1;
  2757. offline.setSong (std::move (song));
  2758. offline.dispatchPendingMessages();
  2759. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  2760. for (int page = 0; page < pages; ++page)
  2761. {
  2762. auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  2763. : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  2764. if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
  2765. continue;
  2766. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  2767. const auto paint = [&] {
  2768. juce::Graphics g (image);
  2769. editor->paintEntireComponent (g, false);
  2770. };
  2771. paint();
  2772. // drags from a grid of points, as a user moving every control (plain left button)
  2773. if (round >= 3 && drags)
  2774. {
  2775. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  2776. const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
  2777. for (int y = step / 2; y < editor->getHeight(); y += step)
  2778. for (int x = step / 2; x < editor->getWidth(); x += step)
  2779. {
  2780. auto* target = editor->getComponentAt (x, y);
  2781. if (target == nullptr)
  2782. continue;
  2783. const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
  2784. const auto now = juce::Time::getCurrentTime();
  2785. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
  2786. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
  2787. };
  2788. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  2789. const juce::Component::SafePointer<juce::Component> alive (target);
  2790. target->mouseDown (event (at, down));
  2791. const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
  2792. if (alive != nullptr)
  2793. target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
  2794. if (alive != nullptr)
  2795. target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
  2796. if (alive != nullptr)
  2797. target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
  2798. juce::PopupMenu::dismissAllActiveMenus();
  2799. offline.dispatchPendingMessages();
  2800. }
  2801. paint();
  2802. }
  2803. }
  2804. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  2805. offline.renderOffline (0.05, rate);
  2806. if (round == 0 || round >= 3) // keep what the drags set for the next round
  2807. if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
  2808. {
  2809. const auto& now = offline.getSong().mixer[1].effects[0];
  2810. for (std::size_t p = 0; p < fx.params.size(); ++p)
  2811. dragged += now.params[p] != fx.params[p] ? 1 : 0;
  2812. dragged += now.state != fx.state ? 1 : 0;
  2813. fx = now;
  2814. }
  2815. }
  2816. const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
  2817. allFinite = allFinite && broken == 0;
  2818. report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
  2819. << " (" << dragged << " changes by mouse)\n";
  2820. if (reportPath.isNotEmpty())
  2821. juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
  2822. }
  2823. }
  2824. lynx::setNativeEditorDemo (false);
  2825. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  2826. report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
  2827. if (reportPath.isNotEmpty())
  2828. juce::File (reportPath).replaceWithText (report);
  2829. return allFinite;
  2830. }
  2831. // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
  2832. // native windows are real); one step per timer tick.
  2833. void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
  2834. {
  2835. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2836. struct OpenTest final : juce::Timer
  2837. {
  2838. juce::String reportPath, report;
  2839. bool visible = false, ok = true;
  2840. std::function<void (bool)> done;
  2841. std::unique_ptr<lynx::AudioEngine> engine;
  2842. std::vector<std::pair<juce::String, std::function<void()>>> steps;
  2843. std::size_t next = 0;
  2844. std::atomic<std::int64_t> lastStep { 0 };
  2845. std::atomic<bool> finished { false };
  2846. std::thread watchdog;
  2847. juce::String current;
  2848. std::mutex currentLock;
  2849. int opened = 0, painted = 0;
  2850. // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
  2851. const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
  2852. static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
  2853. void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
  2854. ~OpenTest() override
  2855. {
  2856. finished = true;
  2857. if (watchdog.joinable())
  2858. watchdog.join();
  2859. }
  2860. void start()
  2861. {
  2862. lastStep = now();
  2863. // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
  2864. const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
  2865. folder.deleteRecursively();
  2866. folder.createDirectory();
  2867. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
  2868. watchdog = std::thread ([this] {
  2869. while (! finished)
  2870. {
  2871. std::this_thread::sleep_for (std::chrono::milliseconds (200));
  2872. if (now() - lastStep.load() > timeoutMs)
  2873. {
  2874. juce::String at;
  2875. {
  2876. const std::lock_guard<std::mutex> l (currentLock);
  2877. at = current;
  2878. }
  2879. juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
  2880. lynx::crashguard::exitNow (3);
  2881. }
  2882. }
  2883. });
  2884. startTimer (30);
  2885. }
  2886. // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
  2887. void touchWindows (bool resize, bool large)
  2888. {
  2889. auto& desktop = juce::Desktop::getInstance();
  2890. for (int i = desktop.getNumComponents(); --i >= 0;)
  2891. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
  2892. {
  2893. if (! visible && c->getScreenX() > -3000)
  2894. c->setTopLeftPosition (-6000, -6000);
  2895. if (resize)
  2896. if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
  2897. {
  2898. const auto b = w->getBounds();
  2899. w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
  2900. }
  2901. if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
  2902. {
  2903. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  2904. juce::Graphics g (image);
  2905. c->paintEntireComponent (g, false);
  2906. ++painted;
  2907. // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
  2908. if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
  2909. {
  2910. juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
  2911. if (out.openedOk())
  2912. {
  2913. out.setPosition (0), out.truncate();
  2914. juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  2915. }
  2916. }
  2917. }
  2918. }
  2919. }
  2920. void timerCallback() override
  2921. {
  2922. if (next >= steps.size())
  2923. {
  2924. stopTimer();
  2925. lynx::NativeEffectWindows::closeAll();
  2926. lynx::closeChannelSettings();
  2927. // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
  2928. {
  2929. const auto before = lynx::crashguard::lastHangFile();
  2930. for (const auto until = now() + 7000; now() < until;)
  2931. lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
  2932. for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
  2933. std::this_thread::sleep_for (std::chrono::milliseconds (20));
  2934. lynx::crashguard::stopHangWatch();
  2935. const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
  2936. const auto text = hang.loadFileAsString();
  2937. const auto frames = juce::StringArray::fromLines (text).size() - 2;
  2938. #if JUCE_WINDOWS
  2939. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
  2940. #else
  2941. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
  2942. #endif
  2943. report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
  2944. << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
  2945. ok = ok && hangOk;
  2946. }
  2947. report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
  2948. write();
  2949. finished = true;
  2950. if (done)
  2951. done (ok);
  2952. return;
  2953. }
  2954. auto& [label, fn] = steps[next++];
  2955. {
  2956. const std::lock_guard<std::mutex> l (currentLock);
  2957. current = label;
  2958. }
  2959. fn();
  2960. lastStep = now();
  2961. lynx::crashguard::heartbeat();
  2962. }
  2963. };
  2964. auto* test = new OpenTest();
  2965. test->reportPath = reportPath;
  2966. test->visible = visible;
  2967. test->engine = std::make_unique<lynx::AudioEngine> (false);
  2968. test->done = [test, done] (bool ok) {
  2969. juce::MessageManager::callAsync ([test, done, ok] {
  2970. delete test;
  2971. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  2972. done (ok);
  2973. });
  2974. };
  2975. auto& engine = *test->engine;
  2976. lynx::setNativeEditorDemo (true); // live displays animate without an audio device
  2977. const auto songWith = [] (const lynx::EffectSlot& fx) {
  2978. auto song = lynx::Song::makeDefault();
  2979. song.mixer.resize (2);
  2980. song.mixer[0].name = "Master";
  2981. song.mixer[1].name = "Insert 1";
  2982. song.mixer[1].effects.assign (1, fx);
  2983. for (auto& channel : song.channels)
  2984. channel.mixerTrack = 1;
  2985. return song;
  2986. };
  2987. // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
  2988. // parameters a newer LYNX added after them take their defaults)
  2989. const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
  2990. auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
  2991. if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
  2992. if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
  2993. if (auto* params = (*effects)[0]["params"].getArray())
  2994. params->removeRange ((int) count, params->size());
  2995. juce::String error;
  2996. return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
  2997. };
  2998. auto& steps = test->steps;
  2999. juce::Random random (157);
  3000. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  3001. {
  3002. const auto kind = (lynx::EffectKind) k;
  3003. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  3004. continue;
  3005. const auto& info = lynx::effectInfo (kind);
  3006. const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  3007. const auto n = info.params.size();
  3008. std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
  3009. variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
  3010. for (const auto value : { 0.0f, 1.0f })
  3011. variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
  3012. auto fx = base;
  3013. for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
  3014. return std::optional<lynx::Song> (songWith (fx));
  3015. } });
  3016. const auto seed = random.nextInt64();
  3017. variants.push_back ({ "random", [=] {
  3018. juce::Random r (seed);
  3019. auto fx = base;
  3020. for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
  3021. return std::optional<lynx::Song> (songWith (fx));
  3022. } });
  3023. std::vector<std::size_t> cuts { n / 2 };
  3024. for (const auto c : { (std::size_t) 90, (std::size_t) 114, (std::size_t) 128, (std::size_t) 160 }) // (Facet's 90 → 114 params; the 128 → 160 → 192 slot)
  3025. if (c < n) cuts.push_back (c);
  3026. for (const auto c : cuts)
  3027. variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
  3028. for (const auto& [variant, makeSong] : variants)
  3029. {
  3030. const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
  3031. steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
  3032. auto song = makeSong();
  3033. if (! song)
  3034. {
  3035. test->report << "FAIL " << label << ": project reader refused the state\n";
  3036. test->ok = false;
  3037. return;
  3038. }
  3039. engine.setSong (std::move (*song));
  3040. engine.dispatchPendingMessages();
  3041. lynx::NativeEffectWindows::open (engine, 1, 0);
  3042. ++test->opened;
  3043. test->touchWindows (false, false);
  3044. } });
  3045. steps.push_back ({ label + ": run", [test, &engine] {
  3046. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  3047. engine.renderOffline (0.03, rate);
  3048. test->touchWindows (false, false);
  3049. } });
  3050. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  3051. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  3052. steps.push_back ({ label + ": close", [test, label] {
  3053. lynx::NativeEffectWindows::closeAll();
  3054. test->report << label << ": OK\n";
  3055. test->write ("(running)\n");
  3056. } });
  3057. }
  3058. }
  3059. // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
  3060. for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
  3061. {
  3062. const auto kind = (lynx::InstrumentKind) k;
  3063. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  3064. continue;
  3065. for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
  3066. {
  3067. if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
  3068. continue;
  3069. const auto label = "instrument " + juce::String (k) + " / " + variant;
  3070. steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
  3071. auto song = lynx::Song::makeDefault();
  3072. auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  3073. lynx::ChannelDef def;
  3074. def.instrument = kind;
  3075. def.name = "Test";
  3076. song.channels.push_back (channel ? *channel : def);
  3077. if (kind == lynx::InstrumentKind::soundfont && variant != "default")
  3078. {
  3079. // a real font when FL's is there; NaN / huge / truncated settings
  3080. const auto& roots = lynx::flStudioAccess().roots;
  3081. if (! roots.data.empty())
  3082. song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  3083. .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
  3084. .getFullPathName().toStdString();
  3085. if (variant == "odd settings")
  3086. song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
  3087. }
  3088. if (old)
  3089. {
  3090. juce::String error;
  3091. if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
  3092. song = std::move (*again);
  3093. }
  3094. const auto index = (int) song.channels.size() - 1;
  3095. engine.setSong (std::move (song));
  3096. engine.dispatchPendingMessages();
  3097. lynx::openChannelSettings (engine, index);
  3098. ++test->opened;
  3099. test->touchWindows (false, false);
  3100. } });
  3101. steps.push_back ({ label + ": run", [test, &engine] {
  3102. engine.renderOffline (0.03, 48000.0);
  3103. test->touchWindows (false, false);
  3104. } });
  3105. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  3106. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  3107. steps.push_back ({ label + ": close", [test, label] {
  3108. lynx::closeChannelSettings();
  3109. test->report << label << ": OK\n";
  3110. test->write ("(running)\n");
  3111. } });
  3112. }
  3113. }
  3114. test->start();
  3115. }
  3116. void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
  3117. {
  3118. struct Test final : juce::Timer
  3119. {
  3120. juce::String reportPath, report;
  3121. std::unique_ptr<lynx::AudioEngine> engine;
  3122. bool instrument = false;
  3123. int phase = 0, ticks = 0, seconds = 15;
  3124. juce::AudioPluginInstance* instance = nullptr;
  3125. juce::AudioProcessorParameter* checked = nullptr;
  3126. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  3127. std::function<void (bool)> done;
  3128. void step (const juce::String& line)
  3129. {
  3130. report << line << "\n";
  3131. juce::File (reportPath).replaceWithText (report);
  3132. }
  3133. juce::AudioPluginInstance* find()
  3134. {
  3135. if (instrument)
  3136. {
  3137. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (0).get()))
  3138. return &p->getInstance();
  3139. }
  3140. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  3141. return &p->getInstance();
  3142. return nullptr;
  3143. }
  3144. void timerCallback() override
  3145. {
  3146. ++ticks;
  3147. if (phase == 0) // waiting for the engine to host the plugin
  3148. {
  3149. instance = find();
  3150. if (instance == nullptr)
  3151. {
  3152. if (ticks > 200)
  3153. {
  3154. step ("result=FAILED (not hosted)");
  3155. stopTimer();
  3156. done (false);
  3157. }
  3158. return;
  3159. }
  3160. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  3161. step ("programs=" + juce::String (instance->getNumPrograms()));
  3162. for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
  3163. step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
  3164. step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
  3165. // preset round trip: save, change the first parameter, load, compare
  3166. juce::AudioProcessorParameter* param = nullptr;
  3167. for (auto* candidate : instance->getParameters())
  3168. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  3169. {
  3170. param = candidate;
  3171. break;
  3172. }
  3173. if (param != nullptr)
  3174. {
  3175. step ("param=" + param->getName (64));
  3176. checked = param;
  3177. const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
  3178. juce::String error;
  3179. const auto before = param->getValue();
  3180. const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
  3181. param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
  3182. const auto changed = param->getValue();
  3183. const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
  3184. step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
  3185. + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
  3186. + (error.isNotEmpty() ? " error=" + error : juce::String()));
  3187. for (const auto* ext : { "fxp", "fxb", "vstpreset" })
  3188. {
  3189. juce::String e2;
  3190. const auto f2 = file.withFileExtension (ext);
  3191. const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
  3192. step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
  3193. f2.deleteFile();
  3194. }
  3195. step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
  3196. }
  3197. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (0))
  3198. : std::shared_ptr<void> (engine->getEffect (1, 0));
  3199. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  3200. { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  3201. if (instrument)
  3202. return song.channels.empty() ? nullptr : &song.channels[0].plugin;
  3203. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  3204. }, instrument });
  3205. owner.reset();
  3206. step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  3207. phase = 1;
  3208. ticks = 0;
  3209. return;
  3210. }
  3211. if (phase == 1 && ticks == 20 && checked != nullptr)
  3212. step ("param_after_1s=" + juce::String (checked->getValue(), 4));
  3213. if (phase == 1 && ticks >= seconds * 20) // remove the plugin from the song
  3214. {
  3215. engine->editSong ([this] (lynx::Song& song) {
  3216. if (instrument)
  3217. song.channels.clear();
  3218. else
  3219. song.mixer[1].effects.clear();
  3220. });
  3221. step ("removed");
  3222. phase = 2;
  3223. ticks = 0;
  3224. return;
  3225. }
  3226. if (phase == 2 && ticks >= 40)
  3227. {
  3228. const auto open = lynx::PluginWindows::isOpen (*instance);
  3229. step ("window_open_after_remove=" + juce::String ((int) open));
  3230. step (open ? "result=FAILED" : "result=OK");
  3231. stopTimer();
  3232. lynx::PluginWindows::closeAll();
  3233. done (! open);
  3234. }
  3235. }
  3236. };
  3237. auto* test = new Test();
  3238. test->reportPath = reportPath;
  3239. test->seconds = seconds;
  3240. test->done = [this, test] (bool ok) {
  3241. setApplicationReturnValue (ok ? 0 : 1);
  3242. juce::MessageManager::callAsync ([this, test] {
  3243. lynx::setMainWindowForOwnership (nullptr);
  3244. test->mainWindow = nullptr;
  3245. test->engine = nullptr;
  3246. delete test;
  3247. quit();
  3248. });
  3249. };
  3250. test->engine = std::make_unique<lynx::AudioEngine> (false);
  3251. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  3252. test->mainWindow->setBounds (20, 20, 300, 200);
  3253. test->mainWindow->setVisible (true);
  3254. lynx::setMainWindowForOwnership (test->mainWindow.get());
  3255. auto& host = test->engine->getPluginHost();
  3256. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  3257. std::optional<juce::PluginDescription> chosen;
  3258. for (const auto& type : host.getKnownPlugins().getTypes())
  3259. if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  3260. && (only.isEmpty() || type.name == only))
  3261. {
  3262. chosen = type;
  3263. break;
  3264. }
  3265. if (! chosen)
  3266. {
  3267. test->step ("result=FAILED (no plugin)");
  3268. test->done (false);
  3269. return;
  3270. }
  3271. test->instrument = chosen->isInstrument;
  3272. lynx::PluginRef ref;
  3273. ref.id = chosen->createIdentifierString().toStdString();
  3274. ref.name = chosen->name.toStdString();
  3275. test->engine->editSong ([&] (lynx::Song& song) {
  3276. if (test->instrument)
  3277. {
  3278. lynx::ChannelDef c;
  3279. c.name = ref.name;
  3280. c.instrument = lynx::InstrumentKind::plugin;
  3281. c.plugin = ref;
  3282. song.channels.push_back (c);
  3283. }
  3284. else
  3285. {
  3286. while (song.mixer.size() < 2)
  3287. song.mixer.emplace_back();
  3288. lynx::EffectSlot slot;
  3289. slot.kind = lynx::EffectKind::plugin;
  3290. slot.plugin = ref;
  3291. song.mixer[1].effects.push_back (slot);
  3292. }
  3293. });
  3294. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  3295. test->startTimerHz (20);
  3296. }
  3297. void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
  3298. {
  3299. struct CrashTest final : juce::Timer
  3300. {
  3301. juce::String reportPath, report;
  3302. std::unique_ptr<lynx::PluginHost> host;
  3303. juce::AudioPluginInstance* plugin = nullptr;
  3304. std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
  3305. std::function<void (bool)> done;
  3306. int ticks = 0, crashesBefore = 0;
  3307. void step (const juce::String& line)
  3308. {
  3309. report << line << "\n";
  3310. juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
  3311. }
  3312. void timerCallback() override
  3313. {
  3314. ++ticks;
  3315. const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
  3316. const auto open = lynx::PluginWindows::isOpen (*plugin);
  3317. if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
  3318. {
  3319. stopTimer();
  3320. step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
  3321. bool traced = false;
  3322. if (crashes > 0)
  3323. {
  3324. const auto last = lynx::PluginWindows::editorCrashes().back();
  3325. traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
  3326. step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
  3327. + juce::String ((int) traced));
  3328. last.traceFile.deleteFile();
  3329. }
  3330. // still alive: one more message through the loop after the fault
  3331. juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
  3332. step ("message_loop_after_fault=1");
  3333. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  3334. done (ok);
  3335. });
  3336. }
  3337. }
  3338. };
  3339. auto* test = new CrashTest();
  3340. test->reportPath = reportPath;
  3341. test->done = [this, test] (bool ok)
  3342. {
  3343. setApplicationReturnValue (ok ? 0 : 1);
  3344. juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
  3345. };
  3346. #if ! JUCE_WINDOWS
  3347. test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
  3348. test->done (true);
  3349. return;
  3350. #else
  3351. _putenv_s ("LYNX_TEST_CRASH", "editor");
  3352. test->host = std::make_unique<lynx::PluginHost> (false);
  3353. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  3354. std::shared_ptr<juce::AudioPluginInstance> instance;
  3355. for (const auto& type : test->host->getKnownPlugins().getTypes())
  3356. {
  3357. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
  3358. continue;
  3359. juce::String error;
  3360. instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
  3361. test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
  3362. break;
  3363. }
  3364. if (instance == nullptr || ! instance->hasEditor())
  3365. {
  3366. test->step ("result=FAILED (no plugin with an editor)");
  3367. test->done (false);
  3368. return;
  3369. }
  3370. lynx::preparePlugin (*instance, 48000.0, 512);
  3371. test->plugin = instance.get();
  3372. test->keep = instance;
  3373. test->crashesBefore = lynx::PluginWindows::editorCrashCount();
  3374. lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
  3375. test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  3376. test->startTimer (100);
  3377. #endif
  3378. }
  3379. void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
  3380. {
  3381. struct EditorTest final : juce::Timer
  3382. {
  3383. juce::String reportPath, report;
  3384. std::unique_ptr<lynx::PluginHost> host;
  3385. std::unique_ptr<juce::AudioPluginInstance> plugin;
  3386. std::unique_ptr<juce::DocumentWindow> window;
  3387. std::function<void (bool)> done;
  3388. void step (const juce::String& line)
  3389. {
  3390. report << line << "\n";
  3391. juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
  3392. }
  3393. void timerCallback() override
  3394. {
  3395. stopTimer();
  3396. window = nullptr;
  3397. step ("step=closed");
  3398. plugin = nullptr;
  3399. step ("result=OK");
  3400. done (true);
  3401. }
  3402. };
  3403. auto* test = new EditorTest();
  3404. test->reportPath = reportPath;
  3405. test->done = [this, test] (bool ok)
  3406. {
  3407. setApplicationReturnValue (ok ? 0 : 1);
  3408. juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
  3409. };
  3410. test->host = std::make_unique<lynx::PluginHost> (false);
  3411. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  3412. test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
  3413. for (const auto& type : test->host->getKnownPlugins().getTypes())
  3414. {
  3415. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  3416. || (only.isNotEmpty() && type.name != only))
  3417. continue;
  3418. juce::String error;
  3419. test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
  3420. test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
  3421. break;
  3422. }
  3423. if (test->plugin == nullptr)
  3424. {
  3425. test->step ("result=FAILED");
  3426. test->done (false);
  3427. return;
  3428. }
  3429. lynx::preparePlugin (*test->plugin, 48000.0, 512);
  3430. test->step ("step=create_editor");
  3431. test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
  3432. test->window->setUsingNativeTitleBar (true);
  3433. if (auto* editor = test->plugin->createEditorIfNeeded())
  3434. test->window->setContentOwned (editor, true);
  3435. else
  3436. test->step ("no_editor");
  3437. test->step ("step=show");
  3438. test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
  3439. test->window->setVisible (true);
  3440. test->step ("step=shown");
  3441. test->startTimer (4000);
  3442. }
  3443. void runFitTest (const juce::String& reportPath, int percent)
  3444. {
  3445. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3446. struct FitTest final : juce::Timer
  3447. {
  3448. juce::String path, report;
  3449. bool ok = true;
  3450. int step = 0, percent = 150;
  3451. std::unique_ptr<juce::DocumentWindow> tall, big;
  3452. std::function<void()> done;
  3453. // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
  3454. void check (const juce::String& what, juce::Component& w, bool whole)
  3455. {
  3456. juce::BorderSize<int> frame;
  3457. if (auto* peer = w.getPeer())
  3458. if (const auto f = peer->getFrameSizeIfPresent())
  3459. frame = *f;
  3460. auto outer = frame.addedTo (w.getBounds());
  3461. const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
  3462. const auto area = display != nullptr ? display->userArea : outer;
  3463. #if JUCE_LINUX
  3464. // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
  3465. // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
  3466. const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
  3467. outer = outer.reduced (shadow);
  3468. const auto slack = shadow > 0 ? 4 : 0;
  3469. #else
  3470. const auto slack = 0;
  3471. #endif
  3472. const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
  3473. && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
  3474. report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
  3475. << frame.getLeft() << ") screen=" << area.toString() << "\n";
  3476. ok = ok && passed;
  3477. }
  3478. void start()
  3479. {
  3480. report << "scale=" << percent << "%\n";
  3481. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  3482. // a tool window taller than the screen, centred (its title bar would be above the screen)
  3483. tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
  3484. tall->setUsingNativeTitleBar (true);
  3485. auto* content = new juce::Component();
  3486. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  3487. content->setSize (500, area.getHeight() + 200);
  3488. tall->setContentOwned (content, true);
  3489. tall->setCentrePosition (area.getCentre());
  3490. tall->setVisible (true);
  3491. lynx::keepAboveMainWindow (*tall);
  3492. // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
  3493. startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
  3494. }
  3495. void timerCallback() override
  3496. {
  3497. ++step;
  3498. if (step == 1)
  3499. {
  3500. check ("tall tool window: title bar and close button on the screen", *tall, false);
  3501. tall.reset();
  3502. // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
  3503. auto content = std::make_unique<juce::Component>();
  3504. const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  3505. content->setSize (520, screen.getHeight() + 300);
  3506. lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
  3507. return;
  3508. }
  3509. if (step == 2)
  3510. {
  3511. if (auto* w = lynx::findToolWindow ("fittest-fixed"))
  3512. {
  3513. check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
  3514. const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
  3515. && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
  3516. report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
  3517. ok = ok && scrolls;
  3518. }
  3519. else
  3520. {
  3521. report << "FAIL fixed-size tool window not found\n";
  3522. ok = false;
  3523. }
  3524. lynx::closeAllToolWindows();
  3525. // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
  3526. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  3527. big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
  3528. big->setUsingNativeTitleBar (true);
  3529. big->setResizable (true, false);
  3530. big->setResizeLimits (400, 300, 10000, 10000);
  3531. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  3532. big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
  3533. big->setVisible (true);
  3534. return;
  3535. }
  3536. if (step == 3)
  3537. {
  3538. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  3539. juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
  3540. return;
  3541. }
  3542. if (step == 4)
  3543. {
  3544. check ("resizable window after the zoom change: fits the screen", *big, true);
  3545. big.reset();
  3546. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  3547. juce::File (path).replaceWithText (report);
  3548. stopTimer();
  3549. if (done)
  3550. done();
  3551. }
  3552. }
  3553. };
  3554. static std::unique_ptr<FitTest> test;
  3555. test = std::make_unique<FitTest>();
  3556. test->path = reportPath;
  3557. test->percent = juce::jlimit (50, 300, percent);
  3558. test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
  3559. test->start();
  3560. }
  3561. void runWindowTest (const juce::String& reportPath)
  3562. {
  3563. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3564. struct WindowTest final : juce::Timer
  3565. {
  3566. juce::String reportPath, report;
  3567. bool ok = true;
  3568. int stepIndex = 0;
  3569. std::unique_ptr<lynx::AudioEngine> engine;
  3570. lynx::MainComponent* ui = nullptr;
  3571. std::unique_ptr<juce::DocumentWindow> main, pluginLike;
  3572. juce::TextEditor* pluginField = nullptr;
  3573. std::unique_ptr<juce::AlertWindow> nameDialog;
  3574. std::function<void()> done;
  3575. void line (const juce::String& text)
  3576. {
  3577. report << text << "\n";
  3578. juce::File (reportPath).replaceWithText (report);
  3579. }
  3580. void check (const juce::String& what, bool passed)
  3581. {
  3582. line ((passed ? "ok " : "FAIL ") + what);
  3583. ok = ok && passed;
  3584. }
  3585. bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
  3586. bool focusIn (juce::Component* w)
  3587. {
  3588. auto* f = juce::Component::getCurrentlyFocusedComponent();
  3589. return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
  3590. }
  3591. void timerCallback() override
  3592. {
  3593. switch (stepIndex++)
  3594. {
  3595. case 0:
  3596. line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
  3597. ui->openQuickAddForTest();
  3598. break;
  3599. case 1:
  3600. {
  3601. auto* w = lynx::findToolWindow ("quickadd");
  3602. check ("quick-add palette open", w != nullptr);
  3603. check ("quick-add palette active", w != nullptr && w->isActiveWindow());
  3604. check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  3605. check ("quick-add palette above the main window", isAbove (w));
  3606. auto* f = juce::Component::getCurrentlyFocusedComponent();
  3607. check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
  3608. lynx::closeAllToolWindows();
  3609. lynx::openAudioEditor (*engine);
  3610. break;
  3611. }
  3612. case 2:
  3613. {
  3614. auto* w = lynx::findToolWindow ("audioeditor");
  3615. check ("audio editor open", w != nullptr);
  3616. check ("audio editor active", w != nullptr && w->isActiveWindow());
  3617. check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  3618. check ("audio editor above the main window", isAbove (w));
  3619. lynx::forceForegroundForTest (*main); // the user clicks the main window
  3620. break;
  3621. }
  3622. case 3:
  3623. {
  3624. auto* w = lynx::findToolWindow ("audioeditor");
  3625. check ("audio editor stays above the main window after clicking it", isAbove (w));
  3626. lynx::closeAllToolWindows();
  3627. // a plugin editor's window: its own controls keep the keyboard focus
  3628. pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
  3629. pluginLike->setUsingNativeTitleBar (true);
  3630. auto* field = new juce::TextEditor();
  3631. field->setSize (300, 120);
  3632. pluginLike->setContentOwned (field, true);
  3633. pluginLike->centreWithSize (300, 120);
  3634. pluginLike->setVisible (true);
  3635. lynx::keepAboveMainWindow (*pluginLike);
  3636. pluginLike->toFront (true);
  3637. field->grabKeyboardFocus();
  3638. pluginField = field;
  3639. break;
  3640. }
  3641. case 4:
  3642. check ("plugin window active", pluginLike->isActiveWindow());
  3643. check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
  3644. check ("plugin window above the main window", isAbove (pluginLike.get()));
  3645. pluginLike = nullptr;
  3646. lynx::forceForegroundForTest (*main);
  3647. juce::Component::unfocusAllComponents();
  3648. break;
  3649. case 5:
  3650. check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
  3651. // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
  3652. nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
  3653. nameDialog->enterModalState (true, nullptr, false);
  3654. lynx::keepAboveMainWindow (*nameDialog);
  3655. break;
  3656. case 6:
  3657. {
  3658. auto* f = juce::Component::getCurrentlyFocusedComponent();
  3659. auto* field = dynamic_cast<juce::TextEditor*> (f);
  3660. check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
  3661. if (field != nullptr)
  3662. field->keyPressed (juce::KeyPress ('x', {}, 'x'));
  3663. check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
  3664. nameDialog->exitModalState (0);
  3665. nameDialog = nullptr;
  3666. line (ok ? "result=OK" : "result=FAILED");
  3667. stopTimer();
  3668. done();
  3669. break;
  3670. }
  3671. default:
  3672. break;
  3673. }
  3674. }
  3675. };
  3676. auto* test = new WindowTest();
  3677. test->reportPath = reportPath;
  3678. test->engine = std::make_unique<lynx::AudioEngine> (false);
  3679. test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
  3680. test->main->setUsingNativeTitleBar (true);
  3681. test->ui = new lynx::MainComponent (*test->engine, false);
  3682. test->main->setContentOwned (test->ui, true);
  3683. test->main->setResizable (true, true);
  3684. test->main->centreWithSize (1280, 760);
  3685. test->main->setVisible (true);
  3686. lynx::setMainWindowForOwnership (test->main.get());
  3687. lynx::forceForegroundForTest (*test->main);
  3688. test->main->toFront (true);
  3689. test->done = [this, test] {
  3690. setApplicationReturnValue (test->ok ? 0 : 1);
  3691. juce::MessageManager::callAsync ([this, test] {
  3692. lynx::closeAllToolWindows();
  3693. lynx::setMainWindowForOwnership (nullptr);
  3694. test->main = nullptr;
  3695. delete test;
  3696. quit();
  3697. });
  3698. };
  3699. test->startTimer (1500);
  3700. }
  3701. // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
  3702. // instrument (and runs audio through it if it is an effect) and measures the audio.
  3703. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
  3704. {
  3705. juce::String report;
  3706. bool ok = false;
  3707. {
  3708. lynx::AudioEngine offline (false);
  3709. auto& host = offline.getPluginHost();
  3710. const auto added = host.addPluginFile (juce::File (pluginPath));
  3711. report << "plugins_in_file=" << added << "\n";
  3712. juce::PluginDescription instrument, effect;
  3713. bool hasInstrument = false, hasEffect = false;
  3714. for (const auto& type : host.getKnownPlugins().getTypes())
  3715. {
  3716. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  3717. || (only.isNotEmpty() && type.name != only))
  3718. continue;
  3719. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  3720. << ") in " << type.fileOrIdentifier << "\n";
  3721. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  3722. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  3723. }
  3724. auto song = lynx::Song::makeDefault();
  3725. if (hasInstrument)
  3726. {
  3727. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  3728. c.instrument = lynx::InstrumentKind::plugin;
  3729. c.plugin.id = instrument.createIdentifierString().toStdString();
  3730. c.plugin.name = instrument.name.toStdString();
  3731. c.volume = 1.0f;
  3732. for (int i = 0; i < 4; ++i) // one chord per beat
  3733. for (int key : { 60, 64, 67 })
  3734. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  3735. song.patterns[0].sortNotes();
  3736. }
  3737. if (hasEffect)
  3738. {
  3739. lynx::EffectSlot slot;
  3740. slot.kind = lynx::EffectKind::plugin;
  3741. slot.plugin.id = effect.createIdentifierString().toStdString();
  3742. slot.plugin.name = effect.name.toStdString();
  3743. song.mixer[0].effects.push_back (slot);
  3744. }
  3745. const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
  3746. offline.setSong (song);
  3747. // after a render: the rack (and its plugins) is built when the engine is prepared
  3748. const auto peak = offline.renderOffline (3.0, 48000.0);
  3749. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  3750. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
  3751. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  3752. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  3753. if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
  3754. report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
  3755. report << "peak=" << peak << "\n";
  3756. // plugins that crashed inside a call, were caught and switched off (round 111)
  3757. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  3758. for (const auto& c : lynx::pluginCrashes())
  3759. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  3760. offline.capturePluginStates();
  3761. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  3762. report << "state_bytes_base64=" << (int) stateSize << "\n";
  3763. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  3764. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  3765. }
  3766. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  3767. juce::File (reportPath).replaceWithText (report);
  3768. setApplicationReturnValue (ok ? 0 : 1);
  3769. quit();
  3770. }
  3771. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
  3772. // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
  3773. // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
  3774. // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
  3775. // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
  3776. // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
  3777. // the latency the plugin reports after its last restart.
  3778. void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
  3779. {
  3780. struct Run
  3781. {
  3782. std::unique_ptr<lynx::AudioEngine> engine;
  3783. juce::String report;
  3784. int slot = -1;
  3785. std::thread render;
  3786. std::atomic<bool> done { false };
  3787. double renderSeconds = 0.0;
  3788. };
  3789. auto run = std::make_shared<Run>();
  3790. const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  3791. counters.deleteFile();
  3792. #if JUCE_WINDOWS
  3793. _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
  3794. #else
  3795. setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
  3796. #endif
  3797. const auto fail = [this, reportPath] (juce::String report) {
  3798. report << "result=FAILED\n";
  3799. juce::File (reportPath).replaceWithText (report);
  3800. setApplicationReturnValue (1);
  3801. quit();
  3802. };
  3803. run->engine = std::make_unique<lynx::AudioEngine> (false);
  3804. auto& host = run->engine->getPluginHost();
  3805. run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  3806. std::optional<juce::PluginDescription> clap;
  3807. for (const auto& type : host.getKnownPlugins().getTypes())
  3808. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  3809. clap = type;
  3810. if (! clap)
  3811. {
  3812. fail (run->report + "no CLAP plugin in the file\n");
  3813. return;
  3814. }
  3815. auto song = lynx::Song::makeDefault();
  3816. lynx::EffectSlot slot;
  3817. slot.kind = lynx::EffectKind::plugin;
  3818. slot.plugin.id = clap->createIdentifierString().toStdString();
  3819. slot.plugin.name = clap->name.toStdString();
  3820. slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
  3821. song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
  3822. run->slot = (int) song.mixer[0].effects.size() - 1;
  3823. run->engine->setSong (song);
  3824. run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
  3825. if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
  3826. {
  3827. fail (run->report + "effect_loaded=no\n");
  3828. return;
  3829. }
  3830. auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
  3831. run->render = std::thread ([run, effect] {
  3832. const auto start = juce::Time::getMillisecondCounterHiRes();
  3833. run->engine->renderOffline (30.0, 48000.0);
  3834. run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
  3835. // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
  3836. // plugin aborts unless activate / deactivate reach the main thread
  3837. auto& instance = effect->getInstance();
  3838. instance.prepareToPlay (44100.0, 1024);
  3839. instance.releaseResources();
  3840. instance.prepareToPlay (48000.0, 512);
  3841. run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
  3842. run->done = true;
  3843. });
  3844. // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
  3845. auto finish = std::make_shared<std::function<void()>>();
  3846. *finish = [this, run, counters, reportPath, fail, finish] {
  3847. if (! run->done)
  3848. {
  3849. juce::Timer::callAfterDelay (50, *finish);
  3850. return;
  3851. }
  3852. run->render.join();
  3853. juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
  3854. auto report = run->report;
  3855. int pluginLatency = -1;
  3856. if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
  3857. pluginLatency = effect->latencySamples();
  3858. const auto pdc = run->engine->getLatencySamples();
  3859. report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
  3860. << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
  3861. << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  3862. run->engine.reset(); // destroys the plugin: it writes its counters
  3863. // one line per plugin instance (the engine may have made more than one): none may have been
  3864. // deactivated inside process(), and the one that rendered must have restarted
  3865. int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
  3866. bool otherRate = false;
  3867. for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
  3868. {
  3869. juce::StringPairArray values;
  3870. for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
  3871. if (token.contains ("="))
  3872. values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
  3873. if (values.size() == 0)
  3874. continue;
  3875. ++lines;
  3876. report << "instance: " << line << "\n";
  3877. overlapped += values["overlapped"].getIntValue();
  3878. inactive += values["inactive_blocks"].getIntValue();
  3879. // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
  3880. // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
  3881. wrongThread += values["wrong_thread"].getIntValue();
  3882. misordered += values["misordered"].getIntValue();
  3883. unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
  3884. otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
  3885. if (values["requests"].getIntValue() > requests)
  3886. {
  3887. requests = values["requests"].getIntValue();
  3888. activations = values["activations"].getIntValue();
  3889. }
  3890. }
  3891. report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
  3892. << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
  3893. const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
  3894. && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
  3895. && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
  3896. if (! ok)
  3897. {
  3898. fail (report);
  3899. return;
  3900. }
  3901. report << "result=OK\n";
  3902. juce::File (reportPath).replaceWithText (report);
  3903. setApplicationReturnValue (0);
  3904. quit();
  3905. });
  3906. };
  3907. juce::Timer::callAfterDelay (50, *finish);
  3908. }
  3909. // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
  3910. // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
  3911. // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
  3912. void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
  3913. {
  3914. juce::String report;
  3915. bool ok = false;
  3916. {
  3917. lynx::AudioEngine offline (false);
  3918. auto& host = offline.getPluginHost();
  3919. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  3920. std::optional<juce::PluginDescription> vst2;
  3921. for (const auto& type : host.getKnownPlugins().getTypes())
  3922. if (type.pluginFormatName == "VST")
  3923. vst2 = type;
  3924. auto render = [&] (float gain, float& tempoSeen, int& adopted) {
  3925. lynx::FlVst2State state;
  3926. state.flags = 8;
  3927. state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
  3928. std::memcpy (state.chunk.data() + 4, &gain, 4);
  3929. auto song = lynx::Song::makeDefault();
  3930. song.bpm = 137.0;
  3931. auto& f = song.channels[4].plugin.foreign;
  3932. f.format = lynx::ForeignPlugin::Format::vst2;
  3933. f.vst2Id = (std::uint32_t) vst2->uniqueId;
  3934. f.name = "Some other name"; // found by the VST2 ID
  3935. f.state = lynx::writeFlVst2State (state);
  3936. song.channels[4].volume = 1.0f;
  3937. song.patterns[0].notes.clear();
  3938. song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
  3939. for (std::size_t c = 0; c < song.channels.size(); ++c)
  3940. if (c != 4)
  3941. song.channels[c].muted = true;
  3942. adopted = host.adoptFlPlugins (song);
  3943. offline.setSong (song);
  3944. const auto peak = offline.renderOffline (1.0, 48000.0);
  3945. offline.capturePluginStates();
  3946. juce::MemoryBlock saved;
  3947. saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
  3948. lynx::FlVst2State back;
  3949. tempoSeen = 0.0f;
  3950. if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
  3951. && back.chunk.size() >= 12)
  3952. std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
  3953. return peak;
  3954. };
  3955. if (vst2)
  3956. {
  3957. report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
  3958. float tempoA = 0, tempoB = 0;
  3959. int adoptedA = 0, adoptedB = 0;
  3960. const auto quiet = render (0.1f, tempoA, adoptedA);
  3961. const auto loud = render (0.4f, tempoB, adoptedB);
  3962. report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
  3963. << " tempo_seen=" << tempoB * 1000.0f << "\n";
  3964. ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
  3965. && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
  3966. }
  3967. }
  3968. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  3969. juce::File (reportPath).replaceWithText (report);
  3970. setApplicationReturnValue (ok ? 0 : 1);
  3971. quit();
  3972. }
  3973. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  3974. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  3975. // that the plugin comes back with the changed parameter.
  3976. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  3977. {
  3978. juce::String report;
  3979. bool ok = false;
  3980. {
  3981. lynx::AudioEngine offline (false);
  3982. auto& host = offline.getPluginHost();
  3983. host.addPluginFile (juce::File (pluginPath));
  3984. const juce::PluginDescription* vst3 = nullptr;
  3985. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  3986. for (const auto& type : types)
  3987. if (type.pluginFormatName == "VST3" && type.isInstrument)
  3988. vst3 = &type;
  3989. if (vst3 != nullptr)
  3990. {
  3991. juce::String error;
  3992. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  3993. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  3994. if (parameter != nullptr)
  3995. {
  3996. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  3997. parameter->setValueNotifyingHost (target);
  3998. juce::MemoryBlock juceState;
  3999. plugin->getStateInformation (juceState);
  4000. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  4001. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  4002. std::vector<std::uint8_t> flState;
  4003. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  4004. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  4005. put32 (id);
  4006. put32 ((std::uint32_t) data.getSize());
  4007. put32 (0);
  4008. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  4009. };
  4010. put32 (1);
  4011. record (1, juce::MemoryBlock (64, true));
  4012. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  4013. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  4014. juce::MemoryBlock slots;
  4015. const auto paramId = [&] (int i) {
  4016. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  4017. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  4018. };
  4019. const bool reorder = plugin->getParameters().size() >= 3;
  4020. if (reorder)
  4021. {
  4022. for (auto v : { 2u, paramId (2), paramId (0) })
  4023. slots.append (&v, 4);
  4024. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  4025. }
  4026. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  4027. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  4028. if (auto* child = xml->getChildByName (tag))
  4029. {
  4030. juce::MemoryBlock data;
  4031. data.fromBase64Encoding (child->getAllSubText());
  4032. record (id, data);
  4033. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  4034. }
  4035. if (reorder)
  4036. record (4, slots);
  4037. plugin.reset();
  4038. auto song = lynx::Song::makeDefault();
  4039. auto& f = song.channels[4].plugin.foreign;
  4040. f.format = lynx::ForeignPlugin::Format::vst3;
  4041. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  4042. f.state = flState;
  4043. {
  4044. std::vector<std::uint8_t> comp, ctrl;
  4045. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  4046. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  4047. }
  4048. for (int k = 0; k < 3; ++k)
  4049. {
  4050. lynx::Automation a;
  4051. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  4052. song.automations.push_back (a);
  4053. }
  4054. const auto adopted = host.adoptFlPlugins (song);
  4055. report << "adopted=" << adopted << "\n";
  4056. juce::String mapped;
  4057. for (const auto& a : song.automations)
  4058. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  4059. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  4060. report << "slot_positions=" << mapped << "\n";
  4061. const auto slotsOk = ! reorder || mapped == "2,0,1";
  4062. offline.setSong (song);
  4063. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  4064. {
  4065. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  4066. report << "restored_value=" << value << "\n";
  4067. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  4068. }
  4069. }
  4070. }
  4071. }
  4072. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  4073. juce::File (reportPath).replaceWithText (report);
  4074. setApplicationReturnValue (ok ? 0 : 1);
  4075. quit();
  4076. }
  4077. void runShowcase (const juce::String& outputPath, int currentPattern)
  4078. {
  4079. using namespace lynx;
  4080. Song song;
  4081. song.bpm = 124.0;
  4082. song.mixer = Song::defaultMixer();
  4083. const auto presets = synthPresets();
  4084. auto preset = [&] (const char* name) {
  4085. for (const auto& [n, sset] : presets)
  4086. if (n == name)
  4087. return sset;
  4088. return SynthSettings {};
  4089. };
  4090. auto channel = [&] (const char* name, InstrumentKind kind, float volume, int track, std::uint32_t colour) {
  4091. ChannelDef c;
  4092. c.name = name;
  4093. c.instrument = kind;
  4094. c.volume = volume;
  4095. c.mixerTrack = track;
  4096. c.colour = colour;
  4097. song.channels.push_back (c);
  4098. return (int) song.channels.size() - 1;
  4099. };
  4100. const auto kick = channel ("Kick", InstrumentKind::kick, 0.9f, 1, 0xffd9534f);
  4101. const auto clap = channel ("Clap", InstrumentKind::clap, 0.75f, 2, 0xfff0ad4e);
  4102. const auto hat = channel ("Hat", InstrumentKind::hat, 0.6f, 3, 0xfff7d774);
  4103. const auto snare = channel ("Snare", InstrumentKind::snare, 0.7f, 4, 0xffe8835a);
  4104. const auto bass = channel ("Reese Bass", InstrumentKind::synth, 0.8f, 5, 0xff5bc0de);
  4105. song.channels[(std::size_t) bass].synth = preset ("Reese Bass"); // preset name as defined in core/SynthPresets
  4106. const auto pad = channel ("Pad", InstrumentKind::synth, 0.7f, 6, 0xff9b7fd6);
  4107. song.channels[(std::size_t) pad].synth = preset ("Pad");
  4108. const auto pluck = channel ("Pluck", InstrumentKind::synth, 0.72f, 7, 0xff5cb85c);
  4109. song.channels[(std::size_t) pluck].synth = preset ("Pluck");
  4110. const auto lead = channel ("Supersaw", InstrumentKind::synth, 0.6f, 8, 0xff4fc3a1);
  4111. song.channels[(std::size_t) lead].synth = preset ("Supersaw");
  4112. auto addPattern = [&] (const char* name, std::uint32_t colour) {
  4113. auto& p = song.patterns.emplace_back();
  4114. p.name = name;
  4115. p.colour = colour;
  4116. return (int) song.patterns.size() - 1;
  4117. };
  4118. auto note = [&] (int pattern, int ch, double beat, double beats, int key, float velocity = 0.8f) {
  4119. Note n;
  4120. n.channel = ch;
  4121. n.start = (std::int64_t) (beat * ppq);
  4122. n.length = (std::int64_t) (beats * ppq);
  4123. n.key = key;
  4124. n.velocity = velocity;
  4125. song.patterns[(std::size_t) pattern].notes.push_back (n);
  4126. };
  4127. const auto beat = addPattern ("Beat", 0xffd9534f);
  4128. for (int s = 0; s < 16; s += 4)
  4129. song.patterns[(std::size_t) beat].toggleStep (kick, s);
  4130. for (int s : { 4, 12 })
  4131. song.patterns[(std::size_t) beat].toggleStep (clap, s);
  4132. for (int s = 2; s < 16; s += 4)
  4133. song.patterns[(std::size_t) beat].toggleStep (hat, s);
  4134. for (int s : { 7, 15 })
  4135. song.patterns[(std::size_t) beat].toggleStep (snare, s);
  4136. const auto groove = addPattern ("Groove", 0xfff0ad4e);
  4137. for (int s = 0; s < 16; ++s)
  4138. song.patterns[(std::size_t) groove].toggleStep (hat, s);
  4139. for (int s : { 4, 12 })
  4140. song.patterns[(std::size_t) groove].toggleStep (clap, s);
  4141. // Am – F – C – G, one bar each
  4142. const int roots[4] = { 45, 41, 48, 43 };
  4143. const int chords[4][3] = { { 57, 60, 64 }, { 53, 57, 60 }, { 55, 60, 64 }, { 55, 59, 62 } };
  4144. const auto bassline = addPattern ("Bass", 0xff5bc0de);
  4145. for (int bar = 0; bar < 4; ++bar)
  4146. for (int e = 0; e < 8; ++e)
  4147. if (e != 3)
  4148. note (bassline, bass, bar * 4 + e * 0.5, 0.4, roots[bar] - 12 + (e == 6 ? 12 : 0), e % 2 == 0 ? 0.9f : 0.65f);
  4149. const auto chordsPattern = addPattern ("Chords", 0xff9b7fd6);
  4150. for (int bar = 0; bar < 4; ++bar)
  4151. for (int k = 0; k < 3; ++k)
  4152. note (chordsPattern, pad, bar * 4, 3.9, chords[bar][k], 0.7f);
  4153. const auto melody = addPattern ("Melody", 0xff5cb85c);
  4154. const int line[] = { 69, 72, 76, 74, 72, 69, 67, 69, 65, 69, 72, 74, 72, 69, 67, 64,
  4155. 72, 76, 79, 76, 74, 72, 74, 76, 71, 74, 79, 78, 76, 74, 71, 67 };
  4156. for (int k = 0; k < 32; ++k)
  4157. if (k % 8 != 7)
  4158. note (melody, pluck, k * 0.5, k % 4 == 3 ? 0.9 : 0.4, line[k], k % 2 == 0 ? 0.85f : 0.65f);
  4159. const auto hook = addPattern ("Hook", 0xff4fc3a1);
  4160. for (int bar = 0; bar < 4; ++bar)
  4161. for (int k = 0; k < 3; ++k)
  4162. note (hook, lead, bar * 4 + k * 1.5, k == 2 ? 1.0 : 1.4, chords[bar][2] + 12 - k * 3, 0.8f);
  4163. // Playlist: intro, verse, drop, breakdown, final drop
  4164. song.playlistTracks = { { "Drums" }, { "Groove" }, { "Bass" }, { "Chords" }, { "Melody" }, { "Hook" }, { "Automation" } };
  4165. const auto bar = (std::int64_t) ppq * 4;
  4166. auto clip = [&] (int pattern, int track, int fromBar, int bars) {
  4167. const auto length = song.patterns[(std::size_t) pattern].effectiveLength (song.beatsPerBar);
  4168. for (int b = fromBar; b < fromBar + bars;)
  4169. {
  4170. Clip c;
  4171. c.pattern = pattern;
  4172. c.track = track;
  4173. c.start = b * bar;
  4174. c.length = length;
  4175. song.playlist.push_back (c);
  4176. b += (int) std::max<std::int64_t> (1, length / bar);
  4177. }
  4178. };
  4179. clip (chordsPattern, 3, 0, 8);
  4180. clip (melody, 4, 4, 4);
  4181. clip (beat, 0, 8, 16);
  4182. clip (groove, 1, 12, 12);
  4183. clip (bassline, 2, 8, 8);
  4184. clip (melody, 4, 8, 8);
  4185. clip (chordsPattern, 3, 16, 4);
  4186. clip (bassline, 2, 20, 4);
  4187. clip (hook, 5, 20, 4);
  4188. clip (melody, 4, 20, 4);
  4189. song.addMarker ({ 0, "Intro" });
  4190. song.addMarker ({ 8 * bar, "Drop" });
  4191. song.addMarker ({ 16 * bar, "Breakdown" });
  4192. song.addMarker ({ 20 * bar, "Final" });
  4193. // automation: the pad volume opens up during the intro
  4194. Automation a;
  4195. a.name = "Pad Volume";
  4196. a.target = { AutomationTargetKind::mixerVolume, 6, 0, 0 };
  4197. a.points = { { 0, 0.15f, 0.4f }, { 8 * bar, 0.8f, 0.0f } };
  4198. song.automations.push_back (a);
  4199. Clip ac;
  4200. ac.kind = ClipKind::automation;
  4201. ac.automation = 0;
  4202. ac.track = 6;
  4203. ac.start = 0;
  4204. ac.length = 8 * bar;
  4205. song.playlist.push_back (ac);
  4206. // mixer: names, colours and effects (bass compressor sidechained to the kick)
  4207. const char* names[] = { "Master", "Kick", "Clap", "Hat", "Snare", "Bass", "Pad", "Pluck", "Lead" };
  4208. for (int t = 0; t < 9; ++t)
  4209. {
  4210. song.mixer[(std::size_t) t].name = names[t];
  4211. if (t > 0)
  4212. song.mixer[(std::size_t) t].colour = song.channels[(std::size_t) t - 1].colour;
  4213. }
  4214. auto fx = [&] (int track, EffectKind kind) -> EffectSlot& {
  4215. song.mixer[(std::size_t) track].effects.push_back (makeEffectSlot (kind));
  4216. return song.mixer[(std::size_t) track].effects.back();
  4217. };
  4218. {
  4219. // kick EQ: cut below 30 Hz, weight at 60 Hz, remove the "boxiness" at 350 Hz, brightness at 4 kHz
  4220. auto& eq = fx (1, EffectKind::parametricEq);
  4221. auto band = [&] (int b, peq::BandType type, double hz, double db, double q) {
  4222. eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (type);
  4223. eq.params[(std::size_t) peq::param (b, 1)] = peq::hzValue (hz);
  4224. eq.params[(std::size_t) peq::param (b, 2)] = peq::gainValue (db);
  4225. eq.params[(std::size_t) peq::param (b, 3)] = peq::qValue (q);
  4226. };
  4227. band (0, peq::BandType::lowCut, 30.0, 0.0, 0.7);
  4228. band (1, peq::BandType::peak, 62.0, 5.0, 1.2);
  4229. band (2, peq::BandType::peak, 350.0, -6.0, 2.0);
  4230. band (3, peq::BandType::peak, 4200.0, 3.5, 1.5);
  4231. band (4, peq::BandType::highCut, 14000.0, 0.0, 0.7);
  4232. for (int b = 5; b < peq::bands; ++b)
  4233. eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (peq::BandType::off);
  4234. }
  4235. fx (1, EffectKind::distortion).mix = 0.3f;
  4236. auto& comp = fx (5, EffectKind::compressor);
  4237. comp.params[0] = 0.55f;
  4238. comp.params[1] = 0.8f;
  4239. comp.sidechain = 1;
  4240. fx (5, EffectKind::parametricEq);
  4241. fx (6, EffectKind::chorus);
  4242. fx (6, EffectKind::reverb);
  4243. fx (7, EffectKind::delay);
  4244. fx (7, EffectKind::reverb).mix = 0.4f;
  4245. fx (8, EffectKind::effector);
  4246. fx (8, EffectKind::delay);
  4247. fx (0, EffectKind::parametricEq);
  4248. auto& limiter = fx (0, EffectKind::limiter);
  4249. limiter.params = { 11.7f / 12.0f, 0.1f, 0.5f };
  4250. song.mixer[1].volume = 0.78f;
  4251. song.mixer[5].volume = 0.72f;
  4252. song.mixer[6].volume = 0.6f;
  4253. song.mixer[6].pan = -0.2f;
  4254. song.mixer[7].pan = 0.25f;
  4255. song.mode = PlayMode::song;
  4256. song.currentPattern = std::clamp (currentPattern, 0, (int) song.patterns.size() - 1);
  4257. juce::String error;
  4258. const auto ok = ProjectFile::save (song, juce::File (outputPath), error);
  4259. setApplicationReturnValue (ok ? 0 : 1);
  4260. quit();
  4261. }
  4262. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  4263. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  4264. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  4265. // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
  4266. struct TestVoice
  4267. {
  4268. explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
  4269. {
  4270. if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
  4271. instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
  4272. else
  4273. effect = std::move (p);
  4274. }
  4275. void noteOn()
  4276. {
  4277. if (instrument != nullptr)
  4278. instrument->noteOn (60, 0.9f);
  4279. }
  4280. void render (float* l, float* r, int n, float gainLeft, float gainRight)
  4281. {
  4282. if (instrument != nullptr)
  4283. {
  4284. instrument->render (l, r, n, gainLeft, gainRight);
  4285. return;
  4286. }
  4287. const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
  4288. juce::AudioBuffer<float> block (channels, 512);
  4289. juce::MidiBuffer midi;
  4290. for (int done = 0; done < n; done += 512)
  4291. {
  4292. const auto k = juce::jmin (512, n - done);
  4293. block.setSize (channels, k, false, false, true);
  4294. for (int i = 0; i < k; ++i)
  4295. {
  4296. const auto v = 0.25f * (float) std::sin (phase);
  4297. phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
  4298. for (int c = 0; c < channels; ++c)
  4299. block.setSample (c, i, v);
  4300. }
  4301. effect->processBlock (block, midi);
  4302. for (int i = 0; i < k; ++i)
  4303. {
  4304. l[done + i] += gainLeft * block.getSample (0, i);
  4305. r[done + i] += gainRight * block.getSample (1, i);
  4306. }
  4307. }
  4308. }
  4309. std::unique_ptr<lynx::PluginInstrument> instrument;
  4310. std::unique_ptr<juce::AudioPluginInstance> effect;
  4311. double phase = 0.0;
  4312. };
  4313. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  4314. {
  4315. juce::String report;
  4316. bool ok = false;
  4317. lynx::setPluginSandboxAlerts (false);
  4318. const juce::File log (reportPath + ".log");
  4319. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  4320. log.deleteFile();
  4321. {
  4322. lynx::PluginHost host (false);
  4323. host.addPluginFile (juce::File (pluginPath));
  4324. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  4325. // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
  4326. const juce::PluginDescription* instrument = nullptr;
  4327. for (const auto& type : types)
  4328. if (type.isInstrument)
  4329. instrument = &type;
  4330. for (const auto& type : types)
  4331. if (instrument == nullptr && ! type.isInstrument)
  4332. instrument = &type;
  4333. step ("host");
  4334. juce::String error;
  4335. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  4336. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  4337. step ("created");
  4338. if (remote != nullptr)
  4339. {
  4340. auto& proxy = *remote;
  4341. TestVoice voice (std::move (remote));
  4342. std::vector<float> l (48000), r (48000);
  4343. auto peakOf = [&] {
  4344. float peak = 0.0f;
  4345. for (std::size_t k = 0; k < l.size(); ++k)
  4346. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  4347. return peak;
  4348. };
  4349. const auto start = juce::Time::getMillisecondCounterHiRes();
  4350. voice.noteOn();
  4351. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  4352. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  4353. const auto peak = peakOf();
  4354. step ("played");
  4355. if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
  4356. {
  4357. // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
  4358. const auto dead = lynx::isSandboxedPluginDead (proxy);
  4359. std::fill (l.begin(), l.end(), 0.0f);
  4360. std::fill (r.begin(), r.end(), 0.0f);
  4361. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  4362. report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  4363. ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
  4364. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  4365. juce::File (reportPath).replaceWithText (report);
  4366. setApplicationReturnValue (ok ? 0 : 1);
  4367. quit();
  4368. return;
  4369. }
  4370. report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
  4371. << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  4372. if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
  4373. {
  4374. // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
  4375. std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
  4376. juce::Thread::sleep (4000);
  4377. juce::MemoryBlock state;
  4378. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  4379. proxy.getStateInformation (state);
  4380. report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
  4381. editor.reset();
  4382. }
  4383. // parameter -> state -> in-process plugin
  4384. bool stateOk = false;
  4385. if (! proxy.getParameters().isEmpty())
  4386. {
  4387. auto* p = proxy.getParameters()[0];
  4388. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  4389. p->setValue (target);
  4390. std::fill (l.begin(), l.end(), 0.0f);
  4391. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  4392. juce::MemoryBlock state;
  4393. proxy.getStateInformation (state);
  4394. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  4395. {
  4396. local->setStateInformation (state.getData(), (int) state.getSize());
  4397. const auto back = local->getParameters()[0]->getValue();
  4398. // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
  4399. auto control = target;
  4400. if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  4401. {
  4402. a->enableAllBuses();
  4403. a->prepareToPlay (48000.0, 512);
  4404. a->getParameters()[0]->setValue (target);
  4405. juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
  4406. block.clear();
  4407. juce::MidiBuffer none;
  4408. a->processBlock (block, none);
  4409. juce::MemoryBlock direct;
  4410. a->getStateInformation (direct);
  4411. if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  4412. {
  4413. b->setStateInformation (direct.getData(), (int) direct.getSize());
  4414. control = b->getParameters()[0]->getValue();
  4415. }
  4416. a->releaseResources();
  4417. }
  4418. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
  4419. stateOk = std::abs (back - control) < 0.02f;
  4420. }
  4421. }
  4422. step ("state");
  4423. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  4424. lynx::hangSandboxedPluginForTest (proxy);
  4425. juce::Thread::sleep (200);
  4426. std::fill (l.begin(), l.end(), 1.0f);
  4427. std::fill (r.begin(), r.end(), 1.0f);
  4428. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  4429. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  4430. std::fill (l.begin(), l.end(), 0.0f);
  4431. std::fill (r.begin(), r.end(), 0.0f);
  4432. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  4433. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  4434. const auto dead = lynx::isSandboxedPluginDead (proxy);
  4435. const auto hangPeak = peakOf();
  4436. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
  4437. // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
  4438. bool crashOk = false;
  4439. if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
  4440. {
  4441. auto& proxy2 = *second;
  4442. TestVoice voice2 (std::move (second));
  4443. voice2.noteOn();
  4444. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  4445. lynx::crashSandboxedPluginForTest (proxy2);
  4446. const auto crashStart = juce::Time::getMillisecondCounterHiRes();
  4447. while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
  4448. {
  4449. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  4450. juce::Thread::sleep (5);
  4451. }
  4452. const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
  4453. std::fill (l.begin(), l.end(), 0.0f);
  4454. std::fill (r.begin(), r.end(), 0.0f);
  4455. voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  4456. const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
  4457. report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
  4458. crashOk = crashDead && crashMs < 3000.0;
  4459. }
  4460. step ("crash");
  4461. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
  4462. }
  4463. }
  4464. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  4465. juce::File (reportPath).replaceWithText (report);
  4466. setApplicationReturnValue (ok ? 0 : 1);
  4467. quit();
  4468. }
  4469. // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
  4470. // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
  4471. // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
  4472. // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
  4473. // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
  4474. // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
  4475. void runUiPerf (const juce::File& project, const juce::File& report)
  4476. {
  4477. startupOptions = lynx::StartupOptions::load();
  4478. engine = std::make_unique<lynx::AudioEngine>();
  4479. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  4480. crashEngine = engine.get();
  4481. createMainWindow();
  4482. mainWindow->reveal();
  4483. juce::String error;
  4484. auto ok = false;
  4485. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  4486. if (project.hasFileExtension ("flp"))
  4487. ok = engine->importFlpFile (project, error);
  4488. else if (auto song = lynx::ProjectFile::load (project, error))
  4489. {
  4490. engine->setSong (std::move (*song));
  4491. ok = true;
  4492. }
  4493. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  4494. if (! ok)
  4495. {
  4496. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  4497. setApplicationReturnValue (1);
  4498. quit();
  4499. return;
  4500. }
  4501. // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
  4502. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
  4503. engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
  4504. struct Step
  4505. {
  4506. juce::String name;
  4507. std::function<void()> setup;
  4508. std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
  4509. int frames;
  4510. std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
  4511. };
  4512. struct UiPerf final : juce::Timer
  4513. {
  4514. LynxApplication& app;
  4515. juce::File report;
  4516. juce::String text;
  4517. std::vector<Step> steps;
  4518. std::size_t step = 0;
  4519. int frame = -1;
  4520. std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
  4521. std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
  4522. double setupMs = 0.0, wallStart = 0.0;
  4523. double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
  4524. double messageCpuStart = 0.0; // the message thread's CPU seconds
  4525. double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
  4526. int audioLoadTicks = 0;
  4527. UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r)) {}
  4528. juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
  4529. double paintNow() const
  4530. {
  4531. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  4532. if (auto* p = peer())
  4533. p->performAnyPendingRepaintsNow();
  4534. return juce::Time::getMillisecondCounterHiRes() - t0;
  4535. }
  4536. void timerCallback() override
  4537. {
  4538. if (step >= steps.size())
  4539. {
  4540. stopTimer();
  4541. finish();
  4542. return;
  4543. }
  4544. auto& s = steps[step];
  4545. if (frame < 0)
  4546. {
  4547. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  4548. if (s.setup)
  4549. s.setup();
  4550. paintNow();
  4551. setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
  4552. times.clear();
  4553. rendered.clear();
  4554. frames.clear();
  4555. wallStart = juce::Time::getMillisecondCounterHiRes();
  4556. cpuStart = lynx::processCpuSeconds();
  4557. messageCpuStart = lynx::threadCpuSeconds();
  4558. audioLoadSum = 0.0;
  4559. audioLoadTicks = 0;
  4560. frame = 0;
  4561. return;
  4562. }
  4563. audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
  4564. ++audioLoadTicks;
  4565. if (s.action)
  4566. s.action (frame);
  4567. if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
  4568. times.push_back (ms);
  4569. ++frame;
  4570. if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
  4571. return;
  4572. const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
  4573. const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
  4574. const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
  4575. text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
  4576. << " painted frames: " << stats (rendered) << "\n"
  4577. << " timed here (event + paint + blit): " << stats (times)
  4578. << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
  4579. << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
  4580. << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
  4581. << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
  4582. if (s.finish)
  4583. text << s.finish();
  4584. juce::File (report).replaceWithText (text);
  4585. ++step;
  4586. frame = -1;
  4587. }
  4588. static juce::String stats (std::vector<double> sorted)
  4589. {
  4590. std::sort (sorted.begin(), sorted.end());
  4591. 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()))]; };
  4592. double sum = 0.0;
  4593. int over = 0;
  4594. for (auto t : sorted)
  4595. {
  4596. sum += t;
  4597. over += t > 16.0 ? 1 : 0;
  4598. }
  4599. return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
  4600. + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
  4601. + " ms, >16 ms " + juce::String (over);
  4602. }
  4603. void finish()
  4604. {
  4605. // the cost of asking where the mouse is (X11: a round trip to the display server)
  4606. const auto q0 = juce::Time::getMillisecondCounterHiRes();
  4607. for (int i = 0; i < 100; ++i)
  4608. juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
  4609. text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
  4610. app.mainWindow->onFrame = nullptr;
  4611. app.mainWindow->watchFrames ({});
  4612. app.engine->stop();
  4613. text << "result=OK\n";
  4614. report.replaceWithText (text);
  4615. app.setApplicationReturnValue (0);
  4616. app.quit();
  4617. }
  4618. };
  4619. auto* ui = &mainWindow->getContent();
  4620. auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
  4621. auto* peer = mainWindow->getPeer();
  4622. if (peer == nullptr || ! target.isShowing())
  4623. return;
  4624. juce::ModifierKeys::currentModifiers = mods;
  4625. const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
  4626. juce::MouseWheelDetails wheel { dx, dy, false, false, false };
  4627. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  4628. juce::ModifierKeys::currentModifiers = {};
  4629. };
  4630. auto run = std::make_unique<UiPerf> (*this, report);
  4631. mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
  4632. // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
  4633. auto drag = std::make_shared<UiPerfDrag>();
  4634. mainWindow->watchFrames ([r = run.get(), drag] (double now, juce::Rectangle<int> area) {
  4635. if (r->frame >= 0)
  4636. r->frames.push_back (now);
  4637. drag->framePainted (now, area);
  4638. });
  4639. run->text << "project: " << project.getFullPathName() << "\n"
  4640. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  4641. << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
  4642. << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  4643. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
  4644. << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
  4645. << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
  4646. const auto none = juce::ModifierKeys();
  4647. // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
  4648. // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
  4649. // window's own mouse path, the frames painted as the window paints them)
  4650. const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
  4651. run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
  4652. ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  4653. engine->getTransport().songMode = false;
  4654. engine->rewind();
  4655. engine->play();
  4656. }, {}, 4000 });
  4657. run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
  4658. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  4659. const auto rail = strips.faderRailForSnapshot (dragTrack);
  4660. drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
  4661. }, {}, 3000, [drag] { return drag->stop(); } });
  4662. run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
  4663. run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
  4664. run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
  4665. run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
  4666. run->steps.push_back ({ "mixer scroll", {}, [wheelAt, ui, none] (int f) { wheelAt (ui->getMixerForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  4667. // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
  4668. // through the old path (a whole snapshot per move) and through editLevels
  4669. auto faderMove = [this] (bool levels, int f) {
  4670. for (int k = 0; k < 4; ++k)
  4671. {
  4672. const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
  4673. const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
  4674. if (levels)
  4675. engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
  4676. else
  4677. engine->editSong (edit, false);
  4678. }
  4679. };
  4680. run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
  4681. run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
  4682. // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
  4683. // loading while it stays open, pointing at the tiles, then closing it
  4684. run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
  4685. run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
  4686. // (round 175b: the picker is its own window)
  4687. if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
  4688. {
  4689. const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
  4690. 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
  4691. const auto local = picker->getPeer()->globalToLocal (p.toFloat());
  4692. picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
  4693. juce::Time::currentTimeMillis());
  4694. }
  4695. }, 60 });
  4696. run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
  4697. run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
  4698. run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
  4699. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  4700. run->steps.push_back ({ "playlist scroll sideways", {},
  4701. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  4702. run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
  4703. run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
  4704. [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  4705. // let the window draw the project first
  4706. perf = std::move (run);
  4707. juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
  4708. }
  4709. // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
  4710. // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
  4711. void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
  4712. const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
  4713. {
  4714. startupOptions = lynx::StartupOptions::load();
  4715. engine = std::make_unique<lynx::AudioEngine>();
  4716. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  4717. crashEngine = engine.get();
  4718. // the user's saved device stays as it was: this run's choices are undone before quitting
  4719. savedDeviceState = engine->getDeviceManager().createStateXml();
  4720. auto& devices = engine->getDeviceManager();
  4721. const auto driverFile = addDriverFileDeviceType();
  4722. const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
  4723. if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
  4724. devices.setCurrentAudioDeviceType (type, true);
  4725. if (bufferSize > 0 || deviceName.isNotEmpty())
  4726. {
  4727. auto setup = devices.getAudioDeviceSetup();
  4728. if (bufferSize > 0)
  4729. setup.bufferSize = bufferSize;
  4730. if (deviceName.isNotEmpty())
  4731. setup.outputDeviceName = deviceName;
  4732. const auto error = devices.setAudioDeviceSetup (setup, true);
  4733. if (error.isNotEmpty())
  4734. report.replaceWithText ("device error: " + error + "\n");
  4735. }
  4736. createMainWindow();
  4737. if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
  4738. mainWindow->reveal();
  4739. juce::String error;
  4740. auto ok = false;
  4741. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  4742. if (project.hasFileExtension ("flp"))
  4743. ok = engine->importFlpFile (project, error);
  4744. else if (auto song = lynx::ProjectFile::load (project, error))
  4745. {
  4746. engine->setSong (std::move (*song));
  4747. ok = true;
  4748. }
  4749. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  4750. if (! ok)
  4751. {
  4752. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  4753. restoreSavedDeviceState();
  4754. setApplicationReturnValue (1);
  4755. quit();
  4756. return;
  4757. }
  4758. if (recordTo.isNotEmpty())
  4759. engine->setAudioRecordingArmed (true); // opens the input of the driver
  4760. // let the window draw the project, then play from the start with fresh statistics
  4761. juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
  4762. if (engine == nullptr)
  4763. return;
  4764. engine->stop();
  4765. engine->rewind();
  4766. engine->getRtStats().reset();
  4767. engine->takeUiPulse();
  4768. if (recordTo.isNotEmpty())
  4769. engine->setRecording (true);
  4770. // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
  4771. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  4772. if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
  4773. engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
  4774. ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
  4775. engine->play();
  4776. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
  4777. if (engine == nullptr)
  4778. return;
  4779. engine->stop();
  4780. juce::String recording;
  4781. if (engine->getAudioLogger().isLogging())
  4782. {
  4783. recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
  4784. engine->getAudioLogger().stop();
  4785. }
  4786. if (recordTo.isNotEmpty())
  4787. recording = finishStressTake (juce::File (recordTo), seconds);
  4788. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  4789. const auto s = engine->getRtStats().snapshot();
  4790. juce::String text;
  4791. text << "project: " << project.getFullPathName() << "\n"
  4792. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  4793. << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
  4794. << juce::SystemStats::getCpuModel() << "\n"
  4795. << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
  4796. << engine->describeRealtime();
  4797. const auto pulse = engine->takeUiPulse();
  4798. text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
  4799. << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
  4800. text << " load histogram (share of the deadline: callbacks):";
  4801. for (std::size_t b = 0; b < s.histogram.size(); ++b)
  4802. if (s.histogram[b] > 0)
  4803. text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
  4804. text << "\n";
  4805. text << recording;
  4806. // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
  4807. if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
  4808. {
  4809. auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
  4810. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  4811. {
  4812. juce::Graphics g (image);
  4813. g.fillAll (lynx::theme::panel);
  4814. page->paintEntireComponent (g, false);
  4815. }
  4816. const juce::File shot (cli[at + 1].unquoted());
  4817. shot.deleteFile();
  4818. if (auto out = shot.createOutputStream())
  4819. juce::PNGImageFormat().writeImageToStream (image, *out);
  4820. }
  4821. text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
  4822. report.replaceWithText (text);
  4823. restoreSavedDeviceState();
  4824. setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
  4825. quit();
  4826. });
  4827. });
  4828. }
  4829. // --bendrectest (round 167a): see the command line above
  4830. void runBendRecordTest (const juce::File& report, bool songMode)
  4831. {
  4832. engine = std::make_unique<lynx::AudioEngine>();
  4833. auto text = std::make_shared<juce::String>();
  4834. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  4835. auto finish = [this] (int code) {
  4836. setApplicationReturnValue (code);
  4837. quit();
  4838. };
  4839. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  4840. if (device == nullptr)
  4841. {
  4842. step ("result=ERROR no audio device");
  4843. finish (1);
  4844. return;
  4845. }
  4846. step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
  4847. auto song = lynx::Song::makeDefault();
  4848. song.bpm = 120.0;
  4849. song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
  4850. engine->setSong (std::move (song));
  4851. auto o = engine->getRecordOptions();
  4852. o.recordNotes = true;
  4853. o.recordAutomation = true;
  4854. o.countInBars = 0;
  4855. o.waitForInput = false;
  4856. o.quantiseAutomation = false;
  4857. o.punchLoopRegion = false;
  4858. o.preRollBars = o.postRollBars = 0;
  4859. engine->setRecordOptions (o);
  4860. engine->stop();
  4861. engine->rewind();
  4862. engine->setRecording (true);
  4863. engine->startPlayback();
  4864. // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
  4865. auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
  4866. auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
  4867. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
  4868. auto tick = std::make_shared<std::function<void()>>();
  4869. *tick = [this, sent, t0, tick, step, finish, songMode] {
  4870. if (engine == nullptr)
  4871. return;
  4872. const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
  4873. if (ms < 2000.0)
  4874. {
  4875. const auto x = ms / 1000.0;
  4876. const auto v = (float) (x < 0.5 ? x * 2.0 : x < 1.5 ? 1.0 - (x - 0.5) * 2.0 : -1.0 + (x - 1.5) * 2.0);
  4877. const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
  4878. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
  4879. sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
  4880. juce::Timer::callAfterDelay (10, *tick);
  4881. return;
  4882. }
  4883. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
  4884. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  4885. juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
  4886. if (engine == nullptr)
  4887. return;
  4888. engine->stop();
  4889. juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
  4890. if (engine == nullptr)
  4891. return;
  4892. engine->setRecording (false);
  4893. const auto& s = engine->getSong();
  4894. // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
  4895. std::vector<std::pair<std::int64_t, float>> got;
  4896. juce::String where = "nothing";
  4897. for (const auto& a : s.automations)
  4898. if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
  4899. {
  4900. where = "automation clip \"" + juce::String (a.name) + "\"";
  4901. for (const auto& pt : a.points)
  4902. got.push_back ({ pt.tick, pt.value });
  4903. }
  4904. for (const auto& p : s.patterns)
  4905. for (const auto& lane : p.events)
  4906. if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
  4907. {
  4908. where = "pattern \"" + juce::String (p.name) + "\" event lane";
  4909. for (const auto& e : lane.events)
  4910. got.push_back ({ e.tick, e.value });
  4911. }
  4912. int notes = 0;
  4913. for (const auto& p : s.patterns)
  4914. notes += (int) p.notes.size();
  4915. float lo = 1.0f, hi = 0.0f;
  4916. for (const auto& [t, v] : got)
  4917. lo = std::min (lo, v), hi = std::max (hi, v);
  4918. // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
  4919. const auto span = got.empty() ? 0 : got.back().first - got.front().first;
  4920. const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
  4921. step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
  4922. step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
  4923. + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
  4924. + ", notes " + juce::String (notes));
  4925. if (! got.empty())
  4926. step ("last=" + juce::String (got.back().second, 3));
  4927. // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
  4928. // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
  4929. const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
  4930. const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
  4931. && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
  4932. : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
  4933. step (ok ? "result=OK" : "result=FAILED");
  4934. finish (ok ? 0 : 1);
  4935. });
  4936. });
  4937. };
  4938. juce::Timer::callAfterDelay (300, *tick);
  4939. }
  4940. // --countinrectest (round 170d): see the command line above.
  4941. void runCountInRecordTest (const juce::File& report)
  4942. {
  4943. engine = std::make_unique<lynx::AudioEngine>();
  4944. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  4945. struct StandIn final : juce::AudioIODevice
  4946. {
  4947. StandIn() : juce::AudioIODevice ("countin", "test") {}
  4948. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  4949. juce::StringArray getInputChannelNames() override { return {}; }
  4950. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  4951. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  4952. int getDefaultBufferSize() override { return 512; }
  4953. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  4954. void close() override {}
  4955. bool isOpen() override { return true; }
  4956. void start (juce::AudioIODeviceCallback*) override {}
  4957. void stop() override {}
  4958. bool isPlaying() override { return true; }
  4959. juce::String getLastError() override { return {}; }
  4960. int getCurrentBufferSizeSamples() override { return 512; }
  4961. double getCurrentSampleRate() override { return 48000.0; }
  4962. int getCurrentBitDepth() override { return 32; }
  4963. juce::BigInteger getActiveOutputChannels() const override
  4964. {
  4965. juce::BigInteger b;
  4966. b.setRange (0, 2, true);
  4967. return b;
  4968. }
  4969. juce::BigInteger getActiveInputChannels() const override { return {}; }
  4970. int getOutputLatencyInSamples() override { return 256; }
  4971. int getInputLatencyInSamples() override { return 0; }
  4972. };
  4973. auto device = std::make_shared<StandIn>();
  4974. auto text = std::make_shared<juce::String>();
  4975. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  4976. auto finish = [this] (int code) {
  4977. setApplicationReturnValue (code);
  4978. quit();
  4979. };
  4980. constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
  4981. lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
  4982. song.bpm = 120.0;
  4983. song.mixer = lynx::Song::defaultMixer (2);
  4984. song.channels.resize (1);
  4985. song.channels[0].mixerTrack = 1;
  4986. song.patterns.emplace_back();
  4987. song.mode = lynx::PlayMode::song;
  4988. song.currentPattern = 0;
  4989. engine->setSong (song);
  4990. engine->getTransport().metronome.store (true);
  4991. auto o = engine->getRecordOptions();
  4992. o.countInBars = 1;
  4993. o.catchWindow = lynx::ppq / 4;
  4994. o.compensateOutput = true;
  4995. o.recordNotes = true;
  4996. o.recordAudio = false;
  4997. o.recordAutomation = false;
  4998. o.waitForInput = false;
  4999. o.quantise = 0;
  5000. o.placeSongClip = true;
  5001. o.recordingMarkers = false;
  5002. o.punchLoopRegion = false;
  5003. o.preRollBars = o.postRollBars = 0;
  5004. engine->setRecordOptions (o);
  5005. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  5006. step ("stand-in device: 48 kHz, blocks of 512, output latency 256 samples; Song mode, 120 BPM, take from bar 3, count-in 1 bar");
  5007. // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
  5008. struct Event
  5009. {
  5010. std::int64_t heard;
  5011. juce::MidiMessage message;
  5012. };
  5013. struct Pass
  5014. {
  5015. std::vector<float> out;
  5016. std::vector<Event> events;
  5017. std::int64_t playingAt = -1; // the first sample of the block the song started in
  5018. int block = 0, blocks = 0;
  5019. std::function<void()> done;
  5020. };
  5021. constexpr int n = 512;
  5022. constexpr double rate = 48000.0;
  5023. // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
  5024. // ticks (the take is committed there); then stopped and its results left to the timer
  5025. auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  5026. *runPass = [this] (std::shared_ptr<Pass> pass) {
  5027. auto& cb = engine->deviceCallback();
  5028. std::vector<float> l (n), r (n);
  5029. float* outs[] = { l.data(), r.data() };
  5030. juce::AudioIODeviceCallbackContext context;
  5031. if (pass->block == 0)
  5032. {
  5033. engine->stop();
  5034. engine->seek ((double) (2 * bar));
  5035. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
  5036. engine->setRecording (true);
  5037. engine->startPlayback(); // the count-in starts
  5038. }
  5039. for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
  5040. {
  5041. // the events heard in this block: stamped the way the engine's clock maps time to heard samples
  5042. const auto blockStart = (std::int64_t) pass->block * n;
  5043. const auto clock = engine->liveClock();
  5044. const auto compMs = 1000.0 * (n + 256) / rate;
  5045. for (auto& e : pass->events)
  5046. if (e.heard >= blockStart && e.heard < blockStart + n)
  5047. {
  5048. auto m = e.message;
  5049. m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
  5050. engine->injectMidiInput (m);
  5051. }
  5052. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
  5053. pass->out.insert (pass->out.end(), l.begin(), l.end());
  5054. if (pass->playingAt < 0 && engine->getTransport().playing.load())
  5055. pass->playingAt = blockStart;
  5056. }
  5057. };
  5058. // (the recursion through the message loop; written out so each step lets the engine's timer run)
  5059. auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  5060. *drive = [this, runPass, drive, device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
  5061. if (engine == nullptr)
  5062. return;
  5063. (*runPass) (pass);
  5064. if (pass->block < pass->blocks)
  5065. {
  5066. juce::Timer::callAfterDelay (40, [pass, drive] { (*drive) (pass); });
  5067. return;
  5068. }
  5069. engine->stop();
  5070. juce::Timer::callAfterDelay (300, [this, pass] {
  5071. if (engine == nullptr)
  5072. return;
  5073. engine->setRecording (false);
  5074. juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
  5075. });
  5076. };
  5077. auto onsets = [] (const std::vector<float>& out) {
  5078. std::vector<std::int64_t> at;
  5079. std::int64_t last = -100000;
  5080. for (std::size_t i = 0; i < out.size(); ++i)
  5081. if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
  5082. {
  5083. at.push_back ((std::int64_t) i);
  5084. last = (std::int64_t) i;
  5085. }
  5086. else if (std::abs (out[i]) > 0.02f)
  5087. last = (std::int64_t) i;
  5088. return at;
  5089. };
  5090. // the graph is (re)built on the message thread: start once it has settled
  5091. juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
  5092. if (engine == nullptr)
  5093. return;
  5094. auto first = std::make_shared<Pass>();
  5095. first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
  5096. first->done = [this, first, step, finish, drive, onsets] {
  5097. const auto clicks = onsets (first->out);
  5098. juce::String list;
  5099. for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
  5100. list << clicks[i] << " ";
  5101. step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
  5102. // the bar-3 downbeat: the click at the block the song started in
  5103. std::int64_t down = -1;
  5104. for (auto c : clicks)
  5105. if (std::abs (c - first->playingAt) < n)
  5106. down = c;
  5107. if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
  5108. {
  5109. step ("result=FAILED no downbeat click found (or notes recorded without input)");
  5110. finish (1);
  5111. return;
  5112. }
  5113. const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
  5114. auto second = std::make_shared<Pass>();
  5115. second->blocks = first->blocks;
  5116. auto add = [&second] (std::int64_t at, int key, bool on) {
  5117. second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
  5118. };
  5119. for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
  5120. {
  5121. add (ms (-15.0), key, true);
  5122. add (ms (500.0), key, false);
  5123. }
  5124. add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
  5125. add (ms (-1250.0), 62, false);
  5126. add (ms (503.0), 77, true); // 3 ms after beat 2
  5127. add (ms (603.0), 77, false);
  5128. for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
  5129. {
  5130. add (ms (b * 2000.0), 70 + b, true);
  5131. add (ms (b * 2000.0 + 250.0), 70 + b, false);
  5132. }
  5133. second->done = [this, step, finish] {
  5134. const auto& s = engine->getSong();
  5135. const auto& p = s.patterns[0];
  5136. const lynx::Clip* clip = nullptr;
  5137. for (const auto& c : s.playlist)
  5138. if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
  5139. clip = &c;
  5140. const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
  5141. step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
  5142. auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
  5143. // where each one was heard (song ticks): 0.5 ms = ~1 tick
  5144. const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
  5145. { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
  5146. { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
  5147. { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
  5148. for (const auto& [key, tick] : want)
  5149. {
  5150. const lynx::Note* found = nullptr;
  5151. for (const auto& note : p.notes)
  5152. if (note.key == key)
  5153. found = &note;
  5154. const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
  5155. const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
  5156. ok = ok && good;
  5157. step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
  5158. + (good ? " ok" : " WRONG"));
  5159. }
  5160. const auto* chord = [&p] () -> const lynx::Note* {
  5161. for (const auto& note : p.notes)
  5162. if (note.key == 60)
  5163. return &note;
  5164. return nullptr;
  5165. }();
  5166. if (chord != nullptr)
  5167. step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
  5168. step (ok ? "result=OK" : "result=FAILED");
  5169. finish (ok ? 0 : 1);
  5170. };
  5171. (*drive) (second);
  5172. };
  5173. (*drive) (first);
  5174. });
  5175. }
  5176. // --cliplooptest (round 167q): see the command line above.
  5177. void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
  5178. {
  5179. engine = std::make_unique<lynx::AudioEngine>();
  5180. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  5181. struct StandIn final : juce::AudioIODevice
  5182. {
  5183. StandIn() : juce::AudioIODevice ("cliploop", "test") {}
  5184. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  5185. juce::StringArray getInputChannelNames() override { return {}; }
  5186. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  5187. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  5188. int getDefaultBufferSize() override { return 512; }
  5189. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  5190. void close() override {}
  5191. bool isOpen() override { return true; }
  5192. void start (juce::AudioIODeviceCallback*) override {}
  5193. void stop() override {}
  5194. bool isPlaying() override { return true; }
  5195. juce::String getLastError() override { return {}; }
  5196. int getCurrentBufferSizeSamples() override { return 512; }
  5197. double getCurrentSampleRate() override { return 48000.0; }
  5198. int getCurrentBitDepth() override { return 32; }
  5199. juce::BigInteger getActiveOutputChannels() const override
  5200. {
  5201. juce::BigInteger b;
  5202. b.setRange (0, 2, true);
  5203. return b;
  5204. }
  5205. juce::BigInteger getActiveInputChannels() const override { return {}; }
  5206. int getOutputLatencyInSamples() override { return 0; }
  5207. int getInputLatencyInSamples() override { return 0; }
  5208. };
  5209. auto device = std::make_shared<StandIn>();
  5210. auto text = std::make_shared<juce::String>();
  5211. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  5212. constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
  5213. const auto ppq = (double) lynx::ppq;
  5214. lynx::Song song;
  5215. song.bpm = 120.0;
  5216. song.mixer = lynx::Song::defaultMixer (2);
  5217. song.channels.resize (1); // the synth of a new channel: deterministic
  5218. song.channels[0].mixerTrack = 1;
  5219. auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
  5220. for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
  5221. {
  5222. lynx::Note n;
  5223. n.start = b * lynx::ppq;
  5224. n.length = lynx::ppq / 4;
  5225. n.key = key;
  5226. pattern.notes.push_back (n);
  5227. }
  5228. lynx::Clip clip;
  5229. clip.pattern = 0;
  5230. clip.length = 16 * lynx::ppq; // stretched to 4 bars
  5231. song.playlist.push_back (clip);
  5232. song.mode = lynx::PlayMode::song;
  5233. {
  5234. // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
  5235. auto gui = song;
  5236. gui.playlist[0].length = 4 * lynx::ppq;
  5237. juce::String error;
  5238. lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
  5239. }
  5240. engine->setSong (song);
  5241. auto& callback = engine->deviceCallback();
  5242. callback.audioDeviceAboutToStart (device.get());
  5243. step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
  5244. // the graph is (re)built on the message thread: the scenarios run once it has settled
  5245. juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
  5246. if (engine == nullptr)
  5247. return;
  5248. auto& cb = engine->deviceCallback();
  5249. // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
  5250. auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
  5251. engine->stop();
  5252. engine->seek (from);
  5253. std::vector<float> l (512), r (512), out;
  5254. float* outs[] = { l.data(), r.data() };
  5255. juce::AudioIODeviceCallbackContext context;
  5256. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
  5257. engine->play();
  5258. for (int k = 0; (int) out.size() < samples; ++k)
  5259. {
  5260. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  5261. out.insert (out.end(), l.begin(), l.end());
  5262. if (between)
  5263. between (k);
  5264. }
  5265. engine->stop();
  5266. for (int k = 0; k < 400; ++k) // the tails of the scenario die out
  5267. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  5268. out.resize ((std::size_t) samples);
  5269. return out;
  5270. };
  5271. auto rms = [] (const std::vector<float>& x, int from, int count) {
  5272. double sum = 0.0;
  5273. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  5274. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5275. return std::sqrt (sum / juce::jmax (1, count));
  5276. };
  5277. auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
  5278. double m = 0.0;
  5279. for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
  5280. m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
  5281. return m;
  5282. };
  5283. auto num = [] (double v) { return juce::String (v, 6); };
  5284. bool ok = true;
  5285. auto check = [&ok, step] (bool good, const juce::String& what) {
  5286. ok = ok && good;
  5287. step ((good ? "ok " : "FAIL ") + what);
  5288. };
  5289. lynx::setStretchedClipsLoop (true);
  5290. const auto a = play (0.0, 4 * bar);
  5291. const auto bar1 = rms (a, 0, bar);
  5292. check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
  5293. for (int k = 1; k < 4; ++k)
  5294. {
  5295. const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
  5296. check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  5297. "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
  5298. }
  5299. {
  5300. const auto x = play (10 * ppq, bar + bar / 2);
  5301. const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
  5302. check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
  5303. "start inside a repeat (bar 3, beat 3): RMS " + num (rms (x, 0, (int) x.size())) + ", max diff vs bar 1 " + juce::String (d, 9));
  5304. }
  5305. {
  5306. // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
  5307. const auto jumpBlock = 7 * beat / 512 - 1;
  5308. const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
  5309. if (k == jumpBlock)
  5310. engine->seek (14 * ppq);
  5311. });
  5312. // (the best of 0-2 samples late: anything but 0 fails)
  5313. const auto at = (jumpBlock + 1) * 512;
  5314. int lag = 0;
  5315. auto d = 1.0e9;
  5316. for (int l = 0; l <= 2; ++l)
  5317. if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
  5318. d = dl, lag = l;
  5319. d = lag == 0 ? d : 1.0;
  5320. const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
  5321. check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
  5322. "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
  5323. + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
  5324. }
  5325. {
  5326. engine->editSong ([ppq] (lynx::Song& s) {
  5327. s.loopStart = (std::int64_t) (4 * ppq);
  5328. s.loopEnd = (std::int64_t) (12 * ppq);
  5329. }, false);
  5330. const auto x = play (0.0, 7 * bar);
  5331. double d = 0.0;
  5332. juce::String lags;
  5333. for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
  5334. {
  5335. auto best = 1.0e9;
  5336. int lag = 0;
  5337. for (int l = 0; l <= 2; ++l)
  5338. if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
  5339. best = dl, lag = l;
  5340. d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
  5341. lags << (k > 1 ? "," : "") << lag;
  5342. }
  5343. const auto r = rms (x, bar, 6 * bar);
  5344. check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  5345. "loop region bars 2-3, played 3 times: RMS " + num (r) + " (x" + num (r / bar1) + "), max diff of each bar vs bar 1 " + juce::String (d, 9)
  5346. + " (samples late, bars 2-7: " + lags + ")");
  5347. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  5348. }
  5349. {
  5350. // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
  5351. // wrap used to play one sample more)
  5352. engine->editSong ([ppq] (lynx::Song& s) {
  5353. s.loopStart = (std::int64_t) (4 * ppq);
  5354. s.loopEnd = (std::int64_t) (8 * ppq);
  5355. }, false);
  5356. const auto x = play (0.0, 101 * bar);
  5357. double d = 0.0;
  5358. int worst = 0;
  5359. for (int k = 1; k <= 100; ++k)
  5360. if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
  5361. d = dk, worst = k + 1;
  5362. check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
  5363. + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
  5364. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  5365. }
  5366. lynx::setStretchedClipsLoop (false);
  5367. {
  5368. const auto x = play (0.0, 4 * bar);
  5369. const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
  5370. check (diff (x, 0, a, 0, bar) < 1.0e-4 && r < 1.0e-5, "option off (FL): bar 1 the same, bars 2-4 RMS at most " + juce::String (r, 9));
  5371. }
  5372. lynx::setStretchedClipsLoop (true);
  5373. cb.audioDeviceStopped();
  5374. // the export: a WAV of the 4 bars, read back from the file
  5375. if (wavFile != juce::File())
  5376. {
  5377. for (const auto loops : { true, false })
  5378. {
  5379. lynx::setStretchedClipsLoop (loops);
  5380. const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
  5381. file.deleteFile();
  5382. {
  5383. juce::WavAudioFormat wav;
  5384. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
  5385. engine->stop();
  5386. engine->seek (0.0);
  5387. lynx::AudioEngine::RenderOptions o;
  5388. o.seconds = 8.0;
  5389. o.sampleRate = 48000.0;
  5390. o.output = writer.get();
  5391. engine->renderOffline (o);
  5392. }
  5393. juce::WavAudioFormat wav;
  5394. std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
  5395. std::vector<float> x;
  5396. if (reader != nullptr)
  5397. {
  5398. juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
  5399. reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
  5400. x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
  5401. }
  5402. const auto b1 = rms (x, 0, bar);
  5403. juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
  5404. bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
  5405. for (int k = 1; k < 4; ++k)
  5406. {
  5407. const auto rk = rms (x, k * bar, bar);
  5408. line << ", bar " << (k + 1) << " " << num (rk);
  5409. good = good && (loops ? std::abs (rk / b1 - 1.0) < 1.0e-3 && diff (x, k * bar, x, 0, bar) < 1.0e-4 : rk < 1.0e-5);
  5410. }
  5411. if (loops)
  5412. line << ", max |bar - bar 1| " << juce::String (juce::jmax (diff (x, bar, x, 0, bar), juce::jmax (diff (x, 2 * bar, x, 0, bar), diff (x, 3 * bar, x, 0, bar))), 9);
  5413. check (good, line);
  5414. }
  5415. lynx::setStretchedClipsLoop (true);
  5416. }
  5417. step (ok ? "result=OK" : "result=FAILED");
  5418. setApplicationReturnValue (ok ? 0 : 1);
  5419. quit();
  5420. });
  5421. }
  5422. // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
  5423. // process leaves what was done).
  5424. void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  5425. const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
  5426. {
  5427. engine = std::make_unique<lynx::AudioEngine>();
  5428. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  5429. savedDeviceState = engine->getDeviceManager().createStateXml();
  5430. auto text = std::make_shared<juce::String>();
  5431. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  5432. auto finish = [this, step] (int code) {
  5433. restoreSavedDeviceState();
  5434. setApplicationReturnValue (code);
  5435. quit();
  5436. };
  5437. auto& devices = engine->getDeviceManager();
  5438. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  5439. devices.setCurrentAudioDeviceType (deviceType, true);
  5440. {
  5441. auto setup = devices.getAudioDeviceSetup();
  5442. if (deviceName.isNotEmpty())
  5443. setup.outputDeviceName = deviceName;
  5444. if (bufferSize > 0)
  5445. setup.bufferSize = bufferSize;
  5446. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  5447. step ("device_error=" + error);
  5448. }
  5449. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  5450. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  5451. // takes go next to the report, not into the user's recordings folder
  5452. engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
  5453. auto* device = devices.getCurrentAudioDevice();
  5454. if (device == nullptr || engine->getInputChannelNames().empty())
  5455. {
  5456. step ("result=ERROR no device / no input");
  5457. finish (1);
  5458. return;
  5459. }
  5460. const auto rate = device->getCurrentSampleRate();
  5461. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
  5462. + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
  5463. // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
  5464. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  5465. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  5466. {
  5467. lynx::takes::WavTakeWriter w;
  5468. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  5469. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  5470. std::vector<float> block (4096);
  5471. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  5472. {
  5473. std::fill (block.begin(), block.end(), 0.0f);
  5474. for (int k = 0; k < (int) block.size(); ++k)
  5475. {
  5476. const auto f = at + k;
  5477. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  5478. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  5479. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  5480. if (rel >= 0 && rel < 5)
  5481. block[(std::size_t) k] = 0.5f * shape[rel];
  5482. }
  5483. const float* d[] { block.data() };
  5484. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  5485. }
  5486. w.close();
  5487. }
  5488. lynx::Song song = lynx::Song::makeDefault();
  5489. song.bpm = 120.0;
  5490. song.mode = lynx::PlayMode::song;
  5491. song.playlist.clear();
  5492. lynx::ChannelDef c;
  5493. c.name = "Clicks";
  5494. c.instrument = lynx::InstrumentKind::audioClip;
  5495. c.samplePath = clickFile.getFullPathName().toStdString();
  5496. c.mixerTrack = 0;
  5497. c.volume = 1.0f;
  5498. song.channels.push_back (c);
  5499. lynx::Clip clip;
  5500. clip.kind = lynx::ClipKind::audio;
  5501. clip.channel = (int) song.channels.size() - 1;
  5502. clip.track = 0;
  5503. clip.start = 0;
  5504. clip.length = (std::int64_t) beats * lynx::ppq;
  5505. song.playlist.push_back (clip);
  5506. if (mode == 1) // loop recording, bars 2-4
  5507. {
  5508. song.loopStart = 4 * lynx::ppq;
  5509. song.loopEnd = 16 * lynx::ppq;
  5510. }
  5511. else if (mode == 2) // punch in/out, bars 3-4
  5512. {
  5513. song.loopStart = 8 * lynx::ppq;
  5514. song.loopEnd = 16 * lynx::ppq;
  5515. }
  5516. if (song.mixer.size() > 1)
  5517. {
  5518. song.mixer[1].name = "Loop In";
  5519. song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
  5520. }
  5521. engine->setSong (std::move (song));
  5522. engine->setInsertInput (1, 0, false);
  5523. juce::ignoreUnused (pdcSamples);
  5524. // 1) the ping
  5525. if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
  5526. step ("ping_error=" + error);
  5527. juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
  5528. if (engine == nullptr)
  5529. return;
  5530. if (engine->isPinging())
  5531. engine->cancelLatencyPing();
  5532. const auto r = engine->finishLatencyPing();
  5533. step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
  5534. + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
  5535. const auto l = engine->currentLatency();
  5536. step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
  5537. // 2) record
  5538. engine->setInsertArmed (1, true);
  5539. auto o = engine->getRecordOptions();
  5540. o.recordAudio = true;
  5541. o.countInBars = 0;
  5542. o.waitForInput = false;
  5543. o.punchLoopRegion = mode == 2;
  5544. o.preRollBars = mode == 2 ? 1 : 0;
  5545. o.postRollBars = mode == 2 ? 1 : 0;
  5546. engine->setRecordOptions (o);
  5547. engine->stop();
  5548. engine->rewind();
  5549. engine->setRecording (true);
  5550. juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
  5551. if (engine == nullptr)
  5552. return;
  5553. engine->startPlayback(); // (as the Play button: pre-roll / punch)
  5554. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
  5555. if (engine == nullptr)
  5556. return;
  5557. if (mode == 2)
  5558. step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
  5559. engine->stop();
  5560. juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
  5561. if (engine == nullptr)
  5562. return;
  5563. engine->setRecording (false);
  5564. const auto& s = engine->getSong();
  5565. const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
  5566. int take = -1;
  5567. for (int ch = 0; ch < (int) s.channels.size(); ++ch)
  5568. if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
  5569. take = ch;
  5570. if (take < 0)
  5571. {
  5572. step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
  5573. finish (1);
  5574. return;
  5575. }
  5576. std::vector<std::vector<float>> audio;
  5577. double takeRate = 0.0;
  5578. const auto& path = s.channels[(std::size_t) take].samplePath;
  5579. lynx::takes::readWav (path, audio, &takeRate);
  5580. const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
  5581. step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
  5582. + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
  5583. // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
  5584. std::vector<juce::int64> peaks;
  5585. if (! audio.empty())
  5586. for (juce::int64 f = 1; f + 1 < frames; ++f)
  5587. {
  5588. const auto x = std::abs (audio[0][(std::size_t) f]);
  5589. if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
  5590. && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
  5591. peaks.push_back (f);
  5592. }
  5593. // every clip of the take: each click inside it against the nearest beat
  5594. int clips = 0, checked = 0, muted = 0;
  5595. double worst = 0.0, sum = 0.0;
  5596. for (const auto& c : s.playlist)
  5597. {
  5598. if (c.kind != lynx::ClipKind::audio || c.channel != take)
  5599. continue;
  5600. ++clips;
  5601. muted += c.muted ? 1 : 0;
  5602. const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
  5603. for (const auto f : peaks)
  5604. {
  5605. const auto intoClip = (double) f - skip;
  5606. if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
  5607. continue;
  5608. const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
  5609. const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
  5610. const auto error = (songTick - beat) / tps;
  5611. worst = std::max (worst, std::abs (error));
  5612. sum += error;
  5613. ++checked;
  5614. }
  5615. step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
  5616. + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
  5617. + (c.muted ? " (muted lane)" : ""));
  5618. }
  5619. step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
  5620. + " muted_lanes=" + juce::String (muted));
  5621. step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
  5622. auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
  5623. if (mode == 2) // one clip, exactly the punch range, its 8 beats
  5624. {
  5625. const auto& sp = engine->getSong();
  5626. bool exact = false;
  5627. for (const auto& c : sp.playlist)
  5628. if (c.kind == lynx::ClipKind::audio && c.channel == take)
  5629. exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
  5630. step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
  5631. ok = ok && clips == 1 && exact && checked == 8;
  5632. }
  5633. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  5634. finish (ok ? 0 : 1);
  5635. });
  5636. });
  5637. });
  5638. });
  5639. }
  5640. // --hwinserttest (round 164d): see the command line above.
  5641. void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  5642. const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
  5643. {
  5644. engine = std::make_unique<lynx::AudioEngine>();
  5645. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  5646. savedDeviceState = engine->getDeviceManager().createStateXml();
  5647. auto text = std::make_shared<juce::String>();
  5648. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  5649. auto finish = [this] (int code) {
  5650. if (engine != nullptr)
  5651. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  5652. restoreSavedDeviceState();
  5653. setApplicationReturnValue (code);
  5654. quit();
  5655. };
  5656. auto& devices = engine->getDeviceManager();
  5657. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  5658. devices.setCurrentAudioDeviceType (deviceType, true);
  5659. {
  5660. auto setup = devices.getAudioDeviceSetup();
  5661. if (deviceName.isNotEmpty())
  5662. setup.outputDeviceName = deviceName;
  5663. if (bufferSize > 0)
  5664. setup.bufferSize = bufferSize;
  5665. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  5666. step ("device_error=" + error);
  5667. }
  5668. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  5669. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  5670. auto* device = devices.getCurrentAudioDevice();
  5671. if (device == nullptr || engine->getInputChannelNames().empty())
  5672. {
  5673. step ("result=ERROR no device / no input");
  5674. finish (1);
  5675. return;
  5676. }
  5677. const auto rate = device->getCurrentSampleRate();
  5678. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
  5679. // the click track: the ping's pulse on every beat at 120 bpm
  5680. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  5681. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  5682. {
  5683. lynx::takes::WavTakeWriter w;
  5684. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  5685. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  5686. std::vector<float> block (4096);
  5687. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  5688. {
  5689. std::fill (block.begin(), block.end(), 0.0f);
  5690. for (int k = 0; k < (int) block.size(); ++k)
  5691. {
  5692. const auto f = at + k;
  5693. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  5694. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  5695. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  5696. if (rel >= 0 && rel < 5)
  5697. block[(std::size_t) k] = 0.5f * shape[rel];
  5698. }
  5699. const float* d[] { block.data() };
  5700. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  5701. }
  5702. w.close();
  5703. }
  5704. lynx::Song song = lynx::Song::makeDefault();
  5705. song.bpm = 120.0;
  5706. song.mode = lynx::PlayMode::song;
  5707. song.playlist.clear();
  5708. song.channels.clear();
  5709. for (int k = 0; k < 2; ++k)
  5710. {
  5711. lynx::ChannelDef c;
  5712. c.name = k == 0 ? "Wet" : "Dry";
  5713. c.instrument = lynx::InstrumentKind::audioClip;
  5714. c.samplePath = clickFile.getFullPathName().toStdString();
  5715. c.mixerTrack = k + 1;
  5716. c.volume = 1.0f;
  5717. song.channels.push_back (c);
  5718. lynx::Clip clip;
  5719. clip.kind = lynx::ClipKind::audio;
  5720. clip.channel = k;
  5721. clip.track = k;
  5722. clip.start = 0;
  5723. clip.length = (std::int64_t) beats * lynx::ppq;
  5724. song.playlist.push_back (clip);
  5725. }
  5726. song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
  5727. for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
  5728. fx.enabled = false;
  5729. song.mixer[1].pan = -1.0f;
  5730. song.mixer[2].pan = 1.0f;
  5731. auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  5732. hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
  5733. hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
  5734. hw.params[lynx::hwinsert::inputStereo] = 1.0f;
  5735. song.mixer[1].effects.clear();
  5736. lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
  5737. if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
  5738. {
  5739. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  5740. lynx::PatchNode node;
  5741. node.effect = hw;
  5742. slot.patcher.nodes = { node };
  5743. lynx::PatchWire in, out;
  5744. in.from = lynx::patchFromHost;
  5745. in.to = 0;
  5746. out.from = 0;
  5747. out.to = lynx::patchToHost;
  5748. slot.patcher.wires = { in, out };
  5749. song.mixer[1].effects.push_back (slot);
  5750. ref.nodes = { 0 };
  5751. }
  5752. else
  5753. song.mixer[1].effects.push_back (hw);
  5754. engine->setSong (std::move (song));
  5755. step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
  5756. const auto meter = [this, ref] (int output) {
  5757. const auto fx = engine->runningHardwareInsert (ref);
  5758. return fx != nullptr ? fx->controlOutput (output) : 0.0f;
  5759. };
  5760. // 1) the insert's ping (as its Ping button: a momentary value flipped)
  5761. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  5762. if (engine == nullptr)
  5763. return;
  5764. engine->pingHardwareInserts ({ ref });
  5765. juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  5766. if (engine == nullptr)
  5767. return;
  5768. // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
  5769. // new round trip rebuilds the insert (its latency), so the result is read from the slot
  5770. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  5771. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  5772. const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
  5773. const auto state = meter (lynx::hwinsert::pingState);
  5774. const auto ok = samples > 0 && setup == engine->currentSetupKey();
  5775. step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
  5776. + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
  5777. if (! ok)
  5778. {
  5779. step ("result=FAILED ping");
  5780. finish (1);
  5781. return;
  5782. }
  5783. // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
  5784. step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
  5785. // 2) play, capturing the Master
  5786. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
  5787. if (engine == nullptr)
  5788. return;
  5789. step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
  5790. // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
  5791. // odd round trip (12345 samples: the project keeps it to the sample)
  5792. if (! inPatcher)
  5793. {
  5794. auto odd = engine->getSong();
  5795. odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
  5796. juce::String error;
  5797. auto same = true;
  5798. for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
  5799. {
  5800. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
  5801. const auto saved = lynx::ProjectFile::save (*song, file, error);
  5802. const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
  5803. same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  5804. && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
  5805. && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
  5806. && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
  5807. }
  5808. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
  5809. step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
  5810. if (! same)
  5811. {
  5812. step ("result=FAILED project");
  5813. finish (1);
  5814. return;
  5815. }
  5816. }
  5817. auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
  5818. engine->stop();
  5819. engine->rewind();
  5820. engine->getMeters().capture.setSource (0);
  5821. engine->play();
  5822. auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
  5823. auto pull = std::make_shared<std::function<void()>>();
  5824. *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
  5825. if (engine == nullptr)
  5826. return;
  5827. engine->getMeters().capture.pull (*left, *right);
  5828. if (*pulls == 10) // the insert's editor while it plays (next to the report)
  5829. for (const auto scale : { 1.0f, 1.5f })
  5830. {
  5831. auto editor = inPatcher ? lynx::makeNodeEffectEditor (
  5832. *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
  5833. [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
  5834. : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
  5835. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  5836. {
  5837. juce::Graphics g (image);
  5838. g.fillAll (lynx::theme::panel);
  5839. editor->paintEntireComponent (g, false);
  5840. }
  5841. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
  5842. file.deleteFile();
  5843. juce::PNGImageFormat png;
  5844. if (auto stream = file.createOutputStream())
  5845. png.writeImageToStream (image, *stream);
  5846. }
  5847. if (--*pulls > 0)
  5848. {
  5849. juce::Timer::callAfterDelay (200, *pull);
  5850. return;
  5851. }
  5852. engine->stop();
  5853. const auto dropped = engine->getMeters().capture.droppedFrames();
  5854. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  5855. // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
  5856. auto peaksOf = [rate] (const std::vector<float>& x) {
  5857. std::vector<juce::int64> peaks;
  5858. for (std::size_t f = 1; f + 1 < x.size(); ++f)
  5859. 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])
  5860. && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
  5861. peaks.push_back ((juce::int64) f);
  5862. return peaks;
  5863. };
  5864. const auto wet = peaksOf (*left), dry = peaksOf (*right);
  5865. int pairs = 0;
  5866. juce::int64 worst = 0;
  5867. double gainSum = 0.0, residual = 0.0, energy = 0.0;
  5868. for (const auto w : wet)
  5869. {
  5870. 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); });
  5871. if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
  5872. continue;
  5873. ++pairs;
  5874. worst = std::max (worst, std::abs (*best - w));
  5875. gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
  5876. }
  5877. const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
  5878. // dry clicks with no wet click beside them (a dropout of the cable / device), listed
  5879. juce::String unmatched;
  5880. for (const auto d : dry)
  5881. if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
  5882. unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
  5883. if (unmatched.isNotEmpty())
  5884. step ("dry_clicks_without_wet=" + unmatched);
  5885. // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
  5886. for (const auto w : wet)
  5887. for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
  5888. {
  5889. const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
  5890. residual += d * d;
  5891. energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
  5892. }
  5893. const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
  5894. step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
  5895. + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
  5896. step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
  5897. auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
  5898. const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
  5899. step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
  5900. const auto excused = xruns > 0 ? 2 * xruns : 0;
  5901. const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
  5902. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  5903. // (round 165c) then the re-ping notice after a buffer size change
  5904. auto then = [this, ref, step, finish] (int code) {
  5905. if (code != 0)
  5906. finish (code);
  5907. else
  5908. runRepingCheck (ref, step, finish);
  5909. };
  5910. if (! ok)
  5911. {
  5912. finish (1);
  5913. return;
  5914. }
  5915. if (bounceFile == juce::File())
  5916. then (0);
  5917. else
  5918. runBounceCheck (bounceFile, step, then);
  5919. };
  5920. juce::Timer::callAfterDelay (200, *pull);
  5921. });
  5922. });
  5923. });
  5924. }
  5925. // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
  5926. // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
  5927. // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
  5928. // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
  5929. // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
  5930. // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
  5931. void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  5932. {
  5933. auto& devices = engine->getDeviceManager();
  5934. auto setup = devices.getAudioDeviceSetup();
  5935. const auto before = setup.bufferSize;
  5936. setup.bufferSize = before == 512 ? 256 : 512;
  5937. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  5938. step ("reping_device_error=" + error);
  5939. engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
  5940. juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
  5941. if (engine == nullptr)
  5942. return;
  5943. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  5944. const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
  5945. const auto notice = engine->takeHardwareInsertNotice();
  5946. step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
  5947. + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
  5948. if (notice.size() != 1 || ! (notice[0] == ref))
  5949. {
  5950. step ("result_reping=FAILED (no notice)");
  5951. finish (1);
  5952. return;
  5953. }
  5954. engine->pingHardwareInserts (notice); // ("Ping now")
  5955. juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
  5956. if (engine == nullptr)
  5957. return;
  5958. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  5959. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  5960. const auto stale = (int) engine->staleHardwareInserts().size();
  5961. step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
  5962. const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
  5963. step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
  5964. finish (ok ? 0 : 1);
  5965. });
  5966. });
  5967. }
  5968. void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  5969. {
  5970. // the Export window as the user sees it with the real-time option ticked (next to the report)
  5971. lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
  5972. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  5973. if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
  5974. {
  5975. std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
  5976. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
  5977. return t;
  5978. for (auto* child : c.getChildren())
  5979. if (auto* t = find (*child))
  5980. return t;
  5981. return nullptr;
  5982. };
  5983. if (auto* toggle = find (*w))
  5984. {
  5985. step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
  5986. toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
  5987. auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
  5988. if (c != nullptr)
  5989. {
  5990. const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
  5991. file.deleteFile();
  5992. juce::FileOutputStream out (file);
  5993. juce::PNGImageFormat png;
  5994. if (out.openedOk())
  5995. png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  5996. }
  5997. delete w;
  5998. break;
  5999. }
  6000. }
  6001. lynx::exportopts::Options o;
  6002. o.format = lynx::exportopts::Format::wav;
  6003. o.wavBits = 32;
  6004. o.dither = lynx::exportopts::DitherMode::none;
  6005. o.tail = lynx::exportopts::TailMode::cut;
  6006. o.range = lynx::exportopts::Range::song;
  6007. o.trimPdc = true;
  6008. o.hqAllPlugins = false;
  6009. o.pluginWarmUp = false;
  6010. const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
  6011. auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
  6012. o.sampleRate = engine->getTransport().sampleRate.load();
  6013. auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
  6014. struct Shared
  6015. {
  6016. std::atomic<int> done { 0 };
  6017. bool okRealtime = false, okOffline = false;
  6018. juce::String errorRealtime, errorOffline;
  6019. double lastProgress = 0.0;
  6020. double started = juce::Time::getMillisecondCounterHiRes();
  6021. };
  6022. auto shared = std::make_shared<Shared>();
  6023. // (the jobs stay owned by the message thread's poll below: they are destroyed there)
  6024. juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
  6025. shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
  6026. shared->okOffline = off->run ({}, shared->errorOffline);
  6027. shared->done.store (1);
  6028. });
  6029. auto poll = std::make_shared<std::function<void()>>();
  6030. *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
  6031. if (shared->done.load() == 0)
  6032. {
  6033. juce::Timer::callAfterDelay (100, *poll);
  6034. return;
  6035. }
  6036. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
  6037. step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
  6038. + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
  6039. + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
  6040. juce::AudioFormatManager formats;
  6041. formats.registerBasicFormats();
  6042. std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
  6043. if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
  6044. {
  6045. step ("result=FAILED bounce");
  6046. finish (1);
  6047. return;
  6048. }
  6049. const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
  6050. juce::AudioBuffer<float> x (2, frames), y (2, frames);
  6051. a->read (&x, 0, frames, 0, true, true);
  6052. b->read (&y, 0, frames, 0, true, true);
  6053. double residual = 0.0, energy = 0.0, wetDry = 0.0;
  6054. for (int ch = 0; ch < 2; ++ch)
  6055. for (int i = 0; i < frames; ++i)
  6056. {
  6057. const double d = x.getSample (ch, i) - y.getSample (ch, i);
  6058. residual += d * d;
  6059. energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
  6060. }
  6061. for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
  6062. wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
  6063. const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
  6064. step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
  6065. + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
  6066. + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
  6067. const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
  6068. step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
  6069. finish (ok ? 0 : 1);
  6070. };
  6071. juce::Timer::callAfterDelay (100, *poll);
  6072. }
  6073. // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
  6074. // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
  6075. juce::String finishStressTake (const juce::File& target, double seconds)
  6076. {
  6077. juce::String text;
  6078. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  6079. text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
  6080. if (device != nullptr)
  6081. text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
  6082. engine->setRecording (false); // closes the take: a clip of the song
  6083. juce::File take;
  6084. for (const auto& c : engine->getSong().channels)
  6085. if (c.instrument == lynx::InstrumentKind::audioClip)
  6086. take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
  6087. if (! take.existsAsFile())
  6088. return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
  6089. target.deleteFile();
  6090. if (! take.moveFileTo (target))
  6091. take.copyFileTo (target);
  6092. juce::AudioFormatManager formats;
  6093. formats.registerBasicFormats();
  6094. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
  6095. {
  6096. juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
  6097. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
  6098. const auto peak = audio.getMagnitude (0, audio.getNumSamples());
  6099. const auto length = (double) reader->lengthInSamples / reader->sampleRate;
  6100. text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
  6101. << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
  6102. << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
  6103. }
  6104. else
  6105. text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
  6106. return text;
  6107. }
  6108. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  6109. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  6110. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  6111. {
  6112. lynx::AudioEngine offline (false);
  6113. const juce::File input (inputPath);
  6114. juce::String error, report;
  6115. bool ok = false;
  6116. if (input.hasFileExtension ("flp;als"))
  6117. ok = offline.importFlpFile (input, error);
  6118. else if (auto song = lynx::ProjectFile::load (input, error))
  6119. {
  6120. offline.setSong (std::move (*song));
  6121. ok = true;
  6122. }
  6123. int samplers = 0, samplersLoaded = 0;
  6124. if (ok)
  6125. {
  6126. for (const auto& c : offline.getSong().channels)
  6127. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  6128. {
  6129. ++samplers;
  6130. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  6131. }
  6132. const juce::File output (outputPath);
  6133. output.deleteFile();
  6134. juce::WavAudioFormat wav;
  6135. std::unique_ptr<juce::AudioFormatWriter> writer (
  6136. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  6137. if (writer == nullptr)
  6138. {
  6139. ok = false;
  6140. error = lynx::utf8 ("could not create ") + outputPath;
  6141. }
  6142. else
  6143. {
  6144. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  6145. report << "peak=" << peak << "\n";
  6146. ok = peak > 0.001f;
  6147. }
  6148. }
  6149. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  6150. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  6151. juce::File (outputPath + ".txt").replaceWithText (report);
  6152. setApplicationReturnValue (ok ? 0 : 1);
  6153. quit();
  6154. }
  6155. // LYNX.exe --export-flp project.(lynx|flp) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
  6156. // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
  6157. // report goes to output.txt
  6158. void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
  6159. {
  6160. juce::String error;
  6161. bool ok = false;
  6162. lynx::flstudio::Written written;
  6163. {
  6164. lynx::AudioEngine loader (false);
  6165. const juce::File input (inputPath);
  6166. if (input.hasFileExtension ("flp"))
  6167. ok = loader.importFlpFile (input, error);
  6168. else if (auto song = lynx::ProjectFile::load (input, error))
  6169. {
  6170. loader.setSong (std::move (*song));
  6171. ok = true;
  6172. }
  6173. if (ok)
  6174. {
  6175. const juce::File output (outputPath);
  6176. const auto zip = output.hasFileExtension ("zip");
  6177. const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
  6178. loader.capturePluginStates();
  6179. auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
  6180. // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
  6181. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
  6182. options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
  6183. const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
  6184. : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
  6185. ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
  6186. [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
  6187. const std::function<bool (double)>& progress, juce::String& err) {
  6188. lynx::ExportJob job (s, settings, wav);
  6189. return job.run (progress, err);
  6190. },
  6191. {}, written, error);
  6192. if (zip)
  6193. renderDir.deleteRecursively();
  6194. }
  6195. }
  6196. juce::String report;
  6197. report << (ok ? "ok" : "error=" + error) << "\n"
  6198. << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
  6199. << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
  6200. << " samples=" << written.samples << "\n\n"
  6201. << lynx::flstudio::reportText (written) << "\n";
  6202. juce::File (outputPath + ".txt").replaceWithText (report);
  6203. setApplicationReturnValue (ok ? 0 : 1);
  6204. quit();
  6205. }
  6206. // LYNX.exe --export project.(flp|lynx) output.(wav|flac|ogg|mp3) [--pattern] [--insert N] [--rate N]
  6207. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail.
  6208. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  6209. {
  6210. juce::String error, report;
  6211. bool ok = false;
  6212. const auto started = juce::Time::getMillisecondCounterHiRes();
  6213. lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
  6214. {
  6215. lynx::AudioEngine loader (false);
  6216. const juce::File input (inputPath);
  6217. // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
  6218. if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
  6219. {
  6220. juce::MemoryBlock data;
  6221. if (input.loadFileAsData (data))
  6222. try
  6223. {
  6224. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  6225. auto& host = loader.getPluginHost();
  6226. const auto listed = std::chrono::steady_clock::now();
  6227. const auto files = host.filesToScanFor (uses);
  6228. lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
  6229. report << "scanned=" << files.joinIntoString (";") << "\n";
  6230. const auto scanned = std::chrono::steady_clock::now();
  6231. host.scanFiles (files, {});
  6232. lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
  6233. }
  6234. catch (const flp::Error&)
  6235. {
  6236. }
  6237. }
  6238. if (input.hasFileExtension ("flp"))
  6239. ok = loader.importFlpFile (input, error);
  6240. else if (auto song = lynx::ProjectFile::load (input, error))
  6241. {
  6242. loader.setSong (std::move (*song));
  6243. ok = true;
  6244. }
  6245. if (ok)
  6246. {
  6247. const juce::File output (outputPath);
  6248. lynx::ExportSettings settings;
  6249. settings.wholeSong = ! patternOnly;
  6250. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  6251. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  6252. : lynx::ExportSettings::Format::wav24;
  6253. // --insert N: only that insert's output (what "Render to audio" records)
  6254. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  6255. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  6256. loader.editSong ([] (lynx::Song& s) {
  6257. for (auto& t : s.mixer)
  6258. t.effects.clear();
  6259. }, false);
  6260. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  6261. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  6262. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  6263. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  6264. // .mp3: the Export window's MP3 (320 kbps); everything else as before
  6265. auto options = settings.toOptions();
  6266. // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
  6267. if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
  6268. options.saveTempo = true;
  6269. // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
  6270. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
  6271. options.pluginWarmUp = false;
  6272. // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
  6273. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
  6274. if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
  6275. options.sampleRate = rate;
  6276. if (output.hasFileExtension ("mp3"))
  6277. {
  6278. options.format = lynx::exportopts::Format::mp3;
  6279. options.mp3Kbps = 320;
  6280. }
  6281. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
  6282. job.setExtraData (true);
  6283. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  6284. lynx::loadtrace::end();
  6285. int lastPercent = -1;
  6286. ok = job.run ([&lastPercent] (double p) {
  6287. lastPercent = (int) (p * 100.0);
  6288. return true;
  6289. }, error);
  6290. auto joined = [] (const std::map<std::string, int>& items) {
  6291. juce::StringArray names;
  6292. for (const auto& [name, count] : items)
  6293. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  6294. return names.joinIntoString (", ");
  6295. };
  6296. const auto& importReport = loader.getImportReport();
  6297. report << "converted=" << joined (importReport.converted) << "\n"
  6298. << "approximated=" << joined (importReport.approximated) << "\n"
  6299. << "unsupported=" << joined (importReport.unsupported) << "\n"
  6300. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  6301. << "partial_effects=" << joined (importReport.partialEffects) << "\n"
  6302. << "missing_samples=" << importReport.missingSamples << "\n";
  6303. // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
  6304. for (const auto& line : loader.getMatchedPlugins())
  6305. report << "plugin_found=" << line << "\n";
  6306. for (const auto& m : loader.getMissingPluginDetails())
  6307. report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
  6308. << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
  6309. {
  6310. const auto& song = loader.getSong();
  6311. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  6312. {
  6313. const auto& track = song.mixer[t];
  6314. if (track.effects.empty() && track.sends.empty())
  6315. continue;
  6316. report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
  6317. << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
  6318. for (const auto& s : track.sends)
  6319. report << " send>" << s.target << "@" << juce::String (s.level, 3);
  6320. report << " |";
  6321. for (const auto& fx : track.effects)
  6322. report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
  6323. : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
  6324. << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
  6325. << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
  6326. report << "\n";
  6327. }
  6328. }
  6329. report << juce::String (lynx::loadtrace::reportLines());
  6330. lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
  6331. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  6332. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  6333. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  6334. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  6335. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  6336. << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
  6337. << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
  6338. << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
  6339. << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
  6340. << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
  6341. << "song_seconds=" << job.getMusicSeconds() << "\n"
  6342. << "peak=" << job.getPeak() << "\n"
  6343. << "final_progress=" << lastPercent << "\n"
  6344. << "bytes=" << output.getSize() << "\n";
  6345. ok = ok && job.getPeak() > 0.001f;
  6346. }
  6347. }
  6348. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  6349. juce::File (outputPath + ".txt").replaceWithText (report);
  6350. setApplicationReturnValue (ok ? 0 : 1);
  6351. quit();
  6352. }
  6353. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  6354. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  6355. // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
  6356. struct EditorCpuRun final : juce::Timer
  6357. {
  6358. struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
  6359. std::vector<Case> cases;
  6360. std::size_t at = 0;
  6361. int phase = 0;
  6362. double t0 = 0.0, c0 = 0.0;
  6363. juce::String report;
  6364. juce::File out;
  6365. std::unique_ptr<lynx::AudioEngine> engine;
  6366. std::unique_ptr<juce::DocumentWindow> window;
  6367. std::function<void()> done;
  6368. void start()
  6369. {
  6370. engine = std::make_unique<lynx::AudioEngine> (false);
  6371. report << "editor\tmode\tcpu % of one core\n";
  6372. open();
  6373. startTimer (250);
  6374. }
  6375. void open()
  6376. {
  6377. window.reset();
  6378. if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
  6379. const auto& c = cases[at];
  6380. lynx::Song song;
  6381. song.mixer.resize (2);
  6382. song.mixer[0].name = "Master";
  6383. song.mixer[1].name = "Insert 1";
  6384. song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
  6385. engine->setSong (std::move (song));
  6386. engine->dispatchPendingMessages();
  6387. lynx::setNativeEditorDemo (c.demo);
  6388. auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
  6389. : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
  6390. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
  6391. window->setUsingNativeTitleBar (true);
  6392. window->setContentOwned (editor.release(), true);
  6393. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  6394. window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
  6395. window->setVisible (true);
  6396. phase = 0;
  6397. t0 = juce::Time::getMillisecondCounterHiRes();
  6398. }
  6399. void timerCallback() override
  6400. {
  6401. const auto now = juce::Time::getMillisecondCounterHiRes();
  6402. if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
  6403. if (phase == 1 && now - t0 > 8000.0)
  6404. {
  6405. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  6406. const auto& c = cases[at];
  6407. report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
  6408. ++at;
  6409. open();
  6410. }
  6411. }
  6412. };
  6413. std::unique_ptr<EditorCpuRun> editorCpu;
  6414. void runEditorCpu (const juce::String& path)
  6415. {
  6416. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6417. editorCpu = std::make_unique<EditorCpuRun>();
  6418. editorCpu->out = juce::File (path);
  6419. using K = lynx::EffectKind;
  6420. for (const auto demo : { false, true })
  6421. for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
  6422. { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
  6423. { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
  6424. { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
  6425. editorCpu->cases.push_back (c);
  6426. editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
  6427. editorCpu->start();
  6428. }
  6429. void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
  6430. {
  6431. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6432. int kindIndex = -1;
  6433. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  6434. if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
  6435. kindIndex = k;
  6436. if (kindIndex < 0)
  6437. return;
  6438. const auto kind = (lynx::EffectKind) kindIndex;
  6439. auto fx = lynx::makeEffectSlot (kind);
  6440. if (paramsFile.isNotEmpty())
  6441. for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
  6442. {
  6443. const auto t = juce::StringArray::fromTokens (line, " \t", "");
  6444. const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
  6445. if (index >= 0 && index < lynx::maxEffectParams)
  6446. fx.params[(std::size_t) index] = t[1].getFloatValue();
  6447. }
  6448. lynx::AudioEngine offline (false);
  6449. auto song = lynx::Song::makeDefault();
  6450. song.mixer.resize (2);
  6451. song.mixer[0].name = "Master";
  6452. song.mixer[1].name = "Insert 1";
  6453. song.mixer[1].effects.assign (1, fx);
  6454. for (auto& c : song.channels)
  6455. c.mixerTrack = 1;
  6456. offline.setSong (std::move (song));
  6457. offline.dispatchPendingMessages();
  6458. const bool facet = kind == lynx::EffectKind::facetEq;
  6459. // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
  6460. // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
  6461. const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
  6462. // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
  6463. const bool pro = lynx::ProEditorWindows::handles (kind)
  6464. && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
  6465. auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  6466. : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  6467. if (editor == nullptr)
  6468. return;
  6469. if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
  6470. {
  6471. lynx::AudioEngine::RenderOptions o;
  6472. o.seconds = 3.0;
  6473. o.sampleRate = 48000.0;
  6474. o.pluginWarmUp = false;
  6475. int sinceTick = 0;
  6476. o.capture = [&] (const float*, const float*, int n) {
  6477. sinceTick += n;
  6478. if (sinceTick < 1600) return;
  6479. sinceTick = 0;
  6480. if (facet) lynx::tickFacetEqEditor (*editor);
  6481. else lynx::tickNativeEffectEditor (*editor);
  6482. };
  6483. offline.renderOffline (o);
  6484. }
  6485. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  6486. {
  6487. juce::Graphics g (image);
  6488. g.fillAll (lynx::theme::panel);
  6489. editor->paintEntireComponent (g, false);
  6490. }
  6491. const juce::File file (path);
  6492. file.deleteFile();
  6493. juce::PNGImageFormat png;
  6494. if (auto stream = file.createOutputStream())
  6495. png.writeImageToStream (image, *stream);
  6496. }
  6497. void runEq166fShots (const juce::String& folder)
  6498. {
  6499. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6500. const juce::File out (folder);
  6501. out.createDirectory();
  6502. lynx::AudioEngine offline (false);
  6503. auto save = [&] (juce::Component& editor, const juce::String& name) {
  6504. juce::Image image (juce::Image::ARGB, editor.getWidth(), editor.getHeight(), true);
  6505. {
  6506. juce::Graphics g (image);
  6507. g.fillAll (lynx::theme::panel);
  6508. editor.paintEntireComponent (g, false);
  6509. }
  6510. const auto f = out.getChildFile (name);
  6511. f.deleteFile();
  6512. juce::PNGImageFormat png;
  6513. if (auto stream = f.createOutputStream())
  6514. png.writeImageToStream (image, *stream);
  6515. };
  6516. // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
  6517. auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
  6518. auto song = lynx::Song::makeDefault();
  6519. song.mixer.resize (3);
  6520. song.mixer[0].name = "Master";
  6521. song.mixer[1].name = "Vocal";
  6522. song.mixer[2].name = "Reference mix";
  6523. song.mixer[1].effects.assign (1, fx);
  6524. for (std::size_t c = 0; c < song.channels.size(); ++c)
  6525. song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
  6526. return song;
  6527. };
  6528. auto feed = [&] (juce::Component& editor, bool facet, int frames) {
  6529. // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
  6530. lynx::AudioEngine::RenderOptions o;
  6531. o.seconds = frames / 30.0;
  6532. o.sampleRate = 48000.0;
  6533. o.pluginWarmUp = false;
  6534. int sinceTick = 0;
  6535. o.capture = [&] (const float*, const float*, int n) {
  6536. sinceTick += n;
  6537. if (sinceTick < 1600) return;
  6538. sinceTick = 0;
  6539. if (facet) lynx::tickFacetEqEditor (editor);
  6540. else lynx::tickNativeEffectEditor (editor);
  6541. };
  6542. offline.renderOffline (o);
  6543. if (facet) lynx::tickFacetEqEditor (editor);
  6544. else lynx::tickNativeEffectEditor (editor);
  6545. };
  6546. // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
  6547. auto& display = lynx::peqview::displaySettings();
  6548. const auto kept = display;
  6549. display.spectrum = display.heatmap = true;
  6550. display.position = 0;
  6551. for (const auto& [gain, name] : { std::pair { 0.0, "peq2-heatmap-flat.png" }, { 12.0, "peq2-heatmap-boost.png" }, { -12.0, "peq2-heatmap-cut.png" },
  6552. { 0.0, "peq2-heatmap-top.png" } })
  6553. {
  6554. auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  6555. eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
  6556. eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
  6557. display.position = juce::String (name).contains ("top") ? 1 : 0;
  6558. offline.setSong (songWith (eq, false));
  6559. offline.dispatchPendingMessages();
  6560. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
  6561. feed (*editor, false, 120);
  6562. save (*editor, name);
  6563. }
  6564. display = kept;
  6565. // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
  6566. {
  6567. using namespace lynx::facet;
  6568. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  6569. eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
  6570. eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
  6571. eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
  6572. eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
  6573. eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
  6574. eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
  6575. eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
  6576. eq.sidechain = 2;
  6577. for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
  6578. {
  6579. eq.params[(std::size_t) listenParam] = listenValue (l);
  6580. offline.setSong (songWith (eq, true));
  6581. offline.dispatchPendingMessages();
  6582. auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
  6583. feed (*editor, true, 90);
  6584. save (*editor, name);
  6585. }
  6586. }
  6587. }
  6588. void runDesign168rShots (const juce::String& folder)
  6589. {
  6590. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6591. const juce::File out (folder);
  6592. out.createDirectory();
  6593. lynx::AudioEngine offline (false);
  6594. using K = lynx::EffectKind;
  6595. for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
  6596. K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
  6597. K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
  6598. K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
  6599. {
  6600. const auto& bank = lynx::presets::factory (kind);
  6601. // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
  6602. std::optional<lynx::EffectSlot> flPreset;
  6603. if (kind == K::lovePhilter || kind == K::distructor)
  6604. {
  6605. const auto roots = lynx::findFlStudioRoots();
  6606. const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  6607. .getChildFile ("Patches/Plugin presets/Effects")
  6608. .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
  6609. juce::MemoryBlock bytes;
  6610. if (file.loadFileAsData (bytes))
  6611. flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
  6612. (const std::uint8_t*) bytes.getData() + bytes.getSize()));
  6613. }
  6614. for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
  6615. {
  6616. auto fx = lynx::makeEffectSlot (kind);
  6617. if (pass == 1 && flPreset)
  6618. fx = *flPreset;
  6619. else if (pass == 1)
  6620. {
  6621. fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
  6622. fx.presetName = bank.front().name;
  6623. }
  6624. lynx::Song song;
  6625. song.mixer.resize (2);
  6626. song.mixer[0].name = "Master";
  6627. song.mixer[1].name = "Insert 1";
  6628. song.mixer[1].effects.push_back (fx);
  6629. offline.setSong (std::move (song));
  6630. offline.dispatchPendingMessages();
  6631. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  6632. for (const auto scale : { 1.0f, 2.0f })
  6633. for (int page = 0; page < pages; ++page)
  6634. {
  6635. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
  6636. if (editor == nullptr)
  6637. continue;
  6638. juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
  6639. {
  6640. juce::Graphics g (image);
  6641. g.fillAll (lynx::theme::panel);
  6642. editor->paintEntireComponent (g, false);
  6643. }
  6644. // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
  6645. const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
  6646. + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
  6647. + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
  6648. + (scale > 1.5f ? "-200" : "-100") + ".png");
  6649. file.deleteFile();
  6650. juce::PNGImageFormat png;
  6651. if (auto stream = file.createOutputStream())
  6652. png.writeImageToStream (image, *stream);
  6653. }
  6654. }
  6655. }
  6656. }
  6657. bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
  6658. {
  6659. folder.createDirectory();
  6660. auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
  6661. juce::StringArray wanted;
  6662. wanted.addTokens (which, ",", "");
  6663. auto ok = true;
  6664. struct Shot
  6665. {
  6666. juce::String name;
  6667. std::optional<lynx::ChannelDef> channel;
  6668. };
  6669. std::vector<Shot> shots;
  6670. for (const auto& e : lynx::natives::instrumentEngines())
  6671. {
  6672. const auto name = key (e.name);
  6673. const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
  6674. if (! banked && ! wanted.contains (name))
  6675. continue;
  6676. auto channel = source == "fl" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
  6677. : lynx::banks::defaultChannel (e.kind, e.name);
  6678. if (! channel)
  6679. {
  6680. std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
  6681. ok = false;
  6682. continue;
  6683. }
  6684. shots.push_back ({ name, std::move (channel) });
  6685. }
  6686. // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
  6687. if (wanted.contains ("autogun"))
  6688. {
  6689. if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
  6690. shots.push_back ({ "autogun", std::move (channel) });
  6691. else
  6692. {
  6693. std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
  6694. ok = false;
  6695. }
  6696. }
  6697. for (auto& shot : shots)
  6698. {
  6699. const auto& name = shot.name;
  6700. auto& channel = shot.channel;
  6701. lynx::AudioEngine offline (false);
  6702. lynx::Song song;
  6703. song.mixer = lynx::Song::defaultMixer (2);
  6704. song.channels.push_back (*channel);
  6705. song.patterns.emplace_back();
  6706. {
  6707. juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
  6708. lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
  6709. }
  6710. offline.setSong (std::move (song));
  6711. offline.dispatchPendingMessages();
  6712. auto frame = lynx::makeChannelFrame (offline, 0, 0);
  6713. if (frame == nullptr || frame->getWidth() <= 0)
  6714. {
  6715. ok = false;
  6716. continue;
  6717. }
  6718. for (const auto scale : { 1.0f, 1.5f, 2.0f })
  6719. {
  6720. const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  6721. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
  6722. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
  6723. }
  6724. // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
  6725. for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
  6726. {
  6727. lynx::showChannelLayoutPage (*frame, page);
  6728. const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
  6729. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
  6730. std::printf ("%s\n", file.getFullPathName().toRawUTF8());
  6731. }
  6732. }
  6733. return ok;
  6734. }
  6735. // --- round 170j: the pilot editors with their own art -------------------------------------------------
  6736. struct ArtPilot
  6737. {
  6738. std::string file; // the art's name as a file name: "toxic-biohazard"
  6739. bool instrument;
  6740. lynx::InstrumentKind instrumentKind;
  6741. lynx::EffectKind effectKind;
  6742. lynx::skin::Style before; // the automatic style it had before the Themed style
  6743. };
  6744. static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
  6745. {
  6746. static juce::StringArray only;
  6747. return only;
  6748. }
  6749. // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
  6750. // registries, so a new theme is shot without touching this list
  6751. static const std::vector<ArtPilot>& artPilots()
  6752. {
  6753. using I = lynx::InstrumentKind;
  6754. using E = lynx::EffectKind;
  6755. static const std::vector<ArtPilot> list = [] {
  6756. std::vector<ArtPilot> all;
  6757. auto slug = [] (lynx::skin::Art a) {
  6758. return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
  6759. };
  6760. for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
  6761. if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
  6762. all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
  6763. for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
  6764. if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
  6765. all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
  6766. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  6767. if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
  6768. all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
  6769. std::vector<ArtPilot> kept;
  6770. for (auto& p : all)
  6771. if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
  6772. if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
  6773. kept.push_back (p);
  6774. return kept;
  6775. }();
  6776. return list;
  6777. }
  6778. // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
  6779. static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
  6780. {
  6781. lynx::Song song;
  6782. song.mixer = lynx::Song::defaultMixer (2);
  6783. if (p.instrument)
  6784. {
  6785. for (const auto& e : lynx::natives::instrumentEngines())
  6786. if (e.kind == p.instrumentKind)
  6787. {
  6788. auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
  6789. if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
  6790. if (! channel) return nullptr;
  6791. song.channels.push_back (*channel);
  6792. break;
  6793. }
  6794. if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
  6795. {
  6796. const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
  6797. auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
  6798. if (! channel)
  6799. {
  6800. channel = lynx::ChannelDef {};
  6801. channel->instrument = p.instrumentKind;
  6802. channel->name = name;
  6803. }
  6804. song.channels.push_back (*channel);
  6805. }
  6806. song.patterns.emplace_back();
  6807. }
  6808. else
  6809. {
  6810. song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
  6811. }
  6812. engine.setSong (std::move (song));
  6813. engine.dispatchPendingMessages();
  6814. if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
  6815. if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
  6816. if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
  6817. return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
  6818. }
  6819. // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
  6820. static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
  6821. {
  6822. lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
  6823. lynx::skin::setArtMotion (mode != "still");
  6824. }
  6825. bool runArtShots (const juce::File& folder, bool before)
  6826. {
  6827. folder.createDirectory();
  6828. auto ok = true;
  6829. juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
  6830. for (const auto& p : artPilots())
  6831. {
  6832. artPilotStyle (p, before ? "before" : "after");
  6833. lynx::AudioEngine offline (false);
  6834. auto editor = makeArtPilot (offline, p);
  6835. if (editor == nullptr || editor->getWidth() <= 0)
  6836. {
  6837. std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
  6838. ok = false;
  6839. continue;
  6840. }
  6841. if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
  6842. // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
  6843. auto fit = [&] (const juce::String& at) {
  6844. const auto f = lynx::skin::lastTitleFit();
  6845. if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
  6846. titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
  6847. << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
  6848. };
  6849. for (const auto scale : { 1.0f, 2.0f })
  6850. {
  6851. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  6852. lynx::skin::resetTitleFit();
  6853. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
  6854. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
  6855. if (scale == 1.0f) fit ("100");
  6856. }
  6857. // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
  6858. if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
  6859. {
  6860. editor->setSize (smallest.x, smallest.y);
  6861. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
  6862. lynx::skin::resetTitleFit();
  6863. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, 1.0f), file.getFullPathName());
  6864. fit ("min");
  6865. }
  6866. }
  6867. folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
  6868. lynx::skin::setForcedStyle (-1);
  6869. return ok;
  6870. }
  6871. struct ArtGuiRun final : juce::Timer
  6872. {
  6873. juce::File folder;
  6874. juce::String mode, report;
  6875. std::size_t at = 0;
  6876. int phase = 0;
  6877. double t0 = 0.0, c0 = 0.0;
  6878. std::unique_ptr<lynx::AudioEngine> engine;
  6879. std::unique_ptr<juce::DocumentWindow> window;
  6880. std::function<void()> done;
  6881. void start()
  6882. {
  6883. engine = std::make_unique<lynx::AudioEngine> (false);
  6884. report << "editor\tmode\tcpu % of one core\tart layer animating\n";
  6885. open();
  6886. startTimer (100);
  6887. }
  6888. void open()
  6889. {
  6890. window.reset();
  6891. const auto& pilots = artPilots();
  6892. if (at >= pilots.size())
  6893. {
  6894. folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
  6895. stopTimer();
  6896. lynx::skin::setForcedStyle (-1);
  6897. lynx::skin::setArtMotion (true);
  6898. if (done) done();
  6899. return;
  6900. }
  6901. const auto& p = pilots[at];
  6902. artPilotStyle (p, mode);
  6903. auto editor = makeArtPilot (*engine, p);
  6904. if (editor == nullptr) { ++at; open(); return; }
  6905. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
  6906. window->setUsingNativeTitleBar (true);
  6907. window->setContentOwned (editor.release(), true);
  6908. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  6909. window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
  6910. window->setAlwaysOnTop (true);
  6911. window->setVisible (true);
  6912. phase = 0;
  6913. t0 = juce::Time::getMillisecondCounterHiRes();
  6914. }
  6915. bool animating() const
  6916. {
  6917. if (window == nullptr || window->getContentComponent() == nullptr) return false;
  6918. std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
  6919. if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
  6920. for (auto* child : c.getChildren())
  6921. if (find (*child)) return true;
  6922. return false;
  6923. };
  6924. return find (*window->getContentComponent());
  6925. }
  6926. void timerCallback() override
  6927. {
  6928. const auto now = juce::Time::getMillisecondCounterHiRes();
  6929. const auto& p = artPilots()[at];
  6930. const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
  6931. const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
  6932. if (phase == 0 && now - t0 > 1500.0)
  6933. {
  6934. // the window's content on screen, in physical pixels, for the outside screenshot to crop
  6935. auto* c = window->getContentComponent();
  6936. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  6937. const auto b = c->getScreenBounds();
  6938. shotDone.deleteFile();
  6939. ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
  6940. + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
  6941. phase = 1;
  6942. t0 = now;
  6943. return;
  6944. }
  6945. if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
  6946. {
  6947. ready.deleteFile();
  6948. shotDone.deleteFile();
  6949. phase = 2;
  6950. t0 = now;
  6951. c0 = lynx::processCpuSeconds();
  6952. return;
  6953. }
  6954. if (phase == 2 && now - t0 > 6000.0)
  6955. {
  6956. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  6957. report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
  6958. ++at;
  6959. open();
  6960. }
  6961. }
  6962. };
  6963. std::unique_ptr<ArtGuiRun> artGui;
  6964. void runArtGui (const juce::File& folder, const juce::String& mode)
  6965. {
  6966. folder.createDirectory();
  6967. artGui = std::make_unique<ArtGuiRun>();
  6968. artGui->folder = folder;
  6969. artGui->mode = mode;
  6970. artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
  6971. artGui->start();
  6972. }
  6973. void runPluginEditorSnapshots (const juce::String& folder)
  6974. {
  6975. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6976. {
  6977. const juce::File out (folder);
  6978. out.createDirectory();
  6979. lynx::AudioEngine offline (false);
  6980. const auto roots = lynx::findFlStudioRoots();
  6981. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  6982. auto kinds = lynx::plugui::flLayoutKinds();
  6983. kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
  6984. for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
  6985. kinds.push_back (own);
  6986. kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
  6987. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
  6988. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
  6989. kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
  6990. const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
  6991. auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
  6992. auto ridgePasses = 0;
  6993. for (const auto kind : kinds)
  6994. {
  6995. auto fx = lynx::makeEffectSlot (kind);
  6996. juce::String name (lynx::effectInfo (kind).name);
  6997. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  6998. {
  6999. const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
  7000. auto file = dir.getChildFile ("Default.fst");
  7001. if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
  7002. for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
  7003. file = f;
  7004. if (! file.existsAsFile())
  7005. {
  7006. auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
  7007. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
  7008. file = files.isEmpty() ? juce::File() : files[0];
  7009. }
  7010. juce::MemoryBlock data;
  7011. if (file.existsAsFile() && file.loadFileAsData (data))
  7012. {
  7013. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  7014. if (auto loaded = lynx::effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), 130.0); loaded && loaded->kind == kind)
  7015. fx = *loaded;
  7016. }
  7017. name = juce::String::fromUTF8 (plugin.c_str());
  7018. break;
  7019. }
  7020. if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
  7021. {
  7022. juce::MemoryBlock data;
  7023. juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
  7024. lynx::maximusfx::Blob blob;
  7025. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  7026. blob.mix = 600;
  7027. const auto* b = static_cast<const std::uint8_t*> (data.getData());
  7028. blob.state.assign (b, b + data.getSize());
  7029. fx = lynx::makeEffectSlot (kind);
  7030. fx.state = lynx::maximusfx::pack (blob);
  7031. name = "Soundgoodizer";
  7032. }
  7033. if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
  7034. {
  7035. for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
  7036. { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
  7037. { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
  7038. { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
  7039. { "Process order", 0.4783f }, { "De-esser", 1.0f } })
  7040. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  7041. name = "Ridge Strip (Vocal strip)";
  7042. }
  7043. else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
  7044. {
  7045. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
  7046. { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
  7047. { "Filter split", 1.0f }, { "Expander", 1.0f } })
  7048. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  7049. name = "Ridge Strip (E console)";
  7050. }
  7051. else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
  7052. for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
  7053. { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
  7054. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  7055. if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
  7056. {
  7057. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
  7058. { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
  7059. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  7060. name = "Compressor (RComp role)";
  7061. }
  7062. if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
  7063. fx.params[0] = 0.33f;
  7064. if (kind == lynx::EffectKind::ember)
  7065. {
  7066. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
  7067. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
  7068. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
  7069. }
  7070. if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
  7071. for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
  7072. { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
  7073. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  7074. lynx::Song song;
  7075. song.mixer.resize (2);
  7076. song.mixer[0].name = "Master";
  7077. song.mixer[1].name = "Insert 1";
  7078. song.mixer[1].effects.push_back (fx);
  7079. offline.setSong (std::move (song));
  7080. offline.dispatchPendingMessages();
  7081. if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
  7082. {
  7083. auto editor = lynx::makeProEditor (offline, 1, 0, true);
  7084. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  7085. {
  7086. juce::Graphics g (image);
  7087. editor->paintEntireComponent (g, false);
  7088. }
  7089. const auto file = out.getChildFile (name + ".png");
  7090. file.deleteFile();
  7091. juce::PNGImageFormat png;
  7092. if (auto stream = file.createOutputStream())
  7093. png.writeImageToStream (image, *stream);
  7094. continue;
  7095. }
  7096. const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  7097. for (int page = 0; page < pages; ++page)
  7098. {
  7099. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  7100. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  7101. {
  7102. juce::Graphics g (image);
  7103. g.fillAll (lynx::theme::panel);
  7104. editor->paintEntireComponent (g, false);
  7105. }
  7106. const auto file = out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png");
  7107. file.deleteFile();
  7108. juce::PNGImageFormat png;
  7109. if (auto stream = file.createOutputStream())
  7110. png.writeImageToStream (image, *stream);
  7111. }
  7112. }
  7113. // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
  7114. {
  7115. namespace ef = lynx::echosuite::echoform;
  7116. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  7117. fx.params[ef::rhythm] = 1.0f;
  7118. fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
  7119. fx.params[ef::rhythmDecay] = 0.25f;
  7120. fx.params[ef::rhythmTap1 + 2] = 0.45f;
  7121. fx.params[ef::feedback] = 0.25f;
  7122. fx.params[ef::era] = 0.5f;
  7123. for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
  7124. fx.params[(std::size_t) param] = value;
  7125. fx.params[ef::rhythmShape] = 0.5f; // swell
  7126. lynx::Song song;
  7127. song.mixer.resize (2);
  7128. song.mixer[0].name = "Master";
  7129. song.mixer[1].name = "Insert 1";
  7130. song.mixer[1].effects.push_back (fx);
  7131. offline.setSong (std::move (song));
  7132. offline.dispatchPendingMessages();
  7133. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  7134. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  7135. {
  7136. juce::Graphics g (image);
  7137. g.fillAll (lynx::theme::panel);
  7138. editor->paintEntireComponent (g, false);
  7139. }
  7140. const auto file = out.getChildFile ("Echoform-rhythm.png");
  7141. file.deleteFile();
  7142. juce::PNGImageFormat png;
  7143. if (auto stream = file.createOutputStream())
  7144. png.writeImageToStream (image, *stream);
  7145. }
  7146. // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
  7147. {
  7148. namespace ef = lynx::echosuite::echoform;
  7149. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  7150. fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
  7151. fx.params[ef::style] = ef::styleValue (ef::Style::dual);
  7152. lynx::Song song;
  7153. song.mixer.resize (2);
  7154. song.mixer[0].name = "Master";
  7155. song.mixer[1].name = "Insert 1";
  7156. song.mixer[1].effects.push_back (fx);
  7157. offline.setSong (std::move (song));
  7158. offline.dispatchPendingMessages();
  7159. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  7160. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  7161. {
  7162. juce::Graphics g (image);
  7163. g.fillAll (lynx::theme::panel);
  7164. editor->paintEntireComponent (g, false);
  7165. }
  7166. const auto file = out.getChildFile ("Echoform-voicing.png");
  7167. file.deleteFile();
  7168. juce::PNGImageFormat png;
  7169. if (auto stream = file.createOutputStream())
  7170. png.writeImageToStream (image, *stream);
  7171. }
  7172. // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
  7173. {
  7174. auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  7175. fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
  7176. fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
  7177. lynx::Song song;
  7178. song.mixer.resize (2);
  7179. song.mixer[0].name = "Master";
  7180. song.mixer[1].name = "Insert 1";
  7181. song.mixer[1].effects.push_back (fx);
  7182. offline.setSong (std::move (song));
  7183. offline.dispatchPendingMessages();
  7184. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  7185. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  7186. {
  7187. juce::Graphics g (image);
  7188. g.fillAll (lynx::theme::panel);
  7189. editor->paintEntireComponent (g, false);
  7190. }
  7191. const auto file = out.getChildFile ("Auto-pan-tweak.png");
  7192. file.deleteFile();
  7193. juce::PNGImageFormat png;
  7194. if (auto stream = file.createOutputStream())
  7195. png.writeImageToStream (image, *stream);
  7196. }
  7197. // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
  7198. {
  7199. namespace em = lynx::mixsuite::ember;
  7200. auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
  7201. fx.params[em::voicing] = 1.0f;
  7202. fx.params[em::classicDrive] = 0.35f;
  7203. lynx::Song song;
  7204. song.mixer.resize (2);
  7205. song.mixer[0].name = "Master";
  7206. song.mixer[1].name = "Insert 1";
  7207. song.mixer[1].effects.push_back (fx);
  7208. offline.setSong (std::move (song));
  7209. offline.dispatchPendingMessages();
  7210. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  7211. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  7212. {
  7213. juce::Graphics g (image);
  7214. g.fillAll (lynx::theme::panel);
  7215. editor->paintEntireComponent (g, false);
  7216. }
  7217. const auto file = out.getChildFile ("Ember Saturator-classic.png");
  7218. file.deleteFile();
  7219. juce::PNGImageFormat png;
  7220. if (auto stream = file.createOutputStream())
  7221. png.writeImageToStream (image, *stream);
  7222. }
  7223. // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
  7224. {
  7225. auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
  7226. fx.params[14] = 1.0f; // the measured plate voicing
  7227. fx.params[15] = 1.0f; // View = Plate
  7228. lynx::Song song;
  7229. song.mixer.resize (2);
  7230. song.mixer[0].name = "Master";
  7231. song.mixer[1].name = "Insert 1";
  7232. song.mixer[1].effects.push_back (fx);
  7233. offline.setSong (std::move (song));
  7234. offline.dispatchPendingMessages();
  7235. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  7236. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  7237. {
  7238. juce::Graphics g (image);
  7239. g.fillAll (lynx::theme::panel);
  7240. editor->paintEntireComponent (g, false);
  7241. }
  7242. const auto file = out.getChildFile ("Foil Plate-plate.png");
  7243. file.deleteFile();
  7244. juce::PNGImageFormat png;
  7245. if (auto stream = file.createOutputStream())
  7246. png.writeImageToStream (image, *stream);
  7247. }
  7248. // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
  7249. // and LYNX Tune (demo pitch phrase)
  7250. {
  7251. lynx::setNativeEditorDemo (true);
  7252. using namespace lynx::facet;
  7253. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7254. const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
  7255. { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
  7256. { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
  7257. };
  7258. for (int b = 0; b < 5; ++b)
  7259. {
  7260. eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
  7261. eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
  7262. eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
  7263. eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
  7264. eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
  7265. eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
  7266. }
  7267. eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
  7268. const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
  7269. lynx::Song song;
  7270. song.mixer.resize (2);
  7271. song.mixer[0].name = "Master";
  7272. song.mixer[1].name = "Vocal";
  7273. song.mixer[1].effects.push_back (fx);
  7274. offline.setSong (std::move (song));
  7275. offline.dispatchPendingMessages();
  7276. auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
  7277. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  7278. {
  7279. juce::Graphics g (image);
  7280. g.fillAll (lynx::theme::panel);
  7281. editor->paintEntireComponent (g, false);
  7282. }
  7283. const auto f = out.getChildFile (file);
  7284. f.deleteFile();
  7285. juce::PNGImageFormat png;
  7286. if (auto stream = f.createOutputStream())
  7287. png.writeImageToStream (image, *stream);
  7288. };
  7289. own (eq, "Facet EQ.png", true);
  7290. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
  7291. {
  7292. // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
  7293. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  7294. tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
  7295. tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
  7296. tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
  7297. // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
  7298. tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
  7299. tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
  7300. tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
  7301. tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
  7302. tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
  7303. tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
  7304. own (tune, "LYNX Tune-p2.png", false, 1);
  7305. }
  7306. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
  7307. lynx::setNativeEditorDemo (false);
  7308. }
  7309. // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
  7310. const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
  7311. 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" } })
  7312. {
  7313. juce::MemoryBlock data;
  7314. if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
  7315. {
  7316. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  7317. files.sort();
  7318. for (const auto& f : files)
  7319. {
  7320. juce::MemoryBlock block;
  7321. if (! f.loadFileAsData (block))
  7322. continue;
  7323. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  7324. try
  7325. {
  7326. const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
  7327. if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
  7328. {
  7329. preset = nullptr;
  7330. data = block;
  7331. break;
  7332. }
  7333. }
  7334. catch (const std::exception&)
  7335. {
  7336. }
  7337. }
  7338. }
  7339. auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
  7340. : generators.getChildFile (folder).getChildFile (preset);
  7341. if (! file.existsAsFile())
  7342. {
  7343. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  7344. files.sort();
  7345. file = files.isEmpty() ? juce::File() : files[0];
  7346. }
  7347. if (data.isEmpty() && ! file.loadFileAsData (data))
  7348. continue;
  7349. try
  7350. {
  7351. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  7352. auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
  7353. if (project.channels.empty())
  7354. continue;
  7355. project.channels.front().type = flp::ChannelType::native;
  7356. lynx::FlpImportOptions options;
  7357. options.roots = roots;
  7358. options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
  7359. options.readFile = [] (const std::string& path) {
  7360. juce::MemoryBlock block;
  7361. lynx::platform::localFile (path).loadFileAsData (block);
  7362. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  7363. return std::vector<std::uint8_t> (b, b + block.getSize());
  7364. };
  7365. options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  7366. const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
  7367. f.getParentDirectory().createDirectory();
  7368. f.replaceWithData (wav.data(), wav.size());
  7369. return f.getFullPathName().toStdString();
  7370. };
  7371. auto song = lynx::importFlp (project, options);
  7372. // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
  7373. if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
  7374. {
  7375. song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
  7376. song.channels.front().modelParams.assign (3, 32768.0f);
  7377. }
  7378. if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
  7379. {
  7380. song.channels.front().instrument = lynx::InstrumentKind::flkeys;
  7381. song.channels.front().pluginState = project.channels.front().pluginState;
  7382. }
  7383. offline.setSong (std::move (song));
  7384. offline.dispatchPendingMessages();
  7385. if (offline.getSong().channels.empty())
  7386. continue;
  7387. auto panel = lynx::makeChannelSettingsPanel (offline, 0);
  7388. juce::Image image (juce::Image::ARGB, panel->getWidth(), panel->getHeight(), true);
  7389. {
  7390. juce::Graphics g (image);
  7391. g.fillAll (lynx::theme::panel);
  7392. panel->paintEntireComponent (g, false);
  7393. }
  7394. const auto out2 = out.getChildFile (juce::String (folder) + ".png");
  7395. out2.deleteFile();
  7396. juce::PNGImageFormat png;
  7397. if (auto stream = out2.createOutputStream())
  7398. png.writeImageToStream (image, *stream);
  7399. }
  7400. catch (const std::exception&)
  7401. {
  7402. }
  7403. }
  7404. }
  7405. quit();
  7406. }
  7407. void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
  7408. {
  7409. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7410. // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
  7411. struct VideoShot final : juce::Timer
  7412. {
  7413. lynx::AudioEngine offline { false };
  7414. std::unique_ptr<juce::Component> editor;
  7415. juce::String prefix, report;
  7416. int step = 0;
  7417. std::function<void()> done;
  7418. void moveTo (double seconds)
  7419. {
  7420. offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
  7421. }
  7422. void timerCallback() override
  7423. {
  7424. static constexpr double times[] = { 0.0, 1.5, 3.25 };
  7425. if (step > 0 && editor != nullptr)
  7426. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + juce::String (step - 1) + ".png");
  7427. if (editor == nullptr || step >= (int) std::size (times))
  7428. {
  7429. stopTimer();
  7430. juce::File (prefix + "-report.txt").replaceWithText (report);
  7431. if (done)
  7432. done();
  7433. return;
  7434. }
  7435. moveTo (times[step++]);
  7436. }
  7437. };
  7438. static std::unique_ptr<VideoShot> shot;
  7439. shot = std::make_unique<VideoShot>();
  7440. shot->prefix = prefix;
  7441. auto& offline = shot->offline;
  7442. lynx::videoview::install (offline);
  7443. lynx::Song song;
  7444. song.mixer = lynx::Song::defaultMixer (2);
  7445. lynx::ChannelDef c;
  7446. c.name = "Fruity Video Player";
  7447. c.instrument = lynx::InstrumentKind::videoplayer;
  7448. lynx::video::Settings vs;
  7449. vs.path = juce::File (videoPath).getFullPathName().toStdString();
  7450. vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
  7451. c.pluginState = lynx::video::write (vs);
  7452. song.channels.push_back (c);
  7453. song.patterns.emplace_back();
  7454. offline.setSong (std::move (song));
  7455. offline.dispatchPendingMessages();
  7456. auto& report = shot->report;
  7457. report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
  7458. report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
  7459. shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
  7460. if (shot->editor != nullptr)
  7461. shot->editor->setVisible (true);
  7462. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  7463. shot->startTimer (1500);
  7464. }
  7465. void runDanceShot (const juce::String& prefix)
  7466. {
  7467. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7468. // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
  7469. {
  7470. constexpr int cell = 120, cols = 8;
  7471. juce::Image sheet (juce::Image::ARGB, 130 + cols * cell, lynx::dance::moveCount * cell + 10, true);
  7472. juce::Graphics g (sheet);
  7473. g.fillAll (lynx::theme::colour::bg0);
  7474. for (int m = 0; m < lynx::dance::moveCount; ++m)
  7475. {
  7476. g.setColour (lynx::theme::colour::textSecondary);
  7477. g.setFont (14.0f);
  7478. g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
  7479. for (int k = 0; k < cols; ++k)
  7480. {
  7481. const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
  7482. lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
  7483. }
  7484. }
  7485. savePng (sheet, prefix + "-moves.png");
  7486. }
  7487. lynx::AudioEngine offline (false);
  7488. lynx::Song song;
  7489. song.mixer = lynx::Song::defaultMixer (2);
  7490. for (int d = 0; d < 2; ++d)
  7491. {
  7492. lynx::ChannelDef c;
  7493. c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
  7494. c.instrument = lynx::InstrumentKind::fruitydance;
  7495. lynx::dance::Settings s;
  7496. s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
  7497. s.x = d == 0 ? 520 : 760;
  7498. s.y = 560;
  7499. s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
  7500. s.mirrored = d == 1;
  7501. c.pluginState = lynx::dance::toState (s);
  7502. song.channels.push_back (c);
  7503. }
  7504. song.patterns.emplace_back();
  7505. {
  7506. const juce::File demo (prefix + "-demo.lynx");
  7507. juce::String error;
  7508. lynx::ProjectFile::save (song, demo, error);
  7509. }
  7510. offline.setSong (std::move (song));
  7511. offline.dispatchPendingMessages();
  7512. if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
  7513. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
  7514. if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
  7515. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-frame.png");
  7516. }
  7517. void runControllerShot (const juce::String& prefix)
  7518. {
  7519. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7520. lynx::AudioEngine offline (false);
  7521. lynx::Song song;
  7522. song.mixer = lynx::Song::defaultMixer (2);
  7523. song.mixer[1].name = "Insert 1";
  7524. auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
  7525. lynx::formula::State formula;
  7526. formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
  7527. fx.state = lynx::formula::writeState (formula);
  7528. fx.params[0] = 0.5f;
  7529. fx.params[1] = 0.25f;
  7530. fx.params[2] = 0.5f;
  7531. song.mixer[1].effects.push_back (fx);
  7532. // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
  7533. {
  7534. auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
  7535. xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
  7536. xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
  7537. xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
  7538. song.mixer[1].effects.push_back (xyFx);
  7539. auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
  7540. xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
  7541. song.mixer[1].effects.push_back (xyzFx);
  7542. // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
  7543. xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
  7544. xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
  7545. xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
  7546. xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
  7547. song.mixer[1].effects.push_back (xyzFx);
  7548. auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
  7549. lynx::SurfaceControl c;
  7550. for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
  7551. { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
  7552. { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
  7553. { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
  7554. { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
  7555. { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
  7556. { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
  7557. {
  7558. c.kind = kind;
  7559. c.name = name;
  7560. c.value = v;
  7561. c.valueY = 0.6f;
  7562. c.x = x;
  7563. c.y = y;
  7564. lynx::surface::add (panel, c);
  7565. }
  7566. song.mixer[1].effects.push_back (panel);
  7567. }
  7568. lynx::ChannelDef env;
  7569. env.name = "Envelope Controller";
  7570. env.instrument = lynx::InstrumentKind::controller;
  7571. auto ecData = lynx::defaultEnvelopeController();
  7572. ecData[0].lfoOn = true;
  7573. ecData[0].lfoTempo = true;
  7574. ecData[0].lfoSpeed = 40898;
  7575. ecData[0].maps[lynx::mapKeyboard].count = 2;
  7576. ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  7577. ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  7578. ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
  7579. env.controllerState = lynx::writeEnvelopeController (ecData);
  7580. song.channels.push_back (env);
  7581. lynx::ChannelDef out;
  7582. out.name = "MIDI Out";
  7583. out.instrument = lynx::InstrumentKind::midiOut;
  7584. lynx::midictl::MidiOutSettings settings;
  7585. settings.port = 1;
  7586. lynx::midictl::writeMidiOut (out.pluginState, settings);
  7587. song.channels.push_back (out);
  7588. // a Layer (round 164) over three synths split across the keyboard, crossfading
  7589. for (const auto* name : { "Bass", "Pad", "Lead" })
  7590. {
  7591. lynx::ChannelDef c;
  7592. c.name = name;
  7593. c.instrument = lynx::InstrumentKind::synth;
  7594. song.channels.push_back (c);
  7595. }
  7596. {
  7597. lynx::ChannelDef layer;
  7598. layer.name = "Layer";
  7599. layer.instrument = lynx::InstrumentKind::layer;
  7600. song.channels.push_back (layer);
  7601. const auto self = (int) song.channels.size() - 1;
  7602. lynx::layer::setChildren (song, self, { 2, 3, 4 });
  7603. song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
  7604. song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
  7605. song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
  7606. song.channels[(std::size_t) self].layer.crossfade = true;
  7607. song.channels[(std::size_t) self].layer.fade = 0.35f;
  7608. }
  7609. {
  7610. lynx::ChannelDef dash; // channel 6
  7611. dash.name = "Dashboard";
  7612. dash.instrument = lynx::InstrumentKind::dashboard;
  7613. dash.patcher.surface = lynx::surface::starterControls();
  7614. song.channels.push_back (dash);
  7615. }
  7616. {
  7617. lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
  7618. volt.name = "Voltage Controller";
  7619. volt.instrument = lynx::InstrumentKind::voltage;
  7620. lynx::voltage::Settings v;
  7621. v.enabled = true;
  7622. v.params[9] = 49152;
  7623. v.unipolar[2] = true;
  7624. v.tracks = { 3, 0, 0 };
  7625. v.source[6] = lynx::voltage::Source::clock;
  7626. volt.pluginState = lynx::voltage::write (v);
  7627. song.channels.push_back (volt);
  7628. }
  7629. song.patterns.emplace_back();
  7630. offline.setSong (std::move (song));
  7631. offline.dispatchPendingMessages();
  7632. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  7633. if (c == nullptr)
  7634. return;
  7635. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
  7636. };
  7637. shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
  7638. shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
  7639. shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
  7640. shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
  7641. {
  7642. const auto slotOf = [] (int k) -> lynx::SlotLocator {
  7643. return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
  7644. };
  7645. const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
  7646. shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
  7647. shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
  7648. shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
  7649. shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
  7650. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
  7651. shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
  7652. }
  7653. // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
  7654. if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
  7655. for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
  7656. {
  7657. juce::MemoryBlock bytes;
  7658. if (! file.loadFileAsData (bytes))
  7659. continue;
  7660. const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
  7661. const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
  7662. if (! dash || dash->controls.empty())
  7663. continue;
  7664. offline.editSong ([&] (lynx::Song& s) {
  7665. s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
  7666. s.channels[6].patcher.surface = dash->controls;
  7667. s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
  7668. });
  7669. offline.dispatchPendingMessages();
  7670. const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
  7671. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
  7672. // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
  7673. if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
  7674. {
  7675. std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
  7676. for (auto* child : c.getChildren())
  7677. {
  7678. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
  7679. b->setToggleState (true, juce::sendNotificationSync);
  7680. pressEdit (*child);
  7681. }
  7682. };
  7683. pressEdit (*panel);
  7684. shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
  7685. }
  7686. }
  7687. // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
  7688. if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
  7689. for (int part = 0; part < 7; ++part)
  7690. {
  7691. for (auto* child : ec->getChildren())
  7692. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  7693. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  7694. savePng (ec->createComponentSnapshot (ec->getLocalBounds()), prefix + "-ec-part" + juce::String (part) + ".png");
  7695. }
  7696. lynx::FormulaControllerWindows::open (offline, 1, 0);
  7697. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  7698. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  7699. if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
  7700. savePng (w->getContentComponent()->createComponentSnapshot (w->getContentComponent()->getLocalBounds()), prefix + "-formula-controller.png");
  7701. lynx::FormulaControllerWindows::closeAll();
  7702. }
  7703. void runEdisonShot (const juce::String& prefix, const juce::String& file)
  7704. {
  7705. namespace ae = lynx::audioedit;
  7706. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7707. lynx::AudioEngine offline (false);
  7708. ae::Document d;
  7709. if (file.isNotEmpty())
  7710. {
  7711. juce::MemoryBlock bytes;
  7712. if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
  7713. {
  7714. std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
  7715. return;
  7716. }
  7717. }
  7718. else
  7719. {
  7720. // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
  7721. d.title = "Drum loop";
  7722. d.audio.sampleRate = 44100.0;
  7723. const auto frames = (std::size_t) (44100 * 2);
  7724. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  7725. std::uint32_t seed = 7;
  7726. for (std::size_t i = 0; i < frames; ++i)
  7727. {
  7728. seed = seed * 1664525u + 1013904223u;
  7729. const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
  7730. const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
  7731. d.audio.channels[0][i] = hiss + hum;
  7732. d.audio.channels[1][i] = hiss * 0.9f + hum;
  7733. }
  7734. for (int hit = 0; hit < 8; ++hit)
  7735. {
  7736. const auto at = (std::size_t) hit * frames / 8;
  7737. const auto kick = hit % 2 == 0;
  7738. double phase = 0.0;
  7739. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  7740. {
  7741. seed = seed * 1664525u + 1013904223u;
  7742. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  7743. const auto t = (double) i / 44100.0;
  7744. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  7745. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  7746. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  7747. d.audio.channels[0][at + i] += v;
  7748. d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
  7749. }
  7750. }
  7751. for (int hit = 1; hit < 8; ++hit)
  7752. ae::addMarker (d, (std::int64_t) (hit * frames / 8));
  7753. ae::setLoop (d, { 0, (std::int64_t) frames });
  7754. }
  7755. // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
  7756. d.volumeEnvelope.points = { { 0.0, 0.0, 0.0f }, { 0.12, 0.5, 0.4f }, { 0.55, 0.5, 0.0f }, { 0.62, 0.25, 0.0f }, { 0.7, 0.5, 0.0f }, { 1.0, 0.5, 0.0f } };
  7757. auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
  7758. auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
  7759. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  7760. {
  7761. juce::Graphics g (image);
  7762. g.fillAll (lynx::theme::panel);
  7763. c.paintEntireComponent (g, false);
  7764. }
  7765. savePng (image, prefix + name);
  7766. };
  7767. editor->setSize (1120, 600);
  7768. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
  7769. shot (*editor, "-editor-volume-envelope.png");
  7770. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
  7771. juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  7772. for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
  7773. {
  7774. const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
  7775. if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
  7776. {
  7777. offline.dispatchPendingMessages();
  7778. const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
  7779. shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
  7780. if (envelopeTool)
  7781. shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
  7782. panel.reset(); // (puts the envelope back)
  7783. }
  7784. }
  7785. }
  7786. static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
  7787. {
  7788. if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
  7789. return b;
  7790. for (auto* child : root.getChildren())
  7791. if (auto* b = findButton (*child, text))
  7792. return b;
  7793. return nullptr;
  7794. }
  7795. // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
  7796. void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
  7797. {
  7798. const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
  7799. for (const auto& [tab, file] : tabs)
  7800. if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
  7801. {
  7802. b->onClick();
  7803. savePng (panel.createComponentSnapshot (panel.getLocalBounds()), name + "-tab-" + file + ".png");
  7804. }
  7805. engine.editSong ([&] (lynx::Song& s) {
  7806. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  7807. auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
  7808. settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
  7809. " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
  7810. st.fl = lynx::vfx::writeScript (settings);
  7811. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  7812. });
  7813. engine.dispatchPendingMessages();
  7814. if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
  7815. {
  7816. engine.dispatchPendingMessages();
  7817. if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
  7818. b->onClick();
  7819. savePng (broken->createComponentSnapshot (broken->getLocalBounds()), name + "-error.png");
  7820. }
  7821. }
  7822. void runVfxShot (const juce::String& prefix)
  7823. {
  7824. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7825. lynx::AudioEngine offline (false);
  7826. lynx::MainComponent ui (offline, false);
  7827. ui.setSize (1280, 720);
  7828. auto song = lynx::Song::makeDefault();
  7829. song.channels.clear();
  7830. for (const auto kind : lynx::vfx::allKinds)
  7831. {
  7832. lynx::ChannelDef c;
  7833. lynx::vfx::makeChannel (c, kind);
  7834. if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
  7835. for (const auto& p : lynx::vfx::builtInPresets (kind))
  7836. if (p.name == "Major triad")
  7837. {
  7838. auto st = *lynx::vfx::readState (c.pluginState);
  7839. st.fl = p.fl;
  7840. c.pluginState = lynx::vfx::writeState (st);
  7841. }
  7842. song.channels.push_back (c);
  7843. }
  7844. // a Patcher: its notes through a Color Mapper to three synths
  7845. lynx::ChannelDef patcher;
  7846. patcher.name = "Patcher";
  7847. patcher.instrument = lynx::InstrumentKind::patcher;
  7848. lynx::PatchNode mapper;
  7849. mapper.generator = true;
  7850. lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
  7851. mapper.x = 260.0f;
  7852. patcher.patcher.nodes.push_back (mapper);
  7853. lynx::PatchWire notes;
  7854. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  7855. patcher.patcher.wires.push_back (notes);
  7856. for (int k = 0; k < 3; ++k)
  7857. {
  7858. lynx::PatchNode synth;
  7859. synth.generator = true;
  7860. synth.channel.instrument = lynx::InstrumentKind::synth;
  7861. synth.channel.name = "Synth " + std::to_string (k + 1);
  7862. synth.x = 520.0f, synth.y = (float) k * 90.0f;
  7863. patcher.patcher.nodes.push_back (synth);
  7864. lynx::PatchWire in, out;
  7865. in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
  7866. out.from = 1 + k, out.to = lynx::patchToHost;
  7867. patcher.patcher.wires.push_back (in);
  7868. patcher.patcher.wires.push_back (out);
  7869. }
  7870. patcher.patcher.outputX = 760.0f;
  7871. song.channels.push_back (patcher);
  7872. offline.setSong (std::move (song));
  7873. offline.dispatchPendingMessages();
  7874. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  7875. if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
  7876. {
  7877. offline.dispatchPendingMessages();
  7878. savePng (panel->createComponentSnapshot (panel->getLocalBounds()),
  7879. prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
  7880. }
  7881. // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
  7882. // a Script with FL's "Snap To Scale"
  7883. if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
  7884. {
  7885. const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
  7886. const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
  7887. { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
  7888. { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
  7889. };
  7890. for (const auto& [kind, path] : extra)
  7891. {
  7892. juce::MemoryBlock bytes;
  7893. if (! data.getChildFile (path).loadFileAsData (bytes))
  7894. continue;
  7895. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  7896. const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
  7897. int index = -1;
  7898. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  7899. if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
  7900. index = c;
  7901. if (! fl || index < 0)
  7902. continue;
  7903. offline.editSong ([&] (lynx::Song& s) {
  7904. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  7905. st.fl = *fl;
  7906. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  7907. });
  7908. offline.dispatchPendingMessages();
  7909. if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
  7910. {
  7911. offline.dispatchPendingMessages();
  7912. const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
  7913. savePng (panel->createComponentSnapshot (panel->getLocalBounds()), name + "-fl.png");
  7914. if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
  7915. shootScriptTabs (*panel, offline, index, name);
  7916. }
  7917. }
  7918. }
  7919. lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
  7920. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  7921. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  7922. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  7923. {
  7924. auto* content = w->getContentComponent();
  7925. savePng (content->createComponentSnapshot (content->getLocalBounds()), prefix + "-patcher.png");
  7926. delete w;
  7927. break;
  7928. }
  7929. lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
  7930. savePng (image, prefix + "-patcher-menu-" + name + ".png");
  7931. });
  7932. // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
  7933. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
  7934. {
  7935. const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
  7936. offline.getPluginHost().setPluginName (key, "1_EQ");
  7937. offline.editSong ([] (lynx::Song& s) {
  7938. if (s.mixer.size() > 1)
  7939. {
  7940. lynx::EffectSlot slot;
  7941. slot.kind = lynx::EffectKind::parametricEq;
  7942. s.mixer[1].effects.push_back (slot);
  7943. }
  7944. });
  7945. offline.dispatchPendingMessages();
  7946. {
  7947. lynx::QuickAddTargets targets;
  7948. targets.addInstrument = [] (lynx::ChannelDef) {};
  7949. targets.addEffect = [] (lynx::EffectSlot) {};
  7950. auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
  7951. savePng (palette->createComponentSnapshot (palette->getLocalBounds()), prefix + "-quickadd-renamed.png");
  7952. }
  7953. ui.selectTabForSnapshot (3);
  7954. ui.getMixerForSnapshot().selectTrack (1);
  7955. offline.dispatchPendingMessages();
  7956. savePng (ui.createComponentSnapshot (ui.getLocalBounds()), prefix + "-mixer-renamed.png");
  7957. offline.getPluginHost().setPluginName (key, "");
  7958. }
  7959. }
  7960. void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
  7961. {
  7962. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7963. lynx::AudioEngine offline (false);
  7964. {
  7965. lynx::MainComponent ui (offline, false);
  7966. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  7967. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  7968. if (projectPath.isNotEmpty())
  7969. ui.openFile (juce::File (projectPath));
  7970. offline.dispatchPendingMessages();
  7971. ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
  7972. offline.dispatchPendingMessages();
  7973. // the scale the pattern's notes fit best (major / minor, any root)
  7974. const auto& song = offline.getSong();
  7975. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  7976. int bestRoot = 0, bestScale = 1, bestHits = -1;
  7977. for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
  7978. {
  7979. const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
  7980. if (name != "Major" && name != "Minor")
  7981. continue;
  7982. for (int root = 0; root < 12; ++root)
  7983. {
  7984. int hits = 0;
  7985. for (const auto& n : notes)
  7986. hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
  7987. if (hits > bestHits)
  7988. bestHits = hits, bestRoot = root, bestScale = sc;
  7989. }
  7990. }
  7991. auto& roll = ui.getPianoRollForSnapshot();
  7992. roll.setScaleForSnapshot (bestRoot, bestScale);
  7993. roll.scrollToNotes();
  7994. offline.dispatchPendingMessages();
  7995. saveSnapshot (ui, prefix + "-pr-scale.png");
  7996. roll.setFoldToScale (true);
  7997. offline.dispatchPendingMessages();
  7998. saveSnapshot (ui, prefix + "-pr-folded.png");
  7999. roll.setFoldToScale (false);
  8000. // ghost channels: only the first other channel with notes stays a ghost
  8001. const auto selected = offline.getSelectedChannel();
  8002. int keep = -1;
  8003. for (const auto& n : notes)
  8004. if (n.channel != selected && keep < 0)
  8005. keep = n.channel;
  8006. offline.editSong ([keep] (lynx::Song& s) {
  8007. for (int c = 0; c < (int) s.channels.size(); ++c)
  8008. s.channels[(std::size_t) c].ghostHidden = c != keep;
  8009. }, false);
  8010. offline.dispatchPendingMessages();
  8011. saveSnapshot (ui, prefix + "-pr-ghost-one.png");
  8012. saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
  8013. offline.editSong ([] (lynx::Song& s) {
  8014. for (auto& c : s.channels)
  8015. c.ghostHidden = false;
  8016. }, false);
  8017. // the Mixer at 500 inserts
  8018. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  8019. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
  8020. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  8021. offline.dispatchPendingMessages();
  8022. ui.selectTabForSnapshot (3);
  8023. offline.dispatchPendingMessages();
  8024. auto& mixer = ui.getMixerForSnapshot();
  8025. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  8026. saveSnapshot (ui, prefix + "-mixer500-start.png");
  8027. const auto t3 = juce::Time::getMillisecondCounterHiRes();
  8028. mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
  8029. offline.dispatchPendingMessages();
  8030. saveSnapshot (ui, prefix + "-mixer500-end.png");
  8031. juce::File (prefix + "-mixer500.txt")
  8032. .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
  8033. + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
  8034. }
  8035. }
  8036. void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
  8037. {
  8038. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8039. lynx::AudioEngine offline (false);
  8040. {
  8041. lynx::MainComponent ui (offline, false);
  8042. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  8043. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  8044. if (projectPath.isNotEmpty())
  8045. ui.openFile (juce::File (projectPath));
  8046. offline.dispatchPendingMessages();
  8047. // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
  8048. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
  8049. offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
  8050. offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
  8051. offline.dispatchPendingMessages();
  8052. // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
  8053. // and on every other one the next clip waiting for its sync point
  8054. const auto& song = offline.getSong();
  8055. auto& live = offline.performanceStateForSnapshot();
  8056. const auto zone = lynx::perf::zoneClips (song);
  8057. int lastTrack = -1, launched = 0;
  8058. for (const auto index : zone)
  8059. {
  8060. const auto& c = song.playlist[(std::size_t) index];
  8061. if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
  8062. continue;
  8063. lastTrack = c.track;
  8064. std::int64_t clips[64];
  8065. const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
  8066. auto& view = live.tracks[(std::size_t) c.track];
  8067. view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
  8068. view.progress.store (0.2f + 0.15f * (float) (launched % 5));
  8069. if (launched % 2 == 1 && n > 1)
  8070. view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
  8071. ++launched;
  8072. }
  8073. live.anyPlaying.store (launched > 0);
  8074. ui.selectTabForSnapshot (2);
  8075. offline.dispatchPendingMessages();
  8076. auto& playlist = ui.getPlaylistForSnapshot();
  8077. savePng (playlist.createComponentSnapshot (playlist.getLocalBounds()), prefix + "-playlist-song.png");
  8078. playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
  8079. offline.dispatchPendingMessages();
  8080. saveSnapshot (ui, prefix + "-playlist.png");
  8081. savePng (playlist.createComponentSnapshot (playlist.getLocalBounds()), prefix + "-playlist-only.png");
  8082. // patcherize: the first insert with effects (all of them) and the first channel that can be
  8083. auto patched = offline.getSong();
  8084. for (int t = 0; t < (int) patched.mixer.size(); ++t)
  8085. if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
  8086. {
  8087. lynx::patcherize::patcherizeSlots (patched, t, 0, true);
  8088. break;
  8089. }
  8090. for (int c = 0; c < (int) patched.channels.size(); ++c)
  8091. if (lynx::patcherize::patcherizeChannel (patched, c))
  8092. break;
  8093. juce::String error;
  8094. lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
  8095. }
  8096. }
  8097. void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
  8098. {
  8099. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8100. lynx::AudioEngine offline (false);
  8101. {
  8102. lynx::MainComponent ui (offline, false);
  8103. ui.setSize (1280, 720);
  8104. if (projectPath.isNotEmpty())
  8105. ui.openFile (juce::File (projectPath));
  8106. else
  8107. {
  8108. auto song = lynx::Song::makeDefault();
  8109. song.mixer.resize (4);
  8110. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  8111. slot.patcher.wires.clear();
  8112. for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
  8113. { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
  8114. {
  8115. lynx::PatchNode n;
  8116. n.effect = lynx::makeEffectSlot (kind);
  8117. n.x = x;
  8118. n.y = y;
  8119. slot.patcher.nodes.push_back (n);
  8120. }
  8121. { // round 165c: a Hardware Insert node (its editor opens from the node)
  8122. lynx::PatchNode n;
  8123. n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  8124. n.x = 420.0f, n.y = 260.0f;
  8125. slot.patcher.nodes.push_back (n);
  8126. }
  8127. auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
  8128. lynx::PatchWire w;
  8129. w.kind = kind;
  8130. w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
  8131. slot.patcher.wires.push_back (w);
  8132. };
  8133. wire (lynx::patchFromHost, 0, 0, 0);
  8134. wire (0, 1, 1, 0);
  8135. wire (0, 3, 2, 0, 0.5f);
  8136. wire (1, 0, lynx::patchToHost, 0);
  8137. wire (2, 0, lynx::patchToHost, 0);
  8138. wire (lynx::patchFromHost, 1, 3, 0);
  8139. wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  8140. wire (0, 2, lynx::patchToHost, 1, 0.7f);
  8141. // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
  8142. // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
  8143. {
  8144. lynx::SurfaceControl knob;
  8145. knob.name = "Knob 1";
  8146. knob.value = 0.6f;
  8147. slot.patcher.surface = { knob };
  8148. slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
  8149. lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
  8150. lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
  8151. lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
  8152. wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
  8153. wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  8154. }
  8155. slot.patcher.outputTracks = { 3 };
  8156. slot.patcher.inputX = -20.0f;
  8157. slot.patcher.outputX = 660.0f;
  8158. song.mixer[1].effects = { slot };
  8159. lynx::ChannelDef ch;
  8160. ch.name = "Patcher";
  8161. ch.instrument = lynx::InstrumentKind::patcher;
  8162. lynx::PatchNode synth, chorus;
  8163. synth.generator = true;
  8164. synth.channel.instrument = lynx::InstrumentKind::synth;
  8165. synth.channel.name = "Synth";
  8166. synth.x = 220.0f;
  8167. chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
  8168. chorus.x = 420.0f;
  8169. // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
  8170. // on the notes moving the chorus
  8171. lynx::PatchNode midiOut, envelope;
  8172. midiOut.generator = envelope.generator = true;
  8173. midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
  8174. midiOut.channel.name = "MIDI Out";
  8175. lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
  8176. midiOut.x = 220.0f, midiOut.y = 160.0f;
  8177. envelope.channel.instrument = lynx::InstrumentKind::controller;
  8178. envelope.channel.name = "Envelope Controller";
  8179. envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  8180. envelope.x = 220.0f, envelope.y = 260.0f;
  8181. lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
  8182. osc.generator = true;
  8183. osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  8184. osc.channel.instrument = lynx::InstrumentKind::threeosc;
  8185. osc.channel.name = "3x Osc";
  8186. osc.x = 420.0f, osc.y = 260.0f;
  8187. // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
  8188. lynx::PatchNode keys, soundfont, granulizer, dashboard;
  8189. keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
  8190. keys.channel.instrument = lynx::InstrumentKind::controller;
  8191. keys.channel.name = "Keyboard Controller";
  8192. {
  8193. lynx::KeyboardControllerData ramp;
  8194. for (std::size_t k = 0; k < ramp.keys.size(); ++k)
  8195. ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
  8196. lynx::writeKeyboardController (ramp, keys.channel.controllerState);
  8197. }
  8198. soundfont.channel = lynx::sf::makeChannel();
  8199. granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  8200. granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
  8201. granulizer.channel.name = "Fruity Granulizer";
  8202. dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
  8203. dashboard.channel.name = "Dashboard";
  8204. dashboard.channel.patcher.surface = lynx::surface::starterControls();
  8205. keys.x = 20.0f, keys.y = 440.0f;
  8206. soundfont.x = 220.0f, soundfont.y = 440.0f;
  8207. granulizer.x = 420.0f, granulizer.y = 440.0f;
  8208. dashboard.x = 20.0f, dashboard.y = 540.0f;
  8209. // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
  8210. lynx::PatchNode layerNode;
  8211. layerNode.generator = true;
  8212. layerNode.channel.instrument = lynx::InstrumentKind::layer;
  8213. layerNode.channel.name = "Layer";
  8214. layerNode.channel.layer.crossfade = true;
  8215. layerNode.channel.layer.fade = 0.35f;
  8216. layerNode.x = 220.0f, layerNode.y = 540.0f;
  8217. ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
  8218. lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
  8219. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  8220. a.from = 0, a.to = 1;
  8221. b.from = 1;
  8222. portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
  8223. portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
  8224. envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
  8225. envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
  8226. lynx::PatchWire oscNotes, oscOut;
  8227. oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
  8228. oscOut.from = 4;
  8229. lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
  8230. layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
  8231. layerNotes.to = 9;
  8232. layerToFont.from = 9, layerToFont.to = 6;
  8233. layerToGrains.from = 9, layerToGrains.to = 7;
  8234. fontOut.from = 6;
  8235. grainsOut.from = 7;
  8236. ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
  8237. ch.patcher.fromMidiPorts = { 1, 5 };
  8238. ch.patcher.toMidiPorts = { 3 };
  8239. ch.patcher.outputX = 640.0f;
  8240. song.channels.push_back (ch);
  8241. // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
  8242. if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
  8243. {
  8244. if (! song.patterns.empty())
  8245. for (int k = 0; k < 4; ++k)
  8246. 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 });
  8247. juce::String error;
  8248. lynx::ProjectFile::save (song, juce::File (save), error);
  8249. // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
  8250. juce::String report;
  8251. if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
  8252. {
  8253. const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  8254. && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
  8255. const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
  8256. report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
  8257. if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
  8258. {
  8259. const auto& a = song.mixer[1].effects[0].patcher;
  8260. report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
  8261. << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
  8262. for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
  8263. if (! (a.nodes[n] == d.nodes[n]))
  8264. report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
  8265. << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
  8266. << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
  8267. }
  8268. for (int n = 0; n < (int) d.nodes.size(); ++n)
  8269. report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
  8270. << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
  8271. for (const auto& w : d.wires)
  8272. if (w.kind == lynx::PatchWire::Kind::control)
  8273. report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
  8274. for (const auto& p : d.published)
  8275. report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
  8276. }
  8277. else
  8278. report << "patcher round trip: load failed: " << error << "\n";
  8279. juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
  8280. }
  8281. offline.setSong (std::move (song));
  8282. }
  8283. offline.dispatchPendingMessages();
  8284. const auto& song = offline.getSong();
  8285. auto shootOpen = [&] (const juce::String& name) {
  8286. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  8287. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  8288. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  8289. {
  8290. auto* c = w->getContentComponent();
  8291. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
  8292. delete w;
  8293. return;
  8294. }
  8295. };
  8296. int shots = 0;
  8297. for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
  8298. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  8299. if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
  8300. {
  8301. lynx::PatcherWindows::openSlot (offline, t, s);
  8302. shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
  8303. // each built-in node's editor, as a double-click opens it (round 165c)
  8304. lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
  8305. savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
  8306. });
  8307. ++shots;
  8308. if (shots == 1) // its menus (round 162)
  8309. lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
  8310. savePng (image, prefix + "-menu-" + name + ".png");
  8311. });
  8312. }
  8313. for (int c = 0; c < (int) song.channels.size(); ++c)
  8314. if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
  8315. {
  8316. lynx::PatcherWindows::openChannel (offline, c);
  8317. shootOpen ("-channel" + juce::String (c) + ".png");
  8318. // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
  8319. lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
  8320. savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
  8321. });
  8322. lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
  8323. savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
  8324. });
  8325. }
  8326. }
  8327. }
  8328. // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
  8329. struct TypeAheadTest final : private juce::Timer
  8330. {
  8331. juce::File out;
  8332. juce::StringArray log;
  8333. int step = 0, picked = 0;
  8334. bool ok = true, menuShown = false;
  8335. std::unique_ptr<juce::DocumentWindow> owner;
  8336. juce::PopupMenu pending;
  8337. static juce::String highlighted()
  8338. {
  8339. if (auto* window = juce::Component::getCurrentlyModalComponent())
  8340. for (auto* child : window->getChildren())
  8341. if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
  8342. return h->getTitle();
  8343. return "(none)";
  8344. }
  8345. static void press (const juce::KeyPress& key)
  8346. {
  8347. if (auto* window = juce::Component::getCurrentlyModalComponent())
  8348. if (auto* peer = window->getPeer())
  8349. peer->handleKeyPress (key);
  8350. }
  8351. void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
  8352. {
  8353. const auto good = got == wanted;
  8354. ok = ok && good;
  8355. log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
  8356. }
  8357. void start()
  8358. {
  8359. juce::PopupMenu menu, sub;
  8360. auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
  8361. m.addItem (text, enabled, false, [this, id] { picked = id; });
  8362. };
  8363. menu.addSectionHeader ("LYNX SHARE");
  8364. item (menu, 1, "Echoform");
  8365. item (menu, 2, "EQ");
  8366. item (menu, 3, "Halo");
  8367. menu.addSectionHeader ("Misc");
  8368. item (menu, 4, "Effector");
  8369. item (menu, 5, "Exciter (unavailable)", false);
  8370. item (sub, 10, "Delay");
  8371. item (sub, 11, "Edison");
  8372. item (sub, 12, "Eventide");
  8373. menu.addSubMenu ("Tree", sub);
  8374. // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
  8375. // menu of a background process at once)
  8376. owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
  8377. owner->setBounds (200, 200, 300, 200);
  8378. owner->setVisible (true);
  8379. lynx::forceForegroundForTest (*owner);
  8380. pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
  8381. startTimer (300);
  8382. }
  8383. void timerCallback() override
  8384. {
  8385. const auto e = juce::KeyPress ('e', {}, 'e');
  8386. if (step == 0 && owner != nullptr && ! menuShown)
  8387. {
  8388. menuShown = true;
  8389. lynx::forceForegroundForTest (*owner);
  8390. lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
  8391. return;
  8392. }
  8393. switch (step++)
  8394. {
  8395. case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
  8396. case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
  8397. case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
  8398. case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
  8399. case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
  8400. case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
  8401. case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
  8402. case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
  8403. case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
  8404. case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
  8405. case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
  8406. case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
  8407. case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
  8408. case 13: break;
  8409. default:
  8410. expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
  8411. expect ("Enter picked", juce::String (picked), "12");
  8412. stopTimer();
  8413. owner.reset();
  8414. log.add (ok ? "result=OK" : "result=FAIL");
  8415. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  8416. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  8417. juce::JUCEApplication::quit();
  8418. return;
  8419. }
  8420. }
  8421. };
  8422. std::unique_ptr<TypeAheadTest> typeAheadTest;
  8423. struct ChooserTest final : private juce::Timer
  8424. {
  8425. juce::File out, file;
  8426. juce::StringArray log;
  8427. std::unique_ptr<juce::FileChooser> chooser;
  8428. double started = 0;
  8429. bool shot = false, done = false;
  8430. void start()
  8431. {
  8432. log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
  8433. log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  8434. chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
  8435. started = juce::Time::getMillisecondCounterHiRes();
  8436. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  8437. [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
  8438. startTimer (200);
  8439. }
  8440. static juce::FileChooserDialogBox* builtInDialog()
  8441. {
  8442. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
  8443. if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
  8444. return box;
  8445. return nullptr;
  8446. }
  8447. static juce::FileBrowserComponent* findBrowser (juce::Component& c)
  8448. {
  8449. if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
  8450. return b;
  8451. for (auto* child : c.getChildren())
  8452. if (auto* b = findBrowser (*child))
  8453. return b;
  8454. return nullptr;
  8455. }
  8456. void timerCallback() override
  8457. {
  8458. if (done)
  8459. return;
  8460. if (auto* box = builtInDialog(); box != nullptr && ! shot)
  8461. {
  8462. shot = true;
  8463. log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
  8464. const auto image = box->createComponentSnapshot (box->getLocalBounds());
  8465. juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
  8466. if (png.openedOk())
  8467. {
  8468. png.setPosition (0), png.truncate();
  8469. juce::PNGImageFormat().writeImageToStream (image, png);
  8470. }
  8471. if (auto* browser = findBrowser (*box))
  8472. {
  8473. browser->setRoot (file.getParentDirectory());
  8474. browser->setFileName (file.getFileName());
  8475. log.add ("typed " + file.getFileName());
  8476. box->exitModalState (1);
  8477. }
  8478. else
  8479. log.add ("no file browser in the dialog");
  8480. }
  8481. if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
  8482. finish ({}, "timeout");
  8483. }
  8484. void finish (const juce::File& result, const juce::String& why = {})
  8485. {
  8486. if (done)
  8487. return;
  8488. done = true;
  8489. stopTimer();
  8490. log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
  8491. + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
  8492. log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  8493. const auto ok = result == file && result.existsAsFile();
  8494. log.add (ok ? "result=OK" : "result=FAIL");
  8495. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  8496. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  8497. juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
  8498. }
  8499. };
  8500. std::unique_ptr<ChooserTest> chooserTest;
  8501. void runChooserTest (const juce::File& out, const juce::File& file)
  8502. {
  8503. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8504. chooserTest = std::make_unique<ChooserTest>();
  8505. chooserTest->out = out;
  8506. chooserTest->file = file;
  8507. chooserTest->start();
  8508. }
  8509. void runTypeAheadTest (const juce::File& out)
  8510. {
  8511. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8512. typeAheadTest = std::make_unique<TypeAheadTest>();
  8513. typeAheadTest->out = out;
  8514. typeAheadTest->start();
  8515. }
  8516. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  8517. {
  8518. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8519. // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
  8520. if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
  8521. if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
  8522. lynx::themeui::apply (*spec, false);
  8523. {
  8524. lynx::AudioEngine offline (false);
  8525. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  8526. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  8527. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  8528. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  8529. if (projectPath.isNotEmpty())
  8530. ui.openFile (juce::File (projectPath));
  8531. offline.dispatchPendingMessages(); // change notifications are asynchronous
  8532. ui.waitForBrowserForSnapshot();
  8533. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  8534. // (and a sample hint in the status strip, as when hovering a knob)
  8535. ui.showDesktopForSnapshot (false);
  8536. ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
  8537. offline.dispatchPendingMessages();
  8538. saveSnapshot (ui, prefix + "-desktop.png");
  8539. // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
  8540. {
  8541. const auto size = ui.getBounds();
  8542. ui.showSetupWizard();
  8543. offline.dispatchPendingMessages();
  8544. saveSnapshot (ui, prefix + "-desktop-setup.png");
  8545. ui.setSize (1024, 600);
  8546. offline.dispatchPendingMessages();
  8547. saveSnapshot (ui, prefix + "-desktop-setup-small.png");
  8548. ui.closeSetupWizardForSnapshot();
  8549. ui.setBounds (size);
  8550. offline.dispatchPendingMessages();
  8551. }
  8552. // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
  8553. // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
  8554. {
  8555. const auto size = ui.getBounds();
  8556. for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
  8557. {
  8558. ui.setSize (w, h);
  8559. offline.dispatchPendingMessages();
  8560. saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
  8561. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
  8562. if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
  8563. {
  8564. ui.scrollRackForSnapshot (100000);
  8565. offline.dispatchPendingMessages();
  8566. saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
  8567. ui.scrollRackForSnapshot (0);
  8568. }
  8569. }
  8570. // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
  8571. ui.setSize (1600, 900);
  8572. for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
  8573. {
  8574. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  8575. layout.iconSize = iconSize;
  8576. ui.setToolbarLayoutForSnapshot (layout);
  8577. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
  8578. }
  8579. {
  8580. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  8581. layout.move (lynx::toolbarlayout::Group::windows, -3);
  8582. layout.setShown (lynx::toolbarlayout::Group::record, false);
  8583. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  8584. ui.setToolbarLayoutForSnapshot (layout);
  8585. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
  8586. }
  8587. {
  8588. // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
  8589. ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
  8590. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  8591. lynx::AutomationTarget t;
  8592. t.kind = lynx::AutomationTargetKind::mixerVolume;
  8593. t.index = 0;
  8594. offline.noteTweaked (t);
  8595. ui.refreshTweakReadoutForSnapshot();
  8596. offline.dispatchPendingMessages();
  8597. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
  8598. ui.setSize (1600, 900);
  8599. }
  8600. {
  8601. // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
  8602. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  8603. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  8604. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  8605. ui.setToolbarLayoutForSnapshot (layout);
  8606. ui.setToolbarEditingForSnapshot (true);
  8607. offline.dispatchPendingMessages();
  8608. saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
  8609. ui.setToolbarEditingForSnapshot (false);
  8610. // Ctrl+F11: only the menu and the hint bar
  8611. layout = lynx::toolbarlayout::Layout::makeDefault();
  8612. layout.visible = false;
  8613. ui.setToolbarLayoutForSnapshot (layout);
  8614. saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
  8615. }
  8616. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  8617. // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
  8618. offline.dispatchPendingMessages();
  8619. saveQuickTips (ui, prefix);
  8620. ui.setBounds (size);
  8621. offline.dispatchPendingMessages();
  8622. }
  8623. // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
  8624. // glyphs, and a text too long for one line (two lines)
  8625. {
  8626. const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
  8627. const lynx::ui::Hint hints[] = {
  8628. { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
  8629. { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
  8630. { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  8631. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
  8632. };
  8633. for (int i = 0; i < 3; ++i)
  8634. {
  8635. ui.setHintForSnapshot (hints[i], i == 0);
  8636. saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
  8637. }
  8638. }
  8639. ui.showDesktopForSnapshot (true);
  8640. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  8641. saveSnapshot (ui, prefix + "-desktop-all.png");
  8642. ui.selectTabForSnapshot (0);
  8643. saveSnapshot (ui, prefix + "-rack.png");
  8644. {
  8645. // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
  8646. int found = -1;
  8647. const auto before = offline.getSong().currentPattern;
  8648. {
  8649. const auto& song = offline.getSong();
  8650. for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
  8651. for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
  8652. if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
  8653. found = p;
  8654. }
  8655. if (found >= 0)
  8656. {
  8657. offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
  8658. offline.dispatchPendingMessages();
  8659. saveSnapshot (ui, prefix + "-rack-preview.png");
  8660. offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
  8661. offline.dispatchPendingMessages();
  8662. }
  8663. }
  8664. ui.selectTabForSnapshot (1);
  8665. saveSnapshot (ui, prefix + "-pianoroll.png");
  8666. if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
  8667. saveArea (ui, strip, prefix + "-pianoroll-tools.png");
  8668. // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
  8669. ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
  8670. saveSnapshot (ui, prefix + "-pianoroll-hover.png");
  8671. ui.selectTabForSnapshot (2);
  8672. saveSnapshot (ui, prefix + "-playlist.png");
  8673. if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
  8674. saveArea (ui, strip, prefix + "-playlist-tools.png");
  8675. ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
  8676. saveSnapshot (ui, prefix + "-playlist-hover.png");
  8677. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  8678. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  8679. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  8680. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  8681. offline.dispatchPendingMessages();
  8682. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  8683. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  8684. // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
  8685. {
  8686. int header = -1;
  8687. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
  8688. if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
  8689. header = t;
  8690. if (header >= 0)
  8691. {
  8692. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
  8693. offline.dispatchPendingMessages();
  8694. saveSnapshot (ui, prefix + "-playlist-group-folded.png");
  8695. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
  8696. }
  8697. ui.getPickerForSnapshot().setView (1);
  8698. offline.dispatchPendingMessages();
  8699. saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
  8700. ui.getPickerForSnapshot().setView (0);
  8701. }
  8702. // round 104: the Channel Rack filtered to its first filter group
  8703. if (! offline.getSong().channelGroups.empty())
  8704. {
  8705. ui.selectTabForSnapshot (0);
  8706. ui.getRackForSnapshot().setFilterGroup (0);
  8707. offline.dispatchPendingMessages();
  8708. saveSnapshot (ui, prefix + "-rack-filter.png");
  8709. ui.getRackForSnapshot().setFilterGroup (-1);
  8710. }
  8711. ui.selectTabForSnapshot (3);
  8712. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  8713. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  8714. {
  8715. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  8716. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  8717. offline.dispatchPendingMessages();
  8718. }
  8719. saveSnapshot (ui, prefix + "-mixer.png");
  8720. // round 168h (issue #52): FL's 8 Mixer layouts
  8721. {
  8722. const auto before = lynx::MixerStrips::layout;
  8723. for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
  8724. {
  8725. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
  8726. offline.dispatchPendingMessages();
  8727. saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
  8728. }
  8729. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
  8730. offline.dispatchPendingMessages();
  8731. }
  8732. // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
  8733. {
  8734. const auto size = ui.getBounds();
  8735. for (auto h : { 450, 560, 680, 820 })
  8736. {
  8737. ui.setSize (size.getWidth(), h);
  8738. offline.dispatchPendingMessages();
  8739. saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
  8740. }
  8741. ui.setBounds (size);
  8742. offline.dispatchPendingMessages();
  8743. }
  8744. // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
  8745. // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
  8746. {
  8747. const auto before = offline.getSong();
  8748. offline.editSong ([] (lynx::Song& s) {
  8749. if (s.mixer.size() < 5)
  8750. return;
  8751. s.mixer[1].effects.clear();
  8752. lynx::EffectSlot fx;
  8753. fx.kind = lynx::EffectKind::compressor;
  8754. s.mixer[1].effects.push_back (fx);
  8755. lynx::mixerops::moveEffectBy (s, 1, 0, 1);
  8756. lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
  8757. });
  8758. ui.selectMixerTrackForSnapshot (1);
  8759. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
  8760. offline.dispatchPendingMessages();
  8761. saveSnapshot (ui, prefix + "-mixer170b.png");
  8762. juce::PopupMenu effects, generators;
  8763. lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
  8764. lynx::quickpick::addFolderViewItems (effects, offline);
  8765. lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  8766. lynx::quickpick::addFolderViewItems (generators, offline);
  8767. saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
  8768. offline.setSong (before);
  8769. offline.dispatchPendingMessages();
  8770. }
  8771. // standalone windows, with the theme background
  8772. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  8773. juce::Component frame;
  8774. frame.setSize (c->getWidth(), c->getHeight());
  8775. frame.setOpaque (true);
  8776. frame.addAndMakeVisible (*c);
  8777. c->setTopLeftPosition (0, 0);
  8778. checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
  8779. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  8780. {
  8781. juce::Graphics g (image);
  8782. g.fillAll (lynx::theme::panel);
  8783. frame.paintEntireComponent (g, false);
  8784. }
  8785. const juce::File file (prefix + name);
  8786. file.deleteFile();
  8787. juce::PNGImageFormat png;
  8788. if (auto out = file.createOutputStream())
  8789. png.writeImageToStream (image, *out);
  8790. };
  8791. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  8792. saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
  8793. saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
  8794. {
  8795. // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
  8796. // Export window for "Render selected tracks to wave file(s)"
  8797. const auto before = offline.getSong();
  8798. offline.editSong ([] (lynx::Song& s) {
  8799. if (s.mixer.size() > 3)
  8800. {
  8801. s.mixer[1].latencyMs = 5.0f;
  8802. s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  8803. s.mixer[2].latencyMs = -1.5f;
  8804. }
  8805. });
  8806. offline.dispatchPendingMessages();
  8807. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  8808. strips.setSelection ({ 1, 2, 3 }, 1);
  8809. const auto menu = strips.buildMenu (1);
  8810. juce::StringArray names { "Mixer track" };
  8811. std::vector<juce::PopupMenu> menus { menu };
  8812. const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
  8813. const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
  8814. lynx::tr ("Plugin delay compensation") };
  8815. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  8816. {
  8817. const auto& item = it.getItem();
  8818. if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
  8819. {
  8820. names.add (item.text.upToFirstOccurrenceOf (":", false, false));
  8821. menus.push_back (*item.subMenu);
  8822. }
  8823. }
  8824. saveMenus (names, menus, prefix + "-menus165-mixer.png");
  8825. saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
  8826. offline.setSong (before);
  8827. offline.dispatchPendingMessages();
  8828. }
  8829. saveSplashFrames (prefix);
  8830. saveIconSheet (prefix + "-icons.png", 1.0f);
  8831. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  8832. saveWindow (lynx::MainComponent::makeHelpContent(), "-help.png");
  8833. saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
  8834. saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
  8835. // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
  8836. offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
  8837. offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
  8838. saveMenus (ui, prefix + "-menus.png");
  8839. {
  8840. // the windows' own menus (title bars) and the toolbar's recording menu
  8841. juce::StringArray names;
  8842. std::vector<juce::PopupMenu> menus;
  8843. for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
  8844. { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
  8845. { lynx::workspace::Panel::browser, "Browser" } })
  8846. {
  8847. names.add (name);
  8848. menus.push_back (ui.getPanelMenuForSnapshot (panel));
  8849. }
  8850. names.add ("Recording");
  8851. menus.push_back (ui.getRecordMenuForSnapshot());
  8852. names.add ("Toolbar");
  8853. menus.push_back (ui.getToolbarMenuForSnapshot());
  8854. saveMenus (names, menus, prefix + "-panel-menus.png");
  8855. }
  8856. {
  8857. // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
  8858. std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
  8859. ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
  8860. ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
  8861. saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
  8862. // round 167l: the channel menu ("Lock active/mute state")
  8863. if (! offline.getSong().channels.empty())
  8864. saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
  8865. // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
  8866. {
  8867. juce::PopupMenu folder;
  8868. folder.addSectionHeader ("Documents");
  8869. folder.addItem (1, "Expand all");
  8870. folder.addItem (2, "Collapse all");
  8871. folder.addSeparator();
  8872. folder.addItem (3, "Refresh");
  8873. folder.addSectionHeader ("System");
  8874. folder.addItem (4, "Open");
  8875. folder.addItem (5, "Copy the file path");
  8876. folder.addSectionHeader ("Tags");
  8877. folder.addItem (6, "Starred", true, true);
  8878. folder.addSeparator();
  8879. folder.addItem (7, "Add folder...");
  8880. const auto wasCompact = lynx::theme::menus::compact();
  8881. lynx::theme::menus::setCompact (true);
  8882. saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
  8883. lynx::theme::menus::setCompact (false);
  8884. saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
  8885. lynx::theme::menus::setCompact (wasCompact);
  8886. }
  8887. // and the clip menus of the first pattern, audio and automation clips of the project
  8888. juce::StringArray clipNames;
  8889. std::vector<juce::PopupMenu> clipMenus;
  8890. for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
  8891. { lynx::ClipKind::automation, "Automation clip" } })
  8892. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  8893. if (offline.getSong().playlist[(std::size_t) c].kind == kind)
  8894. {
  8895. clipNames.add (name);
  8896. clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
  8897. break;
  8898. }
  8899. if (! clipMenus.empty())
  8900. saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
  8901. }
  8902. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  8903. alert->setOpaque (true);
  8904. saveWindow (std::move (alert), name);
  8905. };
  8906. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  8907. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  8908. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  8909. saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
  8910. saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
  8911. saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
  8912. saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
  8913. saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
  8914. saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
  8915. // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
  8916. {
  8917. struct Bars final : juce::Component
  8918. {
  8919. Bars()
  8920. {
  8921. constexpr int h = lynx::updater::UpdateBar::height;
  8922. setSize (1100, 4 * (h + 6));
  8923. for (int state = 0; state < 4; ++state)
  8924. {
  8925. bars[state].setBounds (0, state * (h + 6), getWidth(), h);
  8926. bars[state].showForSnapshot (state);
  8927. addAndMakeVisible (bars[state]);
  8928. }
  8929. }
  8930. lynx::updater::UpdateBar bars[4];
  8931. };
  8932. saveWindow (std::make_unique<Bars>(), "-update-bar.png");
  8933. saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
  8934. }
  8935. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
  8936. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
  8937. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
  8938. {
  8939. // the Settings pages, with credits like a project imported from FL would carry
  8940. offline.editSong ([] (lynx::Song& s) {
  8941. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  8942. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  8943. }, false);
  8944. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
  8945. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
  8946. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
  8947. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
  8948. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
  8949. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
  8950. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
  8951. saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
  8952. saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
  8953. }
  8954. {
  8955. // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
  8956. saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
  8957. const auto& clips = offline.getSong().playlist;
  8958. for (int i = 0; i < (int) clips.size(); ++i)
  8959. if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
  8960. {
  8961. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
  8962. break;
  8963. }
  8964. for (int i = 0; i < (int) clips.size(); ++i)
  8965. if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
  8966. {
  8967. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
  8968. break;
  8969. }
  8970. if (offline.getSong().arrangements.size() < 2)
  8971. offline.editSong ([] (lynx::Song& s) {
  8972. const auto current = s.currentArrangement;
  8973. s.addArrangement ("Radio edit", true);
  8974. s.addArrangement ("Intro loop");
  8975. s.selectArrangement (current);
  8976. }, false);
  8977. saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
  8978. saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
  8979. saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
  8980. }
  8981. {
  8982. // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
  8983. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
  8984. {
  8985. juce::AudioBuffer<float> line (1, 44100 * 2);
  8986. const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
  8987. double ph = 0.0;
  8988. for (int i = 0; i < line.getNumSamples(); ++i)
  8989. {
  8990. const auto f0 = hz[std::min (4, i / 17640)];
  8991. 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;
  8992. float v = 0.0f;
  8993. for (int h = 1; f0 > 0.0 && h < 8; ++h)
  8994. v += (float) (0.3 / h * std::sin (h * ph));
  8995. line.setSample (0, i, v);
  8996. }
  8997. wav.deleteFile();
  8998. juce::WavAudioFormat format;
  8999. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  9000. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
  9001. {
  9002. out.release();
  9003. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  9004. writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
  9005. }
  9006. }
  9007. if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
  9008. {
  9009. auto notes = lynx::newtonefx::analyseNotes (*sample);
  9010. if (notes.pitches.size() > 1)
  9011. notes.pitches[1].shift = 2.0;
  9012. lynx::newtonefx::WarpMap warp;
  9013. warp.frames = (std::int64_t) sample->frames();
  9014. warp.markers = { { 22050, 33075 } };
  9015. int at = 0;
  9016. offline.editSong ([&] (lynx::Song& song) {
  9017. if (song.mixer.size() < 2)
  9018. song.mixer.resize (2);
  9019. auto& fx = song.mixer[1].effects;
  9020. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  9021. tone.samplePath = wav.getFullPathName().toStdString();
  9022. tone.state = lynx::newtonefx::writeNative (notes);
  9023. auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
  9024. time.samplePath = tone.samplePath;
  9025. time.state = lynx::newtonefx::writeWarp (warp);
  9026. at = (int) fx.size();
  9027. fx.push_back (tone);
  9028. fx.push_back (time);
  9029. }, false);
  9030. saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
  9031. saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
  9032. offline.editSong ([at] (lynx::Song& song) {
  9033. auto& fx = song.mixer[1].effects;
  9034. fx.erase (fx.begin() + at, fx.begin() + at + 2);
  9035. }, false);
  9036. }
  9037. }
  9038. if (! offline.getSong().automations.empty())
  9039. {
  9040. auto editor = lynx::makeAutomationEditor (offline, 0);
  9041. editor->setSize (760, 300);
  9042. saveWindow (std::move (editor), "-automation.png");
  9043. // round 177b: the same clip in FL's LFO mode (its amplitude points, the played curve, the LFO strip)
  9044. const auto before = offline.getSong().automations[0].lfo;
  9045. offline.editSong ([] (lynx::Song& song) {
  9046. auto& lfo = song.automations[0].lfo;
  9047. lfo.on = true;
  9048. lfo.level = 96;
  9049. lfo.speed = lynx::AutomationLfo::speedForBeats (2.0);
  9050. lfo.tension = 40;
  9051. lfo.amp = { { 0, 0.3f, 0.0f }, { lynx::ppq * 8, 1.0f, 0.0f } };
  9052. }, false);
  9053. auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
  9054. lfoEditor->setSize (760, 330);
  9055. saveWindow (std::move (lfoEditor), "-automation-lfo.png");
  9056. offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
  9057. }
  9058. // round 177b: LYNX's modulators window, with one routed modulator
  9059. {
  9060. offline.editSong ([] (lynx::Song& song) {
  9061. lynx::Modulator m;
  9062. m.name = "LFO 1";
  9063. m.shape = lynx::ModShape::triangle;
  9064. m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  9065. song.modulators.push_back (m);
  9066. lynx::Modulator r;
  9067. r.name = "LFO 2";
  9068. r.shape = lynx::ModShape::smoothRandom;
  9069. r.sync = false;
  9070. r.hz = 0.5;
  9071. song.modulators.push_back (r);
  9072. }, false);
  9073. auto mods = lynx::makeModulatorsPanel (offline);
  9074. mods->setSize (720, 360);
  9075. saveWindow (std::move (mods), "-modulators.png");
  9076. offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
  9077. }
  9078. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  9079. // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
  9080. saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
  9081. saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
  9082. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  9083. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  9084. {
  9085. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  9086. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  9087. break;
  9088. }
  9089. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  9090. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  9091. {
  9092. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  9093. break;
  9094. }
  9095. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  9096. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  9097. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  9098. {
  9099. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  9100. break;
  9101. }
  9102. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  9103. {
  9104. int bestTrack = -1, bestSlot = -1;
  9105. double bestShape = -1.0;
  9106. const auto& mixer = offline.getSong().mixer;
  9107. for (int t = 0; t < (int) mixer.size(); ++t)
  9108. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  9109. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  9110. {
  9111. double shape = 0.0;
  9112. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  9113. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  9114. if (shape > bestShape)
  9115. {
  9116. bestShape = shape;
  9117. bestTrack = t;
  9118. bestSlot = s;
  9119. }
  9120. }
  9121. if (bestTrack >= 0)
  9122. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  9123. }
  9124. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  9125. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  9126. saveWindow (std::move (inspector), "-noteinspector.png");
  9127. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  9128. saveWindow (std::move (inspector), "-noteinspector-one.png");
  9129. // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
  9130. {
  9131. auto& roll = ui.getPianoRollForSnapshot();
  9132. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
  9133. { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
  9134. { lynx::NoteTool::flip, "-tool-flip.png" },
  9135. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  9136. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  9137. { lynx::NoteTool::limit, "-tool-limit.png" },
  9138. { lynx::NoteTool::quantize, "-tool-quantize.png" },
  9139. { lynx::NoteTool::chop, "-tool-chop.png" },
  9140. { lynx::NoteTool::flam, "-tool-flam.png" },
  9141. { lynx::NoteTool::lfo, "-tool-lfo.png" },
  9142. { lynx::NoteTool::claw, "-tool-claw.png" },
  9143. { lynx::NoteTool::articulate, "-tool-articulate.png" },
  9144. { lynx::NoteTool::riffMachine, "-tool-riff.png" },
  9145. { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
  9146. for (const auto& [tool, name] : tools)
  9147. saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
  9148. }
  9149. // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
  9150. {
  9151. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
  9152. const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
  9153. offline.editSong ([&] (lynx::Song& s) {
  9154. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
  9155. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
  9156. lynx::prtools::LfoOptions lfo;
  9157. lfo.startSpeed = 7 * 4096; // one beat
  9158. lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
  9159. }, false);
  9160. saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
  9161. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  9162. }
  9163. // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
  9164. // and its menu items (-audioeditor-menu.txt)
  9165. {
  9166. namespace ae = lynx::audioedit;
  9167. ae::Document d;
  9168. d.title = "Drum loop";
  9169. d.audio.sampleRate = 44100.0;
  9170. const auto frames = (std::size_t) (44100 * 2);
  9171. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  9172. std::uint32_t seed = 7;
  9173. for (int hit = 0; hit < 8; ++hit)
  9174. {
  9175. const auto at = (std::size_t) hit * frames / 8;
  9176. const auto kick = hit % 2 == 0;
  9177. double phase = 0.0;
  9178. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  9179. {
  9180. seed = seed * 1664525u + 1013904223u;
  9181. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  9182. const auto t = (double) i / 44100.0;
  9183. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  9184. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  9185. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  9186. d.audio.channels[0][at + i] += v;
  9187. d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
  9188. }
  9189. }
  9190. ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
  9191. ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
  9192. ae::setLoop (d, { 0, (std::int64_t) frames });
  9193. auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
  9194. juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
  9195. saveWindow (std::move (wave), "-audioeditor.png");
  9196. saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
  9197. }
  9198. // the tempo tapper after five steady taps (round 132)
  9199. saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
  9200. // the Channel Rack's piano-roll view (round 132)
  9201. ui.selectTabForSnapshot (0);
  9202. ui.getRackForSnapshot().setPianoRollView (true);
  9203. offline.dispatchPendingMessages();
  9204. saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
  9205. ui.getRackForSnapshot().setPianoRollView (false);
  9206. // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
  9207. ui.selectTabForSnapshot (0);
  9208. ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
  9209. offline.dispatchPendingMessages();
  9210. saveSnapshot (ui, prefix + "-rack-graph.png");
  9211. ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
  9212. saveSnapshot (ui, prefix + "-rack-graph-pan.png");
  9213. ui.getRackForSnapshot().toggleGraphLanes();
  9214. saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
  9215. // the Mixer with three inserts selected and one armed for recording
  9216. ui.selectTabForSnapshot (3);
  9217. if (offline.getSong().mixer.size() > 4)
  9218. {
  9219. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
  9220. offline.setInsertArmed (3, true);
  9221. offline.dispatchPendingMessages();
  9222. saveSnapshot (ui, prefix + "-mixer-multi.png");
  9223. // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
  9224. offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
  9225. ui.getMixerForSnapshot().selectTrack (3);
  9226. offline.dispatchPendingMessages();
  9227. saveSnapshot (ui, prefix + "-mixer-input.png");
  9228. offline.undo();
  9229. offline.setInsertArmed (3, false);
  9230. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
  9231. }
  9232. // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
  9233. if (offline.getSong().mixer.size() > 6)
  9234. {
  9235. int source = -1;
  9236. for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
  9237. if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
  9238. source = t;
  9239. const auto temporary = source < 0;
  9240. if (temporary) // the demo has no sends: add two for the picture
  9241. {
  9242. source = 1;
  9243. 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); });
  9244. }
  9245. ui.getMixerForSnapshot().selectTrack (source);
  9246. offline.dispatchPendingMessages();
  9247. saveSnapshot (ui, prefix + "-mixer-sends.png");
  9248. if (temporary)
  9249. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
  9250. ui.getMixerForSnapshot().selectTrack (0);
  9251. }
  9252. // the Playlist with ripple editing on
  9253. ui.selectTabForSnapshot (2);
  9254. ui.getPlaylistForSnapshot().setRipple (true);
  9255. saveSnapshot (ui, prefix + "-playlist-ripple.png");
  9256. ui.getPlaylistForSnapshot().setRipple (false);
  9257. // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
  9258. {
  9259. const auto saved = offline.getSong();
  9260. offline.editSong ([] (lynx::Song& s) {
  9261. s.patternBlocksOn = true;
  9262. while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
  9263. lynx::clonePattern (s, (int) s.patterns.size() - 1);
  9264. const auto rows = juce::jmin (6, (int) s.patterns.size());
  9265. for (int r = 0; r < rows; ++r)
  9266. lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
  9267. (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
  9268. }, false);
  9269. offline.dispatchPendingMessages();
  9270. saveSnapshot (ui, prefix + "-playlist-blocks.png");
  9271. offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
  9272. offline.dispatchPendingMessages();
  9273. }
  9274. // quick-add palette, and the Browser searching
  9275. saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
  9276. ui.showDesktopForSnapshot (false);
  9277. ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
  9278. offline.dispatchPendingMessages();
  9279. saveSnapshot (ui, prefix + "-browser-search.png");
  9280. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  9281. ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
  9282. offline.dispatchPendingMessages();
  9283. saveSnapshot (ui, prefix + "-browser-tree.png");
  9284. // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
  9285. ui.getBrowserForSnapshot().showProjectForSnapshot();
  9286. offline.dispatchPendingMessages();
  9287. saveSnapshot (ui, prefix + "-browser-project.png");
  9288. ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
  9289. offline.dispatchPendingMessages();
  9290. saveSnapshot (ui, prefix + "-browser-plugins.png");
  9291. ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
  9292. saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
  9293. {
  9294. // round 164: the content filter leaves out the folders with nothing to list (a small library)
  9295. const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
  9296. lib.deleteRecursively();
  9297. for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
  9298. "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
  9299. lib.getChildFile (path).create();
  9300. ui.showDesktopForSnapshot (false);
  9301. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  9302. offline.dispatchPendingMessages();
  9303. saveSnapshot (ui, prefix + "-browser164-all.png");
  9304. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
  9305. offline.dispatchPendingMessages();
  9306. saveSnapshot (ui, prefix + "-browser164-samples.png");
  9307. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
  9308. offline.dispatchPendingMessages();
  9309. saveSnapshot (ui, prefix + "-browser164-projects.png");
  9310. lib.deleteRecursively();
  9311. ui.getBrowserForSnapshot().resetViewForSnapshot();
  9312. }
  9313. // the undo history after a few edits
  9314. offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
  9315. offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
  9316. offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
  9317. offline.undo();
  9318. saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
  9319. // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
  9320. // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
  9321. {
  9322. const juce::File wav (prefix + "-wavedemo.wav");
  9323. writeWaveDemo (wav, offline.getSong().bpm);
  9324. const auto path = wav.getFullPathName();
  9325. const auto pathUtf8 = path.toStdString();
  9326. int samplerChannel = -1, firstTrack = 0;
  9327. offline.editSong ([&] (lynx::Song& s) {
  9328. for (const auto& clip : s.playlist)
  9329. firstTrack = std::max (firstTrack, clip.track + 1);
  9330. lynx::ChannelDef audio;
  9331. audio.name = "Beat (audio)";
  9332. audio.instrument = lynx::InstrumentKind::audioClip;
  9333. audio.samplePath = pathUtf8;
  9334. s.channels.push_back (audio);
  9335. const auto audioChannel = (int) s.channels.size() - 1;
  9336. lynx::ChannelDef sampler = audio;
  9337. sampler.name = "Beat (sampler)";
  9338. sampler.instrument = lynx::InstrumentKind::sampler;
  9339. sampler.sampler.regionStart = 0.06f;
  9340. sampler.sampler.regionEnd = 0.94f;
  9341. s.channels.push_back (sampler);
  9342. samplerChannel = (int) s.channels.size() - 1;
  9343. const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
  9344. const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
  9345. lynx::Clip clip;
  9346. clip.kind = lynx::ClipKind::audio;
  9347. clip.channel = audioChannel;
  9348. clip.track = firstTrack;
  9349. clip.length = whole;
  9350. s.playlist.push_back (clip);
  9351. clip.track = firstTrack + 1; // a slice of it, later in the song
  9352. clip.start = bar;
  9353. clip.offset = bar;
  9354. clip.length = 2 * bar;
  9355. s.playlist.push_back (clip);
  9356. // taller rows for the audio (tracks can be resized: P18)
  9357. if ((int) s.playlistTracks.size() < firstTrack + 2)
  9358. s.playlistTracks.resize ((std::size_t) firstTrack + 2);
  9359. s.playlistTracks[(std::size_t) firstTrack].height = 80;
  9360. s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
  9361. });
  9362. offline.dispatchPendingMessages();
  9363. auto& cache = *lynx::ui::WaveformCache::getInstance();
  9364. cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  9365. cache.waitUntilIdle (30000);
  9366. ui.selectTabForSnapshot (2);
  9367. auto& playlist = ui.getPlaylistForSnapshot();
  9368. playlist.setTimeSelectionForSnapshot (0, 0);
  9369. {
  9370. // the Playlist alone (the floating Channel Rack would cover the clips)
  9371. auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
  9372. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  9373. saveSnapshot (ui, prefix + "-playlist-audio.png");
  9374. playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
  9375. saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
  9376. lynx::ui::WaveformCache::stereo = true;
  9377. saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
  9378. lynx::ui::WaveformCache::stereo = false;
  9379. lynx::ui::WaveformCache::spectral = true;
  9380. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  9381. saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
  9382. lynx::ui::WaveformCache::spectral = false;
  9383. playlist.setViewForSnapshot (40.0, 0, 0);
  9384. saveSnapshot (ui, prefix + "-playlist-audio-far.png");
  9385. // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
  9386. // a fade, a reversed copy), at three zoom levels
  9387. if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
  9388. ! files.isEmpty())
  9389. {
  9390. const auto realTrack = firstTrack + 2;
  9391. std::vector<juce::String> paths;
  9392. for (const auto& f : files)
  9393. if (juce::File (f.trim()).existsAsFile())
  9394. paths.push_back (f.trim());
  9395. offline.editSong ([&] (lynx::Song& s) {
  9396. const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
  9397. const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
  9398. for (std::size_t i = 0; i < paths.size(); ++i)
  9399. {
  9400. lynx::ChannelDef audio;
  9401. audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
  9402. audio.instrument = lynx::InstrumentKind::audioClip;
  9403. audio.samplePath = paths[i].toStdString();
  9404. audio.colour = colours[i % 6];
  9405. audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
  9406. audio.sampler.keepPitch = true;
  9407. s.channels.push_back (audio);
  9408. lynx::Clip clip;
  9409. clip.kind = lynx::ClipKind::audio;
  9410. clip.channel = (int) s.channels.size() - 1;
  9411. clip.track = realTrack + (int) i;
  9412. clip.length = 4 * bar;
  9413. clip.fadeIn = i == 1 ? bar / 2 : 0;
  9414. s.playlist.push_back (clip);
  9415. clip.start = 4 * bar;
  9416. clip.fadeIn = 0;
  9417. clip.fadeOut = i == 0 ? bar : 0;
  9418. s.playlist.push_back (clip);
  9419. }
  9420. if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
  9421. s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
  9422. if (! paths.empty())
  9423. s.playlistTracks[(std::size_t) realTrack].height = 90;
  9424. });
  9425. offline.dispatchPendingMessages();
  9426. for (const auto& path2 : paths)
  9427. cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
  9428. cache.waitUntilIdle (60000);
  9429. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  9430. saveSnapshot (ui, prefix + "-playlist-real.png");
  9431. playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
  9432. saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
  9433. playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
  9434. saveSnapshot (ui, prefix + "-playlist-real-close.png");
  9435. playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
  9436. saveSnapshot (ui, prefix + "-playlist-real-far.png");
  9437. // the clip menu of the first real clip
  9438. if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
  9439. saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
  9440. if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
  9441. saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
  9442. // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
  9443. {
  9444. juce::StringArray log;
  9445. auto clipOf = [&offline] (const std::string& channelName, int nth) {
  9446. const auto& sg = offline.getSong();
  9447. for (int i = 0; i < (int) sg.playlist.size(); ++i)
  9448. {
  9449. const auto& c = sg.playlist[(std::size_t) i];
  9450. if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
  9451. return i;
  9452. }
  9453. return -1;
  9454. };
  9455. std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
  9456. for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
  9457. {
  9458. auto& item = it.getItem();
  9459. if (item.subMenu != nullptr && run (*item.subMenu, text))
  9460. return true;
  9461. if (item.text.startsWith (text) && item.isEnabled && item.action)
  9462. {
  9463. item.action();
  9464. return true;
  9465. }
  9466. }
  9467. return false;
  9468. };
  9469. auto act = [&] (const std::string& name, int nth, const juce::String& text) {
  9470. const auto clip = clipOf (name, nth);
  9471. const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
  9472. offline.dispatchPendingMessages();
  9473. return ok;
  9474. };
  9475. auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
  9476. for (const auto& c : offline.getSong().channels)
  9477. if (c.name == name)
  9478. return &c;
  9479. return nullptr;
  9480. };
  9481. auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
  9482. const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
  9483. if (names.size() >= 4)
  9484. {
  9485. const auto channelsBefore = offline.getSong().channels.size();
  9486. check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
  9487. offline.undo();
  9488. offline.dispatchPendingMessages();
  9489. check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
  9490. act (names[2], 0, lynx::tr ("Reverse"));
  9491. check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
  9492. && channelOf (names[3] + " #2") != nullptr);
  9493. check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
  9494. && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
  9495. const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
  9496. check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
  9497. && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
  9498. const auto clipsBefore = offline.getSong().playlist.size();
  9499. check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
  9500. check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
  9501. check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
  9502. && offline.getSong().playlist.size() == clipsBefore + 2);
  9503. check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
  9504. check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
  9505. }
  9506. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  9507. saveSnapshot (ui, prefix + "-playlist-real-actions.png");
  9508. juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
  9509. }
  9510. }
  9511. }
  9512. saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
  9513. ui.showDesktopForSnapshot (false);
  9514. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  9515. saveSnapshot (ui, prefix + "-browser-preview.png");
  9516. }
  9517. }
  9518. // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
  9519. // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
  9520. juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
  9521. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  9522. quit();
  9523. }
  9524. // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
  9525. // hats and the noise riser = high), to show the spectral waveform colours
  9526. static void writeWaveDemo (const juce::File& file, double bpm)
  9527. {
  9528. constexpr double rate = 44100.0;
  9529. const auto frames = (int) (8.0 * rate);
  9530. juce::AudioBuffer<float> buffer (2, frames);
  9531. buffer.clear();
  9532. auto* l = buffer.getWritePointer (0);
  9533. auto* r = buffer.getWritePointer (1);
  9534. const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
  9535. std::uint32_t noise = 0x9e3779b9u;
  9536. auto white = [&noise] {
  9537. noise ^= noise << 13;
  9538. noise ^= noise >> 17;
  9539. noise ^= noise << 5;
  9540. return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
  9541. };
  9542. float previous = 0.0f;
  9543. for (int i = 0; i < frames; ++i)
  9544. {
  9545. const auto t = i / rate;
  9546. const auto inBeat = std::fmod (t, beat);
  9547. const auto bar = (int) (t / (beat * 4.0));
  9548. float left = 0.0f, right = 0.0f;
  9549. // kick on every beat: a falling sine
  9550. {
  9551. const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
  9552. const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
  9553. left += k;
  9554. right += k;
  9555. }
  9556. // hats on the off-beats: high-passed noise bursts, a little to the right
  9557. {
  9558. const auto h = std::fmod (t + beat * 0.5, beat);
  9559. const auto n = white();
  9560. const auto hp = (n - previous) * 0.5f;
  9561. previous = n;
  9562. const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
  9563. left += hat * 0.6f;
  9564. right += hat;
  9565. }
  9566. // a chord in the second and third bars (mid band)
  9567. if (bar == 1 || bar == 2)
  9568. {
  9569. const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
  9570. float chord = 0.0f;
  9571. for (const auto hz : { 523.25, 659.25, 783.99 })
  9572. chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
  9573. left += chord * 0.09f * std::max (0.0f, env);
  9574. right += chord * 0.09f * std::max (0.0f, env);
  9575. }
  9576. // a white-noise riser over the last two seconds (high band)
  9577. if (t > 6.0)
  9578. {
  9579. const auto rise = (float) ((t - 6.0) / 2.0);
  9580. left += white() * 0.4f * rise * rise;
  9581. right += white() * 0.4f * rise * rise;
  9582. }
  9583. l[i] = left;
  9584. r[i] = right;
  9585. }
  9586. buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
  9587. file.deleteFile();
  9588. juce::WavAudioFormat wav;
  9589. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
  9590. writer->writeFromAudioSampleBuffer (buffer, 0, frames);
  9591. }
  9592. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  9593. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  9594. {
  9595. const auto names = ui.getMenuNamesForSnapshot();
  9596. std::vector<juce::PopupMenu> source;
  9597. for (int m = 0; m < names.size(); ++m)
  9598. source.push_back (ui.getMenuForSnapshot (m));
  9599. saveMenus (names, source, path);
  9600. }
  9601. // menus side by side, each under its name
  9602. static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
  9603. {
  9604. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  9605. struct Laid
  9606. {
  9607. juce::PopupMenu menu;
  9608. int width = 0, height = 0;
  9609. };
  9610. std::vector<Laid> menus;
  9611. const auto border = lf.getPopupMenuBorderSize();
  9612. for (int m = 0; m < names.size(); ++m)
  9613. {
  9614. Laid laid { source[(std::size_t) m] };
  9615. int width = 160, height = 2 * border;
  9616. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  9617. {
  9618. const auto& item = it.getItem();
  9619. int w = 0, h = 0;
  9620. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  9621. if (item.isSectionHeader) h += h / 2; // as JUCE does
  9622. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  9623. w += 90;
  9624. width = juce::jmax (width, w + 10);
  9625. height += h;
  9626. }
  9627. laid.width = width;
  9628. laid.height = height;
  9629. menus.push_back (std::move (laid));
  9630. }
  9631. int totalWidth = 16, totalHeight = 0;
  9632. for (const auto& l : menus)
  9633. {
  9634. totalWidth += l.width + 16;
  9635. totalHeight = juce::jmax (totalHeight, l.height + 32);
  9636. }
  9637. juce::Image image (juce::Image::ARGB, totalWidth, totalHeight, true);
  9638. {
  9639. juce::Graphics g (image);
  9640. g.fillAll (lynx::theme::colour::bg1);
  9641. int x = 16;
  9642. for (int m = 0; m < (int) menus.size(); ++m)
  9643. {
  9644. const auto& l = menus[(std::size_t) m];
  9645. g.setColour (lynx::theme::colour::textSecondary);
  9646. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  9647. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  9648. {
  9649. juce::Graphics::ScopedSaveState state (g);
  9650. g.reduceClipRegion (x, 24, l.width, l.height);
  9651. g.setOrigin (x, 24);
  9652. lf.drawPopupMenuBackground (g, l.width, l.height);
  9653. int y = border;
  9654. bool first = true;
  9655. for (juce::PopupMenu::MenuItemIterator it (l.menu); it.next();)
  9656. {
  9657. const auto& item = it.getItem();
  9658. int w = 0, h = 0;
  9659. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  9660. if (item.isSectionHeader) h += h / 2; // as JUCE does
  9661. const juce::Rectangle<int> r (0, y, l.width, h);
  9662. auto text = item.text, shortcut = item.shortcutKeyDescription;
  9663. if (text.containsChar ('\t'))
  9664. {
  9665. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  9666. text = text.upToFirstOccurrenceOf ("\t", false, false);
  9667. }
  9668. if (item.isSectionHeader)
  9669. lf.drawPopupMenuSectionHeader (g, r, text);
  9670. else
  9671. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  9672. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  9673. first = false;
  9674. y += h;
  9675. }
  9676. }
  9677. x += l.width + 16;
  9678. }
  9679. }
  9680. const juce::File file (path);
  9681. file.deleteFile();
  9682. juce::PNGImageFormat png;
  9683. if (auto out = file.createOutputStream())
  9684. png.writeImageToStream (image, *out);
  9685. }
  9686. static void writePng (const juce::Image& image, const juce::String& path)
  9687. {
  9688. const juce::File file (path);
  9689. file.deleteFile();
  9690. juce::PNGImageFormat png;
  9691. if (auto out = file.createOutputStream())
  9692. png.writeImageToStream (image, *out);
  9693. }
  9694. // the splash screen: one settled frame, and a strip of frames through its animation
  9695. static void saveSplashFrames (const juce::String& prefix)
  9696. {
  9697. lynx::SplashScreen splash;
  9698. splash.setStatus (lynx::tr ("Loading the workspace..."));
  9699. splash.setTimeForSnapshot (1.6);
  9700. writePng (splash.createComponentSnapshot (splash.getLocalBounds()), prefix + "-splash.png");
  9701. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  9702. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  9703. juce::Image strip (juce::Image::ARGB, 4 * (w + 8) + 8, 2 * (h + 8) + 8, true);
  9704. {
  9705. juce::Graphics g (strip);
  9706. g.fillAll (lynx::theme::colour::bg1);
  9707. for (int i = 0; i < 8; ++i)
  9708. {
  9709. splash.setTimeForSnapshot (times[i]);
  9710. const auto frame = splash.createComponentSnapshot (splash.getLocalBounds());
  9711. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  9712. }
  9713. }
  9714. writePng (strip, prefix + "-splash-frames.png");
  9715. }
  9716. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  9717. // colours: at rest, hovered and switched on
  9718. static void saveIconSheet (const juce::String& path, float scale)
  9719. {
  9720. const int sizes[] = { 16, 20, 24 };
  9721. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  9722. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  9723. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  9724. {
  9725. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  9726. g.addTransform (juce::AffineTransform::scale (scale));
  9727. g.fillAll (lynx::theme::colour::bg3);
  9728. g.setFont (lynx::theme::font (lynx::theme::type::small));
  9729. for (int i = 1; i < lynx::iconCount; ++i)
  9730. {
  9731. const auto y = 8 + (i - 1) * cell;
  9732. g.setColour (lynx::theme::colour::textDisabled);
  9733. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  9734. for (int v = 0; v < 3; ++v)
  9735. for (int s = 0; s < 3; ++s)
  9736. {
  9737. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  9738. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  9739. g.setColour (bg);
  9740. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  9741. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  9742. : lynx::theme::colour::textSecondary.brighter (0.25f);
  9743. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  9744. }
  9745. }
  9746. }
  9747. writePng (image, path);
  9748. }
  9749. // a part of a component (e.g. the main toolbar)
  9750. static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
  9751. {
  9752. const juce::File file (path);
  9753. file.deleteFile();
  9754. juce::PNGImageFormat png;
  9755. if (auto out = file.createOutputStream())
  9756. png.writeImageToStream (c.createComponentSnapshot (area), *out);
  9757. }
  9758. static void savePng (const juce::Image& image, const juce::String& path)
  9759. {
  9760. const juce::File file (path);
  9761. file.deleteFile();
  9762. juce::PNGImageFormat png;
  9763. if (auto out = file.createOutputStream())
  9764. png.writeImageToStream (image, *out);
  9765. }
  9766. // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
  9767. // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
  9768. static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
  9769. {
  9770. const auto tips = ui.getQuickTipsForSnapshot();
  9771. const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
  9772. auto image = ui.createComponentSnapshot (top);
  9773. {
  9774. juce::Graphics g (image);
  9775. const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
  9776. lynx::tr ("Window options"), lynx::tr ("Close") };
  9777. std::vector<juce::Rectangle<int>> used;
  9778. for (const auto& [area, tip] : tips)
  9779. {
  9780. const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
  9781. if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
  9782. continue;
  9783. const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
  9784. if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
  9785. continue;
  9786. used.push_back (bubble);
  9787. g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
  9788. g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
  9789. lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
  9790. }
  9791. }
  9792. savePng (image, prefix + "-toolbar-tips.png");
  9793. // the sheet: bubbles in rows
  9794. const int width = 900;
  9795. int x = 12, y = 12;
  9796. std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
  9797. for (const auto& [area, tip] : tips)
  9798. {
  9799. auto r = lynx::ui::quickTipSize (tip);
  9800. if (x + r.getWidth() > width - 12)
  9801. {
  9802. x = 12;
  9803. y += r.getHeight() + 10;
  9804. }
  9805. placed.emplace_back (r.withPosition (x, y), tip);
  9806. x += r.getWidth() + 10;
  9807. }
  9808. juce::Image sheet (juce::Image::ARGB, width, y + 20 + 12, true);
  9809. {
  9810. juce::Graphics g (sheet);
  9811. g.fillAll (lynx::theme::colour::bg3);
  9812. for (const auto& [r, tip] : placed)
  9813. lynx::ui::paintQuickTip (g, r.toFloat(), tip);
  9814. }
  9815. savePng (sheet, prefix + "-tips-sheet.png");
  9816. }
  9817. static juce::StringArray& textFitLog()
  9818. {
  9819. static juce::StringArray log;
  9820. return log;
  9821. }
  9822. // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
  9823. static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
  9824. {
  9825. if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
  9826. return false;
  9827. auto visible = [] (juce::GlyphArrangement& ga) {
  9828. int n = 0;
  9829. for (int i = 0; i < ga.getNumGlyphs(); ++i)
  9830. n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
  9831. return n;
  9832. };
  9833. juce::GlyphArrangement fitted, full;
  9834. fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
  9835. juce::jmax (1, maxLines), minScale);
  9836. full.addLineOfText (font, text, 0.0f, 0.0f);
  9837. return visible (fitted) < visible (full);
  9838. }
  9839. // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
  9840. static void checkTextFit (juce::Component& root, const juce::String& where)
  9841. {
  9842. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  9843. if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
  9844. return;
  9845. juce::String text;
  9846. bool cut = false;
  9847. if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
  9848. {
  9849. const auto font = label->getLookAndFeel().getLabelFont (*label);
  9850. const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
  9851. text = label->getText();
  9852. cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
  9853. label->getMinimumHorizontalScale());
  9854. }
  9855. else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
  9856. {
  9857. const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
  9858. text = toggle->getButtonText();
  9859. cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
  9860. c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
  9861. }
  9862. else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
  9863. button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
  9864. {
  9865. text = button->getButtonText();
  9866. cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
  9867. button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
  9868. }
  9869. if (cut)
  9870. {
  9871. juce::String path;
  9872. for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
  9873. if (p->getName().isNotEmpty())
  9874. path = p->getName() + (path.isEmpty() ? "" : "/") + path;
  9875. const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
  9876. + (path.isEmpty() ? juce::String() : " | " + path);
  9877. textFitLog().addIfNotAlreadyThere (line);
  9878. }
  9879. for (auto* child : c.getChildren())
  9880. visit (*child);
  9881. };
  9882. visit (root);
  9883. }
  9884. static void saveSnapshot (juce::Component& c, const juce::String& path)
  9885. {
  9886. checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
  9887. const juce::File file (path);
  9888. file.deleteFile();
  9889. juce::PNGImageFormat png;
  9890. if (auto out = file.createOutputStream())
  9891. png.writeImageToStream (c.createComponentSnapshot (c.getLocalBounds()), *out);
  9892. }
  9893. class MainWindow final : public juce::DocumentWindow
  9894. {
  9895. public:
  9896. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  9897. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons)
  9898. {
  9899. setUsingNativeTitleBar (true);
  9900. setIcon (lynx::logoImage());
  9901. content = new lynx::MainComponent (engine);
  9902. setContentOwned (content, true);
  9903. setResizable (true, true);
  9904. setResizeLimits (800, 400, 10000, 10000);
  9905. // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
  9906. // display: the AppImage catalog test runs on an 800x600 screen)
  9907. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  9908. {
  9909. const auto area = display->userArea;
  9910. const auto fit = [] (int design, int available) {
  9911. return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
  9912. };
  9913. setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
  9914. }
  9915. centreWithSize (getWidth(), getHeight());
  9916. // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
  9917. // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
  9918. const auto saved = stateFile().loadFileAsString().trim();
  9919. // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
  9920. const auto firstStart = saved.isEmpty()
  9921. && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
  9922. maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
  9923. if (saved.isNotEmpty())
  9924. restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
  9925. }
  9926. // Shows the window (built hidden while the splash screen is up).
  9927. void reveal()
  9928. {
  9929. if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
  9930. watchFrames ({});
  9931. setVisible (true);
  9932. lynx::applyWindowChrome (*this);
  9933. lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
  9934. if (maximiseOnReveal)
  9935. setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
  9936. toFront (true);
  9937. content->grabKeyboardFocus();
  9938. // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
  9939. // place and above it, once the window manager has placed this one
  9940. juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  9941. if (safe != nullptr)
  9942. safe->content->restoreDetachedWindows();
  9943. });
  9944. }
  9945. // The window's place and maximized state for the next start (main-window.txt in the settings folder).
  9946. void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
  9947. static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
  9948. void openFile (const juce::File& file) { content->openFile (file); }
  9949. lynx::MainComponent& getContent() { return *content; }
  9950. void showSetupWizard() { content->showSetupWizard(); }
  9951. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  9952. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  9953. // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
  9954. // counting when --uiperf watches too.
  9955. void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
  9956. {
  9957. if (probe == nullptr)
  9958. {
  9959. probe = std::make_unique<lynx::ui::FrameProbe>();
  9960. Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
  9961. probe->setBounds (getLocalBounds());
  9962. }
  9963. probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
  9964. if (lynx::uitrace::enabled())
  9965. lynx::uitrace::frame (now);
  9966. if (callback)
  9967. callback (now, area);
  9968. };
  9969. }
  9970. void resized() override
  9971. {
  9972. DocumentWindow::resized();
  9973. if (probe != nullptr)
  9974. probe->setBounds (getLocalBounds());
  9975. }
  9976. // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
  9977. std::function<void (double)> onFrame;
  9978. void paint (juce::Graphics& g) override
  9979. {
  9980. if (onFrame)
  9981. frameStart = juce::Time::getMillisecondCounterHiRes();
  9982. DocumentWindow::paint (g);
  9983. }
  9984. void paintOverChildren (juce::Graphics& g) override
  9985. {
  9986. DocumentWindow::paintOverChildren (g);
  9987. if (onFrame && frameStart > 0.0)
  9988. onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
  9989. frameStart = 0.0;
  9990. }
  9991. private:
  9992. lynx::MainComponent* content = nullptr; // owned by the window
  9993. std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
  9994. double frameStart = 0.0;
  9995. bool maximiseOnReveal = false;
  9996. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  9997. };
  9998. lynx::theme::LookAndFeel lookAndFeel;
  9999. std::unique_ptr<lynx::AudioEngine> engine;
  10000. std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
  10001. // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
  10002. // without registering it, listed as the driver type "ASIO driver file". True when one was added.
  10003. bool addDriverFileDeviceType()
  10004. {
  10005. const auto args = juce::JUCEApplication::getCommandLineParameterArray();
  10006. const auto i = args.indexOf ("--asiodll");
  10007. if (i < 0 || i + 1 >= args.size() || engine == nullptr)
  10008. return false;
  10009. auto& devices = engine->getDeviceManager();
  10010. devices.getAvailableDeviceTypes(); // creates the standard types first
  10011. for (auto* t : devices.getAvailableDeviceTypes())
  10012. if (t->getTypeName() == lynx::dllAsioTypeName)
  10013. return true;
  10014. auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
  10015. if (type == nullptr)
  10016. return false;
  10017. devices.addAudioDeviceType (std::move (type));
  10018. return true;
  10019. }
  10020. void restoreSavedDeviceState()
  10021. {
  10022. if (engine != nullptr)
  10023. engine->restoreAudioDeviceState (savedDeviceState.get());
  10024. }
  10025. std::unique_ptr<MainWindow> mainWindow;
  10026. std::unique_ptr<juce::Timer> perf; // --uiperf
  10027. std::unique_ptr<lynx::SplashScreen> splash;
  10028. double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
  10029. lynx::StartupOptions startupOptions;
  10030. juce::File fileToOpen;
  10031. juce::File openTimeReport; // --opentime
  10032. int openTimeIdleSeconds = 10;
  10033. };
  10034. START_JUCE_APPLICATION (LynxApplication)