Main.cpp 881 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640
  1. #include <juce_gui_basics/juce_gui_basics.h>
  2. #include "engine/FileSort.h"
  3. #include "platform/Paths.h"
  4. #include "core/KeyGuess.h"
  5. #include "core/FlSamplers.h"
  6. #include "core/PlaylistOps.h"
  7. #include "core/Comping.h"
  8. #include "core/Drumaxx.h"
  9. #include "core/PatternBlocks.h"
  10. #include "core/LoadTrace.h"
  11. #include "core/ProjectSafety.h"
  12. #include "core/Patcher.h"
  13. #include "core/Rack.h"
  14. #include "ui/RackEditor.h"
  15. #include "core/Patcherize.h"
  16. #include "core/Performance.h"
  17. #include "core/VideoPlayer.h"
  18. #include "core/Effects.h"
  19. #include "core/MixSuite.h"
  20. #include "core/HardwareInsert.h"
  21. #include "core/EchoSuite.h"
  22. #include "core/LynxTune.h"
  23. #include "core/FlEffects.h"
  24. #include "core/FlpImport.h"
  25. #include "core/NoteEdit.h"
  26. #include "core/MaximusFx.h"
  27. #include "core/MasterLooks.h"
  28. #include "core/Harmor.h"
  29. #include "flp/Flp.h"
  30. #include "core/SynthPresets.h"
  31. #include "core/FlWrapper.h"
  32. #include "engine/AudioEngine.h"
  33. #include "engine/PreviewPlayer.h"
  34. #include "engine/Metronome.h"
  35. #include "engine/AudioLogger.h"
  36. #include "engine/DllAsioDevice.h"
  37. #include "engine/PipeWireDevice.h"
  38. #include "platform/LinuxRealtime.h"
  39. #include "engine/Exporter.h"
  40. #include "engine/FlStudioExport.h"
  41. #include "engine/MidiFileIo.h"
  42. #include "engine/PluginHost.h"
  43. #include "engine/PluginSandbox.h"
  44. #include "engine/Bridge32Test.h"
  45. #include "engine/ClapFormat.h"
  46. #include "engine/ClapTeardownTest.h"
  47. #include "engine/ProjectFile.h"
  48. #include "core/Sha256.h"
  49. #include "engine/SessionPack.h"
  50. #include "engine/LiveTest.h"
  51. #include "engine/ShortExportTest.h"
  52. #include "core/SessionIds.h"
  53. #include "core/SessionParts.h"
  54. #include "engine/SampleLibrary.h"
  55. #include "engine/Text.h"
  56. #include "platform/FileTypes.h"
  57. #include "platform/Package.h"
  58. #include "core/AlsImport.h"
  59. #include "core/PianoRollScript.h"
  60. #include "ui/ScriptPanel.h"
  61. #include "ui/AlsExportDialog.h"
  62. #include "ui/LiveRemoteUi.h"
  63. #include "ui/GamepadInput.h"
  64. #include "ui/SettingsPages.h"
  65. #include "ui/OtherAppsExport.h"
  66. #include "ui/TimerWhileShowing.h"
  67. #include "ui/MixerBasicsCheck.h"
  68. #include "ui/VideoPlayerView.h"
  69. #include "ui/VideoMedia.h"
  70. #include "ui/VideoTracks.h"
  71. #include "ui/AdrWindow.h"
  72. #include "ui/PlaylistComponent.h"
  73. #include "ui/PatternBlocksView.h"
  74. #include "ui/PatcherEditor.h"
  75. #include "ui/VisualEditors.h"
  76. #include "ui/FlExtraEditors.h"
  77. #include "ui/VisualGl.h"
  78. #include "ui/DanceView.h"
  79. #include "ui/PluginPresetMenu.h"
  80. #include "ui/PluginWindow.h"
  81. #include "ui/Motion.h"
  82. #include "ui/NativeChild.h"
  83. #include "ui/Workspace.h"
  84. #include "ui/PluginThumbs.h"
  85. #include "ui/ClipProperties.h"
  86. #include "ui/NewProjectDialog.h"
  87. #include "ui/PluginMonitorWindow.h"
  88. #include "ui/TouchKeyboard.h"
  89. #include "ui/AutomationUi.h"
  90. #include "ui/PluginSkin.h"
  91. #include "ui/ChannelSettings.h"
  92. #include "ui/FlVoicePanel.h"
  93. #include "ui/SlicexEditor.h"
  94. #include "core/LynxBanks.h"
  95. #include "core/NativeEngines.h"
  96. #include "ui/ControllerEditors.h"
  97. #include "ui/NewtoneEditor.h"
  98. #include "core/NewtoneFx.h"
  99. #include "core/FormulaController.h"
  100. #include "core/MidiControls.h"
  101. #include "core/FlSynths.h"
  102. #include "core/SoundFont.h"
  103. #include "core/Sfz.h"
  104. #include "core/Slicex.h"
  105. #include "ui/Dialogs.h"
  106. #include "ui/FileChoosers.h"
  107. #include "ui/TrackIcons.h"
  108. #include "core/RackOps.h"
  109. #include "core/Layer.h"
  110. #include "core/XyController.h"
  111. #include "core/FlCurve.h"
  112. #include "core/ControlSurface.h"
  113. #include "core/VoltageController.h"
  114. #include "ui/Controllers164.h"
  115. #include "ui/ExportDialog.h"
  116. #include "ui/QuickAddPalette.h"
  117. #include "ui/I18n.h"
  118. #include "ui/MainComponent.h"
  119. #include "ui/MidiToolsPanel.h"
  120. #include "ui/FrameProbe.h"
  121. #include "ui/UiTrace.h"
  122. #include "core/MixerOps.h"
  123. #include "ui/QuickPick.h"
  124. #include "core/NoteTools.h"
  125. #include "engine/ProjectPackage.h"
  126. #include "ui/SetupWizard.h"
  127. #include "engine/FlStudio.h"
  128. #include "ui/HistoryPanel.h"
  129. #include "ui/VersionsPanel.h"
  130. #include "ui/PluginsOffPanel.h"
  131. #include "ui/MissingFilesDialog.h"
  132. #include "ui/SettingsDialog.h"
  133. #include "ui/PluginManager.h"
  134. #include "ui/ShortcutManager.h"
  135. #include "ui/NoteToolDialogs.h"
  136. #include "ui/EventEditor.h"
  137. #include "ui/AudioEditor.h"
  138. #include "ui/TempoTapper.h"
  139. #include "core/EventEdit.h"
  140. #include "core/FacetEq.h"
  141. #include "ui/FacetEqEditor.h"
  142. #include "core/RackRenderer.h"
  143. #include "ui/ProEditors.h"
  144. #include "ui/ParametricEqEditor.h"
  145. #include "ui/PluginEditors.h"
  146. #include "core/PluginLayout.h"
  147. #include "core/EffectPresets.h"
  148. #include "core/Vfx.h"
  149. #include "core/TransistorBass.h"
  150. #include "ui/Splash.h"
  151. #include "ui/Theme.h"
  152. #include "ui/ThemeSettings.h"
  153. #include "ui/WaveformView.h"
  154. #include "ui/WindowOwner.h"
  155. #include "ui/PluginKeysTest.h"
  156. #include "ui/Toolbar.h"
  157. #include "ui/ToolWindow.h"
  158. #include "platform/CrashGuard.h"
  159. #include "ui/CrashReporter.h"
  160. #include "ui/Updater.h"
  161. #include "ui/StemExtract.h"
  162. #include "ui/AudioToMidi.h"
  163. #include <atomic>
  164. #include <chrono>
  165. #include <cstdio>
  166. #include <cstdlib>
  167. #include <mutex>
  168. #include <thread>
  169. namespace
  170. {
  171. lynx::AudioEngine* crashEngine = nullptr;
  172. // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
  173. // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
  174. struct StartupTrace
  175. {
  176. using clock = std::chrono::steady_clock;
  177. const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
  178. const bool on = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
  179. juce::String text;
  180. clock::time_point last = t0;
  181. double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
  182. void mark (const char* step)
  183. {
  184. if (! on)
  185. return;
  186. const auto now = clock::now();
  187. const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
  188. text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7) << " " << step << "\n";
  189. last = now;
  190. lynx::platform::settingsFile ("startup.log").replaceWithText (text);
  191. }
  192. };
  193. StartupTrace startupTrace;
  194. void startupMarkHook (const char* step) { startupTrace.mark (step); }
  195. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  196. void onCrash (void* exceptionPointers)
  197. {
  198. const auto folder = lynx::platform::settingsFile ("autosave");
  199. folder.createDirectory();
  200. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  201. // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
  202. // release LYNX.exe has no symbols, so its own frames were missing from the file)
  203. folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
  204. + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
  205. lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
  206. if (crashEngine != nullptr)
  207. {
  208. juce::String error;
  209. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  210. }
  211. }
  212. juce::File sessionsFolder()
  213. {
  214. return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
  215. }
  216. // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
  217. // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
  218. juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
  219. juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
  220. // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
  221. // whether its crash file blames a graphics driver
  222. struct UncleanCause
  223. {
  224. juce::String editorPlugin; // the last steps were that plugin's editor
  225. bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
  226. juce::String driverModule;
  227. };
  228. UncleanCause uncleanCause()
  229. {
  230. UncleanCause cause;
  231. juce::File crashFile;
  232. for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
  233. {
  234. const auto& step = uncleanSteps[i];
  235. if (step.startsWith ("crashed: backtrace in "))
  236. crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
  237. for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
  238. if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
  239. cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
  240. if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
  241. break; // older steps than these did not end the session
  242. }
  243. // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
  244. // likely cause when the session then ended without a word: offer it a separate process too
  245. for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
  246. if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
  247. cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
  248. if (crashFile.existsAsFile())
  249. {
  250. // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
  251. auto text = crashFile.loadFileAsString();
  252. if (text.contains ("--- frames"))
  253. text = text.fromFirstOccurrenceOf ("--- frames", false, false);
  254. auto lines = juce::StringArray::fromLines (text);
  255. int looked = 0;
  256. for (const auto& line : lines)
  257. {
  258. const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
  259. if (module.isEmpty() || ! module.endsWith (".dll"))
  260. continue;
  261. if (++looked > 12)
  262. break;
  263. for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
  264. "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
  265. if (module.startsWith (driver))
  266. {
  267. cause.gpuDriver = true;
  268. cause.driverModule = module;
  269. break;
  270. }
  271. if (cause.gpuDriver)
  272. break;
  273. }
  274. }
  275. return cause;
  276. }
  277. juce::String collectUncleanSessions()
  278. {
  279. juce::String lastStep;
  280. juce::Time newest;
  281. for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
  282. {
  283. const auto text = file.loadFileAsString();
  284. juce::StringPairArray values;
  285. juce::StringArray steps;
  286. for (const auto& line : juce::StringArray::fromLines (text))
  287. {
  288. if (line.startsWith ("step="))
  289. steps.add (line.fromFirstOccurrenceOf ("=", false, false));
  290. else if (line.contains ("="))
  291. values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
  292. }
  293. const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
  294. const auto start = (std::uint64_t) values["start"].getLargeIntValue();
  295. if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
  296. continue; // this run, or another LYNX window still open
  297. lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
  298. .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
  299. file.deleteFile();
  300. if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
  301. {
  302. newest = modified;
  303. lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
  304. uncleanSessionText = text;
  305. uncleanSteps.clear();
  306. for (const auto& step : steps)
  307. uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
  308. }
  309. }
  310. return lastStep;
  311. }
  312. } // namespace
  313. // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
  314. // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
  315. // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
  316. // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
  317. // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
  318. // the mouse is released.
  319. struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
  320. private juce::HighResolutionTimer
  321. {
  322. ~UiPerfDrag() override { stopTimer(); }
  323. void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
  324. {
  325. window = &windowIn;
  326. engine = engineIn;
  327. track = trackIn;
  328. railInWindow = window->getLocalArea (&strips, rail);
  329. watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
  330. visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
  331. const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
  332. x = (float) railInWindow.getCentreX();
  333. startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
  334. amplitude = 0.4f * (float) railInWindow.getHeight();
  335. centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
  336. t0 = juce::Time::getMillisecondCounterHiRes();
  337. inject (x, startY, false);
  338. juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  339. inject (x, startY, true);
  340. active = true;
  341. startTimer (8);
  342. }
  343. // message thread
  344. void framePainted (double now, juce::Rectangle<int> area)
  345. {
  346. if (pending.empty() || ! area.intersects (watch))
  347. return;
  348. for (const auto t : pending)
  349. latencies.push_back (now - t);
  350. pending.clear();
  351. ++framesOverFader;
  352. }
  353. // the moves end; as in the reporter's clip, the song is stopped while the button is still down
  354. juce::String stop()
  355. {
  356. stopTimer();
  357. active = false;
  358. valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
  359. engine->stop();
  360. juce::String text;
  361. text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
  362. << " folded into the next (the message thread still busy with the previous one)\n"
  363. << " move waited for the message thread: " << describe (queueDelays) << "\n"
  364. << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
  365. << " frames over the fader\n";
  366. return text;
  367. }
  368. juce::String release()
  369. {
  370. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  371. juce::ModifierKeys::currentModifiers = {};
  372. inject (x, lastY, false);
  373. return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
  374. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  375. }
  376. juce::String released() const
  377. {
  378. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  379. return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
  380. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  381. }
  382. private:
  383. juce::Component* window = nullptr;
  384. lynx::AudioEngine* engine = nullptr;
  385. int track = 1;
  386. juce::Rectangle<int> railInWindow, watch;
  387. bool visible = false;
  388. float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
  389. double t0 = 0.0;
  390. std::atomic<bool> active { false }, posted { false };
  391. std::atomic<int> dropped { 0 };
  392. int moves = 0, framesOverFader = 0;
  393. float valueAtRelease = 0.0f;
  394. std::vector<double> pending, latencies, queueDelays;
  395. static juce::String describe (std::vector<double> v)
  396. {
  397. if (v.empty())
  398. return "none";
  399. std::sort (v.begin(), v.end());
  400. const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
  401. return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
  402. + juce::String (v.back(), 1) + " ms";
  403. }
  404. void inject (float px, float py, bool down)
  405. {
  406. lastY = py;
  407. if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
  408. {
  409. const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
  410. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
  411. down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
  412. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
  413. juce::Time::currentTimeMillis());
  414. }
  415. }
  416. void hiResTimerCallback() override
  417. {
  418. if (! active.load())
  419. return;
  420. if (posted.exchange (true))
  421. {
  422. ++dropped;
  423. return;
  424. }
  425. const auto postedAt = juce::Time::getMillisecondCounterHiRes();
  426. juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
  427. self->posted = false;
  428. if (! self->active.load())
  429. return;
  430. const auto now = juce::Time::getMillisecondCounterHiRes();
  431. self->queueDelays.push_back (now - postedAt);
  432. // up and down ~1.3 times a second, like the reporter's hand
  433. const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
  434. self->inject (self->x, y, true);
  435. self->pending.push_back (postedAt);
  436. ++self->moves;
  437. });
  438. }
  439. };
  440. class LynxApplication final : public juce::JUCEApplication
  441. {
  442. public:
  443. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  444. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  445. // the plugin scan runs copies of LYNX as child processes
  446. bool moreThanOneInstanceAllowed() override { return true; }
  447. // A file handed to the running application. macOS does this for every Finder double-click, "Open With" and Dock drop,
  448. // also the one that starts LYNX (its argv has no file). On Windows and Linux a second start is a second process
  449. // (moreThanOneInstanceAllowed) with the file as an argument, so this is not called there. Only the first file of a
  450. // multiple selection opens: a project replaces the one before it. (D#92, round 180a)
  451. void anotherInstanceStarted (const juce::String& commandLine) override
  452. {
  453. const auto files = lynx::safety::filesInCommandLine (commandLine.toStdString());
  454. if (files.empty())
  455. return;
  456. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (files.front().c_str()));
  457. if (! startupFileHandled) // still starting: openStartupFile takes it, nothing to ask about yet
  458. {
  459. fileToOpen = file;
  460. return;
  461. }
  462. if (mainWindow != nullptr)
  463. {
  464. mainWindow->toFront (true);
  465. mainWindow->getContent().openFileRequest (file);
  466. }
  467. }
  468. void initialise (const juce::String& commandLine) override
  469. {
  470. // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
  471. if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
  472. {
  473. updateHelper = true;
  474. quit();
  475. return;
  476. }
  477. // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
  478. if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
  479. {
  480. relaunched = true;
  481. setApplicationReturnValue (code);
  482. quit();
  483. return;
  484. }
  485. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
  486. juce::SystemStats::setApplicationCrashHandler (onCrash);
  487. lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
  488. // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
  489. lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
  490. juce::AudioFormatManager formats;
  491. formats.registerBasicFormats();
  492. std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
  493. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
  494. return false;
  495. const auto frames = (int) reader->lengthInSamples;
  496. juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
  497. if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
  498. return false;
  499. out.channels.clear();
  500. for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
  501. out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
  502. out.sampleRate = reader->sampleRate;
  503. out.loopStart = out.loopEnd = -1;
  504. return true;
  505. });
  506. // child process of a sandboxed plugin: no window or audio of its own
  507. if (lynx::runPluginSandboxWorker (commandLine))
  508. {
  509. lynx::crashguard::quietCrashReports();
  510. sandboxChild = true;
  511. return;
  512. }
  513. const auto args = juce::StringArray::fromTokens (commandLine, true);
  514. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  515. lynx::i18n::initialise (args);
  516. // interface font: saved in Settings › General; --uifont "Name" overrides it for this run
  517. const auto uiFontArg = args.indexOf ("--uifont");
  518. lookAndFeel.applyInterfaceFont (lynx::i18n::current(), uiFontArg >= 0 ? args[uiFontArg + 1].unquoted() : juce::String());
  519. if (args.contains ("--showcase"))
  520. {
  521. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  522. const auto i = args.indexOf ("--showcase");
  523. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  524. return;
  525. }
  526. if (args.contains ("--sandboxtest"))
  527. {
  528. const auto i = args.indexOf ("--sandboxtest");
  529. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  530. return;
  531. }
  532. if (args.contains ("--bridge32test"))
  533. {
  534. // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
  535. // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
  536. const auto i = args.indexOf ("--bridge32test");
  537. const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
  538. setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
  539. quit();
  540. return;
  541. }
  542. if (args.contains ("--rtstress"))
  543. {
  544. // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
  545. // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
  546. // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
  547. // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
  548. const auto i = args.indexOf ("--rtstress");
  549. const auto seconds = args[i + 3].getDoubleValue();
  550. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  551. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  552. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  553. runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
  554. option ("--type"), option ("--device"), option ("--record"));
  555. return;
  556. }
  557. if (args.contains ("--cliplooptest"))
  558. {
  559. // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
  560. // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
  561. // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
  562. // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
  563. // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
  564. const auto i = args.indexOf ("--cliplooptest");
  565. runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
  566. return;
  567. }
  568. if (args.contains ("--devicechangetest"))
  569. {
  570. // LYNX --devicechangetest report.txt [switches] [--plugin file]... (round 190c, issue #134: changing the
  571. // output device with a project open crashed LYNX). The engine plays a project of every instrument and effect
  572. // it can make here on stand-in devices with real callback threads, while the output device, its sample
  573. // rate and its buffer size change the way Settings > Audio changes them (8 kHz mono to 192 kHz, buffers of
  574. // 32 to 16384 samples, a device plugged in, the open one unplugged, one that refuses to open). After every
  575. // change the song must sound, finite, at the new rate. No window, no real audio or MIDI device.
  576. const auto i = args.indexOf ("--devicechangetest");
  577. const juce::File report (args[i + 1].unquoted());
  578. const auto switches = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  579. juce::StringArray plugins;
  580. for (int k = 0; k + 1 < args.size(); ++k)
  581. if (args[k] == "--plugin")
  582. plugins.add (args[k + 1].unquoted());
  583. auto text = std::make_shared<juce::String>();
  584. // --quick: the selftest's handful of instruments and effects instead of every one
  585. const auto result = lynx::AudioEngine::deviceChangeSelfTest (switches > 0 ? switches : 40, ! args.contains ("--quick"), plugins, [report, text] (const juce::String& line) {
  586. *text << line << "\n";
  587. report.replaceWithText (*text + "(running)\n"); // what was reached, if it crashes
  588. });
  589. *text << "device_change=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  590. report.replaceWithText (*text);
  591. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  592. quit();
  593. return;
  594. }
  595. if (args.contains ("--shortexporttest"))
  596. {
  597. // LYNX --shortexporttest report.txt [repeats] [--plugin file]... (round 190c, issue #138: a short note at
  598. // the very start of the Playlist exported quiet). Every instrument LYNX can make here, and a synth with
  599. // effects, tail modes, normalising and other rates, exported through the Export window's path (the job
  600. // made on the message thread, run on its own thread, the message loop running) with a 2-second note at
  601. // tick 0 and again with it at bar 2: the note must come out the same. No window.
  602. const auto i = args.indexOf ("--shortexporttest");
  603. const juce::File report (args[i + 1].unquoted());
  604. const auto repeats = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  605. juce::StringArray plugins;
  606. for (int k = 0; k + 1 < args.size(); ++k)
  607. if (args[k] == "--plugin")
  608. plugins.add (args[k + 1].unquoted());
  609. auto text = std::make_shared<juce::String>();
  610. lynx::shortexport::run (true, repeats > 0 ? repeats : 3, plugins,
  611. [report, text] (const juce::String& line) {
  612. *text << line << "\n";
  613. report.replaceWithText (*text + "(running)\n");
  614. },
  615. [this, report, text] (juce::String result) {
  616. *text << "short_export=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  617. report.replaceWithText (*text);
  618. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  619. quit();
  620. });
  621. return;
  622. }
  623. if (args.contains ("--slicexedittest"))
  624. {
  625. // LYNX --slicexedittest project script.txt report.txt [png-prefix] (round 190aj): the Slicex editor of the
  626. // project's first Slicex channel, off screen, driven by the script's commands (ui/SlicexEditor.h; mouse
  627. // gestures at fractions of the deck's width, the menu entries, shortcuts). The report holds each command
  628. // and what the state held after it; "shot <name>" writes <png-prefix><name>.png.
  629. const auto i = args.indexOf ("--slicexedittest");
  630. runSlicexEditTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  631. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  632. return;
  633. }
  634. if (args.contains ("--slicexkeytest"))
  635. {
  636. // LYNX --slicexkeytest report.txt (round 190ac): what a click on the Slicex editor's keyboard sends
  637. // (AudioEngine::sendLiveNote on the channel, velocity 100/128) through the real engine's device callback
  638. // (a stand-in device, driven block by block): the key's region must sound, on the channel's mixer meter
  639. // too, another key must play another region, and the note-off must end it.
  640. runSlicexKeyTest (juce::File (args[args.indexOf ("--slicexkeytest") + 1].unquoted()));
  641. return;
  642. }
  643. if (args.contains ("--countinrectest"))
  644. {
  645. // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
  646. // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
  647. // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
  648. // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
  649. // 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
  650. // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
  651. const auto i = args.indexOf ("--countinrectest");
  652. runCountInRecordTest (juce::File (args[i + 1].unquoted()));
  653. return;
  654. }
  655. if (args.contains ("--bendrectest"))
  656. {
  657. // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
  658. // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
  659. // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
  660. // automation clip (song mode) of the channel's pitch bend must follow the sweep.
  661. const auto i = args.indexOf ("--bendrectest");
  662. const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
  663. runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
  664. return;
  665. }
  666. if (args.contains ("--rectest"))
  667. {
  668. // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
  669. // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
  670. // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
  671. // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
  672. // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
  673. // and 1 of post-roll (playback stops by itself after the post-roll).
  674. const auto i = args.indexOf ("--rectest");
  675. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  676. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  677. runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
  678. args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
  679. return;
  680. }
  681. if (args.contains ("--hwinserttest"))
  682. {
  683. // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
  684. // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
  685. // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
  686. // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
  687. // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
  688. // sample as the right side's.
  689. const auto i = args.indexOf ("--hwinserttest");
  690. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  691. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
  692. // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
  693. // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
  694. runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
  695. option ("--buffer").getIntValue(), args.contains ("--patcher"),
  696. args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
  697. return;
  698. }
  699. if (args.contains ("--uiperf"))
  700. {
  701. // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
  702. const auto i = args.indexOf ("--uiperf");
  703. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  704. runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  705. return;
  706. }
  707. if (args.contains ("--cachetest"))
  708. {
  709. // LYNX --cachetest project.(flp|lynx) report.txt (round 174f): the Playlist's cached picture against exact
  710. // paints after zooms, scrolls and repaints, off screen (no window)
  711. const auto i = args.indexOf ("--cachetest");
  712. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  713. runCacheTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  714. return;
  715. }
  716. if (args.contains ("--timertest"))
  717. {
  718. // LYNX --timertest report.txt (round 174f): ui::TimerWhileShowing through hide / show / minimise (opens a small window)
  719. runTimerTest (juce::File (args[args.indexOf ("--timertest") + 1].unquoted()));
  720. return;
  721. }
  722. if (args.contains ("--livepeer"))
  723. {
  724. // LYNX --livepeer host|guest|rejoin <folder> [--relay URL] [--code CODE|@file]: one computer's side of a live
  725. // session between two real computers, no window (round 190ah)
  726. setApplicationReturnValue (lynx::livetest::runPeer (args));
  727. quit();
  728. return;
  729. }
  730. if (args.contains ("--livetest"))
  731. {
  732. // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
  733. setApplicationReturnValue (lynx::livetest::run (args));
  734. quit();
  735. return;
  736. }
  737. if (args.contains ("--selftest"))
  738. {
  739. const auto i = args.indexOf ("--selftest");
  740. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  741. return;
  742. }
  743. if (args.contains ("--scan-one"))
  744. {
  745. // child process of the plugin scan (see PluginHost::scan)
  746. const auto i = args.indexOf ("--scan-one");
  747. // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
  748. // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
  749. // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
  750. lynx::crashguard::quietCrashReports();
  751. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  752. lynx::crashguard::exitNow (0);
  753. }
  754. if (args.contains ("--packageinfo"))
  755. {
  756. // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
  757. // workflow runs it inside the installed test package
  758. juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
  759. quit();
  760. return;
  761. }
  762. if (args.contains ("--paths"))
  763. {
  764. // diagnostics: folders LYNX searches
  765. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  766. juce::String report;
  767. report << "programs=" << programs.getFullPathName() << "\n";
  768. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  769. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  770. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  771. quit();
  772. return;
  773. }
  774. if (args.contains ("--fldb"))
  775. {
  776. // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
  777. // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
  778. const auto i = args.indexOf ("--fldb");
  779. const auto fl = lynx::findFlStudio();
  780. lynx::PluginHost host (false);
  781. juce::String report;
  782. report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
  783. for (const auto& f : fl.vstFolders)
  784. report << "flvstfolder=" << f << "\n";
  785. report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
  786. for (const auto& e : host.flPluginDatabase().entries())
  787. report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
  788. const auto suggested = host.suggestedFolders();
  789. for (int k = 0; k < suggested.getNumPaths(); ++k)
  790. report << "folder=" << suggested[k].getFullPathName() << "\n";
  791. if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
  792. {
  793. juce::MemoryBlock data;
  794. project.loadFileAsData (data);
  795. try
  796. {
  797. for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
  798. {
  799. juce::String how;
  800. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  801. const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
  802. report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  803. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
  804. << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
  805. }
  806. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  807. const auto candidates = host.filesToScanFor (uses);
  808. report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
  809. if (args.contains ("--scan"))
  810. {
  811. // the targeted scan an open would run (child processes; the user's plugin list is not touched)
  812. report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
  813. for (const auto& use : uses)
  814. {
  815. juce::String how;
  816. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  817. report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  818. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
  819. }
  820. }
  821. }
  822. catch (const flp::Error& e)
  823. {
  824. report << "error=" << e.what() << "\n";
  825. }
  826. }
  827. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  828. quit();
  829. return;
  830. }
  831. if (args.contains ("--midisync-test"))
  832. {
  833. // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
  834. const auto i = args.indexOf ("--midisync-test");
  835. const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  836. const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  837. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
  838. quit();
  839. return;
  840. }
  841. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  842. {
  843. // diagnostics: driver types and output devices JUCE offers (without opening any)
  844. juce::AudioDeviceManager manager;
  845. juce::String report;
  846. manager.getAvailableDeviceTypes();
  847. if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
  848. manager.addAudioDeviceType (std::move (pipeWire));
  849. #if JUCE_LINUX
  850. report << lynx::describePipeWire() << "\n";
  851. #endif
  852. for (auto* type : manager.getAvailableDeviceTypes())
  853. {
  854. type->scanForDevices();
  855. report << "type=" << type->getTypeName() << "\n";
  856. for (const auto& name : type->getDeviceNames (false))
  857. report << " output=" << name << "\n";
  858. for (const auto& name : type->getDeviceNames (true))
  859. report << " input=" << name << "\n";
  860. }
  861. for (const auto& d : juce::MidiInput::getAvailableDevices())
  862. report << "midi-in=" << d.name << "\n";
  863. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  864. report << "midi-out=" << d.name << "\n";
  865. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  866. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  867. quit();
  868. return;
  869. }
  870. if (args.contains ("--devicetest"))
  871. {
  872. // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
  873. // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
  874. // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
  875. // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
  876. // cable / PipeWire link: the round-trip latency (3 s)
  877. const auto i = args.indexOf ("--devicetest");
  878. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  879. auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
  880. const auto wantInput = inputName.isNotEmpty();
  881. juce::String report;
  882. const juce::File reportFile (args[i + 3].unquoted());
  883. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  884. step ("step=start");
  885. juce::AudioDeviceManager manager;
  886. manager.getAvailableDeviceTypes();
  887. if (auto pipeWire = lynx::makePipeWireDeviceType())
  888. manager.addAudioDeviceType (std::move (pipeWire));
  889. std::unique_ptr<juce::AudioIODevice> device;
  890. for (auto* type : manager.getAvailableDeviceTypes())
  891. if (type->getTypeName() == typeName)
  892. {
  893. type->scanForDevices();
  894. if (wantInput && type->hasSeparateInputsAndOutputs())
  895. {
  896. const auto inputs = type->getDeviceNames (true);
  897. if (inputName == "*" || ! inputs.contains (inputName))
  898. {
  899. const auto index = type->getDefaultDeviceIndex (true);
  900. inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  901. }
  902. for (const auto& n : inputs)
  903. step ("input_device=" + n);
  904. step ("input_chosen=" + inputName);
  905. }
  906. else if (wantInput)
  907. inputName = deviceName;
  908. step ("step=create");
  909. device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
  910. step ("step=created");
  911. }
  912. struct Silence final : juce::AudioIODeviceCallback
  913. {
  914. std::atomic<int> calls { 0 }, inputs { 0 };
  915. std::array<std::atomic<float>, 64> peaks {};
  916. // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
  917. // loopback; the delays in samples
  918. bool roundtrip = false;
  919. int period = 12000;
  920. std::int64_t position = 0, lastClick = -1;
  921. std::vector<int> delays;
  922. void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
  923. const juce::AudioIODeviceCallbackContext&) override
  924. {
  925. for (int c = 0; c < channels; ++c)
  926. if (out[c] != nullptr)
  927. juce::FloatVectorOperations::clear (out[c], n);
  928. if (roundtrip)
  929. {
  930. for (int i = 0; i < n; ++i)
  931. {
  932. if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
  933. {
  934. if (delays.size() < delays.capacity())
  935. delays.push_back ((int) (position + i - lastClick));
  936. lastClick = -1;
  937. }
  938. if ((position + i) % period == 0 && position + i > 0)
  939. {
  940. for (int c = 0; c < channels; ++c)
  941. if (out[c] != nullptr)
  942. out[c][i] = 0.9f;
  943. lastClick = position + i;
  944. }
  945. }
  946. position += n;
  947. }
  948. inputs.store (numIn);
  949. for (int c = 0; c < juce::jmin (numIn, 64); ++c)
  950. if (in[c] != nullptr)
  951. {
  952. const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
  953. const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
  954. if (peak > peaks[(std::size_t) c].load())
  955. peaks[(std::size_t) c].store (peak);
  956. }
  957. ++calls;
  958. }
  959. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  960. void audioDeviceStopped() override {}
  961. } silence;
  962. bool ok = false;
  963. if (device == nullptr)
  964. step ("error=device not found");
  965. else
  966. {
  967. step ("step=open");
  968. juce::BigInteger outputs;
  969. outputs.setRange (0, 2, true);
  970. const auto rates = device->getAvailableSampleRates();
  971. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  972. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  973. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  974. juce::BigInteger inputs;
  975. if (wantInput)
  976. {
  977. const auto names = device->getInputChannelNames();
  978. step ("input_channels=" + juce::String (names.size()));
  979. for (int c = 0; c < names.size(); ++c)
  980. step (" in" + juce::String (c + 1) + "=" + names[c]);
  981. inputs.setRange (0, juce::jmin (64, names.size()), true);
  982. }
  983. // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
  984. const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  985. const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
  986. if (error.isNotEmpty())
  987. step ("error=" + error);
  988. else
  989. {
  990. step ("step=start_callbacks");
  991. silence.roundtrip = args.contains ("--roundtrip");
  992. silence.period = juce::jmax (1, (int) (rate / 4));
  993. silence.delays.reserve (64);
  994. device->start (&silence);
  995. juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
  996. device->stop();
  997. if (silence.roundtrip)
  998. {
  999. auto d = silence.delays;
  1000. std::sort (d.begin(), d.end());
  1001. report << "roundtrip_clicks=" << (int) d.size() << "\n";
  1002. if (! d.empty())
  1003. report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
  1004. << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
  1005. }
  1006. report << "rate=" << device->getCurrentSampleRate() << "\n"
  1007. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  1008. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  1009. << "callbacks=" << silence.calls.load() << "\n";
  1010. if (wantInput)
  1011. {
  1012. report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
  1013. << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
  1014. << "callback_inputs=" << silence.inputs.load() << "\n";
  1015. for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
  1016. report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
  1017. }
  1018. ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
  1019. device->close();
  1020. }
  1021. }
  1022. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  1023. setApplicationReturnValue (ok ? 0 : 1);
  1024. quit();
  1025. return;
  1026. }
  1027. if (args.contains ("--scantest"))
  1028. {
  1029. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  1030. const auto i = args.indexOf ("--scantest");
  1031. lynx::PluginHost host (false);
  1032. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  1033. juce::String report;
  1034. report << "found=" << found << "\n";
  1035. for (const auto& t : host.getKnownPlugins().getTypes())
  1036. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  1037. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  1038. report << " blacklisted: " << f << "\n";
  1039. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  1040. setApplicationReturnValue (found > 0 ? 0 : 1);
  1041. quit();
  1042. return;
  1043. }
  1044. if (args.contains ("--wrappermiditest"))
  1045. {
  1046. // LYNX.exe --wrappermiditest plugin.dll report.txt (round 181c), with LYNX_TEST_VST2_MIDILOG set: what a
  1047. // hosted plugin receives after a wrapper MIDI option changes while it runs
  1048. const auto i = args.indexOf ("--wrappermiditest");
  1049. runWrapperMidiTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1050. return;
  1051. }
  1052. if (args.contains ("--wrappershot"))
  1053. {
  1054. const auto i = args.indexOf ("--wrappershot");
  1055. runWrapperShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1056. return;
  1057. }
  1058. if (args.contains ("--multiouttest"))
  1059. {
  1060. const auto i = args.indexOf ("--multiouttest");
  1061. runMultiOutTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1062. return;
  1063. }
  1064. if (args.contains ("--vst2test"))
  1065. {
  1066. const auto i = args.indexOf ("--vst2test");
  1067. runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
  1068. return;
  1069. }
  1070. if (args.contains ("--lv2scantest"))
  1071. {
  1072. runLv2ScanTest (args[args.indexOf ("--lv2scantest") + 1].unquoted());
  1073. return;
  1074. }
  1075. if (args.contains ("--wrappertest"))
  1076. {
  1077. const auto i = args.indexOf ("--wrappertest");
  1078. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1079. return;
  1080. }
  1081. if (args.contains ("--plugintest"))
  1082. {
  1083. const auto i = args.indexOf ("--plugintest");
  1084. // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
  1085. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1086. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1087. return;
  1088. }
  1089. if (args.contains ("--claprestarttest"))
  1090. {
  1091. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
  1092. const auto i = args.indexOf ("--claprestarttest");
  1093. runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1094. return;
  1095. }
  1096. if (args.contains ("--clapteardowntest"))
  1097. {
  1098. // LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt (round 190az, engine/ClapTeardownTest.cpp)
  1099. const auto i = args.indexOf ("--clapteardowntest");
  1100. lynx::runClapTeardownTest (args[i + 1].unquoted(), args[i + 2].unquoted(), [this] (int code) {
  1101. setApplicationReturnValue (code);
  1102. quit();
  1103. });
  1104. return;
  1105. }
  1106. if (args.contains ("--mpetest"))
  1107. {
  1108. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108)
  1109. const auto i = args.indexOf ("--mpetest");
  1110. runMpeTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1111. return;
  1112. }
  1113. if (args.contains ("--editortest"))
  1114. {
  1115. // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
  1116. // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
  1117. const auto i = args.indexOf ("--editortest");
  1118. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1119. runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1120. return;
  1121. }
  1122. if (args.contains ("--editorcrashtest"))
  1123. {
  1124. // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
  1125. // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
  1126. // that editor, record the trace and keep running its message loop.
  1127. const auto i = args.indexOf ("--editorcrashtest");
  1128. runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1129. return;
  1130. }
  1131. if (args.contains ("--reloadtest"))
  1132. {
  1133. // LYNX --reloadtest plugin report.txt [shots folder] [--wait-kill]: round 190ao (reload a crashed plugin).
  1134. // Hosts the plugin in a separate process (a channel for an instrument, insert 1 for an effect) in an offline
  1135. // engine, crashes its process (--wait-kill: writes <report>.pid and waits for the process to be killed
  1136. // from outside), checks that nothing reloads by itself, reloads it on request and checks the new process,
  1137. // the state captured last, the untouched song and undo history; twice. With a shots folder: PNGs of the
  1138. // plugin window's crash notice and of the prompt.
  1139. const auto i = args.indexOf ("--reloadtest");
  1140. runReloadTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1141. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String(), args.contains ("--wait-kill"));
  1142. return;
  1143. }
  1144. if (args.contains ("--pluginoptionstest"))
  1145. {
  1146. // LYNX --pluginoptionstest plugin report.txt [shots folder]: round 190ao. Hosts the plugin inside LYNX (a
  1147. // channel for an instrument, insert 1 for an effect) in an offline engine, opens its window and checks
  1148. // LYNX's own plugin-window options: Pin on top (set, kept above another window, saved with the plugin,
  1149. // back when the window opens again). With a shots folder: PNGs of each state. The window is on screen.
  1150. const auto i = args.indexOf ("--pluginoptionstest");
  1151. runPluginOptionsTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1152. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String());
  1153. return;
  1154. }
  1155. if (args.contains ("--plugwintest"))
  1156. {
  1157. // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
  1158. // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
  1159. // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
  1160. // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
  1161. const auto i = args.indexOf ("--plugwintest");
  1162. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
  1163. auto seconds = 15;
  1164. for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
  1165. if (args[k].containsOnly ("0123456789"))
  1166. seconds = args[k].getIntValue();
  1167. runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
  1168. return;
  1169. }
  1170. if (args.contains ("--fittest"))
  1171. {
  1172. // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
  1173. // the screen and a big resizable window that grows with a zoom change keep their title bar and close
  1174. // button on the screen. The windows show for about two seconds.
  1175. const auto i = args.indexOf ("--fittest");
  1176. runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
  1177. return;
  1178. }
  1179. if (args.contains ("--windowtest"))
  1180. {
  1181. // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
  1182. // over the main window and checks that each one stays in front, owned by the main window, with the
  1183. // keyboard focus (issue #4). The windows appear on screen for a few seconds.
  1184. runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
  1185. return;
  1186. }
  1187. if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
  1188. {
  1189. const auto i = args.indexOf ("--pluginstyle");
  1190. if (i + 1 < args.size())
  1191. {
  1192. const auto name = args[i + 1].unquoted();
  1193. lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
  1194. }
  1195. }
  1196. if (args.contains ("--gfxprobe"))
  1197. {
  1198. // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
  1199. // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
  1200. // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
  1201. // "no clip" and flooded the whole component (Facet EQ's blank pink window).
  1202. const auto i = args.indexOf ("--gfxprobe");
  1203. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
  1204. quit();
  1205. return;
  1206. }
  1207. if (args.contains ("--steppertest"))
  1208. {
  1209. // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
  1210. // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
  1211. const auto i = args.indexOf ("--steppertest");
  1212. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1213. juce::String report;
  1214. int fails = 0, count = 0, skips = 0;
  1215. {
  1216. lynx::AudioEngine offline (false);
  1217. auto kinds = lynx::plugui::flLayoutKinds();
  1218. for (const auto own : lynx::plugui::ownLayoutKinds())
  1219. kinds.push_back (own);
  1220. // FL's Default preset when the installation has one (the state-backed controls need FL's state)
  1221. const auto roots = lynx::findFlStudioRoots();
  1222. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  1223. for (const auto kind : kinds)
  1224. {
  1225. auto fx = lynx::makeEffectSlot (kind);
  1226. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1227. {
  1228. juce::MemoryBlock data;
  1229. const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
  1230. if (file.existsAsFile() && file.loadFileAsData (data))
  1231. {
  1232. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  1233. if (auto loaded = lynx::effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), 130.0, lynx::natives::flDataReader (lynx::flStudioAccess())); loaded && loaded->kind == kind)
  1234. fx = *loaded;
  1235. }
  1236. break;
  1237. }
  1238. lynx::Song song;
  1239. song.mixer.resize (2);
  1240. song.mixer[0].name = "Master";
  1241. song.mixer[1].name = "Insert 1";
  1242. song.mixer[1].effects.push_back (fx);
  1243. offline.setSong (std::move (song));
  1244. offline.dispatchPendingMessages();
  1245. const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
  1246. for (const auto& line : juce::StringArray::fromLines (lines))
  1247. if (line.isNotEmpty())
  1248. {
  1249. ++count;
  1250. fails += line.contains (": FAIL") ? 1 : 0;
  1251. skips += line.contains (": SKIP") ? 1 : 0;
  1252. }
  1253. report << lines;
  1254. juce::PopupMenu::dismissAllActiveMenus();
  1255. offline.dispatchPendingMessages();
  1256. }
  1257. }
  1258. report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
  1259. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1260. quit();
  1261. return;
  1262. }
  1263. if (args.contains ("--plugui"))
  1264. {
  1265. // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
  1266. // loaded with the FL plugin's Default preset when the FL installation has one
  1267. const auto i = args.indexOf ("--plugui");
  1268. runPluginEditorSnapshots (args[i + 1].unquoted());
  1269. return;
  1270. }
  1271. if (args.contains ("--parityshot"))
  1272. {
  1273. // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
  1274. // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
  1275. // of the third-party parity pictures (round tp172b)
  1276. const auto i = args.indexOf ("--parityshot");
  1277. runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1278. if (parityShotFailed)
  1279. setApplicationReturnValue (2);
  1280. if (parityShow == nullptr)
  1281. quit();
  1282. return;
  1283. }
  1284. if (args.contains ("--design168rshot"))
  1285. {
  1286. // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
  1287. // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
  1288. // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
  1289. const auto i = args.indexOf ("--design168rshot");
  1290. if (i + 2 < args.size() && args[i + 2] == "generated")
  1291. lynx::plugui::showGeneratedLayoutsOnly (true);
  1292. runDesign168rShots (args[i + 1].unquoted());
  1293. quit();
  1294. return;
  1295. }
  1296. if (args.contains ("--eq166fshot"))
  1297. {
  1298. // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
  1299. // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
  1300. // its spectrum over the source's), each fed by the demo song rendered offline
  1301. const auto i = args.indexOf ("--eq166fshot");
  1302. runEq166fShots (args[i + 1].unquoted());
  1303. quit();
  1304. return;
  1305. }
  1306. if (args.contains ("--editorcpu"))
  1307. {
  1308. // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
  1309. // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
  1310. // animates (demo signal) — round 122's check that an idle editor burns no CPU
  1311. const auto i = args.indexOf ("--editorcpu");
  1312. runEditorCpu (args[i + 1].unquoted());
  1313. return;
  1314. }
  1315. if (args.contains ("--precomputeshot"))
  1316. {
  1317. // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
  1318. // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
  1319. const auto i = args.indexOf ("--precomputeshot");
  1320. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1321. lynx::AudioEngine shotEngine (false);
  1322. const juce::File input (args[i + 1].unquoted());
  1323. const auto prefix = args[i + 2].unquoted();
  1324. juce::String error;
  1325. bool ok = false;
  1326. if (input.hasFileExtension ("flp"))
  1327. ok = shotEngine.importFlpFile (input, error);
  1328. else if (auto song = lynx::ProjectFile::load (input, error))
  1329. shotEngine.setSong (std::move (*song)), ok = true;
  1330. shotEngine.dispatchPendingMessages();
  1331. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  1332. if (c == nullptr)
  1333. return false;
  1334. if (c->getWidth() <= 0)
  1335. c->setSize (520, 600);
  1336. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
  1337. return true;
  1338. };
  1339. ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
  1340. ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
  1341. setApplicationReturnValue (ok ? 0 : 1);
  1342. quit();
  1343. return;
  1344. }
  1345. if (args.contains ("--pluginthumbs"))
  1346. {
  1347. // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
  1348. // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
  1349. // the background when pictures are missing. One line per plugin on stdout.
  1350. const auto i = args.indexOf ("--pluginthumbs");
  1351. lynx::crashguard::quietCrashReports();
  1352. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1353. juce::StringArray only;
  1354. if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
  1355. only.addTokens (args[i + 2].unquoted(), ",", "");
  1356. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1357. const auto drawn = lynx::pluginthumbs::renderNative (juce::File (args[i + 1].unquoted()), only, [] (const juce::String& line) {
  1358. std::printf ("%s\n", line.toRawUTF8());
  1359. std::fflush (stdout);
  1360. });
  1361. std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
  1362. setApplicationReturnValue (0);
  1363. quit();
  1364. return;
  1365. }
  1366. if (args.contains ("--jsonroundtrip"))
  1367. {
  1368. // LYNX.exe --jsonroundtrip <folder>: round 183c's finding — a project saved, loaded and saved again: both texts
  1369. // (a.json, b.json) and the first lines that differ (diff.txt) for the default song, with and without a Patcher
  1370. const auto i = args.indexOf ("--jsonroundtrip");
  1371. const juce::File out (args[i + 1].unquoted());
  1372. out.createDirectory();
  1373. juce::String report;
  1374. auto check = [&] (const lynx::Song& song, const juce::String& name) {
  1375. const auto a = lynx::ProjectFile::toJson (song);
  1376. juce::String error;
  1377. const auto back = lynx::ProjectFile::fromJson (a, error);
  1378. const auto b = back ? lynx::ProjectFile::toJson (*back) : juce::String ("(not loaded: " + error + ")");
  1379. out.getChildFile (name + "-a.json").replaceWithText (a);
  1380. out.getChildFile (name + "-b.json").replaceWithText (b);
  1381. juce::StringArray la, lb;
  1382. la.addLines (a);
  1383. lb.addLines (b);
  1384. report << name << ": " << (a == b ? "stable" : "DIFFERS") << " (" << la.size() << " / " << lb.size() << " lines)\n";
  1385. int shown = 0;
  1386. for (int k = 0; k < juce::jmax (la.size(), lb.size()) && shown < 12; ++k)
  1387. if (la[k] != lb[k])
  1388. {
  1389. report << " line " << (k + 1) << "\n a: " << la[k].trim().substring (0, 200) << "\n b: " << lb[k].trim().substring (0, 200) << "\n";
  1390. ++shown;
  1391. }
  1392. };
  1393. auto song = lynx::Song::makeDefault();
  1394. check (song, "default");
  1395. song.mixer.resize (3);
  1396. song.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::patcher) };
  1397. check (song, "patcher");
  1398. song.mixer[1].effects = { lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect) };
  1399. check (song, "rack");
  1400. out.getChildFile ("diff.txt").replaceWithText (report);
  1401. setApplicationReturnValue (0);
  1402. quit();
  1403. return;
  1404. }
  1405. if (args.contains ("--rackshot"))
  1406. {
  1407. // LYNX.exe --rackshot <folder>: round 183c's Rack view drawn off-screen (no window), for the LYNX | Live pairs:
  1408. // rack-deviceview.png (an Audio Effect Rack laid out as in Live's reference shot), rack-mapmode.png (Map mode
  1409. // with the mapping list), rack-instrument.png (an Instrument Rack with its key zones)
  1410. const auto i = args.indexOf ("--rackshot");
  1411. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1412. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1413. setApplicationReturnValue (runRackShots (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
  1414. quit();
  1415. return;
  1416. }
  1417. if (args.contains ("--artshot"))
  1418. {
  1419. // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
  1420. // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
  1421. // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
  1422. const auto i = args.indexOf ("--artshot");
  1423. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1424. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1425. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1426. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1427. setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
  1428. quit();
  1429. return;
  1430. }
  1431. if (args.contains ("--artgui"))
  1432. {
  1433. // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
  1434. // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
  1435. // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
  1436. // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
  1437. const auto i = args.indexOf ("--artgui");
  1438. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1439. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1440. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1441. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1442. runArtGui (juce::File (args[i + 1].unquoted()), mode);
  1443. return;
  1444. }
  1445. if (args.contains ("--instrumentshot"))
  1446. {
  1447. // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
  1448. // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
  1449. // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
  1450. const auto i = args.indexOf ("--instrumentshot");
  1451. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1452. const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
  1453. setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
  1454. quit();
  1455. return;
  1456. }
  1457. if (args.contains ("--flextrashot"))
  1458. {
  1459. // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
  1460. const auto i = args.indexOf ("--flextrashot");
  1461. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1462. lynx::AudioEngine shotEngine (false);
  1463. const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
  1464. setApplicationReturnValue (ok ? 0 : 1);
  1465. quit();
  1466. return;
  1467. }
  1468. if (args.contains ("--visualtest"))
  1469. {
  1470. // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
  1471. // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
  1472. // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
  1473. const auto i = args.indexOf ("--visualtest");
  1474. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1475. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
  1476. lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
  1477. setApplicationReturnValue (ok ? 0 : 1);
  1478. quit();
  1479. });
  1480. return;
  1481. }
  1482. if (args.contains ("--menu-entry"))
  1483. {
  1484. // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
  1485. // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
  1486. const auto i = args.indexOf ("--menu-entry");
  1487. const auto on = args[i + 1].unquoted() != "off";
  1488. const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
  1489. std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
  1490. : "only the LYNX SHARE AppImage on Linux can do this");
  1491. setApplicationReturnValue (ok ? 0 : 1);
  1492. quit();
  1493. return;
  1494. }
  1495. if (args.contains ("--send-test-report"))
  1496. {
  1497. // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
  1498. // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
  1499. // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
  1500. const auto i = args.indexOf ("--send-test-report");
  1501. const juce::File out (args[i + 1].unquoted());
  1502. lynx::crashreporter::Session session;
  1503. session.version = getApplicationVersion();
  1504. for (const auto* pattern : { "crash *.txt", "hang *.txt" })
  1505. {
  1506. auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
  1507. lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
  1508. if (! files.isEmpty())
  1509. (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
  1510. }
  1511. session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
  1512. auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
  1513. input.test = true;
  1514. const auto json = lynx::crashreporter::buildJson (input, false);
  1515. out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
  1516. const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
  1517. out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
  1518. + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
  1519. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  1520. quit();
  1521. return;
  1522. }
  1523. if (args.contains ("--symbolize"))
  1524. {
  1525. // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
  1526. // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
  1527. const auto i = args.indexOf ("--symbolize");
  1528. const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
  1529. juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
  1530. quit();
  1531. return;
  1532. }
  1533. if (args.contains ("--opentest"))
  1534. {
  1535. // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
  1536. // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
  1537. // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
  1538. const auto i = args.indexOf ("--opentest");
  1539. runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
  1540. setApplicationReturnValue (ok ? 0 : 1);
  1541. quit();
  1542. });
  1543. return;
  1544. }
  1545. if (args.contains ("--fxfuzz"))
  1546. {
  1547. // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
  1548. // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
  1549. const auto i = args.indexOf ("--fxfuzz");
  1550. const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
  1551. // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
  1552. const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
  1553. setApplicationReturnValue (ok ? 0 : 1);
  1554. quit();
  1555. return;
  1556. }
  1557. if (args.contains ("--controllershot"))
  1558. {
  1559. // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
  1560. const auto i = args.indexOf ("--controllershot");
  1561. runControllerShot (args[i + 1].unquoted());
  1562. quit();
  1563. return;
  1564. }
  1565. if (args.contains ("--edisonshot"))
  1566. {
  1567. // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
  1568. // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
  1569. const auto i = args.indexOf ("--edisonshot");
  1570. runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1571. quit();
  1572. return;
  1573. }
  1574. if (args.contains ("--danceshot"))
  1575. {
  1576. // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
  1577. // and a demo project with two dance channels (for --snapshot)
  1578. const auto i = args.indexOf ("--danceshot");
  1579. runDanceShot (args[i + 1].unquoted());
  1580. quit();
  1581. return;
  1582. }
  1583. if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
  1584. {
  1585. // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
  1586. // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
  1587. const auto i = args.indexOf ("--videoshot");
  1588. runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1589. return;
  1590. }
  1591. if (args.contains ("--videotrackshot") && args.indexOf ("--videotrackshot") + 2 < args.size())
  1592. {
  1593. // LYNX.exe --videotrackshot prefix video [video2]: round 174d — the Playlist with video tracks (filmstrips,
  1594. // timecode row) and the video window at a few song positions, as PNGs + report.txt (the decoder, the
  1595. // frame shown for each wanted time: frame accuracy, frames dropped)
  1596. const auto i = args.indexOf ("--videotrackshot");
  1597. runVideoTrackShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1598. return;
  1599. }
  1600. if (args.contains ("--vfxshot"))
  1601. {
  1602. // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
  1603. const auto i = args.indexOf ("--vfxshot");
  1604. runVfxShot (args[i + 1].unquoted());
  1605. quit();
  1606. return;
  1607. }
  1608. if (args.contains ("--patchershot"))
  1609. {
  1610. // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
  1611. const auto i = args.indexOf ("--patchershot");
  1612. runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1613. quit();
  1614. return;
  1615. }
  1616. if (args.contains ("--audioxshot"))
  1617. {
  1618. // LYNX.exe --audioxshot prefix (round 190aq): the pre-fader send, the "Low latency while recording" mark on a
  1619. // bypassed slot and the Browser's "Preview in time", drawn off-screen
  1620. runAudioXShot (args[args.indexOf ("--audioxshot") + 1].unquoted());
  1621. quit();
  1622. return;
  1623. }
  1624. if (args.contains ("--comp177shot"))
  1625. {
  1626. // LYNX.exe --comp177shot prefix project (round 177c): a project of loop takes in the maximised
  1627. // Playlist as it opened; every group after "Comp these takes", with a swipe on the first; the track and record menus
  1628. const auto i = args.indexOf ("--comp177shot");
  1629. runComp177Shot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1630. quit();
  1631. return;
  1632. }
  1633. if (args.contains ("--feat166shot"))
  1634. {
  1635. // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
  1636. // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
  1637. // its end, and the time a full repaint takes)
  1638. const auto i = args.indexOf ("--feat166shot");
  1639. runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1640. quit();
  1641. return;
  1642. }
  1643. if (args.contains ("--remoteshot"))
  1644. {
  1645. // LYNX.exe --remoteshot prefix: Online Sessions P5-A1 (round 190ai) — the host's "Share plugins with guests"
  1646. // list and a guest's parameter editor of a plugin the host plays, off-screen with sample data
  1647. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1648. lynx::liveui::saveRemoteShots (args[args.indexOf ("--remoteshot") + 1].unquoted());
  1649. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  1650. quit();
  1651. return;
  1652. }
  1653. if (args.contains ("--perfshot"))
  1654. {
  1655. // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
  1656. // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
  1657. // for --patchershot (round 165m)
  1658. const auto i = args.indexOf ("--perfshot");
  1659. runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1660. quit();
  1661. return;
  1662. }
  1663. if (args.contains ("--gridshot"))
  1664. {
  1665. // LYNX.exe --gridshot prefix [project]: the Clip-launch workflow's layout off-screen, with a grid of sample
  1666. // clips, some playing and waiting, at the size of LYNX_SNAPSHOT_SIZE (round 181a); with a project (.lynx,
  1667. // .flp, .als), that project's grid instead (round 181c: a Live set's Session view as LYNX imports it)
  1668. const auto i = args.indexOf ("--gridshot");
  1669. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1670. runGridShot (args[i + 1].unquoted(), project);
  1671. quit();
  1672. return;
  1673. }
  1674. if (args.contains ("--simpleshot"))
  1675. {
  1676. // LYNX.exe --simpleshot prefix: round 184a's Simple workflow off-screen — View › Layout style with each style
  1677. // chosen, Settings › General (Pattern, then Simple selected) with its style list, the window in Pattern, then
  1678. // Simple, then Pattern again, and how many Simple workflow objects existed before and after (0 before)
  1679. const auto i = args.indexOf ("--simpleshot");
  1680. runSimpleShot (args[i + 1].unquoted());
  1681. quit();
  1682. return;
  1683. }
  1684. // --versionsshot <prefix> (round 190ap): the Versions panel, File's new items, a project opened without its
  1685. // third-party plugins (window, list, File menu) and the Export window's additions, offscreen
  1686. if (args.contains ("--versionsshot"))
  1687. {
  1688. runVersionsShot (args[args.indexOf ("--versionsshot") + 1].unquoted());
  1689. quit();
  1690. return;
  1691. }
  1692. if (args.contains ("--detailshot"))
  1693. {
  1694. // LYNX.exe --detailshot prefix: the Clip-launch workflow's detail view off-screen (round 183a): a track's chain
  1695. // (instrument, effects, one off, one folded), its clip page, and Pattern workflow before / after, at
  1696. // LYNX_SNAPSHOT_SIZE. Writes prefix-counts.txt with what the chain shows.
  1697. const auto i = args.indexOf ("--detailshot");
  1698. runDetailShot (args[i + 1].unquoted());
  1699. quit();
  1700. return;
  1701. }
  1702. if (args.contains ("--typeaheadtest"))
  1703. {
  1704. // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
  1705. // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
  1706. const auto i = args.indexOf ("--typeaheadtest");
  1707. runTypeAheadTest (juce::File (args[i + 1].unquoted()));
  1708. return;
  1709. }
  1710. if (args.contains ("--choosertest"))
  1711. {
  1712. // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
  1713. // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
  1714. // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
  1715. const auto i = args.indexOf ("--choosertest");
  1716. runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1717. return;
  1718. }
  1719. if (args.contains ("--snapshot"))
  1720. {
  1721. const auto i = args.indexOf ("--snapshot");
  1722. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1723. return;
  1724. }
  1725. if (args.contains ("--stemsplit"))
  1726. {
  1727. // LYNX.exe --stemsplit input.wav folder: the stem separation of the clip menu, without the window
  1728. const auto i = args.indexOf ("--stemsplit");
  1729. lynx::AudioEngine loader (false);
  1730. const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1731. juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  1732. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  1733. quit();
  1734. return;
  1735. }
  1736. if (args.contains ("--audio2midi"))
  1737. {
  1738. // LYNX.exe --audio2midi input.wav melody|harmony|drums notes.csv: the clip menu's Convert to MIDI, without the
  1739. // window (round a2m189b's measurements)
  1740. const auto i = args.indexOf ("--audio2midi");
  1741. const auto mode = args[i + 2] == "drums" ? lynx::a2m::Mode::drums : args[i + 2] == "harmony" ? lynx::a2m::Mode::harmony : lynx::a2m::Mode::melody;
  1742. lynx::AudioEngine loader (false);
  1743. const juce::File csv (args[i + 3].unquoted());
  1744. const auto error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), mode, csv);
  1745. csv.getSiblingFile ("audio2midi.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  1746. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  1747. quit();
  1748. return;
  1749. }
  1750. if (args.contains ("--stems"))
  1751. {
  1752. // LYNX.exe --stems project.(flp|als|lynx) base.wav: one WAV per insert that has sound (like "Export stems")
  1753. const auto i = args.indexOf ("--stems");
  1754. juce::String error, report;
  1755. int written = 0;
  1756. {
  1757. lynx::AudioEngine loader (false);
  1758. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  1759. // an .flp or a Live set (.als) opens through the import, as File › Open does (round 182b)
  1760. auto ok = input.hasFileExtension ("flp;als") ? loader.importFlpFile (input, error) : false;
  1761. if (! input.hasFileExtension ("flp;als"))
  1762. if (auto song = lynx::ProjectFile::load (input, error))
  1763. {
  1764. loader.setSong (std::move (*song));
  1765. ok = true;
  1766. }
  1767. const auto& song = loader.getSong();
  1768. for (int t = 1; ok && t < (int) song.mixer.size(); ++t)
  1769. {
  1770. if (std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  1771. continue;
  1772. const auto file = base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav");
  1773. lynx::ExportSettings settings;
  1774. lynx::ExportJob job (lynx::makeBounceSong (song, t), settings, file);
  1775. if (job.run ({}, error))
  1776. {
  1777. ++written;
  1778. report << file.getFileName() << " peak=" << job.getPeak() << "\n";
  1779. }
  1780. }
  1781. }
  1782. report << "stems=" << written << "\n";
  1783. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  1784. setApplicationReturnValue (written > 0 ? 0 : 1);
  1785. quit();
  1786. return;
  1787. }
  1788. // --export-als <in.lynx|.flp|.als> <folder> [--live11] [--reference] [--scan]: "<folder>/<name> Project/<name>.als" (round 175a)
  1789. if (args.contains ("--export-als"))
  1790. {
  1791. const auto i = args.indexOf ("--export-als");
  1792. runAlsExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--live11"), args.contains ("--reference"));
  1793. return;
  1794. }
  1795. // --gamepadshot <prefix> (round 184a, S16): the game controller's hints overlay and the MIDI settings page with
  1796. // the option on, offscreen, plus the poller fed fake pad states ("<prefix>-gamepad.txt")
  1797. if (args.contains ("--gamepadshot"))
  1798. {
  1799. runGamepadShot (args[args.indexOf ("--gamepadshot") + 1].unquoted());
  1800. return;
  1801. }
  1802. // --export-bundle <in.lynx|.flp|.als> <folder> [--zip] [--no-mixdown] [--shot <prefix>] (round 184a, S9): File ›
  1803. // Export › "For other apps..." without the window; the report goes to "<folder>/export-bundle.txt"
  1804. if (args.contains ("--export-bundle"))
  1805. {
  1806. const auto i = args.indexOf ("--export-bundle");
  1807. runBundleExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--zip"), ! args.contains ("--no-mixdown"),
  1808. args.contains ("--shot") ? args[args.indexOf ("--shot") + 1].unquoted() : juce::String());
  1809. return;
  1810. }
  1811. if (args.contains ("--export-flp"))
  1812. {
  1813. const auto i = args.indexOf ("--export-flp");
  1814. runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
  1815. return;
  1816. }
  1817. if (args.contains ("--export"))
  1818. {
  1819. const auto i = args.indexOf ("--export");
  1820. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  1821. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  1822. return;
  1823. }
  1824. if (args.contains ("--render"))
  1825. {
  1826. const auto i = args.indexOf ("--render");
  1827. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  1828. return;
  1829. }
  1830. // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
  1831. uncleanLastStep = collectUncleanSessions();
  1832. sessionsFolder().createDirectory();
  1833. lynx::crashguard::beginSession (
  1834. sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
  1835. ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
  1836. + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
  1837. + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
  1838. startHangWatch();
  1839. // LYNX_PROFILE_MAIN=<file> (round 174f): the message thread sampled every millisecond, 5-second windows
  1840. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  1841. lynx::crashguard::startMainProfiler (profile.toStdString());
  1842. startupTrace.mark ("initialise (normal start)");
  1843. if (startupTrace.on)
  1844. lynx::startupMark = startupMarkHook;
  1845. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1846. lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
  1847. startupOptions = lynx::StartupOptions::load();
  1848. lynx::registerFileTypes();
  1849. startupTrace.mark ("options + file types");
  1850. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument; a path typed in a terminal may be relative
  1851. // (D#92, round 180a: it was ignored, leaving the blank project with no message). A missing file gets "Could not open".
  1852. if (args.size() > 0 && lynx::safety::isFileArgument (args[0].unquoted().toStdString()))
  1853. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[0].unquoted());
  1854. // LYNX --no-plugins project.lynx (round 190ap): File › "Open without third-party plugins..." from the command
  1855. // line, for a project a plugin keeps from opening — no hosted plugin is created, each keeps its settings
  1856. if (const auto i = args.indexOf ("--no-plugins"); i >= 0)
  1857. {
  1858. if (i + 1 < args.size() && lynx::safety::isFileArgument (args[i + 1].unquoted().toStdString()))
  1859. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[i + 1].unquoted());
  1860. startWithoutPlugins = fileToOpen.hasFileExtension ("lynx");
  1861. }
  1862. // LYNX_TEST_MODE=1 LYNX --open-event-test <ms> <file>: the file arrives the way macOS's Finder delivers it (a Linux
  1863. // or Windows run can exercise that path): 0 ms = at once, before the window exists
  1864. if (lynx::platform::testMode() && args[0] == "--open-event-test" && args.size() > 2)
  1865. {
  1866. const auto file = args[2].unquoted().quoted();
  1867. if (args[1].getIntValue() == 0)
  1868. anotherInstanceStarted (file);
  1869. else
  1870. juce::Timer::callAfterDelay (args[1].getIntValue(), [this, file] { anotherInstanceStarted (file); });
  1871. }
  1872. // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
  1873. // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
  1874. // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
  1875. if (args.contains ("--opentime"))
  1876. {
  1877. const auto i = args.indexOf ("--opentime");
  1878. const auto project = args[i + 1].unquoted();
  1879. fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
  1880. openTimeReport = juce::File (args[i + 2].unquoted());
  1881. if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
  1882. openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
  1883. }
  1884. if (! startupOptions.splash)
  1885. {
  1886. startEngine();
  1887. createMainWindow();
  1888. mainWindow->reveal();
  1889. showUncleanNotice();
  1890. startupTrace.mark ("window revealed");
  1891. openStartupFile();
  1892. startupTrace.mark ("startup file opened");
  1893. startOpenTimeProbe();
  1894. startUpdateCheck();
  1895. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  1896. return;
  1897. }
  1898. // the splash first, so it is on screen while the audio device opens; the main window is built
  1899. // once the pepper has landed (the scene is still for a moment then) and shown when the splash ends
  1900. splash = std::make_unique<lynx::SplashScreen>();
  1901. startupTrace.mark ("splash made");
  1902. splash->showOnDesktop();
  1903. startupTrace.mark ("splash on the desktop");
  1904. juce::Timer::callAfterDelay (40, [this] {
  1905. startEngine();
  1906. if (splash == nullptr) // quit meanwhile
  1907. return;
  1908. splash->setStatus (lynx::tr ("Loading the workspace..."));
  1909. splash->startClock();
  1910. // the minimum counts from the process start (the audio device took part of it already)
  1911. splashDuration = lynx::SplashScreen::remainingDuration (startupTrace.seconds());
  1912. splash->setBarDuration (splashDuration);
  1913. juce::Timer::callAfterDelay (1050, [this] {
  1914. if (splash == nullptr || engine == nullptr)
  1915. return;
  1916. createMainWindow();
  1917. const auto wait = juce::jmax (0.0, splashDuration - splash->getElapsed());
  1918. juce::Timer::callAfterDelay ((int) (wait * 1000.0), [this] {
  1919. if (splash == nullptr || mainWindow == nullptr)
  1920. return;
  1921. mainWindow->reveal();
  1922. startupTrace.mark ("window revealed (after the splash)");
  1923. splash->toFront (false);
  1924. splash->finish ([this] { splash = nullptr; });
  1925. showUncleanNotice();
  1926. openStartupFile();
  1927. startupTrace.mark ("startup file opened");
  1928. startOpenTimeProbe();
  1929. startUpdateCheck();
  1930. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  1931. // first run: language, audio, plugin folders (FL Studio's included) and a background scan
  1932. if (! lynx::setupWizardDone() && lynx::platform::testMode())
  1933. lynx::platform::testModeLog ("setup wizard");
  1934. else if (! lynx::setupWizardDone())
  1935. mainWindow->showSetupWizard();
  1936. });
  1937. });
  1938. });
  1939. }
  1940. void startEngine()
  1941. {
  1942. startupTrace.mark ("before the audio engine");
  1943. engine = std::make_unique<lynx::AudioEngine>();
  1944. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  1945. startupTrace.mark ("audio engine + device");
  1946. crashEngine = engine.get();
  1947. lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
  1948. addDriverFileDeviceType();
  1949. if (startupOptions.sound)
  1950. {
  1951. // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
  1952. std::shared_ptr<const lynx::SampleData> sound;
  1953. if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
  1954. sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
  1955. engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
  1956. }
  1957. startupTrace.mark ("startup sound");
  1958. // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
  1959. // thread, while the splash and the main window come up (round 121)
  1960. if (fileToOpen.hasFileExtension ("flp"))
  1961. if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
  1962. try
  1963. {
  1964. engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  1965. startupTrace.mark ("plugin modules started ahead");
  1966. }
  1967. catch (const flp::Error&)
  1968. {
  1969. }
  1970. }
  1971. void createMainWindow()
  1972. {
  1973. mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
  1974. lynx::setMainWindowForOwnership (mainWindow.get());
  1975. lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
  1976. lynx::startRenderingWatch();
  1977. startupTrace.mark ("main window built");
  1978. }
  1979. // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
  1980. // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
  1981. void showUncleanNotice()
  1982. {
  1983. if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
  1984. {
  1985. if (uncleanLastStep.isNotEmpty())
  1986. lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
  1987. return;
  1988. }
  1989. if (uncleanLastStep.isEmpty())
  1990. {
  1991. lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
  1992. return;
  1993. }
  1994. auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
  1995. "LYNX SHARE's autosave folder; details in crash-history.log.",
  1996. { uncleanLastStep });
  1997. uncleanLastStep.clear();
  1998. const auto cause = uncleanCause();
  1999. // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
  2000. // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
  2001. juce::String separatePlugin;
  2002. if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
  2003. separatePlugin = cause.editorPlugin;
  2004. // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
  2005. else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
  2006. {
  2007. lynx::setGpuRenderingEnabled (false);
  2008. message << "\n\n"
  2009. << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
  2010. "rendering back on in Options > General settings (after a driver update, for example).",
  2011. { cause.driverModule });
  2012. }
  2013. // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
  2014. // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
  2015. for (int i = uncleanSteps.size(); --i >= 0;)
  2016. {
  2017. if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
  2018. break;
  2019. if (uncleanSteps[i].contains (lynx::visualgl::startNote))
  2020. {
  2021. if (lynx::visualgl::enabled())
  2022. {
  2023. lynx::visualgl::setEnabled (false);
  2024. message << "\n\n"
  2025. << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
  2026. "button turns it back on.");
  2027. }
  2028. break;
  2029. }
  2030. }
  2031. const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
  2032. auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
  2033. const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
  2034. lynx::crashreporter::retryPending();
  2035. if (action == lynx::crashreport::Action::askUser)
  2036. {
  2037. if (separatePlugin.isNotEmpty())
  2038. message << "\n\n"
  2039. << lynx::tr ("It happened while the window of {0} was opening{1}.",
  2040. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
  2041. lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
  2042. devices);
  2043. return;
  2044. }
  2045. if (action == lynx::crashreport::Action::sendSilently)
  2046. {
  2047. const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
  2048. lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
  2049. message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
  2050. }
  2051. if (separatePlugin.isNotEmpty())
  2052. {
  2053. juce::AlertWindow::showOkCancelBox (
  2054. juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
  2055. message + "\n\n"
  2056. + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
  2057. "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
  2058. "separate process\").",
  2059. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
  2060. lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
  2061. juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
  2062. if (result != 0)
  2063. lynx::setPluginAlwaysSeparate (separatePlugin, true);
  2064. }));
  2065. return;
  2066. }
  2067. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
  2068. }
  2069. // --opentime: after the start-up file was handed to the window
  2070. void startOpenTimeProbe()
  2071. {
  2072. if (openTimeReport == juce::File())
  2073. return;
  2074. struct Probe final : juce::Timer
  2075. {
  2076. LynxApplication& app;
  2077. juce::File report, project;
  2078. int idleSeconds;
  2079. int phase = 0; // 0 loading, 1 settling, 2 idle measurement
  2080. double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
  2081. double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
  2082. Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
  2083. : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
  2084. {
  2085. revealedS = startupTrace.seconds();
  2086. startTimer (250);
  2087. }
  2088. bool loaded() const
  2089. {
  2090. if (project == juce::File())
  2091. return true;
  2092. return app.mainWindow != nullptr
  2093. && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
  2094. }
  2095. void finish (const juce::String& result)
  2096. {
  2097. stopTimer();
  2098. const auto now = startupTrace.seconds();
  2099. const auto cpu = lynx::processCpuSeconds();
  2100. juce::String text;
  2101. text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
  2102. << "window_s=" << juce::String (revealedS, 3) << "\n"
  2103. << "loaded_s=" << juce::String (loadedS, 3) << "\n"
  2104. << "settled_s=" << juce::String (settledS, 3) << "\n"
  2105. << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
  2106. << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
  2107. << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
  2108. << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
  2109. << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
  2110. << "result=" << result << "\n";
  2111. report.replaceWithText (text);
  2112. app.setApplicationReturnValue (result == "OK" ? 0 : 1);
  2113. app.quit();
  2114. }
  2115. void timerCallback() override
  2116. {
  2117. const auto now = startupTrace.seconds();
  2118. const auto cpu = lynx::processCpuSeconds();
  2119. if (phase == 0)
  2120. {
  2121. if (loaded())
  2122. {
  2123. loadedS = now;
  2124. cpuAtLoaded = cpu;
  2125. phase = 1;
  2126. lastCpu = cpu;
  2127. lastT = now;
  2128. }
  2129. else if (now - revealedS > 240.0)
  2130. finish ("TIMEOUT loading");
  2131. return;
  2132. }
  2133. if (phase == 1)
  2134. {
  2135. // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
  2136. const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
  2137. lastCpu = cpu;
  2138. lastT = now;
  2139. if (use < 10.0)
  2140. {
  2141. if (quietSince < 0.0)
  2142. quietSince = now - 0.25;
  2143. if (now - quietSince >= 1.5)
  2144. settledS = quietSince;
  2145. }
  2146. else
  2147. quietSince = -1.0;
  2148. if (settledS >= 0.0 || now - loadedS > 30.0)
  2149. {
  2150. phase = 2;
  2151. idleCpu0 = cpu;
  2152. idleT0 = now;
  2153. }
  2154. return;
  2155. }
  2156. if (now - idleT0 >= (double) idleSeconds)
  2157. finish ("OK");
  2158. }
  2159. };
  2160. perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
  2161. }
  2162. // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
  2163. // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
  2164. void startUpdateCheck()
  2165. {
  2166. if (openTimeReport != juce::File())
  2167. return;
  2168. lynx::updater::afterStart();
  2169. juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
  2170. }
  2171. void openStartupFile()
  2172. {
  2173. startupFileHandled = true;
  2174. if (fileToOpen != juce::File() && mainWindow != nullptr)
  2175. {
  2176. if (std::exchange (startWithoutPlugins, false)) // --no-plugins (round 190ap)
  2177. mainWindow->getContent().openNextWithoutPlugins (true);
  2178. mainWindow->openFile (fileToOpen);
  2179. mainWindow->getContent().openNextWithoutPlugins (false); // (a file that did not open leaves nothing behind)
  2180. }
  2181. else if (mainWindow != nullptr && openTimeReport == juce::File())
  2182. mainWindow->getContent().openStartupProject(); // issue #123 (FL's Startup project)
  2183. }
  2184. void shutdown() override
  2185. {
  2186. parityShow.reset(); // (LYNX_PARITYSHOT_SHOW's window, before the engine it shows)
  2187. if (relaunched || updateHelper)
  2188. return; // the copy that ran owns the session (its crash notes stay for the next start)
  2189. lynx::crashguard::note ("closing");
  2190. lynx::shutdownPluginSandboxWorker();
  2191. splash = nullptr;
  2192. lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
  2193. lynx::shutdownAudioToMidi(); // (the same for a conversion to MIDI)
  2194. if (mainWindow != nullptr && mainWindow->isVisible())
  2195. mainWindow->saveState();
  2196. mainWindow = nullptr; // the UI goes before the engine
  2197. lynx::updater::shutdown(); // (a check or download in flight stops)
  2198. crashEngine = nullptr;
  2199. engine = nullptr;
  2200. // CLAP plugins whose instance another thread deleted while this one was busy: deactivated and destroyed now
  2201. lynx::ClapPluginFormat::finishPendingTeardowns();
  2202. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  2203. heartbeat.stopTimer();
  2204. lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
  2205. lynx::crashguard::stopHangWatch();
  2206. lynx::crashguard::stopMainProfiler();
  2207. lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
  2208. // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
  2209. // teardown runs (some crash in it at exit, round 111)
  2210. if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
  2211. lynx::crashguard::exitNow (getApplicationReturnValue());
  2212. }
  2213. void systemRequestedQuit() override
  2214. {
  2215. if (mainWindow != nullptr)
  2216. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  2217. else
  2218. quit();
  2219. }
  2220. private:
  2221. // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
  2222. // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
  2223. struct Heartbeat final : juce::Timer
  2224. {
  2225. void timerCallback() override { lynx::crashguard::heartbeat(); }
  2226. } heartbeat;
  2227. void startHangWatch()
  2228. {
  2229. const auto folder = lynx::platform::settingsFile ("autosave");
  2230. folder.createDirectory();
  2231. // keep the newest hang files only
  2232. auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
  2233. lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
  2234. for (int i = 20; i < old.size(); ++i)
  2235. old.getReference (i).deleteFile();
  2236. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
  2237. heartbeat.startTimerHz (5);
  2238. }
  2239. bool sandboxChild = false;
  2240. bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
  2241. bool updateHelper = false; // --apply-update (round 166b)
  2242. juce::String uncleanLastStep; // last step of a previous run that ended without closing
  2243. // LYNX_PROFILE_DIR=<folder> LYNX --lv2scantest report.txt (Linux, issue #85): the LV2 scan's promise, with real child
  2244. // processes. A new PluginHost per step, as every start of LYNX has. The LV2 folders of the machine are read too.
  2245. void runLv2ScanTest (const juce::String& reportPath)
  2246. {
  2247. juce::String report;
  2248. auto ok = lynx::platform::profileOverride() != juce::File();
  2249. #if JUCE_LINUX
  2250. const auto folder = lynx::platform::profileOverride().getChildFile ("lv2-test");
  2251. const juce::FileSearchPath paths (folder.getFullPathName());
  2252. const auto check = [&] (const juce::String& name, bool passed) {
  2253. report << name << "=" << (passed ? "ok" : "FAILED") << "\n";
  2254. ok = ok && passed;
  2255. };
  2256. const auto install = [&] (const juce::String& name) {
  2257. const auto bundle = folder.getChildFile (name + ".lv2");
  2258. bundle.createDirectory();
  2259. bundle.getChildFile ("manifest.ttl").replaceWithText ("@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
  2260. "<urn:lynx-test:" + name + "> a lv2:Plugin ; lv2:binary <" + name + ".so> ; rdfs:seeAlso <plugin.ttl> .\n");
  2261. bundle.getChildFile ("plugin.ttl").replaceWithText ("@prefix doap: <http://usefulinc.com/ns/doap#> .\n<urn:lynx-test:" + name + "> doap:name \"" + name + "\" .\n");
  2262. };
  2263. auto date = juce::Time::getCurrentTime();
  2264. const auto touch = [&] { // the next date, whatever the file system's date resolution
  2265. date += juce::RelativeTime::seconds (2.0);
  2266. folder.getChildFile ("a.lv2/plugin.ttl").setLastModificationTime (date);
  2267. };
  2268. const auto listed = [] (lynx::PluginHost& host, const juce::String& name) {
  2269. for (const auto& d : host.getKnownPlugins().getTypes())
  2270. if (d.fileOrIdentifier == "urn:lynx-test:" + name)
  2271. return true;
  2272. return false;
  2273. };
  2274. const auto step = [&] (const juce::String& name, int children, const std::function<void (lynx::PluginHost&)>& prepare = {}) {
  2275. lynx::PluginHost host (true);
  2276. if (prepare)
  2277. prepare (host);
  2278. host.scan (paths, {});
  2279. check (name, host.scanChildrenStarted() == children && listed (host, "a"));
  2280. };
  2281. install ("a");
  2282. step ("first_scan_one_child", 1);
  2283. step ("nothing_changed_no_child", 0);
  2284. touch();
  2285. step ("ttl_updated", 1);
  2286. install ("b");
  2287. step ("bundle_installed", 1);
  2288. step ("forget_file", 1, [] (lynx::PluginHost& host) { host.forgetFile ("urn:lynx-test:a"); });
  2289. step ("forget_all", 1, [] (lynx::PluginHost& host) { host.forgetAll(); });
  2290. lynx::platform::settingsFile ("plugins.xml").deleteFile();
  2291. step ("list_lost", 1);
  2292. step ("nothing_changed_again", 0);
  2293. // cancelled while the child works: stopped at once, and nothing is taken for done
  2294. touch();
  2295. setenv ("LYNX_TEST_CRASH", "lv2-batch-hang", 1);
  2296. {
  2297. lynx::PluginHost host (true);
  2298. const auto started = juce::Time::getMillisecondCounter();
  2299. host.scan (paths, [] (float, const juce::String&) { return false; });
  2300. check ("cancel_stops_the_child", host.scanChildrenStarted() == 1 && juce::Time::getMillisecondCounter() - started < 20000);
  2301. }
  2302. unsetenv ("LYNX_TEST_CRASH");
  2303. step ("described_after_cancel", 1);
  2304. // the child dies: plugin by plugin takes over (stopped after two of them: a machine may have hundreds)
  2305. touch();
  2306. setenv ("LYNX_TEST_CRASH", "lv2-batch", 1);
  2307. {
  2308. lynx::PluginHost host (true);
  2309. host.scan (paths, [&host] (float, const juce::String&) { return host.scanChildrenStarted() < 3; });
  2310. check ("crash_falls_back_plugin_by_plugin", host.scanChildrenStarted() == 3);
  2311. auto blamed = false;
  2312. for (const auto& file : host.getKnownPlugins().getBlacklistedFiles())
  2313. blamed = blamed || file.startsWith ("lv2-folders:");
  2314. check ("crash_blacklists_nothing", ! blamed);
  2315. }
  2316. unsetenv ("LYNX_TEST_CRASH");
  2317. step ("described_after_crash", 1);
  2318. #endif
  2319. juce::File (reportPath).replaceWithText (report + "result=" + (ok ? "OK" : "FAILED") + "\n");
  2320. setApplicationReturnValue (ok ? 0 : 1);
  2321. quit();
  2322. }
  2323. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  2324. // Exit code 0 = audio came out, 1 = silence.
  2325. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  2326. {
  2327. lynx::AudioEngine offline (false);
  2328. const auto peak = offline.renderOffline (2.0, 48000.0);
  2329. const auto audioOk = peak > 0.01f && peak < 10.0f;
  2330. // project format round trip, with accents in the name
  2331. auto original = lynx::Song::makeDefault();
  2332. original.channels[0].name = "Bumbo ação";
  2333. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  2334. original.mode = lynx::PlayMode::song;
  2335. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  2336. original.mixer[3].effects[0].params[1] = 0.25f;
  2337. lynx::Automation automation;
  2338. automation.name = "Pan";
  2339. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  2340. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  2341. original.automations.push_back (automation);
  2342. lynx::Clip automationClip;
  2343. automationClip.kind = lynx::ClipKind::automation;
  2344. automationClip.automation = 0;
  2345. automationClip.track = 4;
  2346. automationClip.length = 3840;
  2347. original.playlist.push_back (automationClip);
  2348. original.loopStart = 960;
  2349. original.loopEnd = 7680;
  2350. original.playlistTracks.resize (3);
  2351. original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
  2352. { // the clip grid (round 181a)
  2353. lynx::launcher::setClip (original, 1, 2, { 0, 0, 0, 1920, 0 });
  2354. auto& slot = *lynx::launcher::settingsAt (*original.clipGrid, 1, 2);
  2355. slot.name = "Clip ação";
  2356. slot.mode = lynx::LaunchMode::toggle;
  2357. slot.quant = lynx::LaunchQuant::eighthTriplet;
  2358. slot.legato = true;
  2359. slot.loop = false;
  2360. original.clipGrid->scenes[0].name = "Intro";
  2361. original.clipGrid->globalQuant = lynx::LaunchQuant::bars2;
  2362. }
  2363. original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
  2364. original.playlistTracks[1].collapsed = true;
  2365. original.channelGroups = { "Drums", "Keys" };
  2366. original.channels[1].group = 1;
  2367. juce::String error;
  2368. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  2369. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  2370. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  2371. const auto projectOk = reloaded && reloaded->channels.size() == original.channels.size()
  2372. && reloaded->channels[0].name == original.channels[0].name
  2373. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  2374. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  2375. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  2376. && reloaded->clipGrid.has_value() && reloaded->clipGrid->globalQuant == lynx::LaunchQuant::bars2
  2377. && reloaded->clipGrid->scenes.size() == 3 && reloaded->clipGrid->scenes[0].name == "Intro"
  2378. && lynx::launcher::clipAt (*reloaded->clipGrid, 1, 2) != nullptr
  2379. && [&reloaded] {
  2380. auto grid = *reloaded->clipGrid;
  2381. const auto* slot = lynx::launcher::settingsAt (grid, 1, 2);
  2382. return slot != nullptr && slot->name == "Clip ação" && slot->mode == lynx::LaunchMode::toggle
  2383. && slot->quant == lynx::LaunchQuant::eighthTriplet && slot->legato && ! slot->loop;
  2384. }()
  2385. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  2386. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  2387. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  2388. && reloaded->automations[0].points[1].tick == 3840
  2389. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  2390. && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
  2391. && reloaded->playlistTracks[1].colour == 0
  2392. && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
  2393. && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
  2394. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  2395. && reloaded->mixer[3].effects.size() == 1
  2396. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  2397. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  2398. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  2399. auto rich = lynx::Song::makeDefault();
  2400. auto& synth = rich.channels[4].synth;
  2401. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  2402. synth.filterType = 2;
  2403. synth.mono = true;
  2404. synth.portaBeats = 0.125f;
  2405. synth.am = true;
  2406. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  2407. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  2408. auto& sampler = rich.channels[0].sampler;
  2409. sampler.cutoff = 1200.0f;
  2410. sampler.resonance = 0.3f;
  2411. sampler.filterType = 1;
  2412. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  2413. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  2414. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  2415. rich.mixer[2].eq.hz[1] = 2200.0f;
  2416. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2417. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  2418. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  2419. rich.mixer[2].effects.push_back (peqSlot);
  2420. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  2421. utilitySlot.params[1] = 0.2f;
  2422. rich.mixer[2].effects.push_back (utilitySlot);
  2423. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  2424. for (int i = 0; i < 300; ++i)
  2425. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  2426. vocodexSlot.sidechain = 1;
  2427. vocodexSlot.sidechain2 = 2;
  2428. rich.mixer[3].effects.push_back (vocodexSlot);
  2429. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  2430. rich.addMarker ({ 7680, {}, 7, 8 });
  2431. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  2432. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  2433. for (std::size_t i = 0; i < a.size(); ++i)
  2434. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  2435. return false;
  2436. return true;
  2437. };
  2438. const auto richOk = richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  2439. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  2440. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  2441. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  2442. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  2443. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  2444. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  2445. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  2446. && richBack->markers() == rich.markers();
  2447. // issue #96's per-plugin option: saved only when on; old projects (no field) read as off
  2448. bool hostKeysOk = false;
  2449. {
  2450. auto song = lynx::Song::makeDefault();
  2451. lynx::ChannelDef plugin;
  2452. plugin.instrument = lynx::InstrumentKind::plugin;
  2453. plugin.plugin.id = "x";
  2454. song.channels.push_back (plugin);
  2455. const auto channel = song.channels.size() - 1;
  2456. const auto off = lynx::ProjectFile::toJson (song);
  2457. song.channels[channel].plugin.allowHostKeys = true;
  2458. song.channels[channel].plugin.hostKeysFirst = true;
  2459. song.channels[channel].plugin.pinned = true; // (round 190ao: Pin on top)
  2460. song.channels[channel].plugin.velocityMode = lynx::prefs::pluginVelocityFixed; // (round 190ao: the plugin's own velocity)
  2461. song.channels[channel].plugin.fixedVelocity = 64;
  2462. const auto on = lynx::ProjectFile::toJson (song);
  2463. const auto offBack = lynx::ProjectFile::fromJson (off, error);
  2464. const auto onBack = lynx::ProjectFile::fromJson (on, error);
  2465. hostKeysOk = ! off.contains ("allowHostKeys") && on.contains ("allowHostKeys") && offBack && onBack
  2466. && ! offBack->channels[channel].plugin.allowHostKeys && onBack->channels[channel].plugin.allowHostKeys
  2467. && ! off.contains ("hostKeysFirst") && ! offBack->channels[channel].plugin.hostKeysFirst && onBack->channels[channel].plugin.hostKeysFirst
  2468. && ! off.contains ("pinnedOnTop") && ! offBack->channels[channel].plugin.pinned && onBack->channels[channel].plugin.pinned
  2469. && ! off.contains ("velocityMode") && ! off.contains ("fixedVelocity") && offBack->channels[channel].plugin.velocityMode == 0
  2470. && offBack->channels[channel].plugin.fixedVelocity == lynx::prefs::defaultFixedVelocity
  2471. && onBack->channels[channel].plugin.velocityMode == lynx::prefs::pluginVelocityFixed && onBack->channels[channel].plugin.fixedVelocity == 64;
  2472. }
  2473. // round 190ad: a new project has FL's plugin levels and keeps them through a save; a project saved before
  2474. // (no "pluginLevels") reads as LYNX's own law, and stays so when it opens
  2475. bool pluginLevelsOk = false;
  2476. {
  2477. const auto fresh = lynx::makeNewProject();
  2478. const auto saved = lynx::ProjectFile::toJson (fresh);
  2479. const auto back = lynx::ProjectFile::fromJson (saved, error);
  2480. auto old = lynx::Song::makeDefault(); // (what every earlier version made)
  2481. const auto oldSaved = lynx::ProjectFile::toJson (old);
  2482. const auto oldBack = lynx::ProjectFile::fromJson (oldSaved, error);
  2483. const auto stripped = lynx::ProjectFile::fromJson (saved.replace ("\"pluginLevels\"", "\"pluginLevelsGone\""), error);
  2484. pluginLevelsOk = fresh.flPluginLevels && saved.contains ("\"pluginLevels\"") && back && back->flPluginLevels
  2485. && ! old.flPluginLevels && ! oldSaved.contains ("pluginLevels") && oldBack && ! oldBack->flPluginLevels
  2486. && stripped && ! stripped->flPluginLevels;
  2487. }
  2488. // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
  2489. bool hwOutOk = false;
  2490. {
  2491. auto song = lynx::Song::makeDefault();
  2492. const auto plain = lynx::ProjectFile::toJson (song);
  2493. song.mixer[0].outputChannel = lynx::outputNone;
  2494. song.mixer[1].outputChannel = 2;
  2495. song.mixer[1].outputMode = lynx::OutputMode::monoRight;
  2496. song.mixer[2].outputChannel = 6;
  2497. song.mixer[3].outputChannel = 4;
  2498. song.mixer[3].outputMode = lynx::OutputMode::monoSum;
  2499. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2500. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  2501. hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
  2502. && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
  2503. && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
  2504. && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
  2505. && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
  2506. }
  2507. // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
  2508. // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
  2509. bool flp168jOk = false;
  2510. {
  2511. auto song = lynx::Song::makeDefault();
  2512. const auto plain = lynx::ProjectFile::toJson (song);
  2513. song.channels[0].icon = 75;
  2514. song.mixer[2].icon = 71;
  2515. song.playlistTracks.resize (3);
  2516. song.playlistTracks[2].icon = 30;
  2517. song.autoPdc = false;
  2518. song.compensateAutomations = false;
  2519. song.timeSignatureMode = true;
  2520. song.scaleHighlight = { 10, 5 };
  2521. song.dataFolder = "D:\\Projects\\data";
  2522. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2523. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  2524. flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
  2525. && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
  2526. && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
  2527. && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
  2528. && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
  2529. && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
  2530. }
  2531. // round 180d: clip fades take FL's S curve; a project saved before that keeps its straight fades, also after another
  2532. // save, and a clip made in it takes the S curve. FL's fade tensions and stretch mode and PITCH survive a save.
  2533. // issue #122: playlist tracks linked to inserts (audio) and channels (instrument) survive save, load and save
  2534. // again byte for byte (they were read before the mixer and fell back to Unassigned)
  2535. bool trackModes122Ok = false;
  2536. {
  2537. auto song = lynx::Song::makeDefault();
  2538. song.playlistTracks.resize (6);
  2539. song.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  2540. song.playlistTracks[1].mixerTrack = 3;
  2541. song.playlistTracks[4].mode = lynx::PlaylistTrackMode::audio;
  2542. song.playlistTracks[4].mixerTrack = (int) song.mixer.size() - 1;
  2543. song.playlistTracks[5].mode = lynx::PlaylistTrackMode::instrument;
  2544. song.playlistTracks[5].channel = 1;
  2545. song.playlistTracks[5].mixerTrack = 2;
  2546. const auto json = lynx::ProjectFile::toJson (song, false);
  2547. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  2548. const auto again = loaded ? lynx::ProjectFile::toJson (*loaded, false) : juce::String();
  2549. trackModes122Ok = loaded && json.contains ("playlistTrackModes") && again == json && loaded->playlistTracks.size() >= 6
  2550. && loaded->playlistTracks[1].mode == lynx::PlaylistTrackMode::audio && loaded->playlistTracks[1].mixerTrack == 3
  2551. && loaded->playlistTracks[4].mode == lynx::PlaylistTrackMode::audio
  2552. && loaded->playlistTracks[4].mixerTrack == (int) song.mixer.size() - 1
  2553. && loaded->playlistTracks[5].mode == lynx::PlaylistTrackMode::instrument && loaded->playlistTracks[5].channel == 1;
  2554. }
  2555. bool clipFades180dOk = false;
  2556. {
  2557. auto song = lynx::Song::makeDefault();
  2558. lynx::Clip faded;
  2559. faded.kind = lynx::ClipKind::audio;
  2560. faded.channel = 0;
  2561. faded.length = lynx::ppq * 8;
  2562. faded.fadeIn = lynx::ppq;
  2563. faded.fadeOutTension = -812.933f;
  2564. faded.fadeOut = lynx::ppq * 2;
  2565. lynx::Clip plainClip = faded;
  2566. plainClip.fadeIn = plainClip.fadeOut = 0;
  2567. plainClip.fadeOutTension = 0.0f;
  2568. plainClip.start = lynx::ppq * 16;
  2569. song.playlist = { faded, plainClip };
  2570. song.channels[0].sampler.flStretchMode = 5;
  2571. song.channels[0].sampler.flStretchPitch = 247;
  2572. const auto json = lynx::ProjectFile::toJson (song);
  2573. const auto current = lynx::ProjectFile::fromJson (json, error);
  2574. const auto oldJson = json.replace ("\"clipFadesPerClip\"", "\"clipFadesOther\"");
  2575. auto old = lynx::ProjectFile::fromJson (oldJson, error);
  2576. auto resaved = old;
  2577. if (resaved)
  2578. {
  2579. auto added = faded;
  2580. added.start = lynx::ppq * 32;
  2581. added.linearFades = 0;
  2582. resaved->playlist.push_back (added);
  2583. resaved = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*resaved), error);
  2584. }
  2585. clipFades180dOk = current && old && resaved && json.contains ("clipFadesPerClip") && ! oldJson.contains ("clipFadesPerClip")
  2586. && current->playlist.size() == 2 && ! current->playlist[0].linearFades
  2587. && current->playlist[0].fadeOutTension == -812.933f && ! current->playlist[1].linearFades
  2588. && current->channels[0].sampler.flStretchMode == 5 && current->channels[0].sampler.flStretchPitch == 247
  2589. && old->playlist.size() == 2 && old->playlist[0].linearFades && ! old->playlist[1].linearFades
  2590. && resaved->playlist.size() == 3 && resaved->playlist[0].linearFades && ! resaved->playlist[1].linearFades
  2591. && ! resaved->playlist[2].linearFades && resaved->playlist[0].fadeOutTension == -812.933f;
  2592. }
  2593. // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
  2594. // them has neither in its file and loads with the option off
  2595. bool blocksOk = false;
  2596. {
  2597. auto song = lynx::Song::makeDefault();
  2598. const auto plain = lynx::ProjectFile::toJson (song);
  2599. song.patternBlocksOn = true;
  2600. lynx::patternblocks::place (song, 0, 0);
  2601. lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
  2602. song.addArrangement ("Second");
  2603. lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
  2604. song.selectArrangement (0);
  2605. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2606. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  2607. blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2
  2608. && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
  2609. && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
  2610. && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
  2611. && ! plain.contains ("patternBlocks");
  2612. }
  2613. // comping (round 177c): a comp's equal-power crossfades (Clip::fadeCurve) and the crossfade length are saved; a
  2614. // project without them has neither in its file
  2615. bool compOk = false;
  2616. {
  2617. auto song = lynx::Song::makeDefault();
  2618. const auto plain = lynx::ProjectFile::toJson (song);
  2619. lynx::ChannelDef take;
  2620. take.instrument = lynx::InstrumentKind::audioClip;
  2621. take.samplePath = "take.wav";
  2622. song.channels.push_back (take);
  2623. lynx::Clip a;
  2624. a.kind = lynx::ClipKind::audio;
  2625. a.channel = (int) song.channels.size() - 1;
  2626. a.length = lynx::ppq;
  2627. a.fadeOut = 20;
  2628. a.fadeCurve = 2;
  2629. auto b = a;
  2630. b.start = lynx::ppq - 20;
  2631. b.fadeOut = 0;
  2632. b.fadeIn = 20;
  2633. b.fadeCurve = 1;
  2634. // round 180d's FL fade fields (indices 17..20) and the comp curve (index 21) on one clip, all kept
  2635. auto c = a;
  2636. c.start = 4 * lynx::ppq;
  2637. c.fadeIn = 30;
  2638. c.fadeInTension = -0.75f;
  2639. c.fadeOutTension = 0.5f;
  2640. c.linearFades = 2;
  2641. c.flFadeFlags = 0x1234u;
  2642. c.fadeCurve = 3;
  2643. song.playlist = { a, b, c };
  2644. song.compCrossfadeMs = 12.5f;
  2645. song.playlistTracks.resize (2);
  2646. song.playlistTracks[0].compTrack = true;
  2647. song.playlistTracks[1].grouped = true;
  2648. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2649. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  2650. const auto* both = back && back->playlist.size() == 3 ? &back->playlist[2] : nullptr;
  2651. compOk = back && back->playlist.size() == 3 && back->playlist[0].fadeCurve == 2 && back->playlist[1].fadeCurve == 1
  2652. && both != nullptr && both->fadeCurve == 3 && both->fadeInTension == -0.75f && both->fadeOutTension == 0.5f
  2653. && both->linearFades == 2 && both->flFadeFlags == 0x1234u && both->fadeIn == 30
  2654. && back->playlist[1].fadeIn == 20 && back->compCrossfadeMs == 12.5f && back->playlistTracks[0].compTrack && ! back->playlistTracks[1].compTrack && plainBack
  2655. && plainBack->compCrossfadeMs == lynx::Song::defaultCompCrossfadeMs && ! plain.contains ("compCrossfadeMs") && ! plain.contains ("playlistCompTracks");
  2656. }
  2657. // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
  2658. // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
  2659. bool polyOk = false;
  2660. {
  2661. auto song = lynx::Song::makeDefault();
  2662. lynx::ChannelDef osc;
  2663. osc.instrument = lynx::InstrumentKind::threeosc;
  2664. osc.misc.mono = osc.misc.porta = true;
  2665. osc.misc.portaBeats = 0.25f;
  2666. song.channels.push_back (osc);
  2667. auto old = osc;
  2668. old.misc = {};
  2669. old.synth.mono = old.synth.porta = true;
  2670. old.synth.portaBeats = 0.5f;
  2671. song.channels.push_back (old);
  2672. old.maxPolyphony = 1;
  2673. song.channels.push_back (old);
  2674. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2675. const auto n = song.channels.size();
  2676. polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
  2677. && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
  2678. && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
  2679. && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
  2680. && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
  2681. }
  2682. // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
  2683. bool latencyOk = false;
  2684. {
  2685. auto song = lynx::Song::makeDefault();
  2686. const auto plain = lynx::ProjectFile::toJson (song);
  2687. song.mixer[1].latencyMs = -20.0f;
  2688. song.mixer[2].latencyMs = 12.5f;
  2689. song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
  2690. song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  2691. song.mixer[3].compensateMasterLatency = false;
  2692. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2693. latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
  2694. && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
  2695. && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
  2696. && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
  2697. && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
  2698. }
  2699. // LYNX's pre-fader sends (round 190aq): saved only when one is used, in a list of its own ("preSends") that a
  2700. // version from before ignores (its sends then play post-fader, as FL's)
  2701. bool preSendOk = false;
  2702. {
  2703. auto song = lynx::Song::makeDefault();
  2704. song.setRoute (1, 3, true, 0.5f);
  2705. song.setRoute (1, 4, true);
  2706. song.setRoute (2, 3, true);
  2707. const auto plain = lynx::ProjectFile::toJson (song);
  2708. song.setSendPre (1, 3, true);
  2709. const auto json = lynx::ProjectFile::toJson (song);
  2710. const auto back = lynx::ProjectFile::fromJson (json, error);
  2711. preSendOk = back && back->sendPre (1, 3) && ! back->sendPre (1, 4) && ! back->sendPre (2, 3)
  2712. && std::abs (back->routeLevel (1, 3) - 0.5f) < 1.0e-4f && back->mixer[1].sends == song.mixer[1].sends
  2713. && ! plain.contains ("preSends") && json.contains ("preSends")
  2714. && json.replace ("\"preSends\"", "\"preSendsOld\"") != json;
  2715. // the same file without the list (what an older version reads): the sends are there, post-fader
  2716. if (const auto old = lynx::ProjectFile::fromJson (json.replace ("\"preSends\"", "\"unknownToOldVersions\""), error))
  2717. preSendOk = preSendOk && old->routes (1, 3) && ! old->sendPre (1, 3) && old->mixer[1].sends.size() == 2;
  2718. else
  2719. preSendOk = false;
  2720. }
  2721. // LYNX's "Low latency while recording" (round 190aq): a latency-adding effect on a monitored insert's path is
  2722. // bypassed in the engine only — PDC drops, the slot is marked, the song and the saved project stay as they are —
  2723. // and it is back when the option goes off
  2724. bool lowLatencyOk = false;
  2725. {
  2726. lynx::AudioEngine live (false);
  2727. live.editSong ([] (lynx::Song& s) {
  2728. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter)); // 1.5 ms look-ahead
  2729. s.mixer[1].inputChannel = 0;
  2730. s.mixer[1].monitor = lynx::InputMonitor::on;
  2731. });
  2732. const auto before = live.getLatencySamples();
  2733. const auto saved = lynx::ProjectFile::toJson (live.getSong());
  2734. const auto idle = live.lowLatencyBypassedCount() == 0; // the option is off: nothing is bypassed
  2735. auto o = live.getRecordOptions();
  2736. o.lowLatencyRecording = true;
  2737. live.setRecordOptions (o);
  2738. const auto during = live.getLatencySamples();
  2739. const auto marked = live.isSlotLowLatencyBypassed (1, 0) && live.lowLatencyBypassedLatency (1, 0) > 0 && live.lowLatencyBypassedCount() >= 1;
  2740. const auto untouched = live.getSong().mixer[1].effects[0].enabled && lynx::ProjectFile::toJson (live.getSong()) == saved;
  2741. // monitoring leaves "On" (nothing armed): the effect returns
  2742. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::whenArmed; });
  2743. const auto released = live.getLatencySamples() == before && ! live.isSlotLowLatencyBypassed (1, 0);
  2744. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::on; });
  2745. const auto again = live.getLatencySamples() == during && live.isSlotLowLatencyBypassed (1, 0);
  2746. o.lowLatencyRecording = false;
  2747. live.setRecordOptions (o);
  2748. lowLatencyOk = before > 0 && idle && during < before && marked && untouched && released && again
  2749. && live.getLatencySamples() == before && live.lowLatencyBypassedCount() == 0;
  2750. }
  2751. // The Browser's "Preview in time" (round 190aq): a loop whose name gives its tempo is stretched to the project's
  2752. // and starts on the beat; a one-shot plays as it always did; off, nothing changes
  2753. bool previewInTimeOk = false;
  2754. double previewPrepareMs = 0.0;
  2755. {
  2756. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-preview");
  2757. dir.deleteRecursively();
  2758. dir.createDirectory();
  2759. auto writeWav = [&dir] (const juce::String& name, int frames, bool loop) {
  2760. const auto wav = dir.getChildFile (name);
  2761. juce::WavAudioFormat format;
  2762. juce::AudioBuffer<float> audio (1, frames);
  2763. for (int i = 0; i < frames; ++i) // a click on every beat of 120 BPM over a tone, or a decaying hit
  2764. audio.setSample (0, i, loop ? (i % 24000 < 400 ? 0.8f : 0.0f) + 0.1f * std::sin (0.02f * (float) i)
  2765. : 0.6f * std::exp (-(float) i / 2000.0f) * std::sin (0.05f * (float) i));
  2766. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  2767. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  2768. {
  2769. out.release();
  2770. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  2771. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  2772. }
  2773. return wav;
  2774. };
  2775. const auto loop = writeWav ("selftest loop 120 bpm.wav", 96000, true); // 4 beats at 120 BPM
  2776. const auto hit = writeWav ("selftest hit.wav", 14400, false); // 0.3 s
  2777. lynx::AudioEngine player (false);
  2778. const auto projectBpm = player.getTransport().bpm.load();
  2779. // off (FL's preview): nothing is prepared, the file plays as it is
  2780. player.previewFile (loop);
  2781. const auto offOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  2782. player.setPreviewInTime (true);
  2783. player.previewFile (hit); // a one-shot: as it always played, at once
  2784. const auto hitOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  2785. player.previewFile (loop);
  2786. const auto queued = player.getPreviewTiming().pending || std::abs (projectBpm - 120.0) < 0.2;
  2787. player.finishPreviewJobs();
  2788. const auto timing = player.getPreviewTiming();
  2789. previewPrepareMs = player.getLastPreviewPrepareMs();
  2790. const auto wanted = lynx::previewtempo::stretchRatio (120.0, projectBpm);
  2791. const auto stretchedOk = timing.inTime && ! timing.pending && timing.source == lynx::previewtempo::Source::name
  2792. && std::abs (timing.fileBpm - 120.0) < 1.0e-9 && std::abs (timing.ratio - wanted) < 1.0e-12
  2793. && std::abs ((double) timing.frames - 96000.0 * wanted) < 96000.0 * 0.01;
  2794. // the second click on the same file has its stretch ready
  2795. player.previewFile (loop);
  2796. const auto cachedOk = ! player.getPreviewTiming().pending && player.getPreviewTiming().inTime && player.getPreviewTiming().frames == timing.frames;
  2797. player.previewFile ({});
  2798. const auto stoppedOk = ! player.getPreviewTiming().inTime && player.getPreviewInTimeProgress() < 0.0;
  2799. // the start: on the next heard beat while the transport plays (sample exact), at once when it is stopped
  2800. auto firstSample = [] (bool playing, double startTick, int latency) {
  2801. lynx::Transport transport;
  2802. transport.sampleRate.store (48000.0);
  2803. transport.bpm.store (120.0); // 0.04 ticks per sample
  2804. transport.playing.store (playing);
  2805. transport.positionTicks.store (startTick);
  2806. lynx::PreviewPlayer p;
  2807. p.prepareToPlay (48000.0, 512);
  2808. p.setTransport (&transport);
  2809. p.setSyncLatency (latency);
  2810. auto dc = std::make_shared<lynx::SampleData>();
  2811. dc->sampleRate = 48000.0;
  2812. dc->left.assign (48000, 0.5f);
  2813. p.playBrowser (dc, 1.0f, true);
  2814. juce::AudioBuffer<float> block (2, 512);
  2815. juce::MidiBuffer midi;
  2816. for (int done = 0; done < 48000; done += 512)
  2817. {
  2818. p.processBlock (block, midi);
  2819. for (int i = 0; i < 512; ++i)
  2820. if (block.getSample (0, i) != 0.0f)
  2821. return done + i;
  2822. if (playing)
  2823. transport.positionTicks.store (transport.positionTicks.load() + 512 * transport.ticksPerSample());
  2824. }
  2825. return -1;
  2826. };
  2827. const auto beatOk = firstSample (true, 480.0, 0) == 12000 // half a beat to go: 480 ticks / 0.04
  2828. && firstSample (true, 480.0, 100) == 12100 // the song is heard 100 samples late (PDC)
  2829. && firstSample (true, 960.0, 0) == 0 // on a beat: now
  2830. && firstSample (false, 480.0, 0) == 0; // stopped: a free start
  2831. previewInTimeOk = loop.existsAsFile() && hit.existsAsFile() && offOk && hitOk && queued && stretchedOk && cachedOk && stoppedOk && beatOk;
  2832. dir.deleteRecursively();
  2833. }
  2834. // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
  2835. // original reference byte for byte (.flp record and LYNX plugin state)
  2836. bool substituteOk = false;
  2837. {
  2838. auto song = lynx::Song::makeDefault();
  2839. lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
  2840. vv.format = lynx::ForeignPlugin::Format::vst3;
  2841. const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
  2842. std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
  2843. vv.hasClassId = true;
  2844. vv.name = "ValhallaVintageVerb";
  2845. vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
  2846. for (int i = 0; i < 777; ++i)
  2847. vv.state.push_back ((std::uint8_t) (i * 13 + 1));
  2848. lynx::EffectSlot fromFlp;
  2849. fromFlp.kind = lynx::EffectKind::plugin;
  2850. fromFlp.plugin.foreign = vv;
  2851. lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
  2852. fromLynx.kind = lynx::EffectKind::plugin;
  2853. fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
  2854. fromLynx.plugin.name = "FabFilter Pro-Q 3";
  2855. fromLynx.plugin.state = "AAECAwQFBgcICQ==";
  2856. const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
  2857. song.mixer[1].effects = { fromFlp, fromLynx };
  2858. const auto substitutesOn = lynx::pluginSubstitutesEnabled();
  2859. const auto changed = offline.getPluginHost().applySubstitutes (song);
  2860. auto& fx = song.mixer[1].effects;
  2861. // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
  2862. const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
  2863. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2864. substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
  2865. && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
  2866. && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
  2867. && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
  2868. && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
  2869. }
  2870. // undo/redo
  2871. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  2872. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  2873. offline.undo();
  2874. const auto afterUndo = offline.getSong().bpm;
  2875. offline.redo();
  2876. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  2877. && offline.isModified();
  2878. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  2879. // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
  2880. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  2881. {
  2882. auto o = offline.getRecordOptions();
  2883. o.mode = lynx::RecordMode::overdub;
  2884. offline.setRecordOptions (o);
  2885. }
  2886. offline.setRecording (true);
  2887. offline.play();
  2888. offline.getTransport().positionTicks.store (960.0);
  2889. offline.sendLiveNote (2, 72, 0.9f, true, true);
  2890. offline.getTransport().positionTicks.store (1920.0);
  2891. offline.sendLiveNote (2, 72, 0.0f, false, true);
  2892. offline.setRecording (false);
  2893. offline.stop();
  2894. const auto& recorded = offline.getSong().patterns[0].notes;
  2895. const auto recordOk = recorded.size() == notesBefore + 1
  2896. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  2897. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  2898. });
  2899. offline.undo();
  2900. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  2901. // FL's Tools › Cancel recording (round 187a): the pass's notes go, an edit made before it stays, recording turns
  2902. // off and playback goes on; nothing to redo
  2903. bool cancelRecordOk = false;
  2904. {
  2905. offline.editSong ([] (lynx::Song& s) { s.bpm = 123.0; });
  2906. const auto notesThen = offline.getSong().patterns[0].notes.size();
  2907. offline.setRecording (true);
  2908. offline.play();
  2909. offline.getTransport().positionTicks.store (960.0);
  2910. offline.sendLiveNote (2, 74, 0.9f, true, true);
  2911. offline.getTransport().positionTicks.store (1920.0);
  2912. offline.sendLiveNote (2, 74, 0.0f, false, true);
  2913. offline.sendLiveNote (2, 76, 0.9f, true, true); // (still held when the pass is cancelled)
  2914. const auto cancelled = offline.cancelRecording();
  2915. cancelRecordOk = cancelled && ! offline.isRecording() && offline.getTransport().playing.load()
  2916. && offline.getSong().patterns[0].notes.size() == notesThen && offline.getSong().bpm == 123.0 && ! offline.canRedo()
  2917. && ! offline.cancelRecording(); // (not recording: nothing to cancel)
  2918. offline.sendLiveNote (2, 76, 0.0f, false, false);
  2919. offline.stop();
  2920. }
  2921. // MIDI: exporting the pattern and importing it back gives the same notes
  2922. bool midiOk = false;
  2923. {
  2924. auto source = lynx::Song::makeDefault();
  2925. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  2926. source.patterns[0].sortNotes();
  2927. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  2928. juce::String midiError;
  2929. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  2930. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  2931. midiFile.deleteFile();
  2932. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  2933. && std::abs (song->bpm - source.bpm) < 0.01)
  2934. {
  2935. midiOk = true;
  2936. const auto& a = source.patterns[0].notes;
  2937. const auto& b = song->patterns[0].notes;
  2938. for (std::size_t i = 0; i < a.size(); ++i)
  2939. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  2940. }
  2941. }
  2942. // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
  2943. // finds its sample inside the extracted folder
  2944. bool packageOk = false;
  2945. {
  2946. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
  2947. dir.deleteRecursively();
  2948. dir.getChildFile ("src").createDirectory();
  2949. const auto wav = dir.getChildFile ("src/hit.wav");
  2950. {
  2951. juce::WavAudioFormat format;
  2952. juce::AudioBuffer<float> hit (1, 480);
  2953. for (int i = 0; i < 480; ++i)
  2954. hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
  2955. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  2956. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  2957. {
  2958. out.release();
  2959. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  2960. writer->writeFromAudioSampleBuffer (hit, 0, 480);
  2961. }
  2962. }
  2963. auto source = lynx::Song::makeDefault();
  2964. lynx::ChannelDef c;
  2965. c.name = "Hit";
  2966. c.instrument = lynx::InstrumentKind::sampler;
  2967. c.samplePath = wav.getFullPathName().toStdString();
  2968. source.channels.push_back (c);
  2969. lynx::ProjectPackage::Result packed;
  2970. juce::String packageError;
  2971. const auto zip = dir.getChildFile ("Beat.zip");
  2972. if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
  2973. {
  2974. const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
  2975. const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
  2976. if (song && ! song->channels.empty())
  2977. {
  2978. const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
  2979. packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
  2980. }
  2981. }
  2982. dir.deleteRecursively();
  2983. }
  2984. // D#92, round 180a: a non-ASCII folder and a dotted name save and load back; an unwritable place says so, and a
  2985. // relative path resolves as the start-up argument does
  2986. bool projectSaveOk = false;
  2987. {
  2988. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-save180a");
  2989. dir.deleteRecursively();
  2990. const auto folder = dir.getChildFile (juce::String::fromUTF8 ("M\xc3\xbasica nova"));
  2991. folder.createDirectory();
  2992. const auto named = lynx::ProjectFile::withProjectExtension (folder.getChildFile (juce::String::fromUTF8 ("Can\xc3\xa7\xc3\xa3o.v2")));
  2993. auto song = lynx::Song::makeDefault();
  2994. lynx::Note note;
  2995. note.length = 240;
  2996. note.key = 64;
  2997. song.patterns[0].notes.push_back (note);
  2998. juce::String error, blockedError;
  2999. const auto again = lynx::ProjectFile::save (song, named, error) ? lynx::ProjectFile::load (named, error) : std::nullopt;
  3000. const auto blocker = dir.getChildFile ("a file");
  3001. blocker.replaceWithText ("x");
  3002. const auto cwd = juce::File::getCurrentWorkingDirectory();
  3003. folder.setAsCurrentWorkingDirectory();
  3004. const auto relative = juce::File::getCurrentWorkingDirectory().getChildFile (named.getFileName());
  3005. cwd.setAsCurrentWorkingDirectory();
  3006. projectSaveOk = named.getFileName().endsWith (".v2.lynx") && again && again->patterns[0].notes.size() == song.patterns[0].notes.size()
  3007. && relative == named && ! lynx::ProjectFile::save (song, blocker.getChildFile ("x.lynx"), blockedError)
  3008. && blockedError.isNotEmpty() && lynx::ProjectFile::withProjectExtension (named) == named;
  3009. dir.deleteRecursively();
  3010. }
  3011. // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
  3012. // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
  3013. juce::String sessionResult = "ERROR";
  3014. {
  3015. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
  3016. dir.deleteRecursively();
  3017. dir.getChildFile ("src").createDirectory();
  3018. const auto wav = dir.getChildFile ("src/hit.wav");
  3019. {
  3020. juce::WavAudioFormat format;
  3021. juce::AudioBuffer<float> hit (1, 4800);
  3022. for (int i = 0; i < 4800; ++i)
  3023. hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
  3024. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  3025. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  3026. {
  3027. out.release();
  3028. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  3029. writer->writeFromAudioSampleBuffer (hit, 0, 4800);
  3030. }
  3031. }
  3032. auto host = lynx::Song::makeDefault();
  3033. host.mode = lynx::PlayMode::song;
  3034. const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
  3035. wav.copyFileTo (copyOfWav);
  3036. for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
  3037. {
  3038. lynx::ChannelDef c;
  3039. c.name = name;
  3040. c.instrument = lynx::InstrumentKind::sampler;
  3041. c.samplePath = file.getFullPathName().toStdString();
  3042. host.channels.push_back (c);
  3043. }
  3044. const auto hitChannel = (int) host.channels.size() - 2;
  3045. lynx::Note hitNote;
  3046. hitNote.channel = hitChannel;
  3047. hitNote.length = 480;
  3048. host.patterns[0].notes.push_back (hitNote);
  3049. host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.beatsPerBar), 0 });
  3050. lynx::uids::normalize (host);
  3051. const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
  3052. juce::String e;
  3053. std::vector<lynx::sessionpack::Rendered> rendered;
  3054. // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
  3055. const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
  3056. const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
  3057. && rendered.size() == 1 && rendered[0].standIns.size() == 2
  3058. && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
  3059. if (renderedOk)
  3060. lynx::sessionpack::apply (host, rendered);
  3061. lynx::sessionpack::Manifest m;
  3062. m.projectName = "Selftest";
  3063. m.from = *host.session.find (lynx::session::hostTag);
  3064. m.to = *host.session.find (2);
  3065. lynx::sessionpack::WriteResult written;
  3066. const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
  3067. const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
  3068. && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
  3069. auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
  3070. bool openOk = false, mergeOk = false;
  3071. if (opened && opened->corrupt.isEmpty())
  3072. {
  3073. const auto& g = opened->song;
  3074. const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
  3075. openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
  3076. && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
  3077. && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
  3078. // the guest adds a channel and a pattern of his own, sends his part back
  3079. auto copy = g;
  3080. lynx::ChannelDef mine;
  3081. mine.name = "Ana's hit";
  3082. mine.instrument = lynx::InstrumentKind::sampler;
  3083. mine.samplePath = sample.getFullPathName().toStdString();
  3084. copy.channels.push_back (mine);
  3085. lynx::Pattern p;
  3086. p.name = "Ana";
  3087. lynx::Note note;
  3088. note.channel = (int) copy.channels.size() - 1;
  3089. note.length = 240;
  3090. note.key = 64;
  3091. p.notes.push_back (note);
  3092. copy.patterns.push_back (p);
  3093. lynx::uids::normalize (copy);
  3094. // its uids survive a save and a load
  3095. const auto saved = dir.getChildFile ("guest.lynx");
  3096. auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
  3097. lynx::sessionpack::Manifest back;
  3098. back.part = true;
  3099. back.from = *copy.session.self();
  3100. const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
  3101. lynx::sessionpack::WriteResult partWritten;
  3102. auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
  3103. ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
  3104. : false;
  3105. auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
  3106. if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
  3107. {
  3108. const auto report = lynx::parts::merge (host, partOpened->song, 2);
  3109. const auto& added = host.channels.back();
  3110. mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
  3111. && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
  3112. && host.channels[(std::size_t) hitChannel].name == "Hit";
  3113. }
  3114. }
  3115. // a crafted package whose project points at a file elsewhere on this computer: opening it must not
  3116. // reach that file, or merging would copy it into the project and the next package would send it on
  3117. if (mergeOk)
  3118. {
  3119. const auto secret = dir.getChildFile ("secret.wav");
  3120. wav.copyFileTo (secret);
  3121. auto evil = lynx::Song::makeDefault();
  3122. lynx::ChannelDef c;
  3123. c.instrument = lynx::InstrumentKind::sampler;
  3124. c.samplePath = secret.getFullPathName().toStdString();
  3125. evil.channels.push_back (c);
  3126. lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
  3127. keys.instrument = lynx::InstrumentKind::flkeys;
  3128. keys.zones.push_back ({});
  3129. keys.zones.back().path = c.samplePath;
  3130. evil.channels.push_back (keys);
  3131. lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
  3132. patch.instrument = lynx::InstrumentKind::patcher;
  3133. patch.patcher.nodes.resize (2);
  3134. patch.patcher.nodes[0].generator = true;
  3135. patch.patcher.nodes[0].channel = c;
  3136. patch.patcher.nodes[1].effect.samplePath = c.samplePath;
  3137. evil.channels.push_back (patch);
  3138. evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
  3139. const auto evilProject = dir.getChildFile ("evil.lynx");
  3140. lynx::sessionpack::Manifest em;
  3141. em.part = true;
  3142. juce::ZipFile::Builder b;
  3143. const auto json = lynx::sessionpack::manifestToJson (em);
  3144. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  3145. const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
  3146. bool zipped = false;
  3147. if (lynx::ProjectFile::save (evil, evilProject, e))
  3148. {
  3149. b.addFile (evilProject, 0, "project.lynx");
  3150. juce::FileOutputStream out (evilPack);
  3151. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  3152. }
  3153. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
  3154. const auto media = dir.getChildFile ("Session media/Evil");
  3155. mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
  3156. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  3157. return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
  3158. || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
  3159. })
  3160. && evilOpened->song.channels.back().patcher.nodes.size() == 2
  3161. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
  3162. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
  3163. && evilOpened->song.mixer[1].recordTo.empty()
  3164. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  3165. if (! mergeOk && e.isEmpty())
  3166. e = "a received package reached a file outside it";
  3167. }
  3168. // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
  3169. // media entry outside the package (it must not even be read: "/dev/zero" would never end)
  3170. if (mergeOk)
  3171. {
  3172. const auto secret = dir.getChildFile ("secret.wav");
  3173. const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
  3174. const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
  3175. const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
  3176. auto evil = lynx::Song::makeDefault();
  3177. for (const auto& path : { climb, dotted })
  3178. {
  3179. lynx::ChannelDef c;
  3180. c.instrument = lynx::InstrumentKind::sampler;
  3181. c.samplePath = path.toStdString();
  3182. evil.channels.push_back (c);
  3183. }
  3184. juce::MemoryBlock secretBytes;
  3185. secret.loadFileAsData (secretBytes);
  3186. lynx::sessionpack::Manifest em;
  3187. em.part = true;
  3188. em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
  3189. "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
  3190. const auto evilProject = dir.getChildFile ("evil2.lynx");
  3191. juce::ZipFile::Builder b;
  3192. const auto json = lynx::sessionpack::manifestToJson (em);
  3193. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  3194. const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
  3195. bool zipped = false;
  3196. if (lynx::ProjectFile::save (evil, evilProject, e))
  3197. {
  3198. b.addFile (evilProject, 0, "project.lynx");
  3199. juce::FileOutputStream out (evilPack);
  3200. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  3201. }
  3202. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
  3203. const auto media = dir.getChildFile ("Session media/Evil2");
  3204. mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
  3205. && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
  3206. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  3207. const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
  3208. return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
  3209. })
  3210. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  3211. if (! mergeOk && e.isEmpty())
  3212. e = "a received package climbed out of its folder";
  3213. }
  3214. if (! packOk && e.isEmpty())
  3215. e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
  3216. + written.missing.joinIntoString (";");
  3217. sessionResult = mergeOk ? juce::String ("OK")
  3218. : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
  3219. dir.deleteRecursively();
  3220. }
  3221. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  3222. juce::String wavpack = "NO_FL";
  3223. {
  3224. const auto roots = lynx::findFlStudioRoots();
  3225. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  3226. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  3227. if (! found.isEmpty())
  3228. {
  3229. lynx::SampleLibrary library;
  3230. const auto sample = library.load (found.getFirst().getFullPathName());
  3231. float peakWv = 0.0f;
  3232. if (sample != nullptr)
  3233. for (std::size_t i = 0; i < sample->frames(); ++i)
  3234. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  3235. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  3236. }
  3237. }
  3238. // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
  3239. const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
  3240. // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
  3241. // generator one plays through the rack
  3242. bool patcherOk = false;
  3243. {
  3244. auto song = lynx::Song::makeDefault();
  3245. song.mixer.resize (4);
  3246. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  3247. lynx::PatchNode reverb, gain;
  3248. reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
  3249. reverb.label = "Room";
  3250. reverb.x = 120.5f;
  3251. reverb.y = 40.0f;
  3252. gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  3253. gain.effect.enabled = false;
  3254. slot.patcher.nodes = { reverb, gain };
  3255. lynx::PatchWire a, b, c, control;
  3256. a.to = 0;
  3257. b.from = 0, b.to = 1, b.gain = 0.5f;
  3258. c.from = 1;
  3259. control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
  3260. slot.patcher.wires = { a, b, c, control };
  3261. slot.patcher.outputTracks = { 3 };
  3262. song.mixer[1].effects = { slot };
  3263. lynx::ChannelDef ch;
  3264. ch.name = "Patched";
  3265. ch.instrument = lynx::InstrumentKind::patcher;
  3266. lynx::PatchNode synth;
  3267. synth.generator = true;
  3268. synth.channel.instrument = lynx::InstrumentKind::synth;
  3269. synth.channel.name = "Synth";
  3270. ch.patcher.nodes = { synth };
  3271. lynx::PatchWire notes, out;
  3272. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  3273. out.from = 0;
  3274. ch.patcher.wires = { notes, out };
  3275. // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
  3276. lynx::PatchNode midiOutNode;
  3277. midiOutNode.generator = true;
  3278. midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
  3279. lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
  3280. ch.patcher.nodes.push_back (midiOutNode);
  3281. lynx::PatchWire portIn, portOut;
  3282. portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
  3283. portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
  3284. portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
  3285. ch.patcher.wires.push_back (portIn);
  3286. ch.patcher.wires.push_back (portOut);
  3287. ch.patcher.fromMidiPorts = { 2, 7 };
  3288. ch.patcher.toMidiPorts = { 9, 11 };
  3289. ch.patcher.fromNotesHidden = true;
  3290. song.channels.push_back (ch);
  3291. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3292. patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
  3293. && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
  3294. && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
  3295. && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
  3296. && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
  3297. && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
  3298. && back->channels.back().patcher.nodes[0].generator
  3299. && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
  3300. && back->channels.back().patcher.wires == ch.patcher.wires;
  3301. }
  3302. // Round 183c, Racks: (1) a plain Patcher's stored JSON loads and saves back byte for byte and never holds a
  3303. // "rack" key (FL's Patcher is untouched); (2) an Audio Effect Rack slot and an Instrument Rack channel survive save /
  3304. // load with their chains, zones, macros, mappings, variations and compiled cables
  3305. juce::String rackResult = "OK";
  3306. {
  3307. lynx::MixerTrack plain;
  3308. plain.name = "Plain Patcher";
  3309. auto fx = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  3310. lynx::PatchNode a, b;
  3311. a.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  3312. a.label = "A";
  3313. a.x = 120.5f;
  3314. b.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  3315. b.effect.enabled = false;
  3316. fx.patcher.nodes = { a, b };
  3317. lynx::PatchWire w1, w2, w3, wc;
  3318. w1.to = 0;
  3319. w2.from = 0, w2.to = 1, w2.gain = 0.5f;
  3320. w3.from = 1;
  3321. wc.kind = lynx::PatchWire::Kind::control, wc.from = 0, wc.to = 1, wc.toPort = 0, wc.curve = { 0.0f, 0.25f, 1.0f };
  3322. fx.patcher.wires = { w1, w2, w3, wc };
  3323. lynx::SurfaceControl knob;
  3324. knob.name = "Drive";
  3325. knob.value = 0.25f;
  3326. fx.patcher.surface = { knob };
  3327. lynx::PatchParam pp;
  3328. pp.node = 0, pp.param = 1, pp.name = "Balance";
  3329. fx.patcher.published = { pp };
  3330. plain.effects = { fx };
  3331. const auto first = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (plain), true);
  3332. const auto again = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (first))), true);
  3333. if (first != again || first.contains ("\"rack\"") || first.contains ("rackMixer"))
  3334. rackResult = "ERROR plain Patcher changed";
  3335. auto song = lynx::Song::makeDefault();
  3336. song.mixer.resize (3);
  3337. auto rackSlot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  3338. auto& doc = rackSlot.patcher;
  3339. lynx::PatchNode u;
  3340. u.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  3341. const auto n0 = lynx::rack::addDevice (doc, 0, u);
  3342. lynx::rack::addChain (doc, "Wet");
  3343. lynx::rack::addDevice (doc, 1, u);
  3344. doc.rack[0].chains[1].select = { 10, 90, 30, 70 };
  3345. lynx::rack::setChainPan (doc, 1, -0.5f);
  3346. lynx::RackMapping m;
  3347. m.node = n0, m.param = 0, m.min = 0.2f, m.max = 0.9f;
  3348. lynx::rack::map (doc, 0, m);
  3349. lynx::RackMapping v;
  3350. v.target = lynx::RackMapping::Target::chainVolume, v.chain = 1, v.min = 0.0f, v.max = lynx::rack::unityVolume;
  3351. lynx::rack::map (doc, 1, v);
  3352. lynx::rack::setMacro (doc, 0, 64.0f);
  3353. lynx::rack::storeVariation (doc);
  3354. lynx::rack::setMacro (doc, 0, 100.0f);
  3355. lynx::rack::storeVariation (doc);
  3356. doc.rack[0].morphOn = true, doc.rack[0].morphA = 0, doc.rack[0].morphB = 1;
  3357. lynx::rack::setMorph (doc, 0.5f);
  3358. lynx::rack::compile (doc);
  3359. song.mixer[1].effects = { rackSlot };
  3360. lynx::ChannelDef inst;
  3361. inst.name = "Instrument Rack";
  3362. inst.instrument = lynx::InstrumentKind::patcher;
  3363. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  3364. lynx::PatchNode synth;
  3365. synth.generator = true;
  3366. synth.channel.instrument = lynx::InstrumentKind::synth;
  3367. synth.channel.name = "Synth";
  3368. lynx::rack::addDevice (inst.patcher, 0, synth);
  3369. inst.patcher.rack[0].chains[0].velocity = { 1, 127, 64, 127 };
  3370. lynx::rack::compile (inst.patcher);
  3371. song.channels.push_back (inst);
  3372. const auto json = lynx::ProjectFile::toJson (song);
  3373. const auto back = lynx::ProjectFile::fromJson (json, error);
  3374. // (the devices' parameters are stored to 4 decimals: the documents are compared as stored, the rack exactly)
  3375. const auto loaded = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1;
  3376. const auto& got = loaded ? back->mixer[1].effects[0].patcher : doc;
  3377. if (! loaded)
  3378. rackResult = "ERROR rack slot not loaded";
  3379. else if (got.rack != doc.rack)
  3380. rackResult = "ERROR rack model";
  3381. else if (got.wires != doc.wires)
  3382. rackResult = "ERROR rack cables";
  3383. else if (got.nodes.size() != doc.nodes.size())
  3384. rackResult = "ERROR rack devices";
  3385. else if (back->channels.back().patcher.rack != inst.patcher.rack || back->channels.back().patcher.wires != inst.patcher.wires
  3386. || back->channels.back().patcher.zones != inst.patcher.zones || back->channels.back().patcher.nodes.size() != inst.patcher.nodes.size())
  3387. rackResult = "ERROR instrument rack";
  3388. // the slot's insert as stored, once more: the same text (the stored form is stable)
  3389. else if (const auto once = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (back->mixer[1]), true);
  3390. once != juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (once))), true))
  3391. rackResult = "ERROR rack stored form not stable";
  3392. }
  3393. // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
  3394. // the instruments play through the rack
  3395. juce::String nativesResult = "OK";
  3396. int nativesMade = 0, nativesSilent = 0;
  3397. {
  3398. auto song = lynx::Song::makeDefault();
  3399. song.channels.clear();
  3400. song.patterns[0].notes.clear();
  3401. song.mixer.resize (3);
  3402. const auto& fl = lynx::flStudioAccess();
  3403. for (const auto& e : lynx::natives::instrumentEngines())
  3404. if (lynx::natives::available (e, fl))
  3405. if (auto c = lynx::natives::makeChannel (e.kind, fl))
  3406. {
  3407. c->mixerTrack = 1;
  3408. song.channels.push_back (*c);
  3409. }
  3410. for (const auto& e : lynx::natives::effectEngines())
  3411. if (auto fx = lynx::natives::makeSlot (e.kind, fl))
  3412. song.mixer[2].effects.push_back (*fx);
  3413. nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
  3414. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3415. auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
  3416. && back->mixer[2].effects.size() == song.mixer[2].effects.size();
  3417. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  3418. {
  3419. const auto& a = song.channels[i];
  3420. const auto& b = back->channels[i];
  3421. same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
  3422. && a.modelParams.size() == b.modelParams.size();
  3423. if (! same)
  3424. nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
  3425. }
  3426. for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
  3427. {
  3428. const auto& a = song.mixer[2].effects[i];
  3429. const auto& b = back->mixer[2].effects[i];
  3430. same = a.kind == b.kind && a.state == b.state;
  3431. for (std::size_t p = 0; same && p < a.params.size(); ++p)
  3432. same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
  3433. if (! same)
  3434. nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
  3435. }
  3436. if (! back)
  3437. nativesResult = "ERROR " + error;
  3438. // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
  3439. // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
  3440. // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
  3441. const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
  3442. {
  3443. juce::WavAudioFormat format;
  3444. juce::AudioBuffer<float> tone (1, 48000);
  3445. for (int i = 0; i < 48000; ++i)
  3446. tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
  3447. toneWav.deleteFile();
  3448. std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
  3449. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  3450. {
  3451. out.release();
  3452. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  3453. writer->writeFromAudioSampleBuffer (tone, 0, 48000);
  3454. }
  3455. }
  3456. juce::StringArray silentNames;
  3457. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  3458. {
  3459. auto one = song;
  3460. one.channels = { song.channels[i] };
  3461. one.channels[0].mixerTrack = 1;
  3462. const auto kind = song.channels[i].instrument;
  3463. // A new Fruity Slicer has no sample and no slices, and FL's is silent then too (round 180c), so it is
  3464. // not one of the engines that must sound here (Linux / macOS CI: "SILENT 1 [Fruity Slicer]", 0.1.25)
  3465. if (kind == lynx::InstrumentKind::fruityslicer && one.channels[0].samplePath.empty())
  3466. continue;
  3467. if (kind == lynx::InstrumentKind::slicex && one.channels[0].samplePath.empty()) // (the same: no sample on its decks yet)
  3468. continue;
  3469. if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
  3470. one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
  3471. one.mixer[2].effects.clear();
  3472. // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
  3473. // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
  3474. auto key = 60;
  3475. if (kind == lynx::InstrumentKind::drumaxx)
  3476. {
  3477. const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
  3478. key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
  3479. }
  3480. // FPC plays its pads' keys; a kit without a sample (FL's "Empty" kit: no FL Studio on this PC) is silent
  3481. // in FL too (round 190q)
  3482. if (kind == lynx::InstrumentKind::fpc)
  3483. {
  3484. const auto pads = lynx::fpcChannelPads (one.channels[0]);
  3485. if (pads.empty())
  3486. continue;
  3487. key = pads.front().key;
  3488. }
  3489. one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
  3490. lynx::AudioEngine player (false);
  3491. player.setSong (std::move (one));
  3492. player.dispatchPendingMessages();
  3493. if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
  3494. {
  3495. ++nativesSilent;
  3496. silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
  3497. }
  3498. }
  3499. toneWav.deleteFile();
  3500. if (nativesSilent > 0 && nativesResult == "OK")
  3501. nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
  3502. }
  3503. const auto nativesOk = nativesResult == "OK";
  3504. // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
  3505. // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
  3506. // insert 2 (muted: silent); never in an export
  3507. juce::String metronomeResult = "OK";
  3508. int metronomeFlSounds = 0;
  3509. float metronomeMaster = 0.0f;
  3510. {
  3511. const auto& flData = lynx::flStudioAccess().roots.data;
  3512. const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
  3513. for (const auto& s : sounds)
  3514. metronomeFlSounds += s.fromFl ? 1 : 0;
  3515. auto renderClick = [] (int track, bool muteInsert, bool include) {
  3516. auto song = lynx::Song::makeDefault();
  3517. song.channels.clear();
  3518. song.playlist.clear();
  3519. for (auto& p : song.patterns)
  3520. p.notes.clear();
  3521. song.mixer[0].effects.clear(); // (the default Master limiter)
  3522. song.mixer[2].muted = muteInsert;
  3523. lynx::AudioEngine player (false);
  3524. player.setSong (std::move (song));
  3525. player.dispatchPendingMessages();
  3526. auto& t = player.getTransport();
  3527. t.metronome = true;
  3528. t.metronomeSound = 1; // Tick
  3529. t.metronomeTrack = track;
  3530. lynx::AudioEngine::RenderOptions o;
  3531. o.seconds = 0.25;
  3532. o.sampleRate = 44100.0;
  3533. o.pluginWarmUp = false;
  3534. o.includeMetronome = include;
  3535. return player.renderOffline (o);
  3536. };
  3537. metronomeMaster = renderClick (0, false, true);
  3538. const auto insert = renderClick (2, false, true);
  3539. const auto muted = renderClick (2, true, true);
  3540. const auto exported = renderClick (0, false, false);
  3541. // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
  3542. const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
  3543. if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
  3544. metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
  3545. else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
  3546. metronomeResult = "ERROR insert " + juce::String (insert, 4);
  3547. else if (muted > 1.0e-4f)
  3548. metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
  3549. else if (exported > 1.0e-4f)
  3550. metronomeResult = "ERROR in export " + juce::String (exported, 4);
  3551. }
  3552. const auto metronomeOk = metronomeResult == "OK";
  3553. // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
  3554. const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
  3555. // issue #134 (round 190c): the output device, its rate and its buffer changed under a playing project, on
  3556. // stand-in devices (a short run; --devicechangetest plays every instrument and effect)
  3557. const auto deviceChange = lynx::AudioEngine::deviceChangeSelfTest (10, false);
  3558. // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
  3559. // through it, the invite code's keys)
  3560. const auto liveResult = lynx::livetest::selfTest (&rich);
  3561. // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
  3562. // mask...), at odd values, through a project save and reload: the same floats back
  3563. juce::String effectParamsResult = "OK";
  3564. {
  3565. auto song = lynx::Song::makeDefault();
  3566. song.mixer.resize (1);
  3567. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  3568. {
  3569. const auto kind = (lynx::EffectKind) k;
  3570. if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
  3571. continue;
  3572. auto fx = lynx::makeEffectSlot (kind);
  3573. for (std::size_t i = 0; i < fx.params.size(); ++i)
  3574. {
  3575. auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
  3576. fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
  3577. }
  3578. if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
  3579. fx.params[3] = 0.0f;
  3580. song.mixer.emplace_back();
  3581. song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
  3582. song.mixer.back().effects.push_back (fx);
  3583. }
  3584. // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
  3585. // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
  3586. {
  3587. auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  3588. for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
  3589. lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
  3590. {
  3591. lynx::PatchNode node;
  3592. node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  3593. if (kind == lynx::EffectKind::peakController)
  3594. node.effect.params[7] = 32750.0f / 65336.0f;
  3595. node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
  3596. patch.patcher.nodes.push_back (node);
  3597. }
  3598. song.mixer.emplace_back();
  3599. song.mixer.back().name = "Patcher";
  3600. song.mixer.back().effects.push_back (patch);
  3601. }
  3602. juce::String why;
  3603. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  3604. if (back && back->mixer.size() == song.mixer.size())
  3605. {
  3606. const auto& a = song.mixer.back().effects[0].patcher.nodes;
  3607. const auto& b = back->mixer.back().effects[0].patcher.nodes;
  3608. for (std::size_t n = 0; n < a.size(); ++n)
  3609. if (n >= b.size() || ! (a[n].effect == b[n].effect))
  3610. effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
  3611. }
  3612. if (! back || back->mixer.size() != song.mixer.size())
  3613. effectParamsResult = "ERROR load " + why;
  3614. else
  3615. for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
  3616. if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
  3617. {
  3618. effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
  3619. break;
  3620. }
  3621. }
  3622. // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
  3623. const auto artResult = lynx::skin::artSelfTest();
  3624. // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
  3625. const auto sidechainResult = lynx::pluginSidechainSelfTest();
  3626. // round 190ap: the Versions panel's list of files, and its labels on disk beside them
  3627. const auto versionsResult = lynx::versionsSelfTest();
  3628. // round 190ap: a project opened with its plugins off creates none of them and saves their settings unchanged
  3629. const auto pluginsOffResult = lynx::pluginsOffSelfTest();
  3630. // round 177b: automation lanes come back from a project (track, automation, height, folded)
  3631. juce::String lanesResult = "OK";
  3632. {
  3633. auto song = lynx::Song::makeDefault();
  3634. const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
  3635. song.playlistTracks[3].lanes[0].height = 72;
  3636. song.playlistTracks[3].lanesFolded = true;
  3637. // (the same round's clip LFO and modulators ride along)
  3638. auto& lfo = song.automations[(std::size_t) lane].lfo;
  3639. lfo.on = true;
  3640. lfo.level = -40;
  3641. lfo.speed = 30000;
  3642. lfo.flags = 1 | 4;
  3643. lfo.phase = 123456789u;
  3644. lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
  3645. lynx::Modulator mod;
  3646. mod.name = "LFO 1";
  3647. mod.shape = lynx::ModShape::square;
  3648. mod.sync = false;
  3649. mod.hz = 2.5;
  3650. mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  3651. song.modulators.push_back (mod);
  3652. juce::String why;
  3653. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  3654. if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
  3655. || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
  3656. || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
  3657. || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
  3658. lanesResult = "ERROR " + why;
  3659. }
  3660. const auto mixerBasics = lynx::mixerbasics::run();
  3661. // issue #142: every font has a typeface, and one without does not crash (fonts get theirs through the
  3662. // look and feel, as in the app)
  3663. auto& lookBefore = juce::LookAndFeel::getDefaultLookAndFeel();
  3664. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3665. const auto fontsResult = lynx::theme::fontSelfTest();
  3666. juce::LookAndFeel::setDefaultLookAndFeel (&lookBefore);
  3667. const auto ok = mixerBasics == "OK" && fontsResult == "OK" && audioOk && projectOk && trackModes122Ok && richOk && hwOutOk && hostKeysOk && pluginLevelsOk && flp168jOk && clipFades180dOk && blocksOk && compOk && polyOk && latencyOk && preSendOk && lowLatencyOk && previewInTimeOk && substituteOk && patcherOk && rackResult == "OK" && nativesOk && undoOk && projectSaveOk && recordOk && recordUndoOk && cancelRecordOk && midiOk && packageOk
  3668. && sessionResult == "OK" && liveResult.startsWith ("OK")
  3669. && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && deviceChange.startsWith ("OK") && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
  3670. && sidechainResult == "OK" && lanesResult == "OK" && versionsResult == "OK" && pluginsOffResult == "OK";
  3671. juce::String report;
  3672. report << "connections=" << offline.getNumGraphConnections() << "\n"
  3673. << "peak=" << peak << "\n"
  3674. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  3675. << "playlist_track_modes_roundtrip=" << (trackModes122Ok ? "OK" : "ERROR") << "\n"
  3676. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  3677. << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
  3678. << "plugin_host_keys_option=" << (hostKeysOk ? "OK" : "ERROR") << "\n"
  3679. << "plugin_levels_new_project=" << (pluginLevelsOk ? "OK" : "ERROR") << "\n"
  3680. << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
  3681. << "clip_fades_180d=" << (clipFades180dOk ? "OK" : "ERROR") << "\n"
  3682. << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
  3683. << "comp_crossfades=" << (compOk ? "OK" : "ERROR") << "\n"
  3684. << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
  3685. << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
  3686. << "pre_fader_sends=" << (preSendOk ? "OK" : "ERROR") << "\n"
  3687. << "low_latency_recording=" << (lowLatencyOk ? "OK" : "ERROR") << "\n"
  3688. << "preview_in_time=" << (previewInTimeOk ? "OK" : "ERROR") << " (2 s loop prepared in " << juce::String (previewPrepareMs, 1) << " ms)\n"
  3689. << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
  3690. << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
  3691. << "racks=" << rackResult << "\n"
  3692. << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
  3693. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  3694. << "mixer_basics=" << mixerBasics << "\n"
  3695. << "fonts=" << fontsResult << "\n"
  3696. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  3697. << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
  3698. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  3699. << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
  3700. << "projectSave=" << (projectSaveOk ? "OK" : "ERROR") << "\n"
  3701. << "online_session=" << sessionResult << "\n"
  3702. << "live_session=" << liveResult << "\n"
  3703. << "wavpack=" << wavpack << "\n"
  3704. << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
  3705. << "effect_params_saved=" << effectParamsResult << "\n"
  3706. << "driver_panel=" << driverPanel << "\n"
  3707. << "device_change=" << deviceChange << "\n"
  3708. << "plugin_art=" << artResult << "\n"
  3709. << "plugin_sidechain=" << sidechainResult << "\n"
  3710. << "versions_panel=" << versionsResult << "\n"
  3711. << "plugins_off=" << pluginsOffResult << "\n"
  3712. << "lanes_saved=" << lanesResult << "\n"
  3713. << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
  3714. << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n";
  3715. // issue #138 (round 190c): a short note at the very start of the Playlist against the same note at bar 2, through
  3716. // the Export window's path (its own thread while the message loop runs: the report is finished from there)
  3717. if (reportPath.isNotEmpty())
  3718. juce::File (reportPath).replaceWithText (report + "(short_export running)\n");
  3719. lynx::shortexport::run (false, 1, {}, {}, [this, report, ok, reportPath] (juce::String shortExport) {
  3720. const auto all = ok && shortExport.startsWith ("OK");
  3721. const auto text = report + "short_export=" + shortExport + "\nresult=" + (all ? "OK" : "FAILED") + "\n";
  3722. if (reportPath.isNotEmpty())
  3723. juce::File (reportPath).replaceWithText (text);
  3724. setApplicationReturnValue (all ? 0 : 1);
  3725. quit();
  3726. });
  3727. }
  3728. // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
  3729. // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
  3730. // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
  3731. bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
  3732. {
  3733. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3734. lynx::setNativeEditorDemo (true);
  3735. juce::String report;
  3736. auto allFinite = true;
  3737. {
  3738. lynx::AudioEngine offline (false);
  3739. juce::Random random (111);
  3740. const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
  3741. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  3742. {
  3743. const auto kind = (lynx::EffectKind) k;
  3744. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
  3745. continue;
  3746. const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
  3747. const auto& info = lynx::effectInfo (kind);
  3748. // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
  3749. auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  3750. int dragged = 0; // parameter changes made by the mouse drags
  3751. for (int round = 0; round < rounds; ++round)
  3752. {
  3753. if (round > 0)
  3754. for (std::size_t p = 0; p < info.params.size(); ++p)
  3755. fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
  3756. auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
  3757. song.mixer.resize (2);
  3758. song.mixer[0].name = "Master";
  3759. song.mixer[1].name = "Insert 1";
  3760. song.mixer[1].effects.assign (1, fx);
  3761. for (auto& channel : song.channels)
  3762. channel.mixerTrack = 1;
  3763. offline.setSong (std::move (song));
  3764. offline.dispatchPendingMessages();
  3765. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  3766. for (int page = 0; page < pages; ++page)
  3767. {
  3768. auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  3769. : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  3770. if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
  3771. continue;
  3772. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  3773. const auto paint = [&] {
  3774. juce::Graphics g (image);
  3775. editor->paintEntireComponent (g, false);
  3776. };
  3777. paint();
  3778. // drags from a grid of points, as a user moving every control (plain left button)
  3779. if (round >= 3 && drags)
  3780. {
  3781. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  3782. const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
  3783. for (int y = step / 2; y < editor->getHeight(); y += step)
  3784. for (int x = step / 2; x < editor->getWidth(); x += step)
  3785. {
  3786. auto* target = editor->getComponentAt (x, y);
  3787. if (target == nullptr)
  3788. continue;
  3789. const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
  3790. const auto now = juce::Time::getCurrentTime();
  3791. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
  3792. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
  3793. };
  3794. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  3795. const juce::Component::SafePointer<juce::Component> alive (target);
  3796. target->mouseDown (event (at, down));
  3797. const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
  3798. if (alive != nullptr)
  3799. target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
  3800. if (alive != nullptr)
  3801. target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
  3802. if (alive != nullptr)
  3803. target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
  3804. juce::PopupMenu::dismissAllActiveMenus();
  3805. offline.dispatchPendingMessages();
  3806. }
  3807. paint();
  3808. }
  3809. }
  3810. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  3811. offline.renderOffline (0.05, rate);
  3812. if (round == 0 || round >= 3) // keep what the drags set for the next round
  3813. if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
  3814. {
  3815. const auto& now = offline.getSong().mixer[1].effects[0];
  3816. for (std::size_t p = 0; p < fx.params.size(); ++p)
  3817. dragged += now.params[p] != fx.params[p] ? 1 : 0;
  3818. dragged += now.state != fx.state ? 1 : 0;
  3819. fx = now;
  3820. }
  3821. }
  3822. const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
  3823. allFinite = allFinite && broken == 0;
  3824. report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
  3825. << " (" << dragged << " changes by mouse)\n";
  3826. if (reportPath.isNotEmpty())
  3827. juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
  3828. }
  3829. }
  3830. lynx::setNativeEditorDemo (false);
  3831. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  3832. report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
  3833. if (reportPath.isNotEmpty())
  3834. juce::File (reportPath).replaceWithText (report);
  3835. return allFinite;
  3836. }
  3837. // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
  3838. // native windows are real); one step per timer tick.
  3839. void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
  3840. {
  3841. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3842. struct OpenTest final : juce::Timer
  3843. {
  3844. juce::String reportPath, report;
  3845. bool visible = false, ok = true;
  3846. std::function<void (bool)> done;
  3847. std::unique_ptr<lynx::AudioEngine> engine;
  3848. std::vector<std::pair<juce::String, std::function<void()>>> steps;
  3849. std::size_t next = 0;
  3850. std::atomic<std::int64_t> lastStep { 0 };
  3851. std::atomic<bool> finished { false };
  3852. std::thread watchdog;
  3853. juce::String current;
  3854. std::mutex currentLock;
  3855. int opened = 0, painted = 0;
  3856. // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
  3857. const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
  3858. static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
  3859. void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
  3860. ~OpenTest() override
  3861. {
  3862. finished = true;
  3863. if (watchdog.joinable())
  3864. watchdog.join();
  3865. }
  3866. void start()
  3867. {
  3868. lastStep = now();
  3869. // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
  3870. const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
  3871. folder.deleteRecursively();
  3872. folder.createDirectory();
  3873. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
  3874. watchdog = std::thread ([this] {
  3875. while (! finished)
  3876. {
  3877. std::this_thread::sleep_for (std::chrono::milliseconds (200));
  3878. if (now() - lastStep.load() > timeoutMs)
  3879. {
  3880. juce::String at;
  3881. {
  3882. const std::lock_guard<std::mutex> l (currentLock);
  3883. at = current;
  3884. }
  3885. juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
  3886. lynx::crashguard::exitNow (3);
  3887. }
  3888. }
  3889. });
  3890. startTimer (30);
  3891. }
  3892. // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
  3893. void touchWindows (bool resize, bool large)
  3894. {
  3895. auto& desktop = juce::Desktop::getInstance();
  3896. for (int i = desktop.getNumComponents(); --i >= 0;)
  3897. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
  3898. {
  3899. if (! visible && c->getScreenX() > -3000)
  3900. c->setTopLeftPosition (-6000, -6000);
  3901. if (resize)
  3902. if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
  3903. {
  3904. const auto b = w->getBounds();
  3905. w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
  3906. }
  3907. if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
  3908. {
  3909. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  3910. juce::Graphics g (image);
  3911. c->paintEntireComponent (g, false);
  3912. ++painted;
  3913. // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
  3914. if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
  3915. {
  3916. juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
  3917. if (out.openedOk())
  3918. {
  3919. out.setPosition (0), out.truncate();
  3920. juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  3921. }
  3922. }
  3923. }
  3924. }
  3925. }
  3926. void timerCallback() override
  3927. {
  3928. if (next >= steps.size())
  3929. {
  3930. stopTimer();
  3931. lynx::NativeEffectWindows::closeAll();
  3932. lynx::closeChannelSettings();
  3933. // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
  3934. {
  3935. const auto before = lynx::crashguard::lastHangFile();
  3936. for (const auto until = now() + 7000; now() < until;)
  3937. lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
  3938. for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
  3939. std::this_thread::sleep_for (std::chrono::milliseconds (20));
  3940. lynx::crashguard::stopHangWatch();
  3941. const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
  3942. const auto text = hang.loadFileAsString();
  3943. const auto frames = juce::StringArray::fromLines (text).size() - 2;
  3944. #if JUCE_WINDOWS
  3945. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
  3946. #else
  3947. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
  3948. #endif
  3949. report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
  3950. << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
  3951. ok = ok && hangOk;
  3952. }
  3953. report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
  3954. write();
  3955. finished = true;
  3956. if (done)
  3957. done (ok);
  3958. return;
  3959. }
  3960. auto& [label, fn] = steps[next++];
  3961. {
  3962. const std::lock_guard<std::mutex> l (currentLock);
  3963. current = label;
  3964. }
  3965. fn();
  3966. lastStep = now();
  3967. lynx::crashguard::heartbeat();
  3968. }
  3969. };
  3970. auto* test = new OpenTest();
  3971. test->reportPath = reportPath;
  3972. test->visible = visible;
  3973. test->engine = std::make_unique<lynx::AudioEngine> (false);
  3974. test->done = [test, done] (bool ok) {
  3975. juce::MessageManager::callAsync ([test, done, ok] {
  3976. delete test;
  3977. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  3978. done (ok);
  3979. });
  3980. };
  3981. auto& engine = *test->engine;
  3982. lynx::setNativeEditorDemo (true); // live displays animate without an audio device
  3983. const auto songWith = [] (const lynx::EffectSlot& fx) {
  3984. auto song = lynx::Song::makeDefault();
  3985. song.mixer.resize (2);
  3986. song.mixer[0].name = "Master";
  3987. song.mixer[1].name = "Insert 1";
  3988. song.mixer[1].effects.assign (1, fx);
  3989. for (auto& channel : song.channels)
  3990. channel.mixerTrack = 1;
  3991. return song;
  3992. };
  3993. // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
  3994. // parameters a newer LYNX added after them take their defaults)
  3995. const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
  3996. auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
  3997. if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
  3998. if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
  3999. if (auto* params = (*effects)[0]["params"].getArray())
  4000. params->removeRange ((int) count, params->size());
  4001. juce::String error;
  4002. return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
  4003. };
  4004. auto& steps = test->steps;
  4005. juce::Random random (157);
  4006. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  4007. {
  4008. const auto kind = (lynx::EffectKind) k;
  4009. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  4010. continue;
  4011. const auto& info = lynx::effectInfo (kind);
  4012. const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  4013. const auto n = info.params.size();
  4014. std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
  4015. variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
  4016. for (const auto value : { 0.0f, 1.0f })
  4017. variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
  4018. auto fx = base;
  4019. for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
  4020. return std::optional<lynx::Song> (songWith (fx));
  4021. } });
  4022. const auto seed = random.nextInt64();
  4023. variants.push_back ({ "random", [=] {
  4024. juce::Random r (seed);
  4025. auto fx = base;
  4026. for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
  4027. return std::optional<lynx::Song> (songWith (fx));
  4028. } });
  4029. std::vector<std::size_t> cuts { n / 2 };
  4030. 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)
  4031. if (c < n) cuts.push_back (c);
  4032. for (const auto c : cuts)
  4033. variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
  4034. for (const auto& [variant, makeSong] : variants)
  4035. {
  4036. const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
  4037. steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
  4038. auto song = makeSong();
  4039. if (! song)
  4040. {
  4041. test->report << "FAIL " << label << ": project reader refused the state\n";
  4042. test->ok = false;
  4043. return;
  4044. }
  4045. engine.setSong (std::move (*song));
  4046. engine.dispatchPendingMessages();
  4047. lynx::NativeEffectWindows::open (engine, 1, 0);
  4048. ++test->opened;
  4049. test->touchWindows (false, false);
  4050. } });
  4051. steps.push_back ({ label + ": run", [test, &engine] {
  4052. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  4053. engine.renderOffline (0.03, rate);
  4054. test->touchWindows (false, false);
  4055. } });
  4056. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  4057. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  4058. steps.push_back ({ label + ": close", [test, label] {
  4059. lynx::NativeEffectWindows::closeAll();
  4060. test->report << label << ": OK\n";
  4061. test->write ("(running)\n");
  4062. } });
  4063. }
  4064. }
  4065. // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
  4066. for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
  4067. {
  4068. const auto kind = (lynx::InstrumentKind) k;
  4069. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  4070. continue;
  4071. for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
  4072. {
  4073. if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
  4074. continue;
  4075. const auto label = "instrument " + juce::String (k) + " / " + variant;
  4076. steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
  4077. auto song = lynx::Song::makeDefault();
  4078. auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  4079. lynx::ChannelDef def;
  4080. def.instrument = kind;
  4081. def.name = "Test";
  4082. song.channels.push_back (channel ? *channel : def);
  4083. if (kind == lynx::InstrumentKind::soundfont && variant != "default")
  4084. {
  4085. // a real font when FL's is there; NaN / huge / truncated settings
  4086. const auto& roots = lynx::flStudioAccess().roots;
  4087. if (! roots.data.empty())
  4088. song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  4089. .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
  4090. .getFullPathName().toStdString();
  4091. if (variant == "odd settings")
  4092. song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
  4093. }
  4094. if (old)
  4095. {
  4096. juce::String error;
  4097. if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
  4098. song = std::move (*again);
  4099. }
  4100. const auto index = (int) song.channels.size() - 1;
  4101. engine.setSong (std::move (song));
  4102. engine.dispatchPendingMessages();
  4103. lynx::openChannelSettings (engine, index);
  4104. ++test->opened;
  4105. test->touchWindows (false, false);
  4106. } });
  4107. steps.push_back ({ label + ": run", [test, &engine] {
  4108. engine.renderOffline (0.03, 48000.0);
  4109. test->touchWindows (false, false);
  4110. } });
  4111. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  4112. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  4113. steps.push_back ({ label + ": close", [test, label] {
  4114. lynx::closeChannelSettings();
  4115. test->report << label << ": OK\n";
  4116. test->write ("(running)\n");
  4117. } });
  4118. }
  4119. }
  4120. test->start();
  4121. }
  4122. void runPluginOptionsTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath)
  4123. {
  4124. struct Test final : juce::Timer
  4125. {
  4126. juce::String reportPath, report;
  4127. juce::File shots;
  4128. std::unique_ptr<lynx::AudioEngine> engine;
  4129. std::unique_ptr<juce::DocumentWindow> mainWindow, other; // LYNX's main window stand-in; another secondary window
  4130. bool instrument = false, ok = true;
  4131. int channelIndex = -1, phase = 0;
  4132. juce::uint32 phaseStart = 0;
  4133. juce::AudioPluginInstance* instance = nullptr;
  4134. std::function<void (bool)> done;
  4135. void step (const juce::String& line)
  4136. {
  4137. report << line << "\n";
  4138. juce::File (reportPath).replaceWithText (report);
  4139. }
  4140. void expect (const juce::String& name, bool value)
  4141. {
  4142. step (name + "=" + juce::String ((int) value));
  4143. ok = ok && value;
  4144. }
  4145. void next (int to)
  4146. {
  4147. phase = to;
  4148. phaseStart = juce::Time::getMillisecondCounter();
  4149. }
  4150. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  4151. lynx::PluginRef* ref (lynx::Song& song) const
  4152. {
  4153. if (instrument)
  4154. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  4155. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  4156. }
  4157. const lynx::PluginRef& refNow() const { return *ref (const_cast<lynx::Song&> (engine->getSong())); }
  4158. juce::AudioPluginInstance* find()
  4159. {
  4160. if (instrument)
  4161. {
  4162. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  4163. return &p->getInstance();
  4164. }
  4165. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  4166. return &p->getInstance();
  4167. return nullptr;
  4168. }
  4169. void openWindow()
  4170. {
  4171. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  4172. : std::shared_ptr<void> (engine->getEffect (1, 0));
  4173. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  4174. { engine.get(), [this] (lynx::Song& song) { return ref (song); }, instrument, instrument ? -1 : 1,
  4175. instrument ? -1 : 0, {}, {} });
  4176. }
  4177. void shot (const char* name, bool settingsPage = false)
  4178. {
  4179. if (shots != juce::File() && instance != nullptr)
  4180. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  4181. }
  4182. // the plugin window is in front of the other secondary window
  4183. bool pluginInFront()
  4184. {
  4185. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  4186. #if JUCE_WINDOWS
  4187. return plug != nullptr && lynx::nativechild::isAbove (plug, other->getWindowHandle());
  4188. #else
  4189. auto& desktop = juce::Desktop::getInstance();
  4190. for (int i = 0; i < desktop.getNumComponents(); ++i)
  4191. if (auto* c = desktop.getComponent (i); c->getWindowHandle() == plug)
  4192. return c->isAlwaysOnTop() || desktop.getComponent (desktop.getNumComponents() - 1) == c;
  4193. return false;
  4194. #endif
  4195. }
  4196. void timerCallback() override
  4197. {
  4198. if (phase == 0) // waiting for the engine to host the plugin
  4199. {
  4200. instance = find();
  4201. if (instance == nullptr)
  4202. {
  4203. if (elapsed() > 20000)
  4204. finish ("not hosted");
  4205. return;
  4206. }
  4207. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  4208. openWindow();
  4209. next (1);
  4210. return;
  4211. }
  4212. if (phase == 1 && elapsed() >= 800) // Pin on top: off for a new plugin
  4213. {
  4214. expect ("pin_off_by_default", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  4215. shot ("pin-off");
  4216. const auto history = engine->getHistoryPosition();
  4217. lynx::PluginWindows::setPinnedOnTop (*instance, true);
  4218. expect ("pin_set", lynx::PluginWindows::isPinnedOnTop (*instance) && refNow().pinned);
  4219. expect ("pin_no_undo_step_project_modified", engine->getHistoryPosition() == history && engine->isModified());
  4220. // another secondary window brought in front of it
  4221. other = std::make_unique<juce::DocumentWindow> ("Another LYNX window", juce::Colours::darkslategrey, juce::DocumentWindow::closeButton);
  4222. other->setUsingNativeTitleBar (true);
  4223. other->setBounds (mainWindow->getX() + 60, mainWindow->getY() + 60, 420, 300);
  4224. other->setVisible (true);
  4225. lynx::keepAboveMainWindow (*other);
  4226. lynx::forceForegroundForTest (*other);
  4227. other->toFront (true);
  4228. next (2);
  4229. return;
  4230. }
  4231. if (phase == 2 && elapsed() >= 1200)
  4232. {
  4233. expect ("pinned_stays_in_front_of_a_clicked_window", pluginInFront());
  4234. shot ("pin-on");
  4235. // closed and opened again: the pin comes back from the project
  4236. lynx::PluginWindows::close (*instance);
  4237. openWindow();
  4238. next (3);
  4239. return;
  4240. }
  4241. if (phase == 3 && elapsed() >= 600)
  4242. {
  4243. expect ("pin_remembered_when_reopened", lynx::PluginWindows::isPinnedOnTop (*instance));
  4244. lynx::PluginWindows::setPinnedOnTop (*instance, false);
  4245. expect ("pin_cleared", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  4246. other->toFront (true);
  4247. next (4);
  4248. return;
  4249. }
  4250. if (phase == 4 && elapsed() >= 1000)
  4251. {
  4252. #if JUCE_WINDOWS
  4253. expect ("unpinned_goes_behind_a_clicked_window", ! pluginInFront());
  4254. #endif
  4255. other = nullptr;
  4256. // the wrapper settings page: LYNX's Velocity row in the MIDI group (instruments), default = follow
  4257. expect ("velocity_follows_midi_settings_by_default", refNow().velocityMode == lynx::prefs::pluginVelocityFollow
  4258. && refNow().fixedVelocity == lynx::prefs::defaultFixedVelocity);
  4259. shot ("wrapper-velocity-default", true);
  4260. engine->editSong ([this] (lynx::Song& song) {
  4261. if (auto* r = ref (song))
  4262. {
  4263. r->velocityMode = lynx::prefs::pluginVelocityFixed;
  4264. r->fixedVelocity = 96;
  4265. }
  4266. });
  4267. next (5);
  4268. return;
  4269. }
  4270. if (phase == 5 && elapsed() >= 400)
  4271. {
  4272. expect ("velocity_change_keeps_the_running_plugin", find() == instance);
  4273. shot ("wrapper-velocity-fixed", true);
  4274. engine->undo();
  4275. expect ("velocity_undo", refNow().velocityMode == lynx::prefs::pluginVelocityFollow && find() == instance);
  4276. // the preset menu's "Play a note when a preset loads": off by default, a user setting
  4277. expect ("audition_off_by_default", ! lynx::pluginpresetui::auditionOnLoad());
  4278. lynx::pluginpresetui::setAuditionOnLoad (true);
  4279. expect ("audition_menu_opened", lynx::PluginWindows::showPresetMenu (*instance));
  4280. next (6);
  4281. return;
  4282. }
  4283. if (phase == 6 && elapsed() >= 500) // the menu, as drawn
  4284. {
  4285. auto found = false;
  4286. auto& desktop = juce::Desktop::getInstance();
  4287. for (int c = desktop.getNumComponents(); --c >= 0 && ! found;)
  4288. if (auto* menu = desktop.getComponent (c); dynamic_cast<juce::TopLevelWindow*> (menu) == nullptr && menu->isVisible()
  4289. && menu->getHeight() > 60 && shots != juce::File())
  4290. {
  4291. const auto image = menu->createComponentSnapshot (menu->getLocalBounds(), true, 1.0f);
  4292. juce::FileOutputStream out (shots.getChildFile ("preset-menu-audition.png"));
  4293. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  4294. }
  4295. step ("shot_preset-menu-audition=" + juce::String ((int) found));
  4296. juce::PopupMenu::dismissAllActiveMenus();
  4297. // a preset loaded while the song is stopped: the note waits a moment, sounds, ends
  4298. const auto asked = engine->auditionPreset (*instance);
  4299. expect ("audition_only_for_channel_instruments", asked == instrument);
  4300. expect ("audition_waits_first", ! instrument || engine->auditionState() == 1);
  4301. next (7);
  4302. return;
  4303. }
  4304. if (phase == 7 && elapsed() >= 300)
  4305. {
  4306. expect ("audition_sounds", ! instrument || engine->auditionState() == 2);
  4307. next (8);
  4308. return;
  4309. }
  4310. if (phase == 8 && elapsed() >= 700)
  4311. {
  4312. expect ("audition_ends", engine->auditionState() == 0);
  4313. engine->getTransport().playing.store (true); // the song plays: no audition
  4314. expect ("no_audition_while_playing", ! engine->auditionPreset (*instance) && engine->auditionState() == 0);
  4315. engine->getTransport().playing.store (false);
  4316. lynx::pluginpresetui::setAuditionOnLoad (false);
  4317. expect ("audition_setting_off_again", ! lynx::pluginpresetui::auditionOnLoad());
  4318. finish ({});
  4319. }
  4320. }
  4321. void finish (const juce::String& failure)
  4322. {
  4323. stopTimer();
  4324. if (failure.isNotEmpty())
  4325. step ("failed=" + failure);
  4326. ok = ok && failure.isEmpty();
  4327. step (ok ? "result=OK" : "result=FAILED");
  4328. lynx::PluginWindows::closeAll();
  4329. done (ok);
  4330. }
  4331. };
  4332. auto* test = new Test();
  4333. test->reportPath = reportPath;
  4334. if (shotsPath.isNotEmpty())
  4335. {
  4336. test->shots = juce::File (shotsPath);
  4337. test->shots.createDirectory();
  4338. }
  4339. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4340. test->done = [this, test] (bool ok) {
  4341. setApplicationReturnValue (ok ? 0 : 1);
  4342. juce::MessageManager::callAsync ([this, test] {
  4343. lynx::setMainWindowForOwnership (nullptr);
  4344. test->other = nullptr;
  4345. test->mainWindow = nullptr;
  4346. test->engine = nullptr;
  4347. delete test;
  4348. quit();
  4349. });
  4350. };
  4351. test->engine = std::make_unique<lynx::AudioEngine> (false);
  4352. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  4353. test->mainWindow->setBounds (20, 20, 300, 200);
  4354. test->mainWindow->setVisible (true);
  4355. lynx::setMainWindowForOwnership (test->mainWindow.get());
  4356. auto& host = test->engine->getPluginHost();
  4357. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  4358. std::optional<juce::PluginDescription> chosen;
  4359. for (const auto& type : host.getKnownPlugins().getTypes())
  4360. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  4361. {
  4362. chosen = type;
  4363. break;
  4364. }
  4365. if (! chosen)
  4366. {
  4367. test->step ("result=FAILED (no plugin)");
  4368. test->done (false);
  4369. return;
  4370. }
  4371. test->instrument = chosen->isInstrument;
  4372. lynx::PluginRef ref;
  4373. ref.id = chosen->createIdentifierString().toStdString();
  4374. ref.name = chosen->name.toStdString();
  4375. test->engine->editSong ([&] (lynx::Song& song) {
  4376. if (test->instrument)
  4377. {
  4378. lynx::ChannelDef c;
  4379. c.name = ref.name;
  4380. c.instrument = lynx::InstrumentKind::plugin;
  4381. c.plugin = ref;
  4382. test->channelIndex = (int) song.channels.size();
  4383. song.channels.push_back (c);
  4384. }
  4385. else
  4386. {
  4387. while (song.mixer.size() < 2)
  4388. song.mixer.emplace_back();
  4389. lynx::EffectSlot slot;
  4390. slot.kind = lynx::EffectKind::plugin;
  4391. slot.plugin = ref;
  4392. song.mixer[1].effects.push_back (slot);
  4393. }
  4394. });
  4395. test->engine->markSaved();
  4396. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  4397. test->next (0);
  4398. test->startTimerHz (20);
  4399. }
  4400. void runReloadTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath, bool waitKill)
  4401. {
  4402. struct Test final : juce::Timer
  4403. {
  4404. juce::String reportPath, report;
  4405. juce::File shots;
  4406. std::unique_ptr<lynx::AudioEngine> engine;
  4407. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  4408. bool instrument = false, waitKill = false, ok = true;
  4409. int channelIndex = -1, phase = 0, round = 0;
  4410. juce::uint32 phaseStart = 0;
  4411. int firstPid = 0, pid = 0, historyBefore = 0;
  4412. bool modifiedBefore = false;
  4413. float captured = -1.0f;
  4414. juce::AudioPluginInstance* instance = nullptr;
  4415. std::vector<lynx::ChannelDef> channelsBefore;
  4416. std::function<void (bool)> done;
  4417. lynx::AudioEngine::HostedSlot where() const { return instrument ? lynx::AudioEngine::HostedSlot { channelIndex, -1, -1 } : lynx::AudioEngine::HostedSlot { -1, 1, 0 }; }
  4418. void step (const juce::String& line)
  4419. {
  4420. report << line << "\n";
  4421. juce::File (reportPath).replaceWithText (report);
  4422. }
  4423. void expect (const juce::String& name, bool value)
  4424. {
  4425. step (name + "=" + juce::String ((int) value));
  4426. ok = ok && value;
  4427. }
  4428. void next (int to)
  4429. {
  4430. phase = to;
  4431. phaseStart = juce::Time::getMillisecondCounter();
  4432. }
  4433. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  4434. juce::AudioPluginInstance* find()
  4435. {
  4436. if (instrument)
  4437. {
  4438. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  4439. return &p->getInstance();
  4440. }
  4441. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  4442. return &p->getInstance();
  4443. return nullptr;
  4444. }
  4445. // a few blocks through the plugin (the offline engine has no audio thread): they carry parameter changes to
  4446. // the plugin's process and its values back
  4447. void pump (int blocks)
  4448. {
  4449. std::vector<float> l (512), r (512);
  4450. lynx::EffectParams none {};
  4451. for (int b = 0; b < blocks; ++b)
  4452. {
  4453. std::fill (l.begin(), l.end(), 0.0f);
  4454. std::fill (r.begin(), r.end(), 0.0f);
  4455. if (instrument)
  4456. {
  4457. if (auto in = engine->getChannelInstrument (channelIndex))
  4458. in->render (l.data(), r.data(), 512, 1.0f, 1.0f);
  4459. }
  4460. else if (auto fx = engine->getEffect (1, 0))
  4461. fx->process (l.data(), r.data(), 512, none, 120.0);
  4462. }
  4463. }
  4464. juce::AudioProcessorParameter* firstParam()
  4465. {
  4466. if (instance != nullptr)
  4467. for (auto* candidate : instance->getParameters())
  4468. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  4469. return candidate;
  4470. return nullptr;
  4471. }
  4472. void openWindow()
  4473. {
  4474. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  4475. : std::shared_ptr<void> (engine->getEffect (1, 0));
  4476. lynx::PluginWindows::WrapperContext context { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  4477. if (instrument)
  4478. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  4479. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  4480. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  4481. }, instrument, instrument ? -1 : 1, instrument ? -1 : 0, {}, {} };
  4482. context.reload = [] {}; // (the test reloads by itself; with it the window shows the notice)
  4483. lynx::PluginWindows::open (owner, *instance, instance->getName(), std::move (context));
  4484. }
  4485. void shot (const char* name, bool settingsPage = false)
  4486. {
  4487. if (shots != juce::File() && instance != nullptr)
  4488. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  4489. }
  4490. void timerCallback() override
  4491. {
  4492. if (phase == 0) // waiting for the engine to host the plugin
  4493. {
  4494. instance = find();
  4495. if (instance == nullptr)
  4496. {
  4497. if (elapsed() > 20000)
  4498. finish ("not hosted");
  4499. return;
  4500. }
  4501. pid = firstPid = lynx::sandboxedPluginProcessId (*instance);
  4502. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName + " pid=" + juce::String (pid));
  4503. expect ("separate_process", lynx::isSandboxedPlugin (*instance) && pid != 0);
  4504. expect ("running", ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  4505. // a setting that is captured (what a save or a backup does), then one that is not
  4506. if (auto* param = firstParam())
  4507. {
  4508. param->setValue (param->getValue() > 0.5f ? 0.13f : 0.87f);
  4509. pump (4);
  4510. engine->capturePluginStates();
  4511. captured = param->getValue();
  4512. param->setValue (captured > 0.5f ? 0.31f : 0.69f);
  4513. pump (4);
  4514. step ("param=" + param->getName (64) + " captured=" + juce::String (captured, 4) + " then=" + juce::String (param->getValue(), 4));
  4515. }
  4516. else
  4517. {
  4518. engine->capturePluginStates();
  4519. step ("param=none");
  4520. }
  4521. channelsBefore = engine->getSong().channels;
  4522. historyBefore = engine->getHistoryPosition();
  4523. modifiedBefore = engine->isModified();
  4524. if (shots != juce::File())
  4525. openWindow();
  4526. next (1);
  4527. return;
  4528. }
  4529. if (phase == 1 && elapsed() >= 600) // the plugin's process goes
  4530. {
  4531. shot (round == 0 ? "window-running" : "window-reloaded");
  4532. if (waitKill && round == 0)
  4533. {
  4534. juce::File (reportPath + ".pid").replaceWithText (juce::String (pid));
  4535. step ("waiting_for_kill pid=" + juce::String (pid));
  4536. }
  4537. else
  4538. lynx::crashSandboxedPluginForTest (*instance);
  4539. next (2);
  4540. return;
  4541. }
  4542. if (phase == 2) // LYNX notices
  4543. {
  4544. if (! engine->hostedPluginDown (where()))
  4545. {
  4546. pump (1); // (as the audio thread would: a block that gets no answer marks it too)
  4547. if (elapsed() > (waitKill && round == 0 ? 120000 : 10000))
  4548. finish ("the plugin never went down");
  4549. return;
  4550. }
  4551. step ("down_after_ms=" + juce::String (elapsed()));
  4552. const auto down = engine->downHostedPlugins();
  4553. expect ("listed_down", down.size() == 1 && down.front() == where());
  4554. expect ("listed_by_name", engine->downHostedPlugins (nameInSong()).size() == 1 && engine->downHostedPlugins ("no such plugin").empty());
  4555. next (3);
  4556. return;
  4557. }
  4558. if (phase == 3 && elapsed() >= 1500) // nothing reloads by itself
  4559. {
  4560. expect ("still_down_without_asking", engine->hostedPluginDown (where()) && find() == instance
  4561. && lynx::sandboxedPluginProcessId (*instance) == pid);
  4562. shot (round == 0 ? "reload-notice" : "reload-notice-again");
  4563. if (shots != juce::File() && round == 0)
  4564. {
  4565. lynx::PluginWindows::close (*instance);
  4566. lynx::PluginWindows::promptReload (*engine, where(), {});
  4567. next (4);
  4568. return;
  4569. }
  4570. next (5);
  4571. return;
  4572. }
  4573. if (phase == 4 && elapsed() >= 500) // the prompt a click on the channel / slot shows
  4574. {
  4575. auto found = false;
  4576. for (int c = juce::Desktop::getInstance().getNumComponents(); --c >= 0;)
  4577. if (auto* alert = dynamic_cast<juce::AlertWindow*> (juce::Desktop::getInstance().getComponent (c)))
  4578. {
  4579. const auto image = alert->createComponentSnapshot (alert->getLocalBounds(), true, 1.0f);
  4580. juce::FileOutputStream out (shots.getChildFile ("reload-prompt.png"));
  4581. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  4582. alert->exitModalState (0); // Close: nothing reloads
  4583. break;
  4584. }
  4585. step ("shot_reload-prompt=" + juce::String ((int) found));
  4586. next (45);
  4587. return;
  4588. }
  4589. if (phase == 45 && elapsed() >= 300)
  4590. {
  4591. expect ("still_down_after_close", engine->hostedPluginDown (where()));
  4592. next (5);
  4593. return;
  4594. }
  4595. if (phase == 5) // Reload, as the notice's button / the prompt / the menu item do
  4596. {
  4597. auto* old = instance;
  4598. const auto running = lynx::PluginWindows::reload (*engine, { where() });
  4599. instance = find();
  4600. const auto newPid = instance != nullptr ? lynx::sandboxedPluginProcessId (*instance) : 0;
  4601. expect ("reloaded", running == 1 && instance != nullptr && ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  4602. expect ("new_process", newPid != 0 && newPid != pid);
  4603. step ("pid=" + juce::String (newPid) + " same_object=" + juce::String ((int) (instance == old)));
  4604. expect ("old_window_closed", ! lynx::PluginWindows::isOpen (*old) || instance == old);
  4605. pid = newPid;
  4606. if (instance != nullptr)
  4607. {
  4608. pump (4);
  4609. if (auto* param = firstParam(); param != nullptr && captured >= 0.0f)
  4610. {
  4611. step ("param_after_reload=" + juce::String (param->getValue(), 4));
  4612. expect ("state_captured_last", std::abs (param->getValue() - captured) < 0.02f);
  4613. }
  4614. }
  4615. expect ("song_untouched", engine->getSong().channels == channelsBefore);
  4616. expect ("no_undo_step", engine->getHistoryPosition() == historyBefore && engine->isModified() == modifiedBefore);
  4617. if (instance == nullptr)
  4618. {
  4619. finish ("no instance after the reload");
  4620. return;
  4621. }
  4622. if (shots != juce::File())
  4623. openWindow();
  4624. if (round == 0) // once more: a plugin that crashes again waits for the user again
  4625. {
  4626. round = 1;
  4627. next (1);
  4628. return;
  4629. }
  4630. next (6);
  4631. return;
  4632. }
  4633. if (phase == 6 && elapsed() >= 400) // an edit and its undo keep the reloaded plugin
  4634. {
  4635. shot ("window-reloaded-twice");
  4636. auto* before = find();
  4637. engine->editSong ([] (lynx::Song& song) { song.bpm += 1.0f; });
  4638. engine->undo();
  4639. expect ("undo_keeps_the_reloaded_plugin", find() == before && ! engine->hostedPluginDown (where()));
  4640. lynx::PluginWindows::closeAll();
  4641. finish ({});
  4642. }
  4643. }
  4644. std::string nameInSong() const
  4645. {
  4646. const auto& song = engine->getSong();
  4647. return instrument ? song.channels[(size_t) channelIndex].plugin.name : song.mixer[1].effects[0].plugin.name;
  4648. }
  4649. void finish (const juce::String& failure)
  4650. {
  4651. stopTimer();
  4652. if (failure.isNotEmpty())
  4653. step ("failed=" + failure);
  4654. ok = ok && failure.isEmpty();
  4655. step (ok ? "result=OK" : "result=FAILED");
  4656. lynx::PluginWindows::closeAll();
  4657. done (ok);
  4658. }
  4659. };
  4660. lynx::setPluginSandboxAlerts (true); // (the deaths are recorded as in the app; no box: there is no main component)
  4661. auto* test = new Test();
  4662. test->reportPath = reportPath;
  4663. test->waitKill = waitKill;
  4664. if (shotsPath.isNotEmpty())
  4665. {
  4666. test->shots = juce::File (shotsPath);
  4667. test->shots.createDirectory();
  4668. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4669. }
  4670. juce::File (reportPath + ".pid").deleteFile();
  4671. test->done = [this, test] (bool ok) {
  4672. setApplicationReturnValue (ok ? 0 : 1);
  4673. juce::MessageManager::callAsync ([this, test] {
  4674. lynx::setMainWindowForOwnership (nullptr);
  4675. test->mainWindow = nullptr;
  4676. test->engine = nullptr;
  4677. delete test;
  4678. quit();
  4679. });
  4680. };
  4681. test->engine = std::make_unique<lynx::AudioEngine> (false);
  4682. if (shotsPath.isNotEmpty())
  4683. {
  4684. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  4685. test->mainWindow->setBounds (20, 20, 300, 200);
  4686. test->mainWindow->setVisible (true);
  4687. lynx::setMainWindowForOwnership (test->mainWindow.get());
  4688. }
  4689. auto& host = test->engine->getPluginHost();
  4690. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  4691. std::optional<juce::PluginDescription> chosen;
  4692. for (const auto& type : host.getKnownPlugins().getTypes())
  4693. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  4694. {
  4695. chosen = type;
  4696. break;
  4697. }
  4698. if (! chosen)
  4699. {
  4700. test->step ("result=FAILED (no plugin)");
  4701. test->done (false);
  4702. return;
  4703. }
  4704. test->instrument = chosen->isInstrument;
  4705. lynx::PluginRef ref;
  4706. ref.separateProcess = true;
  4707. ref.id = chosen->createIdentifierString().toStdString();
  4708. ref.name = chosen->name.toStdString();
  4709. test->engine->editSong ([&] (lynx::Song& song) {
  4710. if (test->instrument)
  4711. {
  4712. lynx::ChannelDef c;
  4713. c.name = ref.name;
  4714. c.instrument = lynx::InstrumentKind::plugin;
  4715. c.plugin = ref;
  4716. test->channelIndex = (int) song.channels.size();
  4717. song.channels.push_back (c);
  4718. }
  4719. else
  4720. {
  4721. while (song.mixer.size() < 2)
  4722. song.mixer.emplace_back();
  4723. lynx::EffectSlot slot;
  4724. slot.kind = lynx::EffectKind::plugin;
  4725. slot.plugin = ref;
  4726. song.mixer[1].effects.push_back (slot);
  4727. }
  4728. });
  4729. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  4730. test->next (0);
  4731. test->startTimerHz (20);
  4732. }
  4733. void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
  4734. {
  4735. struct Test final : juce::Timer
  4736. {
  4737. juce::String reportPath, report;
  4738. std::unique_ptr<lynx::AudioEngine> engine;
  4739. bool instrument = false;
  4740. int phase = 0, ticks = 0, seconds = 15, dockStep = 0;
  4741. juce::uint32 phaseStartMs = 0; // (phase 1 counts real time: the timer's ticks ran faster than 20 Hz here)
  4742. juce::AudioPluginInstance* instance = nullptr;
  4743. juce::AudioProcessorParameter* checked = nullptr;
  4744. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  4745. lynx::Workspace* workspace = nullptr; // LYNX_PLUGWIN_DOCK=1: the real main window's desktop (issue #116)
  4746. int channelIndex = -1; // an instrument: its channel (added after the song's own channels)
  4747. int stepMs = 3000; // dock mode: each state held that long (screenshots)
  4748. bool keysDone = false;
  4749. bool dockOk = true;
  4750. std::function<void (bool)> done;
  4751. // issue #116 (with LYNX_DOCKED_PLUGINS=1 and LYNX_PLUGWIN_DOCK=1), FL's f116 sequence for every floating
  4752. // panel: the docked plugin window goes behind a clicked panel and comes back in front when clicked; a
  4753. // panel called by its key comes in front too; Detached reopens it as a window of its own, which stays above
  4754. // every panel clicked (it is owned by the main window).
  4755. const std::array<lynx::workspace::Panel, 4> dockPanels { lynx::workspace::Panel::channelRack, lynx::workspace::Panel::playlist,
  4756. lynx::workspace::Panel::pianoRoll, lynx::workspace::Panel::mixer };
  4757. const int dockSteps = 2 * 4 + 17; // (the last one reports dock_result)
  4758. int danceChannel = -1; // issue #116 slice 4: a dance channel's dancer over the docked plugin
  4759. lynx::MainComponent* ui = nullptr; // dock mode: the real main window's contents
  4760. struct ScaleSpy final : juce::ComponentPeer::ScaleFactorListener
  4761. {
  4762. int calls = 0;
  4763. double last = 0.0;
  4764. void nativeScaleFactorChanged (double s) override { ++calls; last = s; }
  4765. } scaleSpy;
  4766. juce::ComponentPeer* spiedPeer = nullptr;
  4767. void* panelHandle (lynx::workspace::Panel p) const { return workspace->getFrame (p).getWindowHandle(); }
  4768. void dockCheck (int at)
  4769. {
  4770. using lynx::workspace::Panel;
  4771. auto* main = mainWindow->getWindowHandle();
  4772. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  4773. auto expect = [this] (const juce::String& name, bool value) {
  4774. step (name + "=" + juce::String ((int) value));
  4775. dockOk = dockOk && value;
  4776. };
  4777. auto id = [] (Panel p) { return juce::String (lynx::workspace::panelId (p)); };
  4778. if (at == 0)
  4779. {
  4780. expect ("docked", lynx::PluginWindows::isDocked (*instance));
  4781. expect ("plugin_native_child", plug != nullptr && lynx::nativechild::parentOf (plug) == main);
  4782. for (auto p : dockPanels)
  4783. {
  4784. auto* h = panelHandle (p);
  4785. expect (id (p) + "_visible", workspace->isPanelVisible (p));
  4786. expect (id (p) + "_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  4787. expect ("plugin_above_" + id (p) + "_when_opened", lynx::nativechild::isAbove (plug, h));
  4788. }
  4789. expect ("browser_plain", ! workspace->isNativePanel (Panel::browser));
  4790. }
  4791. if (at < 2 * 4)
  4792. {
  4793. const auto p = dockPanels[at / 2];
  4794. if (at % 2 == 0)
  4795. {
  4796. workspace->activate (p); // a click on the panel
  4797. expect (id (p) + "_above_plugin_after_its_click", lynx::nativechild::isAbove (panelHandle (p), plug));
  4798. // the plugin stays above the panels nobody clicked
  4799. for (auto other : dockPanels)
  4800. if (other != p)
  4801. expect ("plugin_above_" + id (other) + "_after_" + id (p) + "_click", lynx::nativechild::isAbove (plug, panelHandle (other)));
  4802. }
  4803. else
  4804. {
  4805. lynx::PluginWindows::open ({}, *instance, {}); // (open again = a click on the plugin)
  4806. expect ("plugin_above_" + id (p) + "_after_plugin_click", lynx::nativechild::isAbove (plug, panelHandle (p)));
  4807. }
  4808. return;
  4809. }
  4810. if (at == 8)
  4811. {
  4812. // a layout change elsewhere (a panel resized, the Browser shown) keeps the plugin in front; a panel
  4813. // called by its key comes in front of it
  4814. workspace->hide (Panel::browser);
  4815. workspace->show (Panel::browser);
  4816. for (auto p : dockPanels)
  4817. expect ("plugin_above_" + id (p) + "_after_layout_change", lynx::nativechild::isAbove (plug, panelHandle (p)));
  4818. workspace->show (Panel::mixer);
  4819. expect ("mixer_above_plugin_after_show", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  4820. }
  4821. else if (at == 9)
  4822. {
  4823. // the setup wizard (Options › Setup wizard; first start) in front of the native panels and the plugin
  4824. ui->showSetupWizard();
  4825. }
  4826. else if (at == 10)
  4827. {
  4828. auto* overlay = ui->setupOverlayForTest();
  4829. auto* h = overlay != nullptr ? overlay->getWindowHandle() : nullptr;
  4830. expect ("setup_overlay_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  4831. expect ("setup_overlay_above_plugin", lynx::nativechild::isAbove (h, plug));
  4832. for (auto p : dockPanels)
  4833. expect ("setup_overlay_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  4834. workspace->activate (Panel::playlist); // (a panel brought in front by code: the overlay stays in front)
  4835. lynx::PluginWindows::open ({}, *instance, {});
  4836. expect ("setup_overlay_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::playlist)));
  4837. }
  4838. else if (at == 11)
  4839. {
  4840. ui->closeSetupWizardForSnapshot();
  4841. expect ("setup_overlay_closed", ui->setupOverlayForTest() == nullptr);
  4842. // drops: JUCE's list of windows in the native stacking order once a drag starts
  4843. workspace->activate (Panel::mixer);
  4844. workspace->hide (Panel::browser);
  4845. workspace->show (Panel::browser);
  4846. lynx::matchWindowOrderToScreen();
  4847. auto children = lynx::nativechild::attachedChildren (main);
  4848. auto& desktop = juce::Desktop::getInstance();
  4849. int last = -1;
  4850. bool ordered = children.size() >= 5;
  4851. for (auto* c : children)
  4852. if (c->isVisible())
  4853. {
  4854. int at2 = -1;
  4855. for (int k = 0; k < desktop.getNumComponents(); ++k)
  4856. if (desktop.getComponent (k) == c)
  4857. at2 = k;
  4858. ordered = ordered && at2 > last;
  4859. last = at2;
  4860. }
  4861. expect ("drop_order_matches_screen", ordered);
  4862. }
  4863. else if (at == 12)
  4864. {
  4865. // the main window's scale changes (a display with another scale): every native child placed again in
  4866. // physical pixels, the docked editor's window told (JUCE tells child windows nothing by itself)
  4867. for (int i = 0; i < juce::ComponentPeer::getNumPeers(); ++i)
  4868. if (auto* peer = juce::ComponentPeer::getPeer (i); peer != nullptr && peer->getNativeHandle() == plug)
  4869. spiedPeer = peer;
  4870. if (spiedPeer != nullptr)
  4871. spiedPeer->addScaleFactorListener (&scaleSpy);
  4872. lynx::nativechild::notifyScaleListenersForTest (*mainWindow);
  4873. juce::Desktop::getInstance().setGlobalScaleFactor (1.25f); // and LYNX's own UI zoom
  4874. }
  4875. else if (at == 13)
  4876. {
  4877. bool placed = true;
  4878. for (auto* c : lynx::nativechild::attachedChildren (main))
  4879. placed = placed && (! c->isVisible() || lynx::nativechild::placedPhysically (*c));
  4880. expect ("native_children_placed_at_125", placed);
  4881. expect ("docked_editor_told_the_scale", scaleSpy.calls > 0 && spiedPeer != nullptr
  4882. && std::abs (scaleSpy.last - spiedPeer->getPlatformScaleFactor()) < 0.001);
  4883. if (spiedPeer != nullptr && juce::ComponentPeer::isValidPeer (spiedPeer))
  4884. spiedPeer->removeScaleFactorListener (&scaleSpy);
  4885. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  4886. lynx::PluginWindows::setDetached (*instance, true);
  4887. }
  4888. else if (at == 14)
  4889. {
  4890. expect ("detached_reopened", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance));
  4891. expect ("detached_owned_by_main", plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  4892. expect ("detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  4893. for (auto p : dockPanels)
  4894. workspace->activate (p);
  4895. }
  4896. else if (at == 15)
  4897. {
  4898. // (an owned top-level window: above the main window and so above all its child windows)
  4899. expect ("detached_stays_above_clicked_panels", plug != nullptr && lynx::nativechild::ownerOf (plug) == main
  4900. && lynx::nativechild::parentOf (plug) != main && lynx::PluginWindows::isOpen (*instance));
  4901. lynx::PluginWindows::setDetached (*instance, false);
  4902. }
  4903. else if (at == 16)
  4904. {
  4905. // issue #116 slice 4: a Fruity Dance dancer standing on the docked plugin window, in front of it
  4906. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  4907. juce::Rectangle<int> over;
  4908. for (auto* c : lynx::nativechild::attachedChildren (main))
  4909. if (c->getWindowHandle() == plug)
  4910. over = ui->getLocalArea (nullptr, c->getScreenBounds());
  4911. expect ("dance_stage", stage != nullptr && ! over.isEmpty());
  4912. lynx::dance::Settings s;
  4913. s.move = lynx::dance::held; // (a still pose: the pixels tested below stay where they are)
  4914. s.x = over.getCentreX();
  4915. s.y = over.getCentreY() + 70;
  4916. const auto state = lynx::dance::toState (s);
  4917. engine->editSongStructural ([this, state] (lynx::Song& song) {
  4918. lynx::ChannelDef c;
  4919. c.name = "Fruity Dance";
  4920. c.instrument = lynx::InstrumentKind::fruitydance;
  4921. c.pluginState = state;
  4922. danceChannel = (int) song.channels.size();
  4923. song.channels.push_back (c);
  4924. });
  4925. engine->dispatchPendingMessages();
  4926. if (stage != nullptr)
  4927. stage->update();
  4928. }
  4929. else if (at == 17)
  4930. {
  4931. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  4932. auto* w = stage != nullptr ? stage->windowOf (danceChannel) : nullptr;
  4933. auto* h = w != nullptr ? w->getWindowHandle() : nullptr;
  4934. expect ("dancer_window_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  4935. expect ("dancer_window_layered", lynx::nativechild::isLayered (h));
  4936. expect ("dancer_above_plugin", lynx::nativechild::isAbove (h, plug));
  4937. for (auto p : dockPanels)
  4938. expect ("dancer_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  4939. // panels and the plugin brought in front (clicks, keys): the dancer stays in front of them
  4940. workspace->activate (Panel::mixer);
  4941. workspace->show (Panel::pianoRoll);
  4942. lynx::PluginWindows::open ({}, *instance, {});
  4943. expect ("dancer_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::mixer))
  4944. && lynx::nativechild::isAbove (h, panelHandle (Panel::pianoRoll)));
  4945. // the mouse: the dancer's body takes it, its window's transparent pixels let it through
  4946. if (w != nullptr)
  4947. {
  4948. const auto picture = w->createComponentSnapshot (w->getLocalBounds(), true, 1.0f);
  4949. const auto body = stage->bodyOf (danceChannel) - (w->getScreenPosition() - stage->getScreenPosition());
  4950. juce::Point<int> solid { -1, -1 }, clear { -1, -1 };
  4951. for (int y = body.getCentreY() - 10; y < body.getBottom() && solid.x < 0; ++y)
  4952. for (int x = body.getX(); x < body.getRight() && solid.x < 0; ++x)
  4953. if (picture.getBounds().contains (x, y) && picture.getPixelAt (x, y).getAlpha() == 255)
  4954. solid = { x, y };
  4955. for (int y = 0; y < picture.getHeight() && clear.x < 0; y += 2)
  4956. for (int x = 0; x < picture.getWidth() && clear.x < 0; x += 2)
  4957. if (picture.getPixelAt (x, y).getAlpha() == 0 && ! body.expanded (8).contains (x, y))
  4958. clear = { x, y };
  4959. step ("dancer_window=" + w->getBounds().toString() + " solid=" + solid.toString() + " clear=" + clear.toString());
  4960. auto* atSolid = lynx::nativechild::windowAt (*w, solid);
  4961. auto* atClear = lynx::nativechild::windowAt (*w, clear);
  4962. expect ("dancer_takes_its_body_clicks", solid.x >= 0 && atSolid == h);
  4963. expect ("dancer_lets_clicks_through", clear.x >= 0 && atClear != nullptr && atClear != h);
  4964. expect ("stage_leaves_the_mouse", ! stage->hitTest (stage->bodyOf (danceChannel).getCentreX(), stage->bodyOf (danceChannel).getCentreY()));
  4965. }
  4966. }
  4967. else if (at == 18)
  4968. {
  4969. // no dance channel: no dancer window (nothing drawn, no cost)
  4970. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  4971. engine->editSongStructural ([this] (lynx::Song& song) {
  4972. if (danceChannel >= 0 && danceChannel < (int) song.channels.size())
  4973. song.channels.erase (song.channels.begin() + danceChannel);
  4974. });
  4975. engine->dispatchPendingMessages();
  4976. if (stage != nullptr)
  4977. stage->update();
  4978. expect ("dancer_window_gone", stage != nullptr && stage->windowCount() == 0);
  4979. }
  4980. else if (at >= 19 && at <= 22)
  4981. {
  4982. // round 190i: a native panel the user opens or closes fades by its window's own alpha (round
  4983. // 179a's panel fade; LYNX's own, FL has none). Each fade lasts half a step here.
  4984. auto& frame = workspace->getFrame (Panel::mixer);
  4985. const auto fadeMs = juce::jmax (120, stepMs / 2);
  4986. workspace->setNativeFadeScale (fadeMs / (double) lynx::ui::motion::panelFadeMs);
  4987. auto halfWay = [this, &frame, fadeMs] (const juce::String& name, int direction) {
  4988. juce::Timer::callAfterDelay (fadeMs / 2, [this, &frame, name, direction] {
  4989. const auto alpha = frame.getAlpha();
  4990. step (name + "_alpha=" + juce::String (alpha, 2));
  4991. const auto ok = alpha > 0.1f && alpha < 0.9f && frame.isVisible()
  4992. && workspace->nativeFadeDirection (lynx::workspace::Panel::mixer) == direction
  4993. && lynx::nativechild::isLayered (frame.getWindowHandle());
  4994. step (name + "=" + juce::String ((int) ok));
  4995. dockOk = dockOk && ok;
  4996. });
  4997. };
  4998. if (at == 19)
  4999. {
  5000. workspace->show (Panel::mixer); // (in front of the docked plugin: it fades over it)
  5001. expect ("mixer_above_plugin_before_fade", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  5002. workspace->hide (Panel::mixer);
  5003. expect ("mixer_starts_fading_out", workspace->nativeFadeDirection (Panel::mixer) == -1 && frame.isVisible()
  5004. && ! workspace->isPanelVisible (Panel::mixer));
  5005. halfWay ("mixer_half_faded_out", -1);
  5006. }
  5007. else if (at == 20)
  5008. {
  5009. expect ("mixer_hidden_after_fade", ! frame.isVisible() && workspace->nativeFadeDirection (Panel::mixer) == 0
  5010. && frame.getAlpha() == 1.0f);
  5011. workspace->show (Panel::mixer);
  5012. expect ("mixer_starts_fading_in", workspace->nativeFadeDirection (Panel::mixer) == 1 && frame.isVisible()
  5013. && frame.getAlpha() == 0.0f);
  5014. halfWay ("mixer_half_faded_in", 1);
  5015. }
  5016. else if (at == 21)
  5017. {
  5018. expect ("mixer_opaque_after_fade", frame.isVisible() && workspace->nativeFadeDirection (Panel::mixer) == 0
  5019. && frame.getAlpha() == 1.0f && ! lynx::nativechild::isLayered (frame.getWindowHandle())
  5020. && lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  5021. // closed and called back in the middle of the fade: it turns round from where it is
  5022. workspace->hide (Panel::mixer);
  5023. juce::Timer::callAfterDelay (fadeMs / 2, [this, &frame] {
  5024. const auto before = frame.getAlpha();
  5025. workspace->show (lynx::workspace::Panel::mixer);
  5026. const auto ok = before > 0.1f && before < 0.9f && frame.getAlpha() == before && frame.isVisible()
  5027. && workspace->nativeFadeDirection (lynx::workspace::Panel::mixer) == 1;
  5028. step ("mixer_turns_round_mid_fade=" + juce::String ((int) ok));
  5029. dockOk = dockOk && ok;
  5030. });
  5031. }
  5032. else
  5033. {
  5034. expect ("mixer_shown_after_turning_round", frame.isVisible() && frame.getAlpha() == 1.0f
  5035. && workspace->nativeFadeDirection (Panel::mixer) == 0
  5036. && ! lynx::nativechild::isLayered (frame.getWindowHandle()));
  5037. // Settings > General > Animations off: no fade, no timer
  5038. lynx::ui::motion::enabled() = false;
  5039. workspace->hide (Panel::mixer);
  5040. expect ("no_fade_out_without_animations", ! frame.isVisible() && workspace->nativeFadeDirection (Panel::mixer) == 0);
  5041. workspace->show (Panel::mixer);
  5042. expect ("no_fade_in_without_animations", frame.isVisible() && frame.getAlpha() == 1.0f
  5043. && workspace->nativeFadeDirection (Panel::mixer) == 0);
  5044. lynx::ui::motion::enabled() = true;
  5045. workspace->setNativeFadeScale (1.0);
  5046. // FL's Tools > Macros > Switch all plugin editors to > Detached (round 190i)
  5047. lynx::PluginWindows::setAllDetached (*engine, true);
  5048. }
  5049. }
  5050. else if (at == 23)
  5051. {
  5052. expect ("macro_detached_the_open_editor", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance)
  5053. && plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  5054. expect ("macro_detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  5055. lynx::PluginWindows::setAllDetached (*engine, false); // ... > Attached
  5056. }
  5057. else
  5058. {
  5059. expect ("docked_again", lynx::PluginWindows::isDocked (*instance) && engineRef() != nullptr && ! engineRef()->detached);
  5060. step (juce::String ("dock_result=") + (dockOk ? "OK" : "FAILED"));
  5061. }
  5062. }
  5063. const lynx::PluginRef* engineRef() const
  5064. {
  5065. const auto& song = engine->getSong();
  5066. if (instrument)
  5067. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  5068. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  5069. }
  5070. void step (const juce::String& line)
  5071. {
  5072. report << line << "\n";
  5073. juce::File (reportPath).replaceWithText (report);
  5074. }
  5075. juce::AudioPluginInstance* find()
  5076. {
  5077. if (instrument)
  5078. {
  5079. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  5080. return &p->getInstance();
  5081. }
  5082. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  5083. return &p->getInstance();
  5084. return nullptr;
  5085. }
  5086. void timerCallback() override
  5087. {
  5088. ++ticks;
  5089. if (phase == 0) // waiting for the engine to host the plugin
  5090. {
  5091. instance = find();
  5092. if (instance == nullptr)
  5093. {
  5094. if (ticks > 200)
  5095. {
  5096. step ("result=FAILED (not hosted)");
  5097. stopTimer();
  5098. done (false);
  5099. }
  5100. return;
  5101. }
  5102. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  5103. step ("programs=" + juce::String (instance->getNumPrograms()));
  5104. for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
  5105. step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
  5106. step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
  5107. // preset round trip: save, change the first parameter, load, compare
  5108. juce::AudioProcessorParameter* param = nullptr;
  5109. for (auto* candidate : instance->getParameters())
  5110. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  5111. {
  5112. param = candidate;
  5113. break;
  5114. }
  5115. if (param != nullptr)
  5116. {
  5117. step ("param=" + param->getName (64));
  5118. checked = param;
  5119. const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
  5120. juce::String error;
  5121. const auto before = param->getValue();
  5122. const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
  5123. param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
  5124. const auto changed = param->getValue();
  5125. const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
  5126. step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
  5127. + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
  5128. + (error.isNotEmpty() ? " error=" + error : juce::String()));
  5129. for (const auto* ext : { "fxp", "fxb", "vstpreset" })
  5130. {
  5131. juce::String e2;
  5132. const auto f2 = file.withFileExtension (ext);
  5133. const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
  5134. step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
  5135. f2.deleteFile();
  5136. }
  5137. step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
  5138. }
  5139. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  5140. : std::shared_ptr<void> (engine->getEffect (1, 0));
  5141. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  5142. { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  5143. if (instrument)
  5144. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  5145. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  5146. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  5147. }, instrument });
  5148. owner.reset();
  5149. step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  5150. phase = 1;
  5151. ticks = 0;
  5152. phaseStartMs = juce::Time::getMillisecondCounter();
  5153. return;
  5154. }
  5155. if (phase == 1 && ticks >= 30 && ! keysDone && juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_KEYS", {}).isNotEmpty() && instance->getActiveEditor() != nullptr)
  5156. keysDone = ! lynx::pluginKeysTestTick (*instance->getActiveEditor(),
  5157. [this] (bool on) {
  5158. engine->editSong ([this, on] (lynx::Song& song) {
  5159. (instrument ? song.channels[(size_t) channelIndex].plugin : song.mixer[1].effects[0].plugin).hostKeysFirst = on;
  5160. });
  5161. },
  5162. [this] (const juce::String& line) { step (line); });
  5163. const auto elapsedMs = (int) (juce::Time::getMillisecondCounter() - phaseStartMs);
  5164. if (phase == 1 && ticks == 20 && checked != nullptr)
  5165. step ("param_after_1s=" + juce::String (checked->getValue(), 4));
  5166. // (3 s apart: time for screenshots of each state)
  5167. if (phase == 1 && workspace != nullptr && dockStep < dockSteps && elapsedMs >= (dockStep + 1) * stepMs)
  5168. dockCheck (dockStep++);
  5169. if (phase == 1 && elapsedMs >= seconds * 1000 && (workspace == nullptr || dockStep >= dockSteps)) // remove the plugin from the song
  5170. {
  5171. engine->editSong ([this] (lynx::Song& song) {
  5172. if (instrument)
  5173. {
  5174. if (channelIndex >= 0 && channelIndex < (int) song.channels.size())
  5175. song.channels.erase (song.channels.begin() + channelIndex);
  5176. }
  5177. else
  5178. song.mixer[1].effects.clear();
  5179. });
  5180. step ("removed");
  5181. phase = 2;
  5182. ticks = 0;
  5183. return;
  5184. }
  5185. if (phase == 2 && ticks >= 40)
  5186. {
  5187. const auto open = lynx::PluginWindows::isOpen (*instance);
  5188. step ("window_open_after_remove=" + juce::String ((int) open));
  5189. step (open || ! dockOk ? "result=FAILED" : "result=OK");
  5190. stopTimer();
  5191. lynx::PluginWindows::closeAll();
  5192. done (! open && dockOk);
  5193. }
  5194. }
  5195. };
  5196. auto* test = new Test();
  5197. test->reportPath = reportPath;
  5198. test->seconds = seconds;
  5199. test->done = [this, test] (bool ok) {
  5200. setApplicationReturnValue (ok ? 0 : 1);
  5201. juce::MessageManager::callAsync ([this, test] {
  5202. lynx::setMainWindowForOwnership (nullptr);
  5203. lynx::PluginWindows::setDockWorkspace (nullptr);
  5204. test->workspace = nullptr;
  5205. test->mainWindow = nullptr; // (dock mode: the main component with it, before the engine)
  5206. test->engine = nullptr;
  5207. delete test;
  5208. quit();
  5209. });
  5210. };
  5211. test->engine = std::make_unique<lynx::AudioEngine> (false);
  5212. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  5213. test->mainWindow->setBounds (20, 20, 300, 200);
  5214. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DOCK", {}) == "1" && lynx::nativechild::dockingEnabled())
  5215. {
  5216. // the real main window's contents (it docks plugin windows in its own desktop), so the panels are real
  5217. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5218. auto* ui = new lynx::MainComponent (*test->engine, false);
  5219. test->mainWindow->setUsingNativeTitleBar (true);
  5220. test->mainWindow->setContentOwned (ui, false);
  5221. test->mainWindow->setBounds (20, 20, 1500, 900);
  5222. test->workspace = &ui->workspaceForTest();
  5223. test->ui = ui;
  5224. if (const auto ms = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_STEP_MS", {}).getIntValue(); ms > 0)
  5225. test->stepMs = ms;
  5226. }
  5227. test->mainWindow->setVisible (true);
  5228. lynx::setMainWindowForOwnership (test->mainWindow.get());
  5229. if (test->workspace != nullptr)
  5230. {
  5231. using lynx::workspace::Panel;
  5232. for (auto p : { Panel::playlist, Panel::mixer, Panel::pianoRoll, Panel::channelRack })
  5233. test->workspace->show (p);
  5234. test->step ("dock_test=2 rack_visible=" + juce::String ((int) test->workspace->isPanelVisible (Panel::channelRack)));
  5235. }
  5236. auto& host = test->engine->getPluginHost();
  5237. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  5238. std::optional<juce::PluginDescription> chosen;
  5239. for (const auto& type : host.getKnownPlugins().getTypes())
  5240. if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  5241. && (only.isEmpty() || type.name == only))
  5242. {
  5243. chosen = type;
  5244. break;
  5245. }
  5246. if (! chosen)
  5247. {
  5248. test->step ("result=FAILED (no plugin)");
  5249. test->done (false);
  5250. return;
  5251. }
  5252. test->instrument = chosen->isInstrument;
  5253. lynx::PluginRef ref;
  5254. ref.separateProcess = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_SEPARATE", {}) == "1"; // (issue #96's other-process check)
  5255. ref.id = chosen->createIdentifierString().toStdString();
  5256. ref.name = chosen->name.toStdString();
  5257. test->engine->editSong ([&] (lynx::Song& song) {
  5258. if (test->instrument)
  5259. {
  5260. lynx::ChannelDef c;
  5261. c.name = ref.name;
  5262. c.instrument = lynx::InstrumentKind::plugin;
  5263. c.plugin = ref;
  5264. test->channelIndex = (int) song.channels.size();
  5265. song.channels.push_back (c);
  5266. }
  5267. else
  5268. {
  5269. while (song.mixer.size() < 2)
  5270. song.mixer.emplace_back();
  5271. lynx::EffectSlot slot;
  5272. slot.kind = lynx::EffectKind::plugin;
  5273. slot.plugin = ref;
  5274. song.mixer[1].effects.push_back (slot);
  5275. }
  5276. });
  5277. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  5278. test->startTimerHz (20);
  5279. }
  5280. void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
  5281. {
  5282. struct CrashTest final : juce::Timer
  5283. {
  5284. juce::String reportPath, report;
  5285. std::unique_ptr<lynx::PluginHost> host;
  5286. juce::AudioPluginInstance* plugin = nullptr;
  5287. std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
  5288. std::function<void (bool)> done;
  5289. int ticks = 0, crashesBefore = 0;
  5290. void step (const juce::String& line)
  5291. {
  5292. report << line << "\n";
  5293. juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
  5294. }
  5295. void timerCallback() override
  5296. {
  5297. ++ticks;
  5298. const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
  5299. const auto open = lynx::PluginWindows::isOpen (*plugin);
  5300. if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
  5301. {
  5302. stopTimer();
  5303. step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
  5304. bool traced = false;
  5305. if (crashes > 0)
  5306. {
  5307. const auto last = lynx::PluginWindows::editorCrashes().back();
  5308. traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
  5309. step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
  5310. + juce::String ((int) traced));
  5311. last.traceFile.deleteFile();
  5312. }
  5313. // still alive: one more message through the loop after the fault
  5314. juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
  5315. step ("message_loop_after_fault=1");
  5316. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  5317. done (ok);
  5318. });
  5319. }
  5320. }
  5321. };
  5322. auto* test = new CrashTest();
  5323. test->reportPath = reportPath;
  5324. test->done = [this, test] (bool ok)
  5325. {
  5326. setApplicationReturnValue (ok ? 0 : 1);
  5327. juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
  5328. };
  5329. #if ! JUCE_WINDOWS
  5330. test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
  5331. test->done (true);
  5332. return;
  5333. #else
  5334. _putenv_s ("LYNX_TEST_CRASH", "editor");
  5335. test->host = std::make_unique<lynx::PluginHost> (false);
  5336. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  5337. std::shared_ptr<juce::AudioPluginInstance> instance;
  5338. for (const auto& type : test->host->getKnownPlugins().getTypes())
  5339. {
  5340. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
  5341. continue;
  5342. juce::String error;
  5343. instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
  5344. test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
  5345. break;
  5346. }
  5347. if (instance == nullptr || ! instance->hasEditor())
  5348. {
  5349. test->step ("result=FAILED (no plugin with an editor)");
  5350. test->done (false);
  5351. return;
  5352. }
  5353. lynx::preparePlugin (*instance, 48000.0, 512);
  5354. test->plugin = instance.get();
  5355. test->keep = instance;
  5356. test->crashesBefore = lynx::PluginWindows::editorCrashCount();
  5357. lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
  5358. test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  5359. test->startTimer (100);
  5360. #endif
  5361. }
  5362. void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
  5363. {
  5364. struct EditorTest final : juce::Timer
  5365. {
  5366. juce::String reportPath, report;
  5367. std::unique_ptr<lynx::PluginHost> host;
  5368. std::unique_ptr<juce::AudioPluginInstance> plugin;
  5369. std::unique_ptr<juce::DocumentWindow> window;
  5370. std::function<void (bool)> done;
  5371. void step (const juce::String& line)
  5372. {
  5373. report << line << "\n";
  5374. juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
  5375. }
  5376. void timerCallback() override
  5377. {
  5378. stopTimer();
  5379. window = nullptr;
  5380. step ("step=closed");
  5381. plugin = nullptr;
  5382. step ("result=OK");
  5383. done (true);
  5384. }
  5385. };
  5386. auto* test = new EditorTest();
  5387. test->reportPath = reportPath;
  5388. test->done = [this, test] (bool ok)
  5389. {
  5390. setApplicationReturnValue (ok ? 0 : 1);
  5391. juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
  5392. };
  5393. test->host = std::make_unique<lynx::PluginHost> (false);
  5394. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  5395. test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
  5396. for (const auto& type : test->host->getKnownPlugins().getTypes())
  5397. {
  5398. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  5399. || (only.isNotEmpty() && type.name != only))
  5400. continue;
  5401. juce::String error;
  5402. test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
  5403. test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
  5404. break;
  5405. }
  5406. if (test->plugin == nullptr)
  5407. {
  5408. test->step ("result=FAILED");
  5409. test->done (false);
  5410. return;
  5411. }
  5412. lynx::preparePlugin (*test->plugin, 48000.0, 512);
  5413. test->step ("step=create_editor");
  5414. test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
  5415. test->window->setUsingNativeTitleBar (true);
  5416. if (auto* editor = test->plugin->createEditorIfNeeded())
  5417. test->window->setContentOwned (editor, true);
  5418. else
  5419. test->step ("no_editor");
  5420. test->step ("step=show");
  5421. test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
  5422. test->window->setVisible (true);
  5423. test->step ("step=shown");
  5424. test->startTimer (4000);
  5425. }
  5426. void runFitTest (const juce::String& reportPath, int percent)
  5427. {
  5428. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5429. struct FitTest final : juce::Timer
  5430. {
  5431. juce::String path, report;
  5432. bool ok = true;
  5433. int step = 0, percent = 150;
  5434. std::unique_ptr<juce::DocumentWindow> tall, big;
  5435. std::function<void()> done;
  5436. // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
  5437. void check (const juce::String& what, juce::Component& w, bool whole)
  5438. {
  5439. juce::BorderSize<int> frame;
  5440. if (auto* peer = w.getPeer())
  5441. if (const auto f = peer->getFrameSizeIfPresent())
  5442. frame = *f;
  5443. auto outer = frame.addedTo (w.getBounds());
  5444. const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
  5445. const auto area = display != nullptr ? display->userArea : outer;
  5446. #if JUCE_LINUX
  5447. // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
  5448. // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
  5449. const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
  5450. outer = outer.reduced (shadow);
  5451. const auto slack = shadow > 0 ? 4 : 0;
  5452. #else
  5453. const auto slack = 0;
  5454. #endif
  5455. const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
  5456. && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
  5457. report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
  5458. << frame.getLeft() << ") screen=" << area.toString() << "\n";
  5459. ok = ok && passed;
  5460. }
  5461. void start()
  5462. {
  5463. report << "scale=" << percent << "%\n";
  5464. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  5465. // a tool window taller than the screen, centred (its title bar would be above the screen)
  5466. tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
  5467. tall->setUsingNativeTitleBar (true);
  5468. auto* content = new juce::Component();
  5469. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  5470. content->setSize (500, area.getHeight() + 200);
  5471. tall->setContentOwned (content, true);
  5472. tall->setCentrePosition (area.getCentre());
  5473. tall->setVisible (true);
  5474. lynx::keepAboveMainWindow (*tall);
  5475. // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
  5476. startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
  5477. }
  5478. void timerCallback() override
  5479. {
  5480. ++step;
  5481. if (step == 1)
  5482. {
  5483. check ("tall tool window: title bar and close button on the screen", *tall, false);
  5484. tall.reset();
  5485. // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
  5486. auto content = std::make_unique<juce::Component>();
  5487. const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  5488. content->setSize (520, screen.getHeight() + 300);
  5489. lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
  5490. return;
  5491. }
  5492. if (step == 2)
  5493. {
  5494. if (auto* w = lynx::findToolWindow ("fittest-fixed"))
  5495. {
  5496. check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
  5497. const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
  5498. && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
  5499. report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
  5500. ok = ok && scrolls;
  5501. }
  5502. else
  5503. {
  5504. report << "FAIL fixed-size tool window not found\n";
  5505. ok = false;
  5506. }
  5507. lynx::closeAllToolWindows();
  5508. // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
  5509. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  5510. big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
  5511. big->setUsingNativeTitleBar (true);
  5512. big->setResizable (true, false);
  5513. big->setResizeLimits (400, 300, 10000, 10000);
  5514. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  5515. big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
  5516. big->setVisible (true);
  5517. return;
  5518. }
  5519. if (step == 3)
  5520. {
  5521. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  5522. juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
  5523. return;
  5524. }
  5525. if (step == 4)
  5526. {
  5527. check ("resizable window after the zoom change: fits the screen", *big, true);
  5528. big.reset();
  5529. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  5530. juce::File (path).replaceWithText (report);
  5531. stopTimer();
  5532. if (done)
  5533. done();
  5534. }
  5535. }
  5536. };
  5537. static std::unique_ptr<FitTest> test;
  5538. test = std::make_unique<FitTest>();
  5539. test->path = reportPath;
  5540. test->percent = juce::jlimit (50, 300, percent);
  5541. test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
  5542. test->start();
  5543. }
  5544. void runWindowTest (const juce::String& reportPath)
  5545. {
  5546. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5547. struct WindowTest final : juce::Timer
  5548. {
  5549. juce::String reportPath, report;
  5550. bool ok = true;
  5551. int stepIndex = 0;
  5552. std::unique_ptr<lynx::AudioEngine> engine;
  5553. lynx::MainComponent* ui = nullptr;
  5554. std::unique_ptr<juce::DocumentWindow> main, pluginLike;
  5555. juce::TextEditor* pluginField = nullptr;
  5556. std::unique_ptr<juce::AlertWindow> nameDialog;
  5557. std::function<void()> done;
  5558. void line (const juce::String& text)
  5559. {
  5560. report << text << "\n";
  5561. juce::File (reportPath).replaceWithText (report);
  5562. }
  5563. void check (const juce::String& what, bool passed)
  5564. {
  5565. line ((passed ? "ok " : "FAIL ") + what);
  5566. ok = ok && passed;
  5567. }
  5568. bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
  5569. bool focusIn (juce::Component* w)
  5570. {
  5571. auto* f = juce::Component::getCurrentlyFocusedComponent();
  5572. return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
  5573. }
  5574. void timerCallback() override
  5575. {
  5576. switch (stepIndex++)
  5577. {
  5578. case 0:
  5579. line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
  5580. ui->openQuickAddForTest();
  5581. break;
  5582. case 1:
  5583. {
  5584. auto* w = lynx::findToolWindow ("quickadd");
  5585. check ("quick-add palette open", w != nullptr);
  5586. check ("quick-add palette active", w != nullptr && w->isActiveWindow());
  5587. check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  5588. check ("quick-add palette above the main window", isAbove (w));
  5589. auto* f = juce::Component::getCurrentlyFocusedComponent();
  5590. check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
  5591. lynx::closeAllToolWindows();
  5592. lynx::openAudioEditor (*engine);
  5593. break;
  5594. }
  5595. case 2:
  5596. {
  5597. auto* w = lynx::findToolWindow ("audioeditor");
  5598. check ("audio editor open", w != nullptr);
  5599. check ("audio editor active", w != nullptr && w->isActiveWindow());
  5600. check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  5601. check ("audio editor above the main window", isAbove (w));
  5602. lynx::forceForegroundForTest (*main); // the user clicks the main window
  5603. break;
  5604. }
  5605. case 3:
  5606. {
  5607. auto* w = lynx::findToolWindow ("audioeditor");
  5608. check ("audio editor stays above the main window after clicking it", isAbove (w));
  5609. lynx::closeAllToolWindows();
  5610. // a plugin editor's window: its own controls keep the keyboard focus
  5611. pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
  5612. pluginLike->setUsingNativeTitleBar (true);
  5613. auto* field = new juce::TextEditor();
  5614. field->setSize (300, 120);
  5615. pluginLike->setContentOwned (field, true);
  5616. pluginLike->centreWithSize (300, 120);
  5617. pluginLike->setVisible (true);
  5618. lynx::keepAboveMainWindow (*pluginLike);
  5619. pluginLike->toFront (true);
  5620. field->grabKeyboardFocus();
  5621. pluginField = field;
  5622. break;
  5623. }
  5624. case 4:
  5625. check ("plugin window active", pluginLike->isActiveWindow());
  5626. check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
  5627. check ("plugin window above the main window", isAbove (pluginLike.get()));
  5628. pluginLike = nullptr;
  5629. lynx::forceForegroundForTest (*main);
  5630. juce::Component::unfocusAllComponents();
  5631. break;
  5632. case 5:
  5633. check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
  5634. // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
  5635. nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
  5636. nameDialog->enterModalState (true, nullptr, false);
  5637. lynx::keepAboveMainWindow (*nameDialog);
  5638. break;
  5639. case 6:
  5640. {
  5641. auto* f = juce::Component::getCurrentlyFocusedComponent();
  5642. auto* field = dynamic_cast<juce::TextEditor*> (f);
  5643. check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
  5644. if (field != nullptr)
  5645. field->keyPressed (juce::KeyPress ('x', {}, 'x'));
  5646. check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
  5647. nameDialog->exitModalState (0);
  5648. nameDialog = nullptr;
  5649. line (ok ? "result=OK" : "result=FAILED");
  5650. stopTimer();
  5651. done();
  5652. break;
  5653. }
  5654. default:
  5655. break;
  5656. }
  5657. }
  5658. };
  5659. auto* test = new WindowTest();
  5660. test->reportPath = reportPath;
  5661. test->engine = std::make_unique<lynx::AudioEngine> (false);
  5662. test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
  5663. test->main->setUsingNativeTitleBar (true);
  5664. test->ui = new lynx::MainComponent (*test->engine, false);
  5665. test->main->setContentOwned (test->ui, true);
  5666. test->main->setResizable (true, true);
  5667. test->main->centreWithSize (1280, 760);
  5668. test->main->setVisible (true);
  5669. lynx::setMainWindowForOwnership (test->main.get());
  5670. lynx::forceForegroundForTest (*test->main);
  5671. test->main->toFront (true);
  5672. test->done = [this, test] {
  5673. setApplicationReturnValue (test->ok ? 0 : 1);
  5674. juce::MessageManager::callAsync ([this, test] {
  5675. lynx::closeAllToolWindows();
  5676. lynx::setMainWindowForOwnership (nullptr);
  5677. test->main = nullptr;
  5678. delete test;
  5679. quit();
  5680. });
  5681. };
  5682. test->startTimer (1500);
  5683. }
  5684. // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
  5685. // instrument (and runs audio through it if it is an effect) and measures the audio.
  5686. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
  5687. {
  5688. juce::String report;
  5689. bool ok = false;
  5690. {
  5691. lynx::AudioEngine offline (false);
  5692. auto& host = offline.getPluginHost();
  5693. const auto added = host.addPluginFile (juce::File (pluginPath));
  5694. report << "plugins_in_file=" << added << "\n";
  5695. juce::PluginDescription instrument, effect;
  5696. bool hasInstrument = false, hasEffect = false;
  5697. for (const auto& type : host.getKnownPlugins().getTypes())
  5698. {
  5699. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  5700. || (only.isNotEmpty() && type.name != only))
  5701. continue;
  5702. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  5703. << ") in " << type.fileOrIdentifier << "\n";
  5704. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  5705. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  5706. }
  5707. auto song = lynx::Song::makeDefault();
  5708. if (hasInstrument)
  5709. {
  5710. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  5711. c.instrument = lynx::InstrumentKind::plugin;
  5712. c.plugin.id = instrument.createIdentifierString().toStdString();
  5713. c.plugin.name = instrument.name.toStdString();
  5714. c.volume = 1.0f;
  5715. for (int i = 0; i < 4; ++i) // one chord per beat
  5716. for (int key : { 60, 64, 67 })
  5717. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  5718. song.patterns[0].sortNotes();
  5719. }
  5720. if (hasEffect)
  5721. {
  5722. lynx::EffectSlot slot;
  5723. slot.kind = lynx::EffectKind::plugin;
  5724. slot.plugin.id = effect.createIdentifierString().toStdString();
  5725. slot.plugin.name = effect.name.toStdString();
  5726. song.mixer[0].effects.push_back (slot);
  5727. }
  5728. const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
  5729. offline.setSong (song);
  5730. // after a render: the rack (and its plugins) is built when the engine is prepared
  5731. const auto peak = offline.renderOffline (3.0, 48000.0);
  5732. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  5733. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
  5734. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  5735. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  5736. if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
  5737. report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
  5738. report << "peak=" << peak << "\n";
  5739. // plugins that crashed inside a call, were caught and switched off (round 111)
  5740. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  5741. for (const auto& c : lynx::pluginCrashes())
  5742. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  5743. offline.capturePluginStates();
  5744. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  5745. report << "state_bytes_base64=" << (int) stateSize << "\n";
  5746. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  5747. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  5748. }
  5749. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  5750. juce::File (reportPath).replaceWithText (report);
  5751. setApplicationReturnValue (ok ? 0 : 1);
  5752. quit();
  5753. }
  5754. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108): a hosted CLAP
  5755. // instrument with the wrapper's MPE switch on gets each note on its own member channel, its fine pitch / Mod X /
  5756. // Mod Y as tuning / brightness / pressure note expressions before the note on, and a sounding note's expression
  5757. // on that note's channel alone. The plugin writes down what it received; no window, no audio device.
  5758. void runMpeTest (const juce::String& pluginPath, const juce::String& reportPath)
  5759. {
  5760. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  5761. log.deleteFile();
  5762. #if JUCE_WINDOWS
  5763. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  5764. #else
  5765. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  5766. #endif
  5767. juce::String report;
  5768. auto failures = 0;
  5769. {
  5770. lynx::AudioEngine engine (false);
  5771. auto& host = engine.getPluginHost();
  5772. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  5773. std::optional<juce::PluginDescription> clap;
  5774. for (const auto& type : host.getKnownPlugins().getTypes())
  5775. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  5776. clap = type;
  5777. lynx::PluginRef ref;
  5778. if (clap)
  5779. {
  5780. ref.id = clap->createIdentifierString().toStdString();
  5781. ref.name = clap->name.toStdString();
  5782. }
  5783. ref.mpe = true;
  5784. juce::String error;
  5785. auto instrument = clap ? host.makeInstrument (ref, 48000.0, &error) : nullptr;
  5786. report << "instrument_loaded=" << (instrument != nullptr ? "yes" : "no") << (error.isNotEmpty() ? " (" + error + ")" : juce::String()) << "\n";
  5787. if (instrument != nullptr)
  5788. {
  5789. std::vector<float> l (256), r (256);
  5790. auto block = [&] { instrument->render (l.data(), r.data(), 256, 1.0f, 1.0f); };
  5791. block(); // (the zone's setup)
  5792. instrument->setNextNoteFinePitch (30.0f); // +30 cents
  5793. instrument->setNextNoteModulation (0.75f, 1.0f); // timbre 0.75, full pressure
  5794. instrument->noteOn (60, 0.8f);
  5795. instrument->noteOn (64, 0.5f); // a second note: its own channel, centre values
  5796. block();
  5797. instrument->noteExpression (60, (int) lynx::vfx::Prop::pitch, 200.0f, 0.0f);
  5798. instrument->noteExpression (64, (int) lynx::vfx::Prop::modX, 0.25f, 0.0f);
  5799. instrument->noteExpression (60, (int) lynx::vfx::Prop::modY, 0.75f, 0.0f);
  5800. block();
  5801. instrument->noteOff (60);
  5802. instrument->noteOff (64);
  5803. block();
  5804. }
  5805. else
  5806. ++failures;
  5807. } // (the plugin writes its log as it is destroyed)
  5808. struct Line
  5809. {
  5810. juce::String kind;
  5811. int a = 0, b = 0, c = 0, d = 0;
  5812. };
  5813. std::vector<Line> lines;
  5814. for (const auto& text : juce::StringArray::fromLines (log.loadFileAsString()))
  5815. {
  5816. const auto t = juce::StringArray::fromTokens (text, " ", "");
  5817. if (t.size() >= 3)
  5818. lines.push_back ({ t[0], t[1].getIntValue(), t[2].getIntValue(), t.size() > 3 ? t[3].getIntValue() : 0, t.size() > 4 ? t[4].getIntValue() : 0 });
  5819. }
  5820. report << "plugin_events=" << (int) lines.size() << "\n";
  5821. // the first line at or after `from` that matches (−1 = none); `value` within `tolerance` (thousandths)
  5822. auto find = [&lines] (const juce::String& kind, int a, int b, int value, int tolerance, int from = 0) {
  5823. for (auto i = (std::size_t) from; i < lines.size(); ++i)
  5824. {
  5825. const auto& x = lines[i];
  5826. const auto v = kind == "expr" ? x.d : x.c;
  5827. if (x.kind == kind && x.a == a && x.b == b && std::abs (v - value) <= tolerance)
  5828. return (int) i;
  5829. }
  5830. return -1;
  5831. };
  5832. auto check = [&] (const char* what, bool ok) {
  5833. report << what << "=" << (ok ? "ok" : "FAILED") << "\n";
  5834. failures += ok ? 0 : 1;
  5835. };
  5836. // (CLAP expression ids: 2 tuning in semitones, 5 brightness, 6 pressure; channels 0-based: the first member = 1)
  5837. const auto on60 = find ("on", 1, 60, 800, 5), on64 = find ("on", 2, 64, 500, 5);
  5838. check ("zone_setup_sent", find ("midi", 176, 6, 15, 0) >= 0 && find ("midi", 177, 6, 48, 0) >= 0);
  5839. check ("notes_on_their_own_channels", on60 >= 0 && on64 > on60);
  5840. const auto tune = find ("expr", 2, 1, 300, 3), bright = find ("expr", 5, 1, 756, 4), press = find ("expr", 6, 1, 1000, 1);
  5841. check ("expression_before_the_note_on", tune >= 0 && bright >= 0 && press >= 0 && tune < on60 && bright < on60 && press < on60);
  5842. check ("second_note_starts_centred", find ("expr", 2, 2, 0, 1) >= 0 && find ("expr", 5, 2, 504, 4) >= 0 && find ("expr", 6, 2, 0, 1) >= 0);
  5843. const auto later = std::max (on60, on64) + 1;
  5844. check ("sounding_note_expression", later > 0 && find ("expr", 2, 1, 2000, 3, later) >= 0 && find ("expr", 5, 2, 252, 4, later) >= 0
  5845. && find ("expr", 6, 1, 504, 4, later) >= 0);
  5846. check ("other_note_untouched", later > 0 && find ("expr", 2, 2, 2000, 3, later) < 0 && find ("expr", 6, 2, 504, 4, later) < 0);
  5847. check ("notes_off_on_their_channels", find ("off", 1, 60, 0, 100000) >= 0 && find ("off", 2, 64, 0, 100000) >= 0);
  5848. auto expressionAsMidi = false; // (a CLAP-dialect plugin gets no raw bend / pressure / CC 74 on a member channel)
  5849. for (const auto& x : lines)
  5850. if (x.kind == "midi" && (x.a & 0x0f) != 0 && ((x.a & 0xf0) == 0xe0 || (x.a & 0xf0) == 0xd0 || ((x.a & 0xf0) == 0xb0 && x.b == 74)))
  5851. expressionAsMidi = true;
  5852. check ("no_duplicate_midi_expression", ! expressionAsMidi);
  5853. report << "--- plugin log ---\n" << log.loadFileAsString() << "result=" << (failures == 0 ? "OK" : "FAILED") << "\n";
  5854. juce::File (reportPath).replaceWithText (report);
  5855. setApplicationReturnValue (failures == 0 ? 0 : 1);
  5856. quit();
  5857. }
  5858. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
  5859. // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
  5860. // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
  5861. // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
  5862. // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
  5863. // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
  5864. // the latency the plugin reports after its last restart.
  5865. void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
  5866. {
  5867. struct Run
  5868. {
  5869. std::unique_ptr<lynx::AudioEngine> engine;
  5870. juce::String report;
  5871. int slot = -1;
  5872. std::thread render;
  5873. std::atomic<bool> done { false };
  5874. double renderSeconds = 0.0;
  5875. };
  5876. auto run = std::make_shared<Run>();
  5877. const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  5878. counters.deleteFile();
  5879. #if JUCE_WINDOWS
  5880. _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
  5881. #else
  5882. setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
  5883. #endif
  5884. const auto fail = [this, reportPath] (juce::String report) {
  5885. report << "result=FAILED\n";
  5886. juce::File (reportPath).replaceWithText (report);
  5887. setApplicationReturnValue (1);
  5888. quit();
  5889. };
  5890. run->engine = std::make_unique<lynx::AudioEngine> (false);
  5891. auto& host = run->engine->getPluginHost();
  5892. run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  5893. std::optional<juce::PluginDescription> clap;
  5894. for (const auto& type : host.getKnownPlugins().getTypes())
  5895. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  5896. clap = type;
  5897. if (! clap)
  5898. {
  5899. fail (run->report + "no CLAP plugin in the file\n");
  5900. return;
  5901. }
  5902. auto song = lynx::Song::makeDefault();
  5903. lynx::EffectSlot slot;
  5904. slot.kind = lynx::EffectKind::plugin;
  5905. slot.plugin.id = clap->createIdentifierString().toStdString();
  5906. slot.plugin.name = clap->name.toStdString();
  5907. slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
  5908. song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
  5909. run->slot = (int) song.mixer[0].effects.size() - 1;
  5910. run->engine->setSong (song);
  5911. run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
  5912. if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
  5913. {
  5914. fail (run->report + "effect_loaded=no\n");
  5915. return;
  5916. }
  5917. auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
  5918. run->render = std::thread ([run, effect] () mutable {
  5919. const auto start = juce::Time::getMillisecondCounterHiRes();
  5920. run->engine->renderOffline (30.0, 48000.0);
  5921. run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
  5922. // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
  5923. // plugin aborts unless activate / deactivate reach the main thread
  5924. auto& instance = effect->getInstance();
  5925. instance.prepareToPlay (44100.0, 1024);
  5926. instance.releaseResources();
  5927. instance.prepareToPlay (48000.0, 512);
  5928. run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
  5929. // The engine has replaced this instance (made for 48 kHz) by then, so this is its last reference: it is
  5930. // deleted here, on the export's thread, and its deactivate / destroy go to the message thread, which this
  5931. // waits for. That has to happen before `done`: once the message thread sees it, it blocks in join() until
  5932. // this thread ends, and an instance deleted after that waited 10 s for it and then deactivated the plugin
  5933. // right here, off the main thread (the plugin aborts: about 1 run in 40 under load, round 190au).
  5934. effect.reset();
  5935. run->done = true;
  5936. });
  5937. // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
  5938. auto finish = std::make_shared<std::function<void()>>();
  5939. *finish = [this, run, counters, reportPath, fail, finish] {
  5940. if (! run->done)
  5941. {
  5942. juce::Timer::callAfterDelay (50, *finish);
  5943. return;
  5944. }
  5945. run->render.join();
  5946. juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
  5947. auto report = run->report;
  5948. int pluginLatency = -1;
  5949. if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
  5950. pluginLatency = effect->latencySamples();
  5951. const auto pdc = run->engine->getLatencySamples();
  5952. report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
  5953. << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
  5954. << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  5955. run->engine.reset(); // destroys the plugin: it writes its counters
  5956. // one line per plugin instance (the engine may have made more than one): none may have been
  5957. // deactivated inside process(), and the one that rendered must have restarted
  5958. int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
  5959. bool otherRate = false;
  5960. for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
  5961. {
  5962. juce::StringPairArray values;
  5963. for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
  5964. if (token.contains ("="))
  5965. values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
  5966. if (values.size() == 0)
  5967. continue;
  5968. ++lines;
  5969. report << "instance: " << line << "\n";
  5970. overlapped += values["overlapped"].getIntValue();
  5971. inactive += values["inactive_blocks"].getIntValue();
  5972. // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
  5973. // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
  5974. wrongThread += values["wrong_thread"].getIntValue();
  5975. misordered += values["misordered"].getIntValue();
  5976. unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
  5977. otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
  5978. if (values["requests"].getIntValue() > requests)
  5979. {
  5980. requests = values["requests"].getIntValue();
  5981. activations = values["activations"].getIntValue();
  5982. }
  5983. }
  5984. report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
  5985. << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
  5986. const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
  5987. && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
  5988. && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
  5989. if (! ok)
  5990. {
  5991. fail (report);
  5992. return;
  5993. }
  5994. report << "result=OK\n";
  5995. juce::File (reportPath).replaceWithText (report);
  5996. setApplicationReturnValue (0);
  5997. quit();
  5998. });
  5999. };
  6000. juce::Timer::callAfterDelay (50, *finish);
  6001. }
  6002. // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
  6003. // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
  6004. // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
  6005. void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
  6006. {
  6007. juce::String report;
  6008. bool ok = false;
  6009. {
  6010. lynx::AudioEngine offline (false);
  6011. auto& host = offline.getPluginHost();
  6012. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  6013. std::optional<juce::PluginDescription> vst2;
  6014. for (const auto& type : host.getKnownPlugins().getTypes())
  6015. if (type.pluginFormatName == "VST")
  6016. vst2 = type;
  6017. auto render = [&] (float gain, float& tempoSeen, int& adopted) {
  6018. lynx::FlVst2State state;
  6019. state.flags = 8;
  6020. state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
  6021. std::memcpy (state.chunk.data() + 4, &gain, 4);
  6022. auto song = lynx::Song::makeDefault();
  6023. song.bpm = 137.0;
  6024. auto& f = song.channels[4].plugin.foreign;
  6025. f.format = lynx::ForeignPlugin::Format::vst2;
  6026. f.vst2Id = (std::uint32_t) vst2->uniqueId;
  6027. f.name = "Some other name"; // found by the VST2 ID
  6028. f.state = lynx::writeFlVst2State (state);
  6029. song.channels[4].volume = 1.0f;
  6030. song.patterns[0].notes.clear();
  6031. song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
  6032. for (std::size_t c = 0; c < song.channels.size(); ++c)
  6033. if (c != 4)
  6034. song.channels[c].muted = true;
  6035. adopted = host.adoptFlPlugins (song);
  6036. offline.setSong (song);
  6037. const auto peak = offline.renderOffline (1.0, 48000.0);
  6038. offline.capturePluginStates();
  6039. juce::MemoryBlock saved;
  6040. saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
  6041. lynx::FlVst2State back;
  6042. tempoSeen = 0.0f;
  6043. if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
  6044. && back.chunk.size() >= 12)
  6045. std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
  6046. return peak;
  6047. };
  6048. if (vst2)
  6049. {
  6050. report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
  6051. float tempoA = 0, tempoB = 0;
  6052. int adoptedA = 0, adoptedB = 0;
  6053. const auto quiet = render (0.1f, tempoA, adoptedA);
  6054. const auto loud = render (0.4f, tempoB, adoptedB);
  6055. report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
  6056. << " tempo_seen=" << tempoB * 1000.0f << "\n";
  6057. ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
  6058. && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
  6059. }
  6060. }
  6061. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  6062. juce::File (reportPath).replaceWithText (report);
  6063. setApplicationReturnValue (ok ? 0 : 1);
  6064. quit();
  6065. }
  6066. // Round 181c: a wrapper MIDI option changed on a running plugin must act like the same option on a new one. For each
  6067. // option: a control engine whose plugin is created with the option set (proves the test can see it), then an engine
  6068. // whose plugin is already running when the option changes through editSong, as the wrapper page does it. What the
  6069. // plugin received comes from the test plugin's own log. The running instance must also stay the same one.
  6070. void runWrapperMidiTest (const juce::String& pluginPath, const juce::String& reportPath)
  6071. {
  6072. juce::String report;
  6073. auto ok = true;
  6074. const juce::File logFile (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_VST2_MIDILOG", {}));
  6075. struct Event { juce::String instance; int status, data1, data2; };
  6076. auto take = [&] {
  6077. std::vector<Event> out;
  6078. juce::StringArray lines;
  6079. logFile.readLines (lines);
  6080. for (const auto& line : lines)
  6081. {
  6082. const auto p = juce::StringArray::fromTokens (line, " ", {});
  6083. if (p.size() == 4)
  6084. out.push_back ({ p[0], p[1].getIntValue(), p[2].getIntValue(), p[3].getIntValue() });
  6085. }
  6086. logFile.deleteFile();
  6087. return out;
  6088. };
  6089. auto count = [] (const std::vector<Event>& events, int status, int data1, int data2) {
  6090. int n = 0;
  6091. for (const auto& e : events)
  6092. n += (e.status & 0xF0) == status && (data1 < 0 || e.data1 == data1) && (data2 < 0 || e.data2 == data2) ? 1 : 0;
  6093. return n;
  6094. };
  6095. struct Option
  6096. {
  6097. const char* name;
  6098. std::function<void (lynx::PluginRef&)> before, change;
  6099. std::function<juce::String (const std::vector<Event>&)> seen;
  6100. };
  6101. const Option options[] = {
  6102. { "Send note release velocity off", {}, [] (lynx::PluginRef& r) { r.releaseVelocity = false; },
  6103. [&] (const std::vector<Event>& e) { return "offs_with_release_32=" + juce::String (count (e, 0x80, 69, 32)) + " offs_at_0=" + juce::String (count (e, 0x80, 69, 0)); } },
  6104. { "Send pitch bend range on", {}, [] (lynx::PluginRef& r) { r.sendBendRange = true; },
  6105. [&] (const std::vector<Event>& e) { return "rpn_range_12=" + juce::String (count (e, 0xB0, 6, 12)); } },
  6106. { "Pitch bend range 24", [] (lynx::PluginRef& r) { r.sendBendRange = true; }, [] (lynx::PluginRef& r) { r.bendRange = 24; },
  6107. [&] (const std::vector<Event>& e) { return "rpn_range_24=" + juce::String (count (e, 0xB0, 6, 24)); } },
  6108. { "Send MOD X as polyphonic aftertouch on", {}, [] (lynx::PluginRef& r) { r.modXAftertouch = true; },
  6109. [&] (const std::vector<Event>& e) { return "aftertouch=" + juce::String (count (e, 0xA0, 69, -1)); } },
  6110. { "Send All Notes Off when playback stops off", {}, [] (lynx::PluginRef& r) { r.allNotesOffOnStop = false; },
  6111. [&] (const std::vector<Event>& e) { return "cc123=" + juce::String (count (e, 0xB0, 123, -1)); } },
  6112. };
  6113. // each phase has its own engine: an engine keeps the running instance across setSong, so one engine would
  6114. // carry the control's plugin into the "before" phase
  6115. lynx::AudioEngine scanner (false);
  6116. auto& host = scanner.getPluginHost();
  6117. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  6118. std::optional<juce::PluginDescription> vst2;
  6119. for (const auto& type : host.getKnownPlugins().getTypes())
  6120. if (type.pluginFormatName == "VST")
  6121. vst2 = type;
  6122. if (! vst2 || logFile.getFullPathName().isEmpty())
  6123. ok = false;
  6124. else
  6125. for (const auto& option : options)
  6126. {
  6127. auto makeSong = [&] (bool changed) {
  6128. auto song = lynx::Song::makeDefault();
  6129. auto& channel = song.channels[0];
  6130. channel.instrument = lynx::InstrumentKind::plugin;
  6131. channel.plugin = {};
  6132. channel.plugin.id = vst2->createIdentifierString().toStdString();
  6133. channel.plugin.name = vst2->name.toStdString();
  6134. if (option.before)
  6135. option.before (channel.plugin);
  6136. if (changed)
  6137. option.change (channel.plugin);
  6138. song.patterns[0].notes.clear();
  6139. lynx::Note note;
  6140. note.start = 0;
  6141. note.length = lynx::ppq;
  6142. note.channel = 0;
  6143. note.key = 69;
  6144. note.velocity = 1.0f;
  6145. note.release = 0.25f; // 32 of 127
  6146. note.modX = 0.75f;
  6147. song.patterns[0].notes.push_back (note);
  6148. for (std::size_t c = 1; c < song.channels.size(); ++c)
  6149. song.channels[c].muted = true;
  6150. return song;
  6151. };
  6152. // a block of the song, then a note held across "playback stopped", as the options act on either
  6153. auto play = [&] (lynx::AudioEngine& engine) {
  6154. logFile.deleteFile();
  6155. engine.renderOffline (1.0, 48000.0);
  6156. if (auto instrument = engine.getChannelInstrument (0))
  6157. {
  6158. instrument->noteOn (60, 1.0f);
  6159. instrument->transportStopped();
  6160. }
  6161. engine.renderOffline (0.1, 48000.0);
  6162. return take();
  6163. };
  6164. auto newEngine = [&] {
  6165. auto engine = std::make_unique<lynx::AudioEngine> (false);
  6166. engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  6167. return engine;
  6168. };
  6169. std::vector<Event> control;
  6170. {
  6171. auto engine = newEngine();
  6172. engine->setSong (makeSong (true));
  6173. control = play (*engine);
  6174. }
  6175. auto engine = newEngine();
  6176. engine->setSong (makeSong (false));
  6177. const auto before = play (*engine);
  6178. const auto instrumentBefore = engine->getChannelInstrument (0).get();
  6179. engine->capturePluginStates(); // as the wrapper page does
  6180. engine->editSong ([&] (lynx::Song& song) { option.change (song.channels[0].plugin); });
  6181. const auto after = play (*engine);
  6182. const auto sameInstance = engine->getChannelInstrument (0).get() == instrumentBefore;
  6183. // the counts differ between phases (how many blocks the note spans, how many instances the phase made):
  6184. // what matters is whether each kind of event is there at all
  6185. auto shape = [] (const juce::String& seen) {
  6186. juce::String out;
  6187. for (const auto& token : juce::StringArray::fromTokens (seen, " ", {}))
  6188. out << token.upToFirstOccurrenceOf ("=", false, false) << (token.fromFirstOccurrenceOf ("=", false, false).getIntValue() > 0 ? "=yes " : "=no ");
  6189. return out;
  6190. };
  6191. auto instances = [] (const std::vector<Event>& events) {
  6192. std::set<juce::String> made;
  6193. for (const auto& e : events)
  6194. made.insert (e.instance);
  6195. return (int) made.size();
  6196. };
  6197. const auto a = option.seen (control) + " instances=" + juce::String (instances (control)),
  6198. b = option.seen (before) + " instances=" + juce::String (instances (before)),
  6199. c = option.seen (after) + " instances=" + juce::String (instances (after));
  6200. const auto visible = shape (option.seen (control)) != shape (option.seen (before));
  6201. const auto works = shape (option.seen (after)) == shape (option.seen (control));
  6202. report << option.name << ": control " << a << " | before " << b << " | after the change " << c << " | same_instance=" << (int) sameInstance
  6203. << " | test_sees_the_option=" << (int) visible << " | " << (! visible ? "NOT PROVEN" : works ? "acts on the plugin" : "DEAD until re-created") << "\n";
  6204. ok = ok && visible && works;
  6205. }
  6206. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  6207. juce::File (reportPath).replaceWithText (report);
  6208. setApplicationReturnValue (ok ? 0 : 1);
  6209. quit();
  6210. }
  6211. // LYNX.exe --wrappershot "LYNX Test Drums.dll" <folder> (round 188d): the wrapper's Processing tab drawn offscreen
  6212. // (no window, no focus) for the FL | LYNX review: wrap-default.png (a fresh plugin), wrap-automap.png (Auto map
  6213. // outputs, output 3 off: FL's shot b23), wrap-settings.png. Scale 1.5 (FL's shots are at 150 %).
  6214. void runWrapperShot (const juce::String& pluginPath, const juce::String& folderPath)
  6215. {
  6216. const juce::File folder (folderPath);
  6217. folder.createDirectory();
  6218. auto ok = false;
  6219. lynx::AudioEngine engine (false);
  6220. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  6221. std::optional<juce::PluginDescription> vst2;
  6222. for (const auto& type : engine.getPluginHost().getKnownPlugins().getTypes())
  6223. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  6224. vst2 = type; // (the profile may know other test plugins)
  6225. if (vst2 && ! vst2->isInstrument)
  6226. {
  6227. // an effect (round 188d): on insert 1, with insert 2 routed there as a sidechain (FL's k65 / k78 shots):
  6228. // wrap-fx-default.png, wrap-fx-automap.png (Auto map inputs and outputs)
  6229. auto song = lynx::Song::makeDefault();
  6230. if (song.mixer.size() < 4)
  6231. song.mixer.resize (4);
  6232. auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
  6233. slot.plugin.id = vst2->createIdentifierString().toStdString();
  6234. slot.plugin.name = vst2->name.toStdString();
  6235. song.mixer[1].effects = { slot };
  6236. lynx::mixerops::sidechainTo (song, 2, 1);
  6237. engine.setSong (song);
  6238. engine.renderOffline (0.05, 48000.0);
  6239. if (auto fx = std::dynamic_pointer_cast<lynx::PluginEffect> (engine.getEffect (1, 0)))
  6240. {
  6241. auto find = [] (lynx::Song& s) -> lynx::PluginRef* {
  6242. return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
  6243. };
  6244. auto save = [&] (const char* name) {
  6245. const auto image = lynx::wrapperSettingsSnapshot (engine, find, fx->getInstance(), false, 1, 1.5f, 1, 0);
  6246. juce::FileOutputStream out (folder.getChildFile (name));
  6247. out.setPosition (0);
  6248. out.truncate();
  6249. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  6250. };
  6251. ok = save ("wrap-fx-default.png");
  6252. engine.editSong ([] (lynx::Song& s) {
  6253. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.inputs, 2);
  6254. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.outputs, 2);
  6255. s.mixer[1].effects[0].sidechain = lynx::mixerops::sidechainIndexSource (s, 1, 1);
  6256. });
  6257. ok = ok && save ("wrap-fx-automap.png") && engine.getSong().mixer[1].effects[0].sidechain == 2;
  6258. }
  6259. }
  6260. else if (vst2)
  6261. {
  6262. auto song = lynx::Song::makeDefault();
  6263. auto& channel = song.channels[0];
  6264. channel.instrument = lynx::InstrumentKind::plugin;
  6265. channel.plugin = {};
  6266. channel.plugin.id = vst2->createIdentifierString().toStdString();
  6267. channel.plugin.name = vst2->name.toStdString();
  6268. channel.mixerTrack = 5;
  6269. engine.setSong (song);
  6270. engine.renderOffline (0.05, 48000.0); // (the plugin is hosted by then)
  6271. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  6272. {
  6273. auto find = [] (lynx::Song& s) -> lynx::PluginRef* { return s.channels.empty() ? nullptr : &s.channels[0].plugin; };
  6274. auto save = [&] (const char* name, int tab) {
  6275. const auto image = lynx::wrapperSettingsSnapshot (engine, find, instrument->getInstance(), true, tab, 1.5f);
  6276. juce::FileOutputStream out (folder.getChildFile (name));
  6277. out.setPosition (0);
  6278. out.truncate();
  6279. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  6280. };
  6281. ok = save ("wrap-default.png", 1) && save ("wrap-settings.png", 0);
  6282. engine.editSong ([] (lynx::Song& s) {
  6283. lynx::autoMapOutputs (s.channels[0].plugin.outputs, 8);
  6284. s.channels[0].plugin.outputs.resize (8);
  6285. s.channels[0].plugin.outputs[2].active = 0;
  6286. s.channels[0].plugin.processInactive = false; // (as an LED click does, FL's b23)
  6287. });
  6288. ok = ok && save ("wrap-automap.png", 1);
  6289. }
  6290. }
  6291. setApplicationReturnValue (ok ? 0 : 1);
  6292. quit();
  6293. }
  6294. // LYNX.exe --multiouttest "LYNX Test Drums.dll" report.txt (round 188d, issue #114): a multi-output VST2
  6295. // (tools/testplugin/lynx_test_drums_vst2.c: key 36 = output 1 at 110 Hz, key 37 = output 2 at 220 Hz) on a
  6296. // channel routed to insert 1; the wrapper's Processing › Connections as FL plays them [EXEC fl188d]: every output
  6297. // on the channel's insert by default, an offset to another insert, an inactive output silent, the channel's
  6298. // volume on all of them. Measured on the master with insert 1 muted or not.
  6299. void runMultiOutTest (const juce::String& pluginPath, const juce::String& reportPath)
  6300. {
  6301. juce::String report;
  6302. auto ok = true;
  6303. lynx::AudioEngine scanner (false);
  6304. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  6305. std::optional<juce::PluginDescription> vst2;
  6306. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  6307. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  6308. vst2 = type; // (the profile may know other test plugins)
  6309. struct Case
  6310. {
  6311. const char* name;
  6312. std::vector<lynx::PluginOutputRoute> routes;
  6313. bool muteInsert1;
  6314. float volume;
  6315. bool kick, snare; // expected on the master
  6316. };
  6317. const Case cases[] = {
  6318. { "defaults", {}, false, -1.0f, true, true },
  6319. { "defaults, insert 1 muted", {}, true, -1.0f, false, false },
  6320. { "auto map, insert 1 muted", { { 0, 1 }, { 1, 1 } }, true, -1.0f, false, true },
  6321. { "auto map", { { 0, 1 }, { 1, 1 } }, false, -1.0f, true, true },
  6322. { "output 2 inactive", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, false },
  6323. { "output 1 inactive", { { 0, 0 } }, false, -1.0f, false, true },
  6324. { "auto map, channel volume 0", { { 0, 1 }, { 1, 1 } }, false, 0.0f, false, false },
  6325. { "output 2 inactive, Process inactive inputs and outputs on", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, true },
  6326. };
  6327. auto tone = [] (const std::vector<float>& x, double hz) {
  6328. // Goertzel magnitude over the buffer (normalised to a sine's amplitude)
  6329. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 48000.0;
  6330. double s1 = 0.0, s2 = 0.0;
  6331. for (const auto v : x)
  6332. {
  6333. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  6334. s2 = s1;
  6335. s1 = s0;
  6336. }
  6337. return std::sqrt (s1 * s1 + s2 * s2 - 2.0 * std::cos (w) * s1 * s2) * 2.0 / (double) std::max<std::size_t> (1, x.size());
  6338. };
  6339. if (! vst2)
  6340. ok = false;
  6341. else
  6342. for (const auto& c : cases)
  6343. {
  6344. lynx::AudioEngine engine (false);
  6345. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  6346. auto song = lynx::Song::makeDefault();
  6347. auto& channel = song.channels[0];
  6348. channel.instrument = lynx::InstrumentKind::plugin;
  6349. channel.plugin = {};
  6350. channel.plugin.id = vst2->createIdentifierString().toStdString();
  6351. channel.plugin.name = vst2->name.toStdString();
  6352. channel.plugin.outputs = c.routes;
  6353. // (FL's "Process inactive inputs and outputs" plays an inactive output: off but for the case named so)
  6354. channel.plugin.processInactive = juce::String (c.name).contains ("Process inactive");
  6355. channel.mixerTrack = 1;
  6356. if (c.volume >= 0.0f)
  6357. channel.volume = c.volume;
  6358. for (std::size_t k = 1; k < song.channels.size(); ++k)
  6359. song.channels[k].muted = true;
  6360. if (song.mixer.size() < 4)
  6361. song.mixer.resize (4);
  6362. song.mixer[1].muted = c.muteInsert1;
  6363. song.patterns[0].notes.clear();
  6364. for (const auto key : { 36, 37 })
  6365. {
  6366. lynx::Note note;
  6367. note.start = 0;
  6368. note.length = lynx::ppq;
  6369. note.channel = 0;
  6370. note.key = key;
  6371. note.velocity = 1.0f;
  6372. song.patterns[0].notes.push_back (note);
  6373. }
  6374. engine.setSong (song);
  6375. std::vector<float> master;
  6376. lynx::AudioEngine::RenderOptions options;
  6377. options.seconds = 0.25;
  6378. options.sampleRate = 48000.0;
  6379. options.capture = [&master] (const float* l, const float*, int n) { master.insert (master.end(), l, l + n); };
  6380. engine.renderOffline (options);
  6381. const auto kick = tone (master, 110.0), snare = tone (master, 220.0);
  6382. const auto pass = (kick > 0.01) == c.kick && (snare > 0.01) == c.snare;
  6383. report << c.name << ": kick_110Hz=" << juce::String (kick, 4) << " snare_220Hz=" << juce::String (snare, 4) << " expected kick="
  6384. << (int) c.kick << " snare=" << (int) c.snare << (pass ? " OK" : " FAILED") << "\n";
  6385. ok = ok && pass;
  6386. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  6387. if (&c == &cases[0])
  6388. {
  6389. report << "outputs=" << (int) instrument->outputs().size();
  6390. for (const auto& o : instrument->outputs())
  6391. report << " [" << o.name << " ch" << o.channel << "x" << o.channels << "]";
  6392. report << "\n";
  6393. ok = ok && instrument->outputs().size() == 8 && instrument->outputs()[1].name == "Snare";
  6394. }
  6395. }
  6396. // round 189j: "LYNX Test SC.dll" next to it (tools/testplugin/lynx_test_sc_vst2.c) as an effect on insert 1
  6397. const auto sc = juce::File (pluginPath).getSiblingFile ("LYNX Test SC.dll");
  6398. if (sc.existsAsFile())
  6399. ok = runEffectConnectionsTest (sc, report) && ok;
  6400. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  6401. juce::File (reportPath).replaceWithText (report);
  6402. setApplicationReturnValue (ok ? 0 : 1);
  6403. quit();
  6404. }
  6405. // Round 189j: a hosted effect's Processing › Connections against FL 2026's own renders of the same projects
  6406. // [EXEC fxconn189j: FL /R renders of LYNX's .flp exports, docs/analise/REA_rodada189j.md]. Insert 1: a 440 Hz
  6407. // sampler and "LYNX Test SC" (output 1 = input 1, output 2 = input 2); inserts 2 (1000 Hz) and 3 (1500 Hz) routed
  6408. // to insert 1 at level 0 only; insert 4 a 2500 Hz reference on the Master; insert 1 routed to the Master and at
  6409. // level 0 to inserts 5 (panned left) and 6 (right). Each tone's level per side, in dB from the reference's, must be
  6410. // FL's within 0.5 dB (absent: 50 dB under it).
  6411. bool runEffectConnectionsTest (const juce::File& scFile, juce::String& report)
  6412. {
  6413. lynx::AudioEngine scanner (false);
  6414. scanner.getPluginHost().addPluginFile (scFile);
  6415. std::optional<juce::PluginDescription> sc;
  6416. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  6417. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == scFile)
  6418. sc = type;
  6419. report << "effect_plugin=" << (sc ? sc->name : juce::String ("not found")) << "\n";
  6420. if (! sc)
  6421. return false;
  6422. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-fxconn189j");
  6423. dir.createDirectory();
  6424. const double tones[] = { 440.0, 1000.0, 1500.0, 2500.0 };
  6425. for (const auto hz : tones)
  6426. {
  6427. const auto wav = dir.getChildFile ("sine" + juce::String ((int) hz) + ".wav");
  6428. if (wav.existsAsFile())
  6429. continue;
  6430. juce::AudioBuffer<float> sine (1, 44100 * 3);
  6431. for (int i = 0; i < sine.getNumSamples(); ++i)
  6432. sine.setSample (0, i, 0.25f * (float) std::sin (2.0 * juce::MathConstants<double>::pi * hz * i / 44100.0));
  6433. juce::WavAudioFormat format;
  6434. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  6435. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  6436. {
  6437. out.release();
  6438. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  6439. writer->writeFromAudioSampleBuffer (sine, 0, sine.getNumSamples());
  6440. }
  6441. }
  6442. using Route = lynx::PluginOutputRoute;
  6443. constexpr float none = -999.0f;
  6444. struct Case
  6445. {
  6446. const char* name;
  6447. std::vector<Route> inputs, outputs;
  6448. int tweak; // 1 no Master route, 2 insert 1 fader at 0.4, 3 Process inactive off, 4 Master route level 0, 5 route
  6449. // to 7 too, 6 insert 2 fader at 0.4, 7 insert 2 muted, 8 insert 2 panned left
  6450. float level[3][2]; // 440 / 1000 / 1500 Hz, left / right: dB from the reference, FL's
  6451. };
  6452. const Route d { 0, 1 };
  6453. const Case cases[] = {
  6454. { "e00 FL defaults", { d, d }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  6455. { "e01 input 1 at 1", { { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  6456. { "e02 input 1 at 2", { { 2, 1 } }, {}, 0, { { 0, 0 }, { none, none }, { 0, 0 } } },
  6457. { "e03 input 2 at 1", { d, { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  6458. { "e04 output 2 at 1 (Master)", { d, { 1, 1 } }, { d, { 1, 1 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  6459. { "e05 output 2 at 2 (insert 5)", { d, { 1, 1 } }, { d, { 2, 1 } }, 0, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  6460. { "e06 output 1 at 1", {}, { { 1, 1 } }, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  6461. { "e07 output 2 at 5 (past the list)", { d, { 1, 1 } }, { d, { 5, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  6462. { "e08 inputs 1 and 2 at 1", { { 1, 1 }, { 1, 1 } }, {}, 0, { { none, none }, { 6.1f, 6.1f }, { none, none } } },
  6463. { "e09 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  6464. { "e10 input 1 at 5 (past the list)", { { 5, 1 } }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  6465. { "e11 output 2 at 3 (insert 6)", { d, { 1, 1 } }, { d, { 3, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  6466. { "e13 no Master route, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 1, { { none, none }, { 3.0f, none }, { none, none } } },
  6467. { "e14 insert 1 fader 0.4, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 2, { { -12.7f, -12.7f }, { 0, 0 }, { none, none } } },
  6468. { "e15 input 2 inactive", { d, { 1, 0 } }, { d, d }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  6469. { "e16 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  6470. { "e18 route to 7 too, output 2 at 3", { d, { 1, 1 } }, { d, { 3, 1 } }, 5, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  6471. { "e19 Master route at 0, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 4, { { none, none }, { 0, 0 }, { none, none } } },
  6472. { "e22 input 1 at 1 inactive", { { 1, 0 } }, {}, 3, { { 0, 0 }, { none, none }, { none, none } } },
  6473. { "e23 output 2 at -1, insert 1 fader 0.4", { d, { 1, 1 } }, { d, { -1, 1 } }, 2, { { -12.7f, -12.7f }, { 0, 0 }, { none, none } } },
  6474. { "e24 input 1 at 1, insert 2 fader 0.4", { { 1, 1 } }, {}, 6, { { 0, 0 }, { -12.7f, -12.7f }, { none, none } } },
  6475. { "e25 input 1 at 1, insert 2 muted", { { 1, 1 } }, {}, 7, { { 0, 0 }, { none, none }, { none, none } } },
  6476. { "e26 input 1 at 1, insert 2 panned left", { { 1, 1 } }, {}, 8, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  6477. };
  6478. auto goertzel = [] (const std::vector<float>& x, double hz) {
  6479. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 44100.0;
  6480. double s1 = 0.0, s2 = 0.0;
  6481. for (const auto v : x)
  6482. {
  6483. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  6484. s2 = s1;
  6485. s1 = s0;
  6486. }
  6487. const auto a = std::sqrt (juce::jmax (0.0, s1 * s1 + s2 * s2 - 2.0 * std::cos (w) * s1 * s2)) * 2.0 / (double) std::max<std::size_t> (1, x.size());
  6488. return a > 1e-7 ? 20.0 * std::log10 (a) : -140.0;
  6489. };
  6490. auto ok = true;
  6491. for (const auto& c : cases)
  6492. {
  6493. lynx::AudioEngine engine (false);
  6494. engine.getPluginHost().addPluginFile (scFile);
  6495. auto song = lynx::Song::makeDefault();
  6496. song.bpm = 120.0;
  6497. song.channels.clear();
  6498. song.automations.clear();
  6499. for (auto& p : song.patterns)
  6500. p.notes.clear();
  6501. for (int k = 0; k < 4; ++k)
  6502. {
  6503. lynx::ChannelDef ch;
  6504. ch.name = "S" + std::to_string ((int) tones[k]);
  6505. ch.instrument = lynx::InstrumentKind::sampler;
  6506. ch.samplePath = dir.getChildFile ("sine" + juce::String ((int) tones[k]) + ".wav").getFullPathName().toStdString();
  6507. ch.mixerTrack = k + 1;
  6508. song.channels.push_back (ch);
  6509. lynx::Note note;
  6510. note.start = 0;
  6511. note.length = 8 * lynx::ppq;
  6512. note.channel = k;
  6513. note.key = 60;
  6514. note.velocity = 0.78f;
  6515. song.patterns[0].notes.push_back (note);
  6516. }
  6517. if (song.mixer.size() < 10)
  6518. song.mixer.resize (10);
  6519. for (auto& t : song.mixer)
  6520. {
  6521. t.effects.clear();
  6522. t.sends.clear();
  6523. t.toMaster = true;
  6524. }
  6525. lynx::EffectSlot fx;
  6526. fx.kind = lynx::EffectKind::plugin;
  6527. fx.plugin.id = sc->createIdentifierString().toStdString();
  6528. fx.plugin.name = sc->name.toStdString();
  6529. fx.plugin.inputs = c.inputs;
  6530. fx.plugin.outputs = c.outputs;
  6531. fx.plugin.processInactive = c.tweak != 3;
  6532. auto& one = song.mixer[1];
  6533. one.effects.push_back (fx);
  6534. one.sends = { { 5, 0.0f }, { 6, 0.0f } };
  6535. for (const int t : { 2, 3 })
  6536. {
  6537. song.mixer[(std::size_t) t].toMaster = false;
  6538. song.mixer[(std::size_t) t].sends = { { 1, 0.0f } };
  6539. }
  6540. song.mixer[5].pan = -1.0f;
  6541. song.mixer[6].pan = 1.0f;
  6542. one.toMaster = c.tweak != 1;
  6543. if (c.tweak == 2)
  6544. one.volume = 0.4f;
  6545. if (c.tweak == 4)
  6546. one.masterLevel = 0.0f;
  6547. if (c.tweak == 6)
  6548. song.mixer[2].volume = 0.4f;
  6549. song.mixer[2].muted = c.tweak == 7;
  6550. song.mixer[2].pan = c.tweak == 8 ? -1.0f : 0.0f;
  6551. if (c.tweak == 5)
  6552. {
  6553. one.sends = { { 7, 0.0f }, { 5, 0.0f }, { 6, 0.0f } };
  6554. song.mixer[7].pan = 0.5f;
  6555. }
  6556. // (input 2's index sets the slot's side input source, as the Connections page and the import do)
  6557. if (c.inputs.size() > 1 && c.inputs[1].offset > 0)
  6558. one.effects[0].sidechain = lynx::mixerops::sidechainIndexSource (song, 1, c.inputs[1].offset);
  6559. engine.setSong (song);
  6560. std::vector<float> left, right;
  6561. lynx::AudioEngine::RenderOptions options;
  6562. options.seconds = 1.2;
  6563. options.sampleRate = 44100.0;
  6564. options.capture = [&] (const float* l, const float* r, int n) {
  6565. left.insert (left.end(), l, l + n);
  6566. right.insert (right.end(), r, r + n);
  6567. };
  6568. engine.renderOffline (options);
  6569. const auto from = (std::size_t) 22050, to = (std::size_t) 44100;
  6570. if (right.size() < to)
  6571. {
  6572. report << c.name << ": rendered " << (int) right.size() << " samples FAILED\n";
  6573. ok = false;
  6574. continue;
  6575. }
  6576. const std::vector<float> l (left.begin() + (std::ptrdiff_t) from, left.begin() + (std::ptrdiff_t) to);
  6577. const std::vector<float> r (right.begin() + (std::ptrdiff_t) from, right.begin() + (std::ptrdiff_t) to);
  6578. const auto ref = 0.5 * (goertzel (l, 2500.0) + goertzel (r, 2500.0));
  6579. auto pass = ref > -60.0;
  6580. report << c.name << ": ref=" << juce::String (ref, 1);
  6581. for (int k = 0; k < 3; ++k)
  6582. for (int side = 0; side < 2; ++side)
  6583. {
  6584. const auto got = goertzel (side == 0 ? l : r, tones[k]) - ref;
  6585. const auto want = c.level[k][side];
  6586. const auto good = want == none ? got < -50.0 : std::abs (got - want) < 0.5;
  6587. pass = pass && good;
  6588. report << " " << (int) tones[k] << (side == 0 ? "L" : "R") << "=" << (got < -50.0 ? juce::String ("-") : juce::String (got, 1))
  6589. << (good ? "" : "(FL " + (want == none ? juce::String ("-") : juce::String (want, 1)) + ")");
  6590. }
  6591. report << (pass ? " OK" : " FAILED") << "\n";
  6592. ok = ok && pass;
  6593. }
  6594. return ok;
  6595. }
  6596. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  6597. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  6598. // that the plugin comes back with the changed parameter.
  6599. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  6600. {
  6601. juce::String report;
  6602. bool ok = false;
  6603. {
  6604. lynx::AudioEngine offline (false);
  6605. auto& host = offline.getPluginHost();
  6606. host.addPluginFile (juce::File (pluginPath));
  6607. const juce::PluginDescription* vst3 = nullptr;
  6608. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  6609. for (const auto& type : types)
  6610. if (type.pluginFormatName == "VST3" && type.isInstrument)
  6611. vst3 = &type;
  6612. if (vst3 != nullptr)
  6613. {
  6614. juce::String error;
  6615. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  6616. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  6617. if (parameter != nullptr)
  6618. {
  6619. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  6620. parameter->setValueNotifyingHost (target);
  6621. juce::MemoryBlock juceState;
  6622. plugin->getStateInformation (juceState);
  6623. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  6624. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  6625. std::vector<std::uint8_t> flState;
  6626. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  6627. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  6628. put32 (id);
  6629. put32 ((std::uint32_t) data.getSize());
  6630. put32 (0);
  6631. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  6632. };
  6633. put32 (1);
  6634. record (1, juce::MemoryBlock (64, true));
  6635. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  6636. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  6637. juce::MemoryBlock slots;
  6638. const auto paramId = [&] (int i) {
  6639. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  6640. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  6641. };
  6642. const bool reorder = plugin->getParameters().size() >= 3;
  6643. if (reorder)
  6644. {
  6645. for (auto v : { 2u, paramId (2), paramId (0) })
  6646. slots.append (&v, 4);
  6647. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  6648. }
  6649. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  6650. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  6651. if (auto* child = xml->getChildByName (tag))
  6652. {
  6653. juce::MemoryBlock data;
  6654. data.fromBase64Encoding (child->getAllSubText());
  6655. record (id, data);
  6656. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  6657. }
  6658. if (reorder)
  6659. record (4, slots);
  6660. plugin.reset();
  6661. auto song = lynx::Song::makeDefault();
  6662. auto& f = song.channels[4].plugin.foreign;
  6663. f.format = lynx::ForeignPlugin::Format::vst3;
  6664. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  6665. f.state = flState;
  6666. {
  6667. std::vector<std::uint8_t> comp, ctrl;
  6668. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  6669. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  6670. }
  6671. for (int k = 0; k < 3; ++k)
  6672. {
  6673. lynx::Automation a;
  6674. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  6675. song.automations.push_back (a);
  6676. }
  6677. const auto adopted = host.adoptFlPlugins (song);
  6678. report << "adopted=" << adopted << "\n";
  6679. juce::String mapped;
  6680. for (const auto& a : song.automations)
  6681. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  6682. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  6683. report << "slot_positions=" << mapped << "\n";
  6684. const auto slotsOk = ! reorder || mapped == "2,0,1";
  6685. offline.setSong (song);
  6686. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  6687. {
  6688. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  6689. report << "restored_value=" << value << "\n";
  6690. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  6691. }
  6692. }
  6693. }
  6694. }
  6695. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  6696. juce::File (reportPath).replaceWithText (report);
  6697. setApplicationReturnValue (ok ? 0 : 1);
  6698. quit();
  6699. }
  6700. void runShowcase (const juce::String& outputPath, int currentPattern)
  6701. {
  6702. using namespace lynx;
  6703. Song song;
  6704. song.bpm = 124.0;
  6705. song.mixer = Song::defaultMixer();
  6706. const auto presets = synthPresets();
  6707. auto preset = [&] (const char* name) {
  6708. for (const auto& [n, sset] : presets)
  6709. if (n == name)
  6710. return sset;
  6711. return SynthSettings {};
  6712. };
  6713. auto channel = [&] (const char* name, InstrumentKind kind, float volume, int track, std::uint32_t colour) {
  6714. ChannelDef c;
  6715. c.name = name;
  6716. c.instrument = kind;
  6717. c.volume = volume;
  6718. c.mixerTrack = track;
  6719. c.colour = colour;
  6720. song.channels.push_back (c);
  6721. return (int) song.channels.size() - 1;
  6722. };
  6723. const auto kick = channel ("Kick", InstrumentKind::kick, 0.9f, 1, 0xffd9534f);
  6724. const auto clap = channel ("Clap", InstrumentKind::clap, 0.75f, 2, 0xfff0ad4e);
  6725. const auto hat = channel ("Hat", InstrumentKind::hat, 0.6f, 3, 0xfff7d774);
  6726. const auto snare = channel ("Snare", InstrumentKind::snare, 0.7f, 4, 0xffe8835a);
  6727. const auto bass = channel ("Reese Bass", InstrumentKind::synth, 0.8f, 5, 0xff5bc0de);
  6728. song.channels[(std::size_t) bass].synth = preset ("Reese Bass"); // preset name as defined in core/SynthPresets
  6729. const auto pad = channel ("Pad", InstrumentKind::synth, 0.7f, 6, 0xff9b7fd6);
  6730. song.channels[(std::size_t) pad].synth = preset ("Pad");
  6731. const auto pluck = channel ("Pluck", InstrumentKind::synth, 0.72f, 7, 0xff5cb85c);
  6732. song.channels[(std::size_t) pluck].synth = preset ("Pluck");
  6733. const auto lead = channel ("Supersaw", InstrumentKind::synth, 0.6f, 8, 0xff4fc3a1);
  6734. song.channels[(std::size_t) lead].synth = preset ("Supersaw");
  6735. auto addPattern = [&] (const char* name, std::uint32_t colour) {
  6736. auto& p = song.patterns.emplace_back();
  6737. p.name = name;
  6738. p.colour = colour;
  6739. return (int) song.patterns.size() - 1;
  6740. };
  6741. auto note = [&] (int pattern, int ch, double beat, double beats, int key, float velocity = 0.8f) {
  6742. Note n;
  6743. n.channel = ch;
  6744. n.start = (std::int64_t) (beat * ppq);
  6745. n.length = (std::int64_t) (beats * ppq);
  6746. n.key = key;
  6747. n.velocity = velocity;
  6748. song.patterns[(std::size_t) pattern].notes.push_back (n);
  6749. };
  6750. const auto beat = addPattern ("Beat", 0xffd9534f);
  6751. for (int s = 0; s < 16; s += 4)
  6752. song.patterns[(std::size_t) beat].toggleStep (kick, s);
  6753. for (int s : { 4, 12 })
  6754. song.patterns[(std::size_t) beat].toggleStep (clap, s);
  6755. for (int s = 2; s < 16; s += 4)
  6756. song.patterns[(std::size_t) beat].toggleStep (hat, s);
  6757. for (int s : { 7, 15 })
  6758. song.patterns[(std::size_t) beat].toggleStep (snare, s);
  6759. const auto groove = addPattern ("Groove", 0xfff0ad4e);
  6760. for (int s = 0; s < 16; ++s)
  6761. song.patterns[(std::size_t) groove].toggleStep (hat, s);
  6762. for (int s : { 4, 12 })
  6763. song.patterns[(std::size_t) groove].toggleStep (clap, s);
  6764. // Am – F – C – G, one bar each
  6765. const int roots[4] = { 45, 41, 48, 43 };
  6766. const int chords[4][3] = { { 57, 60, 64 }, { 53, 57, 60 }, { 55, 60, 64 }, { 55, 59, 62 } };
  6767. const auto bassline = addPattern ("Bass", 0xff5bc0de);
  6768. for (int bar = 0; bar < 4; ++bar)
  6769. for (int e = 0; e < 8; ++e)
  6770. if (e != 3)
  6771. note (bassline, bass, bar * 4 + e * 0.5, 0.4, roots[bar] - 12 + (e == 6 ? 12 : 0), e % 2 == 0 ? 0.9f : 0.65f);
  6772. const auto chordsPattern = addPattern ("Chords", 0xff9b7fd6);
  6773. for (int bar = 0; bar < 4; ++bar)
  6774. for (int k = 0; k < 3; ++k)
  6775. note (chordsPattern, pad, bar * 4, 3.9, chords[bar][k], 0.7f);
  6776. const auto melody = addPattern ("Melody", 0xff5cb85c);
  6777. const int line[] = { 69, 72, 76, 74, 72, 69, 67, 69, 65, 69, 72, 74, 72, 69, 67, 64,
  6778. 72, 76, 79, 76, 74, 72, 74, 76, 71, 74, 79, 78, 76, 74, 71, 67 };
  6779. for (int k = 0; k < 32; ++k)
  6780. if (k % 8 != 7)
  6781. note (melody, pluck, k * 0.5, k % 4 == 3 ? 0.9 : 0.4, line[k], k % 2 == 0 ? 0.85f : 0.65f);
  6782. const auto hook = addPattern ("Hook", 0xff4fc3a1);
  6783. for (int bar = 0; bar < 4; ++bar)
  6784. for (int k = 0; k < 3; ++k)
  6785. note (hook, lead, bar * 4 + k * 1.5, k == 2 ? 1.0 : 1.4, chords[bar][2] + 12 - k * 3, 0.8f);
  6786. // Playlist: intro, verse, drop, breakdown, final drop
  6787. song.playlistTracks = { { "Drums" }, { "Groove" }, { "Bass" }, { "Chords" }, { "Melody" }, { "Hook" }, { "Automation" } };
  6788. const auto bar = (std::int64_t) ppq * 4;
  6789. auto clip = [&] (int pattern, int track, int fromBar, int bars) {
  6790. const auto length = song.patterns[(std::size_t) pattern].effectiveLength (song.beatsPerBar);
  6791. for (int b = fromBar; b < fromBar + bars;)
  6792. {
  6793. Clip c;
  6794. c.pattern = pattern;
  6795. c.track = track;
  6796. c.start = b * bar;
  6797. c.length = length;
  6798. song.playlist.push_back (c);
  6799. b += (int) std::max<std::int64_t> (1, length / bar);
  6800. }
  6801. };
  6802. clip (chordsPattern, 3, 0, 8);
  6803. clip (melody, 4, 4, 4);
  6804. clip (beat, 0, 8, 16);
  6805. clip (groove, 1, 12, 12);
  6806. clip (bassline, 2, 8, 8);
  6807. clip (melody, 4, 8, 8);
  6808. clip (chordsPattern, 3, 16, 4);
  6809. clip (bassline, 2, 20, 4);
  6810. clip (hook, 5, 20, 4);
  6811. clip (melody, 4, 20, 4);
  6812. song.addMarker ({ 0, "Intro" });
  6813. song.addMarker ({ 8 * bar, "Drop" });
  6814. song.addMarker ({ 16 * bar, "Breakdown" });
  6815. song.addMarker ({ 20 * bar, "Final" });
  6816. // automation: the pad volume opens up during the intro
  6817. Automation a;
  6818. a.name = "Pad Volume";
  6819. a.target = { AutomationTargetKind::mixerVolume, 6, 0, 0 };
  6820. a.points = { { 0, 0.15f, 0.4f }, { 8 * bar, 0.8f, 0.0f } };
  6821. song.automations.push_back (a);
  6822. Clip ac;
  6823. ac.kind = ClipKind::automation;
  6824. ac.automation = 0;
  6825. ac.track = 6;
  6826. ac.start = 0;
  6827. ac.length = 8 * bar;
  6828. song.playlist.push_back (ac);
  6829. // mixer: names, colours and effects (bass compressor sidechained to the kick)
  6830. const char* names[] = { "Master", "Kick", "Clap", "Hat", "Snare", "Bass", "Pad", "Pluck", "Lead" };
  6831. for (int t = 0; t < 9; ++t)
  6832. {
  6833. song.mixer[(std::size_t) t].name = names[t];
  6834. if (t > 0)
  6835. song.mixer[(std::size_t) t].colour = song.channels[(std::size_t) t - 1].colour;
  6836. }
  6837. auto fx = [&] (int track, EffectKind kind) -> EffectSlot& {
  6838. song.mixer[(std::size_t) track].effects.push_back (makeEffectSlot (kind));
  6839. return song.mixer[(std::size_t) track].effects.back();
  6840. };
  6841. {
  6842. // kick EQ: cut below 30 Hz, weight at 60 Hz, remove the "boxiness" at 350 Hz, brightness at 4 kHz
  6843. auto& eq = fx (1, EffectKind::parametricEq);
  6844. auto band = [&] (int b, peq::BandType type, double hz, double db, double q) {
  6845. eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (type);
  6846. eq.params[(std::size_t) peq::param (b, 1)] = peq::hzValue (hz);
  6847. eq.params[(std::size_t) peq::param (b, 2)] = peq::gainValue (db);
  6848. eq.params[(std::size_t) peq::param (b, 3)] = peq::qValue (q);
  6849. };
  6850. band (0, peq::BandType::lowCut, 30.0, 0.0, 0.7);
  6851. band (1, peq::BandType::peak, 62.0, 5.0, 1.2);
  6852. band (2, peq::BandType::peak, 350.0, -6.0, 2.0);
  6853. band (3, peq::BandType::peak, 4200.0, 3.5, 1.5);
  6854. band (4, peq::BandType::highCut, 14000.0, 0.0, 0.7);
  6855. for (int b = 5; b < peq::bands; ++b)
  6856. eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (peq::BandType::off);
  6857. }
  6858. fx (1, EffectKind::distortion).mix = 0.3f;
  6859. auto& comp = fx (5, EffectKind::compressor);
  6860. comp.params[0] = 0.55f;
  6861. comp.params[1] = 0.8f;
  6862. comp.sidechain = 1;
  6863. fx (5, EffectKind::parametricEq);
  6864. fx (6, EffectKind::chorus);
  6865. fx (6, EffectKind::reverb);
  6866. fx (7, EffectKind::delay);
  6867. fx (7, EffectKind::reverb).mix = 0.4f;
  6868. fx (8, EffectKind::effector);
  6869. fx (8, EffectKind::delay);
  6870. fx (0, EffectKind::parametricEq);
  6871. auto& limiter = fx (0, EffectKind::limiter);
  6872. limiter.params = { 11.7f / 12.0f, 0.1f, 0.5f };
  6873. song.mixer[1].volume = 0.78f;
  6874. song.mixer[5].volume = 0.72f;
  6875. song.mixer[6].volume = 0.6f;
  6876. song.mixer[6].pan = -0.2f;
  6877. song.mixer[7].pan = 0.25f;
  6878. song.mode = PlayMode::song;
  6879. song.currentPattern = std::clamp (currentPattern, 0, (int) song.patterns.size() - 1);
  6880. juce::String error;
  6881. const auto ok = ProjectFile::save (song, juce::File (outputPath), error);
  6882. setApplicationReturnValue (ok ? 0 : 1);
  6883. quit();
  6884. }
  6885. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  6886. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  6887. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  6888. // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
  6889. struct TestVoice
  6890. {
  6891. explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
  6892. {
  6893. if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
  6894. instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
  6895. else
  6896. effect = std::move (p);
  6897. }
  6898. void noteOn()
  6899. {
  6900. if (instrument != nullptr)
  6901. instrument->noteOn (60, 0.9f);
  6902. }
  6903. void render (float* l, float* r, int n, float gainLeft, float gainRight)
  6904. {
  6905. if (instrument != nullptr)
  6906. {
  6907. instrument->render (l, r, n, gainLeft, gainRight);
  6908. return;
  6909. }
  6910. const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
  6911. juce::AudioBuffer<float> block (channels, 512);
  6912. juce::MidiBuffer midi;
  6913. for (int done = 0; done < n; done += 512)
  6914. {
  6915. const auto k = juce::jmin (512, n - done);
  6916. block.setSize (channels, k, false, false, true);
  6917. for (int i = 0; i < k; ++i)
  6918. {
  6919. const auto v = 0.25f * (float) std::sin (phase);
  6920. phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
  6921. for (int c = 0; c < channels; ++c)
  6922. block.setSample (c, i, v);
  6923. }
  6924. effect->processBlock (block, midi);
  6925. for (int i = 0; i < k; ++i)
  6926. {
  6927. l[done + i] += gainLeft * block.getSample (0, i);
  6928. r[done + i] += gainRight * block.getSample (1, i);
  6929. }
  6930. }
  6931. }
  6932. std::unique_ptr<lynx::PluginInstrument> instrument;
  6933. std::unique_ptr<juce::AudioPluginInstance> effect;
  6934. double phase = 0.0;
  6935. };
  6936. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  6937. {
  6938. juce::String report;
  6939. bool ok = false;
  6940. lynx::setPluginSandboxAlerts (false);
  6941. const juce::File log (reportPath + ".log");
  6942. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  6943. log.deleteFile();
  6944. {
  6945. lynx::PluginHost host (false);
  6946. host.addPluginFile (juce::File (pluginPath));
  6947. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  6948. // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
  6949. const juce::PluginDescription* instrument = nullptr;
  6950. for (const auto& type : types)
  6951. if (type.isInstrument)
  6952. instrument = &type;
  6953. for (const auto& type : types)
  6954. if (instrument == nullptr && ! type.isInstrument)
  6955. instrument = &type;
  6956. step ("host");
  6957. juce::String error;
  6958. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  6959. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  6960. step ("created");
  6961. if (remote != nullptr)
  6962. {
  6963. auto& proxy = *remote;
  6964. TestVoice voice (std::move (remote));
  6965. std::vector<float> l (48000), r (48000);
  6966. auto peakOf = [&] {
  6967. float peak = 0.0f;
  6968. for (std::size_t k = 0; k < l.size(); ++k)
  6969. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  6970. return peak;
  6971. };
  6972. const auto start = juce::Time::getMillisecondCounterHiRes();
  6973. voice.noteOn();
  6974. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  6975. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  6976. const auto peak = peakOf();
  6977. step ("played");
  6978. if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
  6979. {
  6980. // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
  6981. const auto dead = lynx::isSandboxedPluginDead (proxy);
  6982. std::fill (l.begin(), l.end(), 0.0f);
  6983. std::fill (r.begin(), r.end(), 0.0f);
  6984. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  6985. report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  6986. ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
  6987. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  6988. juce::File (reportPath).replaceWithText (report);
  6989. setApplicationReturnValue (ok ? 0 : 1);
  6990. quit();
  6991. return;
  6992. }
  6993. report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
  6994. << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  6995. if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
  6996. {
  6997. // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
  6998. std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
  6999. juce::Thread::sleep (4000);
  7000. juce::MemoryBlock state;
  7001. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  7002. proxy.getStateInformation (state);
  7003. report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
  7004. editor.reset();
  7005. }
  7006. // parameter -> state -> in-process plugin
  7007. bool stateOk = false;
  7008. if (! proxy.getParameters().isEmpty())
  7009. {
  7010. auto* p = proxy.getParameters()[0];
  7011. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  7012. p->setValue (target);
  7013. std::fill (l.begin(), l.end(), 0.0f);
  7014. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  7015. juce::MemoryBlock state;
  7016. proxy.getStateInformation (state);
  7017. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  7018. {
  7019. local->setStateInformation (state.getData(), (int) state.getSize());
  7020. const auto back = local->getParameters()[0]->getValue();
  7021. // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
  7022. auto control = target;
  7023. if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  7024. {
  7025. a->enableAllBuses();
  7026. a->prepareToPlay (48000.0, 512);
  7027. a->getParameters()[0]->setValue (target);
  7028. juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
  7029. block.clear();
  7030. juce::MidiBuffer none;
  7031. a->processBlock (block, none);
  7032. juce::MemoryBlock direct;
  7033. a->getStateInformation (direct);
  7034. if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  7035. {
  7036. b->setStateInformation (direct.getData(), (int) direct.getSize());
  7037. control = b->getParameters()[0]->getValue();
  7038. }
  7039. a->releaseResources();
  7040. }
  7041. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
  7042. stateOk = std::abs (back - control) < 0.02f;
  7043. }
  7044. }
  7045. step ("state");
  7046. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  7047. lynx::hangSandboxedPluginForTest (proxy);
  7048. juce::Thread::sleep (200);
  7049. std::fill (l.begin(), l.end(), 1.0f);
  7050. std::fill (r.begin(), r.end(), 1.0f);
  7051. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  7052. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  7053. std::fill (l.begin(), l.end(), 0.0f);
  7054. std::fill (r.begin(), r.end(), 0.0f);
  7055. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  7056. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  7057. const auto dead = lynx::isSandboxedPluginDead (proxy);
  7058. const auto hangPeak = peakOf();
  7059. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
  7060. // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
  7061. bool crashOk = false;
  7062. if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
  7063. {
  7064. auto& proxy2 = *second;
  7065. TestVoice voice2 (std::move (second));
  7066. voice2.noteOn();
  7067. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  7068. lynx::crashSandboxedPluginForTest (proxy2);
  7069. const auto crashStart = juce::Time::getMillisecondCounterHiRes();
  7070. while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
  7071. {
  7072. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  7073. juce::Thread::sleep (5);
  7074. }
  7075. const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
  7076. std::fill (l.begin(), l.end(), 0.0f);
  7077. std::fill (r.begin(), r.end(), 0.0f);
  7078. voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  7079. const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
  7080. report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
  7081. crashOk = crashDead && crashMs < 3000.0;
  7082. }
  7083. step ("crash");
  7084. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
  7085. }
  7086. }
  7087. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  7088. juce::File (reportPath).replaceWithText (report);
  7089. setApplicationReturnValue (ok ? 0 : 1);
  7090. quit();
  7091. }
  7092. // --timertest (round 174f): a view's polling timer follows the view and its parents, and survives a minimised window
  7093. void runTimerTest (const juce::File& report)
  7094. {
  7095. struct Ticks final : juce::Timer
  7096. {
  7097. void timerCallback() override {}
  7098. } timer;
  7099. juce::Component top, parent, view;
  7100. parent.addChildComponent (view);
  7101. top.addChildComponent (parent);
  7102. top.setSize (320, 200);
  7103. lynx::ui::TimerWhileShowing watch (view, timer, 30);
  7104. juce::String text;
  7105. auto failures = 0;
  7106. auto expect = [&] (const char* step, bool running) {
  7107. const auto ok = timer.isTimerRunning() == running;
  7108. failures += ok ? 0 : 1;
  7109. text << step << ": timer " << (timer.isTimerRunning() ? "running" : "stopped") << (ok ? "" : " FAIL") << "\n";
  7110. };
  7111. expect ("never shown", false);
  7112. view.setVisible (true);
  7113. parent.setVisible (true);
  7114. expect ("view and parent visible, not on the desktop", false);
  7115. top.addToDesktop (juce::ComponentPeer::windowHasTitleBar);
  7116. top.setVisible (true);
  7117. expect ("window shown", true);
  7118. parent.setVisible (false);
  7119. expect ("parent hidden", false);
  7120. parent.setVisible (true);
  7121. expect ("parent shown", true);
  7122. view.setVisible (false);
  7123. expect ("view hidden", false);
  7124. top.getPeer()->setMinimised (true);
  7125. view.setVisible (true);
  7126. expect ("view shown while minimised", true);
  7127. top.getPeer()->setMinimised (false);
  7128. expect ("window restored", true);
  7129. top.setVisible (false);
  7130. expect ("window hidden", false);
  7131. top.setVisible (true);
  7132. expect ("window shown again", true);
  7133. top.removeFromDesktop();
  7134. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  7135. report.replaceWithText (text);
  7136. setApplicationReturnValue (failures == 0 ? 0 : 1);
  7137. quit();
  7138. }
  7139. // --cachetest (round 174f): PlaylistComponent::cacheSelfTest on the project, the Playlist off screen at 1466 x 930
  7140. void runCacheTest (const juce::File& project, const juce::File& report)
  7141. {
  7142. engine = std::make_unique<lynx::AudioEngine>();
  7143. juce::String error;
  7144. auto ok = false;
  7145. if (project.hasFileExtension ("flp"))
  7146. ok = engine->importFlpFile (project, error);
  7147. else if (auto song = lynx::ProjectFile::load (project, error))
  7148. {
  7149. engine->setSong (std::move (*song));
  7150. ok = true;
  7151. }
  7152. juce::String text = "project: " + project.getFullPathName() + "\n";
  7153. if (ok)
  7154. {
  7155. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  7156. playlist->setBounds (0, 0, 1466, 930);
  7157. playlist->setVisible (true);
  7158. text << playlist->cacheSelfTest ([] { lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000); }, report.getParentDirectory());
  7159. }
  7160. else
  7161. text << "result=ERROR " << error << "\n";
  7162. report.replaceWithText (text);
  7163. setApplicationReturnValue (ok && text.contains ("result=OK") ? 0 : 1);
  7164. quit();
  7165. }
  7166. // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
  7167. // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
  7168. // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
  7169. // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
  7170. // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
  7171. // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
  7172. void runUiPerf (const juce::File& project, const juce::File& report)
  7173. {
  7174. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  7175. lynx::crashguard::startMainProfiler (profile.toStdString()); // (stopped in shutdown)
  7176. startupOptions = lynx::StartupOptions::load();
  7177. engine = std::make_unique<lynx::AudioEngine>();
  7178. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  7179. crashEngine = engine.get();
  7180. createMainWindow();
  7181. mainWindow->reveal();
  7182. // LYNX_UIPERF_SIZE=WxH, LYNX_UIPERF_SCALE=<percent> (round 179a): a large window, a HiDPI desktop's scale
  7183. if (const auto scale = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SCALE", {}).getIntValue(); scale > 0)
  7184. juce::Desktop::getInstance().setGlobalScaleFactor ((float) scale / 100.0f);
  7185. if (const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SIZE", {}), "x", ""); size.size() == 2)
  7186. mainWindow->setBounds (0, 0, size[0].getIntValue(), size[1].getIntValue());
  7187. juce::String error;
  7188. auto ok = false;
  7189. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  7190. if (project.hasFileExtension ("flp"))
  7191. ok = engine->importFlpFile (project, error);
  7192. else if (auto song = lynx::ProjectFile::load (project, error))
  7193. {
  7194. engine->setSong (std::move (*song));
  7195. ok = true;
  7196. }
  7197. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  7198. if (! ok)
  7199. {
  7200. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  7201. setApplicationReturnValue (1);
  7202. quit();
  7203. return;
  7204. }
  7205. // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
  7206. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
  7207. engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
  7208. struct Step
  7209. {
  7210. juce::String name;
  7211. std::function<void()> setup;
  7212. std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
  7213. int frames;
  7214. std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
  7215. };
  7216. struct UiPerf final : juce::Timer
  7217. {
  7218. LynxApplication& app;
  7219. juce::File report;
  7220. juce::String text;
  7221. std::vector<Step> steps;
  7222. std::size_t step = 0;
  7223. int frame = -1;
  7224. std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
  7225. std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
  7226. double setupMs = 0.0, wallStart = 0.0;
  7227. double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
  7228. double messageCpuStart = 0.0; // the message thread's CPU seconds
  7229. double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
  7230. int audioLoadTicks = 0;
  7231. UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r)) {}
  7232. juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
  7233. double paintNow() const
  7234. {
  7235. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  7236. if (auto* p = peer())
  7237. p->performAnyPendingRepaintsNow();
  7238. return juce::Time::getMillisecondCounterHiRes() - t0;
  7239. }
  7240. void timerCallback() override
  7241. {
  7242. if (step >= steps.size())
  7243. {
  7244. stopTimer();
  7245. finish();
  7246. return;
  7247. }
  7248. auto& s = steps[step];
  7249. if (frame < 0)
  7250. {
  7251. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  7252. if (s.setup)
  7253. s.setup();
  7254. paintNow();
  7255. setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
  7256. times.clear();
  7257. rendered.clear();
  7258. frames.clear();
  7259. wallStart = juce::Time::getMillisecondCounterHiRes();
  7260. cpuStart = lynx::processCpuSeconds();
  7261. messageCpuStart = lynx::threadCpuSeconds();
  7262. audioLoadSum = 0.0;
  7263. audioLoadTicks = 0;
  7264. frame = 0;
  7265. return;
  7266. }
  7267. audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
  7268. ++audioLoadTicks;
  7269. if (s.action)
  7270. s.action (frame);
  7271. if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
  7272. times.push_back (ms);
  7273. ++frame;
  7274. if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
  7275. return;
  7276. const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
  7277. const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
  7278. const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
  7279. text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
  7280. << " painted frames: " << stats (rendered) << "\n"
  7281. << " timed here (event + paint + blit): " << stats (times)
  7282. << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
  7283. << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
  7284. << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
  7285. << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
  7286. if (s.finish)
  7287. text << s.finish();
  7288. juce::File (report).replaceWithText (text);
  7289. ++step;
  7290. frame = -1;
  7291. }
  7292. static juce::String stats (std::vector<double> sorted)
  7293. {
  7294. std::sort (sorted.begin(), sorted.end());
  7295. 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()))]; };
  7296. double sum = 0.0;
  7297. int over = 0;
  7298. for (auto t : sorted)
  7299. {
  7300. sum += t;
  7301. over += t > 16.0 ? 1 : 0;
  7302. }
  7303. return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
  7304. + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
  7305. + " ms, >16 ms " + juce::String (over);
  7306. }
  7307. void finish()
  7308. {
  7309. // the cost of asking where the mouse is (X11: a round trip to the display server)
  7310. const auto q0 = juce::Time::getMillisecondCounterHiRes();
  7311. for (int i = 0; i < 100; ++i)
  7312. juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
  7313. text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
  7314. app.mainWindow->onFrame = nullptr;
  7315. app.mainWindow->watchFrames ({});
  7316. app.engine->stop();
  7317. text << "result=OK\n";
  7318. report.replaceWithText (text);
  7319. app.setApplicationReturnValue (0);
  7320. app.quit();
  7321. }
  7322. };
  7323. auto* ui = &mainWindow->getContent();
  7324. auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
  7325. auto* peer = mainWindow->getPeer();
  7326. if (peer == nullptr || ! target.isShowing())
  7327. return;
  7328. juce::ModifierKeys::currentModifiers = mods;
  7329. const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
  7330. juce::MouseWheelDetails wheel { dx, dy, false, false, false };
  7331. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  7332. juce::ModifierKeys::currentModifiers = {};
  7333. };
  7334. auto run = std::make_unique<UiPerf> (*this, report);
  7335. mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
  7336. // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
  7337. auto drag = std::make_shared<UiPerfDrag>();
  7338. mainWindow->watchFrames ([r = run.get(), drag] (double now, juce::Rectangle<int> area) {
  7339. if (r->frame >= 0)
  7340. r->frames.push_back (now);
  7341. drag->framePainted (now, area);
  7342. });
  7343. run->text << "project: " << project.getFullPathName() << "\n"
  7344. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  7345. << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
  7346. << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  7347. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
  7348. << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
  7349. << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
  7350. const auto none = juce::ModifierKeys();
  7351. // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
  7352. // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
  7353. // window's own mouse path, the frames painted as the window paints them)
  7354. const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
  7355. run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
  7356. ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  7357. engine->getTransport().songMode = false;
  7358. engine->rewind();
  7359. engine->play();
  7360. }, {}, 4000 });
  7361. run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
  7362. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  7363. const auto rail = strips.faderRailForSnapshot (dragTrack);
  7364. drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
  7365. }, {}, 3000, [drag] { return drag->stop(); } });
  7366. run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
  7367. run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
  7368. run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
  7369. run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
  7370. // round 177a: only the meters move, so the strips' picture must stay valid, also with a folded group's tab and VCA
  7371. // strips on screen (their levels are drawn over the picture, like the inserts' meters)
  7372. run->steps.push_back ({ "mixer meters over the picture, playing", [this, ui] {
  7373. ui->selectTabForSnapshot (3);
  7374. engine->getTransport().songMode = false;
  7375. engine->rewind();
  7376. engine->play();
  7377. ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  7378. }, {}, 6000, [this, ui, report] {
  7379. const auto [spoiled, refills] = ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  7380. if (juce::FileOutputStream out (report.withFileExtension ("png")); out.openedOk())
  7381. {
  7382. out.setPosition (0);
  7383. out.truncate();
  7384. juce::PNGImageFormat().writeImageToStream (mainWindow->createComponentSnapshot (mainWindow->getLocalBounds()), out);
  7385. }
  7386. return juce::String (" mixer picture: spoiled ") + juce::String (spoiled) + " times, drawn again " + juce::String (refills) + " times\n";
  7387. } });
  7388. run->steps.push_back ({ "mixer scroll", {}, [wheelAt, ui, none] (int f) { wheelAt (ui->getMixerForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  7389. // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
  7390. // through the old path (a whole snapshot per move) and through editLevels
  7391. auto faderMove = [this] (bool levels, int f) {
  7392. for (int k = 0; k < 4; ++k)
  7393. {
  7394. const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
  7395. const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
  7396. if (levels)
  7397. engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
  7398. else
  7399. engine->editSong (edit, false);
  7400. }
  7401. };
  7402. run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
  7403. run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
  7404. // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
  7405. // loading while it stays open, pointing at the tiles, then closing it
  7406. run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
  7407. run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
  7408. // (round 175b: the picker is its own window)
  7409. if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
  7410. {
  7411. const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
  7412. 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
  7413. const auto local = picker->getPeer()->globalToLocal (p.toFloat());
  7414. picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
  7415. juce::Time::currentTimeMillis());
  7416. }
  7417. }, 60 });
  7418. run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
  7419. run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
  7420. run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
  7421. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  7422. run->steps.push_back ({ "playlist scroll sideways", {},
  7423. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  7424. // round 174f: Ctrl+wheel zoom, a notch every third frame (~20 a second), three in then three out, as dupmon drives it
  7425. run->steps.push_back ({ "playlist zoom (Ctrl+wheel)", {},
  7426. [wheelAt, ui] (int f) {
  7427. if (f % 3 == 0)
  7428. wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, juce::ModifierKeys (juce::ModifierKeys::ctrlModifier));
  7429. }, 120 });
  7430. run->steps.push_back ({ "playlist after the zoom (settles)", {}, {}, 500 });
  7431. run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
  7432. run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
  7433. [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  7434. // LYNX_UIPERF_ONLY=text: only the steps whose name has that text
  7435. if (const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_ONLY", {}); only.isNotEmpty())
  7436. run->steps.erase (std::remove_if (run->steps.begin(), run->steps.end(), [&only] (const auto& s) { return ! juce::String (s.name).contains (only); }), run->steps.end());
  7437. // let the window draw the project first
  7438. perf = std::move (run);
  7439. juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
  7440. }
  7441. // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
  7442. // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
  7443. // --rtstress --backuptest N (round 177d): while the project plays, a device's MIDI clock (10/s) and active sensing
  7444. // (3/s) arrive, and the project counts as changed. N > 0 also forces a backup every N seconds on top of the timed ones.
  7445. // The report tells how many backups were written, when, and what the MIDI counters did.
  7446. struct BackupTest final : juce::Timer
  7447. {
  7448. lynx::AudioEngine* engine = nullptr;
  7449. lynx::MainComponent* ui = nullptr;
  7450. double everyMs = 0.0, startMs = 0.0, lastForcedMs = 0.0, longestCallMs = 0.0;
  7451. int ticks = 0, forced = 0;
  7452. std::uint64_t seenOver = 0, seenNear = 0;
  7453. juce::String misses; // each callback over (or near) its deadline: how long after the last forced backup
  7454. void timerCallback() override
  7455. {
  7456. engine->injectMidiInput (juce::MidiMessage (0xf8));
  7457. if (++ticks % 3 == 0)
  7458. engine->injectMidiInput (juce::MidiMessage (0xfe));
  7459. const auto now = juce::Time::getMillisecondCounterHiRes();
  7460. const auto s = engine->getRtStats().snapshot();
  7461. if (s.overBudget != seenOver || s.nearBudget != seenNear)
  7462. {
  7463. misses << " +" << juce::String ((now - lastForcedMs) / 1000.0, 1) << " s after the last forced backup (or the start): over +"
  7464. << (juce::int64) (s.overBudget - seenOver) << ", near +" << (juce::int64) (s.nearBudget - seenNear) << "\n";
  7465. seenOver = s.overBudget;
  7466. seenNear = s.nearBudget;
  7467. }
  7468. if (everyMs > 0.0 && now - lastForcedMs >= everyMs)
  7469. {
  7470. lastForcedMs = now;
  7471. ++forced;
  7472. ui->backupNowForTest();
  7473. longestCallMs = juce::jmax (longestCallMs, juce::Time::getMillisecondCounterHiRes() - now);
  7474. }
  7475. }
  7476. };
  7477. std::unique_ptr<BackupTest> backupTest;
  7478. void startBackupTest()
  7479. {
  7480. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  7481. const auto at = cli.indexOf ("--backuptest");
  7482. auto* ui = mainWindow != nullptr ? dynamic_cast<lynx::MainComponent*> (mainWindow->getContentComponent()) : nullptr;
  7483. if (at < 0 || ui == nullptr)
  7484. return;
  7485. backupTest = std::make_unique<BackupTest>();
  7486. backupTest->engine = engine.get();
  7487. backupTest->ui = ui;
  7488. backupTest->everyMs = cli[at + 1].getDoubleValue() * 1000.0;
  7489. backupTest->startMs = backupTest->lastForcedMs = juce::Time::getMillisecondCounterHiRes();
  7490. // (the project counts as changed, so a backup has something to write; the Master's fader is down, so a long run
  7491. // makes no sound: everything else is processed as usual)
  7492. engine->editSong ([] (lynx::Song& s) {
  7493. if (! s.mixer.empty())
  7494. s.mixer[0].volume = 0.0f;
  7495. });
  7496. backupTest->startTimer (100);
  7497. }
  7498. juce::String finishBackupTest()
  7499. {
  7500. if (backupTest == nullptr)
  7501. return {};
  7502. backupTest->stopTimer();
  7503. juce::String text;
  7504. const auto played = engine->getMidiPlayed();
  7505. text << " backup test: MIDI light count " << (int) engine->getMidiActivity() << ", played count " << (int) played << " (clock and active sensing only)\n";
  7506. text << " backup test: " << backupTest->forced << " forced, longest forced call on the message thread "
  7507. << juce::String (backupTest->longestCallMs, 1) << " ms\n";
  7508. if (backupTest->misses.isNotEmpty())
  7509. text << " backup test: callbacks over or near the deadline (seen within 100 ms):\n" << backupTest->misses;
  7510. auto files = lynx::autosaveFolder().findChildFiles (juce::File::findFiles, false, "*.lynx");
  7511. text << " backup test: " << files.size() << " file(s) in the backup folder:\n";
  7512. for (const auto& f : files)
  7513. text << " " << juce::String ((f.getLastModificationTime().toMilliseconds() - juce::Time::getCurrentTime().toMilliseconds()) / 1000) << " s before the end: "
  7514. << f.getFileName() << " (" << f.getSize() << " bytes)\n";
  7515. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 1));
  7516. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  7517. text << " backup test: after a played note, played count " << (int) engine->getMidiPlayed() << "\n";
  7518. backupTest.reset();
  7519. return text;
  7520. }
  7521. void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
  7522. const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
  7523. {
  7524. startupOptions = lynx::StartupOptions::load();
  7525. engine = std::make_unique<lynx::AudioEngine>();
  7526. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  7527. crashEngine = engine.get();
  7528. // the user's saved device stays as it was: this run's choices are undone before quitting
  7529. savedDeviceState = engine->getDeviceManager().createStateXml();
  7530. auto& devices = engine->getDeviceManager();
  7531. const auto driverFile = addDriverFileDeviceType();
  7532. const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
  7533. if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
  7534. devices.setCurrentAudioDeviceType (type, true);
  7535. if (bufferSize > 0 || deviceName.isNotEmpty())
  7536. {
  7537. auto setup = devices.getAudioDeviceSetup();
  7538. if (bufferSize > 0)
  7539. setup.bufferSize = bufferSize;
  7540. if (deviceName.isNotEmpty())
  7541. setup.outputDeviceName = deviceName;
  7542. const auto error = devices.setAudioDeviceSetup (setup, true);
  7543. if (error.isNotEmpty())
  7544. report.replaceWithText ("device error: " + error + "\n");
  7545. }
  7546. createMainWindow();
  7547. if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
  7548. mainWindow->reveal();
  7549. juce::String error;
  7550. auto ok = false;
  7551. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  7552. if (project.hasFileExtension ("flp"))
  7553. ok = engine->importFlpFile (project, error);
  7554. else if (auto song = lynx::ProjectFile::load (project, error))
  7555. {
  7556. engine->setSong (std::move (*song));
  7557. ok = true;
  7558. }
  7559. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  7560. if (! ok)
  7561. {
  7562. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  7563. restoreSavedDeviceState();
  7564. setApplicationReturnValue (1);
  7565. quit();
  7566. return;
  7567. }
  7568. if (recordTo.isNotEmpty())
  7569. engine->setAudioRecordingArmed (true); // opens the input of the driver
  7570. // let the window draw the project, then play from the start with fresh statistics
  7571. juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
  7572. if (engine == nullptr)
  7573. return;
  7574. engine->stop();
  7575. engine->rewind();
  7576. engine->getRtStats().reset();
  7577. engine->takeUiPulse();
  7578. if (recordTo.isNotEmpty())
  7579. engine->setRecording (true);
  7580. // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
  7581. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  7582. if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
  7583. engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
  7584. ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
  7585. engine->play();
  7586. startBackupTest();
  7587. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
  7588. if (engine == nullptr)
  7589. return;
  7590. const auto backupReport = finishBackupTest();
  7591. engine->stop();
  7592. juce::String recording;
  7593. if (engine->getAudioLogger().isLogging())
  7594. {
  7595. recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
  7596. engine->getAudioLogger().stop();
  7597. }
  7598. if (recordTo.isNotEmpty())
  7599. recording = finishStressTake (juce::File (recordTo), seconds);
  7600. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  7601. const auto s = engine->getRtStats().snapshot();
  7602. juce::String text;
  7603. text << "project: " << project.getFullPathName() << "\n"
  7604. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  7605. << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
  7606. << juce::SystemStats::getCpuModel() << "\n"
  7607. << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
  7608. << engine->describeRealtime();
  7609. const auto pulse = engine->takeUiPulse();
  7610. text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
  7611. << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
  7612. text << " load histogram (share of the deadline: callbacks):";
  7613. for (std::size_t b = 0; b < s.histogram.size(); ++b)
  7614. if (s.histogram[b] > 0)
  7615. text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
  7616. text << "\n";
  7617. text << recording << backupReport;
  7618. // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
  7619. if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
  7620. {
  7621. auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
  7622. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  7623. {
  7624. juce::Graphics g (image);
  7625. g.fillAll (lynx::theme::panel);
  7626. page->paintEntireComponent (g, false);
  7627. }
  7628. const juce::File shot (cli[at + 1].unquoted());
  7629. shot.deleteFile();
  7630. if (auto out = shot.createOutputStream())
  7631. juce::PNGImageFormat().writeImageToStream (image, *out);
  7632. }
  7633. text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
  7634. report.replaceWithText (text);
  7635. restoreSavedDeviceState();
  7636. setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
  7637. quit();
  7638. });
  7639. });
  7640. }
  7641. // --bendrectest (round 167a): see the command line above
  7642. void runBendRecordTest (const juce::File& report, bool songMode)
  7643. {
  7644. engine = std::make_unique<lynx::AudioEngine>();
  7645. auto text = std::make_shared<juce::String>();
  7646. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  7647. auto finish = [this] (int code) {
  7648. setApplicationReturnValue (code);
  7649. quit();
  7650. };
  7651. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  7652. if (device == nullptr)
  7653. {
  7654. step ("result=ERROR no audio device");
  7655. finish (1);
  7656. return;
  7657. }
  7658. step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
  7659. auto song = lynx::Song::makeDefault();
  7660. song.bpm = 120.0;
  7661. song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
  7662. engine->setSong (std::move (song));
  7663. auto o = engine->getRecordOptions();
  7664. o.mode = lynx::RecordMode::overdub;
  7665. o.recordNotes = true;
  7666. o.recordAutomation = true;
  7667. o.countInBars = 0;
  7668. o.waitForInput = false;
  7669. o.quantiseAutomation = false;
  7670. o.punchLoopRegion = false;
  7671. o.preRollBars = o.postRollBars = 0;
  7672. engine->setRecordOptions (o);
  7673. engine->stop();
  7674. engine->rewind();
  7675. engine->setRecording (true);
  7676. engine->startPlayback();
  7677. // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
  7678. auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
  7679. auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
  7680. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
  7681. auto tick = std::make_shared<std::function<void()>>();
  7682. *tick = [this, sent, t0, tick, step, finish, songMode] {
  7683. if (engine == nullptr)
  7684. return;
  7685. const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
  7686. if (ms < 2000.0)
  7687. {
  7688. const auto x = ms / 1000.0;
  7689. 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);
  7690. const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
  7691. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
  7692. sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
  7693. juce::Timer::callAfterDelay (10, *tick);
  7694. return;
  7695. }
  7696. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
  7697. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  7698. juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
  7699. if (engine == nullptr)
  7700. return;
  7701. engine->stop();
  7702. juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
  7703. if (engine == nullptr)
  7704. return;
  7705. engine->setRecording (false);
  7706. const auto& s = engine->getSong();
  7707. // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
  7708. std::vector<std::pair<std::int64_t, float>> got;
  7709. juce::String where = "nothing";
  7710. for (const auto& a : s.automations)
  7711. if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
  7712. {
  7713. where = "automation clip \"" + juce::String (a.name) + "\"";
  7714. for (const auto& pt : a.points)
  7715. got.push_back ({ pt.tick, pt.value });
  7716. }
  7717. for (const auto& p : s.patterns)
  7718. for (const auto& lane : p.events)
  7719. if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
  7720. {
  7721. where = "pattern \"" + juce::String (p.name) + "\" event lane";
  7722. for (const auto& e : lane.events)
  7723. got.push_back ({ e.tick, e.value });
  7724. }
  7725. int notes = 0;
  7726. for (const auto& p : s.patterns)
  7727. notes += (int) p.notes.size();
  7728. float lo = 1.0f, hi = 0.0f;
  7729. for (const auto& [t, v] : got)
  7730. lo = std::min (lo, v), hi = std::max (hi, v);
  7731. // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
  7732. const auto span = got.empty() ? 0 : got.back().first - got.front().first;
  7733. const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
  7734. step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
  7735. step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
  7736. + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
  7737. + ", notes " + juce::String (notes));
  7738. if (! got.empty())
  7739. step ("last=" + juce::String (got.back().second, 3));
  7740. // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
  7741. // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
  7742. const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
  7743. const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
  7744. && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
  7745. : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
  7746. step (ok ? "result=OK" : "result=FAILED");
  7747. finish (ok ? 0 : 1);
  7748. });
  7749. });
  7750. };
  7751. juce::Timer::callAfterDelay (300, *tick);
  7752. }
  7753. // --countinrectest (round 170d): see the command line above.
  7754. void runCountInRecordTest (const juce::File& report)
  7755. {
  7756. engine = std::make_unique<lynx::AudioEngine>();
  7757. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  7758. struct StandIn final : juce::AudioIODevice
  7759. {
  7760. StandIn() : juce::AudioIODevice ("countin", "test") {}
  7761. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  7762. juce::StringArray getInputChannelNames() override { return {}; }
  7763. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  7764. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  7765. int getDefaultBufferSize() override { return 512; }
  7766. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  7767. void close() override {}
  7768. bool isOpen() override { return true; }
  7769. void start (juce::AudioIODeviceCallback*) override {}
  7770. void stop() override {}
  7771. bool isPlaying() override { return true; }
  7772. juce::String getLastError() override { return {}; }
  7773. int getCurrentBufferSizeSamples() override { return 512; }
  7774. double getCurrentSampleRate() override { return 48000.0; }
  7775. int getCurrentBitDepth() override { return 32; }
  7776. juce::BigInteger getActiveOutputChannels() const override
  7777. {
  7778. juce::BigInteger b;
  7779. b.setRange (0, 2, true);
  7780. return b;
  7781. }
  7782. juce::BigInteger getActiveInputChannels() const override { return {}; }
  7783. int getOutputLatencyInSamples() override { return 256; }
  7784. int getInputLatencyInSamples() override { return 0; }
  7785. };
  7786. auto device = std::make_shared<StandIn>();
  7787. auto text = std::make_shared<juce::String>();
  7788. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  7789. auto finish = [this] (int code) {
  7790. setApplicationReturnValue (code);
  7791. quit();
  7792. };
  7793. constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
  7794. lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
  7795. song.bpm = 120.0;
  7796. song.mixer = lynx::Song::defaultMixer (2);
  7797. song.channels.resize (1);
  7798. song.channels[0].mixerTrack = 1;
  7799. song.patterns.emplace_back();
  7800. song.mode = lynx::PlayMode::song;
  7801. song.currentPattern = 0;
  7802. engine->setSong (song);
  7803. engine->getTransport().metronome.store (true);
  7804. auto o = engine->getRecordOptions();
  7805. o.mode = lynx::RecordMode::overdub;
  7806. o.countInBars = 1;
  7807. o.catchWindow = lynx::ppq / 4;
  7808. o.compensateOutput = true;
  7809. o.recordNotes = true;
  7810. o.recordAudio = false;
  7811. o.recordAutomation = false;
  7812. o.waitForInput = false;
  7813. o.quantise = 0;
  7814. o.placeSongClip = true;
  7815. o.recordingMarkers = false;
  7816. o.punchLoopRegion = false;
  7817. o.preRollBars = o.postRollBars = 0;
  7818. engine->setRecordOptions (o);
  7819. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  7820. 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");
  7821. // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
  7822. struct Event
  7823. {
  7824. std::int64_t heard;
  7825. juce::MidiMessage message;
  7826. };
  7827. struct Pass
  7828. {
  7829. std::vector<float> out;
  7830. std::vector<Event> events;
  7831. std::int64_t playingAt = -1; // the first sample of the block the song started in
  7832. int block = 0, blocks = 0;
  7833. std::function<void()> done;
  7834. };
  7835. constexpr int n = 512;
  7836. constexpr double rate = 48000.0;
  7837. // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
  7838. // ticks (the take is committed there); then stopped and its results left to the timer
  7839. auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  7840. *runPass = [this] (std::shared_ptr<Pass> pass) {
  7841. auto& cb = engine->deviceCallback();
  7842. std::vector<float> l (n), r (n);
  7843. float* outs[] = { l.data(), r.data() };
  7844. juce::AudioIODeviceCallbackContext context;
  7845. if (pass->block == 0)
  7846. {
  7847. engine->stop();
  7848. engine->seek ((double) (2 * bar));
  7849. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
  7850. engine->setRecording (true);
  7851. engine->startPlayback(); // the count-in starts
  7852. }
  7853. for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
  7854. {
  7855. // the events heard in this block: stamped the way the engine's clock maps time to heard samples
  7856. const auto blockStart = (std::int64_t) pass->block * n;
  7857. const auto clock = engine->liveClock();
  7858. const auto compMs = 1000.0 * (n + 256) / rate;
  7859. for (auto& e : pass->events)
  7860. if (e.heard >= blockStart && e.heard < blockStart + n)
  7861. {
  7862. auto m = e.message;
  7863. m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
  7864. engine->injectMidiInput (m);
  7865. }
  7866. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
  7867. pass->out.insert (pass->out.end(), l.begin(), l.end());
  7868. if (pass->playingAt < 0 && engine->getTransport().playing.load())
  7869. pass->playingAt = blockStart;
  7870. }
  7871. };
  7872. // (the recursion through the message loop; written out so each step lets the engine's timer run)
  7873. auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  7874. *drive = [this, runPass, drive, device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
  7875. if (engine == nullptr)
  7876. return;
  7877. (*runPass) (pass);
  7878. if (pass->block < pass->blocks)
  7879. {
  7880. juce::Timer::callAfterDelay (40, [pass, drive] { (*drive) (pass); });
  7881. return;
  7882. }
  7883. engine->stop();
  7884. juce::Timer::callAfterDelay (300, [this, pass] {
  7885. if (engine == nullptr)
  7886. return;
  7887. engine->setRecording (false);
  7888. juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
  7889. });
  7890. };
  7891. auto onsets = [] (const std::vector<float>& out) {
  7892. std::vector<std::int64_t> at;
  7893. std::int64_t last = -100000;
  7894. for (std::size_t i = 0; i < out.size(); ++i)
  7895. if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
  7896. {
  7897. at.push_back ((std::int64_t) i);
  7898. last = (std::int64_t) i;
  7899. }
  7900. else if (std::abs (out[i]) > 0.02f)
  7901. last = (std::int64_t) i;
  7902. return at;
  7903. };
  7904. // the graph is (re)built on the message thread: start once it has settled
  7905. juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
  7906. if (engine == nullptr)
  7907. return;
  7908. auto first = std::make_shared<Pass>();
  7909. first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
  7910. first->done = [this, first, step, finish, drive, onsets] {
  7911. const auto clicks = onsets (first->out);
  7912. juce::String list;
  7913. for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
  7914. list << clicks[i] << " ";
  7915. step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
  7916. // the bar-3 downbeat: the click at the block the song started in
  7917. std::int64_t down = -1;
  7918. for (auto c : clicks)
  7919. if (std::abs (c - first->playingAt) < n)
  7920. down = c;
  7921. if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
  7922. {
  7923. step ("result=FAILED no downbeat click found (or notes recorded without input)");
  7924. finish (1);
  7925. return;
  7926. }
  7927. const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
  7928. auto second = std::make_shared<Pass>();
  7929. second->blocks = first->blocks;
  7930. auto add = [&second] (std::int64_t at, int key, bool on) {
  7931. second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
  7932. };
  7933. for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
  7934. {
  7935. add (ms (-15.0), key, true);
  7936. add (ms (500.0), key, false);
  7937. }
  7938. add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
  7939. add (ms (-1250.0), 62, false);
  7940. add (ms (503.0), 77, true); // 3 ms after beat 2
  7941. add (ms (603.0), 77, false);
  7942. for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
  7943. {
  7944. add (ms (b * 2000.0), 70 + b, true);
  7945. add (ms (b * 2000.0 + 250.0), 70 + b, false);
  7946. }
  7947. second->done = [this, step, finish] {
  7948. const auto& s = engine->getSong();
  7949. const auto& p = s.patterns[0];
  7950. const lynx::Clip* clip = nullptr;
  7951. for (const auto& c : s.playlist)
  7952. if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
  7953. clip = &c;
  7954. const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
  7955. step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
  7956. auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
  7957. // where each one was heard (song ticks): 0.5 ms = ~1 tick
  7958. const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
  7959. { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
  7960. { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
  7961. { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
  7962. for (const auto& [key, tick] : want)
  7963. {
  7964. const lynx::Note* found = nullptr;
  7965. for (const auto& note : p.notes)
  7966. if (note.key == key)
  7967. found = &note;
  7968. const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
  7969. const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
  7970. ok = ok && good;
  7971. step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
  7972. + (good ? " ok" : " WRONG"));
  7973. }
  7974. const auto* chord = [&p] () -> const lynx::Note* {
  7975. for (const auto& note : p.notes)
  7976. if (note.key == 60)
  7977. return &note;
  7978. return nullptr;
  7979. }();
  7980. if (chord != nullptr)
  7981. step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
  7982. step (ok ? "result=OK" : "result=FAILED");
  7983. finish (ok ? 0 : 1);
  7984. };
  7985. (*drive) (second);
  7986. };
  7987. (*drive) (first);
  7988. });
  7989. }
  7990. // --cliplooptest (round 167q): see the command line above.
  7991. // --slicexedittest (round 190aj): see the command line above
  7992. void runSlicexEditTest (const juce::File& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  7993. {
  7994. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7995. juce::StringArray lines;
  7996. {
  7997. lynx::AudioEngine offline (false);
  7998. lynx::MainComponent ui (offline, false);
  7999. ui.setSize (1280, 720);
  8000. ui.openFile (project);
  8001. offline.dispatchPendingMessages();
  8002. int channel = -1;
  8003. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  8004. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  8005. channel = c;
  8006. if (channel < 0)
  8007. lines.add ("no Slicex channel in " + project.getFullPathName());
  8008. else
  8009. {
  8010. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  8011. juce::Component frame;
  8012. frame.setSize (panel->getWidth(), panel->getHeight());
  8013. frame.setOpaque (true);
  8014. frame.addAndMakeVisible (*panel);
  8015. panel->setTopLeftPosition (0, 0);
  8016. offline.dispatchPendingMessages();
  8017. juce::StringArray commands;
  8018. script.readLines (commands);
  8019. for (const auto& raw : commands)
  8020. {
  8021. const auto command = raw.trim();
  8022. if (command.isEmpty() || command.startsWith ("#"))
  8023. {
  8024. lines.add (command);
  8025. continue;
  8026. }
  8027. if (command.startsWith ("shot "))
  8028. {
  8029. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  8030. {
  8031. juce::Graphics g (image);
  8032. g.fillAll (lynx::theme::panel);
  8033. frame.paintEntireComponent (g, false);
  8034. }
  8035. const juce::File file (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png");
  8036. file.deleteFile();
  8037. juce::PNGImageFormat png;
  8038. if (auto out = file.createOutputStream())
  8039. png.writeImageToStream (image, *out);
  8040. lines.add (command + " -> " + file.getFileName());
  8041. continue;
  8042. }
  8043. const auto result = lynx::slicexEditorTest (*panel, command);
  8044. offline.dispatchPendingMessages();
  8045. lines.add (command + " -> " + result);
  8046. }
  8047. }
  8048. }
  8049. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  8050. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  8051. quit();
  8052. }
  8053. // --slicexkeytest (round 190ac): see the command line above
  8054. void runSlicexKeyTest (const juce::File& report)
  8055. {
  8056. engine = std::make_unique<lynx::AudioEngine>();
  8057. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  8058. struct StandIn final : juce::AudioIODevice
  8059. {
  8060. StandIn() : juce::AudioIODevice ("slicexkey", "test") {}
  8061. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  8062. juce::StringArray getInputChannelNames() override { return {}; }
  8063. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  8064. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  8065. int getDefaultBufferSize() override { return 512; }
  8066. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  8067. void close() override {}
  8068. bool isOpen() override { return true; }
  8069. void start (juce::AudioIODeviceCallback*) override {}
  8070. void stop() override {}
  8071. bool isPlaying() override { return true; }
  8072. juce::String getLastError() override { return {}; }
  8073. int getCurrentBufferSizeSamples() override { return 512; }
  8074. double getCurrentSampleRate() override { return 48000.0; }
  8075. int getCurrentBitDepth() override { return 32; }
  8076. juce::BigInteger getActiveOutputChannels() const override
  8077. {
  8078. juce::BigInteger b;
  8079. b.setRange (0, 2, true);
  8080. return b;
  8081. }
  8082. juce::BigInteger getActiveInputChannels() const override { return {}; }
  8083. int getOutputLatencyInSamples() override { return 0; }
  8084. int getInputLatencyInSamples() override { return 0; }
  8085. };
  8086. auto device = std::make_shared<StandIn>();
  8087. auto text = std::make_shared<juce::String>();
  8088. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  8089. // the deck's sample: 1 s at 48 kHz, four regions (cue points) of 0.25 s, each a steady tone of its own (200 Hz
  8090. // × region number), so the region a key played can be read from the output
  8091. constexpr int rate = 48000, regionFrames = rate / 4;
  8092. const auto wavFile = report.getSiblingFile ("slicexkey-deck.wav");
  8093. {
  8094. juce::MemoryOutputStream w;
  8095. auto chunk = [&w] (const char* id, const juce::MemoryBlock& body) {
  8096. w.write (id, 4);
  8097. w.writeInt ((int) body.getSize());
  8098. w.write (body.getData(), body.getSize());
  8099. };
  8100. juce::MemoryOutputStream fmt, data, cue;
  8101. fmt.writeShort (1);
  8102. fmt.writeShort (1);
  8103. fmt.writeInt (rate);
  8104. fmt.writeInt (rate * 2);
  8105. fmt.writeShort (2);
  8106. fmt.writeShort (16);
  8107. for (int i = 0; i < 4 * regionFrames; ++i)
  8108. data.writeShort ((short) std::lround (12000.0 * std::sin (juce::MathConstants<double>::twoPi * 200.0 * (double) (i / regionFrames + 1) * (double) i / rate)));
  8109. cue.writeInt (4);
  8110. for (int k = 0; k < 4; ++k)
  8111. {
  8112. cue.writeInt (k + 1);
  8113. cue.writeInt (k * regionFrames);
  8114. cue.write ("data", 4);
  8115. cue.writeInt (0);
  8116. cue.writeInt (0);
  8117. cue.writeInt (k * regionFrames);
  8118. }
  8119. juce::MemoryOutputStream riff;
  8120. riff.write ("WAVE", 4);
  8121. w.reset();
  8122. chunk ("fmt ", fmt.getMemoryBlock());
  8123. chunk ("data", data.getMemoryBlock());
  8124. chunk ("cue ", cue.getMemoryBlock());
  8125. riff.write (w.getData(), w.getDataSize());
  8126. juce::MemoryOutputStream file;
  8127. file.write ("RIFF", 4);
  8128. file.writeInt ((int) riff.getDataSize());
  8129. file.write (riff.getData(), riff.getDataSize());
  8130. wavFile.replaceWithData (file.getData(), file.getDataSize());
  8131. }
  8132. lynx::Song song;
  8133. song.bpm = 120.0;
  8134. song.mixer = lynx::Song::defaultMixer (2);
  8135. song.channels.resize (1);
  8136. auto& channel = song.channels[0];
  8137. channel.instrument = lynx::InstrumentKind::slicex;
  8138. channel.mixerTrack = 1;
  8139. channel.samplePath = wavFile.getFullPathName().toStdString();
  8140. {
  8141. auto state = lynx::slicex::fresh();
  8142. lynx::slicex::setDeckFile (state, 0, channel.samplePath, 4);
  8143. lynx::slicex::setDeckBeats (state, 0, 0.0, 2.0);
  8144. channel.pluginState = lynx::slicex::write (state);
  8145. }
  8146. song.patterns.emplace_back();
  8147. engine->setSong (song);
  8148. auto& callback = engine->deviceCallback();
  8149. callback.audioDeviceAboutToStart (device.get());
  8150. step ("song=one Slicex channel, deck A = 4 regions of 0.25 s (200 / 400 / 600 / 800 Hz), 48 kHz, blocks of 512; keys as the editor's keyboard sends them");
  8151. juce::Timer::callAfterDelay (2000, [this, device, step] {
  8152. if (engine == nullptr)
  8153. return;
  8154. auto& cb = engine->deviceCallback();
  8155. auto pump = [&cb] (int blocks) {
  8156. std::vector<float> l (512), r (512), out;
  8157. float* outs[] = { l.data(), r.data() };
  8158. juce::AudioIODeviceCallbackContext context;
  8159. for (int k = 0; k < blocks; ++k)
  8160. {
  8161. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  8162. out.insert (out.end(), l.begin(), l.end());
  8163. }
  8164. return out;
  8165. };
  8166. auto rms = [] (const std::vector<float>& x, int from, int count) {
  8167. double sum = 0.0;
  8168. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  8169. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  8170. return std::sqrt (sum / juce::jmax (1, count));
  8171. };
  8172. // the tone's frequency from its rising zero crossings over a stretch
  8173. auto hertz = [] (const std::vector<float>& x, int from, int count) {
  8174. int crossings = 0, first = -1, last = -1;
  8175. for (int i = from + 1; i < from + count && i < (int) x.size(); ++i)
  8176. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  8177. {
  8178. first = first < 0 ? i : first;
  8179. last = i;
  8180. ++crossings;
  8181. }
  8182. return crossings > 1 ? 48000.0 * (double) (crossings - 1) / (double) (last - first) : 0.0;
  8183. };
  8184. bool ok = true;
  8185. auto check = [&ok, step] (bool good, const juce::String& what) {
  8186. ok = ok && good;
  8187. step ((good ? "ok " : "FAIL ") + what);
  8188. };
  8189. const auto idle = pump (20);
  8190. engine->getMeters().takePeak (1, 0);
  8191. check (rms (idle, 0, (int) idle.size()) < 1.0e-6, "idle: rms " + juce::String (rms (idle, 0, (int) idle.size()), 9));
  8192. // 4 regions map to keys 60…63 (FL's automatic map); the editor's click: velocity 100 / 128
  8193. engine->sendLiveNote (0, 60, 0.78125f, true);
  8194. const auto first = pump (16); // 8192 frames = 171 ms, inside region 1 (250 ms)
  8195. const auto meter = engine->getMeters().takePeak (1, 0);
  8196. check (rms (first, 1024, 6000) > 0.01, "key 60 down: rms " + juce::String (rms (first, 1024, 6000), 6) + ", " + juce::String (hertz (first, 1024, 6000), 1) + " Hz");
  8197. check (std::abs (hertz (first, 1024, 6000) - 200.0) < 4.0, "key 60 plays region 1 (200 Hz)");
  8198. check (meter > 0.01f, "mixer track 1 meter peak " + juce::String (meter, 6));
  8199. engine->sendLiveNote (0, 60, 0.0f, false);
  8200. const auto tail = pump (60);
  8201. check (rms (tail, (int) tail.size() - 4096, 4096) < 1.0e-5, "key 60 up: the end is silent, rms " + juce::String (rms (tail, (int) tail.size() - 4096, 4096), 9));
  8202. engine->sendLiveNote (0, 62, 0.78125f, true);
  8203. const auto third = pump (16);
  8204. check (rms (third, 1024, 6000) > 0.01 && std::abs (hertz (third, 1024, 6000) - 600.0) < 8.0,
  8205. "key 62 plays region 3 (600 Hz): rms " + juce::String (rms (third, 1024, 6000), 6) + ", " + juce::String (hertz (third, 1024, 6000), 1) + " Hz");
  8206. engine->sendLiveNote (0, 62, 0.0f, false);
  8207. engine->sendLiveNote (0, 72, 0.78125f, true); // a key without a region
  8208. const auto none = pump (60);
  8209. check (rms (none, (int) none.size() - 4096, 4096) < 1.0e-5, "key 72 (no region): silent, rms " + juce::String (rms (none, (int) none.size() - 4096, 4096), 9));
  8210. engine->sendLiveNote (0, 72, 0.0f, false);
  8211. step (ok ? "result=OK" : "result=FAILED");
  8212. setApplicationReturnValue (ok ? 0 : 1);
  8213. quit();
  8214. });
  8215. }
  8216. void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
  8217. {
  8218. engine = std::make_unique<lynx::AudioEngine>();
  8219. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  8220. struct StandIn final : juce::AudioIODevice
  8221. {
  8222. StandIn() : juce::AudioIODevice ("cliploop", "test") {}
  8223. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  8224. juce::StringArray getInputChannelNames() override { return {}; }
  8225. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  8226. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  8227. int getDefaultBufferSize() override { return 512; }
  8228. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  8229. void close() override {}
  8230. bool isOpen() override { return true; }
  8231. void start (juce::AudioIODeviceCallback*) override {}
  8232. void stop() override {}
  8233. bool isPlaying() override { return true; }
  8234. juce::String getLastError() override { return {}; }
  8235. int getCurrentBufferSizeSamples() override { return 512; }
  8236. double getCurrentSampleRate() override { return 48000.0; }
  8237. int getCurrentBitDepth() override { return 32; }
  8238. juce::BigInteger getActiveOutputChannels() const override
  8239. {
  8240. juce::BigInteger b;
  8241. b.setRange (0, 2, true);
  8242. return b;
  8243. }
  8244. juce::BigInteger getActiveInputChannels() const override { return {}; }
  8245. int getOutputLatencyInSamples() override { return 0; }
  8246. int getInputLatencyInSamples() override { return 0; }
  8247. };
  8248. auto device = std::make_shared<StandIn>();
  8249. auto text = std::make_shared<juce::String>();
  8250. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  8251. constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
  8252. const auto ppq = (double) lynx::ppq;
  8253. lynx::Song song;
  8254. song.bpm = 120.0;
  8255. song.mixer = lynx::Song::defaultMixer (2);
  8256. song.channels.resize (1); // the synth of a new channel: deterministic
  8257. song.channels[0].mixerTrack = 1;
  8258. auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
  8259. for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
  8260. {
  8261. lynx::Note n;
  8262. n.start = b * lynx::ppq;
  8263. n.length = lynx::ppq / 4;
  8264. n.key = key;
  8265. pattern.notes.push_back (n);
  8266. }
  8267. lynx::Clip clip;
  8268. clip.pattern = 0;
  8269. clip.length = 16 * lynx::ppq; // stretched to 4 bars
  8270. song.playlist.push_back (clip);
  8271. song.mode = lynx::PlayMode::song;
  8272. {
  8273. // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
  8274. auto gui = song;
  8275. gui.playlist[0].length = 4 * lynx::ppq;
  8276. juce::String error;
  8277. lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
  8278. }
  8279. engine->setSong (song);
  8280. auto& callback = engine->deviceCallback();
  8281. callback.audioDeviceAboutToStart (device.get());
  8282. step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
  8283. // the graph is (re)built on the message thread: the scenarios run once it has settled
  8284. juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
  8285. if (engine == nullptr)
  8286. return;
  8287. auto& cb = engine->deviceCallback();
  8288. // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
  8289. auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
  8290. engine->stop();
  8291. engine->seek (from);
  8292. std::vector<float> l (512), r (512), out;
  8293. float* outs[] = { l.data(), r.data() };
  8294. juce::AudioIODeviceCallbackContext context;
  8295. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
  8296. engine->play();
  8297. for (int k = 0; (int) out.size() < samples; ++k)
  8298. {
  8299. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  8300. out.insert (out.end(), l.begin(), l.end());
  8301. if (between)
  8302. between (k);
  8303. }
  8304. engine->stop();
  8305. for (int k = 0; k < 400; ++k) // the tails of the scenario die out
  8306. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  8307. out.resize ((std::size_t) samples);
  8308. return out;
  8309. };
  8310. auto rms = [] (const std::vector<float>& x, int from, int count) {
  8311. double sum = 0.0;
  8312. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  8313. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  8314. return std::sqrt (sum / juce::jmax (1, count));
  8315. };
  8316. auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
  8317. double m = 0.0;
  8318. for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
  8319. m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
  8320. return m;
  8321. };
  8322. auto num = [] (double v) { return juce::String (v, 6); };
  8323. bool ok = true;
  8324. auto check = [&ok, step] (bool good, const juce::String& what) {
  8325. ok = ok && good;
  8326. step ((good ? "ok " : "FAIL ") + what);
  8327. };
  8328. lynx::setStretchedClipsLoop (true);
  8329. const auto a = play (0.0, 4 * bar);
  8330. const auto bar1 = rms (a, 0, bar);
  8331. check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
  8332. for (int k = 1; k < 4; ++k)
  8333. {
  8334. const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
  8335. check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  8336. "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
  8337. }
  8338. {
  8339. const auto x = play (10 * ppq, bar + bar / 2);
  8340. const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
  8341. check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
  8342. "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));
  8343. }
  8344. {
  8345. // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
  8346. const auto jumpBlock = 7 * beat / 512 - 1;
  8347. const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
  8348. if (k == jumpBlock)
  8349. engine->seek (14 * ppq);
  8350. });
  8351. // (the best of 0-2 samples late: anything but 0 fails)
  8352. const auto at = (jumpBlock + 1) * 512;
  8353. int lag = 0;
  8354. auto d = 1.0e9;
  8355. for (int l = 0; l <= 2; ++l)
  8356. if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
  8357. d = dl, lag = l;
  8358. d = lag == 0 ? d : 1.0;
  8359. const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
  8360. check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
  8361. "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
  8362. + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
  8363. }
  8364. {
  8365. engine->editSong ([ppq] (lynx::Song& s) {
  8366. s.loopStart = (std::int64_t) (4 * ppq);
  8367. s.loopEnd = (std::int64_t) (12 * ppq);
  8368. }, false);
  8369. const auto x = play (0.0, 7 * bar);
  8370. double d = 0.0;
  8371. juce::String lags;
  8372. for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
  8373. {
  8374. auto best = 1.0e9;
  8375. int lag = 0;
  8376. for (int l = 0; l <= 2; ++l)
  8377. if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
  8378. best = dl, lag = l;
  8379. d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
  8380. lags << (k > 1 ? "," : "") << lag;
  8381. }
  8382. const auto r = rms (x, bar, 6 * bar);
  8383. check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  8384. "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)
  8385. + " (samples late, bars 2-7: " + lags + ")");
  8386. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  8387. }
  8388. {
  8389. // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
  8390. // wrap used to play one sample more)
  8391. engine->editSong ([ppq] (lynx::Song& s) {
  8392. s.loopStart = (std::int64_t) (4 * ppq);
  8393. s.loopEnd = (std::int64_t) (8 * ppq);
  8394. }, false);
  8395. const auto x = play (0.0, 101 * bar);
  8396. double d = 0.0;
  8397. int worst = 0;
  8398. for (int k = 1; k <= 100; ++k)
  8399. if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
  8400. d = dk, worst = k + 1;
  8401. check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
  8402. + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
  8403. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  8404. }
  8405. lynx::setStretchedClipsLoop (false);
  8406. {
  8407. const auto x = play (0.0, 4 * bar);
  8408. const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
  8409. 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));
  8410. }
  8411. lynx::setStretchedClipsLoop (true);
  8412. cb.audioDeviceStopped();
  8413. // the export: a WAV of the 4 bars, read back from the file
  8414. if (wavFile != juce::File())
  8415. {
  8416. for (const auto loops : { true, false })
  8417. {
  8418. lynx::setStretchedClipsLoop (loops);
  8419. const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
  8420. file.deleteFile();
  8421. {
  8422. juce::WavAudioFormat wav;
  8423. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
  8424. engine->stop();
  8425. engine->seek (0.0);
  8426. lynx::AudioEngine::RenderOptions o;
  8427. o.seconds = 8.0;
  8428. o.sampleRate = 48000.0;
  8429. o.output = writer.get();
  8430. engine->renderOffline (o);
  8431. }
  8432. juce::WavAudioFormat wav;
  8433. std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
  8434. std::vector<float> x;
  8435. if (reader != nullptr)
  8436. {
  8437. juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
  8438. reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
  8439. x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
  8440. }
  8441. const auto b1 = rms (x, 0, bar);
  8442. juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
  8443. bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
  8444. for (int k = 1; k < 4; ++k)
  8445. {
  8446. const auto rk = rms (x, k * bar, bar);
  8447. line << ", bar " << (k + 1) << " " << num (rk);
  8448. 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);
  8449. }
  8450. if (loops)
  8451. 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);
  8452. check (good, line);
  8453. }
  8454. lynx::setStretchedClipsLoop (true);
  8455. }
  8456. step (ok ? "result=OK" : "result=FAILED");
  8457. setApplicationReturnValue (ok ? 0 : 1);
  8458. quit();
  8459. });
  8460. }
  8461. // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
  8462. // process leaves what was done).
  8463. void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  8464. const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
  8465. {
  8466. engine = std::make_unique<lynx::AudioEngine>();
  8467. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  8468. savedDeviceState = engine->getDeviceManager().createStateXml();
  8469. auto text = std::make_shared<juce::String>();
  8470. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  8471. auto finish = [this, step] (int code) {
  8472. restoreSavedDeviceState();
  8473. setApplicationReturnValue (code);
  8474. quit();
  8475. };
  8476. auto& devices = engine->getDeviceManager();
  8477. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  8478. devices.setCurrentAudioDeviceType (deviceType, true);
  8479. {
  8480. auto setup = devices.getAudioDeviceSetup();
  8481. if (deviceName.isNotEmpty())
  8482. setup.outputDeviceName = deviceName;
  8483. if (bufferSize > 0)
  8484. setup.bufferSize = bufferSize;
  8485. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  8486. step ("device_error=" + error);
  8487. }
  8488. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  8489. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  8490. // takes go next to the report, not into the user's recordings folder
  8491. engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
  8492. auto* device = devices.getCurrentAudioDevice();
  8493. if (device == nullptr || engine->getInputChannelNames().empty())
  8494. {
  8495. step ("result=ERROR no device / no input");
  8496. finish (1);
  8497. return;
  8498. }
  8499. const auto rate = device->getCurrentSampleRate();
  8500. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
  8501. + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
  8502. // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
  8503. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  8504. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  8505. {
  8506. lynx::takes::WavTakeWriter w;
  8507. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  8508. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  8509. std::vector<float> block (4096);
  8510. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  8511. {
  8512. std::fill (block.begin(), block.end(), 0.0f);
  8513. for (int k = 0; k < (int) block.size(); ++k)
  8514. {
  8515. const auto f = at + k;
  8516. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  8517. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  8518. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  8519. if (rel >= 0 && rel < 5)
  8520. block[(std::size_t) k] = 0.5f * shape[rel];
  8521. }
  8522. const float* d[] { block.data() };
  8523. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  8524. }
  8525. w.close();
  8526. }
  8527. lynx::Song song = lynx::Song::makeDefault();
  8528. song.bpm = 120.0;
  8529. song.mode = lynx::PlayMode::song;
  8530. song.playlist.clear();
  8531. lynx::ChannelDef c;
  8532. c.name = "Clicks";
  8533. c.instrument = lynx::InstrumentKind::audioClip;
  8534. c.samplePath = clickFile.getFullPathName().toStdString();
  8535. c.mixerTrack = 0;
  8536. c.volume = 1.0f;
  8537. song.channels.push_back (c);
  8538. lynx::Clip clip;
  8539. clip.kind = lynx::ClipKind::audio;
  8540. clip.channel = (int) song.channels.size() - 1;
  8541. clip.track = 0;
  8542. clip.start = 0;
  8543. clip.length = (std::int64_t) beats * lynx::ppq;
  8544. song.playlist.push_back (clip);
  8545. if (mode == 1) // loop recording, bars 2-4
  8546. {
  8547. song.loopStart = 4 * lynx::ppq;
  8548. song.loopEnd = 16 * lynx::ppq;
  8549. }
  8550. else if (mode == 2) // punch in/out, bars 3-4
  8551. {
  8552. song.loopStart = 8 * lynx::ppq;
  8553. song.loopEnd = 16 * lynx::ppq;
  8554. }
  8555. if (song.mixer.size() > 1)
  8556. {
  8557. song.mixer[1].name = "Loop In";
  8558. song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
  8559. }
  8560. engine->setSong (std::move (song));
  8561. engine->setInsertInput (1, 0, false);
  8562. juce::ignoreUnused (pdcSamples);
  8563. // 1) the ping
  8564. if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
  8565. step ("ping_error=" + error);
  8566. juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
  8567. if (engine == nullptr)
  8568. return;
  8569. if (engine->isPinging())
  8570. engine->cancelLatencyPing();
  8571. const auto r = engine->finishLatencyPing();
  8572. step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
  8573. + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
  8574. const auto l = engine->currentLatency();
  8575. step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
  8576. // 2) record
  8577. engine->setInsertArmed (1, true);
  8578. auto o = engine->getRecordOptions();
  8579. o.recordAudio = true;
  8580. o.countInBars = 0;
  8581. o.waitForInput = false;
  8582. o.punchLoopRegion = mode == 2;
  8583. o.preRollBars = mode == 2 ? 1 : 0;
  8584. o.postRollBars = mode == 2 ? 1 : 0;
  8585. // (round 177c: LYNX_RECTEST_BLEND_OFF=1: Blend off; LYNX_RECTEST_LAST_PASS=1: "only the last pass plays")
  8586. o.mode = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_BLEND_OFF", {}) == "1" ? lynx::RecordMode::replace
  8587. : lynx::RecordMode::overdub;
  8588. o.lastLoopPassPlays = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_LAST_PASS", {}) == "1";
  8589. engine->setRecordOptions (o);
  8590. engine->stop();
  8591. engine->rewind();
  8592. engine->setRecording (true);
  8593. juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
  8594. if (engine == nullptr)
  8595. return;
  8596. engine->startPlayback(); // (as the Play button: pre-roll / punch)
  8597. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
  8598. if (engine == nullptr)
  8599. return;
  8600. if (mode == 2)
  8601. step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
  8602. engine->stop();
  8603. juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
  8604. if (engine == nullptr)
  8605. return;
  8606. engine->setRecording (false);
  8607. const auto& s = engine->getSong();
  8608. const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
  8609. int take = -1;
  8610. for (int ch = 0; ch < (int) s.channels.size(); ++ch)
  8611. if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
  8612. take = ch;
  8613. if (take < 0)
  8614. {
  8615. step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
  8616. finish (1);
  8617. return;
  8618. }
  8619. std::vector<std::vector<float>> audio;
  8620. double takeRate = 0.0;
  8621. const auto& path = s.channels[(std::size_t) take].samplePath;
  8622. lynx::takes::readWav (path, audio, &takeRate);
  8623. const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
  8624. step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
  8625. + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
  8626. // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
  8627. std::vector<juce::int64> peaks;
  8628. if (! audio.empty())
  8629. for (juce::int64 f = 1; f + 1 < frames; ++f)
  8630. {
  8631. const auto x = std::abs (audio[0][(std::size_t) f]);
  8632. if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
  8633. && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
  8634. peaks.push_back (f);
  8635. }
  8636. // every clip of the take: each click inside it against the nearest beat
  8637. int clips = 0, checked = 0, muted = 0;
  8638. double worst = 0.0, sum = 0.0;
  8639. for (const auto& c : s.playlist)
  8640. {
  8641. if (c.kind != lynx::ClipKind::audio || c.channel != take)
  8642. continue;
  8643. ++clips;
  8644. muted += c.muted ? 1 : 0;
  8645. const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
  8646. for (const auto f : peaks)
  8647. {
  8648. const auto intoClip = (double) f - skip;
  8649. if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
  8650. continue;
  8651. const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
  8652. const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
  8653. const auto error = (songTick - beat) / tps;
  8654. worst = std::max (worst, std::abs (error));
  8655. sum += error;
  8656. ++checked;
  8657. }
  8658. step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
  8659. + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
  8660. + (c.muted ? " (muted lane)" : ""));
  8661. }
  8662. step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
  8663. + " muted_lanes=" + juce::String (muted));
  8664. step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
  8665. auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
  8666. if (mode == 2) // one clip, exactly the punch range, its 8 beats
  8667. {
  8668. const auto& sp = engine->getSong();
  8669. bool exact = false;
  8670. for (const auto& c : sp.playlist)
  8671. if (c.kind == lynx::ClipKind::audio && c.channel == take)
  8672. exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
  8673. step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
  8674. ok = ok && clips == 1 && exact && checked == 8;
  8675. }
  8676. report.getSiblingFile (report.getFileNameWithoutExtension() + "-project.lynx").replaceWithText (lynx::ProjectFile::toJson (engine->getSong()));
  8677. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  8678. finish (ok ? 0 : 1);
  8679. });
  8680. });
  8681. });
  8682. });
  8683. }
  8684. // --hwinserttest (round 164d): see the command line above.
  8685. void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  8686. const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
  8687. {
  8688. engine = std::make_unique<lynx::AudioEngine>();
  8689. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  8690. savedDeviceState = engine->getDeviceManager().createStateXml();
  8691. auto text = std::make_shared<juce::String>();
  8692. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  8693. auto finish = [this] (int code) {
  8694. if (engine != nullptr)
  8695. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  8696. restoreSavedDeviceState();
  8697. setApplicationReturnValue (code);
  8698. quit();
  8699. };
  8700. auto& devices = engine->getDeviceManager();
  8701. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  8702. devices.setCurrentAudioDeviceType (deviceType, true);
  8703. {
  8704. auto setup = devices.getAudioDeviceSetup();
  8705. if (deviceName.isNotEmpty())
  8706. setup.outputDeviceName = deviceName;
  8707. if (bufferSize > 0)
  8708. setup.bufferSize = bufferSize;
  8709. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  8710. step ("device_error=" + error);
  8711. }
  8712. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  8713. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  8714. auto* device = devices.getCurrentAudioDevice();
  8715. if (device == nullptr || engine->getInputChannelNames().empty())
  8716. {
  8717. step ("result=ERROR no device / no input");
  8718. finish (1);
  8719. return;
  8720. }
  8721. const auto rate = device->getCurrentSampleRate();
  8722. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
  8723. // the click track: the ping's pulse on every beat at 120 bpm
  8724. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  8725. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  8726. {
  8727. lynx::takes::WavTakeWriter w;
  8728. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  8729. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  8730. std::vector<float> block (4096);
  8731. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  8732. {
  8733. std::fill (block.begin(), block.end(), 0.0f);
  8734. for (int k = 0; k < (int) block.size(); ++k)
  8735. {
  8736. const auto f = at + k;
  8737. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  8738. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  8739. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  8740. if (rel >= 0 && rel < 5)
  8741. block[(std::size_t) k] = 0.5f * shape[rel];
  8742. }
  8743. const float* d[] { block.data() };
  8744. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  8745. }
  8746. w.close();
  8747. }
  8748. lynx::Song song = lynx::Song::makeDefault();
  8749. song.bpm = 120.0;
  8750. song.mode = lynx::PlayMode::song;
  8751. song.playlist.clear();
  8752. song.channels.clear();
  8753. for (int k = 0; k < 2; ++k)
  8754. {
  8755. lynx::ChannelDef c;
  8756. c.name = k == 0 ? "Wet" : "Dry";
  8757. c.instrument = lynx::InstrumentKind::audioClip;
  8758. c.samplePath = clickFile.getFullPathName().toStdString();
  8759. c.mixerTrack = k + 1;
  8760. c.volume = 1.0f;
  8761. song.channels.push_back (c);
  8762. lynx::Clip clip;
  8763. clip.kind = lynx::ClipKind::audio;
  8764. clip.channel = k;
  8765. clip.track = k;
  8766. clip.start = 0;
  8767. clip.length = (std::int64_t) beats * lynx::ppq;
  8768. song.playlist.push_back (clip);
  8769. }
  8770. song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
  8771. for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
  8772. fx.enabled = false;
  8773. song.mixer[1].pan = -1.0f;
  8774. song.mixer[2].pan = 1.0f;
  8775. auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  8776. hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
  8777. hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
  8778. hw.params[lynx::hwinsert::inputStereo] = 1.0f;
  8779. song.mixer[1].effects.clear();
  8780. lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
  8781. if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
  8782. {
  8783. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  8784. lynx::PatchNode node;
  8785. node.effect = hw;
  8786. slot.patcher.nodes = { node };
  8787. lynx::PatchWire in, out;
  8788. in.from = lynx::patchFromHost;
  8789. in.to = 0;
  8790. out.from = 0;
  8791. out.to = lynx::patchToHost;
  8792. slot.patcher.wires = { in, out };
  8793. song.mixer[1].effects.push_back (slot);
  8794. ref.nodes = { 0 };
  8795. }
  8796. else
  8797. song.mixer[1].effects.push_back (hw);
  8798. engine->setSong (std::move (song));
  8799. step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
  8800. const auto meter = [this, ref] (int output) {
  8801. const auto fx = engine->runningHardwareInsert (ref);
  8802. return fx != nullptr ? fx->controlOutput (output) : 0.0f;
  8803. };
  8804. // 1) the insert's ping (as its Ping button: a momentary value flipped)
  8805. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  8806. if (engine == nullptr)
  8807. return;
  8808. engine->pingHardwareInserts ({ ref });
  8809. juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  8810. if (engine == nullptr)
  8811. return;
  8812. // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
  8813. // new round trip rebuilds the insert (its latency), so the result is read from the slot
  8814. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  8815. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  8816. const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
  8817. const auto state = meter (lynx::hwinsert::pingState);
  8818. const auto ok = samples > 0 && setup == engine->currentSetupKey();
  8819. step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
  8820. + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
  8821. if (! ok)
  8822. {
  8823. step ("result=FAILED ping");
  8824. finish (1);
  8825. return;
  8826. }
  8827. // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
  8828. step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
  8829. // 2) play, capturing the Master
  8830. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
  8831. if (engine == nullptr)
  8832. return;
  8833. step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
  8834. // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
  8835. // odd round trip (12345 samples: the project keeps it to the sample)
  8836. if (! inPatcher)
  8837. {
  8838. auto odd = engine->getSong();
  8839. odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
  8840. juce::String error;
  8841. auto same = true;
  8842. for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
  8843. {
  8844. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
  8845. const auto saved = lynx::ProjectFile::save (*song, file, error);
  8846. const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
  8847. same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  8848. && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
  8849. && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
  8850. && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
  8851. }
  8852. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
  8853. step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
  8854. if (! same)
  8855. {
  8856. step ("result=FAILED project");
  8857. finish (1);
  8858. return;
  8859. }
  8860. }
  8861. auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
  8862. engine->stop();
  8863. engine->rewind();
  8864. engine->getMeters().capture.setSource (0);
  8865. engine->play();
  8866. auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
  8867. auto pull = std::make_shared<std::function<void()>>();
  8868. *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
  8869. if (engine == nullptr)
  8870. return;
  8871. engine->getMeters().capture.pull (*left, *right);
  8872. if (*pulls == 10) // the insert's editor while it plays (next to the report)
  8873. for (const auto scale : { 1.0f, 1.5f })
  8874. {
  8875. auto editor = inPatcher ? lynx::makeNodeEffectEditor (
  8876. *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
  8877. [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
  8878. : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
  8879. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  8880. {
  8881. juce::Graphics g (image);
  8882. g.fillAll (lynx::theme::panel);
  8883. editor->paintEntireComponent (g, false);
  8884. }
  8885. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
  8886. file.deleteFile();
  8887. juce::PNGImageFormat png;
  8888. if (auto stream = file.createOutputStream())
  8889. png.writeImageToStream (image, *stream);
  8890. }
  8891. if (--*pulls > 0)
  8892. {
  8893. juce::Timer::callAfterDelay (200, *pull);
  8894. return;
  8895. }
  8896. engine->stop();
  8897. const auto dropped = engine->getMeters().capture.droppedFrames();
  8898. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  8899. // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
  8900. auto peaksOf = [rate] (const std::vector<float>& x) {
  8901. std::vector<juce::int64> peaks;
  8902. for (std::size_t f = 1; f + 1 < x.size(); ++f)
  8903. 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])
  8904. && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
  8905. peaks.push_back ((juce::int64) f);
  8906. return peaks;
  8907. };
  8908. const auto wet = peaksOf (*left), dry = peaksOf (*right);
  8909. int pairs = 0;
  8910. juce::int64 worst = 0;
  8911. double gainSum = 0.0, residual = 0.0, energy = 0.0;
  8912. for (const auto w : wet)
  8913. {
  8914. 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); });
  8915. if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
  8916. continue;
  8917. ++pairs;
  8918. worst = std::max (worst, std::abs (*best - w));
  8919. gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
  8920. }
  8921. const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
  8922. // dry clicks with no wet click beside them (a dropout of the cable / device), listed
  8923. juce::String unmatched;
  8924. for (const auto d : dry)
  8925. if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
  8926. unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
  8927. if (unmatched.isNotEmpty())
  8928. step ("dry_clicks_without_wet=" + unmatched);
  8929. // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
  8930. for (const auto w : wet)
  8931. for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
  8932. {
  8933. const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
  8934. residual += d * d;
  8935. energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
  8936. }
  8937. const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
  8938. step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
  8939. + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
  8940. step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
  8941. auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
  8942. const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
  8943. step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
  8944. const auto excused = xruns > 0 ? 2 * xruns : 0;
  8945. const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
  8946. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  8947. // (round 165c) then the re-ping notice after a buffer size change
  8948. auto then = [this, ref, step, finish] (int code) {
  8949. if (code != 0)
  8950. finish (code);
  8951. else
  8952. runRepingCheck (ref, step, finish);
  8953. };
  8954. if (! ok)
  8955. {
  8956. finish (1);
  8957. return;
  8958. }
  8959. if (bounceFile == juce::File())
  8960. then (0);
  8961. else
  8962. runBounceCheck (bounceFile, step, then);
  8963. };
  8964. juce::Timer::callAfterDelay (200, *pull);
  8965. });
  8966. });
  8967. });
  8968. }
  8969. // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
  8970. // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
  8971. // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
  8972. // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
  8973. // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
  8974. // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
  8975. void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  8976. {
  8977. auto& devices = engine->getDeviceManager();
  8978. auto setup = devices.getAudioDeviceSetup();
  8979. const auto before = setup.bufferSize;
  8980. setup.bufferSize = before == 512 ? 256 : 512;
  8981. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  8982. step ("reping_device_error=" + error);
  8983. engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
  8984. juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
  8985. if (engine == nullptr)
  8986. return;
  8987. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  8988. const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
  8989. const auto notice = engine->takeHardwareInsertNotice();
  8990. step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
  8991. + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
  8992. if (notice.size() != 1 || ! (notice[0] == ref))
  8993. {
  8994. step ("result_reping=FAILED (no notice)");
  8995. finish (1);
  8996. return;
  8997. }
  8998. engine->pingHardwareInserts (notice); // ("Ping now")
  8999. juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
  9000. if (engine == nullptr)
  9001. return;
  9002. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  9003. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  9004. const auto stale = (int) engine->staleHardwareInserts().size();
  9005. step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
  9006. const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
  9007. step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
  9008. finish (ok ? 0 : 1);
  9009. });
  9010. });
  9011. }
  9012. void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  9013. {
  9014. // the Export window as the user sees it with the real-time option ticked (next to the report)
  9015. lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
  9016. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  9017. if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
  9018. {
  9019. std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
  9020. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
  9021. return t;
  9022. for (auto* child : c.getChildren())
  9023. if (auto* t = find (*child))
  9024. return t;
  9025. return nullptr;
  9026. };
  9027. if (auto* toggle = find (*w))
  9028. {
  9029. step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
  9030. toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
  9031. auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
  9032. if (c != nullptr)
  9033. {
  9034. const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
  9035. file.deleteFile();
  9036. juce::FileOutputStream out (file);
  9037. juce::PNGImageFormat png;
  9038. if (out.openedOk())
  9039. png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  9040. }
  9041. delete w;
  9042. break;
  9043. }
  9044. }
  9045. lynx::exportopts::Options o;
  9046. o.format = lynx::exportopts::Format::wav;
  9047. o.wavBits = 32;
  9048. o.dither = lynx::exportopts::DitherMode::none;
  9049. o.tail = lynx::exportopts::TailMode::cut;
  9050. o.range = lynx::exportopts::Range::song;
  9051. o.trimPdc = true;
  9052. o.hqAllPlugins = false;
  9053. o.pluginWarmUp = false;
  9054. const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
  9055. auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
  9056. o.sampleRate = engine->getTransport().sampleRate.load();
  9057. auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
  9058. struct Shared
  9059. {
  9060. std::atomic<int> done { 0 };
  9061. bool okRealtime = false, okOffline = false;
  9062. juce::String errorRealtime, errorOffline;
  9063. double lastProgress = 0.0;
  9064. double started = juce::Time::getMillisecondCounterHiRes();
  9065. };
  9066. auto shared = std::make_shared<Shared>();
  9067. // (the jobs stay owned by the message thread's poll below: they are destroyed there)
  9068. juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
  9069. shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
  9070. shared->okOffline = off->run ({}, shared->errorOffline);
  9071. shared->done.store (1);
  9072. });
  9073. auto poll = std::make_shared<std::function<void()>>();
  9074. *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
  9075. if (shared->done.load() == 0)
  9076. {
  9077. juce::Timer::callAfterDelay (100, *poll);
  9078. return;
  9079. }
  9080. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
  9081. step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
  9082. + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
  9083. + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
  9084. juce::AudioFormatManager formats;
  9085. formats.registerBasicFormats();
  9086. std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
  9087. if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
  9088. {
  9089. step ("result=FAILED bounce");
  9090. finish (1);
  9091. return;
  9092. }
  9093. const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
  9094. juce::AudioBuffer<float> x (2, frames), y (2, frames);
  9095. a->read (&x, 0, frames, 0, true, true);
  9096. b->read (&y, 0, frames, 0, true, true);
  9097. double residual = 0.0, energy = 0.0, wetDry = 0.0;
  9098. for (int ch = 0; ch < 2; ++ch)
  9099. for (int i = 0; i < frames; ++i)
  9100. {
  9101. const double d = x.getSample (ch, i) - y.getSample (ch, i);
  9102. residual += d * d;
  9103. energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
  9104. }
  9105. for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
  9106. wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
  9107. const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
  9108. step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
  9109. + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
  9110. + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
  9111. const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
  9112. step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
  9113. finish (ok ? 0 : 1);
  9114. };
  9115. juce::Timer::callAfterDelay (100, *poll);
  9116. }
  9117. // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
  9118. // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
  9119. juce::String finishStressTake (const juce::File& target, double seconds)
  9120. {
  9121. juce::String text;
  9122. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  9123. text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
  9124. if (device != nullptr)
  9125. text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
  9126. engine->setRecording (false); // closes the take: a clip of the song
  9127. juce::File take;
  9128. for (const auto& c : engine->getSong().channels)
  9129. if (c.instrument == lynx::InstrumentKind::audioClip)
  9130. take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
  9131. if (! take.existsAsFile())
  9132. return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
  9133. target.deleteFile();
  9134. if (! take.moveFileTo (target))
  9135. take.copyFileTo (target);
  9136. juce::AudioFormatManager formats;
  9137. formats.registerBasicFormats();
  9138. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
  9139. {
  9140. juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
  9141. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
  9142. const auto peak = audio.getMagnitude (0, audio.getNumSamples());
  9143. const auto length = (double) reader->lengthInSamples / reader->sampleRate;
  9144. text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
  9145. << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
  9146. << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
  9147. }
  9148. else
  9149. text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
  9150. return text;
  9151. }
  9152. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  9153. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  9154. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  9155. {
  9156. lynx::AudioEngine offline (false);
  9157. const juce::File input (inputPath);
  9158. juce::String error, report;
  9159. bool ok = false;
  9160. if (input.hasFileExtension ("flp;als;flm;songtmpl"))
  9161. ok = offline.importFlpFile (input, error);
  9162. else if (auto song = lynx::ProjectFile::load (input, error))
  9163. {
  9164. offline.setSong (std::move (*song));
  9165. ok = true;
  9166. }
  9167. int samplers = 0, samplersLoaded = 0;
  9168. if (ok)
  9169. {
  9170. for (const auto& c : offline.getSong().channels)
  9171. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  9172. {
  9173. ++samplers;
  9174. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  9175. }
  9176. const juce::File output (outputPath);
  9177. output.deleteFile();
  9178. juce::WavAudioFormat wav;
  9179. std::unique_ptr<juce::AudioFormatWriter> writer (
  9180. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  9181. if (writer == nullptr)
  9182. {
  9183. ok = false;
  9184. error = lynx::utf8 ("could not create ") + outputPath;
  9185. }
  9186. else
  9187. {
  9188. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  9189. report << "peak=" << peak << "\n";
  9190. ok = peak > 0.001f;
  9191. }
  9192. }
  9193. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  9194. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  9195. juce::File (outputPath + ".txt").replaceWithText (report);
  9196. setApplicationReturnValue (ok ? 0 : 1);
  9197. quit();
  9198. }
  9199. // LYNX.exe --export-flp project.(lynx|flp|als) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
  9200. // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
  9201. // report goes to output.txt
  9202. void runAlsExport (const juce::String& inputPath, const juce::String& folderPath, bool live11, bool reference)
  9203. {
  9204. juce::String error;
  9205. juce::StringArray notes;
  9206. juce::File als;
  9207. {
  9208. lynx::AudioEngine loader (false);
  9209. const juce::File input (inputPath);
  9210. bool ok = false;
  9211. // --scan: the targeted plugin scan an open runs first (child processes), so the set's plugins load
  9212. if (juce::JUCEApplication::getCommandLineParameterArray().contains ("--scan") && input.hasFileExtension ("flp;als;flm;songtmpl"))
  9213. {
  9214. juce::MemoryBlock data;
  9215. if (input.loadFileAsData (data))
  9216. {
  9217. const std::vector<std::uint8_t> bytes (static_cast<const std::uint8_t*> (data.getData()),
  9218. static_cast<const std::uint8_t*> (data.getData()) + data.getSize());
  9219. try
  9220. {
  9221. const auto uses = input.hasFileExtension ("als") ? lynx::alsForeignPlugins (bytes)
  9222. : lynx::flpForeignPlugins (flp::parseProject ({ bytes.data(), bytes.size() }));
  9223. loader.getPluginHost().scanFiles (loader.getPluginHost().filesToScanFor (uses), {});
  9224. }
  9225. catch (const std::exception&)
  9226. {
  9227. }
  9228. }
  9229. }
  9230. if (input.hasFileExtension ("flp;als;flm;songtmpl"))
  9231. ok = loader.importFlpFile (input, error);
  9232. else if (auto song = lynx::ProjectFile::load (input, error))
  9233. {
  9234. loader.setSong (std::move (*song));
  9235. ok = true;
  9236. }
  9237. if (ok)
  9238. {
  9239. loader.capturePluginStates();
  9240. const juce::File folder (folderPath);
  9241. folder.createDirectory();
  9242. als = lynx::writeAlsProject (loader.getSong(), &loader.getPluginHost(), live11 ? lynx::AlsVersion::live11 : lynx::AlsVersion::live12, ! reference, folder,
  9243. input.getFileNameWithoutExtension(), notes, error);
  9244. }
  9245. }
  9246. juce::String report;
  9247. report << (als != juce::File() ? "ok " + als.getFullPathName() : "error=" + error) << "\n" << notes.joinIntoString ("\n") << "\n";
  9248. juce::File (folderPath).getChildFile ("export-als.txt").replaceWithText (report);
  9249. setApplicationReturnValue (als != juce::File() ? 0 : 1);
  9250. quit();
  9251. }
  9252. // --versionsshot <prefix> (round 190ap): everything the round adds, offscreen (no window on the desktop):
  9253. // -versions.png / -versions-unsaved.png the Versions panel (a project with versions, backups and labels; a new one)
  9254. // -menu-file.png / -menu-file-pluginsoff.png the File menu, and as it is while the plugins are off
  9255. // -pluginsoff-window.png / -pluginsoff-mixer.png a project opened without its third-party plugins (the tags)
  9256. // -pluginsoff-panel.png / -pluginsoff-panel-one.png the list, all off, then after "Switch on" for one
  9257. // -export-default.png / -export.png the Export window as it opens, and with the additions in use
  9258. void runVersionsShot (const juce::String& prefix)
  9259. {
  9260. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9261. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  9262. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  9263. };
  9264. // ---- the Versions panel, on files in a temporary folder
  9265. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  9266. .getChildFile ("lynx-versionsshot-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  9267. const juce::ScopeGuard cleanUp { [&root] { root.deleteRecursively(); } };
  9268. const auto project = root.getChildFile ("Night Drive"), backup = root.getChildFile ("Backup");
  9269. project.createDirectory();
  9270. backup.createDirectory();
  9271. const auto now = juce::Time::getCurrentTime();
  9272. const auto put = [&now] (const juce::File& folder, const juce::String& name, const char* kind, int kilobytes, double hoursAgo) {
  9273. const auto time = now - juce::RelativeTime::hours (hoursAgo);
  9274. const auto file = folder.getChildFile (kind == nullptr ? name + ".lynx" : name + " (" + kind + " on " + time.formatted ("%Y-%m-%d at %Hh%M") + ").lynx");
  9275. juce::MemoryBlock data ((size_t) kilobytes * 1024, true);
  9276. file.replaceWithData (data.getData(), data.getSize());
  9277. file.setLastModificationTime (time);
  9278. };
  9279. put (project, "Night Drive", nullptr, 412, 26.0 * 24.0);
  9280. put (project, "Night Drive_2", nullptr, 688, 9.0 * 24.0);
  9281. put (project, "Night Drive_3", nullptr, 731, 2.0 * 24.0);
  9282. put (project, "Night Drive_4", nullptr, 905, 1.6);
  9283. put (backup, "Night Drive_4", "autosaved", 907, 0.07);
  9284. put (backup, "Night Drive_4", "autosaved", 906, 0.4);
  9285. put (backup, "Night Drive_4", "overwritten", 890, 1.6);
  9286. put (backup, "Night Drive_4", "autosaved", 884, 3.2);
  9287. put (backup, "Night Drive_3", "overwritten", 720, 2.0 * 24.0);
  9288. put (backup, "Night Drive_2", "autosaved", 690, 8.0 * 24.0);
  9289. const lynx::VersionsContext context { project.getChildFile ("Night Drive_4.lynx"), "Night Drive_4", backup, ".lynx" };
  9290. {
  9291. const auto entries = lynx::versionEntries (context);
  9292. const auto label = [&] (const juce::String& startsWith, const char* text) {
  9293. for (const auto& e : entries)
  9294. if (juce::String::fromUTF8 (e.name.c_str()).startsWith (startsWith))
  9295. {
  9296. lynx::setVersionLabel (context, e, text);
  9297. return;
  9298. }
  9299. };
  9300. label ("Night Drive_2", "first full arrangement");
  9301. label ("Night Drive_3", "sent to the singer");
  9302. label ("Night Drive_4 (autosaved", "new bass line");
  9303. }
  9304. {
  9305. lynx::VersionsActions actions;
  9306. actions.context = [context] { return context; };
  9307. auto panel = lynx::makeVersionsPanel (actions);
  9308. shoot (*panel, "versions");
  9309. lynx::VersionsActions fresh;
  9310. fresh.context = [backup] { return lynx::VersionsContext { juce::File(), "Untitled", backup, ".lynx" }; };
  9311. auto empty = lynx::makeVersionsPanel (fresh);
  9312. shoot (*empty, "versions-unsaved");
  9313. }
  9314. // ---- the window
  9315. lynx::AudioEngine offline (false);
  9316. lynx::MainComponent ui (offline, false);
  9317. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  9318. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  9319. const auto saveFileMenu = [&] (const char* name) {
  9320. const auto index = juce::jmax (0, ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("File")));
  9321. saveMenus (juce::StringArray { lynx::tr ("File") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-" + name + ".png");
  9322. };
  9323. saveFileMenu ("menu-file");
  9324. // ---- a project opened without its third-party plugins (the plugins are not installed: nothing foreign runs)
  9325. {
  9326. const auto ref = [] (const char* id, const char* name) {
  9327. lynx::PluginRef r;
  9328. r.id = id;
  9329. r.name = name;
  9330. r.state = "c2V0dGluZ3M=";
  9331. return r;
  9332. };
  9333. auto song = lynx::Song::makeDefault();
  9334. while (song.channels.size() < 4)
  9335. song.channels.push_back (song.channels.front());
  9336. while (song.mixer.size() < 5)
  9337. song.mixer.push_back (song.mixer.back());
  9338. const char* names[] = { "Lead", "Pad" };
  9339. for (int c = 0; c < 2; ++c)
  9340. {
  9341. auto& channel = song.channels[(std::size_t) (c + 2)];
  9342. channel.instrument = lynx::InstrumentKind::plugin;
  9343. channel.plugin = ref ("VST3-ShotSynth-11111111-aaaaaaaa", "Shot Synth");
  9344. channel.name = names[c];
  9345. channel.mixerTrack = c + 1;
  9346. }
  9347. lynx::EffectSlot fx;
  9348. fx.kind = lynx::EffectKind::plugin;
  9349. fx.plugin = ref ("VST3-ShotVerb-22222222-bbbbbbbb", "Shot Verb");
  9350. song.mixer[1].effects.push_back (fx);
  9351. fx.plugin = ref ("VST3-ShotComp-33333333-cccccccc", "Shot Comp");
  9352. song.mixer[2].effects.push_back (fx);
  9353. song.mixer[0].effects.push_back (fx);
  9354. offline.setSongWithPluginsOff (std::move (song));
  9355. ui.showDesktopForSnapshot (false);
  9356. shoot (ui, "pluginsoff-window");
  9357. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  9358. shoot (ui, "pluginsoff-mixer"); // (the rack's and the mixer's "off" tags together)
  9359. saveFileMenu ("menu-file-pluginsoff");
  9360. auto panel = lynx::makePluginsOffPanel (offline);
  9361. shoot (*panel, "pluginsoff-panel");
  9362. offline.switchPluginOn ("VST3-ShotVerb-22222222-bbbbbbbb"); // (not installed: "Did not load")
  9363. auto after = lynx::makePluginsOffPanel (offline);
  9364. shoot (*after, "pluginsoff-panel-one");
  9365. }
  9366. // ---- the Export window: as it opens, and with a preset chosen, sections on and a last export to repeat
  9367. {
  9368. auto song = lynx::Song::makeDefault();
  9369. const auto bar = (std::int64_t) lynx::ppq * song.beatsPerBar;
  9370. song.mode = lynx::PlayMode::song;
  9371. song.playlist.clear();
  9372. lynx::Clip clip;
  9373. clip.length = 32 * bar;
  9374. song.playlist.push_back (clip);
  9375. const char* sections[] = { "Intro", "Verse", "Chorus", "Outro" };
  9376. for (int i = 0; i < 4; ++i)
  9377. {
  9378. lynx::Marker m;
  9379. m.tick = i * 8 * bar;
  9380. m.name = sections[i];
  9381. song.addMarker (m);
  9382. }
  9383. offline.setSong (std::move (song)); // (also ends the plugins-off mode)
  9384. auto plain = lynx::makeExportPanel (offline, 0);
  9385. shoot (*plain, "export-default");
  9386. auto additions = lynx::makeExportPanelWithAdditions (offline);
  9387. shoot (*additions, "export");
  9388. }
  9389. }
  9390. void runGamepadShot (const juce::String& prefix)
  9391. {
  9392. juce::String report;
  9393. int failures = 0;
  9394. {
  9395. lynx::AudioEngine engine (false);
  9396. auto hints = lynx::makeGamepadHints();
  9397. savePng (hints->createComponentSnapshot (hints->getLocalBounds()), prefix + "-hints.png");
  9398. auto prefs = engine.getMidiPrefs();
  9399. prefs.gamepad = true;
  9400. engine.setMidiPrefs (prefs, false);
  9401. auto page = lynx::makeMidiPage (engine, {}, false);
  9402. page->setSize (760, 1400);
  9403. savePng (page->createComponentSnapshot (page->getLocalBounds()), prefix + "-settings.png");
  9404. // the poller with fake states: what the handler gets
  9405. using namespace lynx::gamepad;
  9406. std::vector<std::string> got;
  9407. lynx::GamepadInput input ([&got] (const Changes& c, const State&, double dt) {
  9408. for (int i = 0; i < c.pressedCount; ++i)
  9409. got.push_back (std::string ("press ") + buttonName (c.pressed[(std::size_t) i]));
  9410. for (int i = 0; i < c.releasedCount; ++i)
  9411. got.push_back (std::string ("release ") + buttonName (c.released[(std::size_t) i]));
  9412. for (int i = 0; i < c.controllerCount; ++i)
  9413. got.push_back ("cc " + std::to_string (c.controller[(std::size_t) i]) + "=" + std::to_string (c.value[(std::size_t) i]));
  9414. if (c.connectedChanged)
  9415. got.push_back ("connected changed");
  9416. got.push_back ("dt " + std::to_string ((int) std::lround (dt * 1000)));
  9417. });
  9418. State pad;
  9419. pad.connected = true;
  9420. input.inject (pad, 1.0 / 60.0);
  9421. pad.buttons = mask (Button::a);
  9422. pad.rightTrigger = 255;
  9423. input.inject (pad, 1.0 / 60.0);
  9424. pad.buttons = 0;
  9425. input.inject (pad, 1.0 / 60.0);
  9426. const std::vector<std::string> expected { "connected changed", "dt 17", "press A", "cc 102=127", "cc 21=127", "dt 17",
  9427. "release A", "cc 102=0", "dt 17" };
  9428. for (const auto& line : got)
  9429. report << line << "\n";
  9430. if (got != expected)
  9431. {
  9432. ++failures;
  9433. report << "FAILED: the poller's changes differ from the expected ones\n";
  9434. }
  9435. report << "xinput " << (input.available() ? "loaded" : "not available") << "\n";
  9436. }
  9437. report << (failures == 0 ? "gamepad OK" : "gamepad FAILED") << "\n";
  9438. juce::File (prefix + "-gamepad.txt").replaceWithText (report);
  9439. setApplicationReturnValue (failures == 0 ? 0 : 1);
  9440. quit();
  9441. }
  9442. void runBundleExport (const juce::String& inputPath, const juce::String& folderPath, bool zip, bool mixdown, const juce::String& shotPrefix)
  9443. {
  9444. juce::String error;
  9445. bool ok = false;
  9446. lynx::otherapps::Result result;
  9447. {
  9448. lynx::AudioEngine loader (false);
  9449. const juce::File input (inputPath);
  9450. if (input.hasFileExtension ("flp;als"))
  9451. ok = loader.importFlpFile (input, error);
  9452. else if (auto song = lynx::ProjectFile::load (input, error))
  9453. {
  9454. loader.setSong (std::move (*song));
  9455. ok = true;
  9456. }
  9457. if (ok)
  9458. {
  9459. loader.capturePluginStates();
  9460. lynx::otherapps::Context context;
  9461. context.host = &loader.getPluginHost();
  9462. context.flOptions = lynx::flstudio::optionsFor (context.host, lynx::flpexport::LynxOnly::renderAudio, loader.getSong());
  9463. context.render = [] (const lynx::Song& s, const lynx::exportopts::Options& o, const juce::File& file,
  9464. const std::function<bool (double)>& progress, juce::String& err) {
  9465. lynx::ExportJob job (s, o, file);
  9466. return job.run (progress, err);
  9467. };
  9468. context.onMessageThread = [] (std::function<void()> f) { f(); };
  9469. lynx::exportbundle::Options options;
  9470. options.zip = zip;
  9471. options.mixdown = mixdown;
  9472. const auto name = input.getFileNameWithoutExtension();
  9473. const auto shot = [&shotPrefix] (juce::Component& c, const juce::String& suffix) {
  9474. if (shotPrefix.isNotEmpty())
  9475. savePng (c.createComponentSnapshot (c.getLocalBounds()), shotPrefix + suffix);
  9476. };
  9477. if (auto panel = lynx::makeOtherAppsExportPanel (loader, name))
  9478. shot (*panel, "-panel.png");
  9479. ok = lynx::otherapps::write (loader.getSong(), name, options, juce::File (folderPath), context, result);
  9480. if (auto report = lynx::makeOtherAppsReportPanel (result.folder, result.written, result.failed))
  9481. shot (*report, "-report.png");
  9482. }
  9483. }
  9484. juce::String report;
  9485. report << (ok ? "ok " + result.folder.getFullPathName() : "error=" + error) << "\n";
  9486. for (const auto& w : result.written)
  9487. report << "written " << w << "\n";
  9488. for (const auto& f : result.failed)
  9489. report << "failed " << f << "\n";
  9490. juce::File (folderPath).getChildFile ("export-bundle.txt").replaceWithText (report);
  9491. setApplicationReturnValue (ok && result.failed.isEmpty() ? 0 : 1);
  9492. quit();
  9493. }
  9494. void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
  9495. {
  9496. juce::String error;
  9497. bool ok = false;
  9498. lynx::flstudio::Written written;
  9499. {
  9500. lynx::AudioEngine loader (false);
  9501. const juce::File input (inputPath);
  9502. // a Live set opens through the same import as an .flp (as File › Open does, and --export-als accepts an .flp)
  9503. if (input.hasFileExtension ("flp;als"))
  9504. ok = loader.importFlpFile (input, error);
  9505. else if (auto song = lynx::ProjectFile::load (input, error))
  9506. {
  9507. loader.setSong (std::move (*song));
  9508. ok = true;
  9509. }
  9510. if (ok)
  9511. {
  9512. const juce::File output (outputPath);
  9513. const auto zip = output.hasFileExtension ("zip");
  9514. const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
  9515. loader.capturePluginStates();
  9516. auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
  9517. // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
  9518. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
  9519. options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
  9520. const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
  9521. : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
  9522. ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
  9523. [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
  9524. const std::function<bool (double)>& progress, juce::String& err) {
  9525. lynx::ExportJob job (s, settings, wav);
  9526. return job.run (progress, err);
  9527. },
  9528. {}, written, error);
  9529. if (zip)
  9530. renderDir.deleteRecursively();
  9531. }
  9532. }
  9533. juce::String report;
  9534. report << (ok ? "ok" : "error=" + error) << "\n"
  9535. << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
  9536. << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
  9537. << " samples=" << written.samples << "\n\n"
  9538. << lynx::flstudio::reportText (written) << "\n";
  9539. juce::File (outputPath + ".txt").replaceWithText (report);
  9540. setApplicationReturnValue (ok ? 0 : 1);
  9541. quit();
  9542. }
  9543. // LYNX.exe --export project.(flp|als|lynx) output.(wav|flac|ogg|mp3) [--pattern] [--insert N] [--rate N]
  9544. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail.
  9545. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  9546. {
  9547. juce::String error, report;
  9548. bool ok = false;
  9549. const auto started = juce::Time::getMillisecondCounterHiRes();
  9550. lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
  9551. {
  9552. lynx::AudioEngine loader (false);
  9553. const juce::File input (inputPath);
  9554. // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
  9555. if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
  9556. {
  9557. juce::MemoryBlock data;
  9558. if (input.loadFileAsData (data))
  9559. try
  9560. {
  9561. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  9562. auto& host = loader.getPluginHost();
  9563. const auto listed = std::chrono::steady_clock::now();
  9564. const auto files = host.filesToScanFor (uses);
  9565. lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
  9566. report << "scanned=" << files.joinIntoString (";") << "\n";
  9567. const auto scanned = std::chrono::steady_clock::now();
  9568. host.scanFiles (files, {});
  9569. lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
  9570. }
  9571. catch (const flp::Error&)
  9572. {
  9573. }
  9574. }
  9575. if (input.hasFileExtension ("flp;als")) // a Live set opens through the same import (round 182b)
  9576. ok = loader.importFlpFile (input, error);
  9577. else if (auto song = lynx::ProjectFile::load (input, error))
  9578. {
  9579. loader.setSong (std::move (*song));
  9580. ok = true;
  9581. }
  9582. if (ok)
  9583. {
  9584. const juce::File output (outputPath);
  9585. lynx::ExportSettings settings;
  9586. settings.wholeSong = ! patternOnly;
  9587. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  9588. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  9589. : lynx::ExportSettings::Format::wav24;
  9590. // --insert N: only that insert's output (what "Render to audio" records)
  9591. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  9592. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  9593. loader.editSong ([] (lynx::Song& s) {
  9594. for (auto& t : s.mixer)
  9595. t.effects.clear();
  9596. }, false);
  9597. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  9598. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  9599. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  9600. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  9601. // .mp3: the Export window's MP3 (320 kbps); everything else as before
  9602. auto options = settings.toOptions();
  9603. // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
  9604. if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
  9605. options.saveTempo = true;
  9606. // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
  9607. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
  9608. options.pluginWarmUp = false;
  9609. // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
  9610. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
  9611. if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
  9612. options.sampleRate = rate;
  9613. if (output.hasFileExtension ("mp3"))
  9614. {
  9615. options.format = lynx::exportopts::Format::mp3;
  9616. options.mp3Kbps = 320;
  9617. }
  9618. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
  9619. job.setExtraData (true);
  9620. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  9621. lynx::loadtrace::end();
  9622. int lastPercent = -1;
  9623. ok = job.run ([&lastPercent] (double p) {
  9624. lastPercent = (int) (p * 100.0);
  9625. return true;
  9626. }, error);
  9627. auto joined = [] (const std::map<std::string, int>& items) {
  9628. juce::StringArray names;
  9629. for (const auto& [name, count] : items)
  9630. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  9631. return names.joinIntoString (", ");
  9632. };
  9633. const auto& importReport = loader.getImportReport();
  9634. report << "converted=" << joined (importReport.converted) << "\n"
  9635. << "approximated=" << joined (importReport.approximated) << "\n"
  9636. << "unsupported=" << joined (importReport.unsupported) << "\n"
  9637. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  9638. << "partial_effects=" << joined (importReport.partialEffects) << "\n"
  9639. << "missing_samples=" << importReport.missingSamples << "\n";
  9640. // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
  9641. for (const auto& line : loader.getMatchedPlugins())
  9642. report << "plugin_found=" << line << "\n";
  9643. for (const auto& m : loader.getMissingPluginDetails())
  9644. report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
  9645. << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
  9646. {
  9647. const auto& song = loader.getSong();
  9648. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  9649. {
  9650. const auto& track = song.mixer[t];
  9651. if (track.effects.empty() && track.sends.empty())
  9652. continue;
  9653. report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
  9654. << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
  9655. for (const auto& s : track.sends)
  9656. report << " send>" << s.target << "@" << juce::String (s.level, 3);
  9657. report << " |";
  9658. for (const auto& fx : track.effects)
  9659. report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
  9660. : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
  9661. << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
  9662. << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
  9663. report << "\n";
  9664. }
  9665. }
  9666. report << juce::String (lynx::loadtrace::reportLines());
  9667. lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
  9668. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  9669. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  9670. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  9671. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  9672. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  9673. << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
  9674. << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
  9675. << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
  9676. << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
  9677. << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
  9678. << "song_seconds=" << job.getMusicSeconds() << "\n"
  9679. << "peak=" << job.getPeak() << "\n"
  9680. << "final_progress=" << lastPercent << "\n"
  9681. << "bytes=" << output.getSize() << "\n";
  9682. ok = ok && job.getPeak() > 0.001f;
  9683. }
  9684. }
  9685. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  9686. juce::File (outputPath + ".txt").replaceWithText (report);
  9687. setApplicationReturnValue (ok ? 0 : 1);
  9688. quit();
  9689. }
  9690. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  9691. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  9692. // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
  9693. struct EditorCpuRun final : juce::Timer
  9694. {
  9695. struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
  9696. std::vector<Case> cases;
  9697. std::size_t at = 0;
  9698. int phase = 0;
  9699. double t0 = 0.0, c0 = 0.0;
  9700. juce::String report;
  9701. juce::File out;
  9702. std::unique_ptr<lynx::AudioEngine> engine;
  9703. std::unique_ptr<juce::DocumentWindow> window;
  9704. std::function<void()> done;
  9705. void start()
  9706. {
  9707. engine = std::make_unique<lynx::AudioEngine> (false);
  9708. report << "editor\tmode\tcpu % of one core\n";
  9709. open();
  9710. startTimer (250);
  9711. }
  9712. void open()
  9713. {
  9714. window.reset();
  9715. if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
  9716. const auto& c = cases[at];
  9717. lynx::Song song;
  9718. song.mixer.resize (2);
  9719. song.mixer[0].name = "Master";
  9720. song.mixer[1].name = "Insert 1";
  9721. song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
  9722. engine->setSong (std::move (song));
  9723. engine->dispatchPendingMessages();
  9724. lynx::setNativeEditorDemo (c.demo);
  9725. auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
  9726. : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
  9727. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
  9728. window->setUsingNativeTitleBar (true);
  9729. window->setContentOwned (editor.release(), true);
  9730. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  9731. window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
  9732. window->setVisible (true);
  9733. phase = 0;
  9734. t0 = juce::Time::getMillisecondCounterHiRes();
  9735. }
  9736. void timerCallback() override
  9737. {
  9738. const auto now = juce::Time::getMillisecondCounterHiRes();
  9739. if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
  9740. if (phase == 1 && now - t0 > 8000.0)
  9741. {
  9742. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  9743. const auto& c = cases[at];
  9744. report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
  9745. ++at;
  9746. open();
  9747. }
  9748. }
  9749. };
  9750. std::unique_ptr<EditorCpuRun> editorCpu;
  9751. void runEditorCpu (const juce::String& path)
  9752. {
  9753. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9754. editorCpu = std::make_unique<EditorCpuRun>();
  9755. editorCpu->out = juce::File (path);
  9756. using K = lynx::EffectKind;
  9757. for (const auto demo : { false, true })
  9758. for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
  9759. { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
  9760. { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
  9761. { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
  9762. editorCpu->cases.push_back (c);
  9763. editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
  9764. editorCpu->start();
  9765. }
  9766. struct ParityShow
  9767. {
  9768. std::unique_ptr<lynx::AudioEngine> engine;
  9769. std::unique_ptr<juce::Component> editor;
  9770. std::unique_ptr<juce::DocumentWindow> window;
  9771. ~ParityShow() { window.reset(); editor.reset(); engine.reset(); }
  9772. };
  9773. std::shared_ptr<ParityShow> parityShow;
  9774. bool parityShotFailed = false; // --parityshot: the effect name matched no built-in effect
  9775. void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
  9776. {
  9777. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9778. int kindIndex = -1;
  9779. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  9780. if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
  9781. kindIndex = k;
  9782. if (kindIndex < 0)
  9783. {
  9784. // round tp172b7: say so and fail (a silent exit 0 hid a split effect name in a launch script)
  9785. std::fprintf (stderr, "unknown effect: %s\n", effectName.toRawUTF8());
  9786. std::fflush (stderr);
  9787. parityShotFailed = true;
  9788. return;
  9789. }
  9790. const auto kind = (lynx::EffectKind) kindIndex;
  9791. auto fx = lynx::makeEffectSlot (kind);
  9792. if (paramsFile.isNotEmpty())
  9793. for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
  9794. {
  9795. const auto t = juce::StringArray::fromTokens (line, " \t", "");
  9796. const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
  9797. if (index >= 0 && index < lynx::maxEffectParams)
  9798. fx.params[(std::size_t) index] = t[1].getFloatValue();
  9799. }
  9800. auto offlineOwner = std::make_unique<lynx::AudioEngine> (false); // (kept alive by LYNX_PARITYSHOT_SHOW's window)
  9801. auto& offline = *offlineOwner;
  9802. auto song = lynx::Song::makeDefault();
  9803. song.mixer.resize (2);
  9804. song.mixer[0].name = "Master";
  9805. song.mixer[1].name = "Insert 1";
  9806. song.mixer[1].effects.assign (1, fx);
  9807. for (auto& c : song.channels)
  9808. c.mixerTrack = 1;
  9809. offline.setSong (std::move (song));
  9810. offline.dispatchPendingMessages();
  9811. const bool facet = kind == lynx::EffectKind::facetEq;
  9812. // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
  9813. // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
  9814. const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
  9815. // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
  9816. const bool pro = lynx::ProEditorWindows::handles (kind)
  9817. && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
  9818. auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  9819. : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  9820. if (editor == nullptr)
  9821. return;
  9822. if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
  9823. {
  9824. lynx::AudioEngine::RenderOptions o;
  9825. o.seconds = 3.0;
  9826. o.sampleRate = 48000.0;
  9827. o.pluginWarmUp = false;
  9828. int sinceTick = 0;
  9829. o.capture = [&] (const float*, const float*, int n) {
  9830. sinceTick += n;
  9831. if (sinceTick < 1600) return;
  9832. sinceTick = 0;
  9833. if (facet) lynx::tickFacetEqEditor (*editor);
  9834. else lynx::tickNativeEffectEditor (*editor);
  9835. };
  9836. offline.renderOffline (o);
  9837. }
  9838. // round tp172b5: LYNX_PARITYSHOT_CLICKS drives the editor before the picture (the originals' pictures have their
  9839. // panels open), tokens in order: "x,y" a click, then the pointer leaves; "h:x,y" the pointer rests there (a hover);
  9840. // "d:x,y,x2,y2" a drag from there to there, the button still down in the picture
  9841. for (const auto& token : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_CLICKS", {}), " ", ""))
  9842. {
  9843. const auto hover = token.startsWith ("h:"), drag = token.startsWith ("d:");
  9844. const auto xy = juce::StringArray::fromTokens (hover || drag ? token.substring (2) : token, ",", "");
  9845. if (xy.size() < (drag ? 4 : 2))
  9846. continue;
  9847. const juce::Point<int> at (xy[0].getIntValue(), xy[1].getIntValue());
  9848. editor->setVisible (true); // (getComponentAt finds nothing in a hidden component; it never goes on screen)
  9849. auto* target = editor->getComponentAt (at);
  9850. if (target == nullptr)
  9851. continue;
  9852. const auto local = target->getLocalPoint (editor.get(), at).toFloat();
  9853. const auto now = juce::Time::getCurrentTime();
  9854. auto source = juce::Desktop::getInstance().getMainMouseSource();
  9855. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  9856. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods, bool dragged) {
  9857. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, local, now, 1, dragged);
  9858. };
  9859. target->mouseMove (event (local, {}, false));
  9860. if (hover)
  9861. continue;
  9862. target->mouseDown (event (local, left, false));
  9863. if (drag)
  9864. {
  9865. const auto end = target->getLocalPoint (editor.get(), juce::Point<int> (xy[2].getIntValue(), xy[3].getIntValue())).toFloat();
  9866. target->mouseDrag (event (end, left, true));
  9867. continue;
  9868. }
  9869. target->mouseUp (event (local, {}, false));
  9870. target->mouseExit (event ({ -1000.0f, -1000.0f }, {}, false));
  9871. }
  9872. // round tp172b6: LYNX_PARITYSHOT_SHOW=1 puts the same editor in a real window and keeps it open (for a guarded GUI check
  9873. // of its pop-up menus, which the offscreen picture cannot hold); closing the window quits
  9874. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_SHOW", {}) == "1")
  9875. {
  9876. struct ShowWindow final : juce::DocumentWindow
  9877. {
  9878. ShowWindow() : juce::DocumentWindow ("LYNX parity check", juce::Colours::black, juce::DocumentWindow::closeButton) {}
  9879. void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }
  9880. };
  9881. parityShow = std::make_shared<ParityShow>();
  9882. parityShow->engine = std::move (offlineOwner);
  9883. parityShow->editor = std::move (editor);
  9884. auto window = std::make_unique<ShowWindow>();
  9885. window->setUsingNativeTitleBar (true);
  9886. window->setContentNonOwned (parityShow->editor.get(), true);
  9887. window->setTopLeftPosition (80, 80);
  9888. window->setVisible (true);
  9889. parityShow->window = std::move (window);
  9890. return;
  9891. }
  9892. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  9893. {
  9894. juce::Graphics g (image);
  9895. g.fillAll (lynx::theme::panel);
  9896. editor->paintEntireComponent (g, false);
  9897. }
  9898. const juce::File file (path);
  9899. file.deleteFile();
  9900. juce::PNGImageFormat png;
  9901. if (auto stream = file.createOutputStream())
  9902. png.writeImageToStream (image, *stream);
  9903. }
  9904. // an Audio Effect Rack shaped like Live's reference (REA_rodada183c §8): two chains with chain-select zones and fades,
  9905. // four named macros (one on a chain's volume, one on two parameters), two variations, every view open
  9906. static lynx::EffectSlot shotRack()
  9907. {
  9908. auto slot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  9909. auto& doc = slot.patcher;
  9910. doc.rack[0].chains[0].name = "Vocoder";
  9911. lynx::PatchNode vocoder, eq, verb;
  9912. vocoder.effect = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  9913. eq.effect = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  9914. verb.effect = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
  9915. const auto nVoc = lynx::rack::addDevice (doc, 0, vocoder);
  9916. const auto nEq = lynx::rack::addDevice (doc, 0, eq);
  9917. lynx::rack::addChain (doc, "dry bypass");
  9918. lynx::rack::addDevice (doc, 1, verb);
  9919. doc.rack[0].chains[0].select = { 0, 79, 0, 63 };
  9920. doc.rack[0].chains[1].select = { 32, 127, 48, 127 };
  9921. lynx::rack::setChainVolume (doc, 0, 0.33f);
  9922. lynx::rack::setChainVolume (doc, 1, 0.5f);
  9923. const char* names[] { "Sibilance", "Intensity", "Formant Shift", "Bright Level" };
  9924. for (int m = 0; m < 4; ++m)
  9925. doc.rack[0].macros[(std::size_t) m].name = names[m];
  9926. lynx::RackMapping vol;
  9927. vol.target = lynx::RackMapping::Target::chainVolume, vol.chain = 0, vol.min = 0.0f, vol.max = lynx::rack::unityVolume;
  9928. lynx::rack::map (doc, 0, vol);
  9929. lynx::RackMapping a, b, c, d;
  9930. a.node = nVoc, a.param = 0;
  9931. b.node = nVoc, b.param = 1, b.min = 0.2f, b.max = 0.8f;
  9932. c.node = nEq, c.param = 0, c.min = 0.3f, c.max = 0.9f;
  9933. d.node = nEq, d.param = 1;
  9934. lynx::rack::map (doc, 1, a);
  9935. lynx::rack::map (doc, 2, b);
  9936. lynx::rack::map (doc, 3, c);
  9937. lynx::rack::map (doc, 3, d);
  9938. lynx::rack::setMacro (doc, 0, 60.0f);
  9939. lynx::rack::setMacro (doc, 1, 40.0f);
  9940. lynx::rack::setMacro (doc, 2, 70.0f);
  9941. lynx::rack::setMacro (doc, 3, 86.0f);
  9942. lynx::rack::storeVariation (doc);
  9943. lynx::rack::renameVariation (doc, 0, "Verse");
  9944. lynx::rack::setMacro (doc, 3, 120.0f);
  9945. lynx::rack::storeVariation (doc);
  9946. lynx::rack::renameVariation (doc, 1, "Drop");
  9947. lynx::rack::launchVariation (doc, 0);
  9948. auto& r = doc.rack[0];
  9949. r.showMacros = r.showChains = r.showDevices = r.showVariations = true;
  9950. r.zoneEditor = 2;
  9951. r.selectedChain = 0;
  9952. lynx::rack::setSelector (doc, 56.0f);
  9953. lynx::rack::compile (doc);
  9954. return slot;
  9955. }
  9956. bool runRackShots (const juce::File& out, const juce::String& liveSet = {})
  9957. {
  9958. out.createDirectory();
  9959. lynx::AudioEngine offline (false);
  9960. auto save = [&] (juce::Component& c, const juce::String& name) {
  9961. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  9962. {
  9963. juce::Graphics g (image);
  9964. g.fillAll (lynx::theme::panel);
  9965. c.paintEntireComponent (g, false);
  9966. }
  9967. const auto f = out.getChildFile (name);
  9968. f.deleteFile();
  9969. juce::PNGImageFormat png;
  9970. if (auto stream = f.createOutputStream())
  9971. return png.writeImageToStream (image, *stream);
  9972. return false;
  9973. };
  9974. auto song = lynx::Song::makeDefault();
  9975. song.mixer.resize (3);
  9976. song.mixer[1].name = "Vocal Main";
  9977. auto slot = shotRack();
  9978. song.mixer[1].effects = { slot };
  9979. // an Instrument Rack: three chains split over the keyboard
  9980. lynx::ChannelDef inst;
  9981. inst.name = "Keys Rack";
  9982. inst.instrument = lynx::InstrumentKind::patcher;
  9983. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  9984. for (int k = 0; k < 3; ++k)
  9985. {
  9986. if (k > 0)
  9987. lynx::rack::addChain (inst.patcher);
  9988. lynx::PatchNode synth;
  9989. synth.generator = true;
  9990. synth.channel.instrument = lynx::InstrumentKind::synth;
  9991. synth.channel.name = "Synth";
  9992. lynx::rack::addDevice (inst.patcher, k, synth);
  9993. }
  9994. inst.patcher.rack[0].chains[0].key = { 0, 52, 0, 47 };
  9995. inst.patcher.rack[0].chains[1].key = { 48, 76, 53, 71 };
  9996. inst.patcher.rack[0].chains[2].key = { 72, 127, 77, 127 };
  9997. inst.patcher.rack[0].chains[0].name = "Low";
  9998. inst.patcher.rack[0].chains[1].name = "Mid";
  9999. inst.patcher.rack[0].chains[2].name = "High";
  10000. inst.patcher.rack[0].showChains = inst.patcher.rack[0].showDevices = true;
  10001. inst.patcher.rack[0].zoneEditor = 0;
  10002. lynx::rack::compile (inst.patcher);
  10003. song.channels.push_back (inst);
  10004. const auto channel = (int) song.channels.size() - 1;
  10005. offline.setSong (std::move (song));
  10006. offline.dispatchPendingMessages();
  10007. bool ok = true;
  10008. // [set.als]: a Live set's racks as LYNX imports them, the one with the most chains drawn with its title bar (the
  10009. // like-for-like pair with Live's own picture of that set)
  10010. if (liveSet.isNotEmpty())
  10011. {
  10012. juce::MemoryBlock bytes;
  10013. juce::File (liveSet).loadFileAsData (bytes);
  10014. const std::vector<std::uint8_t> data ((const std::uint8_t*) bytes.getData(), (const std::uint8_t*) bytes.getData() + bytes.getSize());
  10015. lynx::AlsImportOptions o;
  10016. o.common.projectFolder = juce::File (liveSet).getParentDirectory().getFullPathName().toStdString();
  10017. std::string error;
  10018. if (auto imported = lynx::importAls (data, o, &error))
  10019. {
  10020. int bestTrack = -1, bestSlot = -1;
  10021. std::size_t most = 0;
  10022. for (int t = 0; t < (int) imported->mixer.size(); ++t)
  10023. for (int s = 0; s < (int) imported->mixer[(std::size_t) t].effects.size(); ++s)
  10024. if (const auto& fx = imported->mixer[(std::size_t) t].effects[(std::size_t) s]; lynx::rack::isRack (fx) && fx.patcher.rack[0].chains.size() > most)
  10025. most = fx.patcher.rack[0].chains.size(), bestTrack = t, bestSlot = s;
  10026. if (bestTrack >= 0)
  10027. {
  10028. offline.setSong (std::move (*imported));
  10029. offline.dispatchPendingMessages();
  10030. auto view = lynx::RackWindows::makeSlotView (offline, bestTrack, bestSlot, true);
  10031. view->setSize (view->preferredWidth (228), 228);
  10032. ok = save (*view, "rack-live-import.png") && ok;
  10033. view->setMapMode (true);
  10034. view->setSize (view->preferredWidth (228), 228);
  10035. ok = save (*view, "rack-live-import-map.png") && ok;
  10036. return ok;
  10037. }
  10038. }
  10039. return false;
  10040. }
  10041. {
  10042. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, false);
  10043. view->setSize (view->preferredWidth (206), 206);
  10044. ok = save (*view, "rack-deviceview.png") && ok;
  10045. }
  10046. {
  10047. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, true);
  10048. view->setMapMode (true);
  10049. view->setSize (view->preferredWidth (228), 228);
  10050. ok = save (*view, "rack-mapmode.png") && ok;
  10051. }
  10052. {
  10053. auto view = lynx::RackWindows::makeChannelView (offline, channel, true);
  10054. view->setSize (view->preferredWidth (228), 228);
  10055. ok = save (*view, "rack-instrument.png") && ok;
  10056. }
  10057. return ok;
  10058. }
  10059. void runEq166fShots (const juce::String& folder)
  10060. {
  10061. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10062. const juce::File out (folder);
  10063. out.createDirectory();
  10064. lynx::AudioEngine offline (false);
  10065. auto save = [&] (juce::Component& editor, const juce::String& name) {
  10066. juce::Image image (juce::Image::ARGB, editor.getWidth(), editor.getHeight(), true);
  10067. {
  10068. juce::Graphics g (image);
  10069. g.fillAll (lynx::theme::panel);
  10070. editor.paintEntireComponent (g, false);
  10071. }
  10072. const auto f = out.getChildFile (name);
  10073. f.deleteFile();
  10074. juce::PNGImageFormat png;
  10075. if (auto stream = f.createOutputStream())
  10076. png.writeImageToStream (image, *stream);
  10077. };
  10078. // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
  10079. auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
  10080. auto song = lynx::Song::makeDefault();
  10081. song.mixer.resize (3);
  10082. song.mixer[0].name = "Master";
  10083. song.mixer[1].name = "Vocal";
  10084. song.mixer[2].name = "Reference mix";
  10085. song.mixer[1].effects.assign (1, fx);
  10086. for (std::size_t c = 0; c < song.channels.size(); ++c)
  10087. song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
  10088. return song;
  10089. };
  10090. auto feed = [&] (juce::Component& editor, bool facet, int frames) {
  10091. // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
  10092. lynx::AudioEngine::RenderOptions o;
  10093. o.seconds = frames / 30.0;
  10094. o.sampleRate = 48000.0;
  10095. o.pluginWarmUp = false;
  10096. int sinceTick = 0;
  10097. o.capture = [&] (const float*, const float*, int n) {
  10098. sinceTick += n;
  10099. if (sinceTick < 1600) return;
  10100. sinceTick = 0;
  10101. if (facet) lynx::tickFacetEqEditor (editor);
  10102. else lynx::tickNativeEffectEditor (editor);
  10103. };
  10104. offline.renderOffline (o);
  10105. if (facet) lynx::tickFacetEqEditor (editor);
  10106. else lynx::tickNativeEffectEditor (editor);
  10107. };
  10108. // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
  10109. auto& display = lynx::peqview::displaySettings();
  10110. const auto kept = display;
  10111. display.spectrum = display.heatmap = true;
  10112. display.position = 0;
  10113. 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" },
  10114. { 0.0, "peq2-heatmap-top.png" } })
  10115. {
  10116. auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  10117. eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
  10118. eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
  10119. display.position = juce::String (name).contains ("top") ? 1 : 0;
  10120. offline.setSong (songWith (eq, false));
  10121. offline.dispatchPendingMessages();
  10122. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
  10123. feed (*editor, false, 120);
  10124. save (*editor, name);
  10125. }
  10126. display = kept;
  10127. // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
  10128. {
  10129. using namespace lynx::facet;
  10130. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  10131. eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
  10132. eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
  10133. eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
  10134. eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
  10135. eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
  10136. eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
  10137. eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
  10138. eq.sidechain = 2;
  10139. for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
  10140. {
  10141. eq.params[(std::size_t) listenParam] = listenValue (l);
  10142. offline.setSong (songWith (eq, true));
  10143. offline.dispatchPendingMessages();
  10144. auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
  10145. feed (*editor, true, 90);
  10146. save (*editor, name);
  10147. }
  10148. }
  10149. }
  10150. void runDesign168rShots (const juce::String& folder)
  10151. {
  10152. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10153. const juce::File out (folder);
  10154. out.createDirectory();
  10155. lynx::AudioEngine offline (false);
  10156. using K = lynx::EffectKind;
  10157. for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
  10158. K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
  10159. K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
  10160. K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
  10161. {
  10162. const auto& bank = lynx::presets::factory (kind);
  10163. // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
  10164. std::optional<lynx::EffectSlot> flPreset;
  10165. if (kind == K::lovePhilter || kind == K::distructor)
  10166. {
  10167. const auto roots = lynx::findFlStudioRoots();
  10168. const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  10169. .getChildFile ("Patches/Plugin presets/Effects")
  10170. .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
  10171. juce::MemoryBlock bytes;
  10172. if (file.loadFileAsData (bytes))
  10173. flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
  10174. (const std::uint8_t*) bytes.getData() + bytes.getSize()));
  10175. }
  10176. for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
  10177. {
  10178. auto fx = lynx::makeEffectSlot (kind);
  10179. if (pass == 1 && flPreset)
  10180. fx = *flPreset;
  10181. else if (pass == 1)
  10182. {
  10183. fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
  10184. fx.presetName = bank.front().name;
  10185. }
  10186. lynx::Song song;
  10187. song.mixer.resize (2);
  10188. song.mixer[0].name = "Master";
  10189. song.mixer[1].name = "Insert 1";
  10190. song.mixer[1].effects.push_back (fx);
  10191. offline.setSong (std::move (song));
  10192. offline.dispatchPendingMessages();
  10193. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  10194. for (const auto scale : { 1.0f, 2.0f })
  10195. for (int page = 0; page < pages; ++page)
  10196. {
  10197. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
  10198. if (editor == nullptr)
  10199. continue;
  10200. juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
  10201. {
  10202. juce::Graphics g (image);
  10203. g.fillAll (lynx::theme::panel);
  10204. editor->paintEntireComponent (g, false);
  10205. }
  10206. // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
  10207. const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
  10208. + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
  10209. + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
  10210. + (scale > 1.5f ? "-200" : "-100") + ".png");
  10211. file.deleteFile();
  10212. juce::PNGImageFormat png;
  10213. if (auto stream = file.createOutputStream())
  10214. png.writeImageToStream (image, *stream);
  10215. }
  10216. }
  10217. }
  10218. }
  10219. bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
  10220. {
  10221. folder.createDirectory();
  10222. auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
  10223. juce::StringArray wanted;
  10224. wanted.addTokens (which, ",", "");
  10225. auto ok = true;
  10226. struct Shot
  10227. {
  10228. juce::String name;
  10229. std::optional<lynx::ChannelDef> channel;
  10230. };
  10231. std::vector<Shot> shots;
  10232. for (const auto& e : lynx::natives::instrumentEngines())
  10233. {
  10234. const auto name = key (e.name);
  10235. const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
  10236. if (! banked && ! wanted.contains (name))
  10237. continue;
  10238. auto channel = source == "fl" || source == "flm" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
  10239. : lynx::banks::defaultChannel (e.kind, e.name);
  10240. // (round 190u) source "flm": the channel as the .flm import makes it (Transistor Bass: FL Studio Mobile's build)
  10241. if (source == "flm" && channel && e.kind == lynx::InstrumentKind::transistorbass)
  10242. {
  10243. channel->pluginState = lynx::transistorBassFlmState ({ 1.0f, 0.0f, 1.0f, 1.0f, 0.1f, 1.0f, 0.1f, 0.0f, 0.0f, 0.3f, 0.5f, 0.0f, 0.0f, 0.0f }); // FLM's defaults
  10244. channel->modelParams = { 1.0f };
  10245. channel->samplePath.clear();
  10246. }
  10247. if (! channel)
  10248. {
  10249. std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
  10250. ok = false;
  10251. continue;
  10252. }
  10253. shots.push_back ({ name, std::move (channel) });
  10254. }
  10255. // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
  10256. if (wanted.contains ("autogun"))
  10257. {
  10258. if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
  10259. shots.push_back ({ "autogun", std::move (channel) });
  10260. else
  10261. {
  10262. std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
  10263. ok = false;
  10264. }
  10265. }
  10266. for (auto& shot : shots)
  10267. {
  10268. const auto& name = shot.name;
  10269. auto& channel = shot.channel;
  10270. lynx::AudioEngine offline (false);
  10271. lynx::Song song;
  10272. song.mixer = lynx::Song::defaultMixer (2);
  10273. song.channels.push_back (*channel);
  10274. song.patterns.emplace_back();
  10275. {
  10276. juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
  10277. lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
  10278. }
  10279. offline.setSong (std::move (song));
  10280. offline.dispatchPendingMessages();
  10281. auto frame = lynx::makeChannelFrame (offline, 0, 0);
  10282. if (frame == nullptr || frame->getWidth() <= 0)
  10283. {
  10284. ok = false;
  10285. continue;
  10286. }
  10287. for (const auto scale : { 1.0f, 1.5f, 2.0f })
  10288. {
  10289. const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  10290. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
  10291. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
  10292. }
  10293. // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
  10294. for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
  10295. {
  10296. lynx::showChannelLayoutPage (*frame, page);
  10297. const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
  10298. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
  10299. std::printf ("%s\n", file.getFullPathName().toRawUTF8());
  10300. }
  10301. }
  10302. return ok;
  10303. }
  10304. // --- round 170j: the pilot editors with their own art -------------------------------------------------
  10305. struct ArtPilot
  10306. {
  10307. std::string file; // the art's name as a file name: "toxic-biohazard"
  10308. bool instrument;
  10309. lynx::InstrumentKind instrumentKind;
  10310. lynx::EffectKind effectKind;
  10311. lynx::skin::Style before; // the automatic style it had before the Themed style
  10312. };
  10313. static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
  10314. {
  10315. static juce::StringArray only;
  10316. return only;
  10317. }
  10318. // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
  10319. // registries, so a new theme is shot without touching this list
  10320. static const std::vector<ArtPilot>& artPilots()
  10321. {
  10322. using I = lynx::InstrumentKind;
  10323. using E = lynx::EffectKind;
  10324. static const std::vector<ArtPilot> list = [] {
  10325. std::vector<ArtPilot> all;
  10326. auto slug = [] (lynx::skin::Art a) {
  10327. return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
  10328. };
  10329. for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
  10330. if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
  10331. all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
  10332. for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
  10333. if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
  10334. all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
  10335. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  10336. if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
  10337. all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
  10338. std::vector<ArtPilot> kept;
  10339. for (auto& p : all)
  10340. if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
  10341. if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
  10342. kept.push_back (p);
  10343. return kept;
  10344. }();
  10345. return list;
  10346. }
  10347. // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
  10348. static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
  10349. {
  10350. lynx::Song song;
  10351. song.mixer = lynx::Song::defaultMixer (2);
  10352. if (p.instrument)
  10353. {
  10354. for (const auto& e : lynx::natives::instrumentEngines())
  10355. if (e.kind == p.instrumentKind)
  10356. {
  10357. auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
  10358. if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
  10359. if (! channel) return nullptr;
  10360. song.channels.push_back (*channel);
  10361. break;
  10362. }
  10363. if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
  10364. {
  10365. const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
  10366. auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
  10367. if (! channel)
  10368. {
  10369. channel = lynx::ChannelDef {};
  10370. channel->instrument = p.instrumentKind;
  10371. channel->name = name;
  10372. }
  10373. song.channels.push_back (*channel);
  10374. }
  10375. song.patterns.emplace_back();
  10376. }
  10377. else
  10378. {
  10379. song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
  10380. }
  10381. engine.setSong (std::move (song));
  10382. engine.dispatchPendingMessages();
  10383. if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
  10384. if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
  10385. if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
  10386. return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
  10387. }
  10388. // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
  10389. static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
  10390. {
  10391. lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
  10392. lynx::skin::setArtMotion (mode != "still");
  10393. }
  10394. bool runArtShots (const juce::File& folder, bool before)
  10395. {
  10396. folder.createDirectory();
  10397. auto ok = true;
  10398. juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
  10399. for (const auto& p : artPilots())
  10400. {
  10401. artPilotStyle (p, before ? "before" : "after");
  10402. lynx::AudioEngine offline (false);
  10403. auto editor = makeArtPilot (offline, p);
  10404. if (editor == nullptr || editor->getWidth() <= 0)
  10405. {
  10406. std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
  10407. ok = false;
  10408. continue;
  10409. }
  10410. if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
  10411. // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
  10412. auto fit = [&] (const juce::String& at) {
  10413. const auto f = lynx::skin::lastTitleFit();
  10414. if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
  10415. titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
  10416. << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
  10417. };
  10418. for (const auto scale : { 1.0f, 2.0f })
  10419. {
  10420. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  10421. lynx::skin::resetTitleFit();
  10422. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
  10423. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
  10424. if (scale == 1.0f) fit ("100");
  10425. }
  10426. // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
  10427. if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
  10428. {
  10429. editor->setSize (smallest.x, smallest.y);
  10430. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
  10431. lynx::skin::resetTitleFit();
  10432. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, 1.0f), file.getFullPathName());
  10433. fit ("min");
  10434. }
  10435. }
  10436. folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
  10437. lynx::skin::setForcedStyle (-1);
  10438. return ok;
  10439. }
  10440. struct ArtGuiRun final : juce::Timer
  10441. {
  10442. juce::File folder;
  10443. juce::String mode, report;
  10444. std::size_t at = 0;
  10445. int phase = 0;
  10446. double t0 = 0.0, c0 = 0.0;
  10447. std::unique_ptr<lynx::AudioEngine> engine;
  10448. std::unique_ptr<juce::DocumentWindow> window;
  10449. std::function<void()> done;
  10450. void start()
  10451. {
  10452. engine = std::make_unique<lynx::AudioEngine> (false);
  10453. report << "editor\tmode\tcpu % of one core\tart layer animating\n";
  10454. open();
  10455. startTimer (100);
  10456. }
  10457. void open()
  10458. {
  10459. window.reset();
  10460. const auto& pilots = artPilots();
  10461. if (at >= pilots.size())
  10462. {
  10463. folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
  10464. stopTimer();
  10465. lynx::skin::setForcedStyle (-1);
  10466. lynx::skin::setArtMotion (true);
  10467. if (done) done();
  10468. return;
  10469. }
  10470. const auto& p = pilots[at];
  10471. artPilotStyle (p, mode);
  10472. auto editor = makeArtPilot (*engine, p);
  10473. if (editor == nullptr) { ++at; open(); return; }
  10474. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
  10475. window->setUsingNativeTitleBar (true);
  10476. window->setContentOwned (editor.release(), true);
  10477. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  10478. window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
  10479. window->setAlwaysOnTop (true);
  10480. window->setVisible (true);
  10481. phase = 0;
  10482. t0 = juce::Time::getMillisecondCounterHiRes();
  10483. }
  10484. bool animating() const
  10485. {
  10486. if (window == nullptr || window->getContentComponent() == nullptr) return false;
  10487. std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
  10488. if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
  10489. for (auto* child : c.getChildren())
  10490. if (find (*child)) return true;
  10491. return false;
  10492. };
  10493. return find (*window->getContentComponent());
  10494. }
  10495. void timerCallback() override
  10496. {
  10497. const auto now = juce::Time::getMillisecondCounterHiRes();
  10498. const auto& p = artPilots()[at];
  10499. const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
  10500. const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
  10501. if (phase == 0 && now - t0 > 1500.0)
  10502. {
  10503. // the window's content on screen, in physical pixels, for the outside screenshot to crop
  10504. auto* c = window->getContentComponent();
  10505. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  10506. const auto b = c->getScreenBounds();
  10507. shotDone.deleteFile();
  10508. ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
  10509. + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
  10510. phase = 1;
  10511. t0 = now;
  10512. return;
  10513. }
  10514. if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
  10515. {
  10516. ready.deleteFile();
  10517. shotDone.deleteFile();
  10518. phase = 2;
  10519. t0 = now;
  10520. c0 = lynx::processCpuSeconds();
  10521. return;
  10522. }
  10523. if (phase == 2 && now - t0 > 6000.0)
  10524. {
  10525. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  10526. report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
  10527. ++at;
  10528. open();
  10529. }
  10530. }
  10531. };
  10532. std::unique_ptr<ArtGuiRun> artGui;
  10533. void runArtGui (const juce::File& folder, const juce::String& mode)
  10534. {
  10535. folder.createDirectory();
  10536. artGui = std::make_unique<ArtGuiRun>();
  10537. artGui->folder = folder;
  10538. artGui->mode = mode;
  10539. artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
  10540. artGui->start();
  10541. }
  10542. void runPluginEditorSnapshots (const juce::String& folder)
  10543. {
  10544. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10545. {
  10546. const juce::File out (folder);
  10547. out.createDirectory();
  10548. lynx::AudioEngine offline (false);
  10549. const auto roots = lynx::findFlStudioRoots();
  10550. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  10551. auto kinds = lynx::plugui::flLayoutKinds();
  10552. kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
  10553. for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
  10554. kinds.push_back (own);
  10555. kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
  10556. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
  10557. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
  10558. kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
  10559. const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
  10560. auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
  10561. auto ridgePasses = 0;
  10562. // round 173d3: the parity pictures of one editor — LYNX_PLUGUI_ONLY=<effect name>, LYNX_PLUGUI_PRESET=<.fst>,
  10563. // LYNX_PLUGUI_PAGES=<page,page,…> (the page numbers as the editor encodes them)
  10564. const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_ONLY", {});
  10565. const auto onlyPreset = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PRESET", {});
  10566. const auto onlyPages = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PAGES", {}), ",", "");
  10567. for (const auto kind : kinds)
  10568. {
  10569. if (only.isNotEmpty() && only != lynx::effectInfo (kind).name)
  10570. continue;
  10571. auto fx = lynx::makeEffectSlot (kind);
  10572. juce::String name (lynx::effectInfo (kind).name);
  10573. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  10574. {
  10575. const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
  10576. auto file = dir.getChildFile ("Default.fst");
  10577. if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
  10578. for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
  10579. file = f;
  10580. if (only.isNotEmpty() && onlyPreset.isNotEmpty())
  10581. file = juce::File (onlyPreset);
  10582. if (! file.existsAsFile())
  10583. {
  10584. auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
  10585. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
  10586. file = files.isEmpty() ? juce::File() : files[0];
  10587. }
  10588. juce::MemoryBlock data;
  10589. if (file.existsAsFile() && file.loadFileAsData (data))
  10590. {
  10591. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  10592. if (auto loaded = lynx::effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), 130.0, lynx::natives::flDataReader (lynx::flStudioAccess())); loaded && loaded->kind == kind)
  10593. fx = *loaded;
  10594. }
  10595. name = juce::String::fromUTF8 (plugin.c_str());
  10596. break;
  10597. }
  10598. if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
  10599. {
  10600. juce::MemoryBlock data;
  10601. juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
  10602. lynx::maximusfx::Blob blob;
  10603. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  10604. blob.mix = 600;
  10605. const auto* b = static_cast<const std::uint8_t*> (data.getData());
  10606. blob.state.assign (b, b + data.getSize());
  10607. fx = lynx::makeEffectSlot (kind);
  10608. fx.state = lynx::maximusfx::pack (blob);
  10609. name = "Soundgoodizer";
  10610. }
  10611. if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
  10612. {
  10613. for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
  10614. { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
  10615. { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
  10616. { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
  10617. { "Process order", 0.4783f }, { "De-esser", 1.0f } })
  10618. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  10619. name = "Ridge Strip (Vocal strip)";
  10620. }
  10621. else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
  10622. {
  10623. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
  10624. { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
  10625. { "Filter split", 1.0f }, { "Expander", 1.0f } })
  10626. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  10627. name = "Ridge Strip (E console)";
  10628. }
  10629. else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
  10630. for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
  10631. { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
  10632. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  10633. if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
  10634. {
  10635. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
  10636. { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
  10637. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  10638. name = "Compressor (RComp role)";
  10639. }
  10640. if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
  10641. fx.params[0] = 0.33f;
  10642. if (kind == lynx::EffectKind::ember)
  10643. {
  10644. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
  10645. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
  10646. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
  10647. }
  10648. if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
  10649. for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
  10650. { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
  10651. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  10652. lynx::Song song;
  10653. song.mixer.resize (2);
  10654. song.mixer[0].name = "Master";
  10655. song.mixer[1].name = "Insert 1";
  10656. song.mixer[1].effects.push_back (fx);
  10657. offline.setSong (std::move (song));
  10658. offline.dispatchPendingMessages();
  10659. if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
  10660. {
  10661. auto editor = lynx::makeProEditor (offline, 1, 0, true);
  10662. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  10663. {
  10664. juce::Graphics g (image);
  10665. editor->paintEntireComponent (g, false);
  10666. }
  10667. const auto file = out.getChildFile (name + ".png");
  10668. file.deleteFile();
  10669. juce::PNGImageFormat png;
  10670. if (auto stream = file.createOutputStream())
  10671. png.writeImageToStream (image, *stream);
  10672. continue;
  10673. }
  10674. const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  10675. std::vector<int> pageList;
  10676. for (int page = 0; page < pages; ++page)
  10677. pageList.push_back (page);
  10678. if (only.isNotEmpty() && ! onlyPages.isEmpty())
  10679. {
  10680. pageList.clear();
  10681. for (const auto& p : onlyPages)
  10682. pageList.push_back (p.getIntValue());
  10683. }
  10684. for (const auto page : pageList)
  10685. {
  10686. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  10687. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  10688. {
  10689. juce::Graphics g (image);
  10690. g.fillAll (lynx::theme::panel);
  10691. editor->paintEntireComponent (g, false);
  10692. }
  10693. const auto file = out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png");
  10694. file.deleteFile();
  10695. juce::PNGImageFormat png;
  10696. if (auto stream = file.createOutputStream())
  10697. png.writeImageToStream (image, *stream);
  10698. }
  10699. }
  10700. // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
  10701. {
  10702. namespace ef = lynx::echosuite::echoform;
  10703. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  10704. fx.params[ef::rhythm] = 1.0f;
  10705. fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
  10706. fx.params[ef::rhythmDecay] = 0.25f;
  10707. fx.params[ef::rhythmTap1 + 2] = 0.45f;
  10708. fx.params[ef::feedback] = 0.25f;
  10709. fx.params[ef::era] = 0.5f;
  10710. for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
  10711. fx.params[(std::size_t) param] = value;
  10712. fx.params[ef::rhythmShape] = 0.5f; // swell
  10713. lynx::Song song;
  10714. song.mixer.resize (2);
  10715. song.mixer[0].name = "Master";
  10716. song.mixer[1].name = "Insert 1";
  10717. song.mixer[1].effects.push_back (fx);
  10718. offline.setSong (std::move (song));
  10719. offline.dispatchPendingMessages();
  10720. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  10721. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  10722. {
  10723. juce::Graphics g (image);
  10724. g.fillAll (lynx::theme::panel);
  10725. editor->paintEntireComponent (g, false);
  10726. }
  10727. const auto file = out.getChildFile ("Echoform-rhythm.png");
  10728. file.deleteFile();
  10729. juce::PNGImageFormat png;
  10730. if (auto stream = file.createOutputStream())
  10731. png.writeImageToStream (image, *stream);
  10732. }
  10733. // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
  10734. {
  10735. namespace ef = lynx::echosuite::echoform;
  10736. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  10737. fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
  10738. fx.params[ef::style] = ef::styleValue (ef::Style::dual);
  10739. lynx::Song song;
  10740. song.mixer.resize (2);
  10741. song.mixer[0].name = "Master";
  10742. song.mixer[1].name = "Insert 1";
  10743. song.mixer[1].effects.push_back (fx);
  10744. offline.setSong (std::move (song));
  10745. offline.dispatchPendingMessages();
  10746. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  10747. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  10748. {
  10749. juce::Graphics g (image);
  10750. g.fillAll (lynx::theme::panel);
  10751. editor->paintEntireComponent (g, false);
  10752. }
  10753. const auto file = out.getChildFile ("Echoform-voicing.png");
  10754. file.deleteFile();
  10755. juce::PNGImageFormat png;
  10756. if (auto stream = file.createOutputStream())
  10757. png.writeImageToStream (image, *stream);
  10758. }
  10759. // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
  10760. {
  10761. auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  10762. fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
  10763. fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
  10764. lynx::Song song;
  10765. song.mixer.resize (2);
  10766. song.mixer[0].name = "Master";
  10767. song.mixer[1].name = "Insert 1";
  10768. song.mixer[1].effects.push_back (fx);
  10769. offline.setSong (std::move (song));
  10770. offline.dispatchPendingMessages();
  10771. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  10772. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  10773. {
  10774. juce::Graphics g (image);
  10775. g.fillAll (lynx::theme::panel);
  10776. editor->paintEntireComponent (g, false);
  10777. }
  10778. const auto file = out.getChildFile ("Auto-pan-tweak.png");
  10779. file.deleteFile();
  10780. juce::PNGImageFormat png;
  10781. if (auto stream = file.createOutputStream())
  10782. png.writeImageToStream (image, *stream);
  10783. }
  10784. // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
  10785. {
  10786. namespace em = lynx::mixsuite::ember;
  10787. auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
  10788. fx.params[em::voicing] = 1.0f;
  10789. fx.params[em::classicDrive] = 0.35f;
  10790. lynx::Song song;
  10791. song.mixer.resize (2);
  10792. song.mixer[0].name = "Master";
  10793. song.mixer[1].name = "Insert 1";
  10794. song.mixer[1].effects.push_back (fx);
  10795. offline.setSong (std::move (song));
  10796. offline.dispatchPendingMessages();
  10797. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  10798. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  10799. {
  10800. juce::Graphics g (image);
  10801. g.fillAll (lynx::theme::panel);
  10802. editor->paintEntireComponent (g, false);
  10803. }
  10804. const auto file = out.getChildFile ("Ember Saturator-classic.png");
  10805. file.deleteFile();
  10806. juce::PNGImageFormat png;
  10807. if (auto stream = file.createOutputStream())
  10808. png.writeImageToStream (image, *stream);
  10809. }
  10810. // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
  10811. {
  10812. auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
  10813. fx.params[14] = 1.0f; // the measured plate voicing
  10814. fx.params[15] = 1.0f; // View = Plate
  10815. lynx::Song song;
  10816. song.mixer.resize (2);
  10817. song.mixer[0].name = "Master";
  10818. song.mixer[1].name = "Insert 1";
  10819. song.mixer[1].effects.push_back (fx);
  10820. offline.setSong (std::move (song));
  10821. offline.dispatchPendingMessages();
  10822. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  10823. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  10824. {
  10825. juce::Graphics g (image);
  10826. g.fillAll (lynx::theme::panel);
  10827. editor->paintEntireComponent (g, false);
  10828. }
  10829. const auto file = out.getChildFile ("Foil Plate-plate.png");
  10830. file.deleteFile();
  10831. juce::PNGImageFormat png;
  10832. if (auto stream = file.createOutputStream())
  10833. png.writeImageToStream (image, *stream);
  10834. }
  10835. // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
  10836. // and LYNX Tune (demo pitch phrase)
  10837. {
  10838. lynx::setNativeEditorDemo (true);
  10839. using namespace lynx::facet;
  10840. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  10841. const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
  10842. { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
  10843. { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
  10844. };
  10845. for (int b = 0; b < 5; ++b)
  10846. {
  10847. eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
  10848. eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
  10849. eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
  10850. eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
  10851. eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
  10852. eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
  10853. }
  10854. eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
  10855. const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
  10856. lynx::Song song;
  10857. song.mixer.resize (2);
  10858. song.mixer[0].name = "Master";
  10859. song.mixer[1].name = "Vocal";
  10860. song.mixer[1].effects.push_back (fx);
  10861. offline.setSong (std::move (song));
  10862. offline.dispatchPendingMessages();
  10863. auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
  10864. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  10865. {
  10866. juce::Graphics g (image);
  10867. g.fillAll (lynx::theme::panel);
  10868. editor->paintEntireComponent (g, false);
  10869. }
  10870. const auto f = out.getChildFile (file);
  10871. f.deleteFile();
  10872. juce::PNGImageFormat png;
  10873. if (auto stream = f.createOutputStream())
  10874. png.writeImageToStream (image, *stream);
  10875. };
  10876. own (eq, "Facet EQ.png", true);
  10877. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
  10878. {
  10879. // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
  10880. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  10881. tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
  10882. tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
  10883. tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
  10884. // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
  10885. tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
  10886. tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
  10887. tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
  10888. tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
  10889. tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
  10890. tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
  10891. own (tune, "LYNX Tune-p2.png", false, 1);
  10892. }
  10893. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
  10894. lynx::setNativeEditorDemo (false);
  10895. }
  10896. // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
  10897. const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
  10898. 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" } })
  10899. {
  10900. juce::MemoryBlock data;
  10901. if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
  10902. {
  10903. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  10904. files.sort();
  10905. for (const auto& f : files)
  10906. {
  10907. juce::MemoryBlock block;
  10908. if (! f.loadFileAsData (block))
  10909. continue;
  10910. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  10911. try
  10912. {
  10913. const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
  10914. if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
  10915. {
  10916. preset = nullptr;
  10917. data = block;
  10918. break;
  10919. }
  10920. }
  10921. catch (const std::exception&)
  10922. {
  10923. }
  10924. }
  10925. }
  10926. auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
  10927. : generators.getChildFile (folder).getChildFile (preset);
  10928. if (! file.existsAsFile())
  10929. {
  10930. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  10931. files.sort();
  10932. file = files.isEmpty() ? juce::File() : files[0];
  10933. }
  10934. if (data.isEmpty() && ! file.loadFileAsData (data))
  10935. continue;
  10936. try
  10937. {
  10938. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  10939. auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
  10940. if (project.channels.empty())
  10941. continue;
  10942. project.channels.front().type = flp::ChannelType::native;
  10943. lynx::FlpImportOptions options;
  10944. options.roots = roots;
  10945. options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
  10946. options.readFile = [] (const std::string& path) {
  10947. juce::MemoryBlock block;
  10948. lynx::platform::localFile (path).loadFileAsData (block);
  10949. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  10950. return std::vector<std::uint8_t> (b, b + block.getSize());
  10951. };
  10952. options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  10953. const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
  10954. f.getParentDirectory().createDirectory();
  10955. f.replaceWithData (wav.data(), wav.size());
  10956. return f.getFullPathName().toStdString();
  10957. };
  10958. auto song = lynx::importFlp (project, options);
  10959. // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
  10960. if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
  10961. {
  10962. song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
  10963. song.channels.front().modelParams.assign (3, 32768.0f);
  10964. }
  10965. if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
  10966. {
  10967. song.channels.front().instrument = lynx::InstrumentKind::flkeys;
  10968. song.channels.front().pluginState = project.channels.front().pluginState;
  10969. }
  10970. offline.setSong (std::move (song));
  10971. offline.dispatchPendingMessages();
  10972. if (offline.getSong().channels.empty())
  10973. continue;
  10974. auto panel = lynx::makeChannelSettingsPanel (offline, 0);
  10975. juce::Image image (juce::Image::ARGB, panel->getWidth(), panel->getHeight(), true);
  10976. {
  10977. juce::Graphics g (image);
  10978. g.fillAll (lynx::theme::panel);
  10979. panel->paintEntireComponent (g, false);
  10980. }
  10981. const auto out2 = out.getChildFile (juce::String (folder) + ".png");
  10982. out2.deleteFile();
  10983. juce::PNGImageFormat png;
  10984. if (auto stream = out2.createOutputStream())
  10985. png.writeImageToStream (image, *stream);
  10986. }
  10987. catch (const std::exception&)
  10988. {
  10989. }
  10990. }
  10991. }
  10992. quit();
  10993. }
  10994. void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
  10995. {
  10996. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10997. // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
  10998. struct VideoShot final : juce::Timer
  10999. {
  11000. lynx::AudioEngine offline { false };
  11001. std::unique_ptr<juce::Component> editor;
  11002. juce::String prefix, report;
  11003. int step = 0;
  11004. std::function<void()> done;
  11005. void moveTo (double seconds)
  11006. {
  11007. offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
  11008. }
  11009. void timerCallback() override
  11010. {
  11011. static constexpr double times[] = { 0.0, 1.5, 3.25 };
  11012. constexpr int typeInStep = (int) std::size (times) + 1;
  11013. if (step > 0 && step < typeInStep && editor != nullptr)
  11014. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + juce::String (step - 1) + ".png");
  11015. if (editor != nullptr && step == (int) std::size (times))
  11016. {
  11017. // round 174d: FL's in-place type-in of the current time (a right click on it)
  11018. lynx::videoview::openTypeIn (*editor, 2);
  11019. ++step;
  11020. return;
  11021. }
  11022. if (editor != nullptr && step == typeInStep)
  11023. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-typein.png");
  11024. if (editor == nullptr || step >= typeInStep)
  11025. {
  11026. stopTimer();
  11027. juce::File (prefix + "-report.txt").replaceWithText (report);
  11028. if (done)
  11029. done();
  11030. return;
  11031. }
  11032. moveTo (times[step++]);
  11033. }
  11034. };
  11035. static std::unique_ptr<VideoShot> shot;
  11036. shot = std::make_unique<VideoShot>();
  11037. shot->prefix = prefix;
  11038. auto& offline = shot->offline;
  11039. lynx::videoview::install (offline);
  11040. lynx::Song song;
  11041. song.mixer = lynx::Song::defaultMixer (2);
  11042. lynx::ChannelDef c;
  11043. c.name = "Fruity Video Player";
  11044. c.instrument = lynx::InstrumentKind::videoplayer;
  11045. lynx::video::Settings vs;
  11046. vs.path = juce::File (videoPath).getFullPathName().toStdString();
  11047. vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
  11048. c.pluginState = lynx::video::write (vs);
  11049. song.channels.push_back (c);
  11050. song.patterns.emplace_back();
  11051. {
  11052. // round 174d (A3): the same Video Player in a song whose tempo drops from 120 to 60 BPM at bar 5, for FL
  11053. // (LYNX.exe --export-flp <prefix>-tempo.lynx <prefix>-tempo.flp), to compare FL's video clock with LYNX's
  11054. auto fl = song;
  11055. fl.bpm = 120.0;
  11056. fl.mode = lynx::PlayMode::song;
  11057. auto settings = vs;
  11058. settings.delay = 0;
  11059. settings.timeDisplay = lynx::video::Settings {}.timeDisplay;
  11060. fl.channels[0].pluginState = lynx::video::write (settings);
  11061. fl.patterns[0].name = "Pattern 1";
  11062. lynx::Automation tempo;
  11063. tempo.name = "Tempo";
  11064. tempo.target = { lynx::AutomationTargetKind::tempo, 0, 0, 0 };
  11065. const auto bar = (std::int64_t) lynx::ppq * 4;
  11066. tempo.points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { bar * 4 - 1, lynx::valueFromTempo (120.0), 0.0f },
  11067. { bar * 4, lynx::valueFromTempo (60.0), 0.0f }, { bar * 8, lynx::valueFromTempo (60.0), 0.0f } };
  11068. fl.automations.push_back (tempo);
  11069. lynx::Clip at;
  11070. at.kind = lynx::ClipKind::automation;
  11071. at.automation = 0;
  11072. at.track = 1;
  11073. at.start = 0;
  11074. at.length = bar * 8;
  11075. fl.playlist.push_back (at);
  11076. lynx::Clip pc;
  11077. pc.pattern = 0;
  11078. pc.track = 0;
  11079. pc.start = 0;
  11080. pc.length = bar * 8;
  11081. fl.playlist.push_back (pc);
  11082. juce::String error;
  11083. lynx::ProjectFile::save (fl, juce::File (prefix + "-tempo.lynx"), error);
  11084. }
  11085. offline.setSong (std::move (song));
  11086. offline.dispatchPendingMessages();
  11087. auto& report = shot->report;
  11088. report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
  11089. report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
  11090. shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
  11091. if (shot->editor != nullptr)
  11092. shot->editor->setVisible (true);
  11093. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  11094. shot->startTimer (1500);
  11095. }
  11096. void runVideoTrackShot (const juce::String& prefix, const juce::String& videoPath, const juce::String& secondPath)
  11097. {
  11098. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11099. struct TrackShot final : juce::Timer
  11100. {
  11101. lynx::AudioEngine offline { false };
  11102. std::unique_ptr<lynx::PlaylistComponent> playlist;
  11103. std::unique_ptr<lynx::media::FrameDecoder> decoder;
  11104. juce::String prefix, report, path;
  11105. double fps = 25.0;
  11106. int step = 0, waits = 0, adrStep = 0;
  11107. std::unique_ptr<juce::Component> adrPanel;
  11108. std::function<void()> done;
  11109. // song times (s): before, inside the first clip (on and between frame edges), across the second clip
  11110. std::vector<double> times { 0.0, 1.0, 2.0 + 1.0 / 25.0, 2.5, 4.0, 7.3 };
  11111. void timerCallback() override
  11112. {
  11113. if (step > 0 && adrStep == 0)
  11114. {
  11115. // the frame the decoder shows for the wanted file time (the clip starts at song 1.0 s, offset 0)
  11116. const auto want = times[(std::size_t) step - 1] - 1.0;
  11117. double ft = -1.0;
  11118. const auto img = decoder->frame (ft);
  11119. const auto expected = std::floor (want * fps + 1e-6) / fps;
  11120. if (want >= 0.0 && ft < expected - 1e-3 && ++waits < 20)
  11121. return; // (still decoding)
  11122. waits = 0;
  11123. report << "song " << juce::String (times[(std::size_t) step - 1], 3) << " s: wanted file time " << juce::String (want, 4)
  11124. << ", frame shown at " << juce::String (ft, 4) << " (expected " << juce::String (expected, 4) << ")"
  11125. << (want < 0.0 ? " [before the clip]" : std::abs (ft - expected) < 1e-3 ? " OK" : " MISMATCH") << "\n";
  11126. savePng (playlist->createComponentSnapshot (playlist->getLocalBounds()), prefix + "-playlist-" + juce::String (step - 1) + ".png");
  11127. if (img.isValid())
  11128. savePng (img, prefix + "-frame-" + juce::String (step - 1) + ".png");
  11129. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  11130. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  11131. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + "-window-" + juce::String (step - 1) + ".png");
  11132. }
  11133. if (step >= (int) times.size() && adrStep == 0)
  11134. {
  11135. // the ADR window: two cues, takes on the first; the play position inside the streamer before the in
  11136. // point (4.0 s), so the video window shows the streamer and the line
  11137. adrStep = 1;
  11138. offline.editSong ([] (lynx::Song& s) {
  11139. lynx::AdrCue a, b;
  11140. a.id = "SC1-01";
  11141. a.in = 4.0;
  11142. a.out = 6.4;
  11143. a.character = "Dr. Silva";
  11144. a.line = "We have to leave before the storm reaches the coast.";
  11145. a.notes = "softer, out of breath";
  11146. a.status = lynx::AdrCue::Status::recorded;
  11147. for (int n = 1; n <= 3; ++n)
  11148. {
  11149. lynx::AdrTake t;
  11150. t.number = n;
  11151. t.name = lynx::adr::takeName (a, n);
  11152. t.rating = n == 2 ? 4 : n;
  11153. t.circled = n == 2;
  11154. a.takes.push_back (t);
  11155. }
  11156. a.selected = 2;
  11157. lynx::adr::setCompRange (a, 4.0, 5.1, 2);
  11158. lynx::adr::setCompRange (a, 5.1, 6.4, 3);
  11159. b.id = "SC1-02";
  11160. b.in = 8.0;
  11161. b.out = 9.5;
  11162. b.character = "Marta";
  11163. b.line = "Then we go now.";
  11164. s.adr.cues = { a, b };
  11165. s.adr.current = 0;
  11166. });
  11167. adrPanel = lynx::adrwindow::makePanel (offline);
  11168. adrPanel->setSize (1200, 640);
  11169. adrPanel->setVisible (true);
  11170. offline.getTransport().positionTicks.store (3.0 * offline.getSong().bpm / 60.0 * lynx::ppq);
  11171. decoder->request (2.0, false);
  11172. return;
  11173. }
  11174. if (adrStep == 1)
  11175. {
  11176. adrStep = 2;
  11177. savePng (adrPanel->createComponentSnapshot (adrPanel->getLocalBounds()), prefix + "-adr.png");
  11178. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  11179. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  11180. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + "-adr-window.png");
  11181. offline.getTransport().positionTicks.store (4.5 * offline.getSong().bpm / 60.0 * lynx::ppq);
  11182. decoder->request (3.5, false);
  11183. return;
  11184. }
  11185. if (adrStep == 2)
  11186. {
  11187. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  11188. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  11189. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + "-adr-window-line.png");
  11190. adrPanel.reset();
  11191. // export with video: a 3 s mix under the picture, re-encoded (the clip starts at 1 s) and copied (from 1 s)
  11192. {
  11193. const juce::File wav (prefix + "-mix.wav");
  11194. wav.deleteFile();
  11195. juce::WavAudioFormat format;
  11196. if (std::unique_ptr<juce::OutputStream> os (wav.createOutputStream().release()); os != nullptr)
  11197. if (std::unique_ptr<juce::AudioFormatWriter> w (format.createWriterFor (os.get(), 48000.0, 2, 16, {}, 0)); w != nullptr)
  11198. {
  11199. os.release();
  11200. juce::AudioBuffer<float> b (2, 48000 * 3);
  11201. for (int k = 0; k < b.getNumSamples(); ++k)
  11202. b.setSample (0, k, 0.25f * (float) std::sin (k * 2.0 * juce::MathConstants<double>::pi * 330.0 / 48000.0)), b.setSample (1, k, b.getSample (0, k));
  11203. w->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  11204. }
  11205. for (const auto origin : { 0.0, 1.0 })
  11206. {
  11207. const juce::File out (prefix + "-mux-" + juce::String ((int) origin) + ".mp4");
  11208. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  11209. const auto error = lynx::videotracks::muxWithVideo (offline.getSong(), origin, wav, out);
  11210. report << "export with video from " << origin << " s: " << (error.isEmpty() ? "OK " + juce::String (out.getSize()) + " bytes" : "FAILED " + error)
  11211. << " (" << juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0, 2) << " s)\n";
  11212. }
  11213. }
  11214. stopTimer();
  11215. report << "frames decoded " << decoder->frameCount() << ", dropped " << decoder->droppedCount() << "\n";
  11216. juce::File (prefix + "-report.txt").replaceWithText (report);
  11217. if (done)
  11218. done();
  11219. return;
  11220. }
  11221. const auto t = times[(std::size_t) step++];
  11222. offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
  11223. decoder->request (std::max (0.0, t - 1.0), false);
  11224. }
  11225. };
  11226. static std::unique_ptr<TrackShot> shot;
  11227. shot = std::make_unique<TrackShot>();
  11228. shot->prefix = prefix;
  11229. auto& offline = shot->offline;
  11230. lynx::Song song;
  11231. song.mixer = lynx::Song::defaultMixer (2);
  11232. song.patterns.emplace_back();
  11233. song.mode = lynx::PlayMode::song;
  11234. song.bpm = 120.0;
  11235. offline.setSong (std::move (song));
  11236. offline.dispatchPendingMessages();
  11237. const juce::File video (videoPath);
  11238. const auto pr = lynx::media::probe (video.getFullPathName());
  11239. auto& report = shot->report;
  11240. report << "decoder: " << (pr.backend.isEmpty() ? juce::String ("none") : pr.backend) << " (system: " << lynx::media::nativeBackendName()
  11241. << ", ffmpeg: " << lynx::findFfmpeg().getFullPathName() << ")\n";
  11242. report << "video: " << pr.info.width << "x" << pr.info.height << " " << juce::String (pr.info.fps, 3) << " fps " << juce::String (pr.info.duration, 3)
  11243. << " s, sound " << (pr.info.hasAudio ? "yes" : "no") << "\n";
  11244. shot->fps = pr.info.fps > 1.0 ? pr.info.fps : 25.0;
  11245. shot->times[2] = 2.0 + 1.0 / shot->fps; // (exactly on a frame edge)
  11246. lynx::videotracks::importVideo (offline, video, 1.0, -1);
  11247. if (secondPath.isNotEmpty())
  11248. lynx::videotracks::importVideo (offline, juce::File (secondPath), 3.0, 1);
  11249. offline.editSong ([] (lynx::Song& s) {
  11250. s.video.startTimecode = 3600.0;
  11251. s.video.burnIn = true;
  11252. if (s.videoTracks.size() < 2)
  11253. s.videoTracks.push_back ({});
  11254. s.videoTracks[0].name = "Picture";
  11255. s.videoTracks[1].name = "Reference";
  11256. });
  11257. report << "project rate: " << lynx::vtime::rateName (offline.getSong().video.rate) << ", clip 1: "
  11258. << juce::String (offline.getSong().videoTracks[0].clips.empty() ? -1.0 : offline.getSong().videoTracks[0].clips[0].length, 3) << " s\n";
  11259. // the project round trip
  11260. {
  11261. const juce::File file (prefix + "-project.lynx");
  11262. juce::String error;
  11263. lynx::ProjectFile::save (offline.getSong(), file, error);
  11264. const auto back = lynx::ProjectFile::load (file, error);
  11265. report << "project file round trip: " << (back && back->videoTracks == offline.getSong().videoTracks && back->video == offline.getSong().video ? "OK" : "MISMATCH " + error) << "\n";
  11266. }
  11267. shot->playlist = std::make_unique<lynx::PlaylistComponent> (offline);
  11268. shot->playlist->setSize (1400, 640);
  11269. shot->playlist->setVisible (true);
  11270. shot->decoder = std::make_unique<lynx::media::FrameDecoder>();
  11271. shot->decoder->setSource (video.getFullPathName(), pr.info);
  11272. shot->decoder->setSize (pr.info.width, pr.info.height);
  11273. shot->decoder->startThread (juce::Thread::Priority::low);
  11274. lynx::videotracks::showWindow (offline, 0);
  11275. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  11276. shot->startTimer (700);
  11277. }
  11278. void runDanceShot (const juce::String& prefix)
  11279. {
  11280. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11281. // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
  11282. {
  11283. constexpr int cell = 120, cols = 8;
  11284. juce::Image sheet (juce::Image::ARGB, 130 + cols * cell, lynx::dance::moveCount * cell + 10, true);
  11285. juce::Graphics g (sheet);
  11286. g.fillAll (lynx::theme::colour::bg0);
  11287. for (int m = 0; m < lynx::dance::moveCount; ++m)
  11288. {
  11289. g.setColour (lynx::theme::colour::textSecondary);
  11290. g.setFont (14.0f);
  11291. g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
  11292. for (int k = 0; k < cols; ++k)
  11293. {
  11294. const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
  11295. lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
  11296. }
  11297. }
  11298. savePng (sheet, prefix + "-moves.png");
  11299. }
  11300. lynx::AudioEngine offline (false);
  11301. lynx::Song song;
  11302. song.mixer = lynx::Song::defaultMixer (2);
  11303. for (int d = 0; d < 2; ++d)
  11304. {
  11305. lynx::ChannelDef c;
  11306. c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
  11307. c.instrument = lynx::InstrumentKind::fruitydance;
  11308. lynx::dance::Settings s;
  11309. s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
  11310. s.x = d == 0 ? 520 : 760;
  11311. s.y = 560;
  11312. s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
  11313. s.mirrored = d == 1;
  11314. c.pluginState = lynx::dance::toState (s);
  11315. song.channels.push_back (c);
  11316. }
  11317. song.patterns.emplace_back();
  11318. {
  11319. const juce::File demo (prefix + "-demo.lynx");
  11320. juce::String error;
  11321. lynx::ProjectFile::save (song, demo, error);
  11322. }
  11323. offline.setSong (std::move (song));
  11324. offline.dispatchPendingMessages();
  11325. if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
  11326. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
  11327. if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
  11328. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-frame.png");
  11329. }
  11330. void runControllerShot (const juce::String& prefix)
  11331. {
  11332. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11333. lynx::AudioEngine offline (false);
  11334. lynx::Song song;
  11335. song.mixer = lynx::Song::defaultMixer (2);
  11336. song.mixer[1].name = "Insert 1";
  11337. auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
  11338. lynx::formula::State formula;
  11339. formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
  11340. fx.state = lynx::formula::writeState (formula);
  11341. fx.params[0] = 0.5f;
  11342. fx.params[1] = 0.25f;
  11343. fx.params[2] = 0.5f;
  11344. song.mixer[1].effects.push_back (fx);
  11345. // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
  11346. {
  11347. auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
  11348. xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
  11349. xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
  11350. xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
  11351. song.mixer[1].effects.push_back (xyFx);
  11352. auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
  11353. xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
  11354. song.mixer[1].effects.push_back (xyzFx);
  11355. // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
  11356. xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
  11357. xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
  11358. xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
  11359. xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
  11360. song.mixer[1].effects.push_back (xyzFx);
  11361. auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
  11362. lynx::SurfaceControl c;
  11363. for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
  11364. { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
  11365. { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
  11366. { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
  11367. { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
  11368. { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
  11369. { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
  11370. {
  11371. c.kind = kind;
  11372. c.name = name;
  11373. c.value = v;
  11374. c.valueY = 0.6f;
  11375. c.x = x;
  11376. c.y = y;
  11377. lynx::surface::add (panel, c);
  11378. }
  11379. song.mixer[1].effects.push_back (panel);
  11380. }
  11381. lynx::ChannelDef env;
  11382. env.name = "Envelope Controller";
  11383. env.instrument = lynx::InstrumentKind::controller;
  11384. auto ecData = lynx::defaultEnvelopeController();
  11385. ecData[0].lfoOn = true;
  11386. ecData[0].lfoTempo = true;
  11387. ecData[0].lfoSpeed = 40898;
  11388. ecData[0].maps[lynx::mapKeyboard].count = 2;
  11389. ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  11390. ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  11391. ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
  11392. env.controllerState = lynx::writeEnvelopeController (ecData);
  11393. song.channels.push_back (env);
  11394. lynx::ChannelDef out;
  11395. out.name = "MIDI Out";
  11396. out.instrument = lynx::InstrumentKind::midiOut;
  11397. lynx::midictl::MidiOutSettings settings;
  11398. settings.port = 1;
  11399. lynx::midictl::writeMidiOut (out.pluginState, settings);
  11400. song.channels.push_back (out);
  11401. // a Layer (round 164) over three synths split across the keyboard, crossfading
  11402. for (const auto* name : { "Bass", "Pad", "Lead" })
  11403. {
  11404. lynx::ChannelDef c;
  11405. c.name = name;
  11406. c.instrument = lynx::InstrumentKind::synth;
  11407. song.channels.push_back (c);
  11408. }
  11409. {
  11410. lynx::ChannelDef layer;
  11411. layer.name = "Layer";
  11412. layer.instrument = lynx::InstrumentKind::layer;
  11413. song.channels.push_back (layer);
  11414. const auto self = (int) song.channels.size() - 1;
  11415. lynx::layer::setChildren (song, self, { 2, 3, 4 });
  11416. song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
  11417. song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
  11418. song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
  11419. song.channels[(std::size_t) self].layer.crossfade = true;
  11420. song.channels[(std::size_t) self].layer.fade = 0.35f;
  11421. }
  11422. {
  11423. lynx::ChannelDef dash; // channel 6
  11424. dash.name = "Dashboard";
  11425. dash.instrument = lynx::InstrumentKind::dashboard;
  11426. dash.patcher.surface = lynx::surface::starterControls();
  11427. song.channels.push_back (dash);
  11428. }
  11429. {
  11430. lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
  11431. volt.name = "Voltage Controller";
  11432. volt.instrument = lynx::InstrumentKind::voltage;
  11433. lynx::voltage::Settings v;
  11434. v.enabled = true;
  11435. v.params[9] = 49152;
  11436. v.unipolar[2] = true;
  11437. v.tracks = { 3, 0, 0 };
  11438. v.source[6] = lynx::voltage::Source::clock;
  11439. volt.pluginState = lynx::voltage::write (v);
  11440. song.channels.push_back (volt);
  11441. }
  11442. song.patterns.emplace_back();
  11443. offline.setSong (std::move (song));
  11444. offline.dispatchPendingMessages();
  11445. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  11446. if (c == nullptr)
  11447. return;
  11448. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
  11449. };
  11450. shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
  11451. shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
  11452. shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
  11453. shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
  11454. {
  11455. const auto slotOf = [] (int k) -> lynx::SlotLocator {
  11456. return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
  11457. };
  11458. const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
  11459. shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
  11460. shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
  11461. shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
  11462. shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
  11463. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
  11464. shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
  11465. }
  11466. // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
  11467. if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
  11468. for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
  11469. {
  11470. juce::MemoryBlock bytes;
  11471. if (! file.loadFileAsData (bytes))
  11472. continue;
  11473. const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
  11474. const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
  11475. if (! dash || dash->controls.empty())
  11476. continue;
  11477. offline.editSong ([&] (lynx::Song& s) {
  11478. s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
  11479. s.channels[6].patcher.surface = dash->controls;
  11480. s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
  11481. });
  11482. offline.dispatchPendingMessages();
  11483. const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
  11484. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
  11485. // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
  11486. if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
  11487. {
  11488. std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
  11489. for (auto* child : c.getChildren())
  11490. {
  11491. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
  11492. b->setToggleState (true, juce::sendNotificationSync);
  11493. pressEdit (*child);
  11494. }
  11495. };
  11496. pressEdit (*panel);
  11497. shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
  11498. }
  11499. }
  11500. // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
  11501. if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
  11502. for (int part = 0; part < 7; ++part)
  11503. {
  11504. for (auto* child : ec->getChildren())
  11505. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  11506. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  11507. savePng (ec->createComponentSnapshot (ec->getLocalBounds()), prefix + "-ec-part" + juce::String (part) + ".png");
  11508. }
  11509. lynx::FormulaControllerWindows::open (offline, 1, 0);
  11510. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  11511. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  11512. if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
  11513. savePng (w->getContentComponent()->createComponentSnapshot (w->getContentComponent()->getLocalBounds()), prefix + "-formula-controller.png");
  11514. lynx::FormulaControllerWindows::closeAll();
  11515. }
  11516. void runEdisonShot (const juce::String& prefix, const juce::String& file)
  11517. {
  11518. namespace ae = lynx::audioedit;
  11519. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11520. lynx::AudioEngine offline (false);
  11521. ae::Document d;
  11522. if (file.isNotEmpty())
  11523. {
  11524. juce::MemoryBlock bytes;
  11525. if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
  11526. {
  11527. std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
  11528. return;
  11529. }
  11530. }
  11531. else
  11532. {
  11533. // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
  11534. d.title = "Drum loop";
  11535. d.audio.sampleRate = 44100.0;
  11536. const auto frames = (std::size_t) (44100 * 2);
  11537. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  11538. std::uint32_t seed = 7;
  11539. for (std::size_t i = 0; i < frames; ++i)
  11540. {
  11541. seed = seed * 1664525u + 1013904223u;
  11542. const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
  11543. const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
  11544. d.audio.channels[0][i] = hiss + hum;
  11545. d.audio.channels[1][i] = hiss * 0.9f + hum;
  11546. }
  11547. for (int hit = 0; hit < 8; ++hit)
  11548. {
  11549. const auto at = (std::size_t) hit * frames / 8;
  11550. const auto kick = hit % 2 == 0;
  11551. double phase = 0.0;
  11552. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  11553. {
  11554. seed = seed * 1664525u + 1013904223u;
  11555. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  11556. const auto t = (double) i / 44100.0;
  11557. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  11558. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  11559. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  11560. d.audio.channels[0][at + i] += v;
  11561. d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
  11562. }
  11563. }
  11564. for (int hit = 1; hit < 8; ++hit)
  11565. ae::addMarker (d, (std::int64_t) (hit * frames / 8));
  11566. ae::setLoop (d, { 0, (std::int64_t) frames });
  11567. }
  11568. // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
  11569. 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 } };
  11570. auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
  11571. auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
  11572. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  11573. {
  11574. juce::Graphics g (image);
  11575. g.fillAll (lynx::theme::panel);
  11576. c.paintEntireComponent (g, false);
  11577. }
  11578. savePng (image, prefix + name);
  11579. };
  11580. editor->setSize (1120, 600);
  11581. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
  11582. shot (*editor, "-editor-volume-envelope.png");
  11583. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
  11584. juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  11585. for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
  11586. {
  11587. const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
  11588. if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
  11589. {
  11590. offline.dispatchPendingMessages();
  11591. const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
  11592. shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
  11593. if (envelopeTool)
  11594. shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
  11595. panel.reset(); // (puts the envelope back)
  11596. }
  11597. }
  11598. }
  11599. static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
  11600. {
  11601. if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
  11602. return b;
  11603. for (auto* child : root.getChildren())
  11604. if (auto* b = findButton (*child, text))
  11605. return b;
  11606. return nullptr;
  11607. }
  11608. // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
  11609. void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
  11610. {
  11611. const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
  11612. for (const auto& [tab, file] : tabs)
  11613. if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
  11614. {
  11615. b->onClick();
  11616. savePng (panel.createComponentSnapshot (panel.getLocalBounds()), name + "-tab-" + file + ".png");
  11617. }
  11618. engine.editSong ([&] (lynx::Song& s) {
  11619. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  11620. auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
  11621. settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
  11622. " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
  11623. st.fl = lynx::vfx::writeScript (settings);
  11624. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  11625. });
  11626. engine.dispatchPendingMessages();
  11627. if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
  11628. {
  11629. engine.dispatchPendingMessages();
  11630. if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
  11631. b->onClick();
  11632. savePng (broken->createComponentSnapshot (broken->getLocalBounds()), name + "-error.png");
  11633. }
  11634. }
  11635. void runVfxShot (const juce::String& prefix)
  11636. {
  11637. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11638. lynx::AudioEngine offline (false);
  11639. lynx::MainComponent ui (offline, false);
  11640. ui.setSize (1280, 720);
  11641. auto song = lynx::Song::makeDefault();
  11642. song.channels.clear();
  11643. for (const auto kind : lynx::vfx::allKinds)
  11644. {
  11645. lynx::ChannelDef c;
  11646. lynx::vfx::makeChannel (c, kind);
  11647. if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
  11648. for (const auto& p : lynx::vfx::builtInPresets (kind))
  11649. if (p.name == "Major triad")
  11650. {
  11651. auto st = *lynx::vfx::readState (c.pluginState);
  11652. st.fl = p.fl;
  11653. c.pluginState = lynx::vfx::writeState (st);
  11654. }
  11655. song.channels.push_back (c);
  11656. }
  11657. // a Patcher: its notes through a Color Mapper to three synths
  11658. lynx::ChannelDef patcher;
  11659. patcher.name = "Patcher";
  11660. patcher.instrument = lynx::InstrumentKind::patcher;
  11661. lynx::PatchNode mapper;
  11662. mapper.generator = true;
  11663. lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
  11664. mapper.x = 260.0f;
  11665. patcher.patcher.nodes.push_back (mapper);
  11666. lynx::PatchWire notes;
  11667. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  11668. patcher.patcher.wires.push_back (notes);
  11669. for (int k = 0; k < 3; ++k)
  11670. {
  11671. lynx::PatchNode synth;
  11672. synth.generator = true;
  11673. synth.channel.instrument = lynx::InstrumentKind::synth;
  11674. synth.channel.name = "Synth " + std::to_string (k + 1);
  11675. synth.x = 520.0f, synth.y = (float) k * 90.0f;
  11676. patcher.patcher.nodes.push_back (synth);
  11677. lynx::PatchWire in, out;
  11678. in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
  11679. out.from = 1 + k, out.to = lynx::patchToHost;
  11680. patcher.patcher.wires.push_back (in);
  11681. patcher.patcher.wires.push_back (out);
  11682. }
  11683. patcher.patcher.outputX = 760.0f;
  11684. song.channels.push_back (patcher);
  11685. offline.setSong (std::move (song));
  11686. offline.dispatchPendingMessages();
  11687. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  11688. if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
  11689. {
  11690. offline.dispatchPendingMessages();
  11691. savePng (panel->createComponentSnapshot (panel->getLocalBounds()),
  11692. prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
  11693. }
  11694. // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
  11695. // a Script with FL's "Snap To Scale"
  11696. if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
  11697. {
  11698. const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
  11699. const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
  11700. { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
  11701. { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
  11702. };
  11703. for (const auto& [kind, path] : extra)
  11704. {
  11705. juce::MemoryBlock bytes;
  11706. if (! data.getChildFile (path).loadFileAsData (bytes))
  11707. continue;
  11708. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  11709. const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
  11710. int index = -1;
  11711. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  11712. if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
  11713. index = c;
  11714. if (! fl || index < 0)
  11715. continue;
  11716. offline.editSong ([&] (lynx::Song& s) {
  11717. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  11718. st.fl = *fl;
  11719. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  11720. });
  11721. offline.dispatchPendingMessages();
  11722. if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
  11723. {
  11724. offline.dispatchPendingMessages();
  11725. const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
  11726. savePng (panel->createComponentSnapshot (panel->getLocalBounds()), name + "-fl.png");
  11727. if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
  11728. shootScriptTabs (*panel, offline, index, name);
  11729. }
  11730. }
  11731. }
  11732. lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
  11733. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  11734. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  11735. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  11736. {
  11737. auto* content = w->getContentComponent();
  11738. savePng (content->createComponentSnapshot (content->getLocalBounds()), prefix + "-patcher.png");
  11739. delete w;
  11740. break;
  11741. }
  11742. lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
  11743. savePng (image, prefix + "-patcher-menu-" + name + ".png");
  11744. });
  11745. // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
  11746. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
  11747. {
  11748. const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
  11749. offline.getPluginHost().setPluginName (key, "1_EQ");
  11750. offline.editSong ([] (lynx::Song& s) {
  11751. if (s.mixer.size() > 1)
  11752. {
  11753. lynx::EffectSlot slot;
  11754. slot.kind = lynx::EffectKind::parametricEq;
  11755. s.mixer[1].effects.push_back (slot);
  11756. }
  11757. });
  11758. offline.dispatchPendingMessages();
  11759. {
  11760. lynx::QuickAddTargets targets;
  11761. targets.addInstrument = [] (lynx::ChannelDef) {};
  11762. targets.addEffect = [] (lynx::EffectSlot) {};
  11763. auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
  11764. savePng (palette->createComponentSnapshot (palette->getLocalBounds()), prefix + "-quickadd-renamed.png");
  11765. }
  11766. ui.selectTabForSnapshot (3);
  11767. ui.getMixerForSnapshot().selectTrack (1);
  11768. offline.dispatchPendingMessages();
  11769. savePng (ui.createComponentSnapshot (ui.getLocalBounds()), prefix + "-mixer-renamed.png");
  11770. offline.getPluginHost().setPluginName (key, "");
  11771. }
  11772. }
  11773. void runAudioXShot (const juce::String& prefix)
  11774. {
  11775. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11776. lynx::AudioEngine offline (false);
  11777. {
  11778. lynx::MainComponent ui (offline, false);
  11779. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  11780. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  11781. offline.dispatchPendingMessages();
  11782. // 1. sends: insert 1 feeds insert 3 pre-fader and insert 4 post-fader (FL's way)
  11783. offline.editSong ([] (lynx::Song& s) {
  11784. if (s.mixer.size() < 5)
  11785. return;
  11786. s.mixer[1].name = "Vocal";
  11787. s.mixer[3].name = "Reverb";
  11788. s.mixer[4].name = "Delay";
  11789. s.setRoute (1, 3, true);
  11790. s.setRoute (1, 4, true);
  11791. s.setRouteLevel (1, 3, 0.6f);
  11792. s.setRouteLevel (1, 4, 0.4f);
  11793. s.setSendPre (1, 3, true);
  11794. });
  11795. offline.dispatchPendingMessages();
  11796. ui.selectTabForSnapshot (3);
  11797. ui.getMixerForSnapshot().selectTrack (1);
  11798. offline.dispatchPendingMessages();
  11799. saveSnapshot (ui, prefix + "-send-pre.png");
  11800. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  11801. saveMenus (juce::StringArray { "Send to Reverb (pre-fader)", "Send to Delay (post-fader)" },
  11802. std::vector<juce::PopupMenu> { strips.buildSendMenu (3), strips.buildSendMenu (4) }, prefix + "-send-menu.png");
  11803. // 2. low latency while recording: the monitored track's look-ahead limiter is bypassed, the EQ stays
  11804. offline.editSong ([] (lynx::Song& s) {
  11805. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::parametricEq));
  11806. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  11807. s.mixer[1].inputChannel = 0;
  11808. s.mixer[1].monitor = lynx::InputMonitor::on;
  11809. });
  11810. offline.dispatchPendingMessages();
  11811. saveSnapshot (ui, prefix + "-lowlat-off.png");
  11812. auto options = offline.getRecordOptions();
  11813. options.lowLatencyRecording = true;
  11814. offline.setRecordOptions (options);
  11815. offline.dispatchPendingMessages();
  11816. ui.getMixerForSnapshot().selectTrack (1);
  11817. offline.dispatchPendingMessages();
  11818. saveSnapshot (ui, prefix + "-lowlat-on.png");
  11819. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getFullRecordMenuForSnapshot() }, prefix + "-lowlat-menu.png");
  11820. juce::String report;
  11821. report << "latency_with_option=" << offline.getLatencySamples() << " bypassed_slots=" << offline.lowLatencyBypassedCount() << "\n";
  11822. options.lowLatencyRecording = false;
  11823. offline.setRecordOptions (options);
  11824. offline.dispatchPendingMessages();
  11825. report << "latency_without_option=" << offline.getLatencySamples() << "\n";
  11826. // 3. the Browser's "Preview in time": a 120 BPM loop previewed in a 140 BPM project
  11827. const auto dir = juce::File (prefix).getParentDirectory().getChildFile ("audiox-preview");
  11828. dir.createDirectory();
  11829. const auto wav = dir.getChildFile ("Drum loop 120 bpm.wav");
  11830. {
  11831. const int frames = 44100 * 4;
  11832. juce::AudioBuffer<float> audio (1, frames);
  11833. for (int i = 0; i < frames; ++i)
  11834. {
  11835. const auto t = (double) (i % 22050) / 44100.0;
  11836. audio.setSample (0, i, (float) (0.8 * std::exp (-t * 30.0) * std::sin (6.283185307179586 * (50.0 + 80.0 * std::exp (-t * 40.0)) * t)));
  11837. }
  11838. wav.deleteFile();
  11839. juce::WavAudioFormat format;
  11840. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  11841. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  11842. {
  11843. out.release();
  11844. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  11845. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  11846. }
  11847. }
  11848. offline.getTransport().bpm.store (140.0);
  11849. offline.setPreviewInTime (true);
  11850. ui.showDesktopForSnapshot (false);
  11851. offline.previewFile (wav);
  11852. offline.finishPreviewJobs();
  11853. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  11854. offline.dispatchPendingMessages();
  11855. saveSnapshot (ui, prefix + "-preview-in-time.png");
  11856. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { ui.getBrowserForSnapshot().buildViewMenu() }, prefix + "-preview-menu.png");
  11857. const auto& timing = offline.getPreviewTiming();
  11858. report << "preview file_bpm=" << timing.fileBpm << " project_bpm=" << timing.projectBpm << " ratio=" << timing.ratio
  11859. << " prepare_ms=" << juce::String (offline.getLastPreviewPrepareMs(), 1) << "\n";
  11860. offline.previewFile ({});
  11861. offline.setPreviewInTime (false);
  11862. juce::File (prefix + "-report.txt").replaceWithText (report);
  11863. }
  11864. }
  11865. void runComp177Shot (const juce::String& prefix, const juce::String& projectPath)
  11866. {
  11867. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11868. lynx::AudioEngine offline (false);
  11869. {
  11870. lynx::MainComponent ui (offline, false);
  11871. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  11872. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  11873. ui.openFile (juce::File (projectPath));
  11874. offline.dispatchPendingMessages();
  11875. ui.selectTabForSnapshot (2);
  11876. offline.dispatchPendingMessages();
  11877. auto& playlist = ui.getPlaylistForSnapshot();
  11878. std::int64_t last = 0;
  11879. for (const auto& c : offline.getSong().playlist)
  11880. last = std::max (last, c.end());
  11881. const auto bars = juce::jmax (1, (int) (last / (4 * lynx::ppq)) + 1);
  11882. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  11883. // (the first paint asks for the clips' waveforms, a worker thread loads them)
  11884. saveSnapshot (ui, prefix + "-opened.png");
  11885. juce::Thread::sleep (3000);
  11886. offline.dispatchPendingMessages();
  11887. saveSnapshot (ui, prefix + "-opened.png");
  11888. // a muted clip selected
  11889. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  11890. if (offline.getSong().playlist[(std::size_t) c].muted)
  11891. {
  11892. playlist.selectClipsForSnapshot ({ c });
  11893. offline.dispatchPendingMessages();
  11894. saveSnapshot (ui, prefix + "-selected.png");
  11895. playlist.selectClipsForSnapshot ({});
  11896. break;
  11897. }
  11898. juce::String report;
  11899. const auto listTracks = [&offline, &report] (const juce::String& title) {
  11900. const auto& s = offline.getSong();
  11901. report << title << "\n";
  11902. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  11903. {
  11904. int clips = 0, muted = 0;
  11905. for (const auto& c : s.playlist)
  11906. if (c.track == t)
  11907. ++clips, muted += c.muted ? 1 : 0;
  11908. const auto& pt = s.playlistTracks[(std::size_t) t];
  11909. if (clips > 0 || pt.grouped || ! pt.name.empty())
  11910. report << "track " << (t + 1) << " '" << juce::String::fromUTF8 (pt.name.c_str()) << "' grouped=" << (pt.grouped ? 1 : 0) << " collapsed=" << (pt.collapsed ? 1 : 0)
  11911. << " comp=" << (pt.compTrack ? 1 : 0) << " clips=" << clips << " muted=" << muted << "\n";
  11912. }
  11913. };
  11914. listTracks ("opened");
  11915. // the first group's header (a member's menu holds "Comp these takes" too)
  11916. int firstGroup = -1;
  11917. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && firstGroup < 0; ++t)
  11918. if (lynx::comp::canComp (offline.getSong(), t))
  11919. firstGroup = t;
  11920. report << "first group with takes: track " << (firstGroup + 1) << "\n";
  11921. if (firstGroup >= 0)
  11922. {
  11923. saveMenus (juce::StringArray { "Playlist track" }, std::vector<juce::PopupMenu> { playlist.getTrackMenuForSnapshot (firstGroup) }, prefix + "-trackmenu.png");
  11924. int comp = -1;
  11925. offline.editSong ([firstGroup, &comp] (lynx::Song& s) { comp = lynx::comp::compTakes (s, firstGroup); });
  11926. offline.dispatchPendingMessages();
  11927. saveSnapshot (ui, prefix + "-comped.png");
  11928. listTracks ("after Comp these takes");
  11929. const auto g = lynx::comp::groupOf (offline.getSong(), comp);
  11930. std::int64_t from = -1, to = 0;
  11931. for (const auto& c : offline.getSong().playlist)
  11932. if (c.track == g.first)
  11933. from = from < 0 ? c.start : std::min (from, c.start), to = std::max (to, c.end());
  11934. if (g.valid() && to > from)
  11935. {
  11936. offline.editSong ([&g, from, to] (lynx::Song& s) { lynx::comp::swipe (s, g.first, from + (to - from) / 4, from + (to - from) / 2); });
  11937. offline.dispatchPendingMessages();
  11938. saveSnapshot (ui, prefix + "-swiped.png");
  11939. listTracks ("after a swipe of the middle of the first lane");
  11940. // a lane auditioned; the crossfade close up; the comp flattened
  11941. offline.editSong ([&g] (lynx::Song& s) { lynx::comp::setAudition (s, g.first); }, false);
  11942. offline.dispatchPendingMessages();
  11943. saveSnapshot (ui, prefix + "-audition.png");
  11944. offline.editSong ([] (lynx::Song& s) { lynx::comp::setAudition (s, -1); }, false);
  11945. const auto switchAt = from + (to - from) / 4;
  11946. playlist.setViewForSnapshot (4.0 * 4.0 * lynx::ppq, 0, 0);
  11947. playlist.setScrollTickForSnapshot ((double) (switchAt - 100));
  11948. juce::Thread::sleep (1500);
  11949. offline.dispatchPendingMessages();
  11950. saveSnapshot (ui, prefix + "-crossfade.png");
  11951. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  11952. offline.editSong ([comp] (lynx::Song& s) { lynx::comp::flatten (s, comp); });
  11953. offline.dispatchPendingMessages();
  11954. saveSnapshot (ui, prefix + "-flattened.png");
  11955. listTracks ("after Flatten comp");
  11956. }
  11957. }
  11958. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getRecordMenuForSnapshot() }, prefix + "-recordmenu.png");
  11959. juce::File (prefix + "-tracks.txt").replaceWithText (report);
  11960. }
  11961. }
  11962. void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
  11963. {
  11964. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11965. lynx::AudioEngine offline (false);
  11966. {
  11967. lynx::MainComponent ui (offline, false);
  11968. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  11969. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  11970. if (projectPath.isNotEmpty())
  11971. ui.openFile (juce::File (projectPath));
  11972. offline.dispatchPendingMessages();
  11973. ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
  11974. offline.dispatchPendingMessages();
  11975. // the scale the pattern's notes fit best (major / minor, any root)
  11976. const auto& song = offline.getSong();
  11977. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  11978. int bestRoot = 0, bestScale = 1, bestHits = -1;
  11979. for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
  11980. {
  11981. const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
  11982. if (name != "Major" && name != "Minor")
  11983. continue;
  11984. for (int root = 0; root < 12; ++root)
  11985. {
  11986. int hits = 0;
  11987. for (const auto& n : notes)
  11988. hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
  11989. if (hits > bestHits)
  11990. bestHits = hits, bestRoot = root, bestScale = sc;
  11991. }
  11992. }
  11993. auto& roll = ui.getPianoRollForSnapshot();
  11994. roll.setScaleForSnapshot (bestRoot, bestScale);
  11995. roll.scrollToNotes();
  11996. offline.dispatchPendingMessages();
  11997. saveSnapshot (ui, prefix + "-pr-scale.png");
  11998. roll.setFoldToScale (true);
  11999. offline.dispatchPendingMessages();
  12000. saveSnapshot (ui, prefix + "-pr-folded.png");
  12001. roll.setFoldToScale (false);
  12002. // ghost channels: only the first other channel with notes stays a ghost
  12003. const auto selected = offline.getSelectedChannel();
  12004. int keep = -1;
  12005. for (const auto& n : notes)
  12006. if (n.channel != selected && keep < 0)
  12007. keep = n.channel;
  12008. offline.editSong ([keep] (lynx::Song& s) {
  12009. for (int c = 0; c < (int) s.channels.size(); ++c)
  12010. s.channels[(std::size_t) c].ghostHidden = c != keep;
  12011. }, false);
  12012. offline.dispatchPendingMessages();
  12013. saveSnapshot (ui, prefix + "-pr-ghost-one.png");
  12014. saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
  12015. offline.editSong ([] (lynx::Song& s) {
  12016. for (auto& c : s.channels)
  12017. c.ghostHidden = false;
  12018. }, false);
  12019. // the Mixer at 500 inserts
  12020. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  12021. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
  12022. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  12023. offline.dispatchPendingMessages();
  12024. ui.selectTabForSnapshot (3);
  12025. offline.dispatchPendingMessages();
  12026. auto& mixer = ui.getMixerForSnapshot();
  12027. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  12028. saveSnapshot (ui, prefix + "-mixer500-start.png");
  12029. const auto t3 = juce::Time::getMillisecondCounterHiRes();
  12030. mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
  12031. offline.dispatchPendingMessages();
  12032. saveSnapshot (ui, prefix + "-mixer500-end.png");
  12033. juce::File (prefix + "-mixer500.txt")
  12034. .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
  12035. + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
  12036. }
  12037. }
  12038. void runGridShot (const juce::String& prefix, const juce::String& projectPath = {})
  12039. {
  12040. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12041. lynx::AudioEngine offline (false);
  12042. lynx::MainComponent ui (offline, false);
  12043. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  12044. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  12045. const auto write = [&prefix, &ui] (const char* name) {
  12046. const auto file = juce::File (prefix + "-" + name + ".png");
  12047. file.deleteFile();
  12048. juce::FileOutputStream out (file);
  12049. juce::PNGImageFormat().writeImageToStream (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), out);
  12050. };
  12051. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  12052. if (projectPath.isNotEmpty())
  12053. {
  12054. ui.openFile (juce::File (projectPath));
  12055. offline.dispatchPendingMessages();
  12056. ui.setClipLaunchWorkflow (true);
  12057. offline.dispatchPendingMessages();
  12058. write ("file-both");
  12059. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  12060. write ("file-grid");
  12061. const auto& song = offline.getSong();
  12062. juce::String info;
  12063. info << "grid " << (song.clipGrid ? "yes" : "no") << ", clips " << (song.clipGrid ? (int) song.clipGrid->clips.size() : 0)
  12064. << ", scenes " << (song.clipGrid ? (int) song.clipGrid->scenes.size() : 0) << ", playlist clips " << (int) song.playlist.size() << "\n";
  12065. juce::File (prefix + "-file.txt").replaceWithText (info);
  12066. ui.setClipLaunchWorkflow (false);
  12067. return;
  12068. }
  12069. write ("pattern"); // Pattern workflow: nothing of the grid exists yet
  12070. const auto madeBefore = lynx::launcher::Runtime::instances.load();
  12071. offline.editSong ([] (lynx::Song& s) {
  12072. while (s.patterns.size() < 6)
  12073. s.patterns.emplace_back();
  12074. for (int p = 0; p < 6; ++p)
  12075. {
  12076. auto& pattern = s.patterns[(std::size_t) p];
  12077. const char* names[] { "Drums A", "Drums B", "Bass", "Chords", "Lead", "Pad" };
  12078. pattern.name = names[p];
  12079. pattern.lengthTicks = 4 * lynx::ppq;
  12080. }
  12081. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  12082. const char* tracks[] { "Drums", "Bass", "Chords", "Lead", "Vocals", "FX" };
  12083. for (int t = 0; t < 6; ++t)
  12084. s.playlistTracks[(std::size_t) t].name = tracks[t];
  12085. const int placed[][3] { { 0, 0, 0 }, { 0, 1, 1 }, { 0, 2, 0 }, { 0, 3, 1 }, { 1, 0, 2 }, { 1, 2, 2 }, { 2, 1, 3 }, { 2, 2, 3 }, { 3, 2, 4 }, { 3, 3, 4 }, { 4, 3, 5 } };
  12086. for (const auto& c : placed)
  12087. {
  12088. lynx::Clip clip;
  12089. clip.pattern = c[2];
  12090. clip.length = 4 * lynx::ppq;
  12091. lynx::launcher::setClip (s, c[0], c[1], clip);
  12092. }
  12093. auto& grid = lynx::launcher::ensureGrid (s);
  12094. const char* scenes[] { "Intro", "Verse", "Drop", "Break" };
  12095. grid.scenes.resize (6);
  12096. for (int r = 0; r < 4; ++r)
  12097. grid.scenes[(std::size_t) r].name = scenes[r];
  12098. }, false);
  12099. offline.dispatchPendingMessages();
  12100. write ("pattern-edited"); // the same song as -pattern-after: the workflow must leave no trace
  12101. ui.setClipLaunchWorkflow (true);
  12102. offline.dispatchPendingMessages();
  12103. if (auto* runtime = offline.launcherStateForSnapshot())
  12104. {
  12105. runtime->tracks[0].playing.store (2);
  12106. runtime->tracks[0].progress.store (0.4f);
  12107. runtime->tracks[0].taken.store (true);
  12108. runtime->tracks[1].playing.store (2);
  12109. runtime->tracks[1].progress.store (0.4f);
  12110. runtime->tracks[1].taken.store (true);
  12111. runtime->tracks[2].pending.store (2);
  12112. runtime->tracks[3].taken.store (true);
  12113. }
  12114. write ("both");
  12115. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  12116. write ("grid");
  12117. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  12118. write ("song");
  12119. ui.setClipLaunchWorkflow (false);
  12120. write ("pattern-after");
  12121. juce::File (prefix + "-counts.txt").replaceWithText ("runtimes before " + juce::String (madeBefore) + ", after " + juce::String (lynx::launcher::Runtime::instances.load()) + "\n");
  12122. }
  12123. void runSimpleShot (const juce::String& prefix)
  12124. {
  12125. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12126. lynx::AudioEngine offline (false);
  12127. lynx::MainComponent ui (offline, false);
  12128. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  12129. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  12130. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  12131. const auto file = juce::File (prefix + "-" + name + ".png");
  12132. file.deleteFile();
  12133. juce::FileOutputStream out (file);
  12134. juce::PNGImageFormat().writeImageToStream (image, out);
  12135. };
  12136. const auto write = [&ui, &writeImage] (const char* name) { writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name); };
  12137. // View › Layout style, with its submenu, as it is with `style` chosen
  12138. const auto viewMenu = [&ui] {
  12139. const auto names = ui.getMenuNamesForSnapshot();
  12140. const auto view = names.indexOf (lynx::tr ("View"));
  12141. return ui.getMenuForSnapshot (juce::jmax (0, view));
  12142. };
  12143. const auto saveStyleMenus = [&] (const juce::String& suffix) {
  12144. const auto view = viewMenu();
  12145. juce::StringArray names { lynx::tr ("View") };
  12146. std::vector<juce::PopupMenu> menus { view };
  12147. for (juce::PopupMenu::MenuItemIterator it (view); it.next();)
  12148. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Layout style"))
  12149. {
  12150. names.add (lynx::tr ("Layout style"));
  12151. menus.push_back (*it.getItem().subMenu);
  12152. }
  12153. saveMenus (names, menus, prefix + "-menu-" + suffix + ".png");
  12154. };
  12155. // Settings › General with `style` selected, and its style list
  12156. const auto saveSettings = [&] (lynx::layoutstyle::Style style, const char* name) {
  12157. lynx::SettingsHooks hooks;
  12158. hooks.getGeneral = [style] {
  12159. lynx::GeneralOptions o;
  12160. o.language = lynx::i18n::current();
  12161. o.layoutStyle = (int) style;
  12162. return o;
  12163. };
  12164. auto page = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general, false, hooks);
  12165. juce::Image image (juce::Image::ARGB, page->getWidth(), juce::jmin (page->getHeight(), 420), true);
  12166. {
  12167. juce::Graphics g (image);
  12168. g.fillAll (lynx::theme::panel);
  12169. page->paintEntireComponent (g, false);
  12170. }
  12171. writeImage (image, name);
  12172. std::function<juce::ComboBox* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ComboBox* {
  12173. if (c.getComponentID() == "layoutStyle")
  12174. return dynamic_cast<juce::ComboBox*> (&c);
  12175. for (auto* child : c.getChildren())
  12176. if (auto* box = find (*child))
  12177. return box;
  12178. return nullptr;
  12179. };
  12180. if (auto* box = find (*page); box != nullptr && box->getRootMenu() != nullptr)
  12181. saveMenus (juce::StringArray { lynx::tr ("Layout style") }, std::vector<juce::PopupMenu> { *box->getRootMenu() },
  12182. prefix + "-" + name + "-list.png");
  12183. };
  12184. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  12185. ui.selectTabForSnapshot (2); // the Playlist panel, maximized (as --gridshot)
  12186. write ("pattern");
  12187. saveStyleMenus ("pattern");
  12188. saveSettings (lynx::layoutstyle::Style::pattern, "settings-pattern");
  12189. const auto madePattern = lynx::SimpleWorkflow::instances.load();
  12190. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  12191. saveStyleMenus ("cliplaunch");
  12192. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  12193. offline.dispatchPendingMessages();
  12194. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  12195. simple->showChooser(); // (an empty project opens on it by itself; the offline project may hold the default song)
  12196. write ("simple"); // the New track chooser (slice S3)
  12197. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  12198. {
  12199. simple->showStarterPageForSnapshot();
  12200. write ("simple-starter");
  12201. simple->hideChooser();
  12202. write ("simple-closed");
  12203. // round 190p: a loop keeps time. Two files with the same 4.8 s of audio dropped on the empty Simple timeline:
  12204. // "Guitar loop 100.wav" (2 bars at 100 BPM) lasts 2 bars at the project's tempo, "Guitar take.wav" plays at
  12205. // its own speed. Both are undone again, so the shots after this one are as they were.
  12206. {
  12207. const auto folder = juce::File (prefix + "-loops");
  12208. folder.createDirectory();
  12209. juce::StringArray files;
  12210. for (const auto* name : { "Guitar loop 100.wav", "Guitar take.wav" })
  12211. {
  12212. const auto file = folder.getChildFile (name);
  12213. file.deleteFile();
  12214. const auto rate = 44100.0;
  12215. const auto frames = (int) (4.8 * rate);
  12216. juce::AudioBuffer<float> audio (1, frames);
  12217. for (int i = 0; i < frames; ++i)
  12218. {
  12219. const auto t = (double) i / rate, inBeat = std::fmod (t, 0.6); // a plucked note on every beat at 100 BPM
  12220. audio.setSample (0, i, (float) (0.7 * std::exp (-inBeat * 7.0) * std::sin (juce::MathConstants<double>::twoPi * 196.0 * t)));
  12221. }
  12222. if (auto out = file.createOutputStream())
  12223. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0)))
  12224. {
  12225. out.release();
  12226. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  12227. }
  12228. files.add (file.getFullPathName());
  12229. }
  12230. simple->dropFiles (files, 0);
  12231. offline.dispatchPendingMessages();
  12232. // the clips' waveforms are analysed in the background and drawn once ready (a live window repaints by
  12233. // itself; one off-screen paint came too early and showed empty clips)
  12234. for (const auto& path : files)
  12235. lynx::ui::WaveformCache::getInstance()->find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  12236. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  12237. offline.dispatchPendingMessages();
  12238. write ("simple-loop");
  12239. const auto& song = offline.getSong();
  12240. juce::String report;
  12241. for (const auto& clip : song.playlist)
  12242. if (clip.kind == lynx::ClipKind::audio)
  12243. report << song.channels[(std::size_t) clip.channel].name << ": " << juce::String ((double) clip.length / lynx::ppq, 3) << " beats, stretch "
  12244. << juce::String (song.channels[(std::size_t) clip.channel].sampler.stretchBeats, 2) << "\n";
  12245. juce::File (prefix + "-loop.txt").replaceWithText ("tempo " + juce::String (song.bpm, 1) + "\n" + report);
  12246. for (int i = 0; i < files.size() && offline.canUndo(); ++i) // (one undo step per dropped file)
  12247. offline.undo();
  12248. offline.dispatchPendingMessages();
  12249. simple->hideChooser();
  12250. }
  12251. // round 190t, slice A: one click on a starter beat adds it, placed for four bars (undone again)
  12252. {
  12253. const auto clipsBefore = offline.getSong().playlist.size();
  12254. const auto tempoBefore = offline.getSong().bpm;
  12255. simple->clickStarterForSnapshot (1);
  12256. offline.dispatchPendingMessages();
  12257. write ("simple-starter-added");
  12258. const auto& song = offline.getSong();
  12259. juce::String report ("tempo " + juce::String (tempoBefore, 1) + " -> " + juce::String (song.bpm, 1) + "\n");
  12260. for (auto i = clipsBefore; i < song.playlist.size(); ++i)
  12261. report << "clip at beat " << juce::String ((double) song.playlist[i].start / lynx::ppq, 2) << ", " << juce::String ((double) song.playlist[i].length / lynx::ppq, 2)
  12262. << " beats, pattern " << song.playlist[i].pattern << ", track " << song.playlist[i].track << "\n";
  12263. juce::File (prefix + "-starter.txt").replaceWithText (report);
  12264. if (song.playlist.size() > clipsBefore && offline.canUndo())
  12265. offline.undo();
  12266. offline.dispatchPendingMessages();
  12267. simple->hideChooser();
  12268. }
  12269. // slice S4: the Simple headers with a few tracks (voice, instrument, drums, an audio file), some levels moved
  12270. offline.editSong ([] (lynx::Song& s) {
  12271. namespace st = lynx::simpletracks;
  12272. st::Request q;
  12273. q.kind = st::Kind::voice;
  12274. q.name = "Lead vocal";
  12275. st::addTrack (s, q);
  12276. q = {};
  12277. q.kind = st::Kind::instrument;
  12278. q.name = "Keys";
  12279. lynx::ChannelDef keys;
  12280. keys.instrument = lynx::InstrumentKind::synth;
  12281. q.channel = keys;
  12282. lynx::Pattern chords;
  12283. for (int i = 0; i < 4; ++i)
  12284. for (int k : { 60, 64, 67 })
  12285. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  12286. q.pattern = chords;
  12287. const auto r = st::addTrack (s, q);
  12288. q = {};
  12289. q.kind = st::Kind::drums;
  12290. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  12291. {
  12292. lynx::ChannelDef c;
  12293. c.instrument = kind;
  12294. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  12295. q.kit.push_back (c);
  12296. }
  12297. lynx::Pattern beat;
  12298. const auto hit = [&beat] (int step, int row) { beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, row, 60 }); };
  12299. for (int step = 0; step < 16; step += 2)
  12300. hit (step, 2); // hats on the 8ths, kick on 1 and 3, snare on 2 and 4
  12301. for (int step : { 0, 8 })
  12302. hit (step, 0);
  12303. for (int step : { 4, 12 })
  12304. hit (step, 1);
  12305. q.pattern = beat;
  12306. q.bpm = 96.0;
  12307. st::addTrack (s, q);
  12308. if (r.insert > 0)
  12309. {
  12310. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  12311. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  12312. s.mixer[(std::size_t) r.insert].solo = true;
  12313. }
  12314. });
  12315. offline.dispatchPendingMessages();
  12316. ui.getPlaylistForSnapshot().selectTrack (1);
  12317. write ("simple-tracks");
  12318. // round 190t, slice E: the backup status beside the title tools, in each of its states
  12319. {
  12320. const auto now = juce::Time::currentTimeMillis();
  12321. juce::String states;
  12322. int n = 0;
  12323. for (const auto& text : { lynx::MainComponent::simpleSaveStatusText (true, false, 0, now), lynx::MainComponent::simpleSaveStatusText (true, false, now - 5000, now),
  12324. lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now), lynx::MainComponent::simpleSaveStatusText (false, true, 0, now),
  12325. lynx::MainComponent::simpleSaveStatusText (false, false, 0, now) })
  12326. {
  12327. simple->setStatusForSnapshot (text);
  12328. offline.dispatchPendingMessages();
  12329. states << n << ": " << text << "\n";
  12330. writeImage (ui.createComponentSnapshot (ui.getLocalBounds().withTop (juce::jmin (ui.getHeight() - 1, 70)).withHeight (juce::jmin (ui.getHeight(), 44)), true, 1.0f),
  12331. ("status-" + juce::String (n++)).toRawUTF8());
  12332. }
  12333. juce::File (prefix + "-status.txt").replaceWithText (states);
  12334. simple->setStatusForSnapshot (lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now));
  12335. offline.dispatchPendingMessages();
  12336. write ("simple-status");
  12337. }
  12338. // slice S8: the Finish dock, empty, then with a look on the Master (Balanced, Normal, a little Tone)
  12339. simple->showFinish();
  12340. offline.dispatchPendingMessages();
  12341. write ("simple-finish-empty");
  12342. offline.editSongStructural ([] (lynx::Song& s) { lynx::looks::apply (s, lynx::MasterLookSettings { lynx::looks::balanced, 0.5f, { 1.5f, 0.0f, 1.0f }, -3.0f }); });
  12343. offline.dispatchPendingMessages();
  12344. simple->showFinish();
  12345. write ("simple-finish");
  12346. simple->hideFinish();
  12347. }
  12348. saveStyleMenus ("simple");
  12349. saveSettings (lynx::layoutstyle::Style::simple, "settings-simple");
  12350. // round 184a S11: the Key panel (no key, then an A minor riff and its guesses) and its menu
  12351. const auto toolbarShot = [&] (const char* name) {
  12352. writeImage (ui.createComponentSnapshot (ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 80)), true, 1.0f), name);
  12353. };
  12354. toolbarShot ("key-none");
  12355. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-empty.png");
  12356. offline.editSong ([] (lynx::Song& s) {
  12357. if (s.channels.empty())
  12358. s.channels.resize (1);
  12359. if (s.patterns.empty())
  12360. s.patterns.emplace_back();
  12361. int t = 0;
  12362. for (int k : { 57, 60, 64, 67, 69, 67, 64, 60, 57, 59, 60, 62, 64, 62, 60, 59, 57, 57, 64, 45 })
  12363. {
  12364. lynx::Note n;
  12365. n.channel = 0;
  12366. n.key = k;
  12367. n.start = t * lynx::ppq / 2;
  12368. n.length = k == 57 || k == 45 ? lynx::ppq : lynx::ppq / 2;
  12369. s.patterns[0].notes.push_back (n);
  12370. ++t;
  12371. }
  12372. });
  12373. offline.dispatchPendingMessages();
  12374. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-guess.png");
  12375. const auto guesses = lynx::keyguess::guess (offline.getSong(), 3);
  12376. if (! guesses.empty())
  12377. offline.editSong ([k = guesses[0].key] (lynx::Song& s) { lynx::projectkey::set (s, k); });
  12378. offline.dispatchPendingMessages();
  12379. toolbarShot ("key-set");
  12380. write ("simple-key");
  12381. juce::String keyCounts;
  12382. for (const auto& g : guesses)
  12383. keyCounts << "guess " << lynx::projectkey::name (g.key) << " " << g.notesInScale << "/" << g.notes << " score " << g.score << "\n";
  12384. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, std::nullopt); });
  12385. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  12386. offline.dispatchPendingMessages();
  12387. toolbarShot ("key-pattern-toolbar");
  12388. write ("pattern-after");
  12389. // round 184a S17: the setup wizard with its Workflow choice — a first start (Pattern selected), then reopened in Simple
  12390. for (int style : { 0, 2 })
  12391. {
  12392. auto wizard = lynx::makeSetupWizardContent (offline, {}, {}, style, {});
  12393. juce::Image image (juce::Image::ARGB, wizard->getWidth(), wizard->getHeight(), true);
  12394. {
  12395. juce::Graphics g (image);
  12396. wizard->paintEntireComponent (g, false);
  12397. }
  12398. writeImage (image, style == 0 ? "wizard-pattern" : "wizard-simple");
  12399. }
  12400. juce::File (prefix + "-counts.txt").replaceWithText ("simple workflows before " + juce::String (madeBefore) + ", in pattern workflow "
  12401. + juce::String (madePattern) + ", after " + juce::String (lynx::SimpleWorkflow::instances.load())
  12402. + "\nstyle after " + lynx::layoutstyle::id (ui.getLayoutStyle()) + "\n" + keyCounts);
  12403. }
  12404. void runDetailShot (const juce::String& prefix)
  12405. {
  12406. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12407. lynx::AudioEngine offline (false);
  12408. lynx::MainComponent ui (offline, false);
  12409. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  12410. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  12411. const auto write = [&prefix, &ui] (const char* name) {
  12412. const auto file = juce::File (prefix + "-" + name + ".png");
  12413. file.deleteFile();
  12414. juce::FileOutputStream out (file);
  12415. juce::PNGImageFormat().writeImageToStream (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), out);
  12416. };
  12417. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  12418. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  12419. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  12420. offline.editSong ([] (lynx::Song& s) {
  12421. if (s.channels.size() < 2)
  12422. s.channels.resize (2);
  12423. s.channels[0].name = "Bass synth";
  12424. s.channels[0].mixerTrack = 2;
  12425. s.channels[1].mixerTrack = 3;
  12426. if (s.mixer.size() < 4)
  12427. s.mixer.resize (4);
  12428. s.mixer[2].name = "Bass";
  12429. s.mixer[2].effects.clear();
  12430. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::reverb, lynx::EffectKind::delay })
  12431. {
  12432. lynx::EffectSlot fx;
  12433. fx.kind = kind;
  12434. const auto& info = lynx::effectInfo (kind);
  12435. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  12436. fx.params[k] = info.params[k].defaultValue;
  12437. fx.enabled = kind != lynx::EffectKind::compressor; // one switched off
  12438. s.mixer[2].effects.push_back (fx);
  12439. }
  12440. while (s.patterns.size() < 2)
  12441. s.patterns.emplace_back();
  12442. s.patterns[0].name = "Bass line";
  12443. s.patterns[0].notes.clear();
  12444. for (int n = 0; n < 4; ++n)
  12445. {
  12446. lynx::Note note;
  12447. note.channel = 0;
  12448. note.start = n * lynx::ppq;
  12449. note.key = 36 + (n % 2) * 7;
  12450. s.patterns[0].notes.push_back (note);
  12451. }
  12452. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  12453. lynx::PatternEvents lane; // a volume swell for the Envelopes tab (slice 3)
  12454. lane.target = lynx::AutomationTarget { lynx::AutomationTargetKind::channelVolume, 0 };
  12455. for (int e = 0; e < 16; ++e)
  12456. lane.events.push_back ({ e * lynx::ppq / 4, 0.3f + 0.6f * (float) e / 15.0f });
  12457. s.patterns[0].events = { lane };
  12458. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  12459. s.playlistTracks[1].name = "Bass";
  12460. }, false);
  12461. offline.dispatchPendingMessages();
  12462. write ("pattern"); // Pattern workflow: no detail view exists
  12463. ui.setClipLaunchWorkflow (true);
  12464. offline.editSong ([] (lynx::Song& s) {
  12465. lynx::Clip clip;
  12466. clip.pattern = 0;
  12467. clip.length = 4 * lynx::ppq;
  12468. lynx::launcher::setClip (s, 1, 0, clip);
  12469. }, false);
  12470. offline.dispatchPendingMessages();
  12471. juce::String counts;
  12472. if (auto* detail = ui.getDetailViewForSnapshot())
  12473. {
  12474. detail->showSelection (1, 0);
  12475. detail->setPage (lynx::DetailView::Page::devices);
  12476. write ("devices");
  12477. counts << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << ", channel " << detail->chainChannelForCheck() << "\n";
  12478. detail->toggleFoldForCheck (3); // the reverb (card 0 is the instrument)
  12479. write ("folded");
  12480. counts << "folded card 3: " << (detail->isFoldedForCheck (3) ? 1 : 0) << "\n";
  12481. detail->showSelection (2, 0); // an empty track
  12482. write ("empty-track");
  12483. detail->showSelection (1, 0);
  12484. detail->setPage (lynx::DetailView::Page::clip);
  12485. offline.dispatchPendingMessages();
  12486. ui.getPianoRollForSnapshot().scrollToNotes(); // (the app does it on the message loop, which this shot doesn't run)
  12487. write ("clip"); // slice 2: the Piano roll docked here
  12488. {
  12489. // round 190s: the Transform panel with each MIDI tool, then Arpeggiate applied (and undone again)
  12490. auto& tools = detail->midiToolsForSnapshot();
  12491. for (int t = 0; t < lynx::MidiToolsPanel::toolCount; ++t)
  12492. {
  12493. tools.setTool (t);
  12494. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase()).toRawUTF8());
  12495. }
  12496. // round 190aa: the pages again with the settings of the Live shots they are compared with
  12497. tools.setAuto (false);
  12498. tools.setLiveShotSettingsForSnapshot();
  12499. for (int t : { (int) lynx::MidiToolsPanel::chop, (int) lynx::MidiToolsPanel::quantize, (int) lynx::MidiToolsPanel::timeWarp })
  12500. {
  12501. tools.setTool (t);
  12502. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase() + "-set").toRawUTF8());
  12503. }
  12504. tools.setAuto (true);
  12505. tools.setTool (lynx::MidiToolsPanel::arpeggiate);
  12506. tools.transformNow();
  12507. offline.dispatchPendingMessages();
  12508. write ("clip-mt-applied");
  12509. counts << "midi tools: arpeggiate made " << (int) offline.getSong().patterns[0].notes.size() << " notes of 4\n";
  12510. offline.undo();
  12511. offline.dispatchPendingMessages();
  12512. counts << "midi tools: undo gives " << (int) offline.getSong().patterns[0].notes.size() << " notes\n";
  12513. }
  12514. counts << "piano roll docked: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  12515. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() == detail ? 1 : 0) << "\n";
  12516. detail->setClipTab (true); // slice 3: the pattern's events in the Envelopes tab
  12517. offline.dispatchPendingMessages();
  12518. write ("envelopes");
  12519. detail->setClipTab (false);
  12520. detail->setPage (lynx::DetailView::Page::devices);
  12521. // round 183c-card: an Audio Effect Rack in the chain draws as its own card (the rack's view, Rand / Map in its
  12522. // title bar), as Live's Device View shows a rack
  12523. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.insert (s.mixer[2].effects.begin() + 1, shotRack()); }, false);
  12524. offline.dispatchPendingMessages();
  12525. detail->showSelection (2, 0);
  12526. detail->showSelection (1, 0);
  12527. write ("devices-rack");
  12528. counts << "rack card: cards " << detail->cardCountForCheck() << "\n";
  12529. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.erase (s.mixer[2].effects.begin() + 1); }, false);
  12530. offline.dispatchPendingMessages();
  12531. counts << "piano roll back in its panel: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  12532. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() != detail ? 1 : 0) << "\n";
  12533. }
  12534. else
  12535. counts << "no detail view\n";
  12536. ui.setClipLaunchWorkflow (false);
  12537. offline.dispatchPendingMessages();
  12538. write ("pattern-after");
  12539. juce::File (prefix + "-counts.txt").replaceWithText (counts);
  12540. }
  12541. void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
  12542. {
  12543. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12544. lynx::AudioEngine offline (false);
  12545. {
  12546. lynx::MainComponent ui (offline, false);
  12547. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  12548. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  12549. if (projectPath.isNotEmpty())
  12550. ui.openFile (juce::File (projectPath));
  12551. offline.dispatchPendingMessages();
  12552. // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
  12553. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
  12554. offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
  12555. offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
  12556. offline.dispatchPendingMessages();
  12557. // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
  12558. // and on every other one the next clip waiting for its sync point
  12559. const auto& song = offline.getSong();
  12560. auto& live = offline.performanceStateForSnapshot();
  12561. const auto zone = lynx::perf::zoneClips (song);
  12562. int lastTrack = -1, launched = 0;
  12563. for (const auto index : zone)
  12564. {
  12565. const auto& c = song.playlist[(std::size_t) index];
  12566. if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
  12567. continue;
  12568. lastTrack = c.track;
  12569. std::int64_t clips[64];
  12570. const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
  12571. auto& view = live.tracks[(std::size_t) c.track];
  12572. view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
  12573. view.progress.store (0.2f + 0.15f * (float) (launched % 5));
  12574. if (launched % 2 == 1 && n > 1)
  12575. view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
  12576. ++launched;
  12577. }
  12578. live.anyPlaying.store (launched > 0);
  12579. ui.selectTabForSnapshot (2);
  12580. offline.dispatchPendingMessages();
  12581. auto& playlist = ui.getPlaylistForSnapshot();
  12582. savePng (playlist.createComponentSnapshot (playlist.getLocalBounds()), prefix + "-playlist-song.png");
  12583. playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
  12584. offline.dispatchPendingMessages();
  12585. saveSnapshot (ui, prefix + "-playlist.png");
  12586. savePng (playlist.createComponentSnapshot (playlist.getLocalBounds()), prefix + "-playlist-only.png");
  12587. // patcherize: the first insert with effects (all of them) and the first channel that can be
  12588. auto patched = offline.getSong();
  12589. for (int t = 0; t < (int) patched.mixer.size(); ++t)
  12590. if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
  12591. {
  12592. lynx::patcherize::patcherizeSlots (patched, t, 0, true);
  12593. break;
  12594. }
  12595. for (int c = 0; c < (int) patched.channels.size(); ++c)
  12596. if (lynx::patcherize::patcherizeChannel (patched, c))
  12597. break;
  12598. juce::String error;
  12599. lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
  12600. }
  12601. }
  12602. void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
  12603. {
  12604. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12605. lynx::AudioEngine offline (false);
  12606. {
  12607. lynx::MainComponent ui (offline, false);
  12608. ui.setSize (1280, 720);
  12609. if (projectPath.isNotEmpty())
  12610. ui.openFile (juce::File (projectPath));
  12611. else
  12612. {
  12613. auto song = lynx::Song::makeDefault();
  12614. song.mixer.resize (4);
  12615. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  12616. slot.patcher.wires.clear();
  12617. for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
  12618. { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
  12619. {
  12620. lynx::PatchNode n;
  12621. n.effect = lynx::makeEffectSlot (kind);
  12622. n.x = x;
  12623. n.y = y;
  12624. slot.patcher.nodes.push_back (n);
  12625. }
  12626. { // round 165c: a Hardware Insert node (its editor opens from the node)
  12627. lynx::PatchNode n;
  12628. n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  12629. n.x = 420.0f, n.y = 260.0f;
  12630. slot.patcher.nodes.push_back (n);
  12631. }
  12632. auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
  12633. lynx::PatchWire w;
  12634. w.kind = kind;
  12635. w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
  12636. slot.patcher.wires.push_back (w);
  12637. };
  12638. wire (lynx::patchFromHost, 0, 0, 0);
  12639. wire (0, 1, 1, 0);
  12640. wire (0, 3, 2, 0, 0.5f);
  12641. wire (1, 0, lynx::patchToHost, 0);
  12642. wire (2, 0, lynx::patchToHost, 0);
  12643. wire (lynx::patchFromHost, 1, 3, 0);
  12644. wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  12645. wire (0, 2, lynx::patchToHost, 1, 0.7f);
  12646. // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
  12647. // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
  12648. {
  12649. lynx::SurfaceControl knob;
  12650. knob.name = "Knob 1";
  12651. knob.value = 0.6f;
  12652. slot.patcher.surface = { knob };
  12653. slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
  12654. lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
  12655. lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
  12656. lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
  12657. wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
  12658. wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  12659. }
  12660. slot.patcher.outputTracks = { 3 };
  12661. slot.patcher.inputX = -20.0f;
  12662. slot.patcher.outputX = 660.0f;
  12663. song.mixer[1].effects = { slot };
  12664. lynx::ChannelDef ch;
  12665. ch.name = "Patcher";
  12666. ch.instrument = lynx::InstrumentKind::patcher;
  12667. lynx::PatchNode synth, chorus;
  12668. synth.generator = true;
  12669. synth.channel.instrument = lynx::InstrumentKind::synth;
  12670. synth.channel.name = "Synth";
  12671. synth.x = 220.0f;
  12672. chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
  12673. chorus.x = 420.0f;
  12674. // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
  12675. // on the notes moving the chorus
  12676. lynx::PatchNode midiOut, envelope;
  12677. midiOut.generator = envelope.generator = true;
  12678. midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
  12679. midiOut.channel.name = "MIDI Out";
  12680. lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
  12681. midiOut.x = 220.0f, midiOut.y = 160.0f;
  12682. envelope.channel.instrument = lynx::InstrumentKind::controller;
  12683. envelope.channel.name = "Envelope Controller";
  12684. envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  12685. envelope.x = 220.0f, envelope.y = 260.0f;
  12686. lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
  12687. osc.generator = true;
  12688. osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  12689. osc.channel.instrument = lynx::InstrumentKind::threeosc;
  12690. osc.channel.name = "3x Osc";
  12691. osc.x = 420.0f, osc.y = 260.0f;
  12692. // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
  12693. lynx::PatchNode keys, soundfont, granulizer, dashboard;
  12694. keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
  12695. keys.channel.instrument = lynx::InstrumentKind::controller;
  12696. keys.channel.name = "Keyboard Controller";
  12697. {
  12698. lynx::KeyboardControllerData ramp;
  12699. for (std::size_t k = 0; k < ramp.keys.size(); ++k)
  12700. ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
  12701. lynx::writeKeyboardController (ramp, keys.channel.controllerState);
  12702. }
  12703. soundfont.channel = lynx::sf::makeChannel();
  12704. granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  12705. granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
  12706. granulizer.channel.name = "Fruity Granulizer";
  12707. dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
  12708. dashboard.channel.name = "Dashboard";
  12709. dashboard.channel.patcher.surface = lynx::surface::starterControls();
  12710. keys.x = 20.0f, keys.y = 440.0f;
  12711. soundfont.x = 220.0f, soundfont.y = 440.0f;
  12712. granulizer.x = 420.0f, granulizer.y = 440.0f;
  12713. dashboard.x = 20.0f, dashboard.y = 540.0f;
  12714. // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
  12715. lynx::PatchNode layerNode;
  12716. layerNode.generator = true;
  12717. layerNode.channel.instrument = lynx::InstrumentKind::layer;
  12718. layerNode.channel.name = "Layer";
  12719. layerNode.channel.layer.crossfade = true;
  12720. layerNode.channel.layer.fade = 0.35f;
  12721. layerNode.x = 220.0f, layerNode.y = 540.0f;
  12722. ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
  12723. lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
  12724. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  12725. a.from = 0, a.to = 1;
  12726. b.from = 1;
  12727. portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
  12728. portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
  12729. envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
  12730. envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
  12731. lynx::PatchWire oscNotes, oscOut;
  12732. oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
  12733. oscOut.from = 4;
  12734. lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
  12735. layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
  12736. layerNotes.to = 9;
  12737. layerToFont.from = 9, layerToFont.to = 6;
  12738. layerToGrains.from = 9, layerToGrains.to = 7;
  12739. fontOut.from = 6;
  12740. grainsOut.from = 7;
  12741. ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
  12742. ch.patcher.fromMidiPorts = { 1, 5 };
  12743. ch.patcher.toMidiPorts = { 3 };
  12744. ch.patcher.outputX = 640.0f;
  12745. song.channels.push_back (ch);
  12746. // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
  12747. if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
  12748. {
  12749. if (! song.patterns.empty())
  12750. for (int k = 0; k < 4; ++k)
  12751. 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 });
  12752. juce::String error;
  12753. lynx::ProjectFile::save (song, juce::File (save), error);
  12754. // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
  12755. juce::String report;
  12756. if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
  12757. {
  12758. const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  12759. && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
  12760. const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
  12761. report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
  12762. if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
  12763. {
  12764. const auto& a = song.mixer[1].effects[0].patcher;
  12765. report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
  12766. << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
  12767. for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
  12768. if (! (a.nodes[n] == d.nodes[n]))
  12769. report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
  12770. << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
  12771. << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
  12772. }
  12773. for (int n = 0; n < (int) d.nodes.size(); ++n)
  12774. report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
  12775. << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
  12776. for (const auto& w : d.wires)
  12777. if (w.kind == lynx::PatchWire::Kind::control)
  12778. report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
  12779. for (const auto& p : d.published)
  12780. report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
  12781. }
  12782. else
  12783. report << "patcher round trip: load failed: " << error << "\n";
  12784. juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
  12785. }
  12786. offline.setSong (std::move (song));
  12787. }
  12788. offline.dispatchPendingMessages();
  12789. const auto& song = offline.getSong();
  12790. auto shootOpen = [&] (const juce::String& name) {
  12791. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  12792. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  12793. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  12794. {
  12795. auto* c = w->getContentComponent();
  12796. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
  12797. delete w;
  12798. return;
  12799. }
  12800. };
  12801. int shots = 0;
  12802. for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
  12803. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  12804. if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
  12805. {
  12806. lynx::PatcherWindows::openSlot (offline, t, s);
  12807. shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
  12808. // each built-in node's editor, as a double-click opens it (round 165c)
  12809. lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
  12810. savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
  12811. });
  12812. ++shots;
  12813. if (shots == 1) // its menus (round 162)
  12814. lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
  12815. savePng (image, prefix + "-menu-" + name + ".png");
  12816. });
  12817. }
  12818. for (int c = 0; c < (int) song.channels.size(); ++c)
  12819. if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
  12820. {
  12821. lynx::PatcherWindows::openChannel (offline, c);
  12822. shootOpen ("-channel" + juce::String (c) + ".png");
  12823. // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
  12824. lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
  12825. savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
  12826. });
  12827. lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
  12828. savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
  12829. });
  12830. }
  12831. }
  12832. }
  12833. // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
  12834. struct TypeAheadTest final : private juce::Timer
  12835. {
  12836. juce::File out;
  12837. juce::StringArray log;
  12838. int step = 0, picked = 0;
  12839. bool ok = true, menuShown = false;
  12840. std::unique_ptr<juce::DocumentWindow> owner;
  12841. juce::PopupMenu pending;
  12842. static juce::String highlighted()
  12843. {
  12844. if (auto* window = juce::Component::getCurrentlyModalComponent())
  12845. for (auto* child : window->getChildren())
  12846. if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
  12847. return h->getTitle();
  12848. return "(none)";
  12849. }
  12850. static void press (const juce::KeyPress& key)
  12851. {
  12852. if (auto* window = juce::Component::getCurrentlyModalComponent())
  12853. if (auto* peer = window->getPeer())
  12854. peer->handleKeyPress (key);
  12855. }
  12856. void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
  12857. {
  12858. const auto good = got == wanted;
  12859. ok = ok && good;
  12860. log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
  12861. }
  12862. void start()
  12863. {
  12864. juce::PopupMenu menu, sub;
  12865. auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
  12866. m.addItem (text, enabled, false, [this, id] { picked = id; });
  12867. };
  12868. menu.addSectionHeader ("LYNX SHARE");
  12869. item (menu, 1, "Echoform");
  12870. item (menu, 2, "EQ");
  12871. item (menu, 3, "Halo");
  12872. menu.addSectionHeader ("Misc");
  12873. item (menu, 4, "Effector");
  12874. item (menu, 5, "Exciter (unavailable)", false);
  12875. item (sub, 10, "Delay");
  12876. item (sub, 11, "Edison");
  12877. item (sub, 12, "Eventide");
  12878. menu.addSubMenu ("Tree", sub);
  12879. // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
  12880. // menu of a background process at once)
  12881. owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
  12882. owner->setBounds (200, 200, 300, 200);
  12883. owner->setVisible (true);
  12884. lynx::forceForegroundForTest (*owner);
  12885. pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
  12886. startTimer (300);
  12887. }
  12888. void timerCallback() override
  12889. {
  12890. const auto e = juce::KeyPress ('e', {}, 'e');
  12891. if (step == 0 && owner != nullptr && ! menuShown)
  12892. {
  12893. menuShown = true;
  12894. lynx::forceForegroundForTest (*owner);
  12895. lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
  12896. return;
  12897. }
  12898. switch (step++)
  12899. {
  12900. case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
  12901. case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
  12902. case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
  12903. case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
  12904. case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
  12905. case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
  12906. case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
  12907. case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
  12908. case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
  12909. case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
  12910. case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
  12911. case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
  12912. case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
  12913. case 13: break;
  12914. default:
  12915. expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
  12916. expect ("Enter picked", juce::String (picked), "12");
  12917. stopTimer();
  12918. owner.reset();
  12919. log.add (ok ? "result=OK" : "result=FAIL");
  12920. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  12921. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  12922. juce::JUCEApplication::quit();
  12923. return;
  12924. }
  12925. }
  12926. };
  12927. std::unique_ptr<TypeAheadTest> typeAheadTest;
  12928. struct ChooserTest final : private juce::Timer
  12929. {
  12930. juce::File out, file;
  12931. juce::StringArray log;
  12932. std::unique_ptr<juce::FileChooser> chooser;
  12933. double started = 0;
  12934. bool shot = false, done = false;
  12935. void start()
  12936. {
  12937. log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
  12938. log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  12939. chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
  12940. started = juce::Time::getMillisecondCounterHiRes();
  12941. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  12942. [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
  12943. startTimer (200);
  12944. }
  12945. static juce::FileChooserDialogBox* builtInDialog()
  12946. {
  12947. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
  12948. if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
  12949. return box;
  12950. return nullptr;
  12951. }
  12952. static juce::FileBrowserComponent* findBrowser (juce::Component& c)
  12953. {
  12954. if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
  12955. return b;
  12956. for (auto* child : c.getChildren())
  12957. if (auto* b = findBrowser (*child))
  12958. return b;
  12959. return nullptr;
  12960. }
  12961. void timerCallback() override
  12962. {
  12963. if (done)
  12964. return;
  12965. if (auto* box = builtInDialog(); box != nullptr && ! shot)
  12966. {
  12967. shot = true;
  12968. log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
  12969. const auto image = box->createComponentSnapshot (box->getLocalBounds());
  12970. juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
  12971. if (png.openedOk())
  12972. {
  12973. png.setPosition (0), png.truncate();
  12974. juce::PNGImageFormat().writeImageToStream (image, png);
  12975. }
  12976. if (auto* browser = findBrowser (*box))
  12977. {
  12978. browser->setRoot (file.getParentDirectory());
  12979. browser->setFileName (file.getFileName());
  12980. log.add ("typed " + file.getFileName());
  12981. box->exitModalState (1);
  12982. }
  12983. else
  12984. log.add ("no file browser in the dialog");
  12985. }
  12986. if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
  12987. finish ({}, "timeout");
  12988. }
  12989. void finish (const juce::File& result, const juce::String& why = {})
  12990. {
  12991. if (done)
  12992. return;
  12993. done = true;
  12994. stopTimer();
  12995. log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
  12996. + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
  12997. log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  12998. const auto ok = result == file && result.existsAsFile();
  12999. log.add (ok ? "result=OK" : "result=FAIL");
  13000. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  13001. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  13002. juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
  13003. }
  13004. };
  13005. std::unique_ptr<ChooserTest> chooserTest;
  13006. void runChooserTest (const juce::File& out, const juce::File& file)
  13007. {
  13008. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13009. chooserTest = std::make_unique<ChooserTest>();
  13010. chooserTest->out = out;
  13011. chooserTest->file = file;
  13012. chooserTest->start();
  13013. }
  13014. void runTypeAheadTest (const juce::File& out)
  13015. {
  13016. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13017. typeAheadTest = std::make_unique<TypeAheadTest>();
  13018. typeAheadTest->out = out;
  13019. typeAheadTest->start();
  13020. }
  13021. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  13022. {
  13023. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13024. // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
  13025. if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
  13026. if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
  13027. lynx::themeui::apply (*spec, false);
  13028. {
  13029. lynx::AudioEngine offline (false);
  13030. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  13031. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  13032. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  13033. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  13034. if (projectPath.isNotEmpty())
  13035. ui.openFile (juce::File (projectPath));
  13036. offline.dispatchPendingMessages(); // change notifications are asynchronous
  13037. ui.waitForBrowserForSnapshot();
  13038. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  13039. // (and a sample hint in the status strip, as when hovering a knob)
  13040. ui.showDesktopForSnapshot (false);
  13041. ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
  13042. offline.dispatchPendingMessages();
  13043. saveSnapshot (ui, prefix + "-desktop.png");
  13044. // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
  13045. {
  13046. const auto size = ui.getBounds();
  13047. ui.showSetupWizard();
  13048. offline.dispatchPendingMessages();
  13049. saveSnapshot (ui, prefix + "-desktop-setup.png");
  13050. ui.setSize (1024, 600);
  13051. offline.dispatchPendingMessages();
  13052. saveSnapshot (ui, prefix + "-desktop-setup-small.png");
  13053. ui.closeSetupWizardForSnapshot();
  13054. ui.setBounds (size);
  13055. offline.dispatchPendingMessages();
  13056. }
  13057. // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
  13058. // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
  13059. {
  13060. const auto size = ui.getBounds();
  13061. for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
  13062. {
  13063. ui.setSize (w, h);
  13064. offline.dispatchPendingMessages();
  13065. saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
  13066. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
  13067. if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
  13068. {
  13069. ui.scrollRackForSnapshot (100000);
  13070. offline.dispatchPendingMessages();
  13071. saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
  13072. ui.scrollRackForSnapshot (0);
  13073. }
  13074. }
  13075. // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
  13076. ui.setSize (1600, 900);
  13077. for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
  13078. {
  13079. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  13080. layout.iconSize = iconSize;
  13081. ui.setToolbarLayoutForSnapshot (layout);
  13082. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
  13083. }
  13084. {
  13085. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  13086. layout.move (lynx::toolbarlayout::Group::windows, -3);
  13087. layout.setShown (lynx::toolbarlayout::Group::record, false);
  13088. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  13089. ui.setToolbarLayoutForSnapshot (layout);
  13090. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
  13091. }
  13092. {
  13093. // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
  13094. ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
  13095. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  13096. lynx::AutomationTarget t;
  13097. t.kind = lynx::AutomationTargetKind::mixerVolume;
  13098. t.index = 0;
  13099. offline.noteTweaked (t);
  13100. ui.refreshTweakReadoutForSnapshot();
  13101. offline.dispatchPendingMessages();
  13102. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
  13103. ui.setSize (1600, 900);
  13104. }
  13105. {
  13106. // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
  13107. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  13108. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  13109. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  13110. ui.setToolbarLayoutForSnapshot (layout);
  13111. ui.setToolbarEditingForSnapshot (true);
  13112. offline.dispatchPendingMessages();
  13113. saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
  13114. ui.setToolbarEditingForSnapshot (false);
  13115. // Ctrl+F11: only the menu and the hint bar
  13116. layout = lynx::toolbarlayout::Layout::makeDefault();
  13117. layout.visible = false;
  13118. ui.setToolbarLayoutForSnapshot (layout);
  13119. saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
  13120. }
  13121. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  13122. // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
  13123. offline.dispatchPendingMessages();
  13124. saveQuickTips (ui, prefix);
  13125. ui.setBounds (size);
  13126. offline.dispatchPendingMessages();
  13127. }
  13128. // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
  13129. // glyphs, and a text too long for one line (two lines)
  13130. {
  13131. const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
  13132. const lynx::ui::Hint hints[] = {
  13133. { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
  13134. { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
  13135. { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  13136. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
  13137. };
  13138. for (int i = 0; i < 3; ++i)
  13139. {
  13140. ui.setHintForSnapshot (hints[i], i == 0);
  13141. saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
  13142. }
  13143. }
  13144. ui.showDesktopForSnapshot (true);
  13145. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  13146. saveSnapshot (ui, prefix + "-desktop-all.png");
  13147. ui.selectTabForSnapshot (0);
  13148. saveSnapshot (ui, prefix + "-rack.png");
  13149. {
  13150. // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
  13151. int found = -1;
  13152. const auto before = offline.getSong().currentPattern;
  13153. {
  13154. const auto& song = offline.getSong();
  13155. for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
  13156. for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
  13157. if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
  13158. found = p;
  13159. }
  13160. if (found >= 0)
  13161. {
  13162. offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
  13163. offline.dispatchPendingMessages();
  13164. saveSnapshot (ui, prefix + "-rack-preview.png");
  13165. offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
  13166. offline.dispatchPendingMessages();
  13167. }
  13168. }
  13169. ui.selectTabForSnapshot (1);
  13170. saveSnapshot (ui, prefix + "-pianoroll.png");
  13171. {
  13172. // View › Keyboard style › Piano keys (round 190j, discussion #136), also with tall keys
  13173. auto& roll = ui.getPianoRollForSnapshot();
  13174. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  13175. roll.repaint();
  13176. saveSnapshot (ui, prefix + "-pianoroll-pianokeys.png");
  13177. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::flat;
  13178. roll.repaint();
  13179. // round 190j (discussion #10): the toolbar in a narrow window: the chord stamp as an icon button, and
  13180. // the menu button still there
  13181. for (int narrower : { 150, 270, 330 })
  13182. {
  13183. roll.squeezeToolbarForSnapshot (narrower);
  13184. saveSnapshot (ui, prefix + "-pianoroll-narrow" + juce::String (narrower) + ".png");
  13185. roll.squeezeToolbarForSnapshot (-narrower);
  13186. }
  13187. }
  13188. if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
  13189. saveArea (ui, strip, prefix + "-pianoroll-tools.png");
  13190. // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
  13191. ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
  13192. saveSnapshot (ui, prefix + "-pianoroll-hover.png");
  13193. {
  13194. // a pattern with note Chance or a Velocity Range (round 187c): the Piano roll with those lanes
  13195. const auto& song = offline.getSong();
  13196. const auto& notes = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)].notes;
  13197. if (std::any_of (notes.begin(), notes.end(), [] (const lynx::Note& n) { return n.hasChance(); }))
  13198. {
  13199. auto& roll = ui.getPianoRollForSnapshot();
  13200. ui.setHintForSnapshot ({});
  13201. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneChance, "chance" },
  13202. { lynx::PianoRollComponent::laneVelocityRange, "velrange" },
  13203. { lynx::PianoRollComponent::laneVelocity, "velocity" } })
  13204. {
  13205. roll.setLaneForSnapshot (lane);
  13206. offline.dispatchPendingMessages();
  13207. saveSnapshot (ui, prefix + "-pianoroll-" + name + ".png");
  13208. }
  13209. }
  13210. }
  13211. ui.selectTabForSnapshot (2);
  13212. saveSnapshot (ui, prefix + "-playlist.png");
  13213. if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
  13214. saveArea (ui, strip, prefix + "-playlist-tools.png");
  13215. ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
  13216. saveSnapshot (ui, prefix + "-playlist-hover.png");
  13217. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  13218. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  13219. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  13220. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  13221. offline.dispatchPendingMessages();
  13222. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  13223. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  13224. // round 177b: automation lanes on (two lanes under track 2: a volume ramp and a pan wobble)
  13225. {
  13226. const auto before = offline.getSong();
  13227. offline.editSong ([] (lynx::Song& s) {
  13228. s.loopStart = s.loopEnd = 0; // (no time selection in this one)
  13229. const auto bar = (std::int64_t) lynx::ppq * s.beatsPerBar;
  13230. const auto vol = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Insert 1 - Volume", 0.3f);
  13231. s.automations[(std::size_t) vol].points = { { 0, 0.3f, 0.0f }, { bar * 2, 0.8f, 0.4f }, { bar * 4, 0.6f, 0.0f } };
  13232. const auto pan = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, "Insert 1 - Pan", 0.5f);
  13233. s.automations[(std::size_t) pan].points = { { 0, 0.5f, 0.0f }, { bar, 0.2f, 0.0f }, { bar * 2, 0.8f, 0.0f }, { bar * 3, 0.5f, 0.0f } };
  13234. }, false);
  13235. lynx::autolanes::setShown (true);
  13236. ui.getPlaylistForSnapshot().resized();
  13237. offline.dispatchPendingMessages();
  13238. saveSnapshot (ui, prefix + "-playlist-lanes.png");
  13239. lynx::autolanes::setShown (false);
  13240. offline.editSong ([before] (lynx::Song& s) { s = before; }, false);
  13241. offline.dispatchPendingMessages();
  13242. }
  13243. // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
  13244. {
  13245. int header = -1;
  13246. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
  13247. if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
  13248. header = t;
  13249. if (header >= 0)
  13250. {
  13251. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
  13252. offline.dispatchPendingMessages();
  13253. saveSnapshot (ui, prefix + "-playlist-group-folded.png");
  13254. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
  13255. }
  13256. ui.getPickerForSnapshot().setView (1);
  13257. offline.dispatchPendingMessages();
  13258. saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
  13259. ui.getPickerForSnapshot().setView (0);
  13260. }
  13261. // round 104: the Channel Rack filtered to its first filter group
  13262. if (! offline.getSong().channelGroups.empty())
  13263. {
  13264. ui.selectTabForSnapshot (0);
  13265. ui.getRackForSnapshot().setFilterGroup (0);
  13266. offline.dispatchPendingMessages();
  13267. saveSnapshot (ui, prefix + "-rack-filter.png");
  13268. ui.getRackForSnapshot().setFilterGroup (-1);
  13269. }
  13270. ui.selectTabForSnapshot (3);
  13271. // LYNX_SNAPSHOT_ARRANGE=1 (round 186c): Mixer menu › "Arrange inserts like the Playlist" first
  13272. if (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_ARRANGE", {}) == "1")
  13273. {
  13274. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::arrangeLikePlaylist (s); });
  13275. offline.dispatchPendingMessages();
  13276. }
  13277. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  13278. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  13279. {
  13280. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  13281. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  13282. offline.dispatchPendingMessages();
  13283. }
  13284. saveSnapshot (ui, prefix + "-mixer.png");
  13285. // round 190am: LYNX's two mixer extras, before and after (the demo project leaves most inserts unused). The
  13286. // loudness panel shows a real measurement of 12 s of a test tone (a 1 kHz sine at -14 dBFS after a quieter
  13287. // stretch, pushed through the Master's tap as the audio thread does)
  13288. {
  13289. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  13290. saveSnapshot (ui, prefix + "-mixer190am-before.png");
  13291. strips.setShowUsedOnly (true);
  13292. offline.dispatchPendingMessages();
  13293. saveSnapshot (ui, prefix + "-mixer190am-usedonly.png");
  13294. strips.setShowUsedOnly (false);
  13295. strips.setShowLoudness (true);
  13296. {
  13297. const double sr = 48000.0;
  13298. std::vector<float> tone (480);
  13299. auto& tap = offline.getMeters().loudness;
  13300. for (int block = 0; block < 1200; ++block)
  13301. {
  13302. const auto gain = std::pow (10.0, (block < 400 ? -20.0 : -14.0) / 20.0);
  13303. for (int i = 0; i < 480; ++i)
  13304. tone[(std::size_t) i] = (float) (gain * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * (block * 480 + i) / sr));
  13305. tap.push (tone.data(), tone.data(), 480, sr);
  13306. }
  13307. }
  13308. strips.refreshLoudnessForSnapshot();
  13309. offline.dispatchPendingMessages();
  13310. saveSnapshot (ui, prefix + "-mixer190am-loudness.png");
  13311. for (const auto l : { lynx::mixerlayout::Layout::compact, lynx::mixerlayout::Layout::extraLarge })
  13312. {
  13313. const auto was = lynx::MixerStrips::layout;
  13314. strips.setLayout (l);
  13315. offline.dispatchPendingMessages();
  13316. saveSnapshot (ui, prefix + "-mixer190am-loudness-" + juce::String ((int) l) + ".png");
  13317. strips.setLayout (was);
  13318. }
  13319. strips.setShowUsedOnly (true);
  13320. offline.dispatchPendingMessages();
  13321. saveSnapshot (ui, prefix + "-mixer190am-both.png");
  13322. strips.setShowUsedOnly (false);
  13323. strips.setShowLoudness (false);
  13324. offline.dispatchPendingMessages();
  13325. }
  13326. // round 168h (issue #52): FL's 8 Mixer layouts
  13327. {
  13328. const auto before = lynx::MixerStrips::layout;
  13329. for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
  13330. {
  13331. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
  13332. offline.dispatchPendingMessages();
  13333. saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
  13334. }
  13335. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
  13336. offline.dispatchPendingMessages();
  13337. }
  13338. // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
  13339. {
  13340. const auto size = ui.getBounds();
  13341. for (auto h : { 450, 560, 680, 820 })
  13342. {
  13343. ui.setSize (size.getWidth(), h);
  13344. offline.dispatchPendingMessages();
  13345. saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
  13346. }
  13347. ui.setBounds (size);
  13348. offline.dispatchPendingMessages();
  13349. }
  13350. // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
  13351. // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
  13352. {
  13353. const auto before = offline.getSong();
  13354. offline.editSong ([] (lynx::Song& s) {
  13355. if (s.mixer.size() < 5)
  13356. return;
  13357. s.mixer[1].effects.clear();
  13358. lynx::EffectSlot fx;
  13359. fx.kind = lynx::EffectKind::compressor;
  13360. s.mixer[1].effects.push_back (fx);
  13361. lynx::mixerops::moveEffectBy (s, 1, 0, 1);
  13362. lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
  13363. });
  13364. ui.selectMixerTrackForSnapshot (1);
  13365. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
  13366. offline.dispatchPendingMessages();
  13367. saveSnapshot (ui, prefix + "-mixer170b.png");
  13368. juce::PopupMenu effects, generators;
  13369. lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
  13370. lynx::quickpick::addFolderViewItems (effects, offline);
  13371. lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  13372. lynx::quickpick::addFolderViewItems (generators, offline);
  13373. saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
  13374. offline.setSong (before);
  13375. offline.dispatchPendingMessages();
  13376. }
  13377. // standalone windows, with the theme background
  13378. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  13379. juce::Component frame;
  13380. frame.setSize (c->getWidth(), c->getHeight());
  13381. frame.setOpaque (true);
  13382. // an AlertWindow is built on the desktop: shown there first, it would take the foreground from whoever has it
  13383. // (TopLevelWindow::visibilityChanged calls toFront (true)). Off the desktop, its control that showing it would
  13384. // have focused (what grabKeyboardFocus picks) is marked, so the picture keeps that control's focus ring
  13385. if (c->isOnDesktop())
  13386. {
  13387. c->removeFromDesktop();
  13388. auto* focus = c.get();
  13389. for (int depth = 0; focus != nullptr && depth < 32; ++depth)
  13390. {
  13391. if (focus->getWantsKeyboardFocus() && (focus->isEnabled() || focus == c.get()))
  13392. {
  13393. focus->getProperties().set ("lynxSnapshotFocus", true);
  13394. break;
  13395. }
  13396. auto traverser = focus->createKeyboardFocusTraverser();
  13397. focus = traverser != nullptr ? traverser->getDefaultComponent (focus) : nullptr;
  13398. }
  13399. }
  13400. frame.addAndMakeVisible (*c);
  13401. c->setTopLeftPosition (0, 0);
  13402. checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
  13403. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  13404. {
  13405. juce::Graphics g (image);
  13406. g.fillAll (lynx::theme::panel);
  13407. frame.paintEntireComponent (g, false);
  13408. }
  13409. const juce::File file (prefix + name);
  13410. file.deleteFile();
  13411. juce::PNGImageFormat png;
  13412. if (auto out = file.createOutputStream())
  13413. png.writeImageToStream (image, *out);
  13414. };
  13415. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  13416. saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
  13417. saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
  13418. {
  13419. // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
  13420. // Export window for "Render selected tracks to wave file(s)"
  13421. const auto before = offline.getSong();
  13422. offline.editSong ([] (lynx::Song& s) {
  13423. if (s.mixer.size() > 3)
  13424. {
  13425. s.mixer[1].latencyMs = 5.0f;
  13426. s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  13427. s.mixer[2].latencyMs = -1.5f;
  13428. }
  13429. });
  13430. offline.dispatchPendingMessages();
  13431. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  13432. strips.setSelection ({ 1, 2, 3 }, 1);
  13433. const auto menu = strips.buildMenu (1);
  13434. juce::StringArray names { "Mixer track" };
  13435. std::vector<juce::PopupMenu> menus { menu };
  13436. const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
  13437. const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
  13438. lynx::tr ("Plugin delay compensation") };
  13439. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  13440. {
  13441. const auto& item = it.getItem();
  13442. if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
  13443. {
  13444. names.add (item.text.upToFirstOccurrenceOf (":", false, false));
  13445. menus.push_back (*item.subMenu);
  13446. }
  13447. }
  13448. saveMenus (names, menus, prefix + "-menus165-mixer.png");
  13449. saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
  13450. offline.setSong (before);
  13451. offline.dispatchPendingMessages();
  13452. }
  13453. saveSplashFrames (prefix);
  13454. saveIconSheet (prefix + "-icons.png", 1.0f);
  13455. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  13456. saveWindow (lynx::MainComponent::makeHelpContent(), "-help.png");
  13457. saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
  13458. saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
  13459. // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
  13460. offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
  13461. offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
  13462. saveMenus (ui, prefix + "-menus.png");
  13463. {
  13464. // the windows' own menus (title bars) and the toolbar's recording menu
  13465. juce::StringArray names;
  13466. std::vector<juce::PopupMenu> menus;
  13467. for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
  13468. { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
  13469. { lynx::workspace::Panel::browser, "Browser" } })
  13470. {
  13471. names.add (name);
  13472. menus.push_back (ui.getPanelMenuForSnapshot (panel));
  13473. }
  13474. names.add ("Recording");
  13475. menus.push_back (ui.getRecordMenuForSnapshot());
  13476. names.add ("Toolbar");
  13477. menus.push_back (ui.getToolbarMenuForSnapshot());
  13478. saveMenus (names, menus, prefix + "-panel-menus.png");
  13479. }
  13480. // round 189e: the Playlist menu's Edit and Select submenus (FL's items and order) and the header drop question
  13481. saveMenus (juce::StringArray { "Playlist: Edit", "Playlist: Select" },
  13482. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().editMenu(), ui.getPlaylistForSnapshot().selectMenu() },
  13483. prefix + "-playlist-edit189e.png");
  13484. saveWindow (lynx::PlaylistComponent::makeHeaderDropDialog(), "-header-drop189e.png");
  13485. {
  13486. // round 189i: FL's fade handle menu (right-click on an audio clip's fade handle), on the song's first audio
  13487. // clip, or on one added for the shot
  13488. const auto before = offline.getSong();
  13489. auto clipIndex = -1;
  13490. for (std::size_t i = 0; i < before.playlist.size() && clipIndex < 0; ++i)
  13491. if (before.playlist[i].kind == lynx::ClipKind::audio)
  13492. clipIndex = (int) i;
  13493. if (clipIndex < 0)
  13494. {
  13495. auto song = before;
  13496. lynx::ChannelDef channel;
  13497. channel.instrument = lynx::InstrumentKind::audioClip;
  13498. channel.name = "Audio clip";
  13499. song.channels.push_back (channel);
  13500. lynx::Clip clip;
  13501. clip.kind = lynx::ClipKind::audio;
  13502. clip.channel = (int) song.channels.size() - 1;
  13503. clip.length = lynx::ppq * 4;
  13504. song.playlist.push_back (clip);
  13505. clipIndex = (int) song.playlist.size() - 1;
  13506. offline.setSong (song);
  13507. offline.dispatchPendingMessages();
  13508. }
  13509. saveMenus (juce::StringArray { "Fade handle" },
  13510. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().fadeHandleMenu (clipIndex, 1) },
  13511. prefix + "-fade-handle189i.png");
  13512. if (offline.getSong().playlist.size() != before.playlist.size())
  13513. {
  13514. offline.setSong (before);
  13515. offline.dispatchPendingMessages();
  13516. }
  13517. }
  13518. {
  13519. // round 189n: FL's gain handle menu with two overlapping clips selected (Normalize selection individually / as a
  13520. // group) and the later clip's fade in menu (Create crossfade enabled); FL shots in /mnt/e/lynx-work/flgap189n
  13521. const auto before = offline.getSong();
  13522. auto song = before;
  13523. lynx::ChannelDef channel;
  13524. channel.instrument = lynx::InstrumentKind::audioClip;
  13525. channel.name = "Audio clip";
  13526. song.channels.push_back (channel);
  13527. int lane = 0;
  13528. for (const auto& c : song.playlist)
  13529. lane = std::max (lane, c.track + 1);
  13530. for (int k = 0; k < 2; ++k)
  13531. {
  13532. lynx::Clip clip;
  13533. clip.kind = lynx::ClipKind::audio;
  13534. clip.channel = (int) song.channels.size() - 1;
  13535. clip.track = lane;
  13536. clip.start = k * lynx::ppq * 3;
  13537. clip.length = lynx::ppq * 4;
  13538. song.playlist.push_back (clip);
  13539. }
  13540. const auto second = (int) song.playlist.size() - 1;
  13541. song.autoCrossfades = true; // FL's capture: Thief has Automatic crossfades on
  13542. offline.setSong (song);
  13543. offline.dispatchPendingMessages();
  13544. auto& playlist = ui.getPlaylistForSnapshot();
  13545. playlist.selectForSnapshot ({ second - 1, second });
  13546. auto gain = playlist.gainMenu (second);
  13547. auto fadeIn = playlist.fadeHandleMenu (second, 0); // (both selected, as in FL's capture)
  13548. playlist.selectForSnapshot ({});
  13549. saveMenus (juce::StringArray { "Gain handle, 2 selected", "Fade in, overlapping" },
  13550. std::vector<juce::PopupMenu> { gain, fadeIn }, prefix + "-fade-gain189n.png");
  13551. // round 189o: the audio clip menu with both overlapping clips selected (FL's Fades › Crossfade selected
  13552. // shown) and with none selected (hidden)
  13553. playlist.selectForSnapshot ({ second - 1, second });
  13554. auto clipSelected = playlist.getClipMenuForSnapshot (second);
  13555. playlist.selectForSnapshot ({});
  13556. auto clipAlone = playlist.getClipMenuForSnapshot (second);
  13557. saveMenus (juce::StringArray { "Audio clip, 2 selected", "Audio clip, none selected" },
  13558. std::vector<juce::PopupMenu> { clipSelected, clipAlone }, prefix + "-xfadesel189o.png");
  13559. offline.setSong (before);
  13560. offline.dispatchPendingMessages();
  13561. }
  13562. {
  13563. // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
  13564. std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
  13565. ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
  13566. ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
  13567. saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
  13568. // round 190as: the Piano roll's scripts (FL's Tools › Scripts column) and a script's form
  13569. saveMenus (juce::StringArray { "Piano roll scripts" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getScriptsMenuForSnapshot() },
  13570. prefix + "-prscripts-menu.png");
  13571. {
  13572. lynx::prscript::Score score;
  13573. const auto out = lynx::prscript::run (lynx::prscript::builtins().front().source, score, {});
  13574. if (out.status == lynx::prscript::Outcome::Status::needsForm)
  13575. {
  13576. lynx::ScriptPanel::Options options;
  13577. options.acceptText = lynx::tr ("Accept");
  13578. saveWindow (std::make_unique<lynx::ScriptPanel> (out.form, [] (const lynx::scriptform::Form&) {}, [] (const lynx::scriptform::Form&) {},
  13579. nullptr, options),
  13580. "-prscript-form.png");
  13581. }
  13582. }
  13583. // round 190j (discussion #10): the Piano roll menu's Chord stamp list
  13584. saveMenus (juce::StringArray { "Chord stamp" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getStampMenuForSnapshot() },
  13585. prefix + "-stamp-menu.png");
  13586. // round 167l: the channel menu ("Lock active/mute state")
  13587. if (! offline.getSong().channels.empty())
  13588. saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
  13589. // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
  13590. {
  13591. juce::PopupMenu folder;
  13592. folder.addSectionHeader ("Documents");
  13593. folder.addItem (1, "Expand all");
  13594. folder.addItem (2, "Collapse all");
  13595. folder.addSeparator();
  13596. folder.addItem (3, "Refresh");
  13597. folder.addSectionHeader ("System");
  13598. folder.addItem (4, "Open");
  13599. folder.addItem (5, "Copy the file path");
  13600. folder.addSectionHeader ("Tags");
  13601. folder.addItem (6, "Starred", true, true);
  13602. folder.addSeparator();
  13603. folder.addItem (7, "Add folder...");
  13604. const auto wasCompact = lynx::theme::menus::compact();
  13605. lynx::theme::menus::setCompact (true);
  13606. saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
  13607. lynx::theme::menus::setCompact (false);
  13608. saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
  13609. lynx::theme::menus::setCompact (wasCompact);
  13610. }
  13611. // and the clip menus of the first pattern, audio and automation clips of the project
  13612. juce::StringArray clipNames;
  13613. std::vector<juce::PopupMenu> clipMenus;
  13614. for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
  13615. { lynx::ClipKind::automation, "Automation clip" } })
  13616. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  13617. if (offline.getSong().playlist[(std::size_t) c].kind == kind)
  13618. {
  13619. clipNames.add (name);
  13620. clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
  13621. break;
  13622. }
  13623. if (! clipMenus.empty())
  13624. saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
  13625. }
  13626. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  13627. alert->setOpaque (true);
  13628. saveWindow (std::move (alert), name);
  13629. };
  13630. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  13631. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  13632. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  13633. saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
  13634. // round 190ah: Online Sessions — a guest's "go back in?" at start-up, the host's question at a guest's file limit
  13635. saveAlert (lynx::liveui::makeRejoinDialog ("Ana", juce::Time (2026, 10, 10, 21, 40).toString (true, true, false, true)), "-live-rejoin.png");
  13636. saveAlert (lynx::liveui::makeMediaLimitDialog ("Pedro", (juce::int64) 1010 << 20, (juce::int64) 1 << 30), "-live-media-limit.png");
  13637. saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
  13638. saveAlert (lynx::makeGradientColourDialog (juce::Colour (0xffe5383b), juce::Colour (0xff3a7bd5), 8), "-gradient.png"); // round 177a
  13639. saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
  13640. // round 186c: FL's mixer "Delete" questions and its Settings › General › Manage messages menu
  13641. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Delete tracks"), lynx::tr ("This will |delete| {0} selected mixer track(s). Are you sure?", { "1" }),
  13642. { lynx::tr ("Yes"), lynx::tr ("No") }, true }),
  13643. "-delete-tracks.png");
  13644. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Playlist tracks"),
  13645. lynx::tr ("One or more mixer tracks that will be deleted are connected to instrument/audio tracks.") + "\n"
  13646. + lynx::tr ("Do you want to unlink the tracks and channels or delete them?"),
  13647. { lynx::tr ("Delete tracks and channels"), lynx::tr ("Unlink tracks and channels"), lynx::tr ("Cancel") }, false }),
  13648. "-delete-tracks-linked.png");
  13649. saveMenus (juce::StringArray { "Manage messages" }, std::vector<juce::PopupMenu> { lynx::messages::manageMenu() }, prefix + "-manage-messages.png");
  13650. saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
  13651. saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
  13652. saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
  13653. // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
  13654. {
  13655. struct Bars final : juce::Component
  13656. {
  13657. Bars()
  13658. {
  13659. constexpr int h = lynx::updater::UpdateBar::height;
  13660. setSize (1100, 4 * (h + 6));
  13661. for (int state = 0; state < 4; ++state)
  13662. {
  13663. bars[state].setBounds (0, state * (h + 6), getWidth(), h);
  13664. bars[state].showForSnapshot (state);
  13665. addAndMakeVisible (bars[state]);
  13666. }
  13667. }
  13668. lynx::updater::UpdateBar bars[4];
  13669. };
  13670. saveWindow (std::make_unique<Bars>(), "-update-bar.png");
  13671. saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
  13672. }
  13673. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
  13674. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
  13675. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
  13676. {
  13677. // the Settings pages, with credits like a project imported from FL would carry
  13678. offline.editSong ([] (lynx::Song& s) {
  13679. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  13680. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  13681. }, false);
  13682. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
  13683. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
  13684. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
  13685. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
  13686. {
  13687. // round 189o: the whole General page (the Editing and Plugins sections hold FL's "Monophonic painting in
  13688. // piano roll" and "Limit the number of open plugin editors")
  13689. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  13690. tall->setSize (tall->getWidth(), 3200);
  13691. saveWindow (std::move (tall), "-settings-general-tall189o.png");
  13692. }
  13693. {
  13694. // the whole General page (round 186a: the Startup section is below the first screen)
  13695. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  13696. tall->setSize (tall->getWidth(), 1500);
  13697. saveWindow (std::move (tall), "-settings-general-tall.png");
  13698. }
  13699. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
  13700. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::extras), "-settings-extras.png"); // round 190am
  13701. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
  13702. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
  13703. saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
  13704. saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
  13705. }
  13706. {
  13707. // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
  13708. saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
  13709. const auto& clips = offline.getSong().playlist;
  13710. for (int i = 0; i < (int) clips.size(); ++i)
  13711. if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
  13712. {
  13713. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
  13714. break;
  13715. }
  13716. for (int i = 0; i < (int) clips.size(); ++i)
  13717. if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
  13718. {
  13719. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
  13720. break;
  13721. }
  13722. if (offline.getSong().arrangements.size() < 2)
  13723. offline.editSong ([] (lynx::Song& s) {
  13724. const auto current = s.currentArrangement;
  13725. s.addArrangement ("Radio edit", true);
  13726. s.addArrangement ("Intro loop");
  13727. s.selectArrangement (current);
  13728. }, false);
  13729. saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
  13730. saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
  13731. saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
  13732. }
  13733. {
  13734. // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
  13735. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
  13736. {
  13737. juce::AudioBuffer<float> line (1, 44100 * 2);
  13738. const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
  13739. double ph = 0.0;
  13740. for (int i = 0; i < line.getNumSamples(); ++i)
  13741. {
  13742. const auto f0 = hz[std::min (4, i / 17640)];
  13743. 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;
  13744. float v = 0.0f;
  13745. for (int h = 1; f0 > 0.0 && h < 8; ++h)
  13746. v += (float) (0.3 / h * std::sin (h * ph));
  13747. line.setSample (0, i, v);
  13748. }
  13749. wav.deleteFile();
  13750. juce::WavAudioFormat format;
  13751. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  13752. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
  13753. {
  13754. out.release();
  13755. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  13756. writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
  13757. }
  13758. }
  13759. if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
  13760. {
  13761. auto notes = lynx::newtonefx::analyseNotes (*sample);
  13762. if (notes.pitches.size() > 1)
  13763. notes.pitches[1].shift = 2.0;
  13764. lynx::newtonefx::WarpMap warp;
  13765. warp.frames = (std::int64_t) sample->frames();
  13766. warp.markers = { { 22050, 33075 } };
  13767. int at = 0;
  13768. offline.editSong ([&] (lynx::Song& song) {
  13769. if (song.mixer.size() < 2)
  13770. song.mixer.resize (2);
  13771. auto& fx = song.mixer[1].effects;
  13772. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  13773. tone.samplePath = wav.getFullPathName().toStdString();
  13774. tone.state = lynx::newtonefx::writeNative (notes);
  13775. auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
  13776. time.samplePath = tone.samplePath;
  13777. time.state = lynx::newtonefx::writeWarp (warp);
  13778. at = (int) fx.size();
  13779. fx.push_back (tone);
  13780. fx.push_back (time);
  13781. }, false);
  13782. saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
  13783. saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
  13784. offline.editSong ([at] (lynx::Song& song) {
  13785. auto& fx = song.mixer[1].effects;
  13786. fx.erase (fx.begin() + at, fx.begin() + at + 2);
  13787. }, false);
  13788. }
  13789. }
  13790. if (! offline.getSong().automations.empty())
  13791. {
  13792. auto editor = lynx::makeAutomationEditor (offline, 0);
  13793. editor->setSize (760, 300);
  13794. saveWindow (std::move (editor), "-automation.png");
  13795. // round 177b: the same clip in FL's LFO mode: FL's defaults, then one shaped state (the UI gate pairs)
  13796. const auto before = offline.getSong().automations[0].lfo;
  13797. const auto lfoShot = [&offline, &saveWindow] (std::function<void (lynx::AutomationLfo&)> set, const char* suffix) {
  13798. offline.editSong ([&set] (lynx::Song& song) {
  13799. auto& lfo = song.automations[0].lfo;
  13800. lfo = lynx::AutomationLfo {};
  13801. lfo.on = true;
  13802. set (lfo);
  13803. }, false);
  13804. auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
  13805. lfoEditor->setSize (760, 346);
  13806. saveWindow (std::move (lfoEditor), suffix);
  13807. };
  13808. lfoShot ([] (lynx::AutomationLfo&) {}, "-automation-lfo.png");
  13809. lfoShot ([] (lynx::AutomationLfo& lfo) {
  13810. // the state set through FL's own UI for the UI gate (TNS 50 %, SKEW 25 %, PW 25 %, two points), as FL saved it
  13811. lfo.tension = 64;
  13812. lfo.skew = 32;
  13813. lfo.pulseWidth = 28;
  13814. lfo.amp = { { 0, 0.6716f, 0.0f }, { (std::int64_t) (lynx::ppq * 1.4128), 0.9204f, 0.0f } };
  13815. }, "-automation-lfo-shape.png");
  13816. offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
  13817. }
  13818. // round 177b: LYNX's modulators window, with one routed modulator
  13819. {
  13820. offline.editSong ([] (lynx::Song& song) {
  13821. lynx::Modulator m;
  13822. m.name = "LFO 1";
  13823. m.shape = lynx::ModShape::triangle;
  13824. m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  13825. song.modulators.push_back (m);
  13826. lynx::Modulator r;
  13827. r.name = "LFO 2";
  13828. r.shape = lynx::ModShape::smoothRandom;
  13829. r.sync = false;
  13830. r.hz = 0.5;
  13831. song.modulators.push_back (r);
  13832. }, false);
  13833. auto mods = lynx::makeModulatorsPanel (offline);
  13834. mods->setSize (720, 360);
  13835. saveWindow (std::move (mods), "-modulators.png");
  13836. offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
  13837. }
  13838. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  13839. // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
  13840. saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
  13841. saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
  13842. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  13843. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  13844. {
  13845. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  13846. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  13847. break;
  13848. }
  13849. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  13850. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  13851. {
  13852. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  13853. break;
  13854. }
  13855. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  13856. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  13857. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  13858. {
  13859. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  13860. break;
  13861. }
  13862. // round 180c: Fruity Slicer's editor
  13863. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  13864. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fruityslicer)
  13865. {
  13866. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fruityslicer.png");
  13867. // rounds 190f / 190m: its Envelope / instrument page, one picture per target
  13868. saveWindow (lynx::makeChannelFrame (offline, c, 1), "-fruityslicer-envelope.png");
  13869. for (const auto& [target, name] : std::vector<std::pair<int, const char*>> { { 0, "panning" }, { 2, "modx" }, { 3, "mody" }, { 4, "pitch" } })
  13870. {
  13871. auto frame = lynx::makeChannelFrame (offline, c, 1);
  13872. lynx::showFlVoiceTarget (*frame, target);
  13873. saveWindow (std::move (frame), juce::String ("-fruityslicer-envelope-") + name + ".png");
  13874. }
  13875. break;
  13876. }
  13877. // round 190r: Slicex's editor
  13878. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  13879. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  13880. {
  13881. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-slicex.png");
  13882. break;
  13883. }
  13884. // round 190q: FPC's editor
  13885. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  13886. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fpc)
  13887. {
  13888. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fpc.png");
  13889. break;
  13890. }
  13891. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  13892. {
  13893. int bestTrack = -1, bestSlot = -1;
  13894. double bestShape = -1.0;
  13895. const auto& mixer = offline.getSong().mixer;
  13896. for (int t = 0; t < (int) mixer.size(); ++t)
  13897. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  13898. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  13899. {
  13900. double shape = 0.0;
  13901. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  13902. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  13903. if (shape > bestShape)
  13904. {
  13905. bestShape = shape;
  13906. bestTrack = t;
  13907. bestSlot = s;
  13908. }
  13909. }
  13910. if (bestTrack >= 0)
  13911. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  13912. }
  13913. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  13914. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  13915. saveWindow (std::move (inspector), "-noteinspector.png");
  13916. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  13917. saveWindow (std::move (inspector), "-noteinspector-one.png");
  13918. // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
  13919. {
  13920. auto& roll = ui.getPianoRollForSnapshot();
  13921. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
  13922. { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
  13923. { lynx::NoteTool::flip, "-tool-flip.png" },
  13924. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  13925. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  13926. { lynx::NoteTool::limit, "-tool-limit.png" },
  13927. { lynx::NoteTool::quantize, "-tool-quantize.png" },
  13928. { lynx::NoteTool::chop, "-tool-chop.png" },
  13929. { lynx::NoteTool::flam, "-tool-flam.png" },
  13930. { lynx::NoteTool::lfo, "-tool-lfo.png" },
  13931. { lynx::NoteTool::claw, "-tool-claw.png" },
  13932. { lynx::NoteTool::articulate, "-tool-articulate.png" },
  13933. { lynx::NoteTool::riffMachine, "-tool-riff.png" },
  13934. { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
  13935. for (const auto& [tool, name] : tools)
  13936. saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
  13937. }
  13938. // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
  13939. {
  13940. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
  13941. const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
  13942. offline.editSong ([&] (lynx::Song& s) {
  13943. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
  13944. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
  13945. lynx::prtools::LfoOptions lfo;
  13946. lfo.startSpeed = 7 * 4096; // one beat
  13947. lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
  13948. }, false);
  13949. saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
  13950. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  13951. // issue #86: the same editor on the Tempo target, with the project's own Tempo events (a sample ramp if none)
  13952. const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
  13953. offline.editSong ([&] (lynx::Song& s) {
  13954. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], tempo);
  13955. if (lane.events.empty())
  13956. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.05f, 0.11f, lynx::ticksPerStep);
  13957. }, false);
  13958. saveWindow (lynx::makeEventEditor (offline, tempo), "-eventeditor-tempo.png");
  13959. {
  13960. auto compact = lynx::makeEventEditor (offline, tempo); // the toolbar in a small window
  13961. compact->setSize (640, 300);
  13962. saveWindow (std::move (compact), "-eventeditor-tempo-small.png");
  13963. auto narrowest = lynx::makeEventEditor (offline, tempo); // the tool window's lower limit
  13964. narrowest->setSize (400, 300);
  13965. saveWindow (std::move (narrowest), "-eventeditor-tempo-narrowest.png");
  13966. }
  13967. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  13968. }
  13969. // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
  13970. // and its menu items (-audioeditor-menu.txt)
  13971. {
  13972. namespace ae = lynx::audioedit;
  13973. ae::Document d;
  13974. d.title = "Drum loop";
  13975. d.audio.sampleRate = 44100.0;
  13976. const auto frames = (std::size_t) (44100 * 2);
  13977. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  13978. std::uint32_t seed = 7;
  13979. for (int hit = 0; hit < 8; ++hit)
  13980. {
  13981. const auto at = (std::size_t) hit * frames / 8;
  13982. const auto kick = hit % 2 == 0;
  13983. double phase = 0.0;
  13984. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  13985. {
  13986. seed = seed * 1664525u + 1013904223u;
  13987. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  13988. const auto t = (double) i / 44100.0;
  13989. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  13990. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  13991. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  13992. d.audio.channels[0][at + i] += v;
  13993. d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
  13994. }
  13995. }
  13996. ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
  13997. ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
  13998. ae::setLoop (d, { 0, (std::int64_t) frames });
  13999. auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
  14000. juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
  14001. saveWindow (std::move (wave), "-audioeditor.png");
  14002. saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
  14003. }
  14004. // warp markers (round 175a, M3): the audio editor of the first audio clip whose channel has warp markers,
  14005. // opened as the Playlist opens it, with its warp lane
  14006. {
  14007. const auto& song = offline.getSong();
  14008. for (int i = 0; i < (int) song.playlist.size(); ++i)
  14009. {
  14010. const auto& c = song.playlist[(std::size_t) i];
  14011. if (c.kind == lynx::ClipKind::audio && juce::isPositiveAndBelow (c.channel, (int) song.channels.size())
  14012. && song.channels[(std::size_t) c.channel].sampler.warp.size() >= 3)
  14013. {
  14014. if (auto panel = lynx::makeAudioEditorPanel (offline, c.channel, i, true))
  14015. saveWindow (std::move (panel), "-audioeditor-warp.png");
  14016. break;
  14017. }
  14018. }
  14019. }
  14020. // the tempo tapper after five steady taps (round 132)
  14021. saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
  14022. // the Channel Rack's piano-roll view (round 132)
  14023. ui.selectTabForSnapshot (0);
  14024. ui.getRackForSnapshot().setPianoRollView (true);
  14025. offline.dispatchPendingMessages();
  14026. saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
  14027. ui.getRackForSnapshot().setPianoRollView (false);
  14028. // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
  14029. ui.selectTabForSnapshot (0);
  14030. ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
  14031. offline.dispatchPendingMessages();
  14032. saveSnapshot (ui, prefix + "-rack-graph.png");
  14033. ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
  14034. saveSnapshot (ui, prefix + "-rack-graph-pan.png");
  14035. ui.getRackForSnapshot().toggleGraphLanes();
  14036. saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
  14037. // the Mixer with three inserts selected and one armed for recording
  14038. ui.selectTabForSnapshot (3);
  14039. if (offline.getSong().mixer.size() > 4)
  14040. {
  14041. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
  14042. offline.setInsertArmed (3, true);
  14043. offline.dispatchPendingMessages();
  14044. saveSnapshot (ui, prefix + "-mixer-multi.png");
  14045. // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
  14046. offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
  14047. ui.getMixerForSnapshot().selectTrack (3);
  14048. offline.dispatchPendingMessages();
  14049. saveSnapshot (ui, prefix + "-mixer-input.png");
  14050. offline.undo();
  14051. offline.setInsertArmed (3, false);
  14052. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
  14053. }
  14054. // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
  14055. if (offline.getSong().mixer.size() > 6)
  14056. {
  14057. int source = -1;
  14058. for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
  14059. if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
  14060. source = t;
  14061. const auto temporary = source < 0;
  14062. if (temporary) // the demo has no sends: add two for the picture
  14063. {
  14064. source = 1;
  14065. 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); });
  14066. }
  14067. ui.getMixerForSnapshot().selectTrack (source);
  14068. offline.dispatchPendingMessages();
  14069. saveSnapshot (ui, prefix + "-mixer-sends.png");
  14070. if (temporary)
  14071. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
  14072. ui.getMixerForSnapshot().selectTrack (0);
  14073. }
  14074. // the Playlist with ripple editing on
  14075. ui.selectTabForSnapshot (2);
  14076. ui.getPlaylistForSnapshot().setRipple (true);
  14077. saveSnapshot (ui, prefix + "-playlist-ripple.png");
  14078. ui.getPlaylistForSnapshot().setRipple (false);
  14079. // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
  14080. {
  14081. const auto saved = offline.getSong();
  14082. offline.editSong ([] (lynx::Song& s) {
  14083. s.patternBlocksOn = true;
  14084. while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
  14085. lynx::clonePattern (s, (int) s.patterns.size() - 1);
  14086. const auto rows = juce::jmin (6, (int) s.patterns.size());
  14087. for (int r = 0; r < rows; ++r)
  14088. lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
  14089. (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
  14090. }, false);
  14091. offline.dispatchPendingMessages();
  14092. saveSnapshot (ui, prefix + "-playlist-blocks.png");
  14093. // issue #127 (PR #132 and our follow-up): the Playlist's pencil, brush and eraser on the blocks, driven
  14094. // with real mouse events on the view. One picture per tool, and the gestures' results in
  14095. // <prefix>-playlist-blocks-tools.txt ("OK", or the checks that failed).
  14096. if (auto* blocks = ui.getPlaylistForSnapshot().getBlocksViewForSnapshot())
  14097. {
  14098. juce::StringArray failed;
  14099. const auto expect = [&failed] (bool ok, const char* what) { if (! ok) failed.add (what); };
  14100. const auto bar = (std::int64_t) lynx::ppq * offline.getSong().beatsPerBar;
  14101. offline.editSong ([bar] (lynx::Song& s) {
  14102. s.blocks.clear();
  14103. for (std::size_t r = 0; r < 4 && r < s.patterns.size(); ++r)
  14104. s.patterns[r].lengthTicks = r == 1 ? 2 * bar : bar; // row 2 holds a 2-bar pattern
  14105. }, false);
  14106. offline.dispatchPendingMessages();
  14107. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  14108. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  14109. juce::Point<float> pressedAt;
  14110. const auto event = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  14111. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  14112. const auto now = juce::Time::getCurrentTime();
  14113. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, 1, false);
  14114. };
  14115. const auto press = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  14116. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  14117. blocks->mouseDown (event (row, tick, mods));
  14118. };
  14119. const auto dragTo = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (event (row, tick, mods)); };
  14120. const auto release = [&] (int row, std::int64_t tick) { blocks->mouseUp (event (row, tick, {})); };
  14121. // the starts of row `row`'s blocks, as "0,2,5" (bars from 0)
  14122. const auto rowBars = [&] (int row) {
  14123. juce::StringArray bars;
  14124. for (const auto& b : offline.getSong().blocks)
  14125. if (b.pattern == row)
  14126. bars.add (juce::String (b.start / bar) + (b.start % bar != 0 ? "+" : ""));
  14127. return bars.joinIntoString (",");
  14128. };
  14129. auto& tools = ui.getPlaylistForSnapshot();
  14130. // Pencil: a press on empty space places one block that follows the mouse along its row
  14131. tools.setToolForSnapshot (lynx::EditTool::pencil);
  14132. press (0, 2 * bar + 40, left);
  14133. expect (rowBars (0) == "2", "pencil: a press places one block");
  14134. dragTo (2, 5 * bar + 40, left); // (over another row: the block stays in its own)
  14135. release (2, 5 * bar + 40);
  14136. expect (rowBars (0) == "5" && rowBars (2).isEmpty(), "pencil: the placed block follows the drag in its row");
  14137. // a 2-bar block grabbed by its second bar keeps that bar under the mouse (it used to jump a bar)
  14138. press (1, 1 * bar + 40, left);
  14139. release (1, 1 * bar + 40);
  14140. expect (rowBars (1) == "1", "pencil: a click places the 2-bar block");
  14141. press (1, 2 * bar + 40, left);
  14142. dragTo (1, 2 * bar + bar / 2, left);
  14143. expect (rowBars (1) == "1", "move: a small move on the grabbed bar leaves the block in place");
  14144. dragTo (1, 4 * bar + 40, left);
  14145. release (1, 4 * bar + 40);
  14146. expect (rowBars (1) == "3", "move: the grabbed bar stays under the mouse");
  14147. offline.dispatchPendingMessages();
  14148. saveSnapshot (ui, prefix + "-playlist-blocks-pencil.png");
  14149. // Brush: a drag over empty space paints a run; a press on a block moves it
  14150. tools.setToolForSnapshot (lynx::EditTool::brush);
  14151. press (2, 0, left);
  14152. dragTo (2, 3 * bar + 40, left);
  14153. release (2, 3 * bar + 40);
  14154. expect (rowBars (2) == "0,1,2,3", "brush: a drag paints a run");
  14155. press (2, 3 * bar + 40, left);
  14156. dragTo (2, 6 * bar + 40, left);
  14157. release (2, 6 * bar + 40);
  14158. expect (rowBars (2) == "0,1,2,6", "brush: a press on a block moves it");
  14159. offline.dispatchPendingMessages();
  14160. saveSnapshot (ui, prefix + "-playlist-blocks-brush.png");
  14161. // Eraser, and the right button with any tool: only the blocks under the mouse, row by row
  14162. offline.editSong ([bar] (lynx::Song& s) {
  14163. for (int r = 0; r < 4 && r < (int) s.patterns.size(); ++r)
  14164. lynx::patternblocks::place (s, r, 8 * bar);
  14165. }, false);
  14166. offline.dispatchPendingMessages();
  14167. expect (rowBars (0) == "5,8" && rowBars (3) == "8", "eraser: the column is set up");
  14168. saveSnapshot (ui, prefix + "-playlist-blocks-eraser-before.png");
  14169. tools.setToolForSnapshot (lynx::EditTool::eraser);
  14170. press (0, 8 * bar + 40, left);
  14171. expect (rowBars (0) == "5" && rowBars (1) == "3,8" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8",
  14172. "eraser: a click takes only the block under the mouse");
  14173. dragTo (1, 8 * bar + 60, left); // down one row: that row's block goes too, the rows below stay
  14174. release (1, 8 * bar + 60);
  14175. expect (rowBars (1) == "3" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8", "eraser: the drag erases the rows it crosses, no others");
  14176. tools.setToolForSnapshot (lynx::EditTool::pencil);
  14177. press (3, 8 * bar + 40, right);
  14178. release (3, 8 * bar + 40);
  14179. expect (rowBars (3).isEmpty() && rowBars (2) == "0,1,2,6,8", "right click: erases only the block under the mouse");
  14180. offline.dispatchPendingMessages();
  14181. saveSnapshot (ui, prefix + "-playlist-blocks-eraser.png");
  14182. juce::File (prefix + "-playlist-blocks-tools.txt").replaceWithText (failed.isEmpty() ? juce::String ("OK\n") : "ERROR\n" + failed.joinIntoString ("\n") + "\n");
  14183. }
  14184. offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
  14185. offline.dispatchPendingMessages();
  14186. }
  14187. // quick-add palette, and the Browser searching
  14188. saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
  14189. ui.showDesktopForSnapshot (false);
  14190. ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
  14191. offline.dispatchPendingMessages();
  14192. saveSnapshot (ui, prefix + "-browser-search.png");
  14193. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  14194. ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
  14195. offline.dispatchPendingMessages();
  14196. saveSnapshot (ui, prefix + "-browser-tree.png");
  14197. // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
  14198. ui.getBrowserForSnapshot().showProjectForSnapshot();
  14199. offline.dispatchPendingMessages();
  14200. saveSnapshot (ui, prefix + "-browser-project.png");
  14201. ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
  14202. offline.dispatchPendingMessages();
  14203. saveSnapshot (ui, prefix + "-browser-plugins.png");
  14204. ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
  14205. saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
  14206. {
  14207. // round 164: the content filter leaves out the folders with nothing to list (a small library)
  14208. const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
  14209. lib.deleteRecursively();
  14210. for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
  14211. "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
  14212. lib.getChildFile (path).create();
  14213. ui.showDesktopForSnapshot (false);
  14214. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  14215. offline.dispatchPendingMessages();
  14216. saveSnapshot (ui, prefix + "-browser164-all.png");
  14217. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
  14218. offline.dispatchPendingMessages();
  14219. saveSnapshot (ui, prefix + "-browser164-samples.png");
  14220. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
  14221. offline.dispatchPendingMessages();
  14222. saveSnapshot (ui, prefix + "-browser164-projects.png");
  14223. lib.deleteRecursively();
  14224. ui.getBrowserForSnapshot().resetViewForSnapshot();
  14225. }
  14226. {
  14227. // round 190as: "Find similar samples" on a small library of kicks, hats and pads (LYNX_SNAPSHOT_SIMILAR =
  14228. // "<folder>|<file>" lists a real folder instead)
  14229. auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-similar");
  14230. auto query = lib.getChildFile ("Drums/Kicks/Kick 2.wav");
  14231. const auto real = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIMILAR", {});
  14232. const auto made = real.isEmpty();
  14233. if (made)
  14234. {
  14235. lib.deleteRecursively();
  14236. juce::Random random (190);
  14237. const auto write = [&] (const juce::String& path, char kind, int v) {
  14238. const auto rate = 44100.0;
  14239. const auto frames = (int) (rate * (kind == 'k' ? 0.35 : kind == 'h' ? 0.09 : 2.5));
  14240. juce::AudioBuffer<float> audio (1, frames);
  14241. double phase = 0.0;
  14242. float last = 0.0f;
  14243. for (int i = 0; i < frames; ++i)
  14244. {
  14245. const auto t = i / rate;
  14246. float x = 0.0f;
  14247. if (kind == 'k')
  14248. {
  14249. phase += juce::MathConstants<double>::twoPi * ((46.0 + 3.0 * v) + 150.0 * std::exp (-t * 35.0)) / rate;
  14250. x = (float) (std::sin (phase) * std::exp (-t * (8.0 + v)));
  14251. }
  14252. else if (kind == 'h')
  14253. {
  14254. const auto n = random.nextFloat() * 2.0f - 1.0f;
  14255. x = (n - last) * 0.5f * (float) std::exp (-t * (50.0 + 12.0 * v));
  14256. last = n;
  14257. }
  14258. else
  14259. {
  14260. const auto base = 220.0 * std::pow (2.0, v / 12.0);
  14261. x = (float) (0.25 * std::min (1.0, t / 0.4) * std::min (1.0, (2.5 - t) / 0.5)
  14262. * (std::sin (juce::MathConstants<double>::twoPi * base * t) + std::sin (juce::MathConstants<double>::twoPi * base * 1.5 * t)));
  14263. }
  14264. audio.setSample (0, i, 0.8f * x);
  14265. }
  14266. const auto file = lib.getChildFile (path);
  14267. file.getParentDirectory().createDirectory();
  14268. juce::WavAudioFormat wav;
  14269. if (auto out = file.createOutputStream())
  14270. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (out.release(), rate, 1, 16, {}, 0)))
  14271. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  14272. };
  14273. for (int v = 1; v <= 5; ++v)
  14274. {
  14275. write ("Drums/Kicks/Kick " + juce::String (v) + ".wav", 'k', v);
  14276. write ("Drums/Hats/Hat " + juce::String (v) + ".wav", 'h', v);
  14277. write ("Keys/Pad " + juce::String (v) + ".wav", 'p', v);
  14278. }
  14279. }
  14280. else
  14281. {
  14282. lib = juce::File (real.upToFirstOccurrenceOf ("|", false, false));
  14283. query = juce::File (real.fromFirstOccurrenceOf ("|", false, false));
  14284. }
  14285. ui.showDesktopForSnapshot (false);
  14286. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  14287. ui.getBrowserForSnapshot().findSimilarForSnapshot (query, lib);
  14288. offline.dispatchPendingMessages();
  14289. saveSnapshot (ui, prefix + "-browser-similar.png");
  14290. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  14291. if (made)
  14292. lib.deleteRecursively();
  14293. ui.getBrowserForSnapshot().resetViewForSnapshot();
  14294. }
  14295. // the undo history after a few edits
  14296. offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
  14297. offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
  14298. offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
  14299. offline.undo();
  14300. saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
  14301. // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
  14302. // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
  14303. {
  14304. const juce::File wav (prefix + "-wavedemo.wav");
  14305. writeWaveDemo (wav, offline.getSong().bpm);
  14306. const auto path = wav.getFullPathName();
  14307. const auto pathUtf8 = path.toStdString();
  14308. int samplerChannel = -1, firstTrack = 0;
  14309. offline.editSong ([&] (lynx::Song& s) {
  14310. for (const auto& clip : s.playlist)
  14311. firstTrack = std::max (firstTrack, clip.track + 1);
  14312. lynx::ChannelDef audio;
  14313. audio.name = "Beat (audio)";
  14314. audio.instrument = lynx::InstrumentKind::audioClip;
  14315. audio.samplePath = pathUtf8;
  14316. s.channels.push_back (audio);
  14317. const auto audioChannel = (int) s.channels.size() - 1;
  14318. lynx::ChannelDef sampler = audio;
  14319. sampler.name = "Beat (sampler)";
  14320. sampler.instrument = lynx::InstrumentKind::sampler;
  14321. sampler.sampler.regionStart = 0.06f;
  14322. sampler.sampler.regionEnd = 0.94f;
  14323. s.channels.push_back (sampler);
  14324. samplerChannel = (int) s.channels.size() - 1;
  14325. const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
  14326. const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
  14327. lynx::Clip clip;
  14328. clip.kind = lynx::ClipKind::audio;
  14329. clip.channel = audioChannel;
  14330. clip.track = firstTrack;
  14331. clip.length = whole;
  14332. s.playlist.push_back (clip);
  14333. clip.track = firstTrack + 1; // a slice of it, later in the song
  14334. clip.start = bar;
  14335. clip.offset = bar;
  14336. clip.length = 2 * bar;
  14337. s.playlist.push_back (clip);
  14338. // taller rows for the audio (tracks can be resized: P18)
  14339. if ((int) s.playlistTracks.size() < firstTrack + 2)
  14340. s.playlistTracks.resize ((std::size_t) firstTrack + 2);
  14341. s.playlistTracks[(std::size_t) firstTrack].height = 80;
  14342. s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
  14343. });
  14344. offline.dispatchPendingMessages();
  14345. auto& cache = *lynx::ui::WaveformCache::getInstance();
  14346. cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  14347. cache.waitUntilIdle (30000);
  14348. ui.selectTabForSnapshot (2);
  14349. auto& playlist = ui.getPlaylistForSnapshot();
  14350. playlist.setTimeSelectionForSnapshot (0, 0);
  14351. {
  14352. // the Playlist alone (the floating Channel Rack would cover the clips)
  14353. auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
  14354. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  14355. saveSnapshot (ui, prefix + "-playlist-audio.png");
  14356. playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
  14357. saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
  14358. lynx::ui::WaveformCache::stereo = true;
  14359. saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
  14360. lynx::ui::WaveformCache::stereo = false;
  14361. lynx::ui::WaveformCache::spectral = true;
  14362. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  14363. saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
  14364. lynx::ui::WaveformCache::spectral = false;
  14365. playlist.setViewForSnapshot (40.0, 0, 0);
  14366. saveSnapshot (ui, prefix + "-playlist-audio-far.png");
  14367. // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
  14368. // a fade, a reversed copy), at three zoom levels
  14369. if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
  14370. ! files.isEmpty())
  14371. {
  14372. const auto realTrack = firstTrack + 2;
  14373. std::vector<juce::String> paths;
  14374. for (const auto& f : files)
  14375. if (juce::File (f.trim()).existsAsFile())
  14376. paths.push_back (f.trim());
  14377. offline.editSong ([&] (lynx::Song& s) {
  14378. const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
  14379. const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
  14380. for (std::size_t i = 0; i < paths.size(); ++i)
  14381. {
  14382. lynx::ChannelDef audio;
  14383. audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
  14384. audio.instrument = lynx::InstrumentKind::audioClip;
  14385. audio.samplePath = paths[i].toStdString();
  14386. audio.colour = colours[i % 6];
  14387. audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
  14388. audio.sampler.keepPitch = true;
  14389. s.channels.push_back (audio);
  14390. lynx::Clip clip;
  14391. clip.kind = lynx::ClipKind::audio;
  14392. clip.channel = (int) s.channels.size() - 1;
  14393. clip.track = realTrack + (int) i;
  14394. clip.length = 4 * bar;
  14395. clip.fadeIn = i == 1 ? bar / 2 : 0;
  14396. s.playlist.push_back (clip);
  14397. clip.start = 4 * bar;
  14398. clip.fadeIn = 0;
  14399. clip.fadeOut = i == 0 ? bar : 0;
  14400. s.playlist.push_back (clip);
  14401. }
  14402. if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
  14403. s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
  14404. if (! paths.empty())
  14405. s.playlistTracks[(std::size_t) realTrack].height = 90;
  14406. });
  14407. offline.dispatchPendingMessages();
  14408. for (const auto& path2 : paths)
  14409. cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
  14410. cache.waitUntilIdle (60000);
  14411. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  14412. saveSnapshot (ui, prefix + "-playlist-real.png");
  14413. playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
  14414. saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
  14415. playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
  14416. saveSnapshot (ui, prefix + "-playlist-real-close.png");
  14417. playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
  14418. saveSnapshot (ui, prefix + "-playlist-real-far.png");
  14419. // the clip menu of the first real clip
  14420. if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
  14421. saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
  14422. if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
  14423. saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
  14424. // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
  14425. {
  14426. juce::StringArray log;
  14427. auto clipOf = [&offline] (const std::string& channelName, int nth) {
  14428. const auto& sg = offline.getSong();
  14429. for (int i = 0; i < (int) sg.playlist.size(); ++i)
  14430. {
  14431. const auto& c = sg.playlist[(std::size_t) i];
  14432. if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
  14433. return i;
  14434. }
  14435. return -1;
  14436. };
  14437. std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
  14438. for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
  14439. {
  14440. auto& item = it.getItem();
  14441. if (item.subMenu != nullptr && run (*item.subMenu, text))
  14442. return true;
  14443. if (item.text.startsWith (text) && item.isEnabled && item.action)
  14444. {
  14445. item.action();
  14446. return true;
  14447. }
  14448. }
  14449. return false;
  14450. };
  14451. auto act = [&] (const std::string& name, int nth, const juce::String& text) {
  14452. const auto clip = clipOf (name, nth);
  14453. const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
  14454. offline.dispatchPendingMessages();
  14455. return ok;
  14456. };
  14457. auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
  14458. for (const auto& c : offline.getSong().channels)
  14459. if (c.name == name)
  14460. return &c;
  14461. return nullptr;
  14462. };
  14463. auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
  14464. const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
  14465. if (names.size() >= 4)
  14466. {
  14467. const auto channelsBefore = offline.getSong().channels.size();
  14468. check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
  14469. offline.undo();
  14470. offline.dispatchPendingMessages();
  14471. check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
  14472. act (names[2], 0, lynx::tr ("Reverse"));
  14473. check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
  14474. && channelOf (names[3] + " #2") != nullptr);
  14475. check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
  14476. && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
  14477. const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
  14478. check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
  14479. && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
  14480. const auto clipsBefore = offline.getSong().playlist.size();
  14481. check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
  14482. check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
  14483. check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
  14484. && offline.getSong().playlist.size() == clipsBefore + 2);
  14485. check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
  14486. check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
  14487. }
  14488. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  14489. saveSnapshot (ui, prefix + "-playlist-real-actions.png");
  14490. juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
  14491. }
  14492. }
  14493. }
  14494. saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
  14495. ui.showDesktopForSnapshot (false);
  14496. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  14497. saveSnapshot (ui, prefix + "-browser-preview.png");
  14498. }
  14499. }
  14500. // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
  14501. // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
  14502. juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
  14503. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  14504. quit();
  14505. }
  14506. // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
  14507. // hats and the noise riser = high), to show the spectral waveform colours
  14508. static void writeWaveDemo (const juce::File& file, double bpm)
  14509. {
  14510. constexpr double rate = 44100.0;
  14511. const auto frames = (int) (8.0 * rate);
  14512. juce::AudioBuffer<float> buffer (2, frames);
  14513. buffer.clear();
  14514. auto* l = buffer.getWritePointer (0);
  14515. auto* r = buffer.getWritePointer (1);
  14516. const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
  14517. std::uint32_t noise = 0x9e3779b9u;
  14518. auto white = [&noise] {
  14519. noise ^= noise << 13;
  14520. noise ^= noise >> 17;
  14521. noise ^= noise << 5;
  14522. return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
  14523. };
  14524. float previous = 0.0f;
  14525. for (int i = 0; i < frames; ++i)
  14526. {
  14527. const auto t = i / rate;
  14528. const auto inBeat = std::fmod (t, beat);
  14529. const auto bar = (int) (t / (beat * 4.0));
  14530. float left = 0.0f, right = 0.0f;
  14531. // kick on every beat: a falling sine
  14532. {
  14533. const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
  14534. const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
  14535. left += k;
  14536. right += k;
  14537. }
  14538. // hats on the off-beats: high-passed noise bursts, a little to the right
  14539. {
  14540. const auto h = std::fmod (t + beat * 0.5, beat);
  14541. const auto n = white();
  14542. const auto hp = (n - previous) * 0.5f;
  14543. previous = n;
  14544. const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
  14545. left += hat * 0.6f;
  14546. right += hat;
  14547. }
  14548. // a chord in the second and third bars (mid band)
  14549. if (bar == 1 || bar == 2)
  14550. {
  14551. const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
  14552. float chord = 0.0f;
  14553. for (const auto hz : { 523.25, 659.25, 783.99 })
  14554. chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
  14555. left += chord * 0.09f * std::max (0.0f, env);
  14556. right += chord * 0.09f * std::max (0.0f, env);
  14557. }
  14558. // a white-noise riser over the last two seconds (high band)
  14559. if (t > 6.0)
  14560. {
  14561. const auto rise = (float) ((t - 6.0) / 2.0);
  14562. left += white() * 0.4f * rise * rise;
  14563. right += white() * 0.4f * rise * rise;
  14564. }
  14565. l[i] = left;
  14566. r[i] = right;
  14567. }
  14568. buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
  14569. file.deleteFile();
  14570. juce::WavAudioFormat wav;
  14571. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
  14572. writer->writeFromAudioSampleBuffer (buffer, 0, frames);
  14573. }
  14574. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  14575. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  14576. {
  14577. const auto names = ui.getMenuNamesForSnapshot();
  14578. std::vector<juce::PopupMenu> source;
  14579. for (int m = 0; m < names.size(); ++m)
  14580. source.push_back (ui.getMenuForSnapshot (m));
  14581. saveMenus (names, source, path);
  14582. }
  14583. // menus side by side, each under its name
  14584. static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
  14585. {
  14586. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  14587. struct Laid
  14588. {
  14589. juce::PopupMenu menu;
  14590. int width = 0, height = 0;
  14591. };
  14592. std::vector<Laid> menus;
  14593. const auto border = lf.getPopupMenuBorderSize();
  14594. for (int m = 0; m < names.size(); ++m)
  14595. {
  14596. Laid laid { source[(std::size_t) m] };
  14597. int width = 160, height = 2 * border;
  14598. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  14599. {
  14600. const auto& item = it.getItem();
  14601. int w = 0, h = 0;
  14602. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  14603. if (item.isSectionHeader) h += h / 2; // as JUCE does
  14604. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  14605. w += 90;
  14606. width = juce::jmax (width, w + 10);
  14607. height += h;
  14608. }
  14609. laid.width = width;
  14610. laid.height = height;
  14611. menus.push_back (std::move (laid));
  14612. }
  14613. int totalWidth = 16, totalHeight = 0;
  14614. for (const auto& l : menus)
  14615. {
  14616. totalWidth += l.width + 16;
  14617. totalHeight = juce::jmax (totalHeight, l.height + 32);
  14618. }
  14619. juce::Image image (juce::Image::ARGB, totalWidth, totalHeight, true);
  14620. {
  14621. juce::Graphics g (image);
  14622. g.fillAll (lynx::theme::colour::bg1);
  14623. int x = 16;
  14624. for (int m = 0; m < (int) menus.size(); ++m)
  14625. {
  14626. const auto& l = menus[(std::size_t) m];
  14627. g.setColour (lynx::theme::colour::textSecondary);
  14628. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  14629. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  14630. {
  14631. juce::Graphics::ScopedSaveState state (g);
  14632. g.reduceClipRegion (x, 24, l.width, l.height);
  14633. g.setOrigin (x, 24);
  14634. lf.drawPopupMenuBackground (g, l.width, l.height);
  14635. int y = border;
  14636. bool first = true;
  14637. for (juce::PopupMenu::MenuItemIterator it (l.menu); it.next();)
  14638. {
  14639. const auto& item = it.getItem();
  14640. int w = 0, h = 0;
  14641. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  14642. if (item.isSectionHeader) h += h / 2; // as JUCE does
  14643. const juce::Rectangle<int> r (0, y, l.width, h);
  14644. auto text = item.text, shortcut = item.shortcutKeyDescription;
  14645. if (text.containsChar ('\t'))
  14646. {
  14647. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  14648. text = text.upToFirstOccurrenceOf ("\t", false, false);
  14649. }
  14650. if (item.isSectionHeader)
  14651. lf.drawPopupMenuSectionHeader (g, r, text);
  14652. else
  14653. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  14654. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  14655. first = false;
  14656. y += h;
  14657. }
  14658. }
  14659. x += l.width + 16;
  14660. }
  14661. }
  14662. const juce::File file (path);
  14663. file.deleteFile();
  14664. juce::PNGImageFormat png;
  14665. if (auto out = file.createOutputStream())
  14666. png.writeImageToStream (image, *out);
  14667. }
  14668. static void writePng (const juce::Image& image, const juce::String& path)
  14669. {
  14670. const juce::File file (path);
  14671. file.deleteFile();
  14672. juce::PNGImageFormat png;
  14673. if (auto out = file.createOutputStream())
  14674. png.writeImageToStream (image, *out);
  14675. }
  14676. // the splash screen: one settled frame, and a strip of frames through its animation
  14677. static void saveSplashFrames (const juce::String& prefix)
  14678. {
  14679. lynx::SplashScreen splash;
  14680. splash.setStatus (lynx::tr ("Loading the workspace..."));
  14681. splash.setTimeForSnapshot (1.6);
  14682. writePng (splash.createComponentSnapshot (splash.getLocalBounds()), prefix + "-splash.png");
  14683. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  14684. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  14685. juce::Image strip (juce::Image::ARGB, 4 * (w + 8) + 8, 2 * (h + 8) + 8, true);
  14686. {
  14687. juce::Graphics g (strip);
  14688. g.fillAll (lynx::theme::colour::bg1);
  14689. for (int i = 0; i < 8; ++i)
  14690. {
  14691. splash.setTimeForSnapshot (times[i]);
  14692. const auto frame = splash.createComponentSnapshot (splash.getLocalBounds());
  14693. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  14694. }
  14695. }
  14696. writePng (strip, prefix + "-splash-frames.png");
  14697. }
  14698. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  14699. // colours: at rest, hovered and switched on
  14700. static void saveIconSheet (const juce::String& path, float scale)
  14701. {
  14702. const int sizes[] = { 16, 20, 24 };
  14703. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  14704. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  14705. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  14706. {
  14707. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  14708. g.addTransform (juce::AffineTransform::scale (scale));
  14709. g.fillAll (lynx::theme::colour::bg3);
  14710. g.setFont (lynx::theme::font (lynx::theme::type::small));
  14711. for (int i = 1; i < lynx::iconCount; ++i)
  14712. {
  14713. const auto y = 8 + (i - 1) * cell;
  14714. g.setColour (lynx::theme::colour::textDisabled);
  14715. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  14716. for (int v = 0; v < 3; ++v)
  14717. for (int s = 0; s < 3; ++s)
  14718. {
  14719. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  14720. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  14721. g.setColour (bg);
  14722. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  14723. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  14724. : lynx::theme::colour::textSecondary.brighter (0.25f);
  14725. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  14726. }
  14727. }
  14728. }
  14729. writePng (image, path);
  14730. }
  14731. // a part of a component (e.g. the main toolbar)
  14732. static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
  14733. {
  14734. const juce::File file (path);
  14735. file.deleteFile();
  14736. juce::PNGImageFormat png;
  14737. if (auto out = file.createOutputStream())
  14738. png.writeImageToStream (c.createComponentSnapshot (area), *out);
  14739. }
  14740. static void savePng (const juce::Image& image, const juce::String& path)
  14741. {
  14742. const juce::File file (path);
  14743. file.deleteFile();
  14744. juce::PNGImageFormat png;
  14745. if (auto out = file.createOutputStream())
  14746. png.writeImageToStream (image, *out);
  14747. }
  14748. // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
  14749. // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
  14750. static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
  14751. {
  14752. const auto tips = ui.getQuickTipsForSnapshot();
  14753. const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
  14754. auto image = ui.createComponentSnapshot (top);
  14755. {
  14756. juce::Graphics g (image);
  14757. const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
  14758. lynx::tr ("Window options"), lynx::tr ("Close") };
  14759. std::vector<juce::Rectangle<int>> used;
  14760. for (const auto& [area, tip] : tips)
  14761. {
  14762. const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
  14763. if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
  14764. continue;
  14765. const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
  14766. if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
  14767. continue;
  14768. used.push_back (bubble);
  14769. g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
  14770. g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
  14771. lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
  14772. }
  14773. }
  14774. savePng (image, prefix + "-toolbar-tips.png");
  14775. // the sheet: bubbles in rows
  14776. const int width = 900;
  14777. int x = 12, y = 12;
  14778. std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
  14779. for (const auto& [area, tip] : tips)
  14780. {
  14781. auto r = lynx::ui::quickTipSize (tip);
  14782. if (x + r.getWidth() > width - 12)
  14783. {
  14784. x = 12;
  14785. y += r.getHeight() + 10;
  14786. }
  14787. placed.emplace_back (r.withPosition (x, y), tip);
  14788. x += r.getWidth() + 10;
  14789. }
  14790. juce::Image sheet (juce::Image::ARGB, width, y + 20 + 12, true);
  14791. {
  14792. juce::Graphics g (sheet);
  14793. g.fillAll (lynx::theme::colour::bg3);
  14794. for (const auto& [r, tip] : placed)
  14795. lynx::ui::paintQuickTip (g, r.toFloat(), tip);
  14796. }
  14797. savePng (sheet, prefix + "-tips-sheet.png");
  14798. }
  14799. static juce::StringArray& textFitLog()
  14800. {
  14801. static juce::StringArray log;
  14802. return log;
  14803. }
  14804. // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
  14805. static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
  14806. {
  14807. if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
  14808. return false;
  14809. auto visible = [] (juce::GlyphArrangement& ga) {
  14810. int n = 0;
  14811. for (int i = 0; i < ga.getNumGlyphs(); ++i)
  14812. n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
  14813. return n;
  14814. };
  14815. juce::GlyphArrangement fitted, full;
  14816. fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
  14817. juce::jmax (1, maxLines), minScale);
  14818. full.addLineOfText (font, text, 0.0f, 0.0f);
  14819. return visible (fitted) < visible (full);
  14820. }
  14821. // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
  14822. static void checkTextFit (juce::Component& root, const juce::String& where)
  14823. {
  14824. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  14825. if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
  14826. return;
  14827. juce::String text;
  14828. bool cut = false;
  14829. if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
  14830. {
  14831. const auto font = label->getLookAndFeel().getLabelFont (*label);
  14832. const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
  14833. text = label->getText();
  14834. cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
  14835. label->getMinimumHorizontalScale());
  14836. }
  14837. else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
  14838. {
  14839. const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
  14840. text = toggle->getButtonText();
  14841. cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
  14842. c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
  14843. }
  14844. else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
  14845. button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
  14846. {
  14847. text = button->getButtonText();
  14848. cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
  14849. button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
  14850. }
  14851. if (cut)
  14852. {
  14853. juce::String path;
  14854. for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
  14855. if (p->getName().isNotEmpty())
  14856. path = p->getName() + (path.isEmpty() ? "" : "/") + path;
  14857. const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
  14858. + (path.isEmpty() ? juce::String() : " | " + path);
  14859. textFitLog().addIfNotAlreadyThere (line);
  14860. }
  14861. for (auto* child : c.getChildren())
  14862. visit (*child);
  14863. };
  14864. visit (root);
  14865. }
  14866. static void saveSnapshot (juce::Component& c, const juce::String& path)
  14867. {
  14868. checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
  14869. const juce::File file (path);
  14870. file.deleteFile();
  14871. juce::PNGImageFormat png;
  14872. if (auto out = file.createOutputStream())
  14873. png.writeImageToStream (c.createComponentSnapshot (c.getLocalBounds()), *out);
  14874. }
  14875. class MainWindow final : public juce::DocumentWindow
  14876. {
  14877. public:
  14878. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  14879. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons)
  14880. {
  14881. setUsingNativeTitleBar (true);
  14882. setIcon (lynx::logoImage());
  14883. content = new lynx::MainComponent (engine);
  14884. setContentOwned (content, true);
  14885. setResizable (true, true);
  14886. setResizeLimits (800, 400, 10000, 10000);
  14887. // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
  14888. // display: the AppImage catalog test runs on an 800x600 screen)
  14889. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  14890. {
  14891. const auto area = display->userArea;
  14892. const auto fit = [] (int design, int available) {
  14893. return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
  14894. };
  14895. setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
  14896. }
  14897. centreWithSize (getWidth(), getHeight());
  14898. // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
  14899. // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
  14900. const auto saved = stateFile().loadFileAsString().trim();
  14901. // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
  14902. const auto firstStart = saved.isEmpty()
  14903. && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
  14904. maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
  14905. if (saved.isNotEmpty())
  14906. restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
  14907. }
  14908. // Shows the window (built hidden while the splash screen is up).
  14909. void reveal()
  14910. {
  14911. if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
  14912. watchFrames ({});
  14913. setVisible (true);
  14914. lynx::applyWindowChrome (*this);
  14915. lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
  14916. if (maximiseOnReveal)
  14917. setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
  14918. toFront (true);
  14919. content->grabKeyboardFocus();
  14920. // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
  14921. // place and above it, once the window manager has placed this one
  14922. juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  14923. if (safe != nullptr)
  14924. safe->content->restoreDetachedWindows();
  14925. });
  14926. }
  14927. // The window's place and maximized state for the next start (main-window.txt in the settings folder).
  14928. void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
  14929. static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
  14930. void openFile (const juce::File& file) { content->openFile (file); }
  14931. lynx::MainComponent& getContent() { return *content; }
  14932. void showSetupWizard() { content->showSetupWizard(); }
  14933. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  14934. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  14935. // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
  14936. // counting when --uiperf watches too.
  14937. void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
  14938. {
  14939. if (probe == nullptr)
  14940. {
  14941. probe = std::make_unique<lynx::ui::FrameProbe>();
  14942. Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
  14943. probe->setBounds (getLocalBounds());
  14944. }
  14945. probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
  14946. if (lynx::uitrace::enabled())
  14947. lynx::uitrace::frame (now);
  14948. if (callback)
  14949. callback (now, area);
  14950. };
  14951. }
  14952. void resized() override
  14953. {
  14954. DocumentWindow::resized();
  14955. if (probe != nullptr)
  14956. probe->setBounds (getLocalBounds());
  14957. }
  14958. // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
  14959. std::function<void (double)> onFrame;
  14960. void paint (juce::Graphics& g) override
  14961. {
  14962. if (onFrame)
  14963. frameStart = juce::Time::getMillisecondCounterHiRes();
  14964. DocumentWindow::paint (g);
  14965. }
  14966. void paintOverChildren (juce::Graphics& g) override
  14967. {
  14968. DocumentWindow::paintOverChildren (g);
  14969. if (onFrame && frameStart > 0.0)
  14970. onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
  14971. frameStart = 0.0;
  14972. }
  14973. private:
  14974. lynx::MainComponent* content = nullptr; // owned by the window
  14975. std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
  14976. double frameStart = 0.0;
  14977. bool maximiseOnReveal = false;
  14978. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  14979. };
  14980. lynx::theme::LookAndFeel lookAndFeel;
  14981. std::unique_ptr<lynx::AudioEngine> engine;
  14982. std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
  14983. // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
  14984. // without registering it, listed as the driver type "ASIO driver file". True when one was added.
  14985. bool addDriverFileDeviceType()
  14986. {
  14987. const auto args = juce::JUCEApplication::getCommandLineParameterArray();
  14988. const auto i = args.indexOf ("--asiodll");
  14989. if (i < 0 || i + 1 >= args.size() || engine == nullptr)
  14990. return false;
  14991. auto& devices = engine->getDeviceManager();
  14992. devices.getAvailableDeviceTypes(); // creates the standard types first
  14993. for (auto* t : devices.getAvailableDeviceTypes())
  14994. if (t->getTypeName() == lynx::dllAsioTypeName)
  14995. return true;
  14996. auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
  14997. if (type == nullptr)
  14998. return false;
  14999. devices.addAudioDeviceType (std::move (type));
  15000. return true;
  15001. }
  15002. void restoreSavedDeviceState()
  15003. {
  15004. if (engine != nullptr)
  15005. engine->restoreAudioDeviceState (savedDeviceState.get());
  15006. }
  15007. std::unique_ptr<MainWindow> mainWindow;
  15008. std::unique_ptr<juce::Timer> perf; // --uiperf
  15009. std::unique_ptr<lynx::SplashScreen> splash;
  15010. double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
  15011. lynx::StartupOptions startupOptions;
  15012. juce::File fileToOpen;
  15013. bool startupFileHandled = false;
  15014. bool startWithoutPlugins = false; // --no-plugins project.lynx (round 190ap)
  15015. juce::File openTimeReport; // --opentime
  15016. int openTimeIdleSeconds = 10;
  15017. };
  15018. START_JUCE_APPLICATION (LynxApplication)