Main.cpp 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324
  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/Groove.h"
  6. #include "core/DrawMode.h"
  7. #include "core/SessionOps.h"
  8. #include "ui/ClipGridComponent.h"
  9. #include "ui/SessionMixer.h"
  10. #include "core/FlSamplers.h"
  11. #include "core/ArrangeOps.h"
  12. #include "core/ClipSample.h"
  13. #include "core/DetailChain.h"
  14. #include "core/SessionMixer.h"
  15. #include "core/PlaylistOps.h"
  16. #include "core/LastTweaked.h"
  17. #include "core/ClipOps.h"
  18. #include "core/FlTrackMenus.h"
  19. #include "core/FlClipMenu.h"
  20. #include "core/OneClickRec.h"
  21. #include "core/WarpTools.h"
  22. #include "core/Comping.h"
  23. #include "core/Drumaxx.h"
  24. #include "core/PatternBlocks.h"
  25. #include "core/LoadTrace.h"
  26. #include "core/ProjectSafety.h"
  27. #include "core/Patcher.h"
  28. #include "core/Rack.h"
  29. #include "ui/RackEditor.h"
  30. #include "ui/DrumRackShot.h"
  31. #include "core/Patcherize.h"
  32. #include "core/Performance.h"
  33. #include "core/VideoPlayer.h"
  34. #include "core/Effects.h"
  35. #include "core/MixSuite.h"
  36. #include "core/HardwareInsert.h"
  37. #include "core/EchoSuite.h"
  38. #include "core/LynxTune.h"
  39. #include "core/FlEffects.h"
  40. #include "core/FlpImport.h"
  41. #include "core/NoteEdit.h"
  42. #include "core/MaximusFx.h"
  43. #include "core/ChainPresets.h"
  44. #include "core/GoalKnobs.h"
  45. #include "core/MasterLooks.h"
  46. #include "core/Harmor.h"
  47. #include "flp/Flp.h"
  48. #include "core/DemoSongs.h"
  49. #include "core/FirstSongTour.h"
  50. #include "core/ShowcaseSong.h"
  51. #include "core/SynthPresets.h"
  52. #include "core/FlWrapper.h"
  53. #include "engine/AudioEngine.h"
  54. #include "engine/PreviewPlayer.h"
  55. #include "engine/Metronome.h"
  56. #include "engine/AudioLogger.h"
  57. #include "engine/DllAsioDevice.h"
  58. #include "engine/PipeWireDevice.h"
  59. #include "platform/LinuxRealtime.h"
  60. #include "engine/Exporter.h"
  61. #include "engine/FlStudioExport.h"
  62. #include "engine/MidiFileIo.h"
  63. #include "engine/PluginHost.h"
  64. #include "engine/Vst3NoteTuning.h"
  65. #include "engine/PluginSandbox.h"
  66. #include "engine/Bridge32Test.h"
  67. #include "engine/ClapFormat.h"
  68. #include "engine/ClapTeardownTest.h"
  69. #include "core/EdisonFx.h"
  70. #include "engine/ProjectFile.h"
  71. #include "ui/RemoteControl.h"
  72. #include "core/FlControlMenus.h"
  73. #include "core/PlaylistOps.h"
  74. #include "core/Sha256.h"
  75. #include "engine/SessionPack.h"
  76. #include "engine/LiveTest.h"
  77. #include "engine/ShortExportTest.h"
  78. #include "core/SessionIds.h"
  79. #include "core/SessionParts.h"
  80. #include "engine/SampleLibrary.h"
  81. #include "engine/Text.h"
  82. #include "platform/FileTypes.h"
  83. #include "platform/Package.h"
  84. #include "core/AlsImport.h"
  85. #include "core/PianoRollScript.h"
  86. #include "ui/ScriptPanel.h"
  87. #include "ui/AlsExportDialog.h"
  88. #include "ui/LiveRemoteUi.h"
  89. #include "ui/GamepadInput.h"
  90. #include "ui/SettingsPages.h"
  91. #include "ui/OtherAppsExport.h"
  92. #include "ui/TimerWhileShowing.h"
  93. #include "ui/MixerBasicsCheck.h"
  94. #include "ui/VideoPlayerView.h"
  95. #include "ui/VideoMedia.h"
  96. #include "ui/VideoTracks.h"
  97. #include "ui/AdrWindow.h"
  98. #include "ui/PlaylistComponent.h"
  99. #include "ui/PictureCheck.h"
  100. #include "ui/PatternBlocksView.h"
  101. #include "ui/PatcherEditor.h"
  102. #include "ui/VisualEditors.h"
  103. #include "ui/FlExtraEditors.h"
  104. #include "ui/VisualGl.h"
  105. #include "ui/DanceView.h"
  106. #include "ui/PluginPresetMenu.h"
  107. #include "ui/PluginWindow.h"
  108. #include "ui/Motion.h"
  109. #include "ui/NativeChild.h"
  110. #include "ui/Workspace.h"
  111. #include "ui/PluginThumbs.h"
  112. #include "ui/ClipProperties.h"
  113. #include "ui/NewProjectDialog.h"
  114. #include "ui/PluginMonitorWindow.h"
  115. #include "ui/TouchKeyboard.h"
  116. #include "ui/AutomationUi.h"
  117. #include "ui/PluginSkin.h"
  118. #include "ui/ChannelSettings.h"
  119. #include "ui/TempoDetectionDialog.h"
  120. #include "ui/AudioClipboard.h"
  121. #include "ui/FlVoicePanel.h"
  122. #include "ui/SlicexEditor.h"
  123. #include "core/LynxBanks.h"
  124. #include "core/NativeEngines.h"
  125. #include "ui/ControllerEditors.h"
  126. #include "ui/NewtoneEditor.h"
  127. #include "core/NewtoneFx.h"
  128. #include "core/FormulaController.h"
  129. #include "core/MidiControls.h"
  130. #include "core/FlSynths.h"
  131. #include "core/SoundFont.h"
  132. #include "core/Sfz.h"
  133. #include "core/Slicex.h"
  134. #include "ui/Dialogs.h"
  135. #include "ui/FileChoosers.h"
  136. #include "ui/TrackIcons.h"
  137. #include "core/RackOps.h"
  138. #include "core/Layer.h"
  139. #include "core/XyController.h"
  140. #include "core/FlCurve.h"
  141. #include "core/ControlSurface.h"
  142. #include "core/VoltageController.h"
  143. #include "ui/Controllers164.h"
  144. #include "core/StandIns.h"
  145. #include "ui/ExportDialog.h"
  146. #include "ui/QuickAddPalette.h"
  147. #include "ui/I18n.h"
  148. #include "ui/MainComponent.h"
  149. #include "ui/SimpleDock.h"
  150. #include "core/ScaleKeys.h"
  151. #include "core/KeyFollow.h"
  152. #include "core/SoundLibrary.h"
  153. #include "ui/MidiToolsPanel.h"
  154. #include "ui/FrameProbe.h"
  155. #include "ui/UiTrace.h"
  156. #include "core/MixerOps.h"
  157. #include "ui/QuickPick.h"
  158. #include "core/NoteTools.h"
  159. #include "engine/ProjectPackage.h"
  160. #include "ui/SetupWizard.h"
  161. #include "engine/FlStudio.h"
  162. #include "ui/HistoryPanel.h"
  163. #include "ui/VersionsPanel.h"
  164. #include "ui/CleanVoiceMenu.h"
  165. #include "ui/LyricsPanel.h"
  166. #include "ui/ReferenceMatchPanel.h"
  167. #include "ui/StartFromPanel.h"
  168. #include "ui/FirstSongTour.h"
  169. #include "ui/PluginsOffPanel.h"
  170. #include "ui/MissingFilesDialog.h"
  171. #include "ui/SettingsDialog.h"
  172. #include "ui/PluginManager.h"
  173. #include "ui/ShortcutManager.h"
  174. #include "ui/NoteToolDialogs.h"
  175. #include "ui/EventEditor.h"
  176. #include "ui/AudioEditor.h"
  177. #include "ui/TempoTapper.h"
  178. #include "core/EventEdit.h"
  179. #include "core/FacetEq.h"
  180. #include "ui/FacetEqEditor.h"
  181. #include "core/RackRenderer.h"
  182. #include "ui/ProEditors.h"
  183. #include "ui/ParametricEqEditor.h"
  184. #include "ui/PluginEditors.h"
  185. #include "core/PluginLayout.h"
  186. #include "core/EffectPresets.h"
  187. #include "ui/PluginHeader.h"
  188. #include "core/Vfx.h"
  189. #include "core/TransistorBass.h"
  190. #include "ui/Splash.h"
  191. #include "ui/Theme.h"
  192. #include "ui/ThemeSettings.h"
  193. #include "ui/WaveformView.h"
  194. #include "ui/WindowOwner.h"
  195. #include "ui/PluginKeysTest.h"
  196. #include "ui/Toolbar.h"
  197. #include "ui/ToolWindow.h"
  198. #include "platform/CrashGuard.h"
  199. #include "ui/CrashReporter.h"
  200. #include "ui/Updater.h"
  201. #include "ui/StemExtract.h"
  202. #include "ui/AudioToMidi.h"
  203. #include "ui/ShotScale.h"
  204. #include <atomic>
  205. #include <chrono>
  206. #include <cstdio>
  207. #include <cstdlib>
  208. #include <mutex>
  209. #include <thread>
  210. namespace
  211. {
  212. lynx::AudioEngine* crashEngine = nullptr;
  213. // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
  214. // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
  215. struct StartupTrace
  216. {
  217. using clock = std::chrono::steady_clock;
  218. const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
  219. const bool on = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
  220. juce::String text;
  221. clock::time_point last = t0;
  222. double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
  223. void mark (const char* step)
  224. {
  225. if (! on)
  226. return;
  227. const auto now = clock::now();
  228. const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
  229. text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7) << " " << step << "\n";
  230. last = now;
  231. lynx::platform::settingsFile ("startup.log").replaceWithText (text);
  232. }
  233. };
  234. StartupTrace startupTrace;
  235. void startupMarkHook (const char* step) { startupTrace.mark (step); }
  236. juce::File crashFolderForTest; // --faulttest: where the crash file goes instead of the settings' autosave folder
  237. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  238. void onCrash (void* exceptionPointers)
  239. {
  240. // (round 190ci: once. The hook for stacks Windows cannot walk, crashguard::setUnwalkableFaultHandler, may have run
  241. // this before the top-level filter does)
  242. static std::atomic<bool> reported { false };
  243. if (reported.exchange (true))
  244. return;
  245. const auto folder = crashFolderForTest != juce::File() ? crashFolderForTest : lynx::platform::settingsFile ("autosave");
  246. folder.createDirectory();
  247. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  248. // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
  249. // release LYNX.exe has no symbols, so its own frames were missing from the file)
  250. folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
  251. + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
  252. lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
  253. if (crashEngine != nullptr)
  254. {
  255. juce::String error;
  256. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  257. }
  258. }
  259. juce::File sessionsFolder()
  260. {
  261. return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
  262. }
  263. // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
  264. // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
  265. juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
  266. juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
  267. // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
  268. // whether its crash file blames a graphics driver
  269. struct UncleanCause
  270. {
  271. juce::String editorPlugin; // the last steps were that plugin's editor
  272. bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
  273. juce::String driverModule;
  274. };
  275. UncleanCause uncleanCause()
  276. {
  277. UncleanCause cause;
  278. juce::File crashFile;
  279. for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
  280. {
  281. const auto& step = uncleanSteps[i];
  282. if (step.startsWith ("crashed: backtrace in "))
  283. crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
  284. for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
  285. if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
  286. cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
  287. if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
  288. break; // older steps than these did not end the session
  289. }
  290. // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
  291. // likely cause when the session then ended without a word: offer it a separate process too
  292. for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
  293. if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
  294. cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
  295. if (crashFile.existsAsFile())
  296. {
  297. // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
  298. auto text = crashFile.loadFileAsString();
  299. if (text.contains ("--- frames"))
  300. text = text.fromFirstOccurrenceOf ("--- frames", false, false);
  301. auto lines = juce::StringArray::fromLines (text);
  302. int looked = 0;
  303. for (const auto& line : lines)
  304. {
  305. const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
  306. if (module.isEmpty() || ! module.endsWith (".dll"))
  307. continue;
  308. if (++looked > 12)
  309. break;
  310. for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
  311. "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
  312. if (module.startsWith (driver))
  313. {
  314. cause.gpuDriver = true;
  315. cause.driverModule = module;
  316. break;
  317. }
  318. if (cause.gpuDriver)
  319. break;
  320. }
  321. }
  322. return cause;
  323. }
  324. juce::String collectUncleanSessions()
  325. {
  326. juce::String lastStep;
  327. juce::Time newest;
  328. for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
  329. {
  330. const auto text = file.loadFileAsString();
  331. juce::StringPairArray values;
  332. juce::StringArray steps;
  333. for (const auto& line : juce::StringArray::fromLines (text))
  334. {
  335. if (line.startsWith ("step="))
  336. steps.add (line.fromFirstOccurrenceOf ("=", false, false));
  337. else if (line.contains ("="))
  338. values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
  339. }
  340. const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
  341. const auto start = (std::uint64_t) values["start"].getLargeIntValue();
  342. if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
  343. continue; // this run, or another LYNX window still open
  344. lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
  345. .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
  346. file.deleteFile();
  347. if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
  348. {
  349. newest = modified;
  350. lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
  351. uncleanSessionText = text;
  352. uncleanSteps.clear();
  353. for (const auto& step : steps)
  354. uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
  355. }
  356. }
  357. return lastStep;
  358. }
  359. } // namespace
  360. // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
  361. // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
  362. // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
  363. // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
  364. // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
  365. // the mouse is released.
  366. struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
  367. private juce::HighResolutionTimer
  368. {
  369. ~UiPerfDrag() override { stopTimer(); }
  370. void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
  371. {
  372. window = &windowIn;
  373. engine = engineIn;
  374. track = trackIn;
  375. railInWindow = window->getLocalArea (&strips, rail);
  376. watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
  377. visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
  378. const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
  379. x = (float) railInWindow.getCentreX();
  380. startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
  381. amplitude = 0.4f * (float) railInWindow.getHeight();
  382. centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
  383. t0 = juce::Time::getMillisecondCounterHiRes();
  384. inject (x, startY, false);
  385. juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  386. inject (x, startY, true);
  387. active = true;
  388. startTimer (8);
  389. }
  390. // message thread
  391. void framePainted (double now, juce::Rectangle<int> area)
  392. {
  393. if (pending.empty() || ! area.intersects (watch))
  394. return;
  395. for (const auto t : pending)
  396. latencies.push_back (now - t);
  397. pending.clear();
  398. ++framesOverFader;
  399. }
  400. // the moves end; as in the reporter's clip, the song is stopped while the button is still down
  401. juce::String stop()
  402. {
  403. stopTimer();
  404. active = false;
  405. valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
  406. engine->stop();
  407. juce::String text;
  408. text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
  409. << " folded into the next (the message thread still busy with the previous one)\n"
  410. << " move waited for the message thread: " << describe (queueDelays) << "\n"
  411. << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
  412. << " frames over the fader\n";
  413. return text;
  414. }
  415. juce::String release()
  416. {
  417. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  418. juce::ModifierKeys::currentModifiers = {};
  419. inject (x, lastY, false);
  420. return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
  421. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  422. }
  423. juce::String released() const
  424. {
  425. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  426. return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
  427. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  428. }
  429. private:
  430. juce::Component* window = nullptr;
  431. lynx::AudioEngine* engine = nullptr;
  432. int track = 1;
  433. juce::Rectangle<int> railInWindow, watch;
  434. bool visible = false;
  435. float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
  436. double t0 = 0.0;
  437. std::atomic<bool> active { false }, posted { false };
  438. std::atomic<int> dropped { 0 };
  439. int moves = 0, framesOverFader = 0;
  440. float valueAtRelease = 0.0f;
  441. std::vector<double> pending, latencies, queueDelays;
  442. static juce::String describe (std::vector<double> v)
  443. {
  444. if (v.empty())
  445. return "none";
  446. std::sort (v.begin(), v.end());
  447. const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
  448. return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
  449. + juce::String (v.back(), 1) + " ms";
  450. }
  451. void inject (float px, float py, bool down)
  452. {
  453. lastY = py;
  454. if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
  455. {
  456. const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
  457. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
  458. down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
  459. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
  460. juce::Time::currentTimeMillis());
  461. }
  462. }
  463. void hiResTimerCallback() override
  464. {
  465. if (! active.load())
  466. return;
  467. if (posted.exchange (true))
  468. {
  469. ++dropped;
  470. return;
  471. }
  472. const auto postedAt = juce::Time::getMillisecondCounterHiRes();
  473. juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
  474. self->posted = false;
  475. if (! self->active.load())
  476. return;
  477. const auto now = juce::Time::getMillisecondCounterHiRes();
  478. self->queueDelays.push_back (now - postedAt);
  479. // up and down ~1.3 times a second, like the reporter's hand
  480. const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
  481. self->inject (self->x, y, true);
  482. self->pending.push_back (postedAt);
  483. ++self->moves;
  484. });
  485. }
  486. };
  487. class LynxApplication final : public juce::JUCEApplication
  488. {
  489. public:
  490. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  491. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  492. // the plugin scan runs copies of LYNX as child processes
  493. bool moreThanOneInstanceAllowed() override { return true; }
  494. // A file handed to the running application. macOS does this for every Finder double-click, "Open With" and Dock drop,
  495. // also the one that starts LYNX (its argv has no file). On Windows and Linux a second start is a second process
  496. // (moreThanOneInstanceAllowed) with the file as an argument, so this is not called there. Only the first file of a
  497. // multiple selection opens: a project replaces the one before it. (D#92, round 180a)
  498. void anotherInstanceStarted (const juce::String& commandLine) override
  499. {
  500. const auto files = lynx::safety::filesInCommandLine (commandLine.toStdString());
  501. if (files.empty())
  502. return;
  503. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (files.front().c_str()));
  504. if (! startupFileHandled) // still starting: openStartupFile takes it, nothing to ask about yet
  505. {
  506. fileToOpen = file;
  507. return;
  508. }
  509. if (mainWindow != nullptr)
  510. {
  511. mainWindow->toFront (true);
  512. mainWindow->getContent().openFileRequest (file);
  513. }
  514. }
  515. void initialise (const juce::String& commandLine) override
  516. {
  517. // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
  518. if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
  519. {
  520. updateHelper = true;
  521. quit();
  522. return;
  523. }
  524. // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
  525. if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
  526. {
  527. relaunched = true;
  528. setApplicationReturnValue (code);
  529. quit();
  530. return;
  531. }
  532. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
  533. juce::SystemStats::setApplicationCrashHandler (onCrash);
  534. // round 190ci: also for a fault on a stack Windows cannot walk, which never reaches that handler (Windows)
  535. lynx::crashguard::setUnwalkableFaultHandler (onCrash);
  536. if (const auto args = juce::StringArray::fromTokens (commandLine, true); args.contains ("--faulttest"))
  537. {
  538. // LYNX.exe --faulttest plain|unwalkable <folder> (round 190ci): ends by an access violation on purpose,
  539. // before any window, so that --selftest can check that the crash file gets written (into <folder>)
  540. const auto i = args.indexOf ("--faulttest");
  541. crashFolderForTest = juce::File (args[i + 2].unquoted());
  542. lynx::crashguard::quietCrashReports();
  543. // round 190dt: guarded / guarded-libc = LYNX's own fault inside a guarded plugin call (Linux / macOS): it must
  544. // reach the crash handler like any other; a return means the guard swallowed it
  545. if (args[i + 1].startsWith ("guarded"))
  546. {
  547. const auto code = lynx::crashguard::faultInGuardedCallForTest (args[i + 1] == "guarded-libc");
  548. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText (lynx::crashguard::describe (code));
  549. lynx::crashguard::exitNow (4);
  550. }
  551. lynx::crashguard::faultForTest (args[i + 1] == "unwalkable");
  552. }
  553. lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
  554. // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
  555. lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
  556. juce::AudioFormatManager formats;
  557. formats.registerBasicFormats();
  558. std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
  559. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
  560. return false;
  561. const auto frames = (int) reader->lengthInSamples;
  562. juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
  563. if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
  564. return false;
  565. out.channels.clear();
  566. for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
  567. out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
  568. out.sampleRate = reader->sampleRate;
  569. out.loopStart = out.loopEnd = -1;
  570. return true;
  571. });
  572. // child process of a sandboxed plugin: no window or audio of its own
  573. if (lynx::runPluginSandboxWorker (commandLine))
  574. {
  575. lynx::crashguard::quietCrashReports();
  576. sandboxChild = true;
  577. return;
  578. }
  579. // --shot-scale <v> / --shot-suffix <text> (round 190bi, ui/ShotScale.h): the pixel scale and file-name suffix of every
  580. // picture route, taken out here so the routes' own arguments keep their places
  581. const auto args = lynx::shot::takeArguments (juce::StringArray::fromTokens (commandLine, true));
  582. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  583. lynx::i18n::initialise (args);
  584. // interface font: saved in Settings › General; --uifont "Name" overrides it for this run
  585. const auto uiFontArg = args.indexOf ("--uifont");
  586. lookAndFeel.applyInterfaceFont (lynx::i18n::current(), uiFontArg >= 0 ? args[uiFontArg + 1].unquoted() : juce::String());
  587. if (args.contains ("--showcase"))
  588. {
  589. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  590. const auto i = args.indexOf ("--showcase");
  591. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  592. return;
  593. }
  594. if (args.contains ("--demosongs"))
  595. {
  596. // round 190dv: LYNX's two short genre demos (core/DemoSongs.h) as .lynx files: --demosongs <folder>
  597. // (resources/demos/ in the repository)
  598. const auto i = args.indexOf ("--demosongs");
  599. runDemoSongs (args[i + 1].unquoted());
  600. return;
  601. }
  602. if (args.contains ("--sandboxtest"))
  603. {
  604. const auto i = args.indexOf ("--sandboxtest");
  605. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  606. return;
  607. }
  608. if (args.contains ("--bridge32test"))
  609. {
  610. // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
  611. // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
  612. const auto i = args.indexOf ("--bridge32test");
  613. const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
  614. setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
  615. quit();
  616. return;
  617. }
  618. if (args.contains ("--rtstress"))
  619. {
  620. // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
  621. // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
  622. // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
  623. // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
  624. const auto i = args.indexOf ("--rtstress");
  625. const auto seconds = args[i + 3].getDoubleValue();
  626. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  627. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  628. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  629. runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
  630. option ("--type"), option ("--device"), option ("--record"));
  631. return;
  632. }
  633. if (args.contains ("--cliplooptest"))
  634. {
  635. // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
  636. // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
  637. // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
  638. // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
  639. // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
  640. const auto i = args.indexOf ("--cliplooptest");
  641. runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
  642. return;
  643. }
  644. if (args.contains ("--devicechangetest"))
  645. {
  646. // LYNX --devicechangetest report.txt [switches] [--plugin file]... (round 190c, issue #134: changing the
  647. // output device with a project open crashed LYNX). The engine plays a project of every instrument and effect
  648. // it can make here on stand-in devices with real callback threads, while the output device, its sample
  649. // rate and its buffer size change the way Settings > Audio changes them (8 kHz mono to 192 kHz, buffers of
  650. // 32 to 16384 samples, a device plugged in, the open one unplugged, one that refuses to open). After every
  651. // change the song must sound, finite, at the new rate. No window, no real audio or MIDI device.
  652. const auto i = args.indexOf ("--devicechangetest");
  653. const juce::File report (args[i + 1].unquoted());
  654. const auto switches = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  655. juce::StringArray plugins;
  656. for (int k = 0; k + 1 < args.size(); ++k)
  657. if (args[k] == "--plugin")
  658. plugins.add (args[k + 1].unquoted());
  659. auto text = std::make_shared<juce::String>();
  660. // --quick: the selftest's handful of instruments and effects instead of every one
  661. const auto result = lynx::AudioEngine::deviceChangeSelfTest (switches > 0 ? switches : 40, ! args.contains ("--quick"), plugins, [report, text] (const juce::String& line) {
  662. *text << line << "\n";
  663. report.replaceWithText (*text + "(running)\n"); // what was reached, if it crashes
  664. });
  665. *text << "device_change=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  666. report.replaceWithText (*text);
  667. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  668. quit();
  669. return;
  670. }
  671. if (args.contains ("--shortexporttest"))
  672. {
  673. // LYNX --shortexporttest report.txt [repeats] [--plugin file]... (round 190c, issue #138: a short note at
  674. // the very start of the Playlist exported quiet). Every instrument LYNX can make here, and a synth with
  675. // effects, tail modes, normalising and other rates, exported through the Export window's path (the job
  676. // made on the message thread, run on its own thread, the message loop running) with a 2-second note at
  677. // tick 0 and again with it at bar 2: the note must come out the same. No window.
  678. const auto i = args.indexOf ("--shortexporttest");
  679. const juce::File report (args[i + 1].unquoted());
  680. const auto repeats = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  681. juce::StringArray plugins;
  682. for (int k = 0; k + 1 < args.size(); ++k)
  683. if (args[k] == "--plugin")
  684. plugins.add (args[k + 1].unquoted());
  685. auto text = std::make_shared<juce::String>();
  686. lynx::shortexport::run (true, repeats > 0 ? repeats : 3, plugins,
  687. [report, text] (const juce::String& line) {
  688. *text << line << "\n";
  689. report.replaceWithText (*text + "(running)\n");
  690. },
  691. [this, report, text] (juce::String result) {
  692. *text << "short_export=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  693. report.replaceWithText (*text);
  694. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  695. quit();
  696. });
  697. return;
  698. }
  699. if (args.contains ("--slicexedittest"))
  700. {
  701. // LYNX --slicexedittest project script.txt report.txt [png-prefix] (round 190aj): the Slicex editor of the
  702. // project's first Slicex channel, off screen, driven by the script's commands (ui/SlicexEditor.h; mouse
  703. // gestures at fractions of the deck's width, the menu entries, shortcuts). The report holds each command
  704. // and what the state held after it; "shot <name>" writes <png-prefix><name>.png.
  705. const auto i = args.indexOf ("--slicexedittest");
  706. runSlicexEditTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  707. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  708. return;
  709. }
  710. if (args.contains ("--slicexkeytest"))
  711. {
  712. // LYNX --slicexkeytest report.txt (round 190ac): what a click on the Slicex editor's keyboard sends
  713. // (AudioEngine::sendLiveNote on the channel, velocity 100/128) through the real engine's device callback
  714. // (a stand-in device, driven block by block): the key's region must sound, on the channel's mixer meter
  715. // too, another key must play another region, and the note-off must end it.
  716. runSlicexKeyTest (juce::File (args[args.indexOf ("--slicexkeytest") + 1].unquoted()));
  717. return;
  718. }
  719. if (args.contains ("--countinrectest"))
  720. {
  721. // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
  722. // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
  723. // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
  724. // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
  725. // 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
  726. // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
  727. const auto i = args.indexOf ("--countinrectest");
  728. runCountInRecordTest (juce::File (args[i + 1].unquoted()));
  729. return;
  730. }
  731. if (args.contains ("--bendrectest"))
  732. {
  733. // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
  734. // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
  735. // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
  736. // automation clip (song mode) of the channel's pitch bend must follow the sweep.
  737. const auto i = args.indexOf ("--bendrectest");
  738. const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
  739. runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
  740. return;
  741. }
  742. if (args.contains ("--rectest"))
  743. {
  744. // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
  745. // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
  746. // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
  747. // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
  748. // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
  749. // and 1 of post-roll (playback stops by itself after the post-roll).
  750. const auto i = args.indexOf ("--rectest");
  751. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  752. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  753. runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
  754. args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
  755. return;
  756. }
  757. if (args.contains ("--hwinserttest"))
  758. {
  759. // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
  760. // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
  761. // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
  762. // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
  763. // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
  764. // sample as the right side's.
  765. const auto i = args.indexOf ("--hwinserttest");
  766. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  767. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
  768. // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
  769. // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
  770. runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
  771. option ("--buffer").getIntValue(), args.contains ("--patcher"),
  772. args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
  773. return;
  774. }
  775. if (args.contains ("--uiperf"))
  776. {
  777. // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
  778. const auto i = args.indexOf ("--uiperf");
  779. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  780. runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  781. return;
  782. }
  783. if (args.contains ("--cachetest"))
  784. {
  785. // LYNX --cachetest project.(flp|lynx) report.txt (round 174f): the Playlist's cached picture against exact
  786. // paints after zooms, scrolls and repaints, off screen (no window)
  787. const auto i = args.indexOf ("--cachetest");
  788. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  789. runCacheTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  790. return;
  791. }
  792. if (args.contains ("--picturetest"))
  793. {
  794. // LYNX --picturetest report.txt [project.(flp|lynx)] (round 190bm): the Playlist and the Mixer drawn through
  795. // their cached pictures at 100-300 %, into native and software targets, against straight paints; off
  796. // screen (no window)
  797. const auto i = args.indexOf ("--picturetest");
  798. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  799. runPictureTest (juce::File (args[i + 1].unquoted()), i + 2 < args.size() ? juce::File (args[i + 2].unquoted()) : juce::File());
  800. return;
  801. }
  802. if (args.contains ("--timertest"))
  803. {
  804. // LYNX --timertest report.txt (round 174f): ui::TimerWhileShowing through hide / show / minimise (opens a small window)
  805. runTimerTest (juce::File (args[args.indexOf ("--timertest") + 1].unquoted()));
  806. return;
  807. }
  808. if (args.contains ("--livepeer"))
  809. {
  810. // LYNX --livepeer host|guest|rejoin <folder> [--relay URL] [--code CODE|@file]: one computer's side of a live
  811. // session between two real computers, no window (round 190ah)
  812. setApplicationReturnValue (lynx::livetest::runPeer (args));
  813. quit();
  814. return;
  815. }
  816. if (args.contains ("--livetest"))
  817. {
  818. // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
  819. setApplicationReturnValue (lynx::livetest::run (args));
  820. quit();
  821. return;
  822. }
  823. if (args.contains ("--selftest"))
  824. {
  825. const auto i = args.indexOf ("--selftest");
  826. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  827. return;
  828. }
  829. if (args.contains ("--scan-one"))
  830. {
  831. // child process of the plugin scan (see PluginHost::scan)
  832. const auto i = args.indexOf ("--scan-one");
  833. // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
  834. // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
  835. // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
  836. lynx::crashguard::quietCrashReports();
  837. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  838. lynx::crashguard::exitNow (0);
  839. }
  840. if (args.contains ("--packageinfo"))
  841. {
  842. // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
  843. // workflow runs it inside the installed test package
  844. juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
  845. quit();
  846. return;
  847. }
  848. if (args.contains ("--paths"))
  849. {
  850. // diagnostics: folders LYNX searches
  851. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  852. juce::String report;
  853. report << "programs=" << programs.getFullPathName() << "\n";
  854. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  855. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  856. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  857. quit();
  858. return;
  859. }
  860. if (args.contains ("--fldb"))
  861. {
  862. // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
  863. // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
  864. const auto i = args.indexOf ("--fldb");
  865. const auto fl = lynx::findFlStudio();
  866. lynx::PluginHost host (false);
  867. juce::String report;
  868. report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
  869. for (const auto& f : fl.vstFolders)
  870. report << "flvstfolder=" << f << "\n";
  871. report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
  872. for (const auto& e : host.flPluginDatabase().entries())
  873. report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
  874. const auto suggested = host.suggestedFolders();
  875. for (int k = 0; k < suggested.getNumPaths(); ++k)
  876. report << "folder=" << suggested[k].getFullPathName() << "\n";
  877. if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
  878. {
  879. juce::MemoryBlock data;
  880. project.loadFileAsData (data);
  881. try
  882. {
  883. for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
  884. {
  885. juce::String how;
  886. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  887. const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
  888. report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  889. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
  890. << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
  891. }
  892. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  893. const auto candidates = host.filesToScanFor (uses);
  894. report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
  895. if (args.contains ("--scan"))
  896. {
  897. // the targeted scan an open would run (child processes; the user's plugin list is not touched)
  898. report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
  899. for (const auto& use : uses)
  900. {
  901. juce::String how;
  902. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  903. report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  904. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
  905. }
  906. }
  907. }
  908. catch (const flp::Error& e)
  909. {
  910. report << "error=" << e.what() << "\n";
  911. }
  912. }
  913. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  914. quit();
  915. return;
  916. }
  917. if (args.contains ("--midisync-test"))
  918. {
  919. // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
  920. const auto i = args.indexOf ("--midisync-test");
  921. const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  922. const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  923. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
  924. quit();
  925. return;
  926. }
  927. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  928. {
  929. // diagnostics: driver types and output devices JUCE offers (without opening any)
  930. juce::AudioDeviceManager manager;
  931. juce::String report;
  932. manager.getAvailableDeviceTypes();
  933. if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
  934. manager.addAudioDeviceType (std::move (pipeWire));
  935. #if JUCE_LINUX
  936. report << lynx::describePipeWire() << "\n";
  937. #endif
  938. for (auto* type : manager.getAvailableDeviceTypes())
  939. {
  940. type->scanForDevices();
  941. report << "type=" << type->getTypeName() << "\n";
  942. for (const auto& name : type->getDeviceNames (false))
  943. report << " output=" << name << "\n";
  944. for (const auto& name : type->getDeviceNames (true))
  945. report << " input=" << name << "\n";
  946. }
  947. for (const auto& d : juce::MidiInput::getAvailableDevices())
  948. report << "midi-in=" << d.name << "\n";
  949. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  950. report << "midi-out=" << d.name << "\n";
  951. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  952. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  953. quit();
  954. return;
  955. }
  956. if (args.contains ("--devicetest"))
  957. {
  958. // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
  959. // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
  960. // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
  961. // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
  962. // cable / PipeWire link: the round-trip latency (3 s)
  963. const auto i = args.indexOf ("--devicetest");
  964. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  965. auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
  966. const auto wantInput = inputName.isNotEmpty();
  967. juce::String report;
  968. const juce::File reportFile (args[i + 3].unquoted());
  969. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  970. step ("step=start");
  971. juce::AudioDeviceManager manager;
  972. manager.getAvailableDeviceTypes();
  973. if (auto pipeWire = lynx::makePipeWireDeviceType())
  974. manager.addAudioDeviceType (std::move (pipeWire));
  975. std::unique_ptr<juce::AudioIODevice> device;
  976. for (auto* type : manager.getAvailableDeviceTypes())
  977. if (type->getTypeName() == typeName)
  978. {
  979. type->scanForDevices();
  980. if (wantInput && type->hasSeparateInputsAndOutputs())
  981. {
  982. const auto inputs = type->getDeviceNames (true);
  983. if (inputName == "*" || ! inputs.contains (inputName))
  984. {
  985. const auto index = type->getDefaultDeviceIndex (true);
  986. inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  987. }
  988. for (const auto& n : inputs)
  989. step ("input_device=" + n);
  990. step ("input_chosen=" + inputName);
  991. }
  992. else if (wantInput)
  993. inputName = deviceName;
  994. step ("step=create");
  995. device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
  996. step ("step=created");
  997. }
  998. struct Silence final : juce::AudioIODeviceCallback
  999. {
  1000. std::atomic<int> calls { 0 }, inputs { 0 };
  1001. std::array<std::atomic<float>, 64> peaks {};
  1002. // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
  1003. // loopback; the delays in samples
  1004. bool roundtrip = false;
  1005. int period = 12000;
  1006. std::int64_t position = 0, lastClick = -1;
  1007. std::vector<int> delays;
  1008. void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
  1009. const juce::AudioIODeviceCallbackContext&) override
  1010. {
  1011. for (int c = 0; c < channels; ++c)
  1012. if (out[c] != nullptr)
  1013. juce::FloatVectorOperations::clear (out[c], n);
  1014. if (roundtrip)
  1015. {
  1016. for (int i = 0; i < n; ++i)
  1017. {
  1018. if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
  1019. {
  1020. if (delays.size() < delays.capacity())
  1021. delays.push_back ((int) (position + i - lastClick));
  1022. lastClick = -1;
  1023. }
  1024. if ((position + i) % period == 0 && position + i > 0)
  1025. {
  1026. for (int c = 0; c < channels; ++c)
  1027. if (out[c] != nullptr)
  1028. out[c][i] = 0.9f;
  1029. lastClick = position + i;
  1030. }
  1031. }
  1032. position += n;
  1033. }
  1034. inputs.store (numIn);
  1035. for (int c = 0; c < juce::jmin (numIn, 64); ++c)
  1036. if (in[c] != nullptr)
  1037. {
  1038. const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
  1039. const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
  1040. if (peak > peaks[(std::size_t) c].load())
  1041. peaks[(std::size_t) c].store (peak);
  1042. }
  1043. ++calls;
  1044. }
  1045. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  1046. void audioDeviceStopped() override {}
  1047. } silence;
  1048. bool ok = false;
  1049. if (device == nullptr)
  1050. step ("error=device not found");
  1051. else
  1052. {
  1053. step ("step=open");
  1054. juce::BigInteger outputs;
  1055. outputs.setRange (0, 2, true);
  1056. const auto rates = device->getAvailableSampleRates();
  1057. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  1058. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  1059. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  1060. juce::BigInteger inputs;
  1061. if (wantInput)
  1062. {
  1063. const auto names = device->getInputChannelNames();
  1064. step ("input_channels=" + juce::String (names.size()));
  1065. for (int c = 0; c < names.size(); ++c)
  1066. step (" in" + juce::String (c + 1) + "=" + names[c]);
  1067. inputs.setRange (0, juce::jmin (64, names.size()), true);
  1068. }
  1069. // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
  1070. const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  1071. const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
  1072. if (error.isNotEmpty())
  1073. step ("error=" + error);
  1074. else
  1075. {
  1076. step ("step=start_callbacks");
  1077. silence.roundtrip = args.contains ("--roundtrip");
  1078. silence.period = juce::jmax (1, (int) (rate / 4));
  1079. silence.delays.reserve (64);
  1080. device->start (&silence);
  1081. juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
  1082. device->stop();
  1083. if (silence.roundtrip)
  1084. {
  1085. auto d = silence.delays;
  1086. std::sort (d.begin(), d.end());
  1087. report << "roundtrip_clicks=" << (int) d.size() << "\n";
  1088. if (! d.empty())
  1089. report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
  1090. << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
  1091. }
  1092. report << "rate=" << device->getCurrentSampleRate() << "\n"
  1093. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  1094. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  1095. << "callbacks=" << silence.calls.load() << "\n";
  1096. if (wantInput)
  1097. {
  1098. report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
  1099. << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
  1100. << "callback_inputs=" << silence.inputs.load() << "\n";
  1101. for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
  1102. report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
  1103. }
  1104. ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
  1105. device->close();
  1106. }
  1107. }
  1108. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  1109. setApplicationReturnValue (ok ? 0 : 1);
  1110. quit();
  1111. return;
  1112. }
  1113. if (args.contains ("--scantest"))
  1114. {
  1115. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  1116. const auto i = args.indexOf ("--scantest");
  1117. lynx::PluginHost host (false);
  1118. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  1119. juce::String report;
  1120. report << "found=" << found << "\n";
  1121. for (const auto& t : host.getKnownPlugins().getTypes())
  1122. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  1123. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  1124. report << " blacklisted: " << f << "\n";
  1125. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  1126. setApplicationReturnValue (found > 0 ? 0 : 1);
  1127. quit();
  1128. return;
  1129. }
  1130. if (args.contains ("--wrappermiditest"))
  1131. {
  1132. // LYNX.exe --wrappermiditest plugin.dll report.txt (round 181c), with LYNX_TEST_VST2_MIDILOG set: what a
  1133. // hosted plugin receives after a wrapper MIDI option changes while it runs
  1134. const auto i = args.indexOf ("--wrappermiditest");
  1135. runWrapperMidiTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1136. return;
  1137. }
  1138. if (args.contains ("--wrappershot"))
  1139. {
  1140. const auto i = args.indexOf ("--wrappershot");
  1141. runWrapperShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1142. return;
  1143. }
  1144. if (args.contains ("--multiouttest"))
  1145. {
  1146. const auto i = args.indexOf ("--multiouttest");
  1147. runMultiOutTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1148. return;
  1149. }
  1150. if (args.contains ("--vst2test"))
  1151. {
  1152. const auto i = args.indexOf ("--vst2test");
  1153. runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
  1154. return;
  1155. }
  1156. if (args.contains ("--vst3noteidtest"))
  1157. {
  1158. const auto i = args.indexOf ("--vst3noteidtest");
  1159. runVst3NoteIdTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1160. return;
  1161. }
  1162. if (args.contains ("--lv2scantest"))
  1163. {
  1164. runLv2ScanTest (args[args.indexOf ("--lv2scantest") + 1].unquoted());
  1165. return;
  1166. }
  1167. if (args.contains ("--wrappertest"))
  1168. {
  1169. const auto i = args.indexOf ("--wrappertest");
  1170. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1171. return;
  1172. }
  1173. if (args.contains ("--plugintest"))
  1174. {
  1175. const auto i = args.indexOf ("--plugintest");
  1176. // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
  1177. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1178. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1179. return;
  1180. }
  1181. if (args.contains ("--crashguardtest"))
  1182. {
  1183. // LYNX --crashguardtest "LYNX Test Crash.vst3|.clap" report.txt [process|memcpy] (round 190dt,
  1184. // tools/testplugin/lynx_test_crash*.{c,cpp}): the plugin crashes in its 40th block on insert 1; LYNX must
  1185. // catch it, mark the slot, keep playing the other inserts, save the project, reload the plugin; then the
  1186. // saved project opens with the plugin crashing on its state; and LYNX's own faults are still crashes
  1187. const auto i = args.indexOf ("--crashguardtest");
  1188. runCrashGuardTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1189. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("process"));
  1190. return;
  1191. }
  1192. if (args.contains ("--claprestarttest"))
  1193. {
  1194. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
  1195. const auto i = args.indexOf ("--claprestarttest");
  1196. runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1197. return;
  1198. }
  1199. if (args.contains ("--clapteardowntest"))
  1200. {
  1201. // LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt (round 190az, engine/ClapTeardownTest.cpp)
  1202. const auto i = args.indexOf ("--clapteardowntest");
  1203. lynx::runClapTeardownTest (args[i + 1].unquoted(), args[i + 2].unquoted(), [this] (int code) {
  1204. setApplicationReturnValue (code);
  1205. quit();
  1206. });
  1207. return;
  1208. }
  1209. if (args.contains ("--mpetest"))
  1210. {
  1211. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108)
  1212. const auto i = args.indexOf ("--mpetest");
  1213. runMpeTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1214. return;
  1215. }
  1216. if (args.contains ("--editortest"))
  1217. {
  1218. // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
  1219. // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
  1220. const auto i = args.indexOf ("--editortest");
  1221. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1222. runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1223. return;
  1224. }
  1225. if (args.contains ("--editorcrashtest"))
  1226. {
  1227. // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
  1228. // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
  1229. // that editor, record the trace and keep running its message loop.
  1230. const auto i = args.indexOf ("--editorcrashtest");
  1231. runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1232. return;
  1233. }
  1234. if (args.contains ("--reloadtest"))
  1235. {
  1236. // LYNX --reloadtest plugin report.txt [shots folder] [--wait-kill]: round 190ao (reload a crashed plugin).
  1237. // Hosts the plugin in a separate process (a channel for an instrument, insert 1 for an effect) in an offline
  1238. // engine, crashes its process (--wait-kill: writes <report>.pid and waits for the process to be killed
  1239. // from outside), checks that nothing reloads by itself, reloads it on request and checks the new process,
  1240. // the state captured last, the untouched song and undo history; twice. With a shots folder: PNGs of the
  1241. // plugin window's crash notice and of the prompt.
  1242. const auto i = args.indexOf ("--reloadtest");
  1243. runReloadTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1244. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String(), args.contains ("--wait-kill"));
  1245. return;
  1246. }
  1247. if (args.contains ("--pluginoptionstest"))
  1248. {
  1249. // LYNX --pluginoptionstest plugin report.txt [shots folder]: round 190ao. Hosts the plugin inside LYNX (a
  1250. // channel for an instrument, insert 1 for an effect) in an offline engine, opens its window and checks
  1251. // LYNX's own plugin-window options: Pin on top (set, kept above another window, saved with the plugin,
  1252. // back when the window opens again). With a shots folder: PNGs of each state. The window is on screen.
  1253. const auto i = args.indexOf ("--pluginoptionstest");
  1254. runPluginOptionsTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1255. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String());
  1256. return;
  1257. }
  1258. if (args.contains ("--plugwintest"))
  1259. {
  1260. // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
  1261. // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
  1262. // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
  1263. // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
  1264. const auto i = args.indexOf ("--plugwintest");
  1265. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
  1266. auto seconds = 15;
  1267. for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
  1268. if (args[k].containsOnly ("0123456789"))
  1269. seconds = args[k].getIntValue();
  1270. runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
  1271. return;
  1272. }
  1273. if (args.contains ("--fittest"))
  1274. {
  1275. // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
  1276. // the screen and a big resizable window that grows with a zoom change keep their title bar and close
  1277. // button on the screen. The windows show for about two seconds.
  1278. const auto i = args.indexOf ("--fittest");
  1279. runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
  1280. return;
  1281. }
  1282. if (args.contains ("--windowtest"))
  1283. {
  1284. // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
  1285. // over the main window and checks that each one stays in front, owned by the main window, with the
  1286. // keyboard focus (issue #4). The windows appear on screen for a few seconds.
  1287. runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
  1288. return;
  1289. }
  1290. if (args.contains ("--focustest"))
  1291. {
  1292. // LYNX --focustest report.txt (issue #161): the main window with the Playlist and the Piano roll (native
  1293. // child windows with docking on). For each: LYNX goes to the background (the main window loses the focus),
  1294. // the user comes back with a click in the panel, then presses Space: playback must start. Also: a text
  1295. // field's focus comes back with the window, and inside the active window the click's answer is unchanged.
  1296. // Shows a window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  1297. runFocusTest (args[args.indexOf ("--focustest") + 1].unquoted());
  1298. return;
  1299. }
  1300. if (args.contains ("--simplekeytest"))
  1301. {
  1302. // LYNX --simplekeytest report.txt (round 190fc, 0.1.27 RC H2): the main window in the Simple layout; after a
  1303. // demo opened from Welcome › Start from and after clicks in the dock, its tabs, the Lyrics button, a track
  1304. // header and the grid, Space must start playback (a text field clicked into keeps its typing keys). Shows a
  1305. // window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  1306. runSimpleKeyTest (args[args.indexOf ("--simplekeytest") + 1].unquoted());
  1307. return;
  1308. }
  1309. if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
  1310. {
  1311. const auto i = args.indexOf ("--pluginstyle");
  1312. if (i + 1 < args.size())
  1313. {
  1314. const auto name = args[i + 1].unquoted();
  1315. lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
  1316. }
  1317. }
  1318. if (args.contains ("--gfxprobe"))
  1319. {
  1320. // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
  1321. // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
  1322. // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
  1323. // "no clip" and flooded the whole component (Facet EQ's blank pink window).
  1324. const auto i = args.indexOf ("--gfxprobe");
  1325. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
  1326. quit();
  1327. return;
  1328. }
  1329. if (args.contains ("--steppertest"))
  1330. {
  1331. // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
  1332. // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
  1333. const auto i = args.indexOf ("--steppertest");
  1334. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1335. juce::String report;
  1336. int fails = 0, count = 0, skips = 0;
  1337. {
  1338. lynx::AudioEngine offline (false);
  1339. auto kinds = lynx::plugui::flLayoutKinds();
  1340. for (const auto own : lynx::plugui::ownLayoutKinds())
  1341. kinds.push_back (own);
  1342. // FL's Default preset when the installation has one (the state-backed controls need FL's state)
  1343. const auto roots = lynx::findFlStudioRoots();
  1344. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  1345. for (const auto kind : kinds)
  1346. {
  1347. auto fx = lynx::makeEffectSlot (kind);
  1348. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1349. {
  1350. juce::MemoryBlock data;
  1351. const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
  1352. if (file.existsAsFile() && file.loadFileAsData (data))
  1353. {
  1354. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  1355. 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)
  1356. fx = *loaded;
  1357. }
  1358. break;
  1359. }
  1360. lynx::Song song;
  1361. song.mixer.resize (2);
  1362. song.mixer[0].name = "Master";
  1363. song.mixer[1].name = "Insert 1";
  1364. song.mixer[1].effects.push_back (fx);
  1365. offline.setSong (std::move (song));
  1366. offline.dispatchPendingMessages();
  1367. const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
  1368. for (const auto& line : juce::StringArray::fromLines (lines))
  1369. if (line.isNotEmpty())
  1370. {
  1371. ++count;
  1372. fails += line.contains (": FAIL") ? 1 : 0;
  1373. skips += line.contains (": SKIP") ? 1 : 0;
  1374. }
  1375. report << lines;
  1376. juce::PopupMenu::dismissAllActiveMenus();
  1377. offline.dispatchPendingMessages();
  1378. }
  1379. }
  1380. report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
  1381. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1382. quit();
  1383. return;
  1384. }
  1385. if (args.contains ("--plugui"))
  1386. {
  1387. // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
  1388. // loaded with the FL plugin's Default preset when the FL installation has one
  1389. const auto i = args.indexOf ("--plugui");
  1390. runPluginEditorSnapshots (args[i + 1].unquoted());
  1391. return;
  1392. }
  1393. if (args.contains ("--parityshot"))
  1394. {
  1395. // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
  1396. // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
  1397. // of the third-party parity pictures (round tp172b)
  1398. const auto i = args.indexOf ("--parityshot");
  1399. runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1400. if (parityShotFailed)
  1401. setApplicationReturnValue (2);
  1402. if (parityShow == nullptr)
  1403. quit();
  1404. return;
  1405. }
  1406. if (args.contains ("--design168rshot"))
  1407. {
  1408. // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
  1409. // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
  1410. // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
  1411. const auto i = args.indexOf ("--design168rshot");
  1412. if (i + 2 < args.size() && args[i + 2] == "generated")
  1413. lynx::plugui::showGeneratedLayoutsOnly (true);
  1414. runDesign168rShots (args[i + 1].unquoted());
  1415. quit();
  1416. return;
  1417. }
  1418. if (args.contains ("--eq166fshot"))
  1419. {
  1420. // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
  1421. // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
  1422. // its spectrum over the source's), each fed by the demo song rendered offline
  1423. const auto i = args.indexOf ("--eq166fshot");
  1424. runEq166fShots (args[i + 1].unquoted());
  1425. quit();
  1426. return;
  1427. }
  1428. if (args.contains ("--editorcpu"))
  1429. {
  1430. // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
  1431. // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
  1432. // animates (demo signal) — round 122's check that an idle editor burns no CPU
  1433. const auto i = args.indexOf ("--editorcpu");
  1434. runEditorCpu (args[i + 1].unquoted());
  1435. return;
  1436. }
  1437. if (args.contains ("--precomputeshot"))
  1438. {
  1439. // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
  1440. // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
  1441. const auto i = args.indexOf ("--precomputeshot");
  1442. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1443. lynx::AudioEngine shotEngine (false);
  1444. const juce::File input (args[i + 1].unquoted());
  1445. const auto prefix = args[i + 2].unquoted();
  1446. juce::String error;
  1447. bool ok = false;
  1448. if (input.hasFileExtension ("flp"))
  1449. ok = shotEngine.importFlpFile (input, error);
  1450. else if (auto song = lynx::ProjectFile::load (input, error))
  1451. shotEngine.setSong (std::move (*song)), ok = true;
  1452. shotEngine.dispatchPendingMessages();
  1453. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  1454. if (c == nullptr)
  1455. return false;
  1456. if (c->getWidth() <= 0)
  1457. c->setSize (520, 600);
  1458. savePng (lynx::shot::snapshot (*c), prefix + name);
  1459. return true;
  1460. };
  1461. ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
  1462. ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
  1463. setApplicationReturnValue (ok ? 0 : 1);
  1464. quit();
  1465. return;
  1466. }
  1467. if (args.contains ("--pluginthumbs"))
  1468. {
  1469. // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
  1470. // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
  1471. // the background when pictures are missing. One line per plugin on stdout.
  1472. const auto i = args.indexOf ("--pluginthumbs");
  1473. lynx::crashguard::quietCrashReports();
  1474. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1475. juce::StringArray only;
  1476. if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
  1477. only.addTokens (args[i + 2].unquoted(), ",", "");
  1478. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1479. // round 190bi: with --shot-scale / LYNX_SHOT_SCALE each plugin's whole editor at that scale, not the picker's
  1480. // small thumbnail (never for the picker's own cache folder, whatever the environment says)
  1481. const juce::File folder (args[i + 1].unquoted());
  1482. const auto full = lynx::shot::given() && folder != lynx::pluginthumbs::nativeFolder() ? lynx::shot::scale() : 0.0f;
  1483. const auto drawn = lynx::pluginthumbs::renderNative (folder, only, [] (const juce::String& line) {
  1484. std::printf ("%s\n", line.toRawUTF8());
  1485. std::fflush (stdout);
  1486. }, full);
  1487. std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
  1488. setApplicationReturnValue (0);
  1489. quit();
  1490. return;
  1491. }
  1492. if (args.contains ("--jsonroundtrip"))
  1493. {
  1494. // LYNX.exe --jsonroundtrip <folder>: round 183c's finding — a project saved, loaded and saved again: both texts
  1495. // (a.json, b.json) and the first lines that differ (diff.txt) for the default song, with and without a Patcher
  1496. const auto i = args.indexOf ("--jsonroundtrip");
  1497. const juce::File out (args[i + 1].unquoted());
  1498. out.createDirectory();
  1499. juce::String report;
  1500. auto check = [&] (const lynx::Song& song, const juce::String& name) {
  1501. const auto a = lynx::ProjectFile::toJson (song);
  1502. juce::String error;
  1503. const auto back = lynx::ProjectFile::fromJson (a, error);
  1504. const auto b = back ? lynx::ProjectFile::toJson (*back) : juce::String ("(not loaded: " + error + ")");
  1505. out.getChildFile (name + "-a.json").replaceWithText (a);
  1506. out.getChildFile (name + "-b.json").replaceWithText (b);
  1507. juce::StringArray la, lb;
  1508. la.addLines (a);
  1509. lb.addLines (b);
  1510. report << name << ": " << (a == b ? "stable" : "DIFFERS") << " (" << la.size() << " / " << lb.size() << " lines)\n";
  1511. int shown = 0;
  1512. for (int k = 0; k < juce::jmax (la.size(), lb.size()) && shown < 12; ++k)
  1513. if (la[k] != lb[k])
  1514. {
  1515. report << " line " << (k + 1) << "\n a: " << la[k].trim().substring (0, 200) << "\n b: " << lb[k].trim().substring (0, 200) << "\n";
  1516. ++shown;
  1517. }
  1518. };
  1519. auto song = lynx::Song::makeDefault();
  1520. check (song, "default");
  1521. song.mixer.resize (3);
  1522. song.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::patcher) };
  1523. check (song, "patcher");
  1524. song.mixer[1].effects = { lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect) };
  1525. check (song, "rack");
  1526. out.getChildFile ("diff.txt").replaceWithText (report);
  1527. setApplicationReturnValue (0);
  1528. quit();
  1529. return;
  1530. }
  1531. if (args.contains ("--rackshot"))
  1532. {
  1533. // LYNX.exe --rackshot <folder>: round 183c's Rack view drawn off-screen (no window), for the LYNX | Live pairs:
  1534. // rack-deviceview.png (an Audio Effect Rack laid out as in Live's reference shot), rack-mapmode.png (Map mode
  1535. // with the mapping list), rack-instrument.png (an Instrument Rack with its key zones)
  1536. const auto i = args.indexOf ("--rackshot");
  1537. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1538. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1539. setApplicationReturnValue (runRackShots (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
  1540. quit();
  1541. return;
  1542. }
  1543. if (args.contains ("--artshot"))
  1544. {
  1545. // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
  1546. // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
  1547. // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
  1548. const auto i = args.indexOf ("--artshot");
  1549. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1550. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1551. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1552. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1553. setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
  1554. quit();
  1555. return;
  1556. }
  1557. if (args.contains ("--artgui"))
  1558. {
  1559. // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
  1560. // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
  1561. // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
  1562. // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
  1563. const auto i = args.indexOf ("--artgui");
  1564. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1565. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1566. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1567. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1568. runArtGui (juce::File (args[i + 1].unquoted()), mode);
  1569. return;
  1570. }
  1571. if (args.contains ("--instrumentshot"))
  1572. {
  1573. // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
  1574. // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
  1575. // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
  1576. const auto i = args.indexOf ("--instrumentshot");
  1577. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1578. const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
  1579. setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
  1580. quit();
  1581. return;
  1582. }
  1583. if (args.contains ("--flextrashot"))
  1584. {
  1585. // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
  1586. const auto i = args.indexOf ("--flextrashot");
  1587. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1588. lynx::AudioEngine shotEngine (false);
  1589. const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
  1590. setApplicationReturnValue (ok ? 0 : 1);
  1591. quit();
  1592. return;
  1593. }
  1594. if (args.contains ("--visualtest"))
  1595. {
  1596. // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
  1597. // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
  1598. // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
  1599. const auto i = args.indexOf ("--visualtest");
  1600. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1601. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
  1602. lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
  1603. setApplicationReturnValue (ok ? 0 : 1);
  1604. quit();
  1605. });
  1606. return;
  1607. }
  1608. if (args.contains ("--menu-entry"))
  1609. {
  1610. // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
  1611. // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
  1612. const auto i = args.indexOf ("--menu-entry");
  1613. const auto on = args[i + 1].unquoted() != "off";
  1614. const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
  1615. std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
  1616. : "only the LYNX SHARE AppImage on Linux can do this");
  1617. setApplicationReturnValue (ok ? 0 : 1);
  1618. quit();
  1619. return;
  1620. }
  1621. if (args.contains ("--send-test-report"))
  1622. {
  1623. // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
  1624. // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
  1625. // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
  1626. const auto i = args.indexOf ("--send-test-report");
  1627. const juce::File out (args[i + 1].unquoted());
  1628. lynx::crashreporter::Session session;
  1629. session.version = getApplicationVersion();
  1630. for (const auto* pattern : { "crash *.txt", "hang *.txt" })
  1631. {
  1632. auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
  1633. lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
  1634. if (! files.isEmpty())
  1635. (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
  1636. }
  1637. session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
  1638. auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
  1639. input.test = true;
  1640. const auto json = lynx::crashreporter::buildJson (input, false);
  1641. out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
  1642. const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
  1643. out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
  1644. + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
  1645. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  1646. quit();
  1647. return;
  1648. }
  1649. if (args.contains ("--symbolize"))
  1650. {
  1651. // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
  1652. // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
  1653. const auto i = args.indexOf ("--symbolize");
  1654. const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
  1655. juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
  1656. quit();
  1657. return;
  1658. }
  1659. if (args.contains ("--opentest"))
  1660. {
  1661. // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
  1662. // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
  1663. // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
  1664. const auto i = args.indexOf ("--opentest");
  1665. runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
  1666. setApplicationReturnValue (ok ? 0 : 1);
  1667. quit();
  1668. });
  1669. return;
  1670. }
  1671. if (args.contains ("--fxfuzz"))
  1672. {
  1673. // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
  1674. // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
  1675. const auto i = args.indexOf ("--fxfuzz");
  1676. const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
  1677. // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
  1678. const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
  1679. setApplicationReturnValue (ok ? 0 : 1);
  1680. quit();
  1681. return;
  1682. }
  1683. if (args.contains ("--controllershot"))
  1684. {
  1685. // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
  1686. const auto i = args.indexOf ("--controllershot");
  1687. runControllerShot (args[i + 1].unquoted());
  1688. quit();
  1689. return;
  1690. }
  1691. if (args.contains ("--edisonshot"))
  1692. {
  1693. // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
  1694. // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
  1695. const auto i = args.indexOf ("--edisonshot");
  1696. runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1697. quit();
  1698. return;
  1699. }
  1700. if (args.contains ("--edisonslottest"))
  1701. {
  1702. // LYNX.exe --edisonslottest folder [project.flp]: round 190cd — the audio editor as a mixer-slot plugin through
  1703. // the engine and the project file (report.txt: one "name=ok|FAIL" per check), its window as slot-*.png, and
  1704. // the Edison slots of an FL project (what was read of each)
  1705. const auto i = args.indexOf ("--edisonslottest");
  1706. const auto ok = runEdisonSlotTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1707. setApplicationReturnValue (ok ? 0 : 1);
  1708. quit();
  1709. return;
  1710. }
  1711. if (args.contains ("--danceshot"))
  1712. {
  1713. // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
  1714. // and a demo project with two dance channels (for --snapshot)
  1715. const auto i = args.indexOf ("--danceshot");
  1716. runDanceShot (args[i + 1].unquoted());
  1717. quit();
  1718. return;
  1719. }
  1720. if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
  1721. {
  1722. // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
  1723. // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
  1724. const auto i = args.indexOf ("--videoshot");
  1725. runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1726. return;
  1727. }
  1728. if (args.contains ("--videotrackshot") && args.indexOf ("--videotrackshot") + 2 < args.size())
  1729. {
  1730. // LYNX.exe --videotrackshot prefix video [video2]: round 174d — the Playlist with video tracks (filmstrips,
  1731. // timecode row) and the video window at a few song positions, as PNGs + report.txt (the decoder, the
  1732. // frame shown for each wanted time: frame accuracy, frames dropped)
  1733. const auto i = args.indexOf ("--videotrackshot");
  1734. runVideoTrackShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1735. return;
  1736. }
  1737. if (args.contains ("--vfxshot"))
  1738. {
  1739. // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
  1740. const auto i = args.indexOf ("--vfxshot");
  1741. runVfxShot (args[i + 1].unquoted());
  1742. quit();
  1743. return;
  1744. }
  1745. if (args.contains ("--patchershot"))
  1746. {
  1747. // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
  1748. const auto i = args.indexOf ("--patchershot");
  1749. runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1750. quit();
  1751. return;
  1752. }
  1753. if (args.contains ("--audioxshot"))
  1754. {
  1755. // LYNX.exe --audioxshot prefix (round 190aq): the pre-fader send, the "Low latency while recording" mark on a
  1756. // bypassed slot and the Browser's "Preview in time", drawn off-screen
  1757. runAudioXShot (args[args.indexOf ("--audioxshot") + 1].unquoted());
  1758. quit();
  1759. return;
  1760. }
  1761. if (args.contains ("--comp177shot"))
  1762. {
  1763. // LYNX.exe --comp177shot prefix project (round 177c): a project of loop takes in the maximised
  1764. // Playlist as it opened; every group after "Comp these takes", with a swipe on the first; the track and record menus
  1765. const auto i = args.indexOf ("--comp177shot");
  1766. runComp177Shot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1767. quit();
  1768. return;
  1769. }
  1770. if (args.contains ("--feat166shot"))
  1771. {
  1772. // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
  1773. // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
  1774. // its end, and the time a full repaint takes)
  1775. const auto i = args.indexOf ("--feat166shot");
  1776. runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1777. quit();
  1778. return;
  1779. }
  1780. if (args.contains ("--trackmodeshot"))
  1781. {
  1782. // LYNX --trackmodeshot prefix: rollup 190cv (UI gate of PR #151) — Playlist track header › Track mode › Audio
  1783. // track, off-screen, in three states of FL's live check 190cu (q1-01 fresh, q1-02 one insert linked
  1784. // elsewhere and one renamed, q1-07 the full state), plus a report that compares each list with FL's
  1785. setApplicationReturnValue (runTrackModeShot (args[args.indexOf ("--trackmodeshot") + 1].unquoted()) ? 0 : 1);
  1786. quit();
  1787. return;
  1788. }
  1789. if (args.contains ("--curveshot"))
  1790. {
  1791. // LYNX.exe --curveshot prefix: round 190bw — an automation clip with one segment per FL curve mode in the
  1792. // point editor and in the Playlist, and FL's point menu, off-screen
  1793. runCurveShot (args[args.indexOf ("--curveshot") + 1].unquoted());
  1794. quit();
  1795. return;
  1796. }
  1797. if (args.contains ("--remoteshot"))
  1798. {
  1799. // LYNX.exe --remoteshot prefix: Online Sessions P5-A1 (round 190ai) — the host's "Share plugins with guests"
  1800. // list and a guest's parameter editor of a plugin the host plays, off-screen with sample data
  1801. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1802. lynx::liveui::saveRemoteShots (args[args.indexOf ("--remoteshot") + 1].unquoted());
  1803. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  1804. quit();
  1805. return;
  1806. }
  1807. if (args.contains ("--settingsshot") && ! args.contains ("--rtstress")) // (--rtstress has its own --settingsshot file.png option, round 161)
  1808. {
  1809. // LYNX.exe --settingsshot prefix: round 190bx — every Settings page off-screen at the window's size, in a
  1810. // small window (390 x 390) and, for the long pages, whole (see runSettingsShot)
  1811. runSettingsShot (args[args.indexOf ("--settingsshot") + 1].unquoted());
  1812. quit();
  1813. return;
  1814. }
  1815. if (args.contains ("--perfshot"))
  1816. {
  1817. // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
  1818. // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
  1819. // for --patchershot (round 165m)
  1820. const auto i = args.indexOf ("--perfshot");
  1821. runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1822. quit();
  1823. return;
  1824. }
  1825. if (args.contains ("--freezetest"))
  1826. {
  1827. // LYNX.exe --freezetest prefix [project]: round 190ay's Freeze end to end, off-screen (see runFreezeTest)
  1828. const auto i = args.indexOf ("--freezetest");
  1829. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1830. // a word after the project: "keep" = freeze, save prefix-frozen.lynx and stop (the audio stays);
  1831. // "measure" = only load and render the project, for the memory and time of a process of its own
  1832. const auto mode = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1833. setApplicationReturnValue (runFreezeTest (args[i + 1].unquoted(), project, mode) ? 0 : 1);
  1834. quit();
  1835. return;
  1836. }
  1837. if (args.contains ("--trackfreezetest"))
  1838. {
  1839. // LYNX --trackfreezetest prefix: round 190ff's Freeze Track, Flatten / Bounce Track in Place, Bounce to New
  1840. // Track and Consolidate end to end in the Clip-launch workflow, off-screen (see runTrackFreezeTest)
  1841. const auto i = args.indexOf ("--trackfreezetest");
  1842. setApplicationReturnValue (runTrackFreezeTest (args[i + 1].unquoted()) ? 0 : 1);
  1843. quit();
  1844. return;
  1845. }
  1846. if (args.contains ("--gridshot"))
  1847. {
  1848. // LYNX.exe --gridshot prefix [project]: the Clip-launch workflow's layout off-screen, with a grid of sample
  1849. // clips, some playing and waiting, at the size of LYNX_SNAPSHOT_SIZE (round 181a); with a project (.lynx,
  1850. // .flp, .als), that project's grid instead (round 181c: a Live set's Session view as LYNX imports it)
  1851. const auto i = args.indexOf ("--gridshot");
  1852. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1853. runGridShot (args[i + 1].unquoted(), project);
  1854. quit();
  1855. return;
  1856. }
  1857. if (args.contains ("--tour190dvshot"))
  1858. {
  1859. // LYNX.exe --tour190dvshot prefix: round 190dv off-screen — the Simple workflow's Welcome screen, every step of
  1860. // the first-song tour done with its "Do it for me" (a loop dropped for the loop step), the end card, Back /
  1861. // Next / close, the Help menu, the chooser's tour button, Start from with the three demo songs, a demo
  1862. // opened in Simple — and a text report of the checks (incl. resources/demos/*.lynx = the generated songs)
  1863. const auto i = args.indexOf ("--tour190dvshot");
  1864. runTour190dvShot (args[i + 1].unquoted());
  1865. quit();
  1866. return;
  1867. }
  1868. if (args.contains ("--simpleclosetest"))
  1869. {
  1870. // LYNX --simpleclosetest <report.txt>: round 190fc off-screen (no window) — the main window in the Simple
  1871. // layout with Welcome, the tour, Start from, a demo, the dock's tabs, Finish and Lyrics open, then closed as at
  1872. // shutdown (the 0.1.27 RC crashed on every such close); exit code 0 = OK
  1873. const auto i = args.indexOf ("--simpleclosetest");
  1874. setApplicationReturnValue (runSimpleCloseTest (args[i + 1].unquoted()) ? 0 : 1);
  1875. quit();
  1876. return;
  1877. }
  1878. if (args.contains ("--patterns190ea"))
  1879. {
  1880. // LYNX --patterns190ea <report.txt>: round 190ea off-screen (no window) — a song with no pattern at all
  1881. // reaching the engine in every layout (the Simple dock's Editor tab, the Piano roll panel of the Pattern
  1882. // layout, the Clip-launch layout), the last pattern deleted, all patterns cleared by an edit, undo / redo,
  1883. // a live session's remote song and an out-of-range current pattern; each must leave one pattern and not crash
  1884. const auto i = args.indexOf ("--patterns190ea");
  1885. setApplicationReturnValue (runPatterns190ea (args[i + 1].unquoted()) ? 0 : 1);
  1886. quit();
  1887. return;
  1888. }
  1889. if (args.contains ("--simple190dsshot"))
  1890. {
  1891. // LYNX.exe --simple190dsshot prefix: round 190ds off-screen, at 1x and 2x — loops dropped in the Simple
  1892. // workflow following the project key (the dock's switch, the clip menu), the docked Piano roll in the Editor
  1893. // tab, the keyboard's modes Keys / Scale keys / Chord pad with the scale selector — and a text report
  1894. const auto i = args.indexOf ("--simple190dsshot");
  1895. runSimple190dsShot (args[i + 1].unquoted());
  1896. quit();
  1897. return;
  1898. }
  1899. if (args.contains ("--simple190dgshot"))
  1900. {
  1901. // LYNX.exe --simple190dgshot prefix: round 190dg's additions to the Simple dock off-screen, at 1x and 2x —
  1902. // the Effects tab with all eight one-knob cards and each card alone, a chain preset with Blend, the
  1903. // favourites in the Preset menu, the sound picker (a search, My plugins with a made-up plugin list) — and a
  1904. // text report of the checks
  1905. const auto i = args.indexOf ("--simple190dgshot");
  1906. runSimple190dgShot (args[i + 1].unquoted());
  1907. quit();
  1908. return;
  1909. }
  1910. if (args.contains ("--simplefxshot"))
  1911. {
  1912. // LYNX.exe --simplefxshot prefix: round 190bu's track dock of the Simple workflow off-screen, at 1x and 2x —
  1913. // the Instrument tab (LYNX sounds, My SoundFonts), the Effects tab (empty, a preset, its menus), and a text
  1914. // report: the dock's edits, a user preset saved and loaded, the same slots in the Pattern workflow's Mixer
  1915. const auto i = args.indexOf ("--simplefxshot");
  1916. runSimpleFxShot (args[i + 1].unquoted());
  1917. quit();
  1918. return;
  1919. }
  1920. if (args.contains ("--simpleshot"))
  1921. {
  1922. // LYNX.exe --simpleshot prefix: round 184a's Simple workflow off-screen — View › Layout style with each style
  1923. // chosen, Settings › General (Pattern, then Simple selected) with its style list, the window in Pattern, then
  1924. // Simple, then Pattern again, and how many Simple workflow objects existed before and after (0 before)
  1925. const auto i = args.indexOf ("--simpleshot");
  1926. runSimpleShot (args[i + 1].unquoted());
  1927. quit();
  1928. return;
  1929. }
  1930. // --versionsshot <prefix> (round 190ap): the Versions panel, File's new items, a project opened without its
  1931. // third-party plugins (window, list, File menu) and the Export window's additions, offscreen
  1932. if (args.contains ("--versionsshot"))
  1933. {
  1934. runVersionsShot (args[args.indexOf ("--versionsshot") + 1].unquoted());
  1935. quit();
  1936. return;
  1937. }
  1938. // --linkshot <prefix> (round 190bt): FL's Remote control settings / Global link settings windows, the control
  1939. // menu with "Link to controller...", the formula presets and controller menus and the Multilink items,
  1940. // offscreen; prefix-checks.txt holds the round's checks of the engine, the project file and the settings
  1941. if (args.contains ("--linkshot"))
  1942. {
  1943. setApplicationReturnValue (runLinkShot (args[args.indexOf ("--linkshot") + 1].unquoted()) ? 0 : 1);
  1944. quit();
  1945. return;
  1946. }
  1947. // --flctlshot <prefix> (round 190df): FL's multilink menu (on / off), the plugin menu's A/B and "Link all
  1948. // parameters...", the sampler's File row with its Sample history, and the Envelope / instrument page of a sampler
  1949. // running FL's voice with its envelope presets, offscreen; prefix-checks.txt holds the checks
  1950. if (args.contains ("--flctlshot"))
  1951. {
  1952. setApplicationReturnValue (runFlCtlShot (args[args.indexOf ("--flctlshot") + 1].unquoted()) ? 0 : 1);
  1953. quit();
  1954. return;
  1955. }
  1956. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen (shots and checks in prefix-checks.txt)
  1957. if (args.contains ("--samplerpageshot"))
  1958. {
  1959. setApplicationReturnValue (runSamplerPageShot (args[args.indexOf ("--samplerpageshot") + 1].unquoted()) ? 0 : 1);
  1960. quit();
  1961. return;
  1962. }
  1963. // --flplshot <prefix> (round 190dx): the audio clip menu (Preview, Automate › Panning / Volume), the Playlist's "+"
  1964. // and its menu, Track mode › Instrument track, the Channel rack's "Assign to new instrument track", Tools › One-click
  1965. // audio recording and Mixer › Disk recording › Latency compensation, offscreen; prefix-checks.txt holds the checks
  1966. if (args.contains ("--flplshot"))
  1967. {
  1968. setApplicationReturnValue (runFlPlShot (args[args.indexOf ("--flplshot") + 1].unquoted()) ? 0 : 1);
  1969. quit();
  1970. return;
  1971. }
  1972. // --flfixshot <prefix> (round 190ey): what the live FL session 190ew found different (the Sampler page, the
  1973. // Multilink menu, the Playlist, issue #152's question), offscreen; prefix-checks.txt holds the checks
  1974. if (args.contains ("--flfixshot"))
  1975. {
  1976. setApplicationReturnValue (runFlFixShot (args[args.indexOf ("--flfixshot") + 1].unquoted()) ? 0 : 1);
  1977. quit();
  1978. return;
  1979. }
  1980. // --flclipshot <prefix> (round 190dz): FL's audio clip menu layout (two columns, FL's sections, LYNX's own items at
  1981. // the end) and the channel's Misc › Levels adjustment, offscreen; prefix-checks.txt holds the checks
  1982. if (args.contains ("--flclipshot"))
  1983. {
  1984. setApplicationReturnValue (runFlClipShot (args[args.indexOf ("--flclipshot") + 1].unquoted()) ? 0 : 1);
  1985. quit();
  1986. return;
  1987. }
  1988. if (args.contains ("--warpshot"))
  1989. {
  1990. // LYNX.exe --warpshot prefix: round 190cg's pictures (warp commands in the audio editor, the Clip page's
  1991. // Audio panel, the arrangement with the loop switched off, a folded track, signature changes), off-screen
  1992. const auto i = args.indexOf ("--warpshot");
  1993. runWarpShot (args[i + 1].unquoted());
  1994. quit();
  1995. return;
  1996. }
  1997. // --bandlabshot <prefix> (round 190ch): Lyrics / Notes, Reference match, Start from and Clean voice, offscreen
  1998. if (args.contains ("--bandlabshot"))
  1999. {
  2000. runBandlabShot (args[args.indexOf ("--bandlabshot") + 1].unquoted());
  2001. quit();
  2002. return;
  2003. }
  2004. if (args.contains ("--detailshot"))
  2005. {
  2006. // LYNX.exe --detailshot prefix: the Clip-launch workflow's detail view off-screen (round 183a): a track's chain
  2007. // (instrument, effects, one off, one folded), its clip page, and Pattern workflow before / after, at
  2008. // LYNX_SNAPSHOT_SIZE. Writes prefix-counts.txt with what the chain shows.
  2009. const auto i = args.indexOf ("--detailshot");
  2010. runDetailShot (args[i + 1].unquoted());
  2011. quit();
  2012. return;
  2013. }
  2014. if (args.contains ("--liveshot190ce"))
  2015. {
  2016. // LYNX.exe --liveshot190ce prefix: round 190ce off-screen, in the Ableton-style layout: the Device View's cards
  2017. // with their hot-swap and save buttons, a device's menu, hot-swap on (the Browser's bar, the lit button), a
  2018. // swap and its undo, a duplicate, and the Browser's collections (STARRED tab, the Collections menu, a search
  2019. // by a collection's name). Writes prefix-checks.txt.
  2020. runLiveShot190ce (args[args.indexOf ("--liveshot190ce") + 1].unquoted());
  2021. quit();
  2022. return;
  2023. }
  2024. if (args.contains ("--missingsearchshot190eo"))
  2025. {
  2026. // LYNX --missingsearchshot190eo prefix folder...: round 190eo (integration of issue #159's fix) off-screen: the
  2027. // Missing files window's Samples page while a real search of the folders runs (matches streamed in, Stop
  2028. // shown, Apply usable). Writes prefix-searching.png and prefix-checks.txt; the search is let go at the end.
  2029. const auto i = args.indexOf ("--missingsearchshot190eo");
  2030. const auto prefix = args[i + 1].unquoted();
  2031. juce::StringArray folders;
  2032. for (int k = i + 2; k < args.size(); ++k)
  2033. folders.add (args[k].unquoted());
  2034. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2035. std::shared_ptr<juce::Component> panel = lynx::makeMissingFilesPanelSearching (lynx::missingFilesSnapshotInfo(), folders);
  2036. juce::Timer::callAfterDelay (700, [this, panel, prefix] {
  2037. juce::String status;
  2038. bool stopShown = false, applyEnabled = false;
  2039. const auto searching = lynx::missingFilesSearchState (*panel, status, stopShown, applyEnabled);
  2040. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  2041. const auto file = juce::File (prefix + "-searching.png");
  2042. file.deleteFile();
  2043. if (auto out = file.createOutputStream())
  2044. juce::PNGImageFormat().writeImageToStream (image, *out);
  2045. juce::String checks;
  2046. auto check = [&checks] (const char* name, bool ok, const juce::String& detail) {
  2047. checks << name << "=" << (ok ? "OK" : "FAIL") << " " << detail << "\n";
  2048. };
  2049. check ("still_searching_at_the_shot", searching, {});
  2050. check ("status_shows_the_walk", status.contains (lynx::tr ("Searching {0}... {1} files looked at").upToFirstOccurrenceOf ("{0}", false, false)), status);
  2051. check ("stop_shown", stopShown, {});
  2052. check ("apply_usable_during_the_search", applyEnabled, {});
  2053. lynx::stopMissingFilesSearch (*panel);
  2054. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  2055. quit();
  2056. });
  2057. return;
  2058. }
  2059. if (args.contains ("--drumshot190ec"))
  2060. {
  2061. // LYNX.exe --drumshot190ec prefix: round 190ec off-screen: a demo Drum Rack's pad view (default and scrolled), its
  2062. // chain list with I-O, sends and return chains, a new empty Drum Rack and the Piano roll's pad names. Writes
  2063. // prefix-checks.txt (hit tests: C1 bottom-left, overview scroll, a pad dragged onto another swaps them).
  2064. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2065. lynx::drumshot::run (args[args.indexOf ("--drumshot190ec") + 1].unquoted());
  2066. quit();
  2067. return;
  2068. }
  2069. if (args.contains ("--mapshot190ef"))
  2070. {
  2071. // LYNX.exe --mapshot190ef prefix: round 190ef's map modes off-screen, in the Clip-launch workflow: MIDI Map Mode
  2072. // (the overlay over the grid, the Session mixer, the Device View and the transport; the Mapping Browser with
  2073. // Min / Max), Key Map Mode, the row menu, the title bar's Draw / Key / MIDI switches, Ctrl+M / Ctrl+K and the
  2074. // Pattern layout keeping Ctrl+M. Writes prefix-checks.txt.
  2075. runMapShot190ef (args[args.indexOf ("--mapshot190ef") + 1].unquoted());
  2076. quit();
  2077. return;
  2078. }
  2079. if (args.contains ("--sceneshot190ef"))
  2080. {
  2081. // LYNX.exe --sceneshot190ef prefix: round 190ef's scene work off-screen, in the Clip-launch workflow: the scene
  2082. // column with its tempo / time signature fields, the scene menu, a scene field's menu, the column title's menu
  2083. // (Rename, colours), a duplicated scene and a captured scene. Writes prefix-checks.txt.
  2084. runSceneShot190ef (args[args.indexOf ("--sceneshot190ef") + 1].unquoted());
  2085. quit();
  2086. return;
  2087. }
  2088. if (args.contains ("--drawshot190ef"))
  2089. {
  2090. // LYNX.exe --drawshot190ef prefix: round 190ef off-screen, in the Clip-launch workflow: Draw Mode in an
  2091. // automation lane, steps at the grid width and an Alt (no grid) freehand stroke drawn through the Playlist's
  2092. // own mouse handlers, and the Options menu with "Draw Mode". Writes prefix-checks.txt.
  2093. runDrawShot190ef (args[args.indexOf ("--drawshot190ef") + 1].unquoted());
  2094. quit();
  2095. return;
  2096. }
  2097. if (args.contains ("--liveshot190dr"))
  2098. {
  2099. // LYNX.exe --liveshot190dr prefix: round 190dr off-screen, in the Clip-launch workflow: the Session mixer
  2100. // under the clip grid (default sections, Track Options, Volume only, hidden, its View menu), the Clip page's
  2101. // Sample panel of an audio clip (Warp on / off, the Set buttons while it plays, the sample's title) and a
  2102. // device dragged from one track's Device View to another track. Writes prefix-checks.txt.
  2103. runLiveShot190dr (args[args.indexOf ("--liveshot190dr") + 1].unquoted());
  2104. quit();
  2105. return;
  2106. }
  2107. if (args.contains ("--typeaheadtest"))
  2108. {
  2109. // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
  2110. // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
  2111. const auto i = args.indexOf ("--typeaheadtest");
  2112. runTypeAheadTest (juce::File (args[i + 1].unquoted()));
  2113. return;
  2114. }
  2115. if (args.contains ("--choosertest"))
  2116. {
  2117. // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
  2118. // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
  2119. // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
  2120. const auto i = args.indexOf ("--choosertest");
  2121. runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  2122. return;
  2123. }
  2124. if (args.contains ("--snapshot"))
  2125. {
  2126. const auto i = args.indexOf ("--snapshot");
  2127. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2128. return;
  2129. }
  2130. if (args.contains ("--stemsplit"))
  2131. {
  2132. // LYNX.exe --stemsplit input.wav folder: the stem separation of the clip menu, without the window
  2133. const auto i = args.indexOf ("--stemsplit");
  2134. lynx::AudioEngine loader (false);
  2135. const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  2136. juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  2137. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  2138. quit();
  2139. return;
  2140. }
  2141. if (args.contains ("--audio2midi"))
  2142. {
  2143. // LYNX.exe --audio2midi input.wav melody|harmony|drums notes.csv: the clip menu's Convert to MIDI, without the
  2144. // window (round a2m189b's measurements)
  2145. const auto i = args.indexOf ("--audio2midi");
  2146. const auto mode = args[i + 2] == "drums" ? lynx::a2m::Mode::drums : args[i + 2] == "harmony" ? lynx::a2m::Mode::harmony : lynx::a2m::Mode::melody;
  2147. lynx::AudioEngine loader (false);
  2148. const juce::File csv (args[i + 3].unquoted());
  2149. const auto error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), mode, csv);
  2150. csv.getSiblingFile ("audio2midi.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  2151. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  2152. quit();
  2153. return;
  2154. }
  2155. if (args.contains ("--stems"))
  2156. {
  2157. // LYNX.exe --stems project.(flp|als|lynx) base.wav: one WAV per insert that has sound (like "Export stems")
  2158. const auto i = args.indexOf ("--stems");
  2159. juce::String error, report;
  2160. int written = 0;
  2161. {
  2162. lynx::AudioEngine loader (false);
  2163. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  2164. // an .flp or a Live set (.als) opens through the import, as File › Open does (round 182b)
  2165. auto ok = input.hasFileExtension ("flp;als") ? loader.importFlpFile (input, error) : false;
  2166. if (! input.hasFileExtension ("flp;als"))
  2167. if (auto song = lynx::ProjectFile::load (input, error))
  2168. {
  2169. loader.setSong (std::move (*song));
  2170. ok = true;
  2171. }
  2172. const auto& song = loader.getSong();
  2173. for (int t = 1; ok && t < (int) song.mixer.size(); ++t)
  2174. {
  2175. if (std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  2176. continue;
  2177. const auto file = base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav");
  2178. lynx::ExportSettings settings;
  2179. lynx::ExportJob job (lynx::makeBounceSong (song, t), settings, file);
  2180. if (job.run ({}, error))
  2181. {
  2182. ++written;
  2183. report << file.getFileName() << " peak=" << job.getPeak() << "\n";
  2184. }
  2185. }
  2186. }
  2187. report << "stems=" << written << "\n";
  2188. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  2189. setApplicationReturnValue (written > 0 ? 0 : 1);
  2190. quit();
  2191. return;
  2192. }
  2193. // --export-als <in.lynx|.flp|.als> <folder> [--live11] [--reference] [--scan]: "<folder>/<name> Project/<name>.als" (round 175a)
  2194. if (args.contains ("--export-als"))
  2195. {
  2196. const auto i = args.indexOf ("--export-als");
  2197. runAlsExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--live11"), args.contains ("--reference"));
  2198. return;
  2199. }
  2200. // --gamepadshot <prefix> (round 184a, S16): the game controller's hints overlay and the MIDI settings page with
  2201. // the option on, offscreen, plus the poller fed fake pad states ("<prefix>-gamepad.txt")
  2202. if (args.contains ("--gamepadshot"))
  2203. {
  2204. runGamepadShot (args[args.indexOf ("--gamepadshot") + 1].unquoted());
  2205. return;
  2206. }
  2207. // --export-bundle <in.lynx|.flp|.als> <folder> [--zip] [--no-mixdown] [--shot <prefix>] (round 184a, S9): File ›
  2208. // Export › "For other apps..." without the window; the report goes to "<folder>/export-bundle.txt"
  2209. if (args.contains ("--export-bundle"))
  2210. {
  2211. const auto i = args.indexOf ("--export-bundle");
  2212. runBundleExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--zip"), ! args.contains ("--no-mixdown"),
  2213. args.contains ("--shot") ? args[args.indexOf ("--shot") + 1].unquoted() : juce::String());
  2214. return;
  2215. }
  2216. if (args.contains ("--export-flp"))
  2217. {
  2218. const auto i = args.indexOf ("--export-flp");
  2219. runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
  2220. return;
  2221. }
  2222. if (args.contains ("--export"))
  2223. {
  2224. const auto i = args.indexOf ("--export");
  2225. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  2226. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  2227. return;
  2228. }
  2229. if (args.contains ("--render"))
  2230. {
  2231. const auto i = args.indexOf ("--render");
  2232. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  2233. return;
  2234. }
  2235. // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
  2236. uncleanLastStep = collectUncleanSessions();
  2237. sessionsFolder().createDirectory();
  2238. lynx::crashguard::beginSession (
  2239. sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
  2240. ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
  2241. + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
  2242. + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
  2243. startHangWatch();
  2244. // LYNX_PROFILE_MAIN=<file> (round 174f): the message thread sampled every millisecond, 5-second windows
  2245. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  2246. lynx::crashguard::startMainProfiler (profile.toStdString());
  2247. startupTrace.mark ("initialise (normal start)");
  2248. if (startupTrace.on)
  2249. lynx::startupMark = startupMarkHook;
  2250. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2251. lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
  2252. startupOptions = lynx::StartupOptions::load();
  2253. lynx::registerFileTypes();
  2254. startupTrace.mark ("options + file types");
  2255. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument; a path typed in a terminal may be relative
  2256. // (D#92, round 180a: it was ignored, leaving the blank project with no message). A missing file gets "Could not open".
  2257. if (args.size() > 0 && lynx::safety::isFileArgument (args[0].unquoted().toStdString()))
  2258. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[0].unquoted());
  2259. // LYNX --no-plugins project.lynx (round 190ap): File › "Open without third-party plugins..." from the command
  2260. // line, for a project a plugin keeps from opening — no hosted plugin is created, each keeps its settings
  2261. if (const auto i = args.indexOf ("--no-plugins"); i >= 0)
  2262. {
  2263. if (i + 1 < args.size() && lynx::safety::isFileArgument (args[i + 1].unquoted().toStdString()))
  2264. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[i + 1].unquoted());
  2265. startWithoutPlugins = fileToOpen.hasFileExtension ("lynx");
  2266. }
  2267. // LYNX_TEST_MODE=1 LYNX --open-event-test <ms> <file>: the file arrives the way macOS's Finder delivers it (a Linux
  2268. // or Windows run can exercise that path): 0 ms = at once, before the window exists
  2269. if (lynx::platform::testMode() && args[0] == "--open-event-test" && args.size() > 2)
  2270. {
  2271. const auto file = args[2].unquoted().quoted();
  2272. if (args[1].getIntValue() == 0)
  2273. anotherInstanceStarted (file);
  2274. else
  2275. juce::Timer::callAfterDelay (args[1].getIntValue(), [this, file] { anotherInstanceStarted (file); });
  2276. }
  2277. // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
  2278. // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
  2279. // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
  2280. if (args.contains ("--opentime"))
  2281. {
  2282. const auto i = args.indexOf ("--opentime");
  2283. const auto project = args[i + 1].unquoted();
  2284. fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
  2285. openTimeReport = juce::File (args[i + 2].unquoted());
  2286. if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
  2287. openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
  2288. }
  2289. if (! startupOptions.splash)
  2290. {
  2291. startEngine();
  2292. createMainWindow();
  2293. mainWindow->reveal();
  2294. showUncleanNotice();
  2295. startupTrace.mark ("window revealed");
  2296. openStartupFile();
  2297. startupTrace.mark ("startup file opened");
  2298. startOpenTimeProbe();
  2299. startUpdateCheck();
  2300. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  2301. return;
  2302. }
  2303. // the splash first, so it is on screen while the audio device opens; the main window is built
  2304. // once the logo has landed (the scene is still for a moment then) and shown when the splash ends
  2305. splash = std::make_unique<lynx::SplashScreen>();
  2306. startupTrace.mark ("splash made");
  2307. splash->showOnDesktop();
  2308. startupTrace.mark ("splash on the desktop");
  2309. juce::Timer::callAfterDelay (40, [this] {
  2310. startEngine();
  2311. if (splash == nullptr) // quit meanwhile
  2312. return;
  2313. splash->setStatus (lynx::tr ("Loading the workspace..."));
  2314. splash->startClock();
  2315. // the minimum counts from the process start (the audio device took part of it already)
  2316. splashDuration = lynx::SplashScreen::remainingDuration (startupTrace.seconds());
  2317. splash->setBarDuration (splashDuration);
  2318. juce::Timer::callAfterDelay (1050, [this] {
  2319. if (splash == nullptr || engine == nullptr)
  2320. return;
  2321. createMainWindow();
  2322. const auto wait = juce::jmax (0.0, splashDuration - splash->getElapsed());
  2323. juce::Timer::callAfterDelay ((int) (wait * 1000.0), [this] {
  2324. if (splash == nullptr || mainWindow == nullptr)
  2325. return;
  2326. mainWindow->reveal();
  2327. startupTrace.mark ("window revealed (after the splash)");
  2328. splash->toFront (false);
  2329. splash->finish ([this] { splash = nullptr; });
  2330. showUncleanNotice();
  2331. openStartupFile();
  2332. startupTrace.mark ("startup file opened");
  2333. startOpenTimeProbe();
  2334. startUpdateCheck();
  2335. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  2336. // first run: language, audio, plugin folders (FL Studio's included) and a background scan
  2337. if (! lynx::setupWizardDone() && lynx::platform::testMode())
  2338. lynx::platform::testModeLog ("setup wizard");
  2339. else if (! lynx::setupWizardDone())
  2340. mainWindow->showSetupWizard();
  2341. });
  2342. });
  2343. });
  2344. }
  2345. void startEngine()
  2346. {
  2347. startupTrace.mark ("before the audio engine");
  2348. engine = std::make_unique<lynx::AudioEngine>();
  2349. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  2350. startupTrace.mark ("audio engine + device");
  2351. crashEngine = engine.get();
  2352. lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
  2353. addDriverFileDeviceType();
  2354. if (startupOptions.sound)
  2355. {
  2356. // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
  2357. std::shared_ptr<const lynx::SampleData> sound;
  2358. if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
  2359. sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
  2360. engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
  2361. }
  2362. startupTrace.mark ("startup sound");
  2363. // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
  2364. // thread, while the splash and the main window come up (round 121)
  2365. if (fileToOpen.hasFileExtension ("flp"))
  2366. if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
  2367. try
  2368. {
  2369. engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  2370. startupTrace.mark ("plugin modules started ahead");
  2371. }
  2372. catch (const flp::Error&)
  2373. {
  2374. }
  2375. }
  2376. void createMainWindow()
  2377. {
  2378. mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
  2379. lynx::setMainWindowForOwnership (mainWindow.get());
  2380. lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
  2381. lynx::startRenderingWatch();
  2382. startupTrace.mark ("main window built");
  2383. }
  2384. // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
  2385. // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
  2386. void showUncleanNotice()
  2387. {
  2388. if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
  2389. {
  2390. if (uncleanLastStep.isNotEmpty())
  2391. lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
  2392. return;
  2393. }
  2394. if (uncleanLastStep.isEmpty())
  2395. {
  2396. lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
  2397. return;
  2398. }
  2399. auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
  2400. "LYNX SHARE's autosave folder; details in crash-history.log.",
  2401. { uncleanLastStep });
  2402. uncleanLastStep.clear();
  2403. const auto cause = uncleanCause();
  2404. // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
  2405. // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
  2406. juce::String separatePlugin;
  2407. if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
  2408. separatePlugin = cause.editorPlugin;
  2409. // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
  2410. else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
  2411. {
  2412. lynx::setGpuRenderingEnabled (false);
  2413. message << "\n\n"
  2414. << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
  2415. "rendering back on in Options > General settings (after a driver update, for example).",
  2416. { cause.driverModule });
  2417. }
  2418. // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
  2419. // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
  2420. for (int i = uncleanSteps.size(); --i >= 0;)
  2421. {
  2422. if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
  2423. break;
  2424. if (uncleanSteps[i].contains (lynx::visualgl::startNote))
  2425. {
  2426. if (lynx::visualgl::enabled())
  2427. {
  2428. lynx::visualgl::setEnabled (false);
  2429. message << "\n\n"
  2430. << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
  2431. "button turns it back on.");
  2432. }
  2433. break;
  2434. }
  2435. }
  2436. const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
  2437. auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
  2438. const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
  2439. lynx::crashreporter::retryPending();
  2440. if (action == lynx::crashreport::Action::askUser)
  2441. {
  2442. if (separatePlugin.isNotEmpty())
  2443. message << "\n\n"
  2444. << lynx::tr ("It happened while the window of {0} was opening{1}.",
  2445. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
  2446. lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
  2447. devices);
  2448. return;
  2449. }
  2450. if (action == lynx::crashreport::Action::sendSilently)
  2451. {
  2452. const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
  2453. lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
  2454. message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
  2455. }
  2456. if (separatePlugin.isNotEmpty())
  2457. {
  2458. juce::AlertWindow::showOkCancelBox (
  2459. juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
  2460. message + "\n\n"
  2461. + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
  2462. "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
  2463. "separate process\").",
  2464. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
  2465. lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
  2466. juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
  2467. if (result != 0)
  2468. lynx::setPluginAlwaysSeparate (separatePlugin, true);
  2469. }));
  2470. return;
  2471. }
  2472. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
  2473. }
  2474. // --opentime: after the start-up file was handed to the window
  2475. void startOpenTimeProbe()
  2476. {
  2477. if (openTimeReport == juce::File())
  2478. return;
  2479. struct Probe final : juce::Timer
  2480. {
  2481. LynxApplication& app;
  2482. juce::File report, project;
  2483. int idleSeconds;
  2484. int phase = 0; // 0 loading, 1 settling, 2 idle measurement
  2485. double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
  2486. double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
  2487. Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
  2488. : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
  2489. {
  2490. revealedS = startupTrace.seconds();
  2491. startTimer (250);
  2492. }
  2493. bool loaded() const
  2494. {
  2495. if (project == juce::File())
  2496. return true;
  2497. return app.mainWindow != nullptr
  2498. && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
  2499. }
  2500. void finish (const juce::String& result)
  2501. {
  2502. stopTimer();
  2503. const auto now = startupTrace.seconds();
  2504. const auto cpu = lynx::processCpuSeconds();
  2505. juce::String text;
  2506. text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
  2507. << "window_s=" << juce::String (revealedS, 3) << "\n"
  2508. << "loaded_s=" << juce::String (loadedS, 3) << "\n"
  2509. << "settled_s=" << juce::String (settledS, 3) << "\n"
  2510. << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
  2511. << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
  2512. << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
  2513. << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
  2514. << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
  2515. << "result=" << result << "\n";
  2516. report.replaceWithText (text);
  2517. app.setApplicationReturnValue (result == "OK" ? 0 : 1);
  2518. app.quit();
  2519. }
  2520. void timerCallback() override
  2521. {
  2522. const auto now = startupTrace.seconds();
  2523. const auto cpu = lynx::processCpuSeconds();
  2524. if (phase == 0)
  2525. {
  2526. if (loaded())
  2527. {
  2528. loadedS = now;
  2529. cpuAtLoaded = cpu;
  2530. phase = 1;
  2531. lastCpu = cpu;
  2532. lastT = now;
  2533. }
  2534. else if (now - revealedS > 240.0)
  2535. finish ("TIMEOUT loading");
  2536. return;
  2537. }
  2538. if (phase == 1)
  2539. {
  2540. // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
  2541. const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
  2542. lastCpu = cpu;
  2543. lastT = now;
  2544. if (use < 10.0)
  2545. {
  2546. if (quietSince < 0.0)
  2547. quietSince = now - 0.25;
  2548. if (now - quietSince >= 1.5)
  2549. settledS = quietSince;
  2550. }
  2551. else
  2552. quietSince = -1.0;
  2553. if (settledS >= 0.0 || now - loadedS > 30.0)
  2554. {
  2555. phase = 2;
  2556. idleCpu0 = cpu;
  2557. idleT0 = now;
  2558. }
  2559. return;
  2560. }
  2561. if (now - idleT0 >= (double) idleSeconds)
  2562. finish ("OK");
  2563. }
  2564. };
  2565. perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
  2566. }
  2567. // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
  2568. // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
  2569. void startUpdateCheck()
  2570. {
  2571. if (openTimeReport != juce::File())
  2572. return;
  2573. lynx::updater::afterStart();
  2574. juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
  2575. }
  2576. void openStartupFile()
  2577. {
  2578. startupFileHandled = true;
  2579. if (fileToOpen != juce::File() && mainWindow != nullptr)
  2580. {
  2581. if (std::exchange (startWithoutPlugins, false)) // --no-plugins (round 190ap)
  2582. mainWindow->getContent().openNextWithoutPlugins (true);
  2583. mainWindow->openFile (fileToOpen);
  2584. mainWindow->getContent().openNextWithoutPlugins (false); // (a file that did not open leaves nothing behind)
  2585. }
  2586. else if (mainWindow != nullptr && openTimeReport == juce::File())
  2587. mainWindow->getContent().openStartupProject(); // issue #123 (FL's Startup project)
  2588. }
  2589. void shutdown() override
  2590. {
  2591. parityShow.reset(); // (LYNX_PARITYSHOT_SHOW's window, before the engine it shows)
  2592. if (relaunched || updateHelper)
  2593. return; // the copy that ran owns the session (its crash notes stay for the next start)
  2594. lynx::crashguard::note ("closing");
  2595. lynx::shutdownPluginSandboxWorker();
  2596. splash = nullptr;
  2597. lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
  2598. lynx::shutdownAudioToMidi(); // (the same for a conversion to MIDI)
  2599. if (mainWindow != nullptr && mainWindow->isVisible())
  2600. mainWindow->saveState();
  2601. mainWindow = nullptr; // the UI goes before the engine
  2602. lynx::updater::shutdown(); // (a check or download in flight stops)
  2603. crashEngine = nullptr;
  2604. engine = nullptr;
  2605. // separate-process plugins end on threads of their own (issue #159): a moment for them, never the 10 s a dead
  2606. // child's pipe can take
  2607. lynx::finishSandboxTeardowns (2000);
  2608. // CLAP plugins whose instance another thread deleted while this one was busy: deactivated and destroyed now
  2609. lynx::ClapPluginFormat::finishPendingTeardowns();
  2610. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  2611. heartbeat.stopTimer();
  2612. lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
  2613. lynx::crashguard::stopHangWatch();
  2614. lynx::crashguard::stopMainProfiler();
  2615. lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
  2616. // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
  2617. // teardown runs (some crash in it at exit, round 111)
  2618. if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
  2619. lynx::crashguard::exitNow (getApplicationReturnValue());
  2620. }
  2621. void systemRequestedQuit() override
  2622. {
  2623. if (mainWindow != nullptr)
  2624. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  2625. else
  2626. quit();
  2627. }
  2628. private:
  2629. // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
  2630. // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
  2631. struct Heartbeat final : juce::Timer
  2632. {
  2633. void timerCallback() override { lynx::crashguard::heartbeat(); }
  2634. } heartbeat;
  2635. void startHangWatch()
  2636. {
  2637. const auto folder = lynx::platform::settingsFile ("autosave");
  2638. folder.createDirectory();
  2639. // keep the newest hang files only
  2640. auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
  2641. lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
  2642. for (int i = 20; i < old.size(); ++i)
  2643. old.getReference (i).deleteFile();
  2644. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
  2645. heartbeat.startTimerHz (5);
  2646. }
  2647. bool sandboxChild = false;
  2648. bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
  2649. bool updateHelper = false; // --apply-update (round 166b)
  2650. juce::String uncleanLastStep; // last step of a previous run that ended without closing
  2651. // LYNX_PROFILE_DIR=<folder> LYNX --lv2scantest report.txt (Linux, issue #85): the LV2 scan's promise, with real child
  2652. // processes. A new PluginHost per step, as every start of LYNX has. The LV2 folders of the machine are read too.
  2653. void runLv2ScanTest (const juce::String& reportPath)
  2654. {
  2655. juce::String report;
  2656. auto ok = lynx::platform::profileOverride() != juce::File();
  2657. #if JUCE_LINUX
  2658. const auto folder = lynx::platform::profileOverride().getChildFile ("lv2-test");
  2659. const juce::FileSearchPath paths (folder.getFullPathName());
  2660. const auto check = [&] (const juce::String& name, bool passed) {
  2661. report << name << "=" << (passed ? "ok" : "FAILED") << "\n";
  2662. ok = ok && passed;
  2663. };
  2664. const auto install = [&] (const juce::String& name) {
  2665. const auto bundle = folder.getChildFile (name + ".lv2");
  2666. bundle.createDirectory();
  2667. bundle.getChildFile ("manifest.ttl").replaceWithText ("@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
  2668. "<urn:lynx-test:" + name + "> a lv2:Plugin ; lv2:binary <" + name + ".so> ; rdfs:seeAlso <plugin.ttl> .\n");
  2669. bundle.getChildFile ("plugin.ttl").replaceWithText ("@prefix doap: <http://usefulinc.com/ns/doap#> .\n<urn:lynx-test:" + name + "> doap:name \"" + name + "\" .\n");
  2670. };
  2671. auto date = juce::Time::getCurrentTime();
  2672. const auto touch = [&] { // the next date, whatever the file system's date resolution
  2673. date += juce::RelativeTime::seconds (2.0);
  2674. folder.getChildFile ("a.lv2/plugin.ttl").setLastModificationTime (date);
  2675. };
  2676. const auto listed = [] (lynx::PluginHost& host, const juce::String& name) {
  2677. for (const auto& d : host.getKnownPlugins().getTypes())
  2678. if (d.fileOrIdentifier == "urn:lynx-test:" + name)
  2679. return true;
  2680. return false;
  2681. };
  2682. const auto step = [&] (const juce::String& name, int children, const std::function<void (lynx::PluginHost&)>& prepare = {}) {
  2683. lynx::PluginHost host (true);
  2684. if (prepare)
  2685. prepare (host);
  2686. host.scan (paths, {});
  2687. check (name, host.scanChildrenStarted() == children && listed (host, "a"));
  2688. };
  2689. install ("a");
  2690. step ("first_scan_one_child", 1);
  2691. step ("nothing_changed_no_child", 0);
  2692. touch();
  2693. step ("ttl_updated", 1);
  2694. install ("b");
  2695. step ("bundle_installed", 1);
  2696. step ("forget_file", 1, [] (lynx::PluginHost& host) { host.forgetFile ("urn:lynx-test:a"); });
  2697. step ("forget_all", 1, [] (lynx::PluginHost& host) { host.forgetAll(); });
  2698. lynx::platform::settingsFile ("plugins.xml").deleteFile();
  2699. step ("list_lost", 1);
  2700. step ("nothing_changed_again", 0);
  2701. // cancelled while the child works: stopped at once, and nothing is taken for done
  2702. touch();
  2703. setenv ("LYNX_TEST_CRASH", "lv2-batch-hang", 1);
  2704. {
  2705. lynx::PluginHost host (true);
  2706. const auto started = juce::Time::getMillisecondCounter();
  2707. host.scan (paths, [] (float, const juce::String&) { return false; });
  2708. check ("cancel_stops_the_child", host.scanChildrenStarted() == 1 && juce::Time::getMillisecondCounter() - started < 20000);
  2709. }
  2710. unsetenv ("LYNX_TEST_CRASH");
  2711. step ("described_after_cancel", 1);
  2712. // the child dies: plugin by plugin takes over (stopped after two of them: a machine may have hundreds)
  2713. touch();
  2714. setenv ("LYNX_TEST_CRASH", "lv2-batch", 1);
  2715. {
  2716. lynx::PluginHost host (true);
  2717. host.scan (paths, [&host] (float, const juce::String&) { return host.scanChildrenStarted() < 3; });
  2718. check ("crash_falls_back_plugin_by_plugin", host.scanChildrenStarted() == 3);
  2719. auto blamed = false;
  2720. for (const auto& file : host.getKnownPlugins().getBlacklistedFiles())
  2721. blamed = blamed || file.startsWith ("lv2-folders:");
  2722. check ("crash_blacklists_nothing", ! blamed);
  2723. }
  2724. unsetenv ("LYNX_TEST_CRASH");
  2725. step ("described_after_crash", 1);
  2726. #endif
  2727. juce::File (reportPath).replaceWithText (report + "result=" + (ok ? "OK" : "FAILED") + "\n");
  2728. setApplicationReturnValue (ok ? 0 : 1);
  2729. quit();
  2730. }
  2731. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  2732. // Exit code 0 = audio came out, 1 = silence.
  2733. // --selftest (round 190ci): two more copies of LYNX end by a fault on purpose (--faulttest), one on a normal stack
  2734. // (the top-level filter) and one on a stack Windows cannot walk (the first-chance hook); each must leave
  2735. // "crash <time>.txt" with the access violation in the folder it is given.
  2736. // Round 190dt (Linux / macOS): a plain fault, and LYNX's own fault inside a guarded plugin call (in its code, and in
  2737. // the C library called from its code), must each leave the crash file with the signal: the plugin guard passes
  2738. // LYNX's own faults on to the crash handler instead of swallowing them ("swallowed.txt" = it did).
  2739. static juce::String faultReportSelfTest()
  2740. {
  2741. #if (JUCE_WINDOWS && (defined (_M_X64) || defined (__x86_64__))) \
  2742. || ((JUCE_LINUX || JUCE_MAC) && (defined (__x86_64__) || defined (__aarch64__)))
  2743. const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
  2744. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  2745. .getChildFile ("lynx-faulttest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  2746. juce::StringArray problems;
  2747. #if JUCE_WINDOWS
  2748. const char* const kinds[] = { "plain", "unwalkable" };
  2749. #else
  2750. const char* const kinds[] = { "plain", "guarded", "guarded-libc" };
  2751. #endif
  2752. for (const auto* kind : kinds)
  2753. {
  2754. const auto folder = root.getChildFile (kind);
  2755. folder.createDirectory();
  2756. juce::ChildProcess child;
  2757. const auto started = child.start (juce::StringArray { exe.getFullPathName(), "--faulttest", kind, folder.getFullPathName() }, 0);
  2758. if (! started || ! child.waitForProcessToFinish (60000))
  2759. {
  2760. child.kill();
  2761. problems.add (juce::String (kind) + ": " + (started ? "did not end" : "did not start"));
  2762. continue;
  2763. }
  2764. juce::String text;
  2765. for (const auto& file : folder.findChildFiles (juce::File::findFiles, false, "crash *.txt"))
  2766. text = file.loadFileAsString();
  2767. #if JUCE_WINDOWS
  2768. const auto found = text.contains ("0xc0000005");
  2769. #else
  2770. const auto found = text.contains ("segmentation fault") || text.contains ("bus error");
  2771. #endif
  2772. if (folder.getChildFile ("swallowed.txt").existsAsFile())
  2773. problems.add (juce::String (kind) + ": LYNX's own fault was caught as a plugin's ("
  2774. + folder.getChildFile ("swallowed.txt").loadFileAsString() + ")");
  2775. else if (! found)
  2776. problems.add (juce::String (kind) + ": " + (text.isEmpty() ? "no crash file" : "a crash file without the fault")
  2777. + " (exit code 0x" + juce::String::toHexString ((juce::int64) child.getExitCode()) + ")");
  2778. }
  2779. root.deleteRecursively();
  2780. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems.joinIntoString ("; ");
  2781. #else
  2782. return "SKIPPED (Windows x64, Linux / macOS x86-64 / ARM64 only)";
  2783. #endif
  2784. }
  2785. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  2786. {
  2787. lynx::AudioEngine offline (false);
  2788. const auto peak = offline.renderOffline (2.0, 48000.0);
  2789. const auto audioOk = peak > 0.01f && peak < 10.0f;
  2790. // project format round trip, with accents in the name
  2791. auto original = lynx::Song::makeDefault();
  2792. original.channels[0].name = "Bumbo ação";
  2793. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  2794. original.mode = lynx::PlayMode::song;
  2795. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  2796. original.mixer[3].effects[0].params[1] = 0.25f;
  2797. lynx::Automation automation;
  2798. automation.name = "Pan";
  2799. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  2800. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  2801. original.automations.push_back (automation);
  2802. lynx::Clip automationClip;
  2803. automationClip.kind = lynx::ClipKind::automation;
  2804. automationClip.automation = 0;
  2805. automationClip.track = 4;
  2806. automationClip.length = 3840;
  2807. original.playlist.push_back (automationClip);
  2808. original.loopStart = 960;
  2809. original.loopEnd = 7680;
  2810. original.playlistTracks.resize (3);
  2811. original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
  2812. { // the clip grid (round 181a)
  2813. lynx::launcher::setClip (original, 1, 2, { 0, 0, 0, 1920, 0 });
  2814. auto& slot = *lynx::launcher::settingsAt (*original.clipGrid, 1, 2);
  2815. slot.name = "Clip ação";
  2816. slot.mode = lynx::LaunchMode::toggle;
  2817. slot.quant = lynx::LaunchQuant::eighthTriplet;
  2818. slot.legato = true;
  2819. slot.loop = false;
  2820. original.clipGrid->scenes[0].name = "Intro";
  2821. original.clipGrid->globalQuant = lynx::LaunchQuant::bars2;
  2822. }
  2823. std::uint32_t savedGroove = 0;
  2824. { // round 190bv: the groove pool, a groove on the slot's clip, and that clip copied and the copy moved
  2825. lynx::Groove g;
  2826. g.name = "Balanço";
  2827. g.base = lynx::GrooveBase::eighth;
  2828. g.quantize = 0.25f;
  2829. g.timing = 0.8f;
  2830. g.random = 0.1f;
  2831. g.velocity = -0.5f;
  2832. g.length = 1920;
  2833. g.points = { { 0, 1.0f }, { 560, 0.5f } };
  2834. savedGroove = lynx::groove::add (original.grooves, g);
  2835. original.grooves.amount = 1.2f;
  2836. lynx::groove::setClipGroove (original, 1, 2, savedGroove);
  2837. lynx::session::moveClip (original, 1, 2, 0, 1, true);
  2838. lynx::session::moveClip (original, 0, 1, 2, 0, false);
  2839. }
  2840. original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
  2841. original.playlistTracks[1].collapsed = true;
  2842. original.channelGroups = { "Drums", "Keys" };
  2843. original.channels[1].group = 1;
  2844. original.channels[1].cutOthersOnly = original.channels[1].cutAtNoteEnd = true; // FL Studio Mobile's cut rule (round 190fe)
  2845. juce::String error;
  2846. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  2847. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  2848. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  2849. // round 190bw: FL's curve modes of automation points come back from a project, tension whole; a bent point
  2850. // without a mode (a project saved before the modes: [tick, value, tension]) keeps LYNX's older law
  2851. const auto curveModesOk = [&original] {
  2852. auto song = original;
  2853. auto& a = song.automations[0];
  2854. a.points = { { 0, 0.25f, 0.5f, (std::uint8_t) lynx::flcurve::stairs },
  2855. { 960, 1.0f, -0.123456f, (std::uint8_t) lynx::flcurve::smooth },
  2856. { 1920, 0.5f, 0.0f, (std::uint8_t) lynx::flcurve::hold },
  2857. { 2400, 0.75f, 0.7f, lynx::AutomationPoint::legacyCurve },
  2858. { 2880, 0.3f, 0.0f, 0 },
  2859. { 3840, 0.6f, 0.0f, 0 } };
  2860. a.lfo.on = true;
  2861. a.lfo.amp = { { 0, 1.0f, -0.25f, (std::uint8_t) lynx::flcurve::pulse }, { 960, 0.5f, 0.0f, 0 } };
  2862. juce::String e;
  2863. const auto text = lynx::ProjectFile::toJson (song);
  2864. const auto back = lynx::ProjectFile::fromJson (text, e);
  2865. return back && back->automations.size() == 1 && back->automations[0].points == a.points && back->automations[0].lfo.amp == a.lfo.amp
  2866. && back->automations[0].valueAt (700.0) == a.valueAt (700.0) && back->automations[0].valueAt (2600.0) == a.valueAt (2600.0);
  2867. }();
  2868. const auto projectOk = curveModesOk && reloaded && reloaded->channels.size() == original.channels.size()
  2869. && reloaded->channels[0].name == original.channels[0].name
  2870. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  2871. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  2872. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  2873. && reloaded->clipGrid.has_value() && reloaded->clipGrid->globalQuant == lynx::LaunchQuant::bars2
  2874. && reloaded->clipGrid->scenes.size() == 3 && reloaded->clipGrid->scenes[0].name == "Intro"
  2875. && lynx::launcher::clipAt (*reloaded->clipGrid, 1, 2) != nullptr
  2876. && [&reloaded] {
  2877. auto grid = *reloaded->clipGrid;
  2878. const auto* slot = lynx::launcher::settingsAt (grid, 1, 2);
  2879. return slot != nullptr && slot->name == "Clip ação" && slot->mode == lynx::LaunchMode::toggle
  2880. && slot->quant == lynx::LaunchQuant::eighthTriplet && slot->legato && ! slot->loop;
  2881. }()
  2882. && [&reloaded, &original, savedGroove] { // round 190bv
  2883. auto grid = *reloaded->clipGrid;
  2884. const auto* kept = lynx::launcher::settingsAt (grid, 1, 2);
  2885. const auto* moved = lynx::launcher::settingsAt (grid, 2, 0);
  2886. const auto* clip = lynx::launcher::clipAt (grid, 2, 0);
  2887. return reloaded->grooves == original.grooves && reloaded->grooves.grooves.size() == 1
  2888. && reloaded->grooves.amount == 1.2f && reloaded->grooves.grooves[0].name == "Balanço"
  2889. && reloaded->grooves.grooves[0].points.size() == 2 && savedGroove != 0
  2890. && kept != nullptr && kept->groove == savedGroove
  2891. && lynx::launcher::clipAt (grid, 0, 1) == nullptr
  2892. && clip != nullptr && clip->pattern == 0 && clip->length == 1920
  2893. && moved != nullptr && moved->groove == savedGroove && moved->name == "Clip ação"
  2894. && moved->mode == lynx::LaunchMode::toggle && moved->legato && ! moved->loop;
  2895. }()
  2896. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  2897. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  2898. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  2899. && reloaded->automations[0].points[1].tick == 3840
  2900. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  2901. && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
  2902. && reloaded->playlistTracks[1].colour == 0
  2903. && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
  2904. && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
  2905. && reloaded->channels[1].cutOthersOnly && reloaded->channels[1].cutAtNoteEnd && ! reloaded->channels[0].cutOthersOnly
  2906. && ! reloaded->channels[0].cutAtNoteEnd
  2907. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  2908. && reloaded->mixer[3].effects.size() == 1
  2909. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  2910. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  2911. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  2912. auto rich = lynx::Song::makeDefault();
  2913. auto& synth = rich.channels[4].synth;
  2914. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  2915. synth.filterType = 2;
  2916. synth.mono = true;
  2917. synth.portaBeats = 0.125f;
  2918. synth.am = true;
  2919. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  2920. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  2921. auto& sampler = rich.channels[0].sampler;
  2922. sampler.cutoff = 1200.0f;
  2923. sampler.resonance = 0.3f;
  2924. sampler.filterType = 1;
  2925. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  2926. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  2927. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  2928. rich.mixer[2].eq.hz[1] = 2200.0f;
  2929. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2930. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  2931. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  2932. rich.mixer[2].effects.push_back (peqSlot);
  2933. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  2934. utilitySlot.params[1] = 0.2f;
  2935. rich.mixer[2].effects.push_back (utilitySlot);
  2936. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  2937. for (int i = 0; i < 300; ++i)
  2938. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  2939. vocodexSlot.sidechain = 1;
  2940. vocodexSlot.sidechain2 = 2;
  2941. rich.mixer[3].effects.push_back (vocodexSlot);
  2942. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  2943. rich.addMarker ({ 7680, {}, 7, 8 });
  2944. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  2945. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  2946. for (std::size_t i = 0; i < a.size(); ++i)
  2947. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  2948. return false;
  2949. return true;
  2950. };
  2951. // round 190bu: a one-knob effect, the chain's Blend and its preset name travel in the project; a project without
  2952. // them reads as before (no goal, Blend 100 %) and writes none of the new keys
  2953. bool fx190buOk = false;
  2954. {
  2955. auto song = lynx::Song::makeDefault();
  2956. const auto plainJson = lynx::ProjectFile::toJson (song);
  2957. const auto* preset = lynx::chains::find ("Whisper Air");
  2958. if (preset != nullptr && song.mixer.size() > 2)
  2959. {
  2960. lynx::chains::apply (song, 1, *preset);
  2961. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::room, 0.62f));
  2962. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::bass, 0.3f));
  2963. song.mixer[2].chainBlend = 0.4f;
  2964. const auto json = lynx::ProjectFile::toJson (song);
  2965. const auto back = lynx::ProjectFile::fromJson (json, error);
  2966. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  2967. auto same = back && back->mixer.size() == song.mixer.size();
  2968. for (std::size_t t = 1; same && t <= 2; ++t)
  2969. {
  2970. const auto& a = song.mixer[t];
  2971. const auto& b = back->mixer[t];
  2972. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  2973. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  2974. same = a.effects[i].kind == b.effects[i].kind && a.effects[i].goal == b.effects[i].goal
  2975. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f && a.effects[i].row == b.effects[i].row
  2976. && lynx::goals::active (b.effects[i]) == lynx::goals::active (a.effects[i]);
  2977. }
  2978. fx190buOk = same && lynx::chains::unchanged (*back, 1) && back->mixer[2].chainPreset.empty()
  2979. && ! plainJson.contains ("\"goal\"") && ! plainJson.contains ("chainBlend") && ! plainJson.contains ("chainPreset")
  2980. && json.contains ("\"goalAmount\"") && plainBack && plainBack->mixer[1].chainBlend == 1.0f
  2981. && lynx::ProjectFile::toJson (*back) == json;
  2982. // a user's chain preset file: the slots, Blend and name come back; the strip's level is not part of it
  2983. song.mixer[2].volume = 0.31f;
  2984. const auto file = lynx::ProjectFile::mixerTrackStateToJson (lynx::chains::stateOf (song.mixer[2], "Mine"));
  2985. const auto state = lynx::ProjectFile::mixerTrackStateFromJson (file, error);
  2986. fx190buOk = fx190buOk && state && state->effects.size() == 2 && state->effects[0].goal == lynx::goals::room
  2987. && lynx::goals::active (state->effects[1]) && std::abs (state->chainBlend - 0.4f) < 1.0e-6f && state->chainPreset == "Mine"
  2988. && state->volume == lynx::MixerTrack().volume;
  2989. }
  2990. }
  2991. const auto richOk = fx190buOk && richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  2992. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  2993. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  2994. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  2995. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  2996. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  2997. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  2998. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  2999. && richBack->markers() == rich.markers();
  3000. // issue #96's per-plugin option: saved only when on; old projects (no field) read as off
  3001. bool hostKeysOk = false;
  3002. {
  3003. auto song = lynx::Song::makeDefault();
  3004. lynx::ChannelDef plugin;
  3005. plugin.instrument = lynx::InstrumentKind::plugin;
  3006. plugin.plugin.id = "x";
  3007. song.channels.push_back (plugin);
  3008. const auto channel = song.channels.size() - 1;
  3009. const auto off = lynx::ProjectFile::toJson (song);
  3010. song.channels[channel].plugin.allowHostKeys = true;
  3011. song.channels[channel].plugin.hostKeysFirst = true;
  3012. song.channels[channel].plugin.pinned = true; // (round 190ao: Pin on top)
  3013. song.channels[channel].plugin.velocityMode = lynx::prefs::pluginVelocityFixed; // (round 190ao: the plugin's own velocity)
  3014. song.channels[channel].plugin.fixedVelocity = 64;
  3015. const auto on = lynx::ProjectFile::toJson (song);
  3016. const auto offBack = lynx::ProjectFile::fromJson (off, error);
  3017. const auto onBack = lynx::ProjectFile::fromJson (on, error);
  3018. hostKeysOk = ! off.contains ("allowHostKeys") && on.contains ("allowHostKeys") && offBack && onBack
  3019. && ! offBack->channels[channel].plugin.allowHostKeys && onBack->channels[channel].plugin.allowHostKeys
  3020. && ! off.contains ("hostKeysFirst") && ! offBack->channels[channel].plugin.hostKeysFirst && onBack->channels[channel].plugin.hostKeysFirst
  3021. && ! off.contains ("pinnedOnTop") && ! offBack->channels[channel].plugin.pinned && onBack->channels[channel].plugin.pinned
  3022. && ! off.contains ("velocityMode") && ! off.contains ("fixedVelocity") && offBack->channels[channel].plugin.velocityMode == 0
  3023. && offBack->channels[channel].plugin.fixedVelocity == lynx::prefs::defaultFixedVelocity
  3024. && onBack->channels[channel].plugin.velocityMode == lynx::prefs::pluginVelocityFixed && onBack->channels[channel].plugin.fixedVelocity == 64;
  3025. }
  3026. // round 190ad: a new project has FL's plugin levels and keeps them through a save; a project saved before
  3027. // (no "pluginLevels") reads as LYNX's own law, and stays so when it opens
  3028. bool pluginLevelsOk = false;
  3029. {
  3030. const auto fresh = lynx::makeNewProject();
  3031. const auto saved = lynx::ProjectFile::toJson (fresh);
  3032. const auto back = lynx::ProjectFile::fromJson (saved, error);
  3033. auto old = lynx::Song::makeDefault(); // (what every earlier version made)
  3034. const auto oldSaved = lynx::ProjectFile::toJson (old);
  3035. const auto oldBack = lynx::ProjectFile::fromJson (oldSaved, error);
  3036. const auto stripped = lynx::ProjectFile::fromJson (saved.replace ("\"pluginLevels\"", "\"pluginLevelsGone\""), error);
  3037. pluginLevelsOk = fresh.flPluginLevels && saved.contains ("\"pluginLevels\"") && back && back->flPluginLevels
  3038. && ! old.flPluginLevels && ! oldSaved.contains ("pluginLevels") && oldBack && ! oldBack->flPluginLevels
  3039. && stripped && ! stripped->flPluginLevels;
  3040. }
  3041. // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
  3042. bool hwOutOk = false;
  3043. {
  3044. auto song = lynx::Song::makeDefault();
  3045. const auto plain = lynx::ProjectFile::toJson (song);
  3046. song.mixer[0].outputChannel = lynx::outputNone;
  3047. song.mixer[1].outputChannel = 2;
  3048. song.mixer[1].outputMode = lynx::OutputMode::monoRight;
  3049. song.mixer[2].outputChannel = 6;
  3050. song.mixer[3].outputChannel = 4;
  3051. song.mixer[3].outputMode = lynx::OutputMode::monoSum;
  3052. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3053. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3054. hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
  3055. && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
  3056. && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
  3057. && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
  3058. && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
  3059. }
  3060. // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
  3061. // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
  3062. bool flp168jOk = false;
  3063. {
  3064. auto song = lynx::Song::makeDefault();
  3065. const auto plain = lynx::ProjectFile::toJson (song);
  3066. song.channels[0].icon = 75;
  3067. song.mixer[2].icon = 71;
  3068. song.playlistTracks.resize (3);
  3069. song.playlistTracks[2].icon = 30;
  3070. song.autoPdc = false;
  3071. song.compensateAutomations = false;
  3072. song.timeSignatureMode = true;
  3073. song.scaleHighlight = { 10, 5 };
  3074. song.dataFolder = "D:\\Projects\\data";
  3075. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3076. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3077. flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
  3078. && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
  3079. && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
  3080. && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
  3081. && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
  3082. && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
  3083. }
  3084. // round 180d: clip fades take FL's S curve; a project saved before that keeps its straight fades, also after another
  3085. // save, and a clip made in it takes the S curve. FL's fade tensions and stretch mode and PITCH survive a save.
  3086. // issue #122: playlist tracks linked to inserts (audio) and channels (instrument) survive save, load and save
  3087. // again byte for byte (they were read before the mixer and fell back to Unassigned)
  3088. bool trackModes122Ok = false;
  3089. {
  3090. auto song = lynx::Song::makeDefault();
  3091. song.playlistTracks.resize (6);
  3092. song.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  3093. song.playlistTracks[1].mixerTrack = 3;
  3094. song.playlistTracks[4].mode = lynx::PlaylistTrackMode::audio;
  3095. song.playlistTracks[4].mixerTrack = (int) song.mixer.size() - 1;
  3096. song.playlistTracks[5].mode = lynx::PlaylistTrackMode::instrument;
  3097. song.playlistTracks[5].channel = 1;
  3098. song.playlistTracks[5].mixerTrack = 2;
  3099. const auto json = lynx::ProjectFile::toJson (song, false);
  3100. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  3101. const auto again = loaded ? lynx::ProjectFile::toJson (*loaded, false) : juce::String();
  3102. trackModes122Ok = loaded && json.contains ("playlistTrackModes") && again == json && loaded->playlistTracks.size() >= 6
  3103. && loaded->playlistTracks[1].mode == lynx::PlaylistTrackMode::audio && loaded->playlistTracks[1].mixerTrack == 3
  3104. && loaded->playlistTracks[4].mode == lynx::PlaylistTrackMode::audio
  3105. && loaded->playlistTracks[4].mixerTrack == (int) song.mixer.size() - 1
  3106. && loaded->playlistTracks[5].mode == lynx::PlaylistTrackMode::instrument && loaded->playlistTracks[5].channel == 1;
  3107. }
  3108. bool clipFades180dOk = false;
  3109. {
  3110. auto song = lynx::Song::makeDefault();
  3111. lynx::Clip faded;
  3112. faded.kind = lynx::ClipKind::audio;
  3113. faded.channel = 0;
  3114. faded.length = lynx::ppq * 8;
  3115. faded.fadeIn = lynx::ppq;
  3116. faded.fadeOutTension = -812.933f;
  3117. faded.fadeOut = lynx::ppq * 2;
  3118. lynx::Clip plainClip = faded;
  3119. plainClip.fadeIn = plainClip.fadeOut = 0;
  3120. plainClip.fadeOutTension = 0.0f;
  3121. plainClip.start = lynx::ppq * 16;
  3122. song.playlist = { faded, plainClip };
  3123. song.channels[0].sampler.flStretchMode = 5;
  3124. song.channels[0].sampler.flStretchPitch = 247;
  3125. const auto json = lynx::ProjectFile::toJson (song);
  3126. const auto current = lynx::ProjectFile::fromJson (json, error);
  3127. const auto oldJson = json.replace ("\"clipFadesPerClip\"", "\"clipFadesOther\"");
  3128. auto old = lynx::ProjectFile::fromJson (oldJson, error);
  3129. auto resaved = old;
  3130. if (resaved)
  3131. {
  3132. auto added = faded;
  3133. added.start = lynx::ppq * 32;
  3134. added.linearFades = 0;
  3135. resaved->playlist.push_back (added);
  3136. resaved = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*resaved), error);
  3137. }
  3138. clipFades180dOk = current && old && resaved && json.contains ("clipFadesPerClip") && ! oldJson.contains ("clipFadesPerClip")
  3139. && current->playlist.size() == 2 && ! current->playlist[0].linearFades
  3140. && current->playlist[0].fadeOutTension == -812.933f && ! current->playlist[1].linearFades
  3141. && current->channels[0].sampler.flStretchMode == 5 && current->channels[0].sampler.flStretchPitch == 247
  3142. && old->playlist.size() == 2 && old->playlist[0].linearFades && ! old->playlist[1].linearFades
  3143. && resaved->playlist.size() == 3 && resaved->playlist[0].linearFades && ! resaved->playlist[1].linearFades
  3144. && ! resaved->playlist[2].linearFades && resaved->playlist[0].fadeOutTension == -812.933f;
  3145. }
  3146. // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
  3147. // them has neither in its file and loads with the option off
  3148. bool blocksOk = false;
  3149. {
  3150. auto song = lynx::Song::makeDefault();
  3151. const auto plain = lynx::ProjectFile::toJson (song);
  3152. song.patternBlocksOn = true;
  3153. lynx::patternblocks::place (song, 0, 0);
  3154. lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
  3155. song.addArrangement ("Second");
  3156. lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
  3157. song.selectArrangement (0);
  3158. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3159. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3160. blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2
  3161. && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
  3162. && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
  3163. && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
  3164. && ! plain.contains ("patternBlocks");
  3165. }
  3166. // FL's pattern clip takeover (issue #158): saved when on; a project saved before it (no key) loads with it off and
  3167. // keeps playing every overlapping clip of a pattern in full; new projects have it on
  3168. bool takeoverOk = false;
  3169. {
  3170. auto song = lynx::Song::makeDefault();
  3171. const auto plain = lynx::ProjectFile::toJson (song);
  3172. song.patternClipTakeover = true;
  3173. const auto json = lynx::ProjectFile::toJson (song);
  3174. const auto back = lynx::ProjectFile::fromJson (json, error);
  3175. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3176. takeoverOk = back && back->patternClipTakeover && json.contains ("patternClipTakeover") && plainBack
  3177. && ! plainBack->patternClipTakeover && ! plain.contains ("patternClipTakeover")
  3178. && lynx::makeNewProject().patternClipTakeover;
  3179. }
  3180. // comping (round 177c): a comp's equal-power crossfades (Clip::fadeCurve) and the crossfade length are saved; a
  3181. // project without them has neither in its file
  3182. bool compOk = false;
  3183. {
  3184. auto song = lynx::Song::makeDefault();
  3185. const auto plain = lynx::ProjectFile::toJson (song);
  3186. lynx::ChannelDef take;
  3187. take.instrument = lynx::InstrumentKind::audioClip;
  3188. take.samplePath = "take.wav";
  3189. song.channels.push_back (take);
  3190. lynx::Clip a;
  3191. a.kind = lynx::ClipKind::audio;
  3192. a.channel = (int) song.channels.size() - 1;
  3193. a.length = lynx::ppq;
  3194. a.fadeOut = 20;
  3195. a.fadeCurve = 2;
  3196. auto b = a;
  3197. b.start = lynx::ppq - 20;
  3198. b.fadeOut = 0;
  3199. b.fadeIn = 20;
  3200. b.fadeCurve = 1;
  3201. // round 180d's FL fade fields (indices 17..20) and the comp curve (index 21) on one clip, all kept
  3202. auto c = a;
  3203. c.start = 4 * lynx::ppq;
  3204. c.fadeIn = 30;
  3205. c.fadeInTension = -0.75f;
  3206. c.fadeOutTension = 0.5f;
  3207. c.linearFades = 2;
  3208. c.flFadeFlags = 0x1234u;
  3209. c.fadeCurve = 3;
  3210. song.playlist = { a, b, c };
  3211. song.compCrossfadeMs = 12.5f;
  3212. song.playlistTracks.resize (2);
  3213. song.playlistTracks[0].compTrack = true;
  3214. song.playlistTracks[1].grouped = true;
  3215. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3216. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  3217. const auto* both = back && back->playlist.size() == 3 ? &back->playlist[2] : nullptr;
  3218. compOk = back && back->playlist.size() == 3 && back->playlist[0].fadeCurve == 2 && back->playlist[1].fadeCurve == 1
  3219. && both != nullptr && both->fadeCurve == 3 && both->fadeInTension == -0.75f && both->fadeOutTension == 0.5f
  3220. && both->linearFades == 2 && both->flFadeFlags == 0x1234u && both->fadeIn == 30
  3221. && back->playlist[1].fadeIn == 20 && back->compCrossfadeMs == 12.5f && back->playlistTracks[0].compTrack && ! back->playlistTracks[1].compTrack && plainBack
  3222. && plainBack->compCrossfadeMs == lynx::Song::defaultCompCrossfadeMs && ! plain.contains ("compCrossfadeMs") && ! plain.contains ("playlistCompTracks");
  3223. }
  3224. // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
  3225. // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
  3226. bool polyOk = false;
  3227. {
  3228. auto song = lynx::Song::makeDefault();
  3229. lynx::ChannelDef osc;
  3230. osc.instrument = lynx::InstrumentKind::threeosc;
  3231. osc.misc.mono = osc.misc.porta = true;
  3232. osc.misc.portaBeats = 0.25f;
  3233. song.channels.push_back (osc);
  3234. auto old = osc;
  3235. old.misc = {};
  3236. old.synth.mono = old.synth.porta = true;
  3237. old.synth.portaBeats = 0.5f;
  3238. song.channels.push_back (old);
  3239. old.maxPolyphony = 1;
  3240. song.channels.push_back (old);
  3241. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3242. const auto n = song.channels.size();
  3243. polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
  3244. && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
  3245. && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
  3246. && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
  3247. && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
  3248. }
  3249. // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
  3250. bool latencyOk = false;
  3251. {
  3252. auto song = lynx::Song::makeDefault();
  3253. const auto plain = lynx::ProjectFile::toJson (song);
  3254. song.mixer[1].latencyMs = -20.0f;
  3255. song.mixer[2].latencyMs = 12.5f;
  3256. song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
  3257. song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  3258. song.mixer[3].compensateMasterLatency = false;
  3259. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3260. latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
  3261. && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
  3262. && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
  3263. && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
  3264. && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
  3265. }
  3266. // LYNX's pre-fader sends (round 190aq): saved only when one is used, in a list of its own ("preSends") that a
  3267. // version from before ignores (its sends then play post-fader, as FL's)
  3268. bool preSendOk = false;
  3269. {
  3270. auto song = lynx::Song::makeDefault();
  3271. song.setRoute (1, 3, true, 0.5f);
  3272. song.setRoute (1, 4, true);
  3273. song.setRoute (2, 3, true);
  3274. const auto plain = lynx::ProjectFile::toJson (song);
  3275. song.setSendPre (1, 3, true);
  3276. const auto json = lynx::ProjectFile::toJson (song);
  3277. const auto back = lynx::ProjectFile::fromJson (json, error);
  3278. preSendOk = back && back->sendPre (1, 3) && ! back->sendPre (1, 4) && ! back->sendPre (2, 3)
  3279. && std::abs (back->routeLevel (1, 3) - 0.5f) < 1.0e-4f && back->mixer[1].sends == song.mixer[1].sends
  3280. && ! plain.contains ("preSends") && json.contains ("preSends")
  3281. && json.replace ("\"preSends\"", "\"preSendsOld\"") != json;
  3282. // the same file without the list (what an older version reads): the sends are there, post-fader
  3283. if (const auto old = lynx::ProjectFile::fromJson (json.replace ("\"preSends\"", "\"unknownToOldVersions\""), error))
  3284. preSendOk = preSendOk && old->routes (1, 3) && ! old->sendPre (1, 3) && old->mixer[1].sends.size() == 2;
  3285. else
  3286. preSendOk = false;
  3287. }
  3288. // LYNX's "Low latency while recording" (round 190aq): a latency-adding effect on a monitored insert's path is
  3289. // bypassed in the engine only — PDC drops, the slot is marked, the song and the saved project stay as they are —
  3290. // and it is back when the option goes off
  3291. bool lowLatencyOk = false;
  3292. {
  3293. lynx::AudioEngine live (false);
  3294. live.editSong ([] (lynx::Song& s) {
  3295. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter)); // 1.5 ms look-ahead
  3296. s.mixer[1].inputChannel = 0;
  3297. s.mixer[1].monitor = lynx::InputMonitor::on;
  3298. });
  3299. const auto before = live.getLatencySamples();
  3300. const auto saved = lynx::ProjectFile::toJson (live.getSong());
  3301. const auto idle = live.lowLatencyBypassedCount() == 0; // the option is off: nothing is bypassed
  3302. auto o = live.getRecordOptions();
  3303. o.lowLatencyRecording = true;
  3304. live.setRecordOptions (o);
  3305. const auto during = live.getLatencySamples();
  3306. const auto marked = live.isSlotLowLatencyBypassed (1, 0) && live.lowLatencyBypassedLatency (1, 0) > 0 && live.lowLatencyBypassedCount() >= 1;
  3307. const auto untouched = live.getSong().mixer[1].effects[0].enabled && lynx::ProjectFile::toJson (live.getSong()) == saved;
  3308. // monitoring leaves "On" (nothing armed): the effect returns
  3309. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::whenArmed; });
  3310. const auto released = live.getLatencySamples() == before && ! live.isSlotLowLatencyBypassed (1, 0);
  3311. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::on; });
  3312. const auto again = live.getLatencySamples() == during && live.isSlotLowLatencyBypassed (1, 0);
  3313. o.lowLatencyRecording = false;
  3314. live.setRecordOptions (o);
  3315. lowLatencyOk = before > 0 && idle && during < before && marked && untouched && released && again
  3316. && live.getLatencySamples() == before && live.lowLatencyBypassedCount() == 0;
  3317. }
  3318. // The Browser's "Preview in time" (round 190aq): a loop whose name gives its tempo is stretched to the project's
  3319. // and starts on the beat; a one-shot plays as it always did; off, nothing changes
  3320. bool previewInTimeOk = false;
  3321. double previewPrepareMs = 0.0;
  3322. {
  3323. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-preview");
  3324. dir.deleteRecursively();
  3325. dir.createDirectory();
  3326. auto writeWav = [&dir] (const juce::String& name, int frames, bool loop) {
  3327. const auto wav = dir.getChildFile (name);
  3328. juce::WavAudioFormat format;
  3329. juce::AudioBuffer<float> audio (1, frames);
  3330. for (int i = 0; i < frames; ++i) // a click on every beat of 120 BPM over a tone, or a decaying hit
  3331. audio.setSample (0, i, loop ? (i % 24000 < 400 ? 0.8f : 0.0f) + 0.1f * std::sin (0.02f * (float) i)
  3332. : 0.6f * std::exp (-(float) i / 2000.0f) * std::sin (0.05f * (float) i));
  3333. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  3334. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  3335. {
  3336. out.release();
  3337. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  3338. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  3339. }
  3340. return wav;
  3341. };
  3342. const auto loop = writeWav ("selftest loop 120 bpm.wav", 96000, true); // 4 beats at 120 BPM
  3343. const auto hit = writeWav ("selftest hit.wav", 14400, false); // 0.3 s
  3344. lynx::AudioEngine player (false);
  3345. const auto projectBpm = player.getTransport().bpm.load();
  3346. // off (FL's preview): nothing is prepared, the file plays as it is
  3347. player.previewFile (loop);
  3348. const auto offOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  3349. player.setPreviewInTime (true);
  3350. player.previewFile (hit); // a one-shot: as it always played, at once
  3351. const auto hitOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  3352. player.previewFile (loop);
  3353. const auto queued = player.getPreviewTiming().pending || std::abs (projectBpm - 120.0) < 0.2;
  3354. player.finishPreviewJobs();
  3355. const auto timing = player.getPreviewTiming();
  3356. previewPrepareMs = player.getLastPreviewPrepareMs();
  3357. const auto wanted = lynx::previewtempo::stretchRatio (120.0, projectBpm);
  3358. const auto stretchedOk = timing.inTime && ! timing.pending && timing.source == lynx::previewtempo::Source::name
  3359. && std::abs (timing.fileBpm - 120.0) < 1.0e-9 && std::abs (timing.ratio - wanted) < 1.0e-12
  3360. && std::abs ((double) timing.frames - 96000.0 * wanted) < 96000.0 * 0.01;
  3361. // the second click on the same file has its stretch ready
  3362. player.previewFile (loop);
  3363. const auto cachedOk = ! player.getPreviewTiming().pending && player.getPreviewTiming().inTime && player.getPreviewTiming().frames == timing.frames;
  3364. player.previewFile ({});
  3365. const auto stoppedOk = ! player.getPreviewTiming().inTime && player.getPreviewInTimeProgress() < 0.0;
  3366. // the start: on the next heard beat while the transport plays (sample exact), at once when it is stopped
  3367. auto firstSample = [] (bool playing, double startTick, int latency) {
  3368. lynx::Transport transport;
  3369. transport.sampleRate.store (48000.0);
  3370. transport.bpm.store (120.0); // 0.04 ticks per sample
  3371. transport.playing.store (playing);
  3372. transport.positionTicks.store (startTick);
  3373. lynx::PreviewPlayer p;
  3374. p.prepareToPlay (48000.0, 512);
  3375. p.setTransport (&transport);
  3376. p.setSyncLatency (latency);
  3377. auto dc = std::make_shared<lynx::SampleData>();
  3378. dc->sampleRate = 48000.0;
  3379. dc->left.assign (48000, 0.5f);
  3380. p.playBrowser (dc, 1.0f, true);
  3381. juce::AudioBuffer<float> block (2, 512);
  3382. juce::MidiBuffer midi;
  3383. for (int done = 0; done < 48000; done += 512)
  3384. {
  3385. p.processBlock (block, midi);
  3386. for (int i = 0; i < 512; ++i)
  3387. if (block.getSample (0, i) != 0.0f)
  3388. return done + i;
  3389. if (playing)
  3390. transport.positionTicks.store (transport.positionTicks.load() + 512 * transport.ticksPerSample());
  3391. }
  3392. return -1;
  3393. };
  3394. const auto beatOk = firstSample (true, 480.0, 0) == 12000 // half a beat to go: 480 ticks / 0.04
  3395. && firstSample (true, 480.0, 100) == 12100 // the song is heard 100 samples late (PDC)
  3396. && firstSample (true, 960.0, 0) == 0 // on a beat: now
  3397. && firstSample (false, 480.0, 0) == 0; // stopped: a free start
  3398. previewInTimeOk = loop.existsAsFile() && hit.existsAsFile() && offOk && hitOk && queued && stretchedOk && cachedOk && stoppedOk && beatOk;
  3399. dir.deleteRecursively();
  3400. }
  3401. // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
  3402. // original reference byte for byte (.flp record and LYNX plugin state)
  3403. bool substituteOk = false;
  3404. {
  3405. auto song = lynx::Song::makeDefault();
  3406. lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
  3407. vv.format = lynx::ForeignPlugin::Format::vst3;
  3408. const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
  3409. std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
  3410. vv.hasClassId = true;
  3411. vv.name = "ValhallaVintageVerb";
  3412. vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
  3413. for (int i = 0; i < 777; ++i)
  3414. vv.state.push_back ((std::uint8_t) (i * 13 + 1));
  3415. lynx::EffectSlot fromFlp;
  3416. fromFlp.kind = lynx::EffectKind::plugin;
  3417. fromFlp.plugin.foreign = vv;
  3418. lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
  3419. fromLynx.kind = lynx::EffectKind::plugin;
  3420. fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
  3421. fromLynx.plugin.name = "FabFilter Pro-Q 3";
  3422. fromLynx.plugin.state = "AAECAwQFBgcICQ==";
  3423. const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
  3424. song.mixer[1].effects = { fromFlp, fromLynx };
  3425. const auto substitutesOn = lynx::pluginSubstitutesEnabled();
  3426. const auto changed = offline.getPluginHost().applySubstitutes (song);
  3427. auto& fx = song.mixer[1].effects;
  3428. // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
  3429. const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
  3430. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3431. substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
  3432. && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
  3433. && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
  3434. && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
  3435. && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
  3436. }
  3437. // undo/redo
  3438. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  3439. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  3440. offline.undo();
  3441. const auto afterUndo = offline.getSong().bpm;
  3442. offline.redo();
  3443. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  3444. && offline.isModified();
  3445. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  3446. // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
  3447. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  3448. {
  3449. auto o = offline.getRecordOptions();
  3450. o.mode = lynx::RecordMode::overdub;
  3451. offline.setRecordOptions (o);
  3452. }
  3453. offline.setRecording (true);
  3454. offline.play();
  3455. offline.getTransport().positionTicks.store (960.0);
  3456. offline.sendLiveNote (2, 72, 0.9f, true, true);
  3457. offline.getTransport().positionTicks.store (1920.0);
  3458. offline.sendLiveNote (2, 72, 0.0f, false, true);
  3459. offline.setRecording (false);
  3460. offline.stop();
  3461. const auto& recorded = offline.getSong().patterns[0].notes;
  3462. const auto recordOk = recorded.size() == notesBefore + 1
  3463. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  3464. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  3465. });
  3466. offline.undo();
  3467. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  3468. // FL's Tools › Cancel recording (round 187a): the pass's notes go, an edit made before it stays, recording turns
  3469. // off and playback goes on; nothing to redo
  3470. bool cancelRecordOk = false;
  3471. {
  3472. offline.editSong ([] (lynx::Song& s) { s.bpm = 123.0; });
  3473. const auto notesThen = offline.getSong().patterns[0].notes.size();
  3474. offline.setRecording (true);
  3475. offline.play();
  3476. offline.getTransport().positionTicks.store (960.0);
  3477. offline.sendLiveNote (2, 74, 0.9f, true, true);
  3478. offline.getTransport().positionTicks.store (1920.0);
  3479. offline.sendLiveNote (2, 74, 0.0f, false, true);
  3480. offline.sendLiveNote (2, 76, 0.9f, true, true); // (still held when the pass is cancelled)
  3481. const auto cancelled = offline.cancelRecording();
  3482. cancelRecordOk = cancelled && ! offline.isRecording() && offline.getTransport().playing.load()
  3483. && offline.getSong().patterns[0].notes.size() == notesThen && offline.getSong().bpm == 123.0 && ! offline.canRedo()
  3484. && ! offline.cancelRecording(); // (not recording: nothing to cancel)
  3485. offline.sendLiveNote (2, 76, 0.0f, false, false);
  3486. offline.stop();
  3487. }
  3488. // MIDI: exporting the pattern and importing it back gives the same notes
  3489. bool midiOk = false;
  3490. {
  3491. auto source = lynx::Song::makeDefault();
  3492. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  3493. source.patterns[0].sortNotes();
  3494. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  3495. juce::String midiError;
  3496. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  3497. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  3498. midiFile.deleteFile();
  3499. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  3500. && std::abs (song->bpm - source.bpm) < 0.01)
  3501. {
  3502. midiOk = true;
  3503. const auto& a = source.patterns[0].notes;
  3504. const auto& b = song->patterns[0].notes;
  3505. for (std::size_t i = 0; i < a.size(); ++i)
  3506. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  3507. }
  3508. }
  3509. // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
  3510. // finds its sample inside the extracted folder
  3511. bool packageOk = false;
  3512. {
  3513. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
  3514. dir.deleteRecursively();
  3515. dir.getChildFile ("src").createDirectory();
  3516. const auto wav = dir.getChildFile ("src/hit.wav");
  3517. {
  3518. juce::WavAudioFormat format;
  3519. juce::AudioBuffer<float> hit (1, 480);
  3520. for (int i = 0; i < 480; ++i)
  3521. hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
  3522. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  3523. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  3524. {
  3525. out.release();
  3526. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  3527. writer->writeFromAudioSampleBuffer (hit, 0, 480);
  3528. }
  3529. }
  3530. auto source = lynx::Song::makeDefault();
  3531. lynx::ChannelDef c;
  3532. c.name = "Hit";
  3533. c.instrument = lynx::InstrumentKind::sampler;
  3534. c.samplePath = wav.getFullPathName().toStdString();
  3535. source.channels.push_back (c);
  3536. lynx::ProjectPackage::Result packed;
  3537. juce::String packageError;
  3538. const auto zip = dir.getChildFile ("Beat.zip");
  3539. if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
  3540. {
  3541. const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
  3542. const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
  3543. if (song && ! song->channels.empty())
  3544. {
  3545. const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
  3546. packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
  3547. }
  3548. }
  3549. dir.deleteRecursively();
  3550. }
  3551. // D#92, round 180a: a non-ASCII folder and a dotted name save and load back; an unwritable place says so, and a
  3552. // relative path resolves as the start-up argument does
  3553. bool projectSaveOk = false;
  3554. {
  3555. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-save180a");
  3556. dir.deleteRecursively();
  3557. const auto folder = dir.getChildFile (juce::String::fromUTF8 ("M\xc3\xbasica nova"));
  3558. folder.createDirectory();
  3559. const auto named = lynx::ProjectFile::withProjectExtension (folder.getChildFile (juce::String::fromUTF8 ("Can\xc3\xa7\xc3\xa3o.v2")));
  3560. auto song = lynx::Song::makeDefault();
  3561. lynx::Note note;
  3562. note.length = 240;
  3563. note.key = 64;
  3564. song.patterns[0].notes.push_back (note);
  3565. juce::String error, blockedError;
  3566. const auto again = lynx::ProjectFile::save (song, named, error) ? lynx::ProjectFile::load (named, error) : std::nullopt;
  3567. const auto blocker = dir.getChildFile ("a file");
  3568. blocker.replaceWithText ("x");
  3569. const auto cwd = juce::File::getCurrentWorkingDirectory();
  3570. folder.setAsCurrentWorkingDirectory();
  3571. const auto relative = juce::File::getCurrentWorkingDirectory().getChildFile (named.getFileName());
  3572. cwd.setAsCurrentWorkingDirectory();
  3573. projectSaveOk = named.getFileName().endsWith (".v2.lynx") && again && again->patterns[0].notes.size() == song.patterns[0].notes.size()
  3574. && relative == named && ! lynx::ProjectFile::save (song, blocker.getChildFile ("x.lynx"), blockedError)
  3575. && blockedError.isNotEmpty() && lynx::ProjectFile::withProjectExtension (named) == named;
  3576. dir.deleteRecursively();
  3577. }
  3578. // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
  3579. // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
  3580. juce::String sessionResult = "ERROR";
  3581. {
  3582. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
  3583. dir.deleteRecursively();
  3584. dir.getChildFile ("src").createDirectory();
  3585. const auto wav = dir.getChildFile ("src/hit.wav");
  3586. {
  3587. juce::WavAudioFormat format;
  3588. juce::AudioBuffer<float> hit (1, 4800);
  3589. for (int i = 0; i < 4800; ++i)
  3590. hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
  3591. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  3592. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  3593. {
  3594. out.release();
  3595. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  3596. writer->writeFromAudioSampleBuffer (hit, 0, 4800);
  3597. }
  3598. }
  3599. auto host = lynx::Song::makeDefault();
  3600. host.mode = lynx::PlayMode::song;
  3601. const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
  3602. wav.copyFileTo (copyOfWav);
  3603. for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
  3604. {
  3605. lynx::ChannelDef c;
  3606. c.name = name;
  3607. c.instrument = lynx::InstrumentKind::sampler;
  3608. c.samplePath = file.getFullPathName().toStdString();
  3609. host.channels.push_back (c);
  3610. }
  3611. const auto hitChannel = (int) host.channels.size() - 2;
  3612. lynx::Note hitNote;
  3613. hitNote.channel = hitChannel;
  3614. hitNote.length = 480;
  3615. host.patterns[0].notes.push_back (hitNote);
  3616. host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.meter()), 0 });
  3617. lynx::uids::normalize (host);
  3618. const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
  3619. juce::String e;
  3620. std::vector<lynx::sessionpack::Rendered> rendered;
  3621. // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
  3622. const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
  3623. const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
  3624. && rendered.size() == 1 && rendered[0].standIns.size() == 2
  3625. && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
  3626. if (renderedOk)
  3627. lynx::sessionpack::apply (host, rendered);
  3628. lynx::sessionpack::Manifest m;
  3629. m.projectName = "Selftest";
  3630. m.from = *host.session.find (lynx::session::hostTag);
  3631. m.to = *host.session.find (2);
  3632. lynx::sessionpack::WriteResult written;
  3633. const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
  3634. const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
  3635. && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
  3636. auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
  3637. bool openOk = false, mergeOk = false;
  3638. if (opened && opened->corrupt.isEmpty())
  3639. {
  3640. const auto& g = opened->song;
  3641. const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
  3642. openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
  3643. && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
  3644. && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
  3645. // the guest adds a channel and a pattern of his own, sends his part back
  3646. auto copy = g;
  3647. lynx::ChannelDef mine;
  3648. mine.name = "Ana's hit";
  3649. mine.instrument = lynx::InstrumentKind::sampler;
  3650. mine.samplePath = sample.getFullPathName().toStdString();
  3651. copy.channels.push_back (mine);
  3652. lynx::Pattern p;
  3653. p.name = "Ana";
  3654. lynx::Note note;
  3655. note.channel = (int) copy.channels.size() - 1;
  3656. note.length = 240;
  3657. note.key = 64;
  3658. p.notes.push_back (note);
  3659. copy.patterns.push_back (p);
  3660. lynx::uids::normalize (copy);
  3661. // its uids survive a save and a load
  3662. const auto saved = dir.getChildFile ("guest.lynx");
  3663. auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
  3664. lynx::sessionpack::Manifest back;
  3665. back.part = true;
  3666. back.from = *copy.session.self();
  3667. const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
  3668. lynx::sessionpack::WriteResult partWritten;
  3669. auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
  3670. ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
  3671. : false;
  3672. auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
  3673. if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
  3674. {
  3675. const auto report = lynx::parts::merge (host, partOpened->song, 2);
  3676. const auto& added = host.channels.back();
  3677. mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
  3678. && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
  3679. && host.channels[(std::size_t) hitChannel].name == "Hit";
  3680. }
  3681. }
  3682. // a crafted package whose project points at a file elsewhere on this computer: opening it must not
  3683. // reach that file, or merging would copy it into the project and the next package would send it on
  3684. if (mergeOk)
  3685. {
  3686. const auto secret = dir.getChildFile ("secret.wav");
  3687. wav.copyFileTo (secret);
  3688. auto evil = lynx::Song::makeDefault();
  3689. lynx::ChannelDef c;
  3690. c.instrument = lynx::InstrumentKind::sampler;
  3691. c.samplePath = secret.getFullPathName().toStdString();
  3692. evil.channels.push_back (c);
  3693. lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
  3694. keys.instrument = lynx::InstrumentKind::flkeys;
  3695. keys.zones.push_back ({});
  3696. keys.zones.back().path = c.samplePath;
  3697. evil.channels.push_back (keys);
  3698. lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
  3699. patch.instrument = lynx::InstrumentKind::patcher;
  3700. patch.patcher.nodes.resize (2);
  3701. patch.patcher.nodes[0].generator = true;
  3702. patch.patcher.nodes[0].channel = c;
  3703. patch.patcher.nodes[1].effect.samplePath = c.samplePath;
  3704. evil.channels.push_back (patch);
  3705. evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
  3706. const auto evilProject = dir.getChildFile ("evil.lynx");
  3707. lynx::sessionpack::Manifest em;
  3708. em.part = true;
  3709. juce::ZipFile::Builder b;
  3710. const auto json = lynx::sessionpack::manifestToJson (em);
  3711. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  3712. const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
  3713. bool zipped = false;
  3714. if (lynx::ProjectFile::save (evil, evilProject, e))
  3715. {
  3716. b.addFile (evilProject, 0, "project.lynx");
  3717. juce::FileOutputStream out (evilPack);
  3718. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  3719. }
  3720. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
  3721. const auto media = dir.getChildFile ("Session media/Evil");
  3722. mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
  3723. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  3724. return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
  3725. || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
  3726. })
  3727. && evilOpened->song.channels.back().patcher.nodes.size() == 2
  3728. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
  3729. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
  3730. && evilOpened->song.mixer[1].recordTo.empty()
  3731. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  3732. if (! mergeOk && e.isEmpty())
  3733. e = "a received package reached a file outside it";
  3734. }
  3735. // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
  3736. // media entry outside the package (it must not even be read: "/dev/zero" would never end)
  3737. if (mergeOk)
  3738. {
  3739. const auto secret = dir.getChildFile ("secret.wav");
  3740. const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
  3741. const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
  3742. const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
  3743. auto evil = lynx::Song::makeDefault();
  3744. for (const auto& path : { climb, dotted })
  3745. {
  3746. lynx::ChannelDef c;
  3747. c.instrument = lynx::InstrumentKind::sampler;
  3748. c.samplePath = path.toStdString();
  3749. evil.channels.push_back (c);
  3750. }
  3751. juce::MemoryBlock secretBytes;
  3752. secret.loadFileAsData (secretBytes);
  3753. lynx::sessionpack::Manifest em;
  3754. em.part = true;
  3755. em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
  3756. "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
  3757. const auto evilProject = dir.getChildFile ("evil2.lynx");
  3758. juce::ZipFile::Builder b;
  3759. const auto json = lynx::sessionpack::manifestToJson (em);
  3760. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  3761. const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
  3762. bool zipped = false;
  3763. if (lynx::ProjectFile::save (evil, evilProject, e))
  3764. {
  3765. b.addFile (evilProject, 0, "project.lynx");
  3766. juce::FileOutputStream out (evilPack);
  3767. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  3768. }
  3769. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
  3770. const auto media = dir.getChildFile ("Session media/Evil2");
  3771. mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
  3772. && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
  3773. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  3774. const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
  3775. return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
  3776. })
  3777. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  3778. if (! mergeOk && e.isEmpty())
  3779. e = "a received package climbed out of its folder";
  3780. }
  3781. if (! packOk && e.isEmpty())
  3782. e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
  3783. + written.missing.joinIntoString (";");
  3784. sessionResult = mergeOk ? juce::String ("OK")
  3785. : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
  3786. dir.deleteRecursively();
  3787. }
  3788. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  3789. juce::String wavpack = "NO_FL";
  3790. {
  3791. const auto roots = lynx::findFlStudioRoots();
  3792. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  3793. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  3794. if (! found.isEmpty())
  3795. {
  3796. lynx::SampleLibrary library;
  3797. const auto sample = library.load (found.getFirst().getFullPathName());
  3798. float peakWv = 0.0f;
  3799. if (sample != nullptr)
  3800. for (std::size_t i = 0; i < sample->frames(); ++i)
  3801. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  3802. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  3803. }
  3804. }
  3805. // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
  3806. const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
  3807. // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
  3808. // generator one plays through the rack
  3809. bool patcherOk = false;
  3810. {
  3811. auto song = lynx::Song::makeDefault();
  3812. song.mixer.resize (4);
  3813. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  3814. lynx::PatchNode reverb, gain;
  3815. reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
  3816. reverb.label = "Room";
  3817. reverb.x = 120.5f;
  3818. reverb.y = 40.0f;
  3819. gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  3820. gain.effect.enabled = false;
  3821. slot.patcher.nodes = { reverb, gain };
  3822. lynx::PatchWire a, b, c, control;
  3823. a.to = 0;
  3824. b.from = 0, b.to = 1, b.gain = 0.5f;
  3825. c.from = 1;
  3826. control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
  3827. slot.patcher.wires = { a, b, c, control };
  3828. slot.patcher.outputTracks = { 3 };
  3829. song.mixer[1].effects = { slot };
  3830. lynx::ChannelDef ch;
  3831. ch.name = "Patched";
  3832. ch.instrument = lynx::InstrumentKind::patcher;
  3833. lynx::PatchNode synth;
  3834. synth.generator = true;
  3835. synth.channel.instrument = lynx::InstrumentKind::synth;
  3836. synth.channel.name = "Synth";
  3837. ch.patcher.nodes = { synth };
  3838. lynx::PatchWire notes, out;
  3839. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  3840. out.from = 0;
  3841. ch.patcher.wires = { notes, out };
  3842. // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
  3843. lynx::PatchNode midiOutNode;
  3844. midiOutNode.generator = true;
  3845. midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
  3846. lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
  3847. ch.patcher.nodes.push_back (midiOutNode);
  3848. lynx::PatchWire portIn, portOut;
  3849. portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
  3850. portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
  3851. portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
  3852. ch.patcher.wires.push_back (portIn);
  3853. ch.patcher.wires.push_back (portOut);
  3854. ch.patcher.fromMidiPorts = { 2, 7 };
  3855. ch.patcher.toMidiPorts = { 9, 11 };
  3856. ch.patcher.fromNotesHidden = true;
  3857. song.channels.push_back (ch);
  3858. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3859. patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
  3860. && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
  3861. && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
  3862. && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
  3863. && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
  3864. && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
  3865. && back->channels.back().patcher.nodes[0].generator
  3866. && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
  3867. && back->channels.back().patcher.wires == ch.patcher.wires;
  3868. }
  3869. // Round 183c, Racks: (1) a plain Patcher's stored JSON loads and saves back byte for byte and never holds a
  3870. // "rack" key (FL's Patcher is untouched); (2) an Audio Effect Rack slot and an Instrument Rack channel survive save /
  3871. // load with their chains, zones, macros, mappings, variations and compiled cables
  3872. juce::String rackResult = "OK";
  3873. {
  3874. lynx::MixerTrack plain;
  3875. plain.name = "Plain Patcher";
  3876. auto fx = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  3877. lynx::PatchNode a, b;
  3878. a.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  3879. a.label = "A";
  3880. a.x = 120.5f;
  3881. b.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  3882. b.effect.enabled = false;
  3883. fx.patcher.nodes = { a, b };
  3884. lynx::PatchWire w1, w2, w3, wc;
  3885. w1.to = 0;
  3886. w2.from = 0, w2.to = 1, w2.gain = 0.5f;
  3887. w3.from = 1;
  3888. wc.kind = lynx::PatchWire::Kind::control, wc.from = 0, wc.to = 1, wc.toPort = 0, wc.curve = { 0.0f, 0.25f, 1.0f };
  3889. fx.patcher.wires = { w1, w2, w3, wc };
  3890. lynx::SurfaceControl knob;
  3891. knob.name = "Drive";
  3892. knob.value = 0.25f;
  3893. fx.patcher.surface = { knob };
  3894. lynx::PatchParam pp;
  3895. pp.node = 0, pp.param = 1, pp.name = "Balance";
  3896. fx.patcher.published = { pp };
  3897. plain.effects = { fx };
  3898. const auto first = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (plain), true);
  3899. const auto again = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (first))), true);
  3900. if (first != again || first.contains ("\"rack\"") || first.contains ("rackMixer"))
  3901. rackResult = "ERROR plain Patcher changed";
  3902. auto song = lynx::Song::makeDefault();
  3903. song.mixer.resize (3);
  3904. auto rackSlot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  3905. auto& doc = rackSlot.patcher;
  3906. lynx::PatchNode u;
  3907. u.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  3908. const auto n0 = lynx::rack::addDevice (doc, 0, u);
  3909. lynx::rack::addChain (doc, "Wet");
  3910. lynx::rack::addDevice (doc, 1, u);
  3911. doc.rack[0].chains[1].select = { 10, 90, 30, 70 };
  3912. lynx::rack::setChainPan (doc, 1, -0.5f);
  3913. lynx::RackMapping m;
  3914. m.node = n0, m.param = 0, m.min = 0.2f, m.max = 0.9f;
  3915. lynx::rack::map (doc, 0, m);
  3916. lynx::RackMapping v;
  3917. v.target = lynx::RackMapping::Target::chainVolume, v.chain = 1, v.min = 0.0f, v.max = lynx::rack::unityVolume;
  3918. lynx::rack::map (doc, 1, v);
  3919. lynx::rack::setMacro (doc, 0, 64.0f);
  3920. lynx::rack::storeVariation (doc);
  3921. lynx::rack::setMacro (doc, 0, 100.0f);
  3922. lynx::rack::storeVariation (doc);
  3923. doc.rack[0].morphOn = true, doc.rack[0].morphA = 0, doc.rack[0].morphB = 1;
  3924. lynx::rack::setMorph (doc, 0.5f);
  3925. lynx::rack::compile (doc);
  3926. song.mixer[1].effects = { rackSlot };
  3927. lynx::ChannelDef inst;
  3928. inst.name = "Instrument Rack";
  3929. inst.instrument = lynx::InstrumentKind::patcher;
  3930. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  3931. lynx::PatchNode synth;
  3932. synth.generator = true;
  3933. synth.channel.instrument = lynx::InstrumentKind::synth;
  3934. synth.channel.name = "Synth";
  3935. lynx::rack::addDevice (inst.patcher, 0, synth);
  3936. inst.patcher.rack[0].chains[0].velocity = { 1, 127, 64, 127 };
  3937. lynx::rack::compile (inst.patcher);
  3938. song.channels.push_back (inst);
  3939. const auto json = lynx::ProjectFile::toJson (song);
  3940. const auto back = lynx::ProjectFile::fromJson (json, error);
  3941. // (the devices' parameters are stored to 4 decimals: the documents are compared as stored, the rack exactly)
  3942. const auto loaded = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1;
  3943. const auto& got = loaded ? back->mixer[1].effects[0].patcher : doc;
  3944. if (! loaded)
  3945. rackResult = "ERROR rack slot not loaded";
  3946. else if (got.rack != doc.rack)
  3947. rackResult = "ERROR rack model";
  3948. else if (got.wires != doc.wires)
  3949. rackResult = "ERROR rack cables";
  3950. else if (got.nodes.size() != doc.nodes.size())
  3951. rackResult = "ERROR rack devices";
  3952. else if (back->channels.back().patcher.rack != inst.patcher.rack || back->channels.back().patcher.wires != inst.patcher.wires
  3953. || back->channels.back().patcher.zones != inst.patcher.zones || back->channels.back().patcher.nodes.size() != inst.patcher.nodes.size())
  3954. rackResult = "ERROR instrument rack";
  3955. // the slot's insert as stored, once more: the same text (the stored form is stable)
  3956. else if (const auto once = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (back->mixer[1]), true);
  3957. once != juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (once))), true))
  3958. rackResult = "ERROR rack stored form not stable";
  3959. }
  3960. // Round 190ec, Drum Rack: pads (Receive / Play / Choke / Audio To / sends), return chains and the views survive save /
  3961. // load with their compiled zones and cables
  3962. if (rackResult == "OK")
  3963. {
  3964. lynx::Song song;
  3965. song.mixer.resize (2);
  3966. lynx::ChannelDef ch;
  3967. ch.name = "Drums";
  3968. ch.instrument = lynx::InstrumentKind::patcher;
  3969. ch.patcher = lynx::rack::makeDrumRack();
  3970. lynx::PatchNode synth;
  3971. synth.generator = true;
  3972. synth.channel.instrument = lynx::InstrumentKind::synth;
  3973. const auto kick = lynx::rack::addPad (ch.patcher, 36, "Kick", synth);
  3974. const auto hat = lynx::rack::addPad (ch.patcher, 42, "Hat", synth);
  3975. lynx::rack::addPad (ch.patcher, -1, "Every note");
  3976. lynx::rack::addReturn (ch.patcher, "A Verb");
  3977. lynx::rack::setPlay (ch.patcher, kick, 64);
  3978. lynx::rack::setChoke (ch.patcher, hat, 2);
  3979. lynx::rack::setSend (ch.patcher, hat, 0, 0.25f, false);
  3980. lynx::rack::setAudioTo (ch.patcher, kick, 0);
  3981. lynx::rack::rackOf (ch.patcher)->showIO = true;
  3982. lynx::rack::rackOf (ch.patcher)->padScroll = 17;
  3983. song.channels.push_back (ch);
  3984. juce::String error;
  3985. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  3986. const auto& got = back && ! back->channels.empty() ? back->channels.back().patcher : lynx::PatcherDoc {};
  3987. if (! back || ! lynx::rack::isDrumRack (got))
  3988. rackResult = "ERROR drum rack not loaded";
  3989. else if (got.rack != ch.patcher.rack)
  3990. rackResult = "ERROR drum rack model";
  3991. else if (got.zones != ch.patcher.zones || got.wires != ch.patcher.wires)
  3992. rackResult = "ERROR drum rack cables";
  3993. }
  3994. // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
  3995. // the instruments play through the rack
  3996. juce::String nativesResult = "OK";
  3997. int nativesMade = 0, nativesSilent = 0;
  3998. {
  3999. auto song = lynx::Song::makeDefault();
  4000. song.channels.clear();
  4001. song.patterns[0].notes.clear();
  4002. song.mixer.resize (3);
  4003. const auto& fl = lynx::flStudioAccess();
  4004. for (const auto& e : lynx::natives::instrumentEngines())
  4005. if (lynx::natives::available (e, fl))
  4006. if (auto c = lynx::natives::makeChannel (e.kind, fl))
  4007. {
  4008. c->mixerTrack = 1;
  4009. song.channels.push_back (*c);
  4010. }
  4011. for (const auto& e : lynx::natives::effectEngines())
  4012. if (auto fx = lynx::natives::makeSlot (e.kind, fl))
  4013. song.mixer[2].effects.push_back (*fx);
  4014. nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
  4015. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  4016. auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
  4017. && back->mixer[2].effects.size() == song.mixer[2].effects.size();
  4018. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  4019. {
  4020. const auto& a = song.channels[i];
  4021. const auto& b = back->channels[i];
  4022. same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
  4023. && a.modelParams.size() == b.modelParams.size();
  4024. if (! same)
  4025. nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
  4026. }
  4027. for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
  4028. {
  4029. const auto& a = song.mixer[2].effects[i];
  4030. const auto& b = back->mixer[2].effects[i];
  4031. same = a.kind == b.kind && a.state == b.state;
  4032. for (std::size_t p = 0; same && p < a.params.size(); ++p)
  4033. same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
  4034. if (! same)
  4035. nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
  4036. }
  4037. if (! back)
  4038. nativesResult = "ERROR " + error;
  4039. // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
  4040. // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
  4041. // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
  4042. const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
  4043. {
  4044. juce::WavAudioFormat format;
  4045. juce::AudioBuffer<float> tone (1, 48000);
  4046. for (int i = 0; i < 48000; ++i)
  4047. tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
  4048. toneWav.deleteFile();
  4049. std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
  4050. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  4051. {
  4052. out.release();
  4053. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  4054. writer->writeFromAudioSampleBuffer (tone, 0, 48000);
  4055. }
  4056. }
  4057. juce::StringArray silentNames;
  4058. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  4059. {
  4060. auto one = song;
  4061. one.channels = { song.channels[i] };
  4062. one.channels[0].mixerTrack = 1;
  4063. const auto kind = song.channels[i].instrument;
  4064. // A new Fruity Slicer has no sample and no slices, and FL's is silent then too (round 180c), so it is
  4065. // not one of the engines that must sound here (Linux / macOS CI: "SILENT 1 [Fruity Slicer]", 0.1.25)
  4066. if (kind == lynx::InstrumentKind::fruityslicer && one.channels[0].samplePath.empty())
  4067. continue;
  4068. if (kind == lynx::InstrumentKind::slicex && one.channels[0].samplePath.empty()) // (the same: no sample on its decks yet)
  4069. continue;
  4070. if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
  4071. one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
  4072. one.mixer[2].effects.clear();
  4073. // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
  4074. // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
  4075. auto key = 60;
  4076. if (kind == lynx::InstrumentKind::drumaxx)
  4077. {
  4078. const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
  4079. key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
  4080. }
  4081. // FPC plays its pads' keys; a kit without a sample (FL's "Empty" kit: no FL Studio on this PC) is silent
  4082. // in FL too (round 190q)
  4083. if (kind == lynx::InstrumentKind::fpc)
  4084. {
  4085. const auto pads = lynx::fpcChannelPads (one.channels[0]);
  4086. if (pads.empty())
  4087. continue;
  4088. key = pads.front().key;
  4089. }
  4090. one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
  4091. lynx::AudioEngine player (false);
  4092. player.setSong (std::move (one));
  4093. player.dispatchPendingMessages();
  4094. if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
  4095. {
  4096. ++nativesSilent;
  4097. silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
  4098. }
  4099. }
  4100. toneWav.deleteFile();
  4101. if (nativesSilent > 0 && nativesResult == "OK")
  4102. nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
  4103. }
  4104. const auto nativesOk = nativesResult == "OK";
  4105. // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
  4106. // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
  4107. // insert 2 (muted: silent); never in an export
  4108. juce::String metronomeResult = "OK";
  4109. int metronomeFlSounds = 0;
  4110. float metronomeMaster = 0.0f;
  4111. {
  4112. const auto& flData = lynx::flStudioAccess().roots.data;
  4113. const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
  4114. for (const auto& s : sounds)
  4115. metronomeFlSounds += s.fromFl ? 1 : 0;
  4116. auto renderClick = [] (int track, bool muteInsert, bool include) {
  4117. auto song = lynx::Song::makeDefault();
  4118. song.channels.clear();
  4119. song.playlist.clear();
  4120. for (auto& p : song.patterns)
  4121. p.notes.clear();
  4122. song.mixer[0].effects.clear(); // (the default Master limiter)
  4123. song.mixer[2].muted = muteInsert;
  4124. lynx::AudioEngine player (false);
  4125. player.setSong (std::move (song));
  4126. player.dispatchPendingMessages();
  4127. auto& t = player.getTransport();
  4128. t.metronome = true;
  4129. t.metronomeSound = 1; // Tick
  4130. t.metronomeTrack = track;
  4131. lynx::AudioEngine::RenderOptions o;
  4132. o.seconds = 0.25;
  4133. o.sampleRate = 44100.0;
  4134. o.pluginWarmUp = false;
  4135. o.includeMetronome = include;
  4136. return player.renderOffline (o);
  4137. };
  4138. metronomeMaster = renderClick (0, false, true);
  4139. const auto insert = renderClick (2, false, true);
  4140. const auto muted = renderClick (2, true, true);
  4141. const auto exported = renderClick (0, false, false);
  4142. // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
  4143. const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
  4144. if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
  4145. metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
  4146. else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
  4147. metronomeResult = "ERROR insert " + juce::String (insert, 4);
  4148. else if (muted > 1.0e-4f)
  4149. metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
  4150. else if (exported > 1.0e-4f)
  4151. metronomeResult = "ERROR in export " + juce::String (exported, 4);
  4152. }
  4153. const auto metronomeOk = metronomeResult == "OK";
  4154. // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
  4155. const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
  4156. // issue #134 (round 190c): the output device, its rate and its buffer changed under a playing project, on
  4157. // stand-in devices (a short run; --devicechangetest plays every instrument and effect)
  4158. const auto deviceChange = lynx::AudioEngine::deviceChangeSelfTest (10, false);
  4159. // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
  4160. // through it, the invite code's keys)
  4161. const auto liveResult = lynx::livetest::selfTest (&rich);
  4162. // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
  4163. // mask...), at odd values, through a project save and reload: the same floats back
  4164. juce::String effectParamsResult = "OK";
  4165. {
  4166. auto song = lynx::Song::makeDefault();
  4167. song.mixer.resize (1);
  4168. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  4169. {
  4170. const auto kind = (lynx::EffectKind) k;
  4171. if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
  4172. continue;
  4173. auto fx = lynx::makeEffectSlot (kind);
  4174. for (std::size_t i = 0; i < fx.params.size(); ++i)
  4175. {
  4176. auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
  4177. fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
  4178. }
  4179. if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
  4180. fx.params[3] = 0.0f;
  4181. song.mixer.emplace_back();
  4182. song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
  4183. song.mixer.back().effects.push_back (fx);
  4184. }
  4185. // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
  4186. // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
  4187. {
  4188. auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  4189. for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
  4190. lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
  4191. {
  4192. lynx::PatchNode node;
  4193. node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  4194. if (kind == lynx::EffectKind::peakController)
  4195. node.effect.params[7] = 32750.0f / 65336.0f;
  4196. node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
  4197. patch.patcher.nodes.push_back (node);
  4198. }
  4199. song.mixer.emplace_back();
  4200. song.mixer.back().name = "Patcher";
  4201. song.mixer.back().effects.push_back (patch);
  4202. }
  4203. juce::String why;
  4204. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  4205. if (back && back->mixer.size() == song.mixer.size())
  4206. {
  4207. const auto& a = song.mixer.back().effects[0].patcher.nodes;
  4208. const auto& b = back->mixer.back().effects[0].patcher.nodes;
  4209. for (std::size_t n = 0; n < a.size(); ++n)
  4210. if (n >= b.size() || ! (a[n].effect == b[n].effect))
  4211. effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
  4212. }
  4213. if (! back || back->mixer.size() != song.mixer.size())
  4214. effectParamsResult = "ERROR load " + why;
  4215. else
  4216. for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
  4217. if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
  4218. {
  4219. effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
  4220. break;
  4221. }
  4222. }
  4223. // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
  4224. const auto artResult = lynx::skin::artSelfTest();
  4225. // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
  4226. const auto sidechainResult = lynx::pluginSidechainSelfTest();
  4227. // round 190ap: the Versions panel's list of files, and its labels on disk beside them
  4228. const auto versionsResult = lynx::versionsSelfTest();
  4229. // round 190ap: a project opened with its plugins off creates none of them and saves their settings unchanged
  4230. const auto pluginsOffResult = lynx::pluginsOffSelfTest();
  4231. // round 190cj: a dancer's own native window stays where the stage put it (it drifted off the screen: JUCE
  4232. // moved a transparent child window by the main window's client offset on every repaint)
  4233. juce::String danceWindowDetail;
  4234. const auto danceWindowResult = lynx::danceWindowSelfTest (&danceWindowDetail);
  4235. // issue #161: a click in a panel (a native child window that takes no focus on a click) of an inactive main
  4236. // window activates it (back from another app, Space played nothing until the Browser was clicked)
  4237. const auto clickActivationResult = lynx::nativechild::clickActivationSelfTest();
  4238. // round 177b: automation lanes come back from a project (track, automation, height, folded)
  4239. juce::String lanesResult = "OK";
  4240. {
  4241. auto song = lynx::Song::makeDefault();
  4242. const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
  4243. song.playlistTracks[3].lanes[0].height = 72;
  4244. song.playlistTracks[3].lanesFolded = true;
  4245. // (the same round's clip LFO and modulators ride along)
  4246. auto& lfo = song.automations[(std::size_t) lane].lfo;
  4247. lfo.on = true;
  4248. lfo.level = -40;
  4249. lfo.speed = 30000;
  4250. lfo.flags = 1 | 4;
  4251. lfo.phase = 123456789u;
  4252. lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
  4253. lynx::Modulator mod;
  4254. mod.name = "LFO 1";
  4255. mod.shape = lynx::ModShape::square;
  4256. mod.sync = false;
  4257. mod.hz = 2.5;
  4258. mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  4259. song.modulators.push_back (mod);
  4260. juce::String why;
  4261. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  4262. if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
  4263. || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
  4264. || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
  4265. || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
  4266. lanesResult = "ERROR " + why;
  4267. }
  4268. // round 190cg: the loop switch, folded tracks and the tempo lane's range come back from a project; a project
  4269. // without them loads as before (loop on, nothing folded, the whole range)
  4270. juce::String arrange190cgResult = "OK";
  4271. {
  4272. auto song = lynx::Song::makeDefault();
  4273. juce::String why;
  4274. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  4275. song.loopStart = 960;
  4276. song.loopEnd = 4800;
  4277. song.loopOff = true;
  4278. song.tempoViewLow = 80.0;
  4279. song.tempoViewHigh = 160.0;
  4280. song.playlistTracks.resize (std::max<std::size_t> (song.playlistTracks.size(), 6));
  4281. song.playlistTracks[2].folded = song.playlistTracks[5].folded = true;
  4282. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  4283. if (! plain || plain->loopOff || plain->tempoViewLow != 0.0 || plain->tempoViewHigh != 0.0
  4284. || std::any_of (plain->playlistTracks.begin(), plain->playlistTracks.end(), [] (const lynx::PlaylistTrack& t) { return t.folded; }))
  4285. arrange190cgResult = "ERROR defaults " + why;
  4286. else if (! back || ! back->loopOff || back->loopStart != 960 || back->loopEnd != 4800 || back->loopPlays() || back->tempoViewLow != 80.0
  4287. || back->tempoViewHigh != 160.0 || back->playlistTracks.size() < 6 || ! back->playlistTracks[2].folded
  4288. || ! back->playlistTracks[5].folded || back->playlistTracks[3].folded)
  4289. arrange190cgResult = "ERROR round trip " + why;
  4290. }
  4291. // round 190dr: the Session mixer's sections come back from a project (a project without them: Live's defaults);
  4292. // a device dragged to another track and a Warp switch are one undo step each in a real engine
  4293. juce::String livescr190drResult = "OK";
  4294. {
  4295. auto song = lynx::Song::makeDefault();
  4296. lynx::launcher::ensureGrid (song);
  4297. juce::String why;
  4298. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  4299. song.clipGrid->mixerView.io = false;
  4300. song.clipGrid->mixerView.trackOptions = true;
  4301. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  4302. if (! plain || ! plain->clipGrid || ! (plain->clipGrid->mixerView == lynx::SessionMixerView {}))
  4303. livescr190drResult = "ERROR view defaults " + why;
  4304. else if (! back || ! back->clipGrid || back->clipGrid->mixerView.io || ! back->clipGrid->mixerView.trackOptions || ! back->clipGrid->mixerView.shown)
  4305. livescr190drResult = "ERROR view round trip " + why;
  4306. lynx::AudioEngine e (false);
  4307. e.editSong ([] (lynx::Song& s) {
  4308. if (s.mixer.size() < 4)
  4309. s.mixer.resize (4);
  4310. s.mixer[2].effects.clear();
  4311. s.mixer[3].effects.clear();
  4312. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  4313. {
  4314. lynx::EffectSlot fx;
  4315. fx.kind = kind;
  4316. s.mixer[2].effects.push_back (fx);
  4317. }
  4318. lynx::Automation a;
  4319. a.target = { lynx::AutomationTargetKind::effectMix, 2, 1, 0 };
  4320. s.automations.push_back (a);
  4321. }, false);
  4322. const auto id = e.getSong().mixer[2].effects[1].instance.id;
  4323. const auto automations = e.getSong().automations.size();
  4324. e.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  4325. const auto& moved = e.getSong();
  4326. if (livescr190drResult == "OK"
  4327. && (moved.mixer[2].effects.size() != 1 || moved.mixer[3].effects.size() != 1 || moved.mixer[3].effects[0].instance.id != id
  4328. || moved.automations.size() != automations || moved.automations.back().target.index != 3 || moved.automations.back().target.slot != 0))
  4329. livescr190drResult = "ERROR device move";
  4330. e.undo();
  4331. const auto& undone = e.getSong();
  4332. if (livescr190drResult == "OK"
  4333. && (undone.mixer[2].effects.size() != 2 || undone.mixer[3].effects.size() != 0 || undone.mixer[2].effects[1].instance.id != id
  4334. || undone.automations.back().target.index != 2 || undone.automations.back().target.slot != 1))
  4335. livescr190drResult = "ERROR device move undo";
  4336. e.editSong ([] (lynx::Song& s) {
  4337. s.channels.resize (std::max<std::size_t> (s.channels.size(), 1));
  4338. s.channels[0].sampler.stretchBeats = 16.0f;
  4339. lynx::Clip c;
  4340. c.kind = lynx::ClipKind::audio;
  4341. c.channel = 0;
  4342. c.offset = 4 * lynx::ppq;
  4343. c.length = 8 * lynx::ppq;
  4344. lynx::launcher::setClip (s, 0, 0, c);
  4345. }, false);
  4346. e.editSong ([] (lynx::Song& s) { lynx::clipsample::setWarp (s, 0, false, 4.0); });
  4347. const auto* off = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  4348. if (livescr190drResult == "OK" && (e.getSong().channels[0].sampler.stretchBeats != 0.0f || off == nullptr || off->length != (std::int64_t) std::llround (8.0 * lynx::ppq * (4.0 * e.getSong().bpm / 60.0) / 16.0)))
  4349. livescr190drResult = "ERROR warp off";
  4350. e.undo();
  4351. const auto* on = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  4352. if (livescr190drResult == "OK" && (e.getSong().channels[0].sampler.stretchBeats != 16.0f || on == nullptr || on->length != 8 * lynx::ppq))
  4353. livescr190drResult = "ERROR warp undo";
  4354. }
  4355. // round 190ef: the map modes' storage (.lynx round trip of key / MIDI mappings and a link's Min / Max; an older
  4356. // reader keeps the plain link), and in a real engine: a link's range, MIDI Map Mode catching the control instead
  4357. // of moving anything, a slot's MIDI mapping firing on its press and release
  4358. juce::String livewf190efResult = "OK";
  4359. {
  4360. using namespace lynx::remotemap;
  4361. auto song = lynx::Song::makeDefault();
  4362. lynx::launcher::ensureGrid (song);
  4363. const lynx::AutomationTarget vol { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  4364. assignMidi (song, Target::parameter (vol), { 0, 20, -1 });
  4365. assignMidi (song, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, 2 });
  4366. assignKey (song, Target::sceneLaunch (0), 'S');
  4367. assignKey (song, Target::parameter ({ lynx::AutomationTargetKind::tempo, 0, 0, 0 }), 'T');
  4368. setRange (song, rows (song, Mode::midi)[0], 0.25f, 0.75f);
  4369. setRange (song, rows (song, Mode::key)[1], 0.9f, 0.1f);
  4370. juce::String why;
  4371. const auto json = lynx::ProjectFile::toJson (song);
  4372. const auto back = lynx::ProjectFile::fromJson (json, why);
  4373. if (! back || back->remoteMappings != song.remoteMappings || back->midiLinks != song.midiLinks)
  4374. livewf190efResult = "ERROR round trip " + why;
  4375. auto parsed = juce::JSON::parse (json);
  4376. if (auto* o = parsed.getDynamicObject())
  4377. {
  4378. o->removeProperty ("remoteMappings");
  4379. o->removeProperty ("midiLinkSettings");
  4380. }
  4381. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  4382. if (livewf190efResult == "OK" && (! older || ! older->remoteMappings.empty() || older->midiLinks.size() != 1 || older->midiLinks[0].max != 1.0f))
  4383. livewf190efResult = "ERROR older reader";
  4384. const auto plain = lynx::ProjectFile::toJson (lynx::Song::makeDefault());
  4385. if (livewf190efResult == "OK" && plain.contains ("remoteMappings"))
  4386. livewf190efResult = "ERROR written without mappings";
  4387. lynx::AudioEngine e (false);
  4388. e.editSong ([vol] (lynx::Song& s) {
  4389. if (s.mixer.size() < 3)
  4390. s.mixer.resize (3);
  4391. lynx::MidiLink l { 20, 0, vol };
  4392. l.min = 0.25f;
  4393. l.max = 0.75f;
  4394. s.midiLinks = { l };
  4395. lynx::launcher::ensureGrid (s);
  4396. assignMidi (s, Target::slot (0, 0), { 0, 21, -1 });
  4397. });
  4398. e.injectControllerForTest (20, 0, 127);
  4399. const auto top = e.currentTargetValue (vol);
  4400. e.injectControllerForTest (20, 0, 0);
  4401. const auto bottom = e.currentTargetValue (vol);
  4402. if (livewf190efResult == "OK" && (std::abs (top - 0.75f) > 0.01f || std::abs (bottom - 0.25f) > 0.01f))
  4403. livewf190efResult = "ERROR range " + juce::String (bottom) + " " + juce::String (top);
  4404. std::vector<Fire> fired;
  4405. e.onRemoteFire = [&fired] (const Fire& f) { fired.push_back (f); };
  4406. e.injectControllerForTest (21, 0, 127);
  4407. e.injectControllerForTest (21, 0, 127); // (still down: no new press)
  4408. e.injectControllerForTest (21, 0, 0);
  4409. if (livewf190efResult == "OK"
  4410. && (fired.size() != 2 || fired[0].edge != Edge::press || fired[1].edge != Edge::release || ! (fired[0].target == Target::slot (0, 0))))
  4411. livewf190efResult = "ERROR slot fire " + juce::String ((int) fired.size());
  4412. e.setMapMode (Mode::midi);
  4413. fired.clear();
  4414. e.injectControllerForTest (20, 0, 127);
  4415. e.injectControllerForTest (21, 0, 127);
  4416. const auto caught = e.takeMapCapture();
  4417. if (livewf190efResult == "OK" && (std::abs (e.currentTargetValue (vol) - 0.25f) > 0.01f || ! fired.empty()))
  4418. livewf190efResult = "ERROR mappings acted in MIDI Map Mode";
  4419. else if (livewf190efResult == "OK" && (! caught || caught->number != 21 || caught->channel != 0 || e.takeMapCapture().has_value()))
  4420. livewf190efResult = "ERROR map capture";
  4421. e.setMapMode (Mode::off);
  4422. e.onRemoteFire = nullptr;
  4423. }
  4424. // round 190em: a scene's time signature denominator (.lynx round trip; an older file without it reads n/4; a
  4425. // launch of a 6 / 8 scene gives the song a 3-beat bar), and Capture MIDI in the clip grid of a real engine: the
  4426. // armed track, the selected scene's slot, the tempo from a phrase played while stopped (8 notes at 148 BPM), the
  4427. // new clip launched and the transport started
  4428. juce::String livewf190emResult = "OK";
  4429. {
  4430. auto song = lynx::Song::makeDefault();
  4431. auto& grid = lynx::launcher::ensureGrid (song);
  4432. grid.scenes.resize (3);
  4433. lynx::session::setSceneSignature (song, 1, 6, 8);
  4434. lynx::session::setSceneTempo (song, 1, 100.0);
  4435. juce::String why;
  4436. const auto json = lynx::ProjectFile::toJson (song);
  4437. const auto back = lynx::ProjectFile::fromJson (json, why);
  4438. if (! back || ! back->clipGrid || back->clipGrid->scenes != song.clipGrid->scenes || back->clipGrid->scenes[1].beatUnit != 8)
  4439. livewf190emResult = "ERROR round trip " + why;
  4440. {
  4441. // a captured clip's blank label (ClipGridSlot::blankName) survives the round trip
  4442. auto withClip = song;
  4443. lynx::Clip c;
  4444. c.pattern = 0;
  4445. c.length = 4 * lynx::ppq;
  4446. if (withClip.patterns.empty())
  4447. withClip.patterns.emplace_back();
  4448. const auto slot = lynx::launcher::setClip (withClip, 0, 0, c);
  4449. if (slot >= 0)
  4450. withClip.clipGrid->slots[(std::size_t) slot].blankName = true;
  4451. const auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (withClip), why);
  4452. const auto* keptClip = again && again->clipGrid ? lynx::launcher::clipAt (*again->clipGrid, 0, 0) : nullptr;
  4453. const auto* kept = keptClip != nullptr ? &again->clipGrid->slots[(std::size_t) keptClip->gridSlot] : nullptr;
  4454. if (livewf190emResult == "OK" && (slot < 0 || kept == nullptr || ! kept->blankName))
  4455. livewf190emResult = "ERROR blank clip name round trip";
  4456. }
  4457. auto parsed = juce::JSON::parse (json);
  4458. if (auto* scenes = parsed.getProperty ("clipGrid", {}).getProperty ("scenes", {}).getArray(); scenes != nullptr && scenes->size() > 1)
  4459. if (auto* o = (*scenes)[1].getDynamicObject())
  4460. o->removeProperty ("beatUnit");
  4461. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  4462. if (livewf190emResult == "OK" && (! older || ! older->clipGrid || older->clipGrid->scenes.size() < 2 || older->clipGrid->scenes[1].beatUnit != 4
  4463. || older->clipGrid->scenes[1].beatsPerBar != 6))
  4464. livewf190emResult = "ERROR older reader";
  4465. if (livewf190emResult == "OK" && lynx::ProjectFile::toJson (lynx::Song::makeDefault()).contains ("beatUnit"))
  4466. livewf190emResult = "ERROR beatUnit written by default";
  4467. // round 190fg: the song meter's denominator round-trips through .lynx; a file without it reads n/4
  4468. {
  4469. auto six = lynx::Song::makeDefault();
  4470. six.beatsPerBar = 6;
  4471. six.beatUnit = 8;
  4472. const auto text = lynx::ProjectFile::toJson (six);
  4473. juce::String why2;
  4474. const auto back = lynx::ProjectFile::fromJson (text, why2);
  4475. auto json = juce::JSON::parse (text);
  4476. if (auto* o = json.getDynamicObject())
  4477. o->removeProperty ("beatUnit");
  4478. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (json), why2);
  4479. if (livewf190emResult == "OK" && (! back || back->beatsPerBar != 6 || back->beatUnit != 8 || ! old || old->beatsPerBar != 6 || old->beatUnit != 4))
  4480. livewf190emResult = "ERROR song meter round trip";
  4481. }
  4482. lynx::AudioEngine e (false);
  4483. e.editSong ([] (lynx::Song& s) {
  4484. s.bpm = 120.0;
  4485. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  4486. auto& g = lynx::launcher::ensureGrid (s);
  4487. g.scenes.resize (3);
  4488. lynx::session::setSceneSignature (s, 2, 6, 8);
  4489. lynx::session::setSceneTempo (s, 2, 90.0);
  4490. }, false);
  4491. e.launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, 2 });
  4492. // (round 190fg: the song takes the scene's 6 / 8 as it is: six eighths a bar, 3 quarters long)
  4493. if (livewf190emResult == "OK" && (e.getSong().beatsPerBar != 6 || e.getSong().beatUnit != 8 || e.getSong().barTicks() != 3 * lynx::ppq
  4494. || e.getSong().bpm != 90.0))
  4495. livewf190emResult = "ERROR scene launch " + juce::String (e.getSong().beatsPerBar) + "/" + juce::String (e.getSong().beatUnit) + " "
  4496. + juce::String (e.getSong().bpm);
  4497. e.stop();
  4498. e.editSong ([] (lynx::Song& s) {
  4499. s.bpm = 120.0;
  4500. s.beatsPerBar = 4;
  4501. s.beatUnit = 4;
  4502. }, false);
  4503. e.setGridTrackArmed (2, true, true);
  4504. const auto now = juce::Time::getMillisecondCounterHiRes();
  4505. const auto beat = 60000.0 / 148.0;
  4506. for (int i = 0; i < 8; ++i)
  4507. {
  4508. const auto at = now - 9.0 * beat + i * beat;
  4509. e.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  4510. e.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  4511. }
  4512. int placed = -1;
  4513. bool into = true;
  4514. const auto r = e.captureMidiToSlot (2, 1, placed, into);
  4515. const auto& g = *e.getSong().clipGrid;
  4516. const auto* clip = lynx::launcher::clipAt (g, 2, 1);
  4517. if (livewf190emResult == "OK" && (r.notes != 8 || placed != 1 || into || clip == nullptr || clip->length != 8 * lynx::ppq))
  4518. livewf190emResult = "ERROR capture " + juce::String (r.notes) + " " + juce::String (placed) + (clip == nullptr ? " no clip" : " " + juce::String ((int) clip->length));
  4519. else if (livewf190emResult == "OK" && std::abs (e.getSong().bpm - 148.0) > 0.5)
  4520. livewf190emResult = "ERROR tempo " + juce::String (e.getSong().bpm, 2);
  4521. else if (livewf190emResult == "OK" && ! e.getTransport().playing.load())
  4522. livewf190emResult = "ERROR the capture did not start the transport";
  4523. e.stop();
  4524. }
  4525. const auto mixerBasics = lynx::mixerbasics::run();
  4526. // issue #142: every font has a typeface, and one without does not crash (fonts get theirs through the
  4527. // look and feel, as in the app)
  4528. auto& lookBefore = juce::LookAndFeel::getDefaultLookAndFeel();
  4529. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4530. const auto fontsResult = lynx::theme::fontSelfTest();
  4531. // round 190bm (0.1.25 showed the Mixer and the Playlist black): their cached pictures shown on native and
  4532. // software targets against straight paints (ui/PictureCheck.h; --picturetest runs more sizes and scales)
  4533. juce::String picturesResult = "OK";
  4534. {
  4535. lynx::AudioEngine pictureEngine (false);
  4536. auto pictureFailures = 0;
  4537. juce::String lines;
  4538. {
  4539. lynx::PlaylistComponent playlist (pictureEngine);
  4540. playlist.setBounds (0, 0, 1200, 700);
  4541. playlist.setVisible (true);
  4542. lines << lynx::ui::picturecheck::run (playlist, "Playlist 1200 x 700", { 1.0f, 1.5f }, pictureFailures, {});
  4543. }
  4544. {
  4545. lynx::MixerComponent mixer (pictureEngine);
  4546. mixer.setBounds (0, 0, 1200, 500);
  4547. mixer.setVisible (true);
  4548. lines << lynx::ui::picturecheck::run (mixer, "Mixer 1200 x 500", { 1.0f, 1.5f }, pictureFailures, {});
  4549. }
  4550. if (pictureFailures > 0 || ! lines.contains (": ok"))
  4551. picturesResult = "ERROR " + lines.trim().replace ("\n", "; ");
  4552. }
  4553. // round 190ci (the 0.1.26 release candidate ended when an FPC channel was added): every built-in generator and
  4554. // effect, its editor built as the Channel Rack / mixer opens it and painted once. The report file names the
  4555. // plugin being opened, so a run that dies there says which one.
  4556. const auto editorsResult = lynx::pluginthumbs::checkEditors ([&reportPath] (const juce::String& key) {
  4557. if (reportPath.isNotEmpty())
  4558. juce::File (reportPath).replaceWithText ("(opening the editor of " + key + ")\n");
  4559. });
  4560. // round 190ci: a fault leaves a crash file, also on a stack Windows cannot walk (that FPC fault left none)
  4561. const auto faultResult = faultReportSelfTest();
  4562. juce::LookAndFeel::setDefaultLookAndFeel (&lookBefore);
  4563. const auto ok = editorsResult.startsWith ("OK") && ! faultResult.startsWith ("ERROR")
  4564. && mixerBasics == "OK" && fontsResult == "OK" && picturesResult == "OK" && audioOk && projectOk && trackModes122Ok && richOk && hwOutOk && hostKeysOk && pluginLevelsOk && flp168jOk && clipFades180dOk && blocksOk && takeoverOk && compOk && polyOk && latencyOk && preSendOk && lowLatencyOk && previewInTimeOk && substituteOk && patcherOk && rackResult == "OK" && nativesOk && undoOk && projectSaveOk && recordOk && recordUndoOk && cancelRecordOk && midiOk && packageOk
  4565. && sessionResult == "OK" && liveResult.startsWith ("OK")
  4566. && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && deviceChange.startsWith ("OK") && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
  4567. && sidechainResult == "OK" && lanesResult == "OK" && arrange190cgResult == "OK" && livescr190drResult == "OK" && livewf190efResult == "OK" && livewf190emResult == "OK" && versionsResult == "OK" && pluginsOffResult == "OK"
  4568. && danceWindowResult == "OK" && clickActivationResult == "OK";
  4569. juce::String report;
  4570. report << "connections=" << offline.getNumGraphConnections() << "\n"
  4571. << "peak=" << peak << "\n"
  4572. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  4573. << "playlist_track_modes_roundtrip=" << (trackModes122Ok ? "OK" : "ERROR") << "\n"
  4574. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  4575. << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
  4576. << "plugin_host_keys_option=" << (hostKeysOk ? "OK" : "ERROR") << "\n"
  4577. << "plugin_levels_new_project=" << (pluginLevelsOk ? "OK" : "ERROR") << "\n"
  4578. << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
  4579. << "clip_fades_180d=" << (clipFades180dOk ? "OK" : "ERROR") << "\n"
  4580. << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
  4581. << "pattern_clip_takeover=" << (takeoverOk ? "OK" : "ERROR") << "\n"
  4582. << "comp_crossfades=" << (compOk ? "OK" : "ERROR") << "\n"
  4583. << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
  4584. << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
  4585. << "pre_fader_sends=" << (preSendOk ? "OK" : "ERROR") << "\n"
  4586. << "low_latency_recording=" << (lowLatencyOk ? "OK" : "ERROR") << "\n"
  4587. << "preview_in_time=" << (previewInTimeOk ? "OK" : "ERROR") << " (2 s loop prepared in " << juce::String (previewPrepareMs, 1) << " ms)\n"
  4588. << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
  4589. << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
  4590. << "racks=" << rackResult << "\n"
  4591. << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
  4592. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  4593. << "mixer_basics=" << mixerBasics << "\n"
  4594. << "fonts=" << fontsResult << "\n"
  4595. << "cached_pictures=" << picturesResult << "\n"
  4596. << "plugin_editors=" << editorsResult << "\n"
  4597. << "fault_report=" << faultResult << "\n"
  4598. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  4599. << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
  4600. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  4601. << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
  4602. << "projectSave=" << (projectSaveOk ? "OK" : "ERROR") << "\n"
  4603. << "online_session=" << sessionResult << "\n"
  4604. << "live_session=" << liveResult << "\n"
  4605. << "wavpack=" << wavpack << "\n"
  4606. << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
  4607. << "effect_params_saved=" << effectParamsResult << "\n"
  4608. << "driver_panel=" << driverPanel << "\n"
  4609. << "device_change=" << deviceChange << "\n"
  4610. << "plugin_art=" << artResult << "\n"
  4611. << "plugin_sidechain=" << sidechainResult << "\n"
  4612. << "versions_panel=" << versionsResult << "\n"
  4613. << "plugins_off=" << pluginsOffResult << "\n"
  4614. << "dance_window=" << danceWindowResult << "\n"
  4615. << "dance_window_detail=" << danceWindowDetail << "\n"
  4616. << "click_activation=" << clickActivationResult << "\n"
  4617. << "lanes_saved=" << lanesResult << "\n"
  4618. << "arrange190cg_saved=" << arrange190cgResult << "\n"
  4619. << "livescr190dr=" << livescr190drResult << "\n"
  4620. << "livewf190ef=" << livewf190efResult << "\n"
  4621. << "livewf190em=" << livewf190emResult << "\n"
  4622. << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
  4623. << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n";
  4624. // issue #138 (round 190c): a short note at the very start of the Playlist against the same note at bar 2, through
  4625. // the Export window's path (its own thread while the message loop runs: the report is finished from there)
  4626. if (reportPath.isNotEmpty())
  4627. juce::File (reportPath).replaceWithText (report + "(short_export running)\n");
  4628. lynx::shortexport::run (false, 1, {}, {}, [this, report, ok, reportPath] (juce::String shortExport) {
  4629. const auto all = ok && shortExport.startsWith ("OK");
  4630. const auto text = report + "short_export=" + shortExport + "\nresult=" + (all ? "OK" : "FAILED") + "\n";
  4631. if (reportPath.isNotEmpty())
  4632. juce::File (reportPath).replaceWithText (text);
  4633. setApplicationReturnValue (all ? 0 : 1);
  4634. quit();
  4635. });
  4636. }
  4637. // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
  4638. // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
  4639. // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
  4640. bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
  4641. {
  4642. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4643. lynx::setNativeEditorDemo (true);
  4644. juce::String report;
  4645. auto allFinite = true;
  4646. {
  4647. lynx::AudioEngine offline (false);
  4648. juce::Random random (111);
  4649. const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
  4650. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  4651. {
  4652. const auto kind = (lynx::EffectKind) k;
  4653. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
  4654. continue;
  4655. const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
  4656. const auto& info = lynx::effectInfo (kind);
  4657. // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
  4658. auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  4659. int dragged = 0; // parameter changes made by the mouse drags
  4660. for (int round = 0; round < rounds; ++round)
  4661. {
  4662. if (round > 0)
  4663. for (std::size_t p = 0; p < info.params.size(); ++p)
  4664. fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
  4665. auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
  4666. song.mixer.resize (2);
  4667. song.mixer[0].name = "Master";
  4668. song.mixer[1].name = "Insert 1";
  4669. song.mixer[1].effects.assign (1, fx);
  4670. for (auto& channel : song.channels)
  4671. channel.mixerTrack = 1;
  4672. offline.setSong (std::move (song));
  4673. offline.dispatchPendingMessages();
  4674. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  4675. for (int page = 0; page < pages; ++page)
  4676. {
  4677. auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  4678. : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  4679. if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
  4680. continue;
  4681. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  4682. const auto paint = [&] {
  4683. juce::Graphics g (image);
  4684. editor->paintEntireComponent (g, false);
  4685. };
  4686. paint();
  4687. // drags from a grid of points, as a user moving every control (plain left button)
  4688. if (round >= 3 && drags)
  4689. {
  4690. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  4691. const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
  4692. for (int y = step / 2; y < editor->getHeight(); y += step)
  4693. for (int x = step / 2; x < editor->getWidth(); x += step)
  4694. {
  4695. auto* target = editor->getComponentAt (x, y);
  4696. if (target == nullptr)
  4697. continue;
  4698. const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
  4699. const auto now = juce::Time::getCurrentTime();
  4700. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
  4701. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
  4702. };
  4703. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  4704. const juce::Component::SafePointer<juce::Component> alive (target);
  4705. target->mouseDown (event (at, down));
  4706. const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
  4707. if (alive != nullptr)
  4708. target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
  4709. if (alive != nullptr)
  4710. target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
  4711. if (alive != nullptr)
  4712. target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
  4713. juce::PopupMenu::dismissAllActiveMenus();
  4714. offline.dispatchPendingMessages();
  4715. }
  4716. paint();
  4717. }
  4718. }
  4719. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  4720. offline.renderOffline (0.05, rate);
  4721. if (round == 0 || round >= 3) // keep what the drags set for the next round
  4722. if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
  4723. {
  4724. const auto& now = offline.getSong().mixer[1].effects[0];
  4725. for (std::size_t p = 0; p < fx.params.size(); ++p)
  4726. dragged += now.params[p] != fx.params[p] ? 1 : 0;
  4727. dragged += now.state != fx.state ? 1 : 0;
  4728. fx = now;
  4729. }
  4730. }
  4731. const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
  4732. allFinite = allFinite && broken == 0;
  4733. report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
  4734. << " (" << dragged << " changes by mouse)\n";
  4735. if (reportPath.isNotEmpty())
  4736. juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
  4737. }
  4738. }
  4739. lynx::setNativeEditorDemo (false);
  4740. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  4741. report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
  4742. if (reportPath.isNotEmpty())
  4743. juce::File (reportPath).replaceWithText (report);
  4744. return allFinite;
  4745. }
  4746. // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
  4747. // native windows are real); one step per timer tick.
  4748. void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
  4749. {
  4750. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4751. struct OpenTest final : juce::Timer
  4752. {
  4753. juce::String reportPath, report;
  4754. bool visible = false, ok = true;
  4755. std::function<void (bool)> done;
  4756. std::unique_ptr<lynx::AudioEngine> engine;
  4757. std::vector<std::pair<juce::String, std::function<void()>>> steps;
  4758. std::size_t next = 0;
  4759. std::atomic<std::int64_t> lastStep { 0 };
  4760. std::atomic<bool> finished { false };
  4761. std::thread watchdog;
  4762. juce::String current;
  4763. std::mutex currentLock;
  4764. int opened = 0, painted = 0;
  4765. // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
  4766. const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
  4767. static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
  4768. void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
  4769. ~OpenTest() override
  4770. {
  4771. finished = true;
  4772. if (watchdog.joinable())
  4773. watchdog.join();
  4774. }
  4775. void start()
  4776. {
  4777. lastStep = now();
  4778. // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
  4779. const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
  4780. folder.deleteRecursively();
  4781. folder.createDirectory();
  4782. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
  4783. watchdog = std::thread ([this] {
  4784. while (! finished)
  4785. {
  4786. std::this_thread::sleep_for (std::chrono::milliseconds (200));
  4787. if (now() - lastStep.load() > timeoutMs)
  4788. {
  4789. juce::String at;
  4790. {
  4791. const std::lock_guard<std::mutex> l (currentLock);
  4792. at = current;
  4793. }
  4794. juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
  4795. lynx::crashguard::exitNow (3);
  4796. }
  4797. }
  4798. });
  4799. startTimer (30);
  4800. }
  4801. // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
  4802. void touchWindows (bool resize, bool large)
  4803. {
  4804. auto& desktop = juce::Desktop::getInstance();
  4805. for (int i = desktop.getNumComponents(); --i >= 0;)
  4806. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
  4807. {
  4808. if (! visible && c->getScreenX() > -3000)
  4809. c->setTopLeftPosition (-6000, -6000);
  4810. if (resize)
  4811. if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
  4812. {
  4813. const auto b = w->getBounds();
  4814. w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
  4815. }
  4816. if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
  4817. {
  4818. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  4819. juce::Graphics g (image);
  4820. c->paintEntireComponent (g, false);
  4821. ++painted;
  4822. // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
  4823. if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
  4824. {
  4825. juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
  4826. if (out.openedOk())
  4827. {
  4828. out.setPosition (0), out.truncate();
  4829. juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  4830. }
  4831. }
  4832. }
  4833. }
  4834. }
  4835. void timerCallback() override
  4836. {
  4837. if (next >= steps.size())
  4838. {
  4839. stopTimer();
  4840. lynx::NativeEffectWindows::closeAll();
  4841. lynx::closeChannelSettings();
  4842. // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
  4843. {
  4844. const auto before = lynx::crashguard::lastHangFile();
  4845. for (const auto until = now() + 7000; now() < until;)
  4846. lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
  4847. for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
  4848. std::this_thread::sleep_for (std::chrono::milliseconds (20));
  4849. lynx::crashguard::stopHangWatch();
  4850. const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
  4851. const auto text = hang.loadFileAsString();
  4852. const auto frames = juce::StringArray::fromLines (text).size() - 2;
  4853. #if JUCE_WINDOWS
  4854. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
  4855. #else
  4856. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
  4857. #endif
  4858. report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
  4859. << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
  4860. ok = ok && hangOk;
  4861. }
  4862. report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
  4863. write();
  4864. finished = true;
  4865. if (done)
  4866. done (ok);
  4867. return;
  4868. }
  4869. auto& [label, fn] = steps[next++];
  4870. {
  4871. const std::lock_guard<std::mutex> l (currentLock);
  4872. current = label;
  4873. }
  4874. fn();
  4875. lastStep = now();
  4876. lynx::crashguard::heartbeat();
  4877. }
  4878. };
  4879. auto* test = new OpenTest();
  4880. test->reportPath = reportPath;
  4881. test->visible = visible;
  4882. test->engine = std::make_unique<lynx::AudioEngine> (false);
  4883. test->done = [test, done] (bool ok) {
  4884. juce::MessageManager::callAsync ([test, done, ok] {
  4885. delete test;
  4886. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  4887. done (ok);
  4888. });
  4889. };
  4890. auto& engine = *test->engine;
  4891. lynx::setNativeEditorDemo (true); // live displays animate without an audio device
  4892. const auto songWith = [] (const lynx::EffectSlot& fx) {
  4893. auto song = lynx::Song::makeDefault();
  4894. song.mixer.resize (2);
  4895. song.mixer[0].name = "Master";
  4896. song.mixer[1].name = "Insert 1";
  4897. song.mixer[1].effects.assign (1, fx);
  4898. for (auto& channel : song.channels)
  4899. channel.mixerTrack = 1;
  4900. return song;
  4901. };
  4902. // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
  4903. // parameters a newer LYNX added after them take their defaults)
  4904. const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
  4905. auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
  4906. if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
  4907. if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
  4908. if (auto* params = (*effects)[0]["params"].getArray())
  4909. params->removeRange ((int) count, params->size());
  4910. juce::String error;
  4911. return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
  4912. };
  4913. auto& steps = test->steps;
  4914. juce::Random random (157);
  4915. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  4916. {
  4917. const auto kind = (lynx::EffectKind) k;
  4918. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  4919. continue;
  4920. const auto& info = lynx::effectInfo (kind);
  4921. const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  4922. const auto n = info.params.size();
  4923. std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
  4924. variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
  4925. for (const auto value : { 0.0f, 1.0f })
  4926. variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
  4927. auto fx = base;
  4928. for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
  4929. return std::optional<lynx::Song> (songWith (fx));
  4930. } });
  4931. const auto seed = random.nextInt64();
  4932. variants.push_back ({ "random", [=] {
  4933. juce::Random r (seed);
  4934. auto fx = base;
  4935. for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
  4936. return std::optional<lynx::Song> (songWith (fx));
  4937. } });
  4938. std::vector<std::size_t> cuts { n / 2 };
  4939. 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)
  4940. if (c < n) cuts.push_back (c);
  4941. for (const auto c : cuts)
  4942. variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
  4943. for (const auto& [variant, makeSong] : variants)
  4944. {
  4945. const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
  4946. steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
  4947. auto song = makeSong();
  4948. if (! song)
  4949. {
  4950. test->report << "FAIL " << label << ": project reader refused the state\n";
  4951. test->ok = false;
  4952. return;
  4953. }
  4954. engine.setSong (std::move (*song));
  4955. engine.dispatchPendingMessages();
  4956. lynx::NativeEffectWindows::open (engine, 1, 0);
  4957. ++test->opened;
  4958. test->touchWindows (false, false);
  4959. } });
  4960. steps.push_back ({ label + ": run", [test, &engine] {
  4961. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  4962. engine.renderOffline (0.03, rate);
  4963. test->touchWindows (false, false);
  4964. } });
  4965. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  4966. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  4967. steps.push_back ({ label + ": close", [test, label] {
  4968. lynx::NativeEffectWindows::closeAll();
  4969. test->report << label << ": OK\n";
  4970. test->write ("(running)\n");
  4971. } });
  4972. }
  4973. }
  4974. // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
  4975. for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
  4976. {
  4977. const auto kind = (lynx::InstrumentKind) k;
  4978. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  4979. continue;
  4980. for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
  4981. {
  4982. if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
  4983. continue;
  4984. const auto label = "instrument " + juce::String (k) + " / " + variant;
  4985. steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
  4986. auto song = lynx::Song::makeDefault();
  4987. auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  4988. lynx::ChannelDef def;
  4989. def.instrument = kind;
  4990. def.name = "Test";
  4991. song.channels.push_back (channel ? *channel : def);
  4992. if (kind == lynx::InstrumentKind::soundfont && variant != "default")
  4993. {
  4994. // a real font when FL's is there; NaN / huge / truncated settings
  4995. const auto& roots = lynx::flStudioAccess().roots;
  4996. if (! roots.data.empty())
  4997. song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  4998. .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
  4999. .getFullPathName().toStdString();
  5000. if (variant == "odd settings")
  5001. song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
  5002. }
  5003. if (old)
  5004. {
  5005. juce::String error;
  5006. if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
  5007. song = std::move (*again);
  5008. }
  5009. const auto index = (int) song.channels.size() - 1;
  5010. engine.setSong (std::move (song));
  5011. engine.dispatchPendingMessages();
  5012. lynx::openChannelSettings (engine, index);
  5013. ++test->opened;
  5014. test->touchWindows (false, false);
  5015. } });
  5016. steps.push_back ({ label + ": run", [test, &engine] {
  5017. engine.renderOffline (0.03, 48000.0);
  5018. test->touchWindows (false, false);
  5019. } });
  5020. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  5021. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  5022. steps.push_back ({ label + ": close", [test, label] {
  5023. lynx::closeChannelSettings();
  5024. test->report << label << ": OK\n";
  5025. test->write ("(running)\n");
  5026. } });
  5027. }
  5028. }
  5029. test->start();
  5030. }
  5031. void runPluginOptionsTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath)
  5032. {
  5033. struct Test final : juce::Timer
  5034. {
  5035. juce::String reportPath, report;
  5036. juce::File shots;
  5037. std::unique_ptr<lynx::AudioEngine> engine;
  5038. std::unique_ptr<juce::DocumentWindow> mainWindow, other; // LYNX's main window stand-in; another secondary window
  5039. bool instrument = false, ok = true;
  5040. int channelIndex = -1, phase = 0;
  5041. juce::uint32 phaseStart = 0;
  5042. juce::AudioPluginInstance* instance = nullptr;
  5043. std::function<void (bool)> done;
  5044. void step (const juce::String& line)
  5045. {
  5046. report << line << "\n";
  5047. juce::File (reportPath).replaceWithText (report);
  5048. }
  5049. void expect (const juce::String& name, bool value)
  5050. {
  5051. step (name + "=" + juce::String ((int) value));
  5052. ok = ok && value;
  5053. }
  5054. void next (int to)
  5055. {
  5056. phase = to;
  5057. phaseStart = juce::Time::getMillisecondCounter();
  5058. }
  5059. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  5060. lynx::PluginRef* ref (lynx::Song& song) const
  5061. {
  5062. if (instrument)
  5063. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  5064. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  5065. }
  5066. const lynx::PluginRef& refNow() const { return *ref (const_cast<lynx::Song&> (engine->getSong())); }
  5067. juce::AudioPluginInstance* find()
  5068. {
  5069. if (instrument)
  5070. {
  5071. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  5072. return &p->getInstance();
  5073. }
  5074. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  5075. return &p->getInstance();
  5076. return nullptr;
  5077. }
  5078. void openWindow()
  5079. {
  5080. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  5081. : std::shared_ptr<void> (engine->getEffect (1, 0));
  5082. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  5083. { engine.get(), [this] (lynx::Song& song) { return ref (song); }, instrument, instrument ? -1 : 1,
  5084. instrument ? -1 : 0, {}, {} });
  5085. }
  5086. void shot (const char* name, bool settingsPage = false)
  5087. {
  5088. if (shots != juce::File() && instance != nullptr)
  5089. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  5090. }
  5091. // the plugin window is in front of the other secondary window
  5092. bool pluginInFront()
  5093. {
  5094. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  5095. #if JUCE_WINDOWS
  5096. return plug != nullptr && lynx::nativechild::isAbove (plug, other->getWindowHandle());
  5097. #else
  5098. auto& desktop = juce::Desktop::getInstance();
  5099. for (int i = 0; i < desktop.getNumComponents(); ++i)
  5100. if (auto* c = desktop.getComponent (i); c->getWindowHandle() == plug)
  5101. return c->isAlwaysOnTop() || desktop.getComponent (desktop.getNumComponents() - 1) == c;
  5102. return false;
  5103. #endif
  5104. }
  5105. void timerCallback() override
  5106. {
  5107. if (phase == 0) // waiting for the engine to host the plugin
  5108. {
  5109. instance = find();
  5110. if (instance == nullptr)
  5111. {
  5112. if (elapsed() > 20000)
  5113. finish ("not hosted");
  5114. return;
  5115. }
  5116. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  5117. openWindow();
  5118. next (1);
  5119. return;
  5120. }
  5121. if (phase == 1 && elapsed() >= 800) // Pin on top: off for a new plugin
  5122. {
  5123. expect ("pin_off_by_default", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  5124. shot ("pin-off");
  5125. const auto history = engine->getHistoryPosition();
  5126. lynx::PluginWindows::setPinnedOnTop (*instance, true);
  5127. expect ("pin_set", lynx::PluginWindows::isPinnedOnTop (*instance) && refNow().pinned);
  5128. expect ("pin_no_undo_step_project_modified", engine->getHistoryPosition() == history && engine->isModified());
  5129. // another secondary window brought in front of it
  5130. other = std::make_unique<juce::DocumentWindow> ("Another LYNX window", juce::Colours::darkslategrey, juce::DocumentWindow::closeButton);
  5131. other->setUsingNativeTitleBar (true);
  5132. other->setBounds (mainWindow->getX() + 60, mainWindow->getY() + 60, 420, 300);
  5133. other->setVisible (true);
  5134. lynx::keepAboveMainWindow (*other);
  5135. lynx::forceForegroundForTest (*other);
  5136. other->toFront (true);
  5137. next (2);
  5138. return;
  5139. }
  5140. if (phase == 2 && elapsed() >= 1200)
  5141. {
  5142. expect ("pinned_stays_in_front_of_a_clicked_window", pluginInFront());
  5143. shot ("pin-on");
  5144. // closed and opened again: the pin comes back from the project
  5145. lynx::PluginWindows::close (*instance);
  5146. openWindow();
  5147. next (3);
  5148. return;
  5149. }
  5150. if (phase == 3 && elapsed() >= 600)
  5151. {
  5152. expect ("pin_remembered_when_reopened", lynx::PluginWindows::isPinnedOnTop (*instance));
  5153. lynx::PluginWindows::setPinnedOnTop (*instance, false);
  5154. expect ("pin_cleared", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  5155. other->toFront (true);
  5156. next (4);
  5157. return;
  5158. }
  5159. if (phase == 4 && elapsed() >= 1000)
  5160. {
  5161. #if JUCE_WINDOWS
  5162. expect ("unpinned_goes_behind_a_clicked_window", ! pluginInFront());
  5163. #endif
  5164. other = nullptr;
  5165. // the wrapper settings page: LYNX's Velocity row in the MIDI group (instruments), default = follow
  5166. expect ("velocity_follows_midi_settings_by_default", refNow().velocityMode == lynx::prefs::pluginVelocityFollow
  5167. && refNow().fixedVelocity == lynx::prefs::defaultFixedVelocity);
  5168. shot ("wrapper-velocity-default", true);
  5169. engine->editSong ([this] (lynx::Song& song) {
  5170. if (auto* r = ref (song))
  5171. {
  5172. r->velocityMode = lynx::prefs::pluginVelocityFixed;
  5173. r->fixedVelocity = 96;
  5174. }
  5175. });
  5176. next (5);
  5177. return;
  5178. }
  5179. if (phase == 5 && elapsed() >= 400)
  5180. {
  5181. expect ("velocity_change_keeps_the_running_plugin", find() == instance);
  5182. shot ("wrapper-velocity-fixed", true);
  5183. engine->undo();
  5184. expect ("velocity_undo", refNow().velocityMode == lynx::prefs::pluginVelocityFollow && find() == instance);
  5185. // the preset menu's "Play a note when a preset loads": off by default, a user setting
  5186. expect ("audition_off_by_default", ! lynx::pluginpresetui::auditionOnLoad());
  5187. lynx::pluginpresetui::setAuditionOnLoad (true);
  5188. expect ("audition_menu_opened", lynx::PluginWindows::showPresetMenu (*instance));
  5189. next (6);
  5190. return;
  5191. }
  5192. if (phase == 6 && elapsed() >= 500) // the menu, as drawn
  5193. {
  5194. auto found = false;
  5195. auto& desktop = juce::Desktop::getInstance();
  5196. for (int c = desktop.getNumComponents(); --c >= 0 && ! found;)
  5197. if (auto* menu = desktop.getComponent (c); dynamic_cast<juce::TopLevelWindow*> (menu) == nullptr && menu->isVisible()
  5198. && menu->getHeight() > 60 && shots != juce::File())
  5199. {
  5200. const auto image = menu->createComponentSnapshot (menu->getLocalBounds(), true, 1.0f);
  5201. juce::FileOutputStream out (shots.getChildFile ("preset-menu-audition.png"));
  5202. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  5203. }
  5204. step ("shot_preset-menu-audition=" + juce::String ((int) found));
  5205. juce::PopupMenu::dismissAllActiveMenus();
  5206. // a preset loaded while the song is stopped: the note waits a moment, sounds, ends
  5207. const auto asked = engine->auditionPreset (*instance);
  5208. expect ("audition_only_for_channel_instruments", asked == instrument);
  5209. expect ("audition_waits_first", ! instrument || engine->auditionState() == 1);
  5210. next (7);
  5211. return;
  5212. }
  5213. if (phase == 7 && elapsed() >= 300)
  5214. {
  5215. expect ("audition_sounds", ! instrument || engine->auditionState() == 2);
  5216. next (8);
  5217. return;
  5218. }
  5219. if (phase == 8 && elapsed() >= 700)
  5220. {
  5221. expect ("audition_ends", engine->auditionState() == 0);
  5222. engine->getTransport().playing.store (true); // the song plays: no audition
  5223. expect ("no_audition_while_playing", ! engine->auditionPreset (*instance) && engine->auditionState() == 0);
  5224. engine->getTransport().playing.store (false);
  5225. lynx::pluginpresetui::setAuditionOnLoad (false);
  5226. expect ("audition_setting_off_again", ! lynx::pluginpresetui::auditionOnLoad());
  5227. finish ({});
  5228. }
  5229. }
  5230. void finish (const juce::String& failure)
  5231. {
  5232. stopTimer();
  5233. if (failure.isNotEmpty())
  5234. step ("failed=" + failure);
  5235. ok = ok && failure.isEmpty();
  5236. step (ok ? "result=OK" : "result=FAILED");
  5237. lynx::PluginWindows::closeAll();
  5238. done (ok);
  5239. }
  5240. };
  5241. auto* test = new Test();
  5242. test->reportPath = reportPath;
  5243. if (shotsPath.isNotEmpty())
  5244. {
  5245. test->shots = juce::File (shotsPath);
  5246. test->shots.createDirectory();
  5247. }
  5248. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5249. test->done = [this, test] (bool ok) {
  5250. setApplicationReturnValue (ok ? 0 : 1);
  5251. juce::MessageManager::callAsync ([this, test] {
  5252. lynx::setMainWindowForOwnership (nullptr);
  5253. test->other = nullptr;
  5254. test->mainWindow = nullptr;
  5255. test->engine = nullptr;
  5256. delete test;
  5257. quit();
  5258. });
  5259. };
  5260. test->engine = std::make_unique<lynx::AudioEngine> (false);
  5261. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  5262. test->mainWindow->setBounds (20, 20, 300, 200);
  5263. test->mainWindow->setVisible (true);
  5264. lynx::setMainWindowForOwnership (test->mainWindow.get());
  5265. auto& host = test->engine->getPluginHost();
  5266. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  5267. std::optional<juce::PluginDescription> chosen;
  5268. for (const auto& type : host.getKnownPlugins().getTypes())
  5269. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  5270. {
  5271. chosen = type;
  5272. break;
  5273. }
  5274. if (! chosen)
  5275. {
  5276. test->step ("result=FAILED (no plugin)");
  5277. test->done (false);
  5278. return;
  5279. }
  5280. test->instrument = chosen->isInstrument;
  5281. lynx::PluginRef ref;
  5282. ref.id = chosen->createIdentifierString().toStdString();
  5283. ref.name = chosen->name.toStdString();
  5284. test->engine->editSong ([&] (lynx::Song& song) {
  5285. if (test->instrument)
  5286. {
  5287. lynx::ChannelDef c;
  5288. c.name = ref.name;
  5289. c.instrument = lynx::InstrumentKind::plugin;
  5290. c.plugin = ref;
  5291. test->channelIndex = (int) song.channels.size();
  5292. song.channels.push_back (c);
  5293. }
  5294. else
  5295. {
  5296. while (song.mixer.size() < 2)
  5297. song.mixer.emplace_back();
  5298. lynx::EffectSlot slot;
  5299. slot.kind = lynx::EffectKind::plugin;
  5300. slot.plugin = ref;
  5301. song.mixer[1].effects.push_back (slot);
  5302. }
  5303. });
  5304. test->engine->markSaved();
  5305. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  5306. test->next (0);
  5307. test->startTimerHz (20);
  5308. }
  5309. void runReloadTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath, bool waitKill)
  5310. {
  5311. struct Test final : juce::Timer
  5312. {
  5313. juce::String reportPath, report;
  5314. juce::File shots;
  5315. std::unique_ptr<lynx::AudioEngine> engine;
  5316. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  5317. bool instrument = false, waitKill = false, ok = true;
  5318. int channelIndex = -1, phase = 0, round = 0;
  5319. juce::uint32 phaseStart = 0;
  5320. int firstPid = 0, pid = 0, historyBefore = 0;
  5321. bool modifiedBefore = false;
  5322. float captured = -1.0f;
  5323. juce::AudioPluginInstance* instance = nullptr;
  5324. std::vector<lynx::ChannelDef> channelsBefore;
  5325. std::function<void (bool)> done;
  5326. lynx::AudioEngine::HostedSlot where() const { return instrument ? lynx::AudioEngine::HostedSlot { channelIndex, -1, -1 } : lynx::AudioEngine::HostedSlot { -1, 1, 0 }; }
  5327. void step (const juce::String& line)
  5328. {
  5329. report << line << "\n";
  5330. juce::File (reportPath).replaceWithText (report);
  5331. }
  5332. void expect (const juce::String& name, bool value)
  5333. {
  5334. step (name + "=" + juce::String ((int) value));
  5335. ok = ok && value;
  5336. }
  5337. void next (int to)
  5338. {
  5339. phase = to;
  5340. phaseStart = juce::Time::getMillisecondCounter();
  5341. }
  5342. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  5343. juce::AudioPluginInstance* find()
  5344. {
  5345. if (instrument)
  5346. {
  5347. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  5348. return &p->getInstance();
  5349. }
  5350. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  5351. return &p->getInstance();
  5352. return nullptr;
  5353. }
  5354. // a few blocks through the plugin (the offline engine has no audio thread): they carry parameter changes to
  5355. // the plugin's process and its values back
  5356. void pump (int blocks)
  5357. {
  5358. std::vector<float> l (512), r (512);
  5359. lynx::EffectParams none {};
  5360. for (int b = 0; b < blocks; ++b)
  5361. {
  5362. std::fill (l.begin(), l.end(), 0.0f);
  5363. std::fill (r.begin(), r.end(), 0.0f);
  5364. if (instrument)
  5365. {
  5366. if (auto in = engine->getChannelInstrument (channelIndex))
  5367. in->render (l.data(), r.data(), 512, 1.0f, 1.0f);
  5368. }
  5369. else if (auto fx = engine->getEffect (1, 0))
  5370. fx->process (l.data(), r.data(), 512, none, 120.0);
  5371. }
  5372. }
  5373. juce::AudioProcessorParameter* firstParam()
  5374. {
  5375. if (instance != nullptr)
  5376. for (auto* candidate : instance->getParameters())
  5377. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  5378. return candidate;
  5379. return nullptr;
  5380. }
  5381. void openWindow()
  5382. {
  5383. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  5384. : std::shared_ptr<void> (engine->getEffect (1, 0));
  5385. lynx::PluginWindows::WrapperContext context { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  5386. if (instrument)
  5387. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  5388. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  5389. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  5390. }, instrument, instrument ? -1 : 1, instrument ? -1 : 0, {}, {} };
  5391. context.reload = [] {}; // (the test reloads by itself; with it the window shows the notice)
  5392. lynx::PluginWindows::open (owner, *instance, instance->getName(), std::move (context));
  5393. }
  5394. void shot (const char* name, bool settingsPage = false)
  5395. {
  5396. if (shots != juce::File() && instance != nullptr)
  5397. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  5398. }
  5399. void timerCallback() override
  5400. {
  5401. if (phase == 0) // waiting for the engine to host the plugin
  5402. {
  5403. instance = find();
  5404. if (instance == nullptr)
  5405. {
  5406. if (elapsed() > 20000)
  5407. finish ("not hosted");
  5408. return;
  5409. }
  5410. pid = firstPid = lynx::sandboxedPluginProcessId (*instance);
  5411. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName + " pid=" + juce::String (pid));
  5412. expect ("separate_process", lynx::isSandboxedPlugin (*instance) && pid != 0);
  5413. expect ("running", ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  5414. // a setting that is captured (what a save or a backup does), then one that is not
  5415. if (auto* param = firstParam())
  5416. {
  5417. param->setValue (param->getValue() > 0.5f ? 0.13f : 0.87f);
  5418. pump (4);
  5419. engine->capturePluginStates();
  5420. captured = param->getValue();
  5421. param->setValue (captured > 0.5f ? 0.31f : 0.69f);
  5422. pump (4);
  5423. step ("param=" + param->getName (64) + " captured=" + juce::String (captured, 4) + " then=" + juce::String (param->getValue(), 4));
  5424. }
  5425. else
  5426. {
  5427. engine->capturePluginStates();
  5428. step ("param=none");
  5429. }
  5430. channelsBefore = engine->getSong().channels;
  5431. historyBefore = engine->getHistoryPosition();
  5432. modifiedBefore = engine->isModified();
  5433. if (shots != juce::File())
  5434. openWindow();
  5435. next (1);
  5436. return;
  5437. }
  5438. if (phase == 1 && elapsed() >= 600) // the plugin's process goes
  5439. {
  5440. shot (round == 0 ? "window-running" : "window-reloaded");
  5441. if (waitKill && round == 0)
  5442. {
  5443. juce::File (reportPath + ".pid").replaceWithText (juce::String (pid));
  5444. step ("waiting_for_kill pid=" + juce::String (pid));
  5445. }
  5446. else
  5447. lynx::crashSandboxedPluginForTest (*instance);
  5448. next (2);
  5449. return;
  5450. }
  5451. if (phase == 2) // LYNX notices
  5452. {
  5453. if (! engine->hostedPluginDown (where()))
  5454. {
  5455. pump (1); // (as the audio thread would: a block that gets no answer marks it too)
  5456. if (elapsed() > (waitKill && round == 0 ? 120000 : 10000))
  5457. finish ("the plugin never went down");
  5458. return;
  5459. }
  5460. step ("down_after_ms=" + juce::String (elapsed()));
  5461. const auto down = engine->downHostedPlugins();
  5462. expect ("listed_down", down.size() == 1 && down.front() == where());
  5463. expect ("listed_by_name", engine->downHostedPlugins (nameInSong()).size() == 1 && engine->downHostedPlugins ("no such plugin").empty());
  5464. next (3);
  5465. return;
  5466. }
  5467. if (phase == 3 && elapsed() >= 1500) // nothing reloads by itself
  5468. {
  5469. expect ("still_down_without_asking", engine->hostedPluginDown (where()) && find() == instance
  5470. && lynx::sandboxedPluginProcessId (*instance) == pid);
  5471. shot (round == 0 ? "reload-notice" : "reload-notice-again");
  5472. if (shots != juce::File() && round == 0)
  5473. {
  5474. lynx::PluginWindows::close (*instance);
  5475. lynx::PluginWindows::promptReload (*engine, where(), {});
  5476. next (4);
  5477. return;
  5478. }
  5479. next (5);
  5480. return;
  5481. }
  5482. if (phase == 4 && elapsed() >= 500) // the prompt a click on the channel / slot shows
  5483. {
  5484. auto found = false;
  5485. for (int c = juce::Desktop::getInstance().getNumComponents(); --c >= 0;)
  5486. if (auto* alert = dynamic_cast<juce::AlertWindow*> (juce::Desktop::getInstance().getComponent (c)))
  5487. {
  5488. const auto image = alert->createComponentSnapshot (alert->getLocalBounds(), true, 1.0f);
  5489. juce::FileOutputStream out (shots.getChildFile ("reload-prompt.png"));
  5490. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  5491. alert->exitModalState (0); // Close: nothing reloads
  5492. break;
  5493. }
  5494. step ("shot_reload-prompt=" + juce::String ((int) found));
  5495. next (45);
  5496. return;
  5497. }
  5498. if (phase == 45 && elapsed() >= 300)
  5499. {
  5500. expect ("still_down_after_close", engine->hostedPluginDown (where()));
  5501. next (5);
  5502. return;
  5503. }
  5504. if (phase == 5) // Reload, as the notice's button / the prompt / the menu item do
  5505. {
  5506. auto* old = instance;
  5507. const auto running = lynx::PluginWindows::reload (*engine, { where() });
  5508. instance = find();
  5509. const auto newPid = instance != nullptr ? lynx::sandboxedPluginProcessId (*instance) : 0;
  5510. expect ("reloaded", running == 1 && instance != nullptr && ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  5511. expect ("new_process", newPid != 0 && newPid != pid);
  5512. step ("pid=" + juce::String (newPid) + " same_object=" + juce::String ((int) (instance == old)));
  5513. expect ("old_window_closed", ! lynx::PluginWindows::isOpen (*old) || instance == old);
  5514. pid = newPid;
  5515. if (instance != nullptr)
  5516. {
  5517. pump (4);
  5518. if (auto* param = firstParam(); param != nullptr && captured >= 0.0f)
  5519. {
  5520. step ("param_after_reload=" + juce::String (param->getValue(), 4));
  5521. expect ("state_captured_last", std::abs (param->getValue() - captured) < 0.02f);
  5522. }
  5523. }
  5524. expect ("song_untouched", engine->getSong().channels == channelsBefore);
  5525. expect ("no_undo_step", engine->getHistoryPosition() == historyBefore && engine->isModified() == modifiedBefore);
  5526. if (instance == nullptr)
  5527. {
  5528. finish ("no instance after the reload");
  5529. return;
  5530. }
  5531. if (shots != juce::File())
  5532. openWindow();
  5533. if (round == 0) // once more: a plugin that crashes again waits for the user again
  5534. {
  5535. round = 1;
  5536. next (1);
  5537. return;
  5538. }
  5539. next (6);
  5540. return;
  5541. }
  5542. if (phase == 6 && elapsed() >= 400) // an edit and its undo keep the reloaded plugin
  5543. {
  5544. shot ("window-reloaded-twice");
  5545. auto* before = find();
  5546. engine->editSong ([] (lynx::Song& song) { song.bpm += 1.0f; });
  5547. engine->undo();
  5548. expect ("undo_keeps_the_reloaded_plugin", find() == before && ! engine->hostedPluginDown (where()));
  5549. lynx::PluginWindows::closeAll();
  5550. finish ({});
  5551. }
  5552. }
  5553. std::string nameInSong() const
  5554. {
  5555. const auto& song = engine->getSong();
  5556. return instrument ? song.channels[(size_t) channelIndex].plugin.name : song.mixer[1].effects[0].plugin.name;
  5557. }
  5558. void finish (const juce::String& failure)
  5559. {
  5560. stopTimer();
  5561. if (failure.isNotEmpty())
  5562. step ("failed=" + failure);
  5563. ok = ok && failure.isEmpty();
  5564. step (ok ? "result=OK" : "result=FAILED");
  5565. lynx::PluginWindows::closeAll();
  5566. done (ok);
  5567. }
  5568. };
  5569. lynx::setPluginSandboxAlerts (true); // (the deaths are recorded as in the app; no box: there is no main component)
  5570. auto* test = new Test();
  5571. test->reportPath = reportPath;
  5572. test->waitKill = waitKill;
  5573. if (shotsPath.isNotEmpty())
  5574. {
  5575. test->shots = juce::File (shotsPath);
  5576. test->shots.createDirectory();
  5577. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5578. }
  5579. juce::File (reportPath + ".pid").deleteFile();
  5580. test->done = [this, test] (bool ok) {
  5581. setApplicationReturnValue (ok ? 0 : 1);
  5582. juce::MessageManager::callAsync ([this, test] {
  5583. lynx::setMainWindowForOwnership (nullptr);
  5584. test->mainWindow = nullptr;
  5585. test->engine = nullptr;
  5586. delete test;
  5587. quit();
  5588. });
  5589. };
  5590. test->engine = std::make_unique<lynx::AudioEngine> (false);
  5591. if (shotsPath.isNotEmpty())
  5592. {
  5593. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  5594. test->mainWindow->setBounds (20, 20, 300, 200);
  5595. test->mainWindow->setVisible (true);
  5596. lynx::setMainWindowForOwnership (test->mainWindow.get());
  5597. }
  5598. auto& host = test->engine->getPluginHost();
  5599. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  5600. std::optional<juce::PluginDescription> chosen;
  5601. for (const auto& type : host.getKnownPlugins().getTypes())
  5602. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  5603. {
  5604. chosen = type;
  5605. break;
  5606. }
  5607. if (! chosen)
  5608. {
  5609. test->step ("result=FAILED (no plugin)");
  5610. test->done (false);
  5611. return;
  5612. }
  5613. test->instrument = chosen->isInstrument;
  5614. lynx::PluginRef ref;
  5615. ref.separateProcess = true;
  5616. ref.id = chosen->createIdentifierString().toStdString();
  5617. ref.name = chosen->name.toStdString();
  5618. test->engine->editSong ([&] (lynx::Song& song) {
  5619. if (test->instrument)
  5620. {
  5621. lynx::ChannelDef c;
  5622. c.name = ref.name;
  5623. c.instrument = lynx::InstrumentKind::plugin;
  5624. c.plugin = ref;
  5625. test->channelIndex = (int) song.channels.size();
  5626. song.channels.push_back (c);
  5627. }
  5628. else
  5629. {
  5630. while (song.mixer.size() < 2)
  5631. song.mixer.emplace_back();
  5632. lynx::EffectSlot slot;
  5633. slot.kind = lynx::EffectKind::plugin;
  5634. slot.plugin = ref;
  5635. song.mixer[1].effects.push_back (slot);
  5636. }
  5637. });
  5638. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  5639. test->next (0);
  5640. test->startTimerHz (20);
  5641. }
  5642. void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
  5643. {
  5644. struct Test final : juce::Timer
  5645. {
  5646. juce::String reportPath, report;
  5647. std::unique_ptr<lynx::AudioEngine> engine;
  5648. bool instrument = false;
  5649. int phase = 0, ticks = 0, seconds = 15, dockStep = 0;
  5650. juce::uint32 phaseStartMs = 0; // (phase 1 counts real time: the timer's ticks ran faster than 20 Hz here)
  5651. juce::AudioPluginInstance* instance = nullptr;
  5652. juce::AudioProcessorParameter* checked = nullptr;
  5653. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  5654. lynx::Workspace* workspace = nullptr; // LYNX_PLUGWIN_DOCK=1: the real main window's desktop (issue #116)
  5655. int channelIndex = -1; // an instrument: its channel (added after the song's own channels)
  5656. int stepMs = 3000; // dock mode: each state held that long (screenshots)
  5657. bool keysDone = false;
  5658. bool dockOk = true;
  5659. std::function<void (bool)> done;
  5660. // issue #116 (with LYNX_DOCKED_PLUGINS=1 and LYNX_PLUGWIN_DOCK=1), FL's f116 sequence for every floating
  5661. // panel: the docked plugin window goes behind a clicked panel and comes back in front when clicked; a
  5662. // panel called by its key comes in front too; Detached reopens it as a window of its own, which stays above
  5663. // every panel clicked (it is owned by the main window).
  5664. const std::array<lynx::workspace::Panel, 4> dockPanels { lynx::workspace::Panel::channelRack, lynx::workspace::Panel::playlist,
  5665. lynx::workspace::Panel::pianoRoll, lynx::workspace::Panel::mixer };
  5666. const int dockSteps = 2 * 4 + 18; // (the last one reports dock_result)
  5667. int danceChannel = -1; // issue #116 slice 4: a dance channel's dancer over the docked plugin
  5668. lynx::MainComponent* ui = nullptr; // dock mode: the real main window's contents
  5669. struct ScaleSpy final : juce::ComponentPeer::ScaleFactorListener
  5670. {
  5671. int calls = 0;
  5672. double last = 0.0;
  5673. void nativeScaleFactorChanged (double s) override { ++calls; last = s; }
  5674. } scaleSpy;
  5675. juce::ComponentPeer* spiedPeer = nullptr;
  5676. void* panelHandle (lynx::workspace::Panel p) const { return workspace->getFrame (p).getWindowHandle(); }
  5677. void dockCheck (int at)
  5678. {
  5679. using lynx::workspace::Panel;
  5680. auto* main = mainWindow->getWindowHandle();
  5681. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  5682. auto expect = [this] (const juce::String& name, bool value) {
  5683. step (name + "=" + juce::String ((int) value));
  5684. dockOk = dockOk && value;
  5685. };
  5686. auto id = [] (Panel p) { return juce::String (lynx::workspace::panelId (p)); };
  5687. if (at == 0)
  5688. {
  5689. expect ("docked", lynx::PluginWindows::isDocked (*instance));
  5690. expect ("plugin_native_child", plug != nullptr && lynx::nativechild::parentOf (plug) == main);
  5691. for (auto p : dockPanels)
  5692. {
  5693. auto* h = panelHandle (p);
  5694. expect (id (p) + "_visible", workspace->isPanelVisible (p));
  5695. expect (id (p) + "_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  5696. expect ("plugin_above_" + id (p) + "_when_opened", lynx::nativechild::isAbove (plug, h));
  5697. }
  5698. expect ("browser_plain", ! workspace->isNativePanel (Panel::browser));
  5699. }
  5700. if (at < 2 * 4)
  5701. {
  5702. const auto p = dockPanels[at / 2];
  5703. if (at % 2 == 0)
  5704. {
  5705. workspace->activate (p); // a click on the panel
  5706. expect (id (p) + "_above_plugin_after_its_click", lynx::nativechild::isAbove (panelHandle (p), plug));
  5707. // the plugin stays above the panels nobody clicked
  5708. for (auto other : dockPanels)
  5709. if (other != p)
  5710. expect ("plugin_above_" + id (other) + "_after_" + id (p) + "_click", lynx::nativechild::isAbove (plug, panelHandle (other)));
  5711. }
  5712. else
  5713. {
  5714. lynx::PluginWindows::open ({}, *instance, {}); // (open again = a click on the plugin)
  5715. expect ("plugin_above_" + id (p) + "_after_plugin_click", lynx::nativechild::isAbove (plug, panelHandle (p)));
  5716. }
  5717. return;
  5718. }
  5719. if (at == 8)
  5720. {
  5721. // a layout change elsewhere (a panel resized, the Browser shown) keeps the plugin in front; a panel
  5722. // called by its key comes in front of it
  5723. workspace->hide (Panel::browser);
  5724. workspace->show (Panel::browser);
  5725. for (auto p : dockPanels)
  5726. expect ("plugin_above_" + id (p) + "_after_layout_change", lynx::nativechild::isAbove (plug, panelHandle (p)));
  5727. workspace->show (Panel::mixer);
  5728. expect ("mixer_above_plugin_after_show", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  5729. }
  5730. else if (at == 9)
  5731. {
  5732. // the setup wizard (Options › Setup wizard; first start) in front of the native panels and the plugin
  5733. ui->showSetupWizard();
  5734. }
  5735. else if (at == 10)
  5736. {
  5737. auto* overlay = ui->setupOverlayForTest();
  5738. auto* h = overlay != nullptr ? overlay->getWindowHandle() : nullptr;
  5739. expect ("setup_overlay_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  5740. expect ("setup_overlay_above_plugin", lynx::nativechild::isAbove (h, plug));
  5741. for (auto p : dockPanels)
  5742. expect ("setup_overlay_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  5743. workspace->activate (Panel::playlist); // (a panel brought in front by code: the overlay stays in front)
  5744. lynx::PluginWindows::open ({}, *instance, {});
  5745. expect ("setup_overlay_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::playlist)));
  5746. }
  5747. else if (at == 11)
  5748. {
  5749. ui->closeSetupWizardForSnapshot();
  5750. expect ("setup_overlay_closed", ui->setupOverlayForTest() == nullptr);
  5751. // drops: JUCE's list of windows in the native stacking order once a drag starts
  5752. workspace->activate (Panel::mixer);
  5753. workspace->hide (Panel::browser);
  5754. workspace->show (Panel::browser);
  5755. lynx::matchWindowOrderToScreen();
  5756. auto children = lynx::nativechild::attachedChildren (main);
  5757. auto& desktop = juce::Desktop::getInstance();
  5758. int last = -1;
  5759. bool ordered = children.size() >= 5;
  5760. for (auto* c : children)
  5761. if (c->isVisible())
  5762. {
  5763. int at2 = -1;
  5764. for (int k = 0; k < desktop.getNumComponents(); ++k)
  5765. if (desktop.getComponent (k) == c)
  5766. at2 = k;
  5767. ordered = ordered && at2 > last;
  5768. last = at2;
  5769. }
  5770. expect ("drop_order_matches_screen", ordered);
  5771. }
  5772. else if (at == 12)
  5773. {
  5774. // the main window's scale changes (a display with another scale): every native child placed again in
  5775. // physical pixels, the docked editor's window told (JUCE tells child windows nothing by itself)
  5776. for (int i = 0; i < juce::ComponentPeer::getNumPeers(); ++i)
  5777. if (auto* peer = juce::ComponentPeer::getPeer (i); peer != nullptr && peer->getNativeHandle() == plug)
  5778. spiedPeer = peer;
  5779. if (spiedPeer != nullptr)
  5780. spiedPeer->addScaleFactorListener (&scaleSpy);
  5781. lynx::nativechild::notifyScaleListenersForTest (*mainWindow);
  5782. juce::Desktop::getInstance().setGlobalScaleFactor (1.25f); // and LYNX's own UI zoom
  5783. }
  5784. else if (at == 13)
  5785. {
  5786. bool placed = true;
  5787. for (auto* c : lynx::nativechild::attachedChildren (main))
  5788. placed = placed && (! c->isVisible() || lynx::nativechild::placedPhysically (*c));
  5789. expect ("native_children_placed_at_125", placed);
  5790. expect ("docked_editor_told_the_scale", scaleSpy.calls > 0 && spiedPeer != nullptr
  5791. && std::abs (scaleSpy.last - spiedPeer->getPlatformScaleFactor()) < 0.001);
  5792. if (spiedPeer != nullptr && juce::ComponentPeer::isValidPeer (spiedPeer))
  5793. spiedPeer->removeScaleFactorListener (&scaleSpy);
  5794. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  5795. lynx::PluginWindows::setDetached (*instance, true);
  5796. }
  5797. else if (at == 14)
  5798. {
  5799. expect ("detached_reopened", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance));
  5800. expect ("detached_owned_by_main", plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  5801. expect ("detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  5802. for (auto p : dockPanels)
  5803. workspace->activate (p);
  5804. }
  5805. else if (at == 15)
  5806. {
  5807. // (an owned top-level window: above the main window and so above all its child windows)
  5808. expect ("detached_stays_above_clicked_panels", plug != nullptr && lynx::nativechild::ownerOf (plug) == main
  5809. && lynx::nativechild::parentOf (plug) != main && lynx::PluginWindows::isOpen (*instance));
  5810. lynx::PluginWindows::setDetached (*instance, false);
  5811. }
  5812. else if (at == 16)
  5813. {
  5814. // issue #116 slice 4: a Fruity Dance dancer standing on the docked plugin window, in front of it
  5815. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  5816. juce::Rectangle<int> over;
  5817. for (auto* c : lynx::nativechild::attachedChildren (main))
  5818. if (c->getWindowHandle() == plug)
  5819. over = ui->getLocalArea (nullptr, c->getScreenBounds());
  5820. expect ("dance_stage", stage != nullptr && ! over.isEmpty());
  5821. lynx::dance::Settings s;
  5822. s.move = lynx::dance::held; // (a still pose: the pixels tested below stay where they are)
  5823. s.x = over.getCentreX();
  5824. s.y = over.getCentreY() + 70;
  5825. const auto state = lynx::dance::toState (s);
  5826. engine->editSongStructural ([this, state] (lynx::Song& song) {
  5827. lynx::ChannelDef c;
  5828. c.name = "Fruity Dance";
  5829. c.instrument = lynx::InstrumentKind::fruitydance;
  5830. c.pluginState = state;
  5831. danceChannel = (int) song.channels.size();
  5832. song.channels.push_back (c);
  5833. });
  5834. engine->dispatchPendingMessages();
  5835. if (stage != nullptr)
  5836. stage->update();
  5837. }
  5838. else if (at == 17)
  5839. {
  5840. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  5841. auto* w = stage != nullptr ? stage->windowOf (danceChannel) : nullptr;
  5842. auto* h = w != nullptr ? w->getWindowHandle() : nullptr;
  5843. expect ("dancer_window_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  5844. expect ("dancer_window_layered", lynx::nativechild::isLayered (h));
  5845. expect ("dancer_above_plugin", lynx::nativechild::isAbove (h, plug));
  5846. for (auto p : dockPanels)
  5847. expect ("dancer_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  5848. // panels and the plugin brought in front (clicks, keys): the dancer stays in front of them
  5849. workspace->activate (Panel::mixer);
  5850. workspace->show (Panel::pianoRoll);
  5851. lynx::PluginWindows::open ({}, *instance, {});
  5852. expect ("dancer_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::mixer))
  5853. && lynx::nativechild::isAbove (h, panelHandle (Panel::pianoRoll)));
  5854. // the mouse: the dancer's body takes it, its window's transparent pixels let it through
  5855. if (w != nullptr)
  5856. {
  5857. const auto picture = w->createComponentSnapshot (w->getLocalBounds(), true, 1.0f);
  5858. const auto body = stage->bodyOf (danceChannel) - (w->getScreenPosition() - stage->getScreenPosition());
  5859. juce::Point<int> solid { -1, -1 }, clear { -1, -1 };
  5860. for (int y = body.getCentreY() - 10; y < body.getBottom() && solid.x < 0; ++y)
  5861. for (int x = body.getX(); x < body.getRight() && solid.x < 0; ++x)
  5862. if (picture.getBounds().contains (x, y) && picture.getPixelAt (x, y).getAlpha() == 255)
  5863. solid = { x, y };
  5864. for (int y = 0; y < picture.getHeight() && clear.x < 0; y += 2)
  5865. for (int x = 0; x < picture.getWidth() && clear.x < 0; x += 2)
  5866. if (picture.getPixelAt (x, y).getAlpha() == 0 && ! body.expanded (8).contains (x, y))
  5867. clear = { x, y };
  5868. step ("dancer_window=" + w->getBounds().toString() + " solid=" + solid.toString() + " clear=" + clear.toString());
  5869. auto* atSolid = lynx::nativechild::windowAt (*w, solid);
  5870. auto* atClear = lynx::nativechild::windowAt (*w, clear);
  5871. expect ("dancer_takes_its_body_clicks", solid.x >= 0 && atSolid == h);
  5872. expect ("dancer_lets_clicks_through", clear.x >= 0 && atClear != nullptr && atClear != h);
  5873. expect ("stage_leaves_the_mouse", ! stage->hitTest (stage->bodyOf (danceChannel).getCentreX(), stage->bodyOf (danceChannel).getCentreY()));
  5874. }
  5875. }
  5876. else if (at == 18)
  5877. {
  5878. // no dance channel: no dancer window (nothing drawn, no cost)
  5879. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  5880. engine->editSongStructural ([this] (lynx::Song& song) {
  5881. if (danceChannel >= 0 && danceChannel < (int) song.channels.size())
  5882. song.channels.erase (song.channels.begin() + danceChannel);
  5883. });
  5884. engine->dispatchPendingMessages();
  5885. if (stage != nullptr)
  5886. stage->update();
  5887. expect ("dancer_window_gone", stage != nullptr && stage->windowCount() == 0);
  5888. }
  5889. else if (at == 19 || at == 20)
  5890. {
  5891. // round 190ev (issue #152, "flickering windows"): on Windows a docked panel no longer fades by its
  5892. // window's alpha (each fade switched its drawing surface twice and the panel flashed); it shows and
  5893. // hides at once, as FL's docked windows. Elsewhere round 190i's fade stays.
  5894. auto& frame = workspace->getFrame (Panel::mixer);
  5895. if (at == 19)
  5896. {
  5897. workspace->show (Panel::mixer);
  5898. expect ("mixer_above_plugin_when_shown", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  5899. workspace->hide (Panel::mixer);
  5900. expect ("mixer_hides_at_once", ! frame.isVisible() && workspace->nativeFadeDirection (Panel::mixer) == 0
  5901. && frame.getAlpha() == 1.0f && ! lynx::nativechild::isLayered (frame.getWindowHandle()));
  5902. }
  5903. else
  5904. {
  5905. workspace->show (Panel::mixer);
  5906. expect ("mixer_shows_at_once", frame.isVisible() && frame.getAlpha() == 1.0f && workspace->nativeFadeDirection (Panel::mixer) == 0
  5907. && ! lynx::nativechild::isLayered (frame.getWindowHandle())
  5908. && lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  5909. }
  5910. }
  5911. else if (at >= 21 && at <= 23)
  5912. {
  5913. // round 190ev (issue #152, "the Channel rack almost never comes to the front"): LYNX's own editor
  5914. // windows (here a channel's settings) are docked like FL's plugin windows, so a click on the rack
  5915. // brings the rack in front of them and a click on one brings it back; a click inside a docked
  5916. // plugin's own view (a native window JUCE never hears of) brings that plugin window in front.
  5917. auto docked = [] {
  5918. auto& desktop = juce::Desktop::getInstance();
  5919. for (int i = 0; i < desktop.getNumComponents(); ++i)
  5920. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible() && (bool) c->getProperties()["lynxDockedWindow"])
  5921. return c;
  5922. return (juce::Component*) nullptr;
  5923. };
  5924. auto* rack = panelHandle (Panel::channelRack);
  5925. if (at == 21)
  5926. {
  5927. lynx::openChannelSettings (*engine, 0);
  5928. auto* ed = docked();
  5929. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  5930. expect ("editor_docked", h != nullptr && lynx::nativechild::parentOf (h) == main && lynx::nativechild::ownerOf (h) == nullptr);
  5931. expect ("editor_above_rack_when_opened", h != nullptr && lynx::nativechild::isAbove (h, rack));
  5932. workspace->activate (Panel::channelRack); // a click on the rack
  5933. expect ("rack_above_editor_after_its_click", h != nullptr && lynx::nativechild::isAbove (rack, h));
  5934. // a real click (a message to the editor's own window) on its title bar, at a point where the editor
  5935. // can be seen. Round 190fc (0.1.27 RC M1): JUCE takes a button-down only where the system says its
  5936. // window is the one under the point (HWNDComponentPeer::contains asks WindowFromPoint), so the old
  5937. // fixed point (60, 8) was dropped whenever the rack, raised just above, covered it there: the
  5938. // check read 0 while real clicks (on what can be seen) raise the editor.
  5939. if (h != nullptr && ed != nullptr)
  5940. {
  5941. juce::Point<int> at (-1, -1);
  5942. for (int x = 30; x < ed->getWidth() - 40 && at.x < 0; x += 12)
  5943. if (lynx::nativechild::windowAt (*ed, { x, 8 }) == h)
  5944. at = { x, 8 };
  5945. step (juce::String ("editor_title_visible_at=") + juce::String (at.x));
  5946. if (at.x >= 0)
  5947. {
  5948. const auto scale = ed->getPeer() != nullptr ? ed->getPeer()->getPlatformScaleFactor() * (double) ed->getDesktopScaleFactor() : 1.0;
  5949. lynx::nativechild::postClickForTest (h, (at.toDouble() * scale).roundToInt());
  5950. }
  5951. }
  5952. }
  5953. else if (at == 22)
  5954. {
  5955. auto* ed = docked();
  5956. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  5957. expect ("editor_above_rack_after_its_click", h != nullptr && lynx::nativechild::isAbove (h, rack));
  5958. workspace->activate (Panel::channelRack);
  5959. expect ("rack_above_plugin_after_its_click", lynx::nativechild::isAbove (rack, plug));
  5960. auto* view = lynx::nativechild::innermostChild (plug);
  5961. step (juce::String ("plugin_view_window=") + (view != nullptr ? "1" : "0"));
  5962. if (view != nullptr) // a click in the plugin's own view, near its top-left corner
  5963. lynx::nativechild::postClickForTest (view, { 2, 2 });
  5964. }
  5965. else
  5966. {
  5967. if (lynx::nativechild::innermostChild (plug) != nullptr)
  5968. expect ("plugin_above_rack_after_click_in_its_view", lynx::nativechild::isAbove (plug, rack));
  5969. lynx::closeChannelSettings();
  5970. // FL's Tools > Macros > Switch all plugin editors to > Detached (round 190i)
  5971. lynx::PluginWindows::setAllDetached (*engine, true);
  5972. }
  5973. }
  5974. else if (at == 24)
  5975. {
  5976. expect ("macro_detached_the_open_editor", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance)
  5977. && plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  5978. expect ("macro_detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  5979. lynx::PluginWindows::setAllDetached (*engine, false); // ... > Attached
  5980. }
  5981. else
  5982. {
  5983. expect ("docked_again", lynx::PluginWindows::isDocked (*instance) && engineRef() != nullptr && ! engineRef()->detached);
  5984. step (juce::String ("dock_result=") + (dockOk ? "OK" : "FAILED"));
  5985. }
  5986. }
  5987. const lynx::PluginRef* engineRef() const
  5988. {
  5989. const auto& song = engine->getSong();
  5990. if (instrument)
  5991. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  5992. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  5993. }
  5994. void step (const juce::String& line)
  5995. {
  5996. report << line << "\n";
  5997. juce::File (reportPath).replaceWithText (report);
  5998. }
  5999. juce::AudioPluginInstance* find()
  6000. {
  6001. if (instrument)
  6002. {
  6003. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  6004. return &p->getInstance();
  6005. }
  6006. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  6007. return &p->getInstance();
  6008. return nullptr;
  6009. }
  6010. void timerCallback() override
  6011. {
  6012. ++ticks;
  6013. if (phase == 0) // waiting for the engine to host the plugin
  6014. {
  6015. instance = find();
  6016. if (instance == nullptr)
  6017. {
  6018. if (ticks > 200)
  6019. {
  6020. step ("result=FAILED (not hosted)");
  6021. stopTimer();
  6022. done (false);
  6023. }
  6024. return;
  6025. }
  6026. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  6027. step ("programs=" + juce::String (instance->getNumPrograms()));
  6028. for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
  6029. step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
  6030. step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
  6031. // preset round trip: save, change the first parameter, load, compare
  6032. juce::AudioProcessorParameter* param = nullptr;
  6033. for (auto* candidate : instance->getParameters())
  6034. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  6035. {
  6036. param = candidate;
  6037. break;
  6038. }
  6039. if (param != nullptr)
  6040. {
  6041. step ("param=" + param->getName (64));
  6042. checked = param;
  6043. const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
  6044. juce::String error;
  6045. const auto before = param->getValue();
  6046. const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
  6047. param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
  6048. const auto changed = param->getValue();
  6049. const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
  6050. step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
  6051. + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
  6052. + (error.isNotEmpty() ? " error=" + error : juce::String()));
  6053. for (const auto* ext : { "fxp", "fxb", "vstpreset" })
  6054. {
  6055. juce::String e2;
  6056. const auto f2 = file.withFileExtension (ext);
  6057. const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
  6058. step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
  6059. f2.deleteFile();
  6060. }
  6061. step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
  6062. }
  6063. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  6064. : std::shared_ptr<void> (engine->getEffect (1, 0));
  6065. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  6066. { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  6067. if (instrument)
  6068. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  6069. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  6070. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  6071. }, instrument });
  6072. owner.reset();
  6073. step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  6074. phase = 1;
  6075. ticks = 0;
  6076. phaseStartMs = juce::Time::getMillisecondCounter();
  6077. return;
  6078. }
  6079. if (phase == 1 && ticks >= 30 && ! keysDone && juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_KEYS", {}).isNotEmpty() && instance->getActiveEditor() != nullptr)
  6080. keysDone = ! lynx::pluginKeysTestTick (*instance->getActiveEditor(),
  6081. [this] (bool on) {
  6082. engine->editSong ([this, on] (lynx::Song& song) {
  6083. (instrument ? song.channels[(size_t) channelIndex].plugin : song.mixer[1].effects[0].plugin).hostKeysFirst = on;
  6084. });
  6085. },
  6086. [this] (const juce::String& line) { step (line); });
  6087. const auto elapsedMs = (int) (juce::Time::getMillisecondCounter() - phaseStartMs);
  6088. if (phase == 1 && ticks == 20 && checked != nullptr)
  6089. step ("param_after_1s=" + juce::String (checked->getValue(), 4));
  6090. // (3 s apart: time for screenshots of each state)
  6091. if (phase == 1 && workspace != nullptr && dockStep < dockSteps && elapsedMs >= (dockStep + 1) * stepMs)
  6092. dockCheck (dockStep++);
  6093. if (phase == 1 && elapsedMs >= seconds * 1000 && (workspace == nullptr || dockStep >= dockSteps)) // remove the plugin from the song
  6094. {
  6095. engine->editSong ([this] (lynx::Song& song) {
  6096. if (instrument)
  6097. {
  6098. if (channelIndex >= 0 && channelIndex < (int) song.channels.size())
  6099. song.channels.erase (song.channels.begin() + channelIndex);
  6100. }
  6101. else
  6102. song.mixer[1].effects.clear();
  6103. });
  6104. step ("removed");
  6105. phase = 2;
  6106. ticks = 0;
  6107. return;
  6108. }
  6109. if (phase == 2 && ticks >= 40)
  6110. {
  6111. const auto open = lynx::PluginWindows::isOpen (*instance);
  6112. step ("window_open_after_remove=" + juce::String ((int) open));
  6113. step (open || ! dockOk ? "result=FAILED" : "result=OK");
  6114. stopTimer();
  6115. lynx::PluginWindows::closeAll();
  6116. done (! open && dockOk);
  6117. }
  6118. }
  6119. };
  6120. auto* test = new Test();
  6121. test->reportPath = reportPath;
  6122. test->seconds = seconds;
  6123. test->done = [this, test] (bool ok) {
  6124. setApplicationReturnValue (ok ? 0 : 1);
  6125. juce::MessageManager::callAsync ([this, test] {
  6126. lynx::setMainWindowForOwnership (nullptr);
  6127. lynx::PluginWindows::setDockWorkspace (nullptr);
  6128. test->workspace = nullptr;
  6129. test->mainWindow = nullptr; // (dock mode: the main component with it, before the engine)
  6130. test->engine = nullptr;
  6131. delete test;
  6132. quit();
  6133. });
  6134. };
  6135. test->engine = std::make_unique<lynx::AudioEngine> (false);
  6136. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  6137. test->mainWindow->setBounds (20, 20, 300, 200);
  6138. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DOCK", {}) == "1" && lynx::nativechild::dockingEnabled())
  6139. {
  6140. // the real main window's contents (it docks plugin windows in its own desktop), so the panels are real
  6141. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6142. auto* ui = new lynx::MainComponent (*test->engine, false);
  6143. test->mainWindow->setUsingNativeTitleBar (true);
  6144. test->mainWindow->setContentOwned (ui, false);
  6145. test->mainWindow->setBounds (20, 20, 1500, 900);
  6146. test->workspace = &ui->workspaceForTest();
  6147. test->ui = ui;
  6148. if (const auto ms = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_STEP_MS", {}).getIntValue(); ms > 0)
  6149. test->stepMs = ms;
  6150. }
  6151. test->mainWindow->setVisible (true);
  6152. lynx::setMainWindowForOwnership (test->mainWindow.get());
  6153. if (test->workspace != nullptr)
  6154. {
  6155. using lynx::workspace::Panel;
  6156. for (auto p : { Panel::playlist, Panel::mixer, Panel::pianoRoll, Panel::channelRack })
  6157. test->workspace->show (p);
  6158. test->step ("dock_test=2 rack_visible=" + juce::String ((int) test->workspace->isPanelVisible (Panel::channelRack)));
  6159. }
  6160. auto& host = test->engine->getPluginHost();
  6161. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  6162. std::optional<juce::PluginDescription> chosen;
  6163. for (const auto& type : host.getKnownPlugins().getTypes())
  6164. if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  6165. && (only.isEmpty() || type.name == only))
  6166. {
  6167. chosen = type;
  6168. break;
  6169. }
  6170. if (! chosen)
  6171. {
  6172. test->step ("result=FAILED (no plugin)");
  6173. test->done (false);
  6174. return;
  6175. }
  6176. test->instrument = chosen->isInstrument;
  6177. lynx::PluginRef ref;
  6178. ref.separateProcess = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_SEPARATE", {}) == "1"; // (issue #96's other-process check)
  6179. ref.id = chosen->createIdentifierString().toStdString();
  6180. ref.name = chosen->name.toStdString();
  6181. test->engine->editSong ([&] (lynx::Song& song) {
  6182. if (test->instrument)
  6183. {
  6184. lynx::ChannelDef c;
  6185. c.name = ref.name;
  6186. c.instrument = lynx::InstrumentKind::plugin;
  6187. c.plugin = ref;
  6188. test->channelIndex = (int) song.channels.size();
  6189. song.channels.push_back (c);
  6190. }
  6191. else
  6192. {
  6193. while (song.mixer.size() < 2)
  6194. song.mixer.emplace_back();
  6195. lynx::EffectSlot slot;
  6196. slot.kind = lynx::EffectKind::plugin;
  6197. slot.plugin = ref;
  6198. song.mixer[1].effects.push_back (slot);
  6199. }
  6200. });
  6201. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  6202. test->startTimerHz (20);
  6203. }
  6204. void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
  6205. {
  6206. struct CrashTest final : juce::Timer
  6207. {
  6208. juce::String reportPath, report;
  6209. std::unique_ptr<lynx::PluginHost> host;
  6210. juce::AudioPluginInstance* plugin = nullptr;
  6211. std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
  6212. std::function<void (bool)> done;
  6213. int ticks = 0, crashesBefore = 0;
  6214. void step (const juce::String& line)
  6215. {
  6216. report << line << "\n";
  6217. juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
  6218. }
  6219. void timerCallback() override
  6220. {
  6221. ++ticks;
  6222. const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
  6223. const auto open = lynx::PluginWindows::isOpen (*plugin);
  6224. if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
  6225. {
  6226. stopTimer();
  6227. step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
  6228. bool traced = false;
  6229. if (crashes > 0)
  6230. {
  6231. const auto last = lynx::PluginWindows::editorCrashes().back();
  6232. traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
  6233. step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
  6234. + juce::String ((int) traced));
  6235. last.traceFile.deleteFile();
  6236. }
  6237. // still alive: one more message through the loop after the fault
  6238. juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
  6239. step ("message_loop_after_fault=1");
  6240. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  6241. done (ok);
  6242. });
  6243. }
  6244. }
  6245. };
  6246. auto* test = new CrashTest();
  6247. test->reportPath = reportPath;
  6248. test->done = [this, test] (bool ok)
  6249. {
  6250. setApplicationReturnValue (ok ? 0 : 1);
  6251. juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
  6252. };
  6253. #if ! JUCE_WINDOWS
  6254. test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
  6255. test->done (true);
  6256. return;
  6257. #else
  6258. _putenv_s ("LYNX_TEST_CRASH", "editor");
  6259. test->host = std::make_unique<lynx::PluginHost> (false);
  6260. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  6261. std::shared_ptr<juce::AudioPluginInstance> instance;
  6262. for (const auto& type : test->host->getKnownPlugins().getTypes())
  6263. {
  6264. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
  6265. continue;
  6266. juce::String error;
  6267. instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
  6268. test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
  6269. break;
  6270. }
  6271. if (instance == nullptr || ! instance->hasEditor())
  6272. {
  6273. test->step ("result=FAILED (no plugin with an editor)");
  6274. test->done (false);
  6275. return;
  6276. }
  6277. lynx::preparePlugin (*instance, 48000.0, 512);
  6278. test->plugin = instance.get();
  6279. test->keep = instance;
  6280. test->crashesBefore = lynx::PluginWindows::editorCrashCount();
  6281. lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
  6282. test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  6283. test->startTimer (100);
  6284. #endif
  6285. }
  6286. void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
  6287. {
  6288. struct EditorTest final : juce::Timer
  6289. {
  6290. juce::String reportPath, report;
  6291. std::unique_ptr<lynx::PluginHost> host;
  6292. std::unique_ptr<juce::AudioPluginInstance> plugin;
  6293. std::unique_ptr<juce::DocumentWindow> window;
  6294. std::function<void (bool)> done;
  6295. void step (const juce::String& line)
  6296. {
  6297. report << line << "\n";
  6298. juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
  6299. }
  6300. void timerCallback() override
  6301. {
  6302. stopTimer();
  6303. window = nullptr;
  6304. step ("step=closed");
  6305. plugin = nullptr;
  6306. step ("result=OK");
  6307. done (true);
  6308. }
  6309. };
  6310. auto* test = new EditorTest();
  6311. test->reportPath = reportPath;
  6312. test->done = [this, test] (bool ok)
  6313. {
  6314. setApplicationReturnValue (ok ? 0 : 1);
  6315. juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
  6316. };
  6317. test->host = std::make_unique<lynx::PluginHost> (false);
  6318. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  6319. test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
  6320. for (const auto& type : test->host->getKnownPlugins().getTypes())
  6321. {
  6322. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  6323. || (only.isNotEmpty() && type.name != only))
  6324. continue;
  6325. juce::String error;
  6326. test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
  6327. test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
  6328. break;
  6329. }
  6330. if (test->plugin == nullptr)
  6331. {
  6332. test->step ("result=FAILED");
  6333. test->done (false);
  6334. return;
  6335. }
  6336. lynx::preparePlugin (*test->plugin, 48000.0, 512);
  6337. test->step ("step=create_editor");
  6338. test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
  6339. test->window->setUsingNativeTitleBar (true);
  6340. if (auto* editor = test->plugin->createEditorIfNeeded())
  6341. test->window->setContentOwned (editor, true);
  6342. else
  6343. test->step ("no_editor");
  6344. test->step ("step=show");
  6345. test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
  6346. test->window->setVisible (true);
  6347. test->step ("step=shown");
  6348. test->startTimer (4000);
  6349. }
  6350. void runFitTest (const juce::String& reportPath, int percent)
  6351. {
  6352. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6353. struct FitTest final : juce::Timer
  6354. {
  6355. juce::String path, report;
  6356. bool ok = true;
  6357. int step = 0, percent = 150;
  6358. std::unique_ptr<juce::DocumentWindow> tall, big;
  6359. std::function<void()> done;
  6360. // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
  6361. void check (const juce::String& what, juce::Component& w, bool whole)
  6362. {
  6363. juce::BorderSize<int> frame;
  6364. if (auto* peer = w.getPeer())
  6365. if (const auto f = peer->getFrameSizeIfPresent())
  6366. frame = *f;
  6367. auto outer = frame.addedTo (w.getBounds());
  6368. const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
  6369. const auto area = display != nullptr ? display->userArea : outer;
  6370. #if JUCE_LINUX
  6371. // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
  6372. // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
  6373. const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
  6374. outer = outer.reduced (shadow);
  6375. const auto slack = shadow > 0 ? 4 : 0;
  6376. #else
  6377. const auto slack = 0;
  6378. #endif
  6379. const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
  6380. && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
  6381. report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
  6382. << frame.getLeft() << ") screen=" << area.toString() << "\n";
  6383. ok = ok && passed;
  6384. }
  6385. void start()
  6386. {
  6387. report << "scale=" << percent << "%\n";
  6388. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  6389. // a tool window taller than the screen, centred (its title bar would be above the screen)
  6390. tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
  6391. tall->setUsingNativeTitleBar (true);
  6392. auto* content = new juce::Component();
  6393. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  6394. content->setSize (500, area.getHeight() + 200);
  6395. tall->setContentOwned (content, true);
  6396. tall->setCentrePosition (area.getCentre());
  6397. tall->setVisible (true);
  6398. lynx::keepAboveMainWindow (*tall);
  6399. // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
  6400. startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
  6401. }
  6402. void timerCallback() override
  6403. {
  6404. ++step;
  6405. if (step == 1)
  6406. {
  6407. check ("tall tool window: title bar and close button on the screen", *tall, false);
  6408. tall.reset();
  6409. // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
  6410. auto content = std::make_unique<juce::Component>();
  6411. const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  6412. content->setSize (520, screen.getHeight() + 300);
  6413. lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
  6414. return;
  6415. }
  6416. if (step == 2)
  6417. {
  6418. if (auto* w = lynx::findToolWindow ("fittest-fixed"))
  6419. {
  6420. check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
  6421. const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
  6422. && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
  6423. report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
  6424. ok = ok && scrolls;
  6425. }
  6426. else
  6427. {
  6428. report << "FAIL fixed-size tool window not found\n";
  6429. ok = false;
  6430. }
  6431. lynx::closeAllToolWindows();
  6432. // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
  6433. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  6434. big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
  6435. big->setUsingNativeTitleBar (true);
  6436. big->setResizable (true, false);
  6437. big->setResizeLimits (400, 300, 10000, 10000);
  6438. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  6439. big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
  6440. big->setVisible (true);
  6441. return;
  6442. }
  6443. if (step == 3)
  6444. {
  6445. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  6446. juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
  6447. return;
  6448. }
  6449. if (step == 4)
  6450. {
  6451. check ("resizable window after the zoom change: fits the screen", *big, true);
  6452. big.reset();
  6453. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  6454. juce::File (path).replaceWithText (report);
  6455. stopTimer();
  6456. if (done)
  6457. done();
  6458. }
  6459. }
  6460. };
  6461. static std::unique_ptr<FitTest> test;
  6462. test = std::make_unique<FitTest>();
  6463. test->path = reportPath;
  6464. test->percent = juce::jlimit (50, 300, percent);
  6465. test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
  6466. test->start();
  6467. }
  6468. void runFocusTest (const juce::String& reportPath)
  6469. {
  6470. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6471. struct FocusTest final : juce::Timer
  6472. {
  6473. juce::String reportPath, report;
  6474. bool ok = true;
  6475. int stepIndex = 0;
  6476. std::unique_ptr<lynx::AudioEngine> engine;
  6477. lynx::MainComponent* ui = nullptr;
  6478. std::unique_ptr<juce::DocumentWindow> main;
  6479. std::function<void()> done;
  6480. void line (const juce::String& text)
  6481. {
  6482. report << text << "\n";
  6483. juce::File (reportPath).replaceWithText (report);
  6484. }
  6485. void check (const juce::String& what, bool passed)
  6486. {
  6487. line ((passed ? "ok " : "FAIL ") + what);
  6488. ok = ok && passed;
  6489. }
  6490. juce::ComponentPeer* mainPeer() const { return main != nullptr ? main->getPeer() : nullptr; }
  6491. bool focusInMain() const
  6492. {
  6493. auto* f = juce::Component::getCurrentlyFocusedComponent();
  6494. return f != nullptr && main->isParentOf (f);
  6495. }
  6496. // a click (press and release) at the middle of the panel's content, through the native window it is in
  6497. static void click (juce::Component& frame, bool right)
  6498. {
  6499. auto* peer = frame.getPeer();
  6500. if (peer == nullptr)
  6501. return;
  6502. const auto at = peer->getComponent().getLocalPoint (&frame, frame.getLocalBounds().getCentre().toFloat());
  6503. const auto button = right ? juce::ModifierKeys::rightButtonModifier : juce::ModifierKeys::leftButtonModifier;
  6504. const auto now = juce::Time::currentTimeMillis();
  6505. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (button), 1.0f, 0.0f, now);
  6506. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  6507. }
  6508. bool space()
  6509. {
  6510. auto* peer = mainPeer(); // (the system sends the key to the window with the focus: the main one)
  6511. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  6512. }
  6513. juce::TextEditor* firstField (juce::Component& c)
  6514. {
  6515. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && t->getWantsKeyboardFocus())
  6516. return t;
  6517. for (auto* child : c.getChildren())
  6518. if (auto* t = firstField (*child))
  6519. return t;
  6520. return nullptr;
  6521. }
  6522. // the user tabs away and comes back with a click in `panel`
  6523. void backWithClickIn (lynx::workspace::Panel panel, bool right)
  6524. {
  6525. auto& frame = ui->workspaceForTest().getFrame (panel);
  6526. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  6527. auto* peer = mainPeer();
  6528. line (name + ": native child window=" + juce::String ((int) lynx::nativechild::isAttached (frame)));
  6529. check (name + ": the main window has the keys before", ui->hasKeyboardFocus (true));
  6530. peer->handleFocusLoss(); // (another app is in front: the main window lost the system focus)
  6531. check (name + ": nothing in LYNX has the keys while it is in the background", ! focusInMain());
  6532. // the cause: JUCE answers the system's "activate?" from the panel's own component, which takes no focus on a click
  6533. line (name + ": JUCE's answer alone would activate the window=" + juce::String ((int) frame.getMouseClickGrabsKeyboardFocus()));
  6534. const auto activates = lynx::nativechild::clickActivatesWindow (frame, false);
  6535. check (name + ": a click in it activates the inactive main window", activates);
  6536. #if JUCE_WINDOWS
  6537. if (lynx::nativechild::isAttached (frame))
  6538. check (name + ": its native window answers WM_MOUSEACTIVATE with MA_ACTIVATE",
  6539. lynx::nativechild::mouseActivateAnswerForTest (frame, true) == 1 /* MA_ACTIVATE */);
  6540. #endif
  6541. if (activates)
  6542. peer->handleFocusGain(); // (the system activates the main window and gives it the focus)
  6543. click (frame, right);
  6544. }
  6545. void spacePlays (lynx::workspace::Panel panel, bool right)
  6546. {
  6547. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  6548. check (name + ": the main window has the keys after the click", ui->hasKeyboardFocus (true));
  6549. auto& transport = engine->getTransport();
  6550. if (transport.playing.load())
  6551. engine->stop();
  6552. const auto used = space();
  6553. check (name + ": Space starts playback", used && transport.playing.load());
  6554. engine->stop();
  6555. }
  6556. void timerCallback() override
  6557. {
  6558. using lynx::workspace::Panel;
  6559. auto& ws = ui->workspaceForTest();
  6560. switch (stepIndex++)
  6561. {
  6562. case 0:
  6563. line ("docking=" + juce::String ((int) lynx::nativechild::dockingEnabled()));
  6564. ws.show (Panel::playlist);
  6565. ws.show (Panel::pianoRoll);
  6566. ui->grabKeyboardFocus();
  6567. break;
  6568. case 1: backWithClickIn (Panel::playlist, false); break;
  6569. case 2: spacePlays (Panel::playlist, false); ui->grabKeyboardFocus(); break;
  6570. case 3: backWithClickIn (Panel::pianoRoll, false); break;
  6571. case 4: spacePlays (Panel::pianoRoll, false); ui->grabKeyboardFocus(); break;
  6572. case 5: backWithClickIn (Panel::playlist, true); break;
  6573. case 6:
  6574. juce::PopupMenu::dismissAllActiveMenus(); // (the right click's menu)
  6575. spacePlays (Panel::playlist, true);
  6576. break;
  6577. case 7:
  6578. {
  6579. // a text field (the Browser's search box) keeps the keys through a switch to another app and back:
  6580. // nothing in LYNX takes them from it (no periodic grab); inside the active window the click's
  6581. // activation answer is unchanged, and a click in the Playlist ends the typing as before (issue #9,
  6582. // as FL ends typing in its search field)
  6583. auto* field = firstField (*ui);
  6584. line ("text field found=" + juce::String ((int) (field != nullptr)));
  6585. if (field != nullptr)
  6586. {
  6587. auto& frame = ws.getFrame (Panel::playlist);
  6588. field->grabKeyboardFocus();
  6589. check ("the text field has the keys", field->hasKeyboardFocus (false));
  6590. mainPeer()->handleFocusLoss();
  6591. mainPeer()->handleFocusGain(); // (back with Alt+Tab, or a click that activates the window)
  6592. check ("the text field gets the keys back with the window", field->hasKeyboardFocus (false));
  6593. check ("active window: a click in a panel does not activate it again", ! lynx::nativechild::clickActivatesWindow (frame, true));
  6594. click (frame, false);
  6595. check ("a click in the Playlist ends the typing: the main window has the keys", ui->hasKeyboardFocus (true) && ! field->hasKeyboardFocus (false));
  6596. }
  6597. line (ok ? "result=OK" : "result=FAILED");
  6598. stopTimer();
  6599. done();
  6600. break;
  6601. }
  6602. default:
  6603. break;
  6604. }
  6605. }
  6606. };
  6607. auto* test = new FocusTest();
  6608. test->reportPath = reportPath;
  6609. startFocusTestWindow (*test);
  6610. test->startTimer (600);
  6611. }
  6612. // --simplekeytest (round 190fc, 0.1.27 RC H2): in the Simple layout Space often did nothing after a click in the
  6613. // window (the dock, a track header, the grid, the Lyrics button) or after a demo opened from Welcome › Start from. The
  6614. // main window in the Simple layout; each step clicks as the system would (through the native window under the point)
  6615. // and presses Space where the system sends it (the native window of the component with the focus): playback must
  6616. // start, except while a text field the user clicked into has the keys (it types). Shows a window (Windows: GUI lock).
  6617. void runSimpleKeyTest (const juce::String& reportPath)
  6618. {
  6619. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6620. struct KeyTest final : juce::Timer
  6621. {
  6622. juce::String reportPath, report;
  6623. bool ok = true;
  6624. int stepIndex = 0, instrumentTrack = 0;
  6625. std::unique_ptr<lynx::AudioEngine> engine;
  6626. lynx::MainComponent* ui = nullptr;
  6627. std::unique_ptr<juce::DocumentWindow> main;
  6628. std::function<void()> done;
  6629. void line (const juce::String& text)
  6630. {
  6631. report << text << "\n";
  6632. juce::File (reportPath).replaceWithText (report);
  6633. }
  6634. void check (const juce::String& what, bool passed)
  6635. {
  6636. line ((passed ? "ok " : "FAIL ") + what);
  6637. ok = ok && passed;
  6638. }
  6639. static juce::String describe (juce::Component* c)
  6640. {
  6641. if (c == nullptr)
  6642. return "nothing";
  6643. juce::String path;
  6644. for (auto* p = c; p != nullptr && path.length() < 160; p = p->getParentComponent())
  6645. {
  6646. auto name = p->getComponentID().isNotEmpty() ? p->getComponentID() : p->getName();
  6647. if (name.isEmpty())
  6648. name = juce::String (typeid (*p).name()).fromLastOccurrenceOf ("::", false, false).substring (0, 28);
  6649. path << (path.isEmpty() ? "" : " < ") << name;
  6650. }
  6651. return path;
  6652. }
  6653. // the first showing component with this ID in the main window or a native child window of it
  6654. juce::Component* find (const juce::String& id)
  6655. {
  6656. std::function<juce::Component* (juce::Component&)> in = [&] (juce::Component& root) -> juce::Component* {
  6657. if (root.getComponentID() == id && root.isShowing())
  6658. return &root;
  6659. for (auto* c : root.getChildren())
  6660. if (auto* f = in (*c))
  6661. return f;
  6662. return nullptr;
  6663. };
  6664. if (auto* f = in (*main))
  6665. return f;
  6666. if (auto* peer = main->getPeer())
  6667. for (auto* attached : lynx::nativechild::attachedChildren (peer->getNativeHandle()))
  6668. if (auto* f = in (*attached))
  6669. return f;
  6670. return nullptr;
  6671. }
  6672. // a click (press and release) at `local` in `c`, through the native window it is in
  6673. juce::String lastHit;
  6674. void click (juce::Component& c, juce::Point<int> local)
  6675. {
  6676. auto* peer = c.getPeer();
  6677. if (peer == nullptr)
  6678. return;
  6679. const auto at = peer->getComponent().getLocalPoint (&c, local.toFloat());
  6680. lastHit = describe (peer->getComponent().getComponentAt (at.roundToInt()));
  6681. line (" click at " + local.toString() + " in " + describe (&c).upToFirstOccurrenceOf (" < ", false, false) + " -> " + lastHit);
  6682. const auto now = juce::Time::currentTimeMillis();
  6683. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, now);
  6684. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  6685. }
  6686. void click (juce::Component& c) { click (c, c.getLocalBounds().getCentre()); }
  6687. // Space where the system sends it: the native window of the focused component (else the main one)
  6688. bool space()
  6689. {
  6690. // Windows: posted to the window with the system's focus, as a real key goes (the system's own routing)
  6691. if (lynx::nativechild::pressSpaceForTest (main->getWindowHandle()))
  6692. return true;
  6693. auto* focused = juce::Component::getCurrentlyFocusedComponent();
  6694. auto* peer = focused != nullptr && focused->getPeer() != nullptr ? focused->getPeer() : main->getPeer();
  6695. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  6696. }
  6697. void spacePlays (const juce::String& after)
  6698. {
  6699. line (" keys at: " + describe (juce::Component::getCurrentlyFocusedComponent()));
  6700. auto& transport = engine->getTransport();
  6701. if (transport.playing.load())
  6702. engine->stop();
  6703. space();
  6704. check ("Space plays after " + after, transport.playing.load());
  6705. engine->stop();
  6706. }
  6707. void timerCallback() override
  6708. {
  6709. auto* simple = ui->getSimpleWorkflowForSnapshot();
  6710. auto& playlist = ui->getPlaylistForSnapshot();
  6711. switch (stepIndex++)
  6712. {
  6713. case 0:
  6714. ui->setLayoutStyle (lynx::layoutstyle::Style::simple);
  6715. ui->grabKeyboardFocus();
  6716. break;
  6717. case 1:
  6718. check ("the Simple workflow is up", simple != nullptr);
  6719. if (simple == nullptr)
  6720. return finish();
  6721. spacePlays ("the layout came up");
  6722. simple->showWelcome();
  6723. break;
  6724. case 2:
  6725. if (auto* demo = find ("tour.welcome.demo"))
  6726. click (*demo); // Welcome › Open a demo song: the Start from list
  6727. else
  6728. check ("Welcome > Open a demo song found", false);
  6729. break;
  6730. case 3:
  6731. {
  6732. if (! simple->isStartFromShowing()) // (X11: a child window just mapped may miss the first click)
  6733. if (auto* demo = find ("tour.welcome.demo"))
  6734. {
  6735. line (" the first click was not taken: once more");
  6736. click (*demo);
  6737. }
  6738. check ("Start from is up", simple->isStartFromShowing());
  6739. if (auto* start = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot()))
  6740. check ("a demo song opens from it", start->openForSnapshot (1));
  6741. break;
  6742. }
  6743. case 4:
  6744. check ("Start from closed with the demo open", ! simple->isStartFromShowing() && ! engine->getSong().playlist.empty());
  6745. spacePlays ("a demo opened from Welcome > Start from");
  6746. instrumentTrack = [] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  6747. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  6748. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  6749. return t;
  6750. return 0;
  6751. } (engine->getSong());
  6752. line ("instrument track: " + juce::String (instrumentTrack));
  6753. playlist.selectTrack (instrumentTrack);
  6754. simple->trackSelected (instrumentTrack);
  6755. break;
  6756. case 5:
  6757. if (auto* dock = simple->dockForSnapshot(); dock != nullptr && dock->isShowing())
  6758. {
  6759. click (*dock, { dock->getWidth() - 6, dock->getHeight() - 6 }); // (its empty corner)
  6760. spacePlays ("a click in the dock");
  6761. }
  6762. else
  6763. check ("the dock shows", false);
  6764. break;
  6765. case 6:
  6766. if (auto* tab = find ("simple.dock.keyboard"))
  6767. {
  6768. click (*tab);
  6769. spacePlays ("a click on a dock tab (Keyboard)");
  6770. }
  6771. if (auto* tab = find ("simple.dock.editor"))
  6772. {
  6773. click (*tab);
  6774. spacePlays ("a click on a dock tab (Editor)");
  6775. }
  6776. break;
  6777. case 7:
  6778. if (auto* lyrics = find ("simple.lyrics"))
  6779. {
  6780. click (*lyrics);
  6781. spacePlays ("a click on the Lyrics button");
  6782. }
  6783. else
  6784. check ("the Lyrics button found", false);
  6785. break;
  6786. case 8:
  6787. {
  6788. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  6789. click (playlist, { juce::jmax (4, playlist.headerWidth / 2), lane.getCentreY() });
  6790. spacePlays ("a click on a track header");
  6791. click (playlist, lane.getCentre() + juce::Point<int> (40, 0));
  6792. spacePlays ("a click in the Playlist grid");
  6793. break;
  6794. }
  6795. case 9:
  6796. {
  6797. // a text field the user clicks into keeps its typing keys; a click outside gives Space back
  6798. // a dock knob clicked keeps the arrow keys, and Space still plays from it
  6799. for (auto tab : { lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::instrument })
  6800. {
  6801. juce::Component* knob = nullptr;
  6802. std::function<void (juce::Component&)> seek = [&] (juce::Component& c) {
  6803. if (knob == nullptr && c.isShowing() && (bool) c.getProperties().getWithDefault ("lynxClickKeepsKeys", false))
  6804. knob = &c;
  6805. for (auto* child : c.getChildren())
  6806. seek (*child);
  6807. };
  6808. if (auto* dock = simple->dockForSnapshot())
  6809. {
  6810. dock->setTab (tab);
  6811. seek (*dock);
  6812. }
  6813. if (knob != nullptr)
  6814. {
  6815. click (*knob);
  6816. spacePlays ("a click on a dock knob");
  6817. break;
  6818. }
  6819. }
  6820. if (auto* dock = simple->dockForSnapshot())
  6821. dock->setTab (lynx::SimpleDock::Tab::instrument);
  6822. juce::TextEditor* field = nullptr;
  6823. std::function<void (juce::Component&)> look = [&] (juce::Component& c) {
  6824. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && field == nullptr)
  6825. field = t;
  6826. for (auto* child : c.getChildren())
  6827. look (*child);
  6828. };
  6829. if (auto* dock = simple->dockForSnapshot())
  6830. look (*dock);
  6831. line ("text field in the dock found=" + juce::String ((int) (field != nullptr)));
  6832. if (field != nullptr)
  6833. {
  6834. click (*field);
  6835. const auto before = field->getText();
  6836. space();
  6837. check ("Space types into the text field the user clicked", field->getText() != before && ! engine->getTransport().playing.load());
  6838. engine->stop();
  6839. field->clear();
  6840. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  6841. click (playlist, lane.getCentre() + juce::Point<int> (60, 0));
  6842. spacePlays ("a click in the grid after typing");
  6843. }
  6844. // H1: the first-song tour's card in front of the native panels, taking no keys (started on the demo
  6845. // as it is: Help's question about a new project is a dialog)
  6846. if (auto* tour = simple->tourForSnapshot())
  6847. tour->start();
  6848. break;
  6849. }
  6850. case 10:
  6851. {
  6852. auto* tour = simple->tourForSnapshot();
  6853. auto* card = tour != nullptr ? tour->cardForSnapshot() : nullptr;
  6854. check ("the tour runs", tour != nullptr && tour->isRunning() && card != nullptr && card->isVisible());
  6855. if (card == nullptr)
  6856. return finish();
  6857. auto& frame = ui->workspaceForTest().getFrame (lynx::workspace::Panel::playlist);
  6858. const auto native = lynx::nativechild::dockingEnabled() && lynx::nativechild::isAttached (frame);
  6859. line ("playlist native child window=" + juce::String ((int) native) + ", tour card native child window="
  6860. + juce::String ((int) lynx::nativechild::isAttached (*card)));
  6861. if (native)
  6862. {
  6863. check ("the tour card is a native child window of the main window (not under the panels)", lynx::nativechild::isAttached (*card));
  6864. #if JUCE_WINDOWS
  6865. check ("the tour card is above the Playlist's native window", lynx::nativechild::isAbove (card->getWindowHandle(), frame.getWindowHandle()));
  6866. juce::Component* layer = nullptr;
  6867. for (auto* c : lynx::nativechild::attachedChildren (main->getPeer()->getNativeHandle()))
  6868. if (c != nullptr && c->getComponentID() == "tour.layer")
  6869. layer = c;
  6870. check ("the ring's layer is above the Playlist too", layer != nullptr && lynx::nativechild::isAbove (layer->getWindowHandle(), frame.getWindowHandle()));
  6871. check ("the ring's layer lets clicks through to the Playlist",
  6872. layer != nullptr && lynx::nativechild::windowAt (*layer, layer->getLocalBounds().getCentre()) != layer->getWindowHandle());
  6873. #endif
  6874. }
  6875. check ("the tour card took no keys", ! card->hasKeyboardFocus (true));
  6876. spacePlays ("the tour came up");
  6877. if (auto* next = card->findChildWithID ("tour.next"); next != nullptr && next->isShowing())
  6878. {
  6879. click (*next);
  6880. check ("a click on the card took no keys", ! card->hasKeyboardFocus (true));
  6881. spacePlays ("a click on the tour card");
  6882. }
  6883. finish();
  6884. break;
  6885. }
  6886. default:
  6887. break;
  6888. }
  6889. }
  6890. void finish()
  6891. {
  6892. line (ok ? "result=OK" : "result=FAILED");
  6893. stopTimer();
  6894. done();
  6895. }
  6896. };
  6897. auto* test = new KeyTest();
  6898. test->reportPath = reportPath;
  6899. startFocusTestWindow (*test);
  6900. // Windows: kept above other apps' windows for its few seconds (JUCE takes a button-down only where the system finds
  6901. // its window under the point, and the test clicks through LYNX's own peers, not the system's input)
  6902. #if JUCE_WINDOWS
  6903. test->main->setAlwaysOnTop (true); // (Linux: JUCE makes the X11 window again for it; the private X server has no other windows)
  6904. #endif
  6905. test->startTimer (700);
  6906. }
  6907. template <typename Test>
  6908. void startFocusTestWindow (Test& t)
  6909. {
  6910. auto* test = &t;
  6911. test->engine = std::make_unique<lynx::AudioEngine> (false);
  6912. test->main = std::make_unique<juce::DocumentWindow> ("LYNX focus test", lynx::theme::window, juce::DocumentWindow::allButtons);
  6913. test->main->setUsingNativeTitleBar (true);
  6914. test->ui = new lynx::MainComponent (*test->engine, false);
  6915. test->main->setContentOwned (test->ui, true);
  6916. test->main->setResizable (true, true);
  6917. test->main->centreWithSize (1280, 760);
  6918. test->main->setVisible (true);
  6919. lynx::setMainWindowForOwnership (test->main.get());
  6920. test->done = [this, test] {
  6921. setApplicationReturnValue (test->ok ? 0 : 1);
  6922. juce::MessageManager::callAsync ([this, test] {
  6923. lynx::setMainWindowForOwnership (nullptr);
  6924. test->main = nullptr;
  6925. delete test;
  6926. quit();
  6927. });
  6928. };
  6929. }
  6930. void runWindowTest (const juce::String& reportPath)
  6931. {
  6932. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  6933. struct WindowTest final : juce::Timer
  6934. {
  6935. juce::String reportPath, report;
  6936. bool ok = true;
  6937. int stepIndex = 0;
  6938. std::unique_ptr<lynx::AudioEngine> engine;
  6939. lynx::MainComponent* ui = nullptr;
  6940. std::unique_ptr<juce::DocumentWindow> main, pluginLike;
  6941. juce::TextEditor* pluginField = nullptr;
  6942. std::unique_ptr<juce::AlertWindow> nameDialog;
  6943. std::function<void()> done;
  6944. void line (const juce::String& text)
  6945. {
  6946. report << text << "\n";
  6947. juce::File (reportPath).replaceWithText (report);
  6948. }
  6949. void check (const juce::String& what, bool passed)
  6950. {
  6951. line ((passed ? "ok " : "FAIL ") + what);
  6952. ok = ok && passed;
  6953. }
  6954. bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
  6955. bool focusIn (juce::Component* w)
  6956. {
  6957. auto* f = juce::Component::getCurrentlyFocusedComponent();
  6958. return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
  6959. }
  6960. void timerCallback() override
  6961. {
  6962. switch (stepIndex++)
  6963. {
  6964. case 0:
  6965. line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
  6966. ui->openQuickAddForTest();
  6967. break;
  6968. case 1:
  6969. {
  6970. auto* w = lynx::findToolWindow ("quickadd");
  6971. check ("quick-add palette open", w != nullptr);
  6972. check ("quick-add palette active", w != nullptr && w->isActiveWindow());
  6973. check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  6974. check ("quick-add palette above the main window", isAbove (w));
  6975. auto* f = juce::Component::getCurrentlyFocusedComponent();
  6976. check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
  6977. lynx::closeAllToolWindows();
  6978. lynx::openAudioEditor (*engine);
  6979. break;
  6980. }
  6981. case 2:
  6982. {
  6983. auto* w = lynx::findToolWindow ("audioeditor");
  6984. check ("audio editor open", w != nullptr);
  6985. check ("audio editor active", w != nullptr && w->isActiveWindow());
  6986. check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  6987. check ("audio editor above the main window", isAbove (w));
  6988. lynx::forceForegroundForTest (*main); // the user clicks the main window
  6989. break;
  6990. }
  6991. case 3:
  6992. {
  6993. auto* w = lynx::findToolWindow ("audioeditor");
  6994. check ("audio editor stays above the main window after clicking it", isAbove (w));
  6995. lynx::closeAllToolWindows();
  6996. // a plugin editor's window: its own controls keep the keyboard focus
  6997. pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
  6998. pluginLike->setUsingNativeTitleBar (true);
  6999. auto* field = new juce::TextEditor();
  7000. field->setSize (300, 120);
  7001. pluginLike->setContentOwned (field, true);
  7002. pluginLike->centreWithSize (300, 120);
  7003. pluginLike->setVisible (true);
  7004. lynx::keepAboveMainWindow (*pluginLike);
  7005. pluginLike->toFront (true);
  7006. field->grabKeyboardFocus();
  7007. pluginField = field;
  7008. break;
  7009. }
  7010. case 4:
  7011. check ("plugin window active", pluginLike->isActiveWindow());
  7012. check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
  7013. check ("plugin window above the main window", isAbove (pluginLike.get()));
  7014. pluginLike = nullptr;
  7015. lynx::forceForegroundForTest (*main);
  7016. juce::Component::unfocusAllComponents();
  7017. break;
  7018. case 5:
  7019. check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
  7020. // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
  7021. nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
  7022. nameDialog->enterModalState (true, nullptr, false);
  7023. lynx::keepAboveMainWindow (*nameDialog);
  7024. break;
  7025. case 6:
  7026. {
  7027. auto* f = juce::Component::getCurrentlyFocusedComponent();
  7028. auto* field = dynamic_cast<juce::TextEditor*> (f);
  7029. check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
  7030. if (field != nullptr)
  7031. field->keyPressed (juce::KeyPress ('x', {}, 'x'));
  7032. check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
  7033. nameDialog->exitModalState (0);
  7034. nameDialog = nullptr;
  7035. line (ok ? "result=OK" : "result=FAILED");
  7036. stopTimer();
  7037. done();
  7038. break;
  7039. }
  7040. default:
  7041. break;
  7042. }
  7043. }
  7044. };
  7045. auto* test = new WindowTest();
  7046. test->reportPath = reportPath;
  7047. test->engine = std::make_unique<lynx::AudioEngine> (false);
  7048. test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
  7049. test->main->setUsingNativeTitleBar (true);
  7050. test->ui = new lynx::MainComponent (*test->engine, false);
  7051. test->main->setContentOwned (test->ui, true);
  7052. test->main->setResizable (true, true);
  7053. test->main->centreWithSize (1280, 760);
  7054. test->main->setVisible (true);
  7055. lynx::setMainWindowForOwnership (test->main.get());
  7056. lynx::forceForegroundForTest (*test->main);
  7057. test->main->toFront (true);
  7058. test->done = [this, test] {
  7059. setApplicationReturnValue (test->ok ? 0 : 1);
  7060. juce::MessageManager::callAsync ([this, test] {
  7061. lynx::closeAllToolWindows();
  7062. lynx::setMainWindowForOwnership (nullptr);
  7063. test->main = nullptr;
  7064. delete test;
  7065. quit();
  7066. });
  7067. };
  7068. test->startTimer (1500);
  7069. }
  7070. // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
  7071. // instrument (and runs audio through it if it is an effect) and measures the audio.
  7072. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
  7073. {
  7074. juce::String report;
  7075. bool ok = false;
  7076. {
  7077. lynx::AudioEngine offline (false);
  7078. auto& host = offline.getPluginHost();
  7079. const auto added = host.addPluginFile (juce::File (pluginPath));
  7080. report << "plugins_in_file=" << added << "\n";
  7081. juce::PluginDescription instrument, effect;
  7082. bool hasInstrument = false, hasEffect = false;
  7083. for (const auto& type : host.getKnownPlugins().getTypes())
  7084. {
  7085. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  7086. || (only.isNotEmpty() && type.name != only))
  7087. continue;
  7088. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  7089. << ") in " << type.fileOrIdentifier << "\n";
  7090. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  7091. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  7092. }
  7093. auto song = lynx::Song::makeDefault();
  7094. if (hasInstrument)
  7095. {
  7096. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  7097. c.instrument = lynx::InstrumentKind::plugin;
  7098. c.plugin.id = instrument.createIdentifierString().toStdString();
  7099. c.plugin.name = instrument.name.toStdString();
  7100. c.volume = 1.0f;
  7101. for (int i = 0; i < 4; ++i) // one chord per beat
  7102. for (int key : { 60, 64, 67 })
  7103. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  7104. song.patterns[0].sortNotes();
  7105. }
  7106. if (hasEffect)
  7107. {
  7108. lynx::EffectSlot slot;
  7109. slot.kind = lynx::EffectKind::plugin;
  7110. slot.plugin.id = effect.createIdentifierString().toStdString();
  7111. slot.plugin.name = effect.name.toStdString();
  7112. song.mixer[0].effects.push_back (slot);
  7113. }
  7114. const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
  7115. offline.setSong (song);
  7116. // after a render: the rack (and its plugins) is built when the engine is prepared
  7117. const auto peak = offline.renderOffline (3.0, 48000.0);
  7118. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  7119. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
  7120. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  7121. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  7122. if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
  7123. report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
  7124. report << "peak=" << peak << "\n";
  7125. // plugins that crashed inside a call, were caught and switched off (round 111)
  7126. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  7127. for (const auto& c : lynx::pluginCrashes())
  7128. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  7129. offline.capturePluginStates();
  7130. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  7131. report << "state_bytes_base64=" << (int) stateSize << "\n";
  7132. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  7133. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  7134. }
  7135. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  7136. juce::File (reportPath).replaceWithText (report);
  7137. setApplicationReturnValue (ok ? 0 : 1);
  7138. quit();
  7139. }
  7140. // LYNX --crashguardtest plugin report.txt [process|memcpy] (round 190dt): see the dispatch in initialise().
  7141. void runCrashGuardTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  7142. {
  7143. juce::String report;
  7144. bool ok = true;
  7145. const auto expect = [&] (const char* name, bool value) {
  7146. report << name << "=" << (value ? 1 : 0) << "\n";
  7147. ok = ok && value;
  7148. };
  7149. const auto setEnv = [] (const char* name, const char* value) {
  7150. #if JUCE_WINDOWS
  7151. _putenv_s (name, value);
  7152. #else
  7153. setenv (name, value, 1);
  7154. #endif
  7155. };
  7156. // renders without the plugin warm-up (its silent blocks would count towards the crash)
  7157. const auto render = [] (lynx::AudioEngine& engine, double seconds, const std::function<void (const float*, const float*, int)>& capture) {
  7158. lynx::AudioEngine::RenderOptions o;
  7159. o.seconds = seconds;
  7160. o.sampleRate = 48000.0;
  7161. o.pluginWarmUp = false;
  7162. o.capture = capture;
  7163. return engine.renderOffline (o);
  7164. };
  7165. const auto peakOf = [] (float& peak) {
  7166. return [&peak] (const float* l, const float* r, int n) {
  7167. for (int k = 0; k < n; ++k)
  7168. peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
  7169. };
  7170. };
  7171. report << "guard=" << (lynx::crashguard::pluginFaultsCaught() ? "on" : "off") << "\nmode=" << mode << "\n";
  7172. setEnv ("LYNX_TEST_CRASH", mode == "memcpy" ? "memcpy" : "process");
  7173. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  7174. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  7175. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  7176. tmp.createDirectory();
  7177. std::optional<lynx::Song> saved;
  7178. std::string savedState;
  7179. {
  7180. lynx::AudioEngine offline (false);
  7181. auto& host = offline.getPluginHost();
  7182. host.addPluginFile (juce::File (pluginPath));
  7183. juce::PluginDescription effect;
  7184. bool found = false;
  7185. for (const auto& type : host.getKnownPlugins().getTypes())
  7186. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  7187. {
  7188. effect = type;
  7189. found = true;
  7190. }
  7191. expect ("plugin_found", found);
  7192. // the plugin on insert 1 (the kick's); the clap and the hat play on inserts 2 and 3
  7193. auto song = lynx::Song::makeDefault();
  7194. lynx::EffectSlot slot;
  7195. slot.kind = lynx::EffectKind::plugin;
  7196. slot.plugin.id = effect.createIdentifierString().toStdString();
  7197. slot.plugin.name = effect.name.toStdString();
  7198. song.mixer[1].effects.push_back (slot);
  7199. offline.setSong (song);
  7200. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  7201. // the rack is published at the engine's rate and an offline render runs at its own (48 kHz) without publishing:
  7202. // one edit after a first render puts the rack (and the plugin) at the render's rate, so later edits keep it
  7203. render (offline, 0.05, {}); // (a few blocks, far from the 40th)
  7204. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  7205. render (offline, 0.05, {});
  7206. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  7207. expect ("plugin_loaded", first != nullptr);
  7208. offline.capturePluginStates();
  7209. savedState = offline.getSong().mixer[1].effects[0].plugin.state;
  7210. expect ("state_captured", ! savedState.empty());
  7211. // the crash: 3 s, the plugin faults in its 40th block
  7212. const auto crashesBefore = lynx::pluginCrashCount();
  7213. juce::int64 position = 0, crashAt = -1;
  7214. float peakAfter = 0.0f;
  7215. const auto afterPeak = peakOf (peakAfter);
  7216. const auto peak = render (offline, 3.0, [&] (const float* l, const float* r, int n) {
  7217. if (crashAt < 0 && lynx::pluginCrashCount() != crashesBefore)
  7218. crashAt = position;
  7219. else if (crashAt >= 0)
  7220. afterPeak (l, r, n);
  7221. position += n;
  7222. });
  7223. report << "peak=" << peak << "\ncrash_at_sample=" << crashAt << "\npeak_after_crash=" << peakAfter << "\n";
  7224. const auto crashes = lynx::pluginCrashes();
  7225. expect ("crash_caught", lynx::pluginCrashCount() == crashesBefore + 1 && ! crashes.empty() && ! crashes.back().onLoad);
  7226. if (! crashes.empty())
  7227. report << "crash=" << crashes.back().plugin << " (" << lynx::crashguard::describe (crashes.back().code) << ")\n";
  7228. expect ("slot_marked_crashed", first != nullptr && offline.getEffect (1, 0).get() == first && first->hasCrashed());
  7229. const auto down = offline.downHostedPlugins();
  7230. expect ("slot_down", down.size() == 1 && down[0] == where);
  7231. expect ("audio_after_crash", crashAt >= 0 && peakAfter > 0.01f);
  7232. // the other inserts: with the kick (through the crashed slot) silent, the clap and the hat still play
  7233. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  7234. float othersPeak = 0.0f;
  7235. render (offline, 1.0, peakOf (othersPeak));
  7236. report << "other_inserts_peak=" << othersPeak << "\n";
  7237. expect ("other_inserts_play", othersPeak > 0.01f);
  7238. expect ("nothing_reloads_by_itself", offline.hostedPluginDown (where) && offline.getEffect (1, 0).get() == first);
  7239. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  7240. // the project saves with the settings the plugin had before it crashed, and opens again
  7241. offline.capturePluginStates();
  7242. expect ("state_kept", offline.getSong().mixer[1].effects[0].plugin.state == savedState);
  7243. const auto file = tmp.getChildFile ("crashed.lynx");
  7244. juce::String error;
  7245. expect ("project_saved", lynx::ProjectFile::save (offline.getSong(), file, error) && file.existsAsFile());
  7246. saved = lynx::ProjectFile::load (file, error);
  7247. expect ("project_reopens", saved.has_value() && saved->mixer.size() > 1 && saved->mixer[1].effects.size() == 1
  7248. && saved->mixer[1].effects[0].plugin.state == savedState);
  7249. // Reload (the prompt's button, round 190ao): a new instance; the module's block count is past 40 now
  7250. const auto running = offline.reloadHostedPlugins (down);
  7251. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  7252. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  7253. float reloadedPeak = 0.0f;
  7254. render (offline, 1.0, peakOf (reloadedPeak));
  7255. report << "reloaded_peak=" << reloadedPeak << "\n";
  7256. expect ("reloaded_plays", reloadedPeak > 0.01f && lynx::pluginCrashCount() == crashesBefore + 1 && again != nullptr && ! again->hasCrashed());
  7257. }
  7258. // the saved project opens again with the plugin crashing on its saved settings: left out, the rest plays, the
  7259. // settings stay in the project
  7260. setEnv ("LYNX_TEST_CRASH", "state");
  7261. if (saved.has_value())
  7262. {
  7263. lynx::AudioEngine reopened (false);
  7264. reopened.getPluginHost().addPluginFile (juce::File (pluginPath));
  7265. const auto before = lynx::pluginCrashCount();
  7266. reopened.setSong (*saved);
  7267. float reopenedPeak = 0.0f;
  7268. render (reopened, 1.0, peakOf (reopenedPeak));
  7269. const auto crashes = lynx::pluginCrashes();
  7270. report << "reopened_peak=" << reopenedPeak << "\n";
  7271. if (reopened.getPluginHost().getLoadFailures().size() > 0)
  7272. report << "load_failures=" << reopened.getPluginHost().getLoadFailures().joinIntoString (" | ") << "\n";
  7273. expect ("state_crash_caught", lynx::pluginCrashCount() == before + 1 && ! crashes.empty() && crashes.back().onLoad);
  7274. expect ("state_crash_left_out", dynamic_cast<lynx::PluginEffect*> (reopened.getEffect (1, 0).get()) == nullptr);
  7275. expect ("state_crash_project_plays", reopenedPeak > 0.01f);
  7276. reopened.capturePluginStates();
  7277. expect ("state_crash_settings_kept", reopened.getSong().mixer[1].effects.size() == 1
  7278. && reopened.getSong().mixer[1].effects[0].plugin.state == savedState);
  7279. }
  7280. setEnv ("LYNX_TEST_CRASH", "");
  7281. // LYNX's own faults inside a guarded call stay crashes (child processes; the selftest runs the same)
  7282. const auto own = faultReportSelfTest();
  7283. report << "own_faults=" << own << "\n";
  7284. ok = ok && ! own.startsWith ("ERROR");
  7285. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  7286. for (const auto& c : lynx::pluginCrashes())
  7287. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << (c.onLoad ? ", loading its state" : "") << ")\n";
  7288. tmp.deleteRecursively();
  7289. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  7290. juce::File (reportPath).replaceWithText (report);
  7291. setApplicationReturnValue (ok ? 0 : 1);
  7292. quit();
  7293. }
  7294. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108): a hosted CLAP
  7295. // instrument with the wrapper's MPE switch on gets each note on its own member channel, its fine pitch / Mod X /
  7296. // Mod Y as tuning / brightness / pressure note expressions before the note on, and a sounding note's expression
  7297. // on that note's channel alone. The plugin writes down what it received; no window, no audio device.
  7298. void runMpeTest (const juce::String& pluginPath, const juce::String& reportPath)
  7299. {
  7300. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  7301. log.deleteFile();
  7302. #if JUCE_WINDOWS
  7303. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  7304. #else
  7305. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  7306. #endif
  7307. juce::String report;
  7308. auto failures = 0;
  7309. {
  7310. lynx::AudioEngine engine (false);
  7311. auto& host = engine.getPluginHost();
  7312. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  7313. std::optional<juce::PluginDescription> clap;
  7314. for (const auto& type : host.getKnownPlugins().getTypes())
  7315. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  7316. clap = type;
  7317. lynx::PluginRef ref;
  7318. if (clap)
  7319. {
  7320. ref.id = clap->createIdentifierString().toStdString();
  7321. ref.name = clap->name.toStdString();
  7322. }
  7323. ref.mpe = true;
  7324. juce::String error;
  7325. auto instrument = clap ? host.makeInstrument (ref, 48000.0, &error) : nullptr;
  7326. report << "instrument_loaded=" << (instrument != nullptr ? "yes" : "no") << (error.isNotEmpty() ? " (" + error + ")" : juce::String()) << "\n";
  7327. if (instrument != nullptr)
  7328. {
  7329. std::vector<float> l (256), r (256);
  7330. auto block = [&] { instrument->render (l.data(), r.data(), 256, 1.0f, 1.0f); };
  7331. block(); // (the zone's setup)
  7332. instrument->setNextNoteFinePitch (30.0f); // +30 cents
  7333. instrument->setNextNoteModulation (0.75f, 1.0f); // timbre 0.75, full pressure
  7334. instrument->noteOn (60, 0.8f);
  7335. instrument->noteOn (64, 0.5f); // a second note: its own channel, centre values
  7336. block();
  7337. instrument->noteExpression (60, (int) lynx::vfx::Prop::pitch, 200.0f, 0.0f);
  7338. instrument->noteExpression (64, (int) lynx::vfx::Prop::modX, 0.25f, 0.0f);
  7339. instrument->noteExpression (60, (int) lynx::vfx::Prop::modY, 0.75f, 0.0f);
  7340. block();
  7341. instrument->noteOff (60);
  7342. instrument->noteOff (64);
  7343. block();
  7344. }
  7345. else
  7346. ++failures;
  7347. } // (the plugin writes its log as it is destroyed)
  7348. struct Line
  7349. {
  7350. juce::String kind;
  7351. int a = 0, b = 0, c = 0, d = 0;
  7352. };
  7353. std::vector<Line> lines;
  7354. for (const auto& text : juce::StringArray::fromLines (log.loadFileAsString()))
  7355. {
  7356. const auto t = juce::StringArray::fromTokens (text, " ", "");
  7357. if (t.size() >= 3)
  7358. 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 });
  7359. }
  7360. report << "plugin_events=" << (int) lines.size() << "\n";
  7361. // the first line at or after `from` that matches (−1 = none); `value` within `tolerance` (thousandths)
  7362. auto find = [&lines] (const juce::String& kind, int a, int b, int value, int tolerance, int from = 0) {
  7363. for (auto i = (std::size_t) from; i < lines.size(); ++i)
  7364. {
  7365. const auto& x = lines[i];
  7366. const auto v = kind == "expr" ? x.d : x.c;
  7367. if (x.kind == kind && x.a == a && x.b == b && std::abs (v - value) <= tolerance)
  7368. return (int) i;
  7369. }
  7370. return -1;
  7371. };
  7372. auto check = [&] (const char* what, bool ok) {
  7373. report << what << "=" << (ok ? "ok" : "FAILED") << "\n";
  7374. failures += ok ? 0 : 1;
  7375. };
  7376. // (CLAP expression ids: 2 tuning in semitones, 5 brightness, 6 pressure; channels 0-based: the first member = 1)
  7377. const auto on60 = find ("on", 1, 60, 800, 5), on64 = find ("on", 2, 64, 500, 5);
  7378. check ("zone_setup_sent", find ("midi", 176, 6, 15, 0) >= 0 && find ("midi", 177, 6, 48, 0) >= 0);
  7379. check ("notes_on_their_own_channels", on60 >= 0 && on64 > on60);
  7380. const auto tune = find ("expr", 2, 1, 300, 3), bright = find ("expr", 5, 1, 756, 4), press = find ("expr", 6, 1, 1000, 1);
  7381. check ("expression_before_the_note_on", tune >= 0 && bright >= 0 && press >= 0 && tune < on60 && bright < on60 && press < on60);
  7382. 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);
  7383. const auto later = std::max (on60, on64) + 1;
  7384. check ("sounding_note_expression", later > 0 && find ("expr", 2, 1, 2000, 3, later) >= 0 && find ("expr", 5, 2, 252, 4, later) >= 0
  7385. && find ("expr", 6, 1, 504, 4, later) >= 0);
  7386. check ("other_note_untouched", later > 0 && find ("expr", 2, 2, 2000, 3, later) < 0 && find ("expr", 6, 2, 504, 4, later) < 0);
  7387. check ("notes_off_on_their_channels", find ("off", 1, 60, 0, 100000) >= 0 && find ("off", 2, 64, 0, 100000) >= 0);
  7388. auto expressionAsMidi = false; // (a CLAP-dialect plugin gets no raw bend / pressure / CC 74 on a member channel)
  7389. for (const auto& x : lines)
  7390. if (x.kind == "midi" && (x.a & 0x0f) != 0 && ((x.a & 0xf0) == 0xe0 || (x.a & 0xf0) == 0xd0 || ((x.a & 0xf0) == 0xb0 && x.b == 74)))
  7391. expressionAsMidi = true;
  7392. check ("no_duplicate_midi_expression", ! expressionAsMidi);
  7393. report << "--- plugin log ---\n" << log.loadFileAsString() << "result=" << (failures == 0 ? "OK" : "FAILED") << "\n";
  7394. juce::File (reportPath).replaceWithText (report);
  7395. setApplicationReturnValue (failures == 0 ? 0 : 1);
  7396. quit();
  7397. }
  7398. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
  7399. // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
  7400. // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
  7401. // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
  7402. // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
  7403. // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
  7404. // the latency the plugin reports after its last restart.
  7405. void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
  7406. {
  7407. struct Run
  7408. {
  7409. std::unique_ptr<lynx::AudioEngine> engine;
  7410. juce::String report;
  7411. int slot = -1;
  7412. std::thread render;
  7413. std::atomic<bool> done { false };
  7414. double renderSeconds = 0.0;
  7415. };
  7416. auto run = std::make_shared<Run>();
  7417. const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  7418. counters.deleteFile();
  7419. #if JUCE_WINDOWS
  7420. _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
  7421. #else
  7422. setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
  7423. #endif
  7424. const auto fail = [this, reportPath] (juce::String report) {
  7425. report << "result=FAILED\n";
  7426. juce::File (reportPath).replaceWithText (report);
  7427. setApplicationReturnValue (1);
  7428. quit();
  7429. };
  7430. run->engine = std::make_unique<lynx::AudioEngine> (false);
  7431. auto& host = run->engine->getPluginHost();
  7432. run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  7433. std::optional<juce::PluginDescription> clap;
  7434. for (const auto& type : host.getKnownPlugins().getTypes())
  7435. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  7436. clap = type;
  7437. if (! clap)
  7438. {
  7439. fail (run->report + "no CLAP plugin in the file\n");
  7440. return;
  7441. }
  7442. auto song = lynx::Song::makeDefault();
  7443. lynx::EffectSlot slot;
  7444. slot.kind = lynx::EffectKind::plugin;
  7445. slot.plugin.id = clap->createIdentifierString().toStdString();
  7446. slot.plugin.name = clap->name.toStdString();
  7447. slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
  7448. song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
  7449. run->slot = (int) song.mixer[0].effects.size() - 1;
  7450. run->engine->setSong (song);
  7451. run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
  7452. if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
  7453. {
  7454. fail (run->report + "effect_loaded=no\n");
  7455. return;
  7456. }
  7457. auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
  7458. run->render = std::thread ([run, effect] () mutable {
  7459. const auto start = juce::Time::getMillisecondCounterHiRes();
  7460. run->engine->renderOffline (30.0, 48000.0);
  7461. run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
  7462. // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
  7463. // plugin aborts unless activate / deactivate reach the main thread
  7464. auto& instance = effect->getInstance();
  7465. instance.prepareToPlay (44100.0, 1024);
  7466. instance.releaseResources();
  7467. instance.prepareToPlay (48000.0, 512);
  7468. run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
  7469. // The engine has replaced this instance (made for 48 kHz) by then, so this is its last reference: it is
  7470. // deleted here, on the export's thread, and its deactivate / destroy go to the message thread, which this
  7471. // waits for. That has to happen before `done`: once the message thread sees it, it blocks in join() until
  7472. // this thread ends, and an instance deleted after that waited 10 s for it and then deactivated the plugin
  7473. // right here, off the main thread (the plugin aborts: about 1 run in 40 under load, round 190au).
  7474. effect.reset();
  7475. run->done = true;
  7476. });
  7477. // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
  7478. auto finish = std::make_shared<std::function<void()>>();
  7479. *finish = [this, run, counters, reportPath, fail, finish] {
  7480. if (! run->done)
  7481. {
  7482. juce::Timer::callAfterDelay (50, *finish);
  7483. return;
  7484. }
  7485. run->render.join();
  7486. juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
  7487. auto report = run->report;
  7488. int pluginLatency = -1;
  7489. if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
  7490. pluginLatency = effect->latencySamples();
  7491. const auto pdc = run->engine->getLatencySamples();
  7492. report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
  7493. << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
  7494. << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  7495. run->engine.reset(); // destroys the plugin: it writes its counters
  7496. // one line per plugin instance (the engine may have made more than one): none may have been
  7497. // deactivated inside process(), and the one that rendered must have restarted
  7498. int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
  7499. bool otherRate = false;
  7500. for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
  7501. {
  7502. juce::StringPairArray values;
  7503. for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
  7504. if (token.contains ("="))
  7505. values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
  7506. if (values.size() == 0)
  7507. continue;
  7508. ++lines;
  7509. report << "instance: " << line << "\n";
  7510. overlapped += values["overlapped"].getIntValue();
  7511. inactive += values["inactive_blocks"].getIntValue();
  7512. // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
  7513. // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
  7514. wrongThread += values["wrong_thread"].getIntValue();
  7515. misordered += values["misordered"].getIntValue();
  7516. unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
  7517. otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
  7518. if (values["requests"].getIntValue() > requests)
  7519. {
  7520. requests = values["requests"].getIntValue();
  7521. activations = values["activations"].getIntValue();
  7522. }
  7523. }
  7524. report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
  7525. << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
  7526. const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
  7527. && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
  7528. && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
  7529. if (! ok)
  7530. {
  7531. fail (report);
  7532. return;
  7533. }
  7534. report << "result=OK\n";
  7535. juce::File (reportPath).replaceWithText (report);
  7536. setApplicationReturnValue (0);
  7537. quit();
  7538. });
  7539. };
  7540. juce::Timer::callAfterDelay (50, *finish);
  7541. }
  7542. // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
  7543. // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
  7544. // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
  7545. void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
  7546. {
  7547. juce::String report;
  7548. bool ok = false;
  7549. {
  7550. lynx::AudioEngine offline (false);
  7551. auto& host = offline.getPluginHost();
  7552. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  7553. std::optional<juce::PluginDescription> vst2;
  7554. for (const auto& type : host.getKnownPlugins().getTypes())
  7555. if (type.pluginFormatName == "VST")
  7556. vst2 = type;
  7557. auto render = [&] (float gain, float& tempoSeen, int& adopted) {
  7558. lynx::FlVst2State state;
  7559. state.flags = 8;
  7560. state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
  7561. std::memcpy (state.chunk.data() + 4, &gain, 4);
  7562. auto song = lynx::Song::makeDefault();
  7563. song.bpm = 137.0;
  7564. auto& f = song.channels[4].plugin.foreign;
  7565. f.format = lynx::ForeignPlugin::Format::vst2;
  7566. f.vst2Id = (std::uint32_t) vst2->uniqueId;
  7567. f.name = "Some other name"; // found by the VST2 ID
  7568. f.state = lynx::writeFlVst2State (state);
  7569. song.channels[4].volume = 1.0f;
  7570. song.patterns[0].notes.clear();
  7571. song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
  7572. for (std::size_t c = 0; c < song.channels.size(); ++c)
  7573. if (c != 4)
  7574. song.channels[c].muted = true;
  7575. adopted = host.adoptFlPlugins (song);
  7576. offline.setSong (song);
  7577. const auto peak = offline.renderOffline (1.0, 48000.0);
  7578. offline.capturePluginStates();
  7579. juce::MemoryBlock saved;
  7580. saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
  7581. lynx::FlVst2State back;
  7582. tempoSeen = 0.0f;
  7583. if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
  7584. && back.chunk.size() >= 12)
  7585. std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
  7586. return peak;
  7587. };
  7588. if (vst2)
  7589. {
  7590. report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
  7591. float tempoA = 0, tempoB = 0;
  7592. int adoptedA = 0, adoptedB = 0;
  7593. const auto quiet = render (0.1f, tempoA, adoptedA);
  7594. const auto loud = render (0.4f, tempoB, adoptedB);
  7595. report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
  7596. << " tempo_seen=" << tempoB * 1000.0f << "\n";
  7597. ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
  7598. && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
  7599. }
  7600. }
  7601. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  7602. juce::File (reportPath).replaceWithText (report);
  7603. setApplicationReturnValue (ok ? 0 : 1);
  7604. quit();
  7605. }
  7606. // LYNX --vst3noteidtest "LYNX Test Synth.vst3" report.txt (round 190fg, cmake/LynxPatchJuce.cmake fix 26): the VST3
  7607. // test synth (tools/testplugin/lynx_test_synth_vst3.cpp: voices kept by noteId, its log the ids it got) plays two
  7608. // overlapping pairs of one key on one channel: FIFO (A 0-4, B 2-6 beats, key 60) and LIFO (C 8-14, D 10-12, key 64).
  7609. // Each note off must carry its own note on's id (FL: each note ends its own voice, round 190ej): the inner note D's
  7610. // end ends D. A second render with the tag hook off shows fix 14 alone (the oldest id: D's end carries C's id).
  7611. void runVst3NoteIdTest (const juce::String& pluginPath, const juce::String& reportPath)
  7612. {
  7613. juce::String report;
  7614. bool ok = false;
  7615. const auto logBase = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-noteid-" + juce::String (juce::Time::currentTimeMillis()));
  7616. // (read by each new instance)
  7617. #if JUCE_WINDOWS
  7618. _putenv_s ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8());
  7619. #else
  7620. setenv ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8(), 1);
  7621. #endif
  7622. struct E
  7623. {
  7624. bool on = false;
  7625. int key = 0, id = -1;
  7626. };
  7627. // (the lines each render added: a running instance keeps its log file open, so the files stay until the end)
  7628. std::map<juce::String, int> linesRead;
  7629. const auto readLog = [&logBase, &linesRead] {
  7630. std::vector<E> events;
  7631. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  7632. {
  7633. juce::StringArray lines;
  7634. f.readLines (lines);
  7635. auto& done = linesRead[f.getFullPathName()];
  7636. for (int i = done; i < lines.size(); ++i)
  7637. {
  7638. const auto p = juce::StringArray::fromTokens (lines[i], " ", {});
  7639. if (p.size() >= 5 && p[0].startsWith ("E"))
  7640. events.push_back ({ p[1] == "on", p[2].getIntValue(), p[4].getIntValue() });
  7641. }
  7642. done = lines.size() - (lines.isEmpty() || lines[lines.size() - 1].isNotEmpty() ? 0 : 1);
  7643. }
  7644. return events;
  7645. };
  7646. {
  7647. lynx::AudioEngine offline (false);
  7648. auto& host = offline.getPluginHost();
  7649. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  7650. std::optional<juce::PluginDescription> vst3;
  7651. for (const auto& type : host.getKnownPlugins().getTypes())
  7652. if (type.pluginFormatName == "VST3" && type.isInstrument)
  7653. vst3 = type;
  7654. const auto render = [&] (bool tags) {
  7655. auto song = lynx::Song::makeDefault();
  7656. song.bpm = 120.0;
  7657. auto& c = song.channels[0];
  7658. c.instrument = lynx::InstrumentKind::plugin;
  7659. c.plugin.id = vst3->createIdentifierString().toStdString();
  7660. c.plugin.name = vst3->name.toStdString();
  7661. for (std::size_t k = 1; k < song.channels.size(); ++k)
  7662. song.channels[k].muted = true;
  7663. auto& notes = song.patterns[0].notes;
  7664. notes.clear();
  7665. const auto beat = (std::int64_t) lynx::ppq;
  7666. notes.push_back ({ 0, 4 * beat, 0, 60, 0.8f }); // A
  7667. notes.push_back ({ 2 * beat, 4 * beat, 0, 60, 0.8f }); // B
  7668. notes.push_back ({ 8 * beat, 6 * beat, 0, 64, 0.8f }); // C
  7669. notes.push_back ({ 10 * beat, 2 * beat, 0, 64, 0.8f }); // D (inside C)
  7670. song.patterns[0].sortNotes();
  7671. song.patterns[0].lengthTicks = 16 * beat;
  7672. offline.setSong (song);
  7673. offline.dispatchPendingMessages();
  7674. if (! tags)
  7675. juce::lynxNoteTagHook = nullptr; // (fix 14 alone: the oldest sounding id; the next instance sets it again)
  7676. offline.renderOffline (7.9, 48000.0); // (C ends at 7 s; the 8 s pattern does not loop yet)
  7677. return readLog();
  7678. };
  7679. const auto check = [&report] (const char* name, const std::vector<E>& events, bool expectOwn) {
  7680. // ons and offs of each key in the order the plugin got them
  7681. std::map<int, std::vector<int>> ons, offs;
  7682. for (const auto& e : events)
  7683. (e.on ? ons : offs)[e.key].push_back (e.id);
  7684. const auto& a = ons[60]; const auto& o60 = offs[60];
  7685. const auto& c = ons[64]; const auto& o64 = offs[64];
  7686. report << name << ": key 60 ons";
  7687. for (auto id : a) report << " " << id;
  7688. report << " offs";
  7689. for (auto id : o60) report << " " << id;
  7690. report << "; key 64 ons";
  7691. for (auto id : c) report << " " << id;
  7692. report << " offs";
  7693. for (auto id : o64) report << " " << id;
  7694. report << "\n";
  7695. if (a.size() != 2 || o60.size() != 2 || c.size() != 2 || o64.size() != 2 || a[0] < 0 || c[0] < 0)
  7696. return false;
  7697. const auto fifo = o60[0] == a[0] && o60[1] == a[1]; // A ends first: A's id either way
  7698. // LIFO: D (c[1]) ends first; its own id with the tags, C's (the oldest) without
  7699. const auto lifo = expectOwn ? (o64[0] == c[1] && o64[1] == c[0]) : (o64[0] == c[0] && o64[1] == c[1]);
  7700. return fifo && lifo;
  7701. };
  7702. if (vst3)
  7703. {
  7704. report << "plugin=" << vst3->name << "\n";
  7705. const auto withTags = render (true);
  7706. const auto okTags = check ("with_tags", withTags, true);
  7707. const auto withoutTags = render (false);
  7708. const auto okBefore = check ("fix14_only", withoutTags, false);
  7709. report << "own_ids=" << (okTags ? "yes" : "NO") << " fix14_only_oldest=" << (okBefore ? "yes" : "NO") << "\n";
  7710. ok = okTags && okBefore;
  7711. }
  7712. }
  7713. if (ok) // (a failure leaves the logs for a look: their path is in the report)
  7714. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  7715. f.deleteFile();
  7716. else
  7717. report << "synth_logs=" << logBase.getFullPathName() << ".*\n";
  7718. #if JUCE_WINDOWS
  7719. _putenv_s ("LYNX_TEST_SYNTH_LOG", "");
  7720. #else
  7721. unsetenv ("LYNX_TEST_SYNTH_LOG");
  7722. #endif
  7723. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  7724. juce::File (reportPath).replaceWithText (report);
  7725. setApplicationReturnValue (ok ? 0 : 1);
  7726. quit();
  7727. }
  7728. // Round 181c: a wrapper MIDI option changed on a running plugin must act like the same option on a new one. For each
  7729. // option: a control engine whose plugin is created with the option set (proves the test can see it), then an engine
  7730. // whose plugin is already running when the option changes through editSong, as the wrapper page does it. What the
  7731. // plugin received comes from the test plugin's own log. The running instance must also stay the same one.
  7732. void runWrapperMidiTest (const juce::String& pluginPath, const juce::String& reportPath)
  7733. {
  7734. juce::String report;
  7735. auto ok = true;
  7736. const juce::File logFile (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_VST2_MIDILOG", {}));
  7737. struct Event { juce::String instance; int status, data1, data2; };
  7738. auto take = [&] {
  7739. std::vector<Event> out;
  7740. juce::StringArray lines;
  7741. logFile.readLines (lines);
  7742. for (const auto& line : lines)
  7743. {
  7744. const auto p = juce::StringArray::fromTokens (line, " ", {});
  7745. if (p.size() == 4)
  7746. out.push_back ({ p[0], p[1].getIntValue(), p[2].getIntValue(), p[3].getIntValue() });
  7747. }
  7748. logFile.deleteFile();
  7749. return out;
  7750. };
  7751. auto count = [] (const std::vector<Event>& events, int status, int data1, int data2) {
  7752. int n = 0;
  7753. for (const auto& e : events)
  7754. n += (e.status & 0xF0) == status && (data1 < 0 || e.data1 == data1) && (data2 < 0 || e.data2 == data2) ? 1 : 0;
  7755. return n;
  7756. };
  7757. struct Option
  7758. {
  7759. const char* name;
  7760. std::function<void (lynx::PluginRef&)> before, change;
  7761. std::function<juce::String (const std::vector<Event>&)> seen;
  7762. };
  7763. const Option options[] = {
  7764. { "Send note release velocity off", {}, [] (lynx::PluginRef& r) { r.releaseVelocity = false; },
  7765. [&] (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)); } },
  7766. { "Send pitch bend range on", {}, [] (lynx::PluginRef& r) { r.sendBendRange = true; },
  7767. [&] (const std::vector<Event>& e) { return "rpn_range_12=" + juce::String (count (e, 0xB0, 6, 12)); } },
  7768. { "Pitch bend range 24", [] (lynx::PluginRef& r) { r.sendBendRange = true; }, [] (lynx::PluginRef& r) { r.bendRange = 24; },
  7769. [&] (const std::vector<Event>& e) { return "rpn_range_24=" + juce::String (count (e, 0xB0, 6, 24)); } },
  7770. { "Send MOD X as polyphonic aftertouch on", {}, [] (lynx::PluginRef& r) { r.modXAftertouch = true; },
  7771. [&] (const std::vector<Event>& e) { return "aftertouch=" + juce::String (count (e, 0xA0, 69, -1)); } },
  7772. { "Send All Notes Off when playback stops off", {}, [] (lynx::PluginRef& r) { r.allNotesOffOnStop = false; },
  7773. [&] (const std::vector<Event>& e) { return "cc123=" + juce::String (count (e, 0xB0, 123, -1)); } },
  7774. };
  7775. // each phase has its own engine: an engine keeps the running instance across setSong, so one engine would
  7776. // carry the control's plugin into the "before" phase
  7777. lynx::AudioEngine scanner (false);
  7778. auto& host = scanner.getPluginHost();
  7779. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  7780. std::optional<juce::PluginDescription> vst2;
  7781. for (const auto& type : host.getKnownPlugins().getTypes())
  7782. if (type.pluginFormatName == "VST")
  7783. vst2 = type;
  7784. if (! vst2 || logFile.getFullPathName().isEmpty())
  7785. ok = false;
  7786. else
  7787. for (const auto& option : options)
  7788. {
  7789. auto makeSong = [&] (bool changed) {
  7790. auto song = lynx::Song::makeDefault();
  7791. auto& channel = song.channels[0];
  7792. channel.instrument = lynx::InstrumentKind::plugin;
  7793. channel.plugin = {};
  7794. channel.plugin.id = vst2->createIdentifierString().toStdString();
  7795. channel.plugin.name = vst2->name.toStdString();
  7796. if (option.before)
  7797. option.before (channel.plugin);
  7798. if (changed)
  7799. option.change (channel.plugin);
  7800. song.patterns[0].notes.clear();
  7801. lynx::Note note;
  7802. note.start = 0;
  7803. note.length = lynx::ppq;
  7804. note.channel = 0;
  7805. note.key = 69;
  7806. note.velocity = 1.0f;
  7807. note.release = 0.25f; // 32 of 127
  7808. note.modX = 0.75f;
  7809. song.patterns[0].notes.push_back (note);
  7810. for (std::size_t c = 1; c < song.channels.size(); ++c)
  7811. song.channels[c].muted = true;
  7812. return song;
  7813. };
  7814. // a block of the song, then a note held across "playback stopped", as the options act on either
  7815. auto play = [&] (lynx::AudioEngine& engine) {
  7816. logFile.deleteFile();
  7817. engine.renderOffline (1.0, 48000.0);
  7818. if (auto instrument = engine.getChannelInstrument (0))
  7819. {
  7820. instrument->noteOn (60, 1.0f);
  7821. instrument->transportStopped();
  7822. }
  7823. engine.renderOffline (0.1, 48000.0);
  7824. return take();
  7825. };
  7826. auto newEngine = [&] {
  7827. auto engine = std::make_unique<lynx::AudioEngine> (false);
  7828. engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  7829. return engine;
  7830. };
  7831. std::vector<Event> control;
  7832. {
  7833. auto engine = newEngine();
  7834. engine->setSong (makeSong (true));
  7835. control = play (*engine);
  7836. }
  7837. auto engine = newEngine();
  7838. engine->setSong (makeSong (false));
  7839. const auto before = play (*engine);
  7840. const auto instrumentBefore = engine->getChannelInstrument (0).get();
  7841. engine->capturePluginStates(); // as the wrapper page does
  7842. engine->editSong ([&] (lynx::Song& song) { option.change (song.channels[0].plugin); });
  7843. const auto after = play (*engine);
  7844. const auto sameInstance = engine->getChannelInstrument (0).get() == instrumentBefore;
  7845. // the counts differ between phases (how many blocks the note spans, how many instances the phase made):
  7846. // what matters is whether each kind of event is there at all
  7847. auto shape = [] (const juce::String& seen) {
  7848. juce::String out;
  7849. for (const auto& token : juce::StringArray::fromTokens (seen, " ", {}))
  7850. out << token.upToFirstOccurrenceOf ("=", false, false) << (token.fromFirstOccurrenceOf ("=", false, false).getIntValue() > 0 ? "=yes " : "=no ");
  7851. return out;
  7852. };
  7853. auto instances = [] (const std::vector<Event>& events) {
  7854. std::set<juce::String> made;
  7855. for (const auto& e : events)
  7856. made.insert (e.instance);
  7857. return (int) made.size();
  7858. };
  7859. const auto a = option.seen (control) + " instances=" + juce::String (instances (control)),
  7860. b = option.seen (before) + " instances=" + juce::String (instances (before)),
  7861. c = option.seen (after) + " instances=" + juce::String (instances (after));
  7862. const auto visible = shape (option.seen (control)) != shape (option.seen (before));
  7863. const auto works = shape (option.seen (after)) == shape (option.seen (control));
  7864. report << option.name << ": control " << a << " | before " << b << " | after the change " << c << " | same_instance=" << (int) sameInstance
  7865. << " | test_sees_the_option=" << (int) visible << " | " << (! visible ? "NOT PROVEN" : works ? "acts on the plugin" : "DEAD until re-created") << "\n";
  7866. ok = ok && visible && works;
  7867. }
  7868. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  7869. juce::File (reportPath).replaceWithText (report);
  7870. setApplicationReturnValue (ok ? 0 : 1);
  7871. quit();
  7872. }
  7873. // LYNX.exe --wrappershot "LYNX Test Drums.dll" <folder> (round 188d): the wrapper's Processing tab drawn offscreen
  7874. // (no window, no focus) for the FL | LYNX review: wrap-default.png (a fresh plugin), wrap-automap.png (Auto map
  7875. // outputs, output 3 off: FL's shot b23), wrap-settings.png. Scale 1.5 (FL's shots are at 150 %).
  7876. void runWrapperShot (const juce::String& pluginPath, const juce::String& folderPath)
  7877. {
  7878. const juce::File folder (folderPath);
  7879. folder.createDirectory();
  7880. auto ok = false;
  7881. lynx::AudioEngine engine (false);
  7882. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  7883. std::optional<juce::PluginDescription> vst2;
  7884. for (const auto& type : engine.getPluginHost().getKnownPlugins().getTypes())
  7885. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  7886. vst2 = type; // (the profile may know other test plugins)
  7887. if (vst2 && ! vst2->isInstrument)
  7888. {
  7889. // an effect (round 188d): on insert 1, with insert 2 routed there as a sidechain (FL's k65 / k78 shots):
  7890. // wrap-fx-default.png, wrap-fx-automap.png (Auto map inputs and outputs)
  7891. auto song = lynx::Song::makeDefault();
  7892. if (song.mixer.size() < 4)
  7893. song.mixer.resize (4);
  7894. auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
  7895. slot.plugin.id = vst2->createIdentifierString().toStdString();
  7896. slot.plugin.name = vst2->name.toStdString();
  7897. song.mixer[1].effects = { slot };
  7898. lynx::mixerops::sidechainTo (song, 2, 1);
  7899. engine.setSong (song);
  7900. engine.renderOffline (0.05, 48000.0);
  7901. if (auto fx = std::dynamic_pointer_cast<lynx::PluginEffect> (engine.getEffect (1, 0)))
  7902. {
  7903. auto find = [] (lynx::Song& s) -> lynx::PluginRef* {
  7904. return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
  7905. };
  7906. auto save = [&] (const char* name) {
  7907. const auto image = lynx::wrapperSettingsSnapshot (engine, find, fx->getInstance(), false, 1, 1.5f, 1, 0);
  7908. juce::FileOutputStream out (folder.getChildFile (name));
  7909. out.setPosition (0);
  7910. out.truncate();
  7911. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  7912. };
  7913. ok = save ("wrap-fx-default.png");
  7914. engine.editSong ([] (lynx::Song& s) {
  7915. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.inputs, 2);
  7916. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.outputs, 2);
  7917. s.mixer[1].effects[0].sidechain = lynx::mixerops::sidechainIndexSource (s, 1, 1);
  7918. });
  7919. ok = ok && save ("wrap-fx-automap.png") && engine.getSong().mixer[1].effects[0].sidechain == 2;
  7920. }
  7921. }
  7922. else if (vst2)
  7923. {
  7924. auto song = lynx::Song::makeDefault();
  7925. auto& channel = song.channels[0];
  7926. channel.instrument = lynx::InstrumentKind::plugin;
  7927. channel.plugin = {};
  7928. channel.plugin.id = vst2->createIdentifierString().toStdString();
  7929. channel.plugin.name = vst2->name.toStdString();
  7930. channel.mixerTrack = 5;
  7931. engine.setSong (song);
  7932. engine.renderOffline (0.05, 48000.0); // (the plugin is hosted by then)
  7933. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  7934. {
  7935. auto find = [] (lynx::Song& s) -> lynx::PluginRef* { return s.channels.empty() ? nullptr : &s.channels[0].plugin; };
  7936. auto save = [&] (const char* name, int tab) {
  7937. const auto image = lynx::wrapperSettingsSnapshot (engine, find, instrument->getInstance(), true, tab, 1.5f);
  7938. juce::FileOutputStream out (folder.getChildFile (name));
  7939. out.setPosition (0);
  7940. out.truncate();
  7941. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  7942. };
  7943. ok = save ("wrap-default.png", 1) && save ("wrap-settings.png", 0);
  7944. engine.editSong ([] (lynx::Song& s) {
  7945. lynx::autoMapOutputs (s.channels[0].plugin.outputs, 8);
  7946. s.channels[0].plugin.outputs.resize (8);
  7947. s.channels[0].plugin.outputs[2].active = 0;
  7948. s.channels[0].plugin.processInactive = false; // (as an LED click does, FL's b23)
  7949. });
  7950. ok = ok && save ("wrap-automap.png", 1);
  7951. }
  7952. }
  7953. setApplicationReturnValue (ok ? 0 : 1);
  7954. quit();
  7955. }
  7956. // LYNX.exe --multiouttest "LYNX Test Drums.dll" report.txt (round 188d, issue #114): a multi-output VST2
  7957. // (tools/testplugin/lynx_test_drums_vst2.c: key 36 = output 1 at 110 Hz, key 37 = output 2 at 220 Hz) on a
  7958. // channel routed to insert 1; the wrapper's Processing › Connections as FL plays them [EXEC fl188d]: every output
  7959. // on the channel's insert by default, an offset to another insert, an inactive output silent, the channel's
  7960. // volume on all of them. Measured on the master with insert 1 muted or not.
  7961. void runMultiOutTest (const juce::String& pluginPath, const juce::String& reportPath)
  7962. {
  7963. juce::String report;
  7964. auto ok = true;
  7965. lynx::AudioEngine scanner (false);
  7966. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  7967. std::optional<juce::PluginDescription> vst2;
  7968. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  7969. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  7970. vst2 = type; // (the profile may know other test plugins)
  7971. struct Case
  7972. {
  7973. const char* name;
  7974. std::vector<lynx::PluginOutputRoute> routes;
  7975. bool muteInsert1;
  7976. float volume;
  7977. bool kick, snare; // expected on the master
  7978. };
  7979. const Case cases[] = {
  7980. { "defaults", {}, false, -1.0f, true, true },
  7981. { "defaults, insert 1 muted", {}, true, -1.0f, false, false },
  7982. { "auto map, insert 1 muted", { { 0, 1 }, { 1, 1 } }, true, -1.0f, false, true },
  7983. { "auto map", { { 0, 1 }, { 1, 1 } }, false, -1.0f, true, true },
  7984. { "output 2 inactive", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, false },
  7985. { "output 1 inactive", { { 0, 0 } }, false, -1.0f, false, true },
  7986. { "auto map, channel volume 0", { { 0, 1 }, { 1, 1 } }, false, 0.0f, false, false },
  7987. { "output 2 inactive, Process inactive inputs and outputs on", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, true },
  7988. };
  7989. auto tone = [] (const std::vector<float>& x, double hz) {
  7990. // Goertzel magnitude over the buffer (normalised to a sine's amplitude)
  7991. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 48000.0;
  7992. double s1 = 0.0, s2 = 0.0;
  7993. for (const auto v : x)
  7994. {
  7995. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  7996. s2 = s1;
  7997. s1 = s0;
  7998. }
  7999. 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());
  8000. };
  8001. if (! vst2)
  8002. ok = false;
  8003. else
  8004. for (const auto& c : cases)
  8005. {
  8006. lynx::AudioEngine engine (false);
  8007. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  8008. auto song = lynx::Song::makeDefault();
  8009. auto& channel = song.channels[0];
  8010. channel.instrument = lynx::InstrumentKind::plugin;
  8011. channel.plugin = {};
  8012. channel.plugin.id = vst2->createIdentifierString().toStdString();
  8013. channel.plugin.name = vst2->name.toStdString();
  8014. channel.plugin.outputs = c.routes;
  8015. // (FL's "Process inactive inputs and outputs" plays an inactive output: off but for the case named so)
  8016. channel.plugin.processInactive = juce::String (c.name).contains ("Process inactive");
  8017. channel.mixerTrack = 1;
  8018. if (c.volume >= 0.0f)
  8019. channel.volume = c.volume;
  8020. for (std::size_t k = 1; k < song.channels.size(); ++k)
  8021. song.channels[k].muted = true;
  8022. if (song.mixer.size() < 4)
  8023. song.mixer.resize (4);
  8024. song.mixer[1].muted = c.muteInsert1;
  8025. song.patterns[0].notes.clear();
  8026. for (const auto key : { 36, 37 })
  8027. {
  8028. lynx::Note note;
  8029. note.start = 0;
  8030. note.length = lynx::ppq;
  8031. note.channel = 0;
  8032. note.key = key;
  8033. note.velocity = 1.0f;
  8034. song.patterns[0].notes.push_back (note);
  8035. }
  8036. engine.setSong (song);
  8037. std::vector<float> master;
  8038. lynx::AudioEngine::RenderOptions options;
  8039. options.seconds = 0.25;
  8040. options.sampleRate = 48000.0;
  8041. options.capture = [&master] (const float* l, const float*, int n) { master.insert (master.end(), l, l + n); };
  8042. engine.renderOffline (options);
  8043. const auto kick = tone (master, 110.0), snare = tone (master, 220.0);
  8044. const auto pass = (kick > 0.01) == c.kick && (snare > 0.01) == c.snare;
  8045. report << c.name << ": kick_110Hz=" << juce::String (kick, 4) << " snare_220Hz=" << juce::String (snare, 4) << " expected kick="
  8046. << (int) c.kick << " snare=" << (int) c.snare << (pass ? " OK" : " FAILED") << "\n";
  8047. ok = ok && pass;
  8048. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  8049. if (&c == &cases[0])
  8050. {
  8051. report << "outputs=" << (int) instrument->outputs().size();
  8052. for (const auto& o : instrument->outputs())
  8053. report << " [" << o.name << " ch" << o.channel << "x" << o.channels << "]";
  8054. report << "\n";
  8055. ok = ok && instrument->outputs().size() == 8 && instrument->outputs()[1].name == "Snare";
  8056. }
  8057. }
  8058. // round 189j: "LYNX Test SC.dll" next to it (tools/testplugin/lynx_test_sc_vst2.c) as an effect on insert 1
  8059. const auto sc = juce::File (pluginPath).getSiblingFile ("LYNX Test SC.dll");
  8060. if (sc.existsAsFile())
  8061. ok = runEffectConnectionsTest (sc, report) && ok;
  8062. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  8063. juce::File (reportPath).replaceWithText (report);
  8064. setApplicationReturnValue (ok ? 0 : 1);
  8065. quit();
  8066. }
  8067. // Round 189j: a hosted effect's Processing › Connections against FL 2026's own renders of the same projects
  8068. // [EXEC fxconn189j: FL /R renders of LYNX's .flp exports, docs/analise/REA_rodada189j.md]. Insert 1: a 440 Hz
  8069. // sampler and "LYNX Test SC" (output 1 = input 1, output 2 = input 2); inserts 2 (1000 Hz) and 3 (1500 Hz) routed
  8070. // to insert 1 at level 0 only; insert 4 a 2500 Hz reference on the Master; insert 1 routed to the Master and at
  8071. // level 0 to inserts 5 (panned left) and 6 (right). Each tone's level per side, in dB from the reference's, must be
  8072. // FL's within 0.5 dB (absent: 50 dB under it).
  8073. bool runEffectConnectionsTest (const juce::File& scFile, juce::String& report)
  8074. {
  8075. lynx::AudioEngine scanner (false);
  8076. scanner.getPluginHost().addPluginFile (scFile);
  8077. std::optional<juce::PluginDescription> sc;
  8078. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  8079. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == scFile)
  8080. sc = type;
  8081. report << "effect_plugin=" << (sc ? sc->name : juce::String ("not found")) << "\n";
  8082. if (! sc)
  8083. return false;
  8084. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-fxconn189j");
  8085. dir.createDirectory();
  8086. const double tones[] = { 440.0, 1000.0, 1500.0, 2500.0 };
  8087. for (const auto hz : tones)
  8088. {
  8089. const auto wav = dir.getChildFile ("sine" + juce::String ((int) hz) + ".wav");
  8090. if (wav.existsAsFile())
  8091. continue;
  8092. juce::AudioBuffer<float> sine (1, 44100 * 3);
  8093. for (int i = 0; i < sine.getNumSamples(); ++i)
  8094. sine.setSample (0, i, 0.25f * (float) std::sin (2.0 * juce::MathConstants<double>::pi * hz * i / 44100.0));
  8095. juce::WavAudioFormat format;
  8096. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  8097. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  8098. {
  8099. out.release();
  8100. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  8101. writer->writeFromAudioSampleBuffer (sine, 0, sine.getNumSamples());
  8102. }
  8103. }
  8104. using Route = lynx::PluginOutputRoute;
  8105. constexpr float none = -999.0f;
  8106. struct Case
  8107. {
  8108. const char* name;
  8109. std::vector<Route> inputs, outputs;
  8110. int tweak; // 1 no Master route, 2 insert 1 fader at 0.4, 3 Process inactive off, 4 Master route level 0, 5 route
  8111. // to 7 too, 6 insert 2 fader at 0.4, 7 insert 2 muted, 8 insert 2 panned left
  8112. float level[3][2]; // 440 / 1000 / 1500 Hz, left / right: dB from the reference, FL's
  8113. };
  8114. const Route d { 0, 1 };
  8115. const Case cases[] = {
  8116. { "e00 FL defaults", { d, d }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  8117. { "e01 input 1 at 1", { { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  8118. { "e02 input 1 at 2", { { 2, 1 } }, {}, 0, { { 0, 0 }, { none, none }, { 0, 0 } } },
  8119. { "e03 input 2 at 1", { d, { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  8120. { "e04 output 2 at 1 (Master)", { d, { 1, 1 } }, { d, { 1, 1 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  8121. { "e05 output 2 at 2 (insert 5)", { d, { 1, 1 } }, { d, { 2, 1 } }, 0, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  8122. { "e06 output 1 at 1", {}, { { 1, 1 } }, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  8123. { "e07 output 2 at 5 (past the list)", { d, { 1, 1 } }, { d, { 5, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  8124. { "e08 inputs 1 and 2 at 1", { { 1, 1 }, { 1, 1 } }, {}, 0, { { none, none }, { 6.1f, 6.1f }, { none, none } } },
  8125. { "e09 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  8126. { "e10 input 1 at 5 (past the list)", { { 5, 1 } }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  8127. { "e11 output 2 at 3 (insert 6)", { d, { 1, 1 } }, { d, { 3, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  8128. { "e13 no Master route, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 1, { { none, none }, { 3.0f, none }, { none, none } } },
  8129. { "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 } } },
  8130. { "e15 input 2 inactive", { d, { 1, 0 } }, { d, d }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  8131. { "e16 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  8132. { "e18 route to 7 too, output 2 at 3", { d, { 1, 1 } }, { d, { 3, 1 } }, 5, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  8133. { "e19 Master route at 0, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 4, { { none, none }, { 0, 0 }, { none, none } } },
  8134. { "e22 input 1 at 1 inactive", { { 1, 0 } }, {}, 3, { { 0, 0 }, { none, none }, { none, none } } },
  8135. { "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 } } },
  8136. { "e24 input 1 at 1, insert 2 fader 0.4", { { 1, 1 } }, {}, 6, { { 0, 0 }, { -12.7f, -12.7f }, { none, none } } },
  8137. { "e25 input 1 at 1, insert 2 muted", { { 1, 1 } }, {}, 7, { { 0, 0 }, { none, none }, { none, none } } },
  8138. { "e26 input 1 at 1, insert 2 panned left", { { 1, 1 } }, {}, 8, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  8139. };
  8140. auto goertzel = [] (const std::vector<float>& x, double hz) {
  8141. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 44100.0;
  8142. double s1 = 0.0, s2 = 0.0;
  8143. for (const auto v : x)
  8144. {
  8145. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  8146. s2 = s1;
  8147. s1 = s0;
  8148. }
  8149. 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());
  8150. return a > 1e-7 ? 20.0 * std::log10 (a) : -140.0;
  8151. };
  8152. auto ok = true;
  8153. for (const auto& c : cases)
  8154. {
  8155. lynx::AudioEngine engine (false);
  8156. engine.getPluginHost().addPluginFile (scFile);
  8157. auto song = lynx::Song::makeDefault();
  8158. song.bpm = 120.0;
  8159. song.channels.clear();
  8160. song.automations.clear();
  8161. for (auto& p : song.patterns)
  8162. p.notes.clear();
  8163. for (int k = 0; k < 4; ++k)
  8164. {
  8165. lynx::ChannelDef ch;
  8166. ch.name = "S" + std::to_string ((int) tones[k]);
  8167. ch.instrument = lynx::InstrumentKind::sampler;
  8168. ch.samplePath = dir.getChildFile ("sine" + juce::String ((int) tones[k]) + ".wav").getFullPathName().toStdString();
  8169. ch.mixerTrack = k + 1;
  8170. song.channels.push_back (ch);
  8171. lynx::Note note;
  8172. note.start = 0;
  8173. note.length = 8 * lynx::ppq;
  8174. note.channel = k;
  8175. note.key = 60;
  8176. note.velocity = 0.78f;
  8177. song.patterns[0].notes.push_back (note);
  8178. }
  8179. if (song.mixer.size() < 10)
  8180. song.mixer.resize (10);
  8181. for (auto& t : song.mixer)
  8182. {
  8183. t.effects.clear();
  8184. t.sends.clear();
  8185. t.toMaster = true;
  8186. }
  8187. lynx::EffectSlot fx;
  8188. fx.kind = lynx::EffectKind::plugin;
  8189. fx.plugin.id = sc->createIdentifierString().toStdString();
  8190. fx.plugin.name = sc->name.toStdString();
  8191. fx.plugin.inputs = c.inputs;
  8192. fx.plugin.outputs = c.outputs;
  8193. fx.plugin.processInactive = c.tweak != 3;
  8194. auto& one = song.mixer[1];
  8195. one.effects.push_back (fx);
  8196. one.sends = { { 5, 0.0f }, { 6, 0.0f } };
  8197. for (const int t : { 2, 3 })
  8198. {
  8199. song.mixer[(std::size_t) t].toMaster = false;
  8200. song.mixer[(std::size_t) t].sends = { { 1, 0.0f } };
  8201. }
  8202. song.mixer[5].pan = -1.0f;
  8203. song.mixer[6].pan = 1.0f;
  8204. one.toMaster = c.tweak != 1;
  8205. if (c.tweak == 2)
  8206. one.volume = 0.4f;
  8207. if (c.tweak == 4)
  8208. one.masterLevel = 0.0f;
  8209. if (c.tweak == 6)
  8210. song.mixer[2].volume = 0.4f;
  8211. song.mixer[2].muted = c.tweak == 7;
  8212. song.mixer[2].pan = c.tweak == 8 ? -1.0f : 0.0f;
  8213. if (c.tweak == 5)
  8214. {
  8215. one.sends = { { 7, 0.0f }, { 5, 0.0f }, { 6, 0.0f } };
  8216. song.mixer[7].pan = 0.5f;
  8217. }
  8218. // (input 2's index sets the slot's side input source, as the Connections page and the import do)
  8219. if (c.inputs.size() > 1 && c.inputs[1].offset > 0)
  8220. one.effects[0].sidechain = lynx::mixerops::sidechainIndexSource (song, 1, c.inputs[1].offset);
  8221. engine.setSong (song);
  8222. std::vector<float> left, right;
  8223. lynx::AudioEngine::RenderOptions options;
  8224. options.seconds = 1.2;
  8225. options.sampleRate = 44100.0;
  8226. options.capture = [&] (const float* l, const float* r, int n) {
  8227. left.insert (left.end(), l, l + n);
  8228. right.insert (right.end(), r, r + n);
  8229. };
  8230. engine.renderOffline (options);
  8231. const auto from = (std::size_t) 22050, to = (std::size_t) 44100;
  8232. if (right.size() < to)
  8233. {
  8234. report << c.name << ": rendered " << (int) right.size() << " samples FAILED\n";
  8235. ok = false;
  8236. continue;
  8237. }
  8238. const std::vector<float> l (left.begin() + (std::ptrdiff_t) from, left.begin() + (std::ptrdiff_t) to);
  8239. const std::vector<float> r (right.begin() + (std::ptrdiff_t) from, right.begin() + (std::ptrdiff_t) to);
  8240. const auto ref = 0.5 * (goertzel (l, 2500.0) + goertzel (r, 2500.0));
  8241. auto pass = ref > -60.0;
  8242. report << c.name << ": ref=" << juce::String (ref, 1);
  8243. for (int k = 0; k < 3; ++k)
  8244. for (int side = 0; side < 2; ++side)
  8245. {
  8246. const auto got = goertzel (side == 0 ? l : r, tones[k]) - ref;
  8247. const auto want = c.level[k][side];
  8248. const auto good = want == none ? got < -50.0 : std::abs (got - want) < 0.5;
  8249. pass = pass && good;
  8250. report << " " << (int) tones[k] << (side == 0 ? "L" : "R") << "=" << (got < -50.0 ? juce::String ("-") : juce::String (got, 1))
  8251. << (good ? "" : "(FL " + (want == none ? juce::String ("-") : juce::String (want, 1)) + ")");
  8252. }
  8253. report << (pass ? " OK" : " FAILED") << "\n";
  8254. ok = ok && pass;
  8255. }
  8256. return ok;
  8257. }
  8258. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  8259. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  8260. // that the plugin comes back with the changed parameter.
  8261. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  8262. {
  8263. juce::String report;
  8264. bool ok = false;
  8265. {
  8266. lynx::AudioEngine offline (false);
  8267. auto& host = offline.getPluginHost();
  8268. host.addPluginFile (juce::File (pluginPath));
  8269. const juce::PluginDescription* vst3 = nullptr;
  8270. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  8271. for (const auto& type : types)
  8272. if (type.pluginFormatName == "VST3" && type.isInstrument)
  8273. vst3 = &type;
  8274. if (vst3 != nullptr)
  8275. {
  8276. juce::String error;
  8277. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  8278. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  8279. if (parameter != nullptr)
  8280. {
  8281. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  8282. parameter->setValueNotifyingHost (target);
  8283. juce::MemoryBlock juceState;
  8284. plugin->getStateInformation (juceState);
  8285. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  8286. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  8287. std::vector<std::uint8_t> flState;
  8288. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  8289. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  8290. put32 (id);
  8291. put32 ((std::uint32_t) data.getSize());
  8292. put32 (0);
  8293. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  8294. };
  8295. put32 (1);
  8296. record (1, juce::MemoryBlock (64, true));
  8297. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  8298. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  8299. juce::MemoryBlock slots;
  8300. const auto paramId = [&] (int i) {
  8301. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  8302. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  8303. };
  8304. const bool reorder = plugin->getParameters().size() >= 3;
  8305. if (reorder)
  8306. {
  8307. for (auto v : { 2u, paramId (2), paramId (0) })
  8308. slots.append (&v, 4);
  8309. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  8310. }
  8311. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  8312. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  8313. if (auto* child = xml->getChildByName (tag))
  8314. {
  8315. juce::MemoryBlock data;
  8316. data.fromBase64Encoding (child->getAllSubText());
  8317. record (id, data);
  8318. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  8319. }
  8320. if (reorder)
  8321. record (4, slots);
  8322. plugin.reset();
  8323. auto song = lynx::Song::makeDefault();
  8324. auto& f = song.channels[4].plugin.foreign;
  8325. f.format = lynx::ForeignPlugin::Format::vst3;
  8326. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  8327. f.state = flState;
  8328. {
  8329. std::vector<std::uint8_t> comp, ctrl;
  8330. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  8331. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  8332. }
  8333. for (int k = 0; k < 3; ++k)
  8334. {
  8335. lynx::Automation a;
  8336. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  8337. song.automations.push_back (a);
  8338. }
  8339. const auto adopted = host.adoptFlPlugins (song);
  8340. report << "adopted=" << adopted << "\n";
  8341. juce::String mapped;
  8342. for (const auto& a : song.automations)
  8343. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  8344. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  8345. report << "slot_positions=" << mapped << "\n";
  8346. const auto slotsOk = ! reorder || mapped == "2,0,1";
  8347. offline.setSong (song);
  8348. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  8349. {
  8350. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  8351. report << "restored_value=" << value << "\n";
  8352. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  8353. }
  8354. }
  8355. }
  8356. }
  8357. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  8358. juce::File (reportPath).replaceWithText (report);
  8359. setApplicationReturnValue (ok ? 0 : 1);
  8360. quit();
  8361. }
  8362. void runDemoSongs (const juce::String& folderPath)
  8363. {
  8364. const juce::File folder (folderPath);
  8365. folder.createDirectory();
  8366. bool ok = true;
  8367. for (int d = 1; d < lynx::demos::count; ++d)
  8368. {
  8369. juce::String error;
  8370. ok = lynx::ProjectFile::save (lynx::demos::make (d), folder.getChildFile (lynx::demos::fileName (d)), error) && ok;
  8371. }
  8372. setApplicationReturnValue (ok ? 0 : 1);
  8373. quit();
  8374. }
  8375. void runShowcase (const juce::String& outputPath, int currentPattern)
  8376. {
  8377. const auto song = lynx::makeShowcaseSong (currentPattern);
  8378. juce::String error;
  8379. const auto ok = lynx::ProjectFile::save (song, juce::File (outputPath), error);
  8380. setApplicationReturnValue (ok ? 0 : 1);
  8381. quit();
  8382. }
  8383. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  8384. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  8385. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  8386. // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
  8387. struct TestVoice
  8388. {
  8389. explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
  8390. {
  8391. if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
  8392. instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
  8393. else
  8394. effect = std::move (p);
  8395. }
  8396. void noteOn()
  8397. {
  8398. if (instrument != nullptr)
  8399. instrument->noteOn (60, 0.9f);
  8400. }
  8401. void render (float* l, float* r, int n, float gainLeft, float gainRight)
  8402. {
  8403. if (instrument != nullptr)
  8404. {
  8405. instrument->render (l, r, n, gainLeft, gainRight);
  8406. return;
  8407. }
  8408. const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
  8409. juce::AudioBuffer<float> block (channels, 512);
  8410. juce::MidiBuffer midi;
  8411. for (int done = 0; done < n; done += 512)
  8412. {
  8413. const auto k = juce::jmin (512, n - done);
  8414. block.setSize (channels, k, false, false, true);
  8415. for (int i = 0; i < k; ++i)
  8416. {
  8417. const auto v = 0.25f * (float) std::sin (phase);
  8418. phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
  8419. for (int c = 0; c < channels; ++c)
  8420. block.setSample (c, i, v);
  8421. }
  8422. effect->processBlock (block, midi);
  8423. for (int i = 0; i < k; ++i)
  8424. {
  8425. l[done + i] += gainLeft * block.getSample (0, i);
  8426. r[done + i] += gainRight * block.getSample (1, i);
  8427. }
  8428. }
  8429. }
  8430. void release()
  8431. {
  8432. instrument.reset();
  8433. effect.reset();
  8434. }
  8435. std::unique_ptr<lynx::PluginInstrument> instrument;
  8436. std::unique_ptr<juce::AudioPluginInstance> effect;
  8437. double phase = 0.0;
  8438. };
  8439. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  8440. {
  8441. juce::String report;
  8442. bool ok = false;
  8443. lynx::setPluginSandboxAlerts (false);
  8444. const juce::File log (reportPath + ".log");
  8445. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  8446. log.deleteFile();
  8447. {
  8448. lynx::PluginHost host (false);
  8449. host.addPluginFile (juce::File (pluginPath));
  8450. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  8451. // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
  8452. const juce::PluginDescription* instrument = nullptr;
  8453. for (const auto& type : types)
  8454. if (type.isInstrument)
  8455. instrument = &type;
  8456. for (const auto& type : types)
  8457. if (instrument == nullptr && ! type.isInstrument)
  8458. instrument = &type;
  8459. step ("host");
  8460. juce::String error;
  8461. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  8462. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  8463. step ("created");
  8464. if (remote != nullptr)
  8465. {
  8466. auto& proxy = *remote;
  8467. TestVoice voice (std::move (remote));
  8468. std::vector<float> l (48000), r (48000);
  8469. auto peakOf = [&] {
  8470. float peak = 0.0f;
  8471. for (std::size_t k = 0; k < l.size(); ++k)
  8472. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  8473. return peak;
  8474. };
  8475. const auto start = juce::Time::getMillisecondCounterHiRes();
  8476. voice.noteOn();
  8477. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  8478. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  8479. const auto peak = peakOf();
  8480. step ("played");
  8481. if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
  8482. {
  8483. // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
  8484. const auto dead = lynx::isSandboxedPluginDead (proxy);
  8485. std::fill (l.begin(), l.end(), 0.0f);
  8486. std::fill (r.begin(), r.end(), 0.0f);
  8487. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  8488. report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  8489. ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
  8490. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  8491. juce::File (reportPath).replaceWithText (report);
  8492. setApplicationReturnValue (ok ? 0 : 1);
  8493. quit();
  8494. return;
  8495. }
  8496. report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
  8497. << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  8498. if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
  8499. {
  8500. // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
  8501. std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
  8502. juce::Thread::sleep (4000);
  8503. juce::MemoryBlock state;
  8504. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  8505. proxy.getStateInformation (state);
  8506. report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
  8507. editor.reset();
  8508. }
  8509. // parameter -> state -> in-process plugin
  8510. bool stateOk = false;
  8511. if (! proxy.getParameters().isEmpty())
  8512. {
  8513. auto* p = proxy.getParameters()[0];
  8514. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  8515. p->setValue (target);
  8516. std::fill (l.begin(), l.end(), 0.0f);
  8517. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  8518. juce::MemoryBlock state;
  8519. proxy.getStateInformation (state);
  8520. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  8521. {
  8522. local->setStateInformation (state.getData(), (int) state.getSize());
  8523. const auto back = local->getParameters()[0]->getValue();
  8524. // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
  8525. auto control = target;
  8526. if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  8527. {
  8528. a->enableAllBuses();
  8529. a->prepareToPlay (48000.0, 512);
  8530. a->getParameters()[0]->setValue (target);
  8531. juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
  8532. block.clear();
  8533. juce::MidiBuffer none;
  8534. a->processBlock (block, none);
  8535. juce::MemoryBlock direct;
  8536. a->getStateInformation (direct);
  8537. if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  8538. {
  8539. b->setStateInformation (direct.getData(), (int) direct.getSize());
  8540. control = b->getParameters()[0]->getValue();
  8541. }
  8542. a->releaseResources();
  8543. }
  8544. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
  8545. stateOk = std::abs (back - control) < 0.02f;
  8546. }
  8547. }
  8548. step ("state");
  8549. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  8550. lynx::hangSandboxedPluginForTest (proxy);
  8551. juce::Thread::sleep (200);
  8552. std::fill (l.begin(), l.end(), 1.0f);
  8553. std::fill (r.begin(), r.end(), 1.0f);
  8554. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  8555. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  8556. std::fill (l.begin(), l.end(), 0.0f);
  8557. std::fill (r.begin(), r.end(), 0.0f);
  8558. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  8559. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  8560. const auto dead = lynx::isSandboxedPluginDead (proxy);
  8561. const auto hangPeak = peakOf();
  8562. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
  8563. // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
  8564. bool crashOk = false;
  8565. if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
  8566. {
  8567. auto& proxy2 = *second;
  8568. TestVoice voice2 (std::move (second));
  8569. voice2.noteOn();
  8570. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  8571. lynx::crashSandboxedPluginForTest (proxy2);
  8572. const auto crashStart = juce::Time::getMillisecondCounterHiRes();
  8573. while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
  8574. {
  8575. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  8576. juce::Thread::sleep (5);
  8577. }
  8578. const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
  8579. std::fill (l.begin(), l.end(), 0.0f);
  8580. std::fill (r.begin(), r.end(), 0.0f);
  8581. voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  8582. const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
  8583. report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
  8584. crashOk = crashDead && crashMs < 3000.0;
  8585. // issue #159: freeing the crashed plugin doesn't wait on its pipe (JUCE waited up to 10 s there for
  8586. // the gone child, on the message thread when the rack freed it); its teardown ends on its own
  8587. const auto freeStart = juce::Time::getMillisecondCounterHiRes();
  8588. voice2.release();
  8589. const auto freeMs = juce::Time::getMillisecondCounterHiRes() - freeStart;
  8590. const auto endedAll = lynx::finishSandboxTeardowns (15000);
  8591. report << "crashed_free_ms=" << freeMs << " teardown_done=" << (endedAll ? 1 : 0) << "\n";
  8592. crashOk = crashOk && freeMs < 250.0 && endedAll;
  8593. }
  8594. step ("crash");
  8595. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
  8596. }
  8597. }
  8598. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  8599. juce::File (reportPath).replaceWithText (report);
  8600. setApplicationReturnValue (ok ? 0 : 1);
  8601. quit();
  8602. }
  8603. // --timertest (round 174f): a view's polling timer follows the view and its parents, and survives a minimised window
  8604. void runTimerTest (const juce::File& report)
  8605. {
  8606. struct Ticks final : juce::Timer
  8607. {
  8608. void timerCallback() override {}
  8609. } timer;
  8610. juce::Component top, parent, view;
  8611. parent.addChildComponent (view);
  8612. top.addChildComponent (parent);
  8613. top.setSize (320, 200);
  8614. lynx::ui::TimerWhileShowing watch (view, timer, 30);
  8615. juce::String text;
  8616. auto failures = 0;
  8617. auto expect = [&] (const char* step, bool running) {
  8618. const auto ok = timer.isTimerRunning() == running;
  8619. failures += ok ? 0 : 1;
  8620. text << step << ": timer " << (timer.isTimerRunning() ? "running" : "stopped") << (ok ? "" : " FAIL") << "\n";
  8621. };
  8622. expect ("never shown", false);
  8623. view.setVisible (true);
  8624. parent.setVisible (true);
  8625. expect ("view and parent visible, not on the desktop", false);
  8626. top.addToDesktop (juce::ComponentPeer::windowHasTitleBar);
  8627. top.setVisible (true);
  8628. expect ("window shown", true);
  8629. parent.setVisible (false);
  8630. expect ("parent hidden", false);
  8631. parent.setVisible (true);
  8632. expect ("parent shown", true);
  8633. view.setVisible (false);
  8634. expect ("view hidden", false);
  8635. top.getPeer()->setMinimised (true);
  8636. view.setVisible (true);
  8637. expect ("view shown while minimised", true);
  8638. top.getPeer()->setMinimised (false);
  8639. expect ("window restored", true);
  8640. top.setVisible (false);
  8641. expect ("window hidden", false);
  8642. top.setVisible (true);
  8643. expect ("window shown again", true);
  8644. top.removeFromDesktop();
  8645. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  8646. report.replaceWithText (text);
  8647. setApplicationReturnValue (failures == 0 ? 0 : 1);
  8648. quit();
  8649. }
  8650. // --cachetest (round 174f): PlaylistComponent::cacheSelfTest on the project, the Playlist off screen at 1466 x 930
  8651. void runCacheTest (const juce::File& project, const juce::File& report)
  8652. {
  8653. engine = std::make_unique<lynx::AudioEngine>();
  8654. juce::String error;
  8655. auto ok = false;
  8656. if (project.hasFileExtension ("flp"))
  8657. ok = engine->importFlpFile (project, error);
  8658. else if (auto song = lynx::ProjectFile::load (project, error))
  8659. {
  8660. engine->setSong (std::move (*song));
  8661. ok = true;
  8662. }
  8663. juce::String text = "project: " + project.getFullPathName() + "\n";
  8664. if (ok)
  8665. {
  8666. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  8667. playlist->setBounds (0, 0, 1466, 930);
  8668. playlist->setVisible (true);
  8669. text << playlist->cacheSelfTest ([] { lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000); }, report.getParentDirectory());
  8670. }
  8671. else
  8672. text << "result=ERROR " << error << "\n";
  8673. report.replaceWithText (text);
  8674. setApplicationReturnValue (ok && text.contains ("result=OK") ? 0 : 1);
  8675. quit();
  8676. }
  8677. // --picturetest (round 190bm): ui/PictureCheck.h on the Playlist and the Mixer, at a window's usual size, at a 4K
  8678. // screen's, and wider than a GPU bitmap can be (16384 px)
  8679. void runPictureTest (const juce::File& report, const juce::File& project)
  8680. {
  8681. engine = std::make_unique<lynx::AudioEngine>();
  8682. juce::String error, text;
  8683. if (project != juce::File())
  8684. {
  8685. auto ok = false;
  8686. if (project.hasFileExtension ("flp"))
  8687. ok = engine->importFlpFile (project, error);
  8688. else if (auto song = lynx::ProjectFile::load (project, error))
  8689. {
  8690. engine->setSong (std::move (*song));
  8691. ok = true;
  8692. }
  8693. text << "project: " << project.getFullPathName() << (ok ? "" : " (not loaded: " + error + ")") << "\n";
  8694. }
  8695. #if JUCE_WINDOWS
  8696. text << "native image: " << juce::NativeImageType().create (juce::Image::RGB, 8, 8, true)->createType()->getTypeID()
  8697. << " (software = " << juce::SoftwareImageType().getTypeID() << ")\n";
  8698. #endif
  8699. auto failures = 0;
  8700. struct Size
  8701. {
  8702. int width, height;
  8703. std::vector<float> scales;
  8704. };
  8705. const auto folder = report.getParentDirectory();
  8706. for (const auto& size : { Size { 1466, 930, { 1.0f, 1.5f, 2.0f, 3.0f } }, Size { 3840, 2040, { 1.0f, 2.0f } }, Size { 17000, 700, { 1.0f } } })
  8707. {
  8708. const auto label = [&size] (const char* name) { return juce::String (name) + " " + juce::String (size.width) + " x " + juce::String (size.height); };
  8709. {
  8710. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  8711. playlist->setBounds (0, 0, size.width, size.height);
  8712. playlist->setVisible (true);
  8713. {
  8714. juce::Image warm (juce::Image::RGB, 64, 64, true); // (one paint asks for the waveforms, then they are waited for)
  8715. juce::Graphics g (warm);
  8716. playlist->paintEntireComponent (g, true);
  8717. }
  8718. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  8719. text << lynx::ui::picturecheck::run (*playlist, label ("Playlist"), size.scales, failures, folder);
  8720. }
  8721. {
  8722. auto mixer = std::make_unique<lynx::MixerComponent> (*engine);
  8723. mixer->setBounds (0, 0, size.width, juce::jmin (size.height, 700));
  8724. mixer->setVisible (true);
  8725. text << lynx::ui::picturecheck::run (*mixer, label ("Mixer"), size.scales, failures, folder);
  8726. }
  8727. }
  8728. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  8729. report.replaceWithText (text);
  8730. setApplicationReturnValue (failures == 0 ? 0 : 1);
  8731. quit();
  8732. }
  8733. // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
  8734. // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
  8735. // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
  8736. // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
  8737. // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
  8738. // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
  8739. void runUiPerf (const juce::File& project, const juce::File& report)
  8740. {
  8741. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  8742. lynx::crashguard::startMainProfiler (profile.toStdString()); // (stopped in shutdown)
  8743. startupOptions = lynx::StartupOptions::load();
  8744. engine = std::make_unique<lynx::AudioEngine>();
  8745. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  8746. crashEngine = engine.get();
  8747. createMainWindow();
  8748. mainWindow->reveal();
  8749. // LYNX_UIPERF_SIZE=WxH, LYNX_UIPERF_SCALE=<percent> (round 179a): a large window, a HiDPI desktop's scale
  8750. if (const auto scale = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SCALE", {}).getIntValue(); scale > 0)
  8751. juce::Desktop::getInstance().setGlobalScaleFactor ((float) scale / 100.0f);
  8752. if (const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SIZE", {}), "x", ""); size.size() == 2)
  8753. mainWindow->setBounds (0, 0, size[0].getIntValue(), size[1].getIntValue());
  8754. juce::String error;
  8755. auto ok = false;
  8756. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  8757. if (project.hasFileExtension ("flp"))
  8758. ok = engine->importFlpFile (project, error);
  8759. else if (auto song = lynx::ProjectFile::load (project, error))
  8760. {
  8761. engine->setSong (std::move (*song));
  8762. ok = true;
  8763. }
  8764. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  8765. if (! ok)
  8766. {
  8767. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  8768. setApplicationReturnValue (1);
  8769. quit();
  8770. return;
  8771. }
  8772. // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
  8773. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
  8774. engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
  8775. struct Step
  8776. {
  8777. juce::String name;
  8778. std::function<void()> setup;
  8779. std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
  8780. int frames;
  8781. std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
  8782. };
  8783. struct UiPerf final : juce::Timer
  8784. {
  8785. LynxApplication& app;
  8786. juce::File report;
  8787. juce::String text;
  8788. std::vector<Step> steps;
  8789. std::size_t step = 0;
  8790. int frame = -1;
  8791. std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
  8792. std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
  8793. double setupMs = 0.0, wallStart = 0.0;
  8794. double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
  8795. double messageCpuStart = 0.0; // the message thread's CPU seconds
  8796. double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
  8797. int audioLoadTicks = 0;
  8798. UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r)) {}
  8799. juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
  8800. double paintNow() const
  8801. {
  8802. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  8803. if (auto* p = peer())
  8804. p->performAnyPendingRepaintsNow();
  8805. return juce::Time::getMillisecondCounterHiRes() - t0;
  8806. }
  8807. void timerCallback() override
  8808. {
  8809. if (step >= steps.size())
  8810. {
  8811. stopTimer();
  8812. finish();
  8813. return;
  8814. }
  8815. auto& s = steps[step];
  8816. if (frame < 0)
  8817. {
  8818. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  8819. if (s.setup)
  8820. s.setup();
  8821. paintNow();
  8822. setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
  8823. times.clear();
  8824. rendered.clear();
  8825. frames.clear();
  8826. wallStart = juce::Time::getMillisecondCounterHiRes();
  8827. cpuStart = lynx::processCpuSeconds();
  8828. messageCpuStart = lynx::threadCpuSeconds();
  8829. audioLoadSum = 0.0;
  8830. audioLoadTicks = 0;
  8831. frame = 0;
  8832. return;
  8833. }
  8834. audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
  8835. ++audioLoadTicks;
  8836. if (s.action)
  8837. s.action (frame);
  8838. if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
  8839. times.push_back (ms);
  8840. ++frame;
  8841. if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
  8842. return;
  8843. const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
  8844. const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
  8845. const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
  8846. text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
  8847. << " painted frames: " << stats (rendered) << "\n"
  8848. << " timed here (event + paint + blit): " << stats (times)
  8849. << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
  8850. << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
  8851. << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
  8852. << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
  8853. if (s.finish)
  8854. text << s.finish();
  8855. juce::File (report).replaceWithText (text);
  8856. ++step;
  8857. frame = -1;
  8858. }
  8859. static juce::String stats (std::vector<double> sorted)
  8860. {
  8861. std::sort (sorted.begin(), sorted.end());
  8862. 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()))]; };
  8863. double sum = 0.0;
  8864. int over = 0;
  8865. for (auto t : sorted)
  8866. {
  8867. sum += t;
  8868. over += t > 16.0 ? 1 : 0;
  8869. }
  8870. return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
  8871. + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
  8872. + " ms, >16 ms " + juce::String (over);
  8873. }
  8874. void finish()
  8875. {
  8876. // the cost of asking where the mouse is (X11: a round trip to the display server)
  8877. const auto q0 = juce::Time::getMillisecondCounterHiRes();
  8878. for (int i = 0; i < 100; ++i)
  8879. juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
  8880. text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
  8881. app.mainWindow->onFrame = nullptr;
  8882. app.mainWindow->watchFrames ({});
  8883. app.engine->stop();
  8884. text << "result=OK\n";
  8885. report.replaceWithText (text);
  8886. app.setApplicationReturnValue (0);
  8887. app.quit();
  8888. }
  8889. };
  8890. auto* ui = &mainWindow->getContent();
  8891. auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
  8892. auto* peer = mainWindow->getPeer();
  8893. if (peer == nullptr || ! target.isShowing())
  8894. return;
  8895. juce::ModifierKeys::currentModifiers = mods;
  8896. const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
  8897. juce::MouseWheelDetails wheel { dx, dy, false, false, false };
  8898. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  8899. juce::ModifierKeys::currentModifiers = {};
  8900. };
  8901. auto run = std::make_unique<UiPerf> (*this, report);
  8902. mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
  8903. // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
  8904. auto drag = std::make_shared<UiPerfDrag>();
  8905. mainWindow->watchFrames ([r = run.get(), drag] (double now, juce::Rectangle<int> area) {
  8906. if (r->frame >= 0)
  8907. r->frames.push_back (now);
  8908. drag->framePainted (now, area);
  8909. });
  8910. run->text << "project: " << project.getFullPathName() << "\n"
  8911. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  8912. << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
  8913. << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  8914. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
  8915. << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
  8916. << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
  8917. const auto none = juce::ModifierKeys();
  8918. // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
  8919. // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
  8920. // window's own mouse path, the frames painted as the window paints them)
  8921. const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
  8922. run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
  8923. ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  8924. engine->getTransport().songMode = false;
  8925. engine->rewind();
  8926. engine->play();
  8927. }, {}, 4000 });
  8928. run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
  8929. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  8930. const auto rail = strips.faderRailForSnapshot (dragTrack);
  8931. drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
  8932. }, {}, 3000, [drag] { return drag->stop(); } });
  8933. run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
  8934. run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
  8935. run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
  8936. run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
  8937. // round 177a: only the meters move, so the strips' picture must stay valid, also with a folded group's tab and VCA
  8938. // strips on screen (their levels are drawn over the picture, like the inserts' meters)
  8939. run->steps.push_back ({ "mixer meters over the picture, playing", [this, ui] {
  8940. ui->selectTabForSnapshot (3);
  8941. engine->getTransport().songMode = false;
  8942. engine->rewind();
  8943. engine->play();
  8944. ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  8945. }, {}, 6000, [this, ui, report] {
  8946. const auto [spoiled, refills] = ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  8947. if (juce::FileOutputStream out (report.withFileExtension ("png")); out.openedOk())
  8948. {
  8949. out.setPosition (0);
  8950. out.truncate();
  8951. juce::PNGImageFormat().writeImageToStream (mainWindow->createComponentSnapshot (mainWindow->getLocalBounds()), out);
  8952. }
  8953. return juce::String (" mixer picture: spoiled ") + juce::String (spoiled) + " times, drawn again " + juce::String (refills) + " times\n";
  8954. } });
  8955. run->steps.push_back ({ "mixer scroll", {}, [wheelAt, ui, none] (int f) { wheelAt (ui->getMixerForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  8956. // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
  8957. // through the old path (a whole snapshot per move) and through editLevels
  8958. auto faderMove = [this] (bool levels, int f) {
  8959. for (int k = 0; k < 4; ++k)
  8960. {
  8961. const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
  8962. const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
  8963. if (levels)
  8964. engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
  8965. else
  8966. engine->editSong (edit, false);
  8967. }
  8968. };
  8969. run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
  8970. run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
  8971. // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
  8972. // loading while it stays open, pointing at the tiles, then closing it
  8973. run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
  8974. run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
  8975. // (round 175b: the picker is its own window)
  8976. if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
  8977. {
  8978. const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
  8979. 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
  8980. const auto local = picker->getPeer()->globalToLocal (p.toFloat());
  8981. picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
  8982. juce::Time::currentTimeMillis());
  8983. }
  8984. }, 60 });
  8985. run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
  8986. run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
  8987. run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
  8988. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  8989. run->steps.push_back ({ "playlist scroll sideways", {},
  8990. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  8991. // round 174f: Ctrl+wheel zoom, a notch every third frame (~20 a second), three in then three out, as dupmon drives it
  8992. run->steps.push_back ({ "playlist zoom (Ctrl+wheel)", {},
  8993. [wheelAt, ui] (int f) {
  8994. if (f % 3 == 0)
  8995. wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, juce::ModifierKeys (juce::ModifierKeys::ctrlModifier));
  8996. }, 120 });
  8997. run->steps.push_back ({ "playlist after the zoom (settles)", {}, {}, 500 });
  8998. run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
  8999. run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
  9000. [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  9001. // LYNX_UIPERF_ONLY=text: only the steps whose name has that text
  9002. if (const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_ONLY", {}); only.isNotEmpty())
  9003. 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());
  9004. // let the window draw the project first
  9005. perf = std::move (run);
  9006. juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
  9007. }
  9008. // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
  9009. // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
  9010. // --rtstress --backuptest N (round 177d): while the project plays, a device's MIDI clock (10/s) and active sensing
  9011. // (3/s) arrive, and the project counts as changed. N > 0 also forces a backup every N seconds on top of the timed ones.
  9012. // The report tells how many backups were written, when, and what the MIDI counters did.
  9013. struct BackupTest final : juce::Timer
  9014. {
  9015. lynx::AudioEngine* engine = nullptr;
  9016. lynx::MainComponent* ui = nullptr;
  9017. double everyMs = 0.0, startMs = 0.0, lastForcedMs = 0.0, longestCallMs = 0.0;
  9018. int ticks = 0, forced = 0;
  9019. std::uint64_t seenOver = 0, seenNear = 0;
  9020. juce::String misses; // each callback over (or near) its deadline: how long after the last forced backup
  9021. void timerCallback() override
  9022. {
  9023. engine->injectMidiInput (juce::MidiMessage (0xf8));
  9024. if (++ticks % 3 == 0)
  9025. engine->injectMidiInput (juce::MidiMessage (0xfe));
  9026. const auto now = juce::Time::getMillisecondCounterHiRes();
  9027. const auto s = engine->getRtStats().snapshot();
  9028. if (s.overBudget != seenOver || s.nearBudget != seenNear)
  9029. {
  9030. misses << " +" << juce::String ((now - lastForcedMs) / 1000.0, 1) << " s after the last forced backup (or the start): over +"
  9031. << (juce::int64) (s.overBudget - seenOver) << ", near +" << (juce::int64) (s.nearBudget - seenNear) << "\n";
  9032. seenOver = s.overBudget;
  9033. seenNear = s.nearBudget;
  9034. }
  9035. if (everyMs > 0.0 && now - lastForcedMs >= everyMs)
  9036. {
  9037. lastForcedMs = now;
  9038. ++forced;
  9039. ui->backupNowForTest();
  9040. longestCallMs = juce::jmax (longestCallMs, juce::Time::getMillisecondCounterHiRes() - now);
  9041. }
  9042. }
  9043. };
  9044. std::unique_ptr<BackupTest> backupTest;
  9045. void startBackupTest()
  9046. {
  9047. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  9048. const auto at = cli.indexOf ("--backuptest");
  9049. auto* ui = mainWindow != nullptr ? dynamic_cast<lynx::MainComponent*> (mainWindow->getContentComponent()) : nullptr;
  9050. if (at < 0 || ui == nullptr)
  9051. return;
  9052. backupTest = std::make_unique<BackupTest>();
  9053. backupTest->engine = engine.get();
  9054. backupTest->ui = ui;
  9055. backupTest->everyMs = cli[at + 1].getDoubleValue() * 1000.0;
  9056. backupTest->startMs = backupTest->lastForcedMs = juce::Time::getMillisecondCounterHiRes();
  9057. // (the project counts as changed, so a backup has something to write; the Master's fader is down, so a long run
  9058. // makes no sound: everything else is processed as usual)
  9059. engine->editSong ([] (lynx::Song& s) {
  9060. if (! s.mixer.empty())
  9061. s.mixer[0].volume = 0.0f;
  9062. });
  9063. backupTest->startTimer (100);
  9064. }
  9065. juce::String finishBackupTest()
  9066. {
  9067. if (backupTest == nullptr)
  9068. return {};
  9069. backupTest->stopTimer();
  9070. juce::String text;
  9071. const auto played = engine->getMidiPlayed();
  9072. text << " backup test: MIDI light count " << (int) engine->getMidiActivity() << ", played count " << (int) played << " (clock and active sensing only)\n";
  9073. text << " backup test: " << backupTest->forced << " forced, longest forced call on the message thread "
  9074. << juce::String (backupTest->longestCallMs, 1) << " ms\n";
  9075. if (backupTest->misses.isNotEmpty())
  9076. text << " backup test: callbacks over or near the deadline (seen within 100 ms):\n" << backupTest->misses;
  9077. auto files = lynx::autosaveFolder().findChildFiles (juce::File::findFiles, false, "*.lynx");
  9078. text << " backup test: " << files.size() << " file(s) in the backup folder:\n";
  9079. for (const auto& f : files)
  9080. text << " " << juce::String ((f.getLastModificationTime().toMilliseconds() - juce::Time::getCurrentTime().toMilliseconds()) / 1000) << " s before the end: "
  9081. << f.getFileName() << " (" << f.getSize() << " bytes)\n";
  9082. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 1));
  9083. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  9084. text << " backup test: after a played note, played count " << (int) engine->getMidiPlayed() << "\n";
  9085. backupTest.reset();
  9086. return text;
  9087. }
  9088. void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
  9089. const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
  9090. {
  9091. startupOptions = lynx::StartupOptions::load();
  9092. engine = std::make_unique<lynx::AudioEngine>();
  9093. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  9094. crashEngine = engine.get();
  9095. // the user's saved device stays as it was: this run's choices are undone before quitting
  9096. savedDeviceState = engine->getDeviceManager().createStateXml();
  9097. auto& devices = engine->getDeviceManager();
  9098. const auto driverFile = addDriverFileDeviceType();
  9099. const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
  9100. if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
  9101. devices.setCurrentAudioDeviceType (type, true);
  9102. if (bufferSize > 0 || deviceName.isNotEmpty())
  9103. {
  9104. auto setup = devices.getAudioDeviceSetup();
  9105. if (bufferSize > 0)
  9106. setup.bufferSize = bufferSize;
  9107. if (deviceName.isNotEmpty())
  9108. setup.outputDeviceName = deviceName;
  9109. const auto error = devices.setAudioDeviceSetup (setup, true);
  9110. if (error.isNotEmpty())
  9111. report.replaceWithText ("device error: " + error + "\n");
  9112. }
  9113. createMainWindow();
  9114. if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
  9115. mainWindow->reveal();
  9116. juce::String error;
  9117. auto ok = false;
  9118. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  9119. if (project.hasFileExtension ("flp"))
  9120. ok = engine->importFlpFile (project, error);
  9121. else if (auto song = lynx::ProjectFile::load (project, error))
  9122. {
  9123. engine->setSong (std::move (*song));
  9124. ok = true;
  9125. }
  9126. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  9127. if (! ok)
  9128. {
  9129. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  9130. restoreSavedDeviceState();
  9131. setApplicationReturnValue (1);
  9132. quit();
  9133. return;
  9134. }
  9135. if (recordTo.isNotEmpty())
  9136. engine->setAudioRecordingArmed (true); // opens the input of the driver
  9137. // let the window draw the project, then play from the start with fresh statistics
  9138. juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
  9139. if (engine == nullptr)
  9140. return;
  9141. engine->stop();
  9142. engine->rewind();
  9143. engine->getRtStats().reset();
  9144. engine->takeUiPulse();
  9145. if (recordTo.isNotEmpty())
  9146. engine->setRecording (true);
  9147. // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
  9148. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  9149. if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
  9150. engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
  9151. ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
  9152. engine->play();
  9153. startBackupTest();
  9154. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
  9155. if (engine == nullptr)
  9156. return;
  9157. const auto backupReport = finishBackupTest();
  9158. engine->stop();
  9159. juce::String recording;
  9160. if (engine->getAudioLogger().isLogging())
  9161. {
  9162. recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
  9163. engine->getAudioLogger().stop();
  9164. }
  9165. if (recordTo.isNotEmpty())
  9166. recording = finishStressTake (juce::File (recordTo), seconds);
  9167. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  9168. const auto s = engine->getRtStats().snapshot();
  9169. juce::String text;
  9170. text << "project: " << project.getFullPathName() << "\n"
  9171. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  9172. << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
  9173. << juce::SystemStats::getCpuModel() << "\n"
  9174. << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
  9175. << engine->describeRealtime();
  9176. const auto pulse = engine->takeUiPulse();
  9177. text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
  9178. << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
  9179. text << " load histogram (share of the deadline: callbacks):";
  9180. for (std::size_t b = 0; b < s.histogram.size(); ++b)
  9181. if (s.histogram[b] > 0)
  9182. text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
  9183. text << "\n";
  9184. text << recording << backupReport;
  9185. // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
  9186. if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
  9187. {
  9188. auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
  9189. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  9190. {
  9191. juce::Graphics g (image);
  9192. g.fillAll (lynx::theme::panel);
  9193. page->paintEntireComponent (g, false);
  9194. }
  9195. const juce::File shot (cli[at + 1].unquoted());
  9196. shot.deleteFile();
  9197. if (auto out = shot.createOutputStream())
  9198. juce::PNGImageFormat().writeImageToStream (image, *out);
  9199. }
  9200. text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
  9201. report.replaceWithText (text);
  9202. restoreSavedDeviceState();
  9203. setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
  9204. quit();
  9205. });
  9206. });
  9207. }
  9208. // --bendrectest (round 167a): see the command line above
  9209. void runBendRecordTest (const juce::File& report, bool songMode)
  9210. {
  9211. engine = std::make_unique<lynx::AudioEngine>();
  9212. auto text = std::make_shared<juce::String>();
  9213. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  9214. auto finish = [this] (int code) {
  9215. setApplicationReturnValue (code);
  9216. quit();
  9217. };
  9218. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  9219. if (device == nullptr)
  9220. {
  9221. step ("result=ERROR no audio device");
  9222. finish (1);
  9223. return;
  9224. }
  9225. step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
  9226. auto song = lynx::Song::makeDefault();
  9227. song.bpm = 120.0;
  9228. song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
  9229. engine->setSong (std::move (song));
  9230. auto o = engine->getRecordOptions();
  9231. o.mode = lynx::RecordMode::overdub;
  9232. o.recordNotes = true;
  9233. o.recordAutomation = true;
  9234. o.countInBars = 0;
  9235. o.waitForInput = false;
  9236. o.quantiseAutomation = false;
  9237. o.punchLoopRegion = false;
  9238. o.preRollBars = o.postRollBars = 0;
  9239. engine->setRecordOptions (o);
  9240. engine->stop();
  9241. engine->rewind();
  9242. engine->setRecording (true);
  9243. engine->startPlayback();
  9244. // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
  9245. auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
  9246. auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
  9247. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
  9248. auto tick = std::make_shared<std::function<void()>>();
  9249. *tick = [this, sent, t0, tick, step, finish, songMode] {
  9250. if (engine == nullptr)
  9251. return;
  9252. const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
  9253. if (ms < 2000.0)
  9254. {
  9255. const auto x = ms / 1000.0;
  9256. 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);
  9257. const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
  9258. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
  9259. sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
  9260. juce::Timer::callAfterDelay (10, *tick);
  9261. return;
  9262. }
  9263. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
  9264. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  9265. juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
  9266. if (engine == nullptr)
  9267. return;
  9268. engine->stop();
  9269. juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
  9270. if (engine == nullptr)
  9271. return;
  9272. engine->setRecording (false);
  9273. const auto& s = engine->getSong();
  9274. // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
  9275. std::vector<std::pair<std::int64_t, float>> got;
  9276. juce::String where = "nothing";
  9277. for (const auto& a : s.automations)
  9278. if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
  9279. {
  9280. where = "automation clip \"" + juce::String (a.name) + "\"";
  9281. for (const auto& pt : a.points)
  9282. got.push_back ({ pt.tick, pt.value });
  9283. }
  9284. for (const auto& p : s.patterns)
  9285. for (const auto& lane : p.events)
  9286. if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
  9287. {
  9288. where = "pattern \"" + juce::String (p.name) + "\" event lane";
  9289. for (const auto& e : lane.events)
  9290. got.push_back ({ e.tick, e.value });
  9291. }
  9292. int notes = 0;
  9293. for (const auto& p : s.patterns)
  9294. notes += (int) p.notes.size();
  9295. float lo = 1.0f, hi = 0.0f;
  9296. for (const auto& [t, v] : got)
  9297. lo = std::min (lo, v), hi = std::max (hi, v);
  9298. // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
  9299. const auto span = got.empty() ? 0 : got.back().first - got.front().first;
  9300. const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
  9301. step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
  9302. step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
  9303. + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
  9304. + ", notes " + juce::String (notes));
  9305. if (! got.empty())
  9306. step ("last=" + juce::String (got.back().second, 3));
  9307. // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
  9308. // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
  9309. const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
  9310. const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
  9311. && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
  9312. : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
  9313. step (ok ? "result=OK" : "result=FAILED");
  9314. finish (ok ? 0 : 1);
  9315. });
  9316. });
  9317. };
  9318. juce::Timer::callAfterDelay (300, *tick);
  9319. }
  9320. // --countinrectest (round 170d): see the command line above.
  9321. void runCountInRecordTest (const juce::File& report)
  9322. {
  9323. engine = std::make_unique<lynx::AudioEngine>();
  9324. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  9325. struct StandIn final : juce::AudioIODevice
  9326. {
  9327. StandIn() : juce::AudioIODevice ("countin", "test") {}
  9328. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  9329. juce::StringArray getInputChannelNames() override { return {}; }
  9330. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  9331. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  9332. int getDefaultBufferSize() override { return 512; }
  9333. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  9334. void close() override {}
  9335. bool isOpen() override { return true; }
  9336. void start (juce::AudioIODeviceCallback*) override {}
  9337. void stop() override {}
  9338. bool isPlaying() override { return true; }
  9339. juce::String getLastError() override { return {}; }
  9340. int getCurrentBufferSizeSamples() override { return 512; }
  9341. double getCurrentSampleRate() override { return 48000.0; }
  9342. int getCurrentBitDepth() override { return 32; }
  9343. juce::BigInteger getActiveOutputChannels() const override
  9344. {
  9345. juce::BigInteger b;
  9346. b.setRange (0, 2, true);
  9347. return b;
  9348. }
  9349. juce::BigInteger getActiveInputChannels() const override { return {}; }
  9350. int getOutputLatencyInSamples() override { return 256; }
  9351. int getInputLatencyInSamples() override { return 0; }
  9352. };
  9353. auto device = std::make_shared<StandIn>();
  9354. auto text = std::make_shared<juce::String>();
  9355. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  9356. auto finish = [this] (int code) {
  9357. setApplicationReturnValue (code);
  9358. quit();
  9359. };
  9360. constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
  9361. lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
  9362. song.bpm = 120.0;
  9363. song.mixer = lynx::Song::defaultMixer (2);
  9364. song.channels.resize (1);
  9365. song.channels[0].mixerTrack = 1;
  9366. song.patterns.emplace_back();
  9367. song.mode = lynx::PlayMode::song;
  9368. song.currentPattern = 0;
  9369. engine->setSong (song);
  9370. engine->getTransport().metronome.store (true);
  9371. auto o = engine->getRecordOptions();
  9372. o.mode = lynx::RecordMode::overdub;
  9373. o.countInBars = 1;
  9374. o.catchWindow = lynx::ppq / 4;
  9375. o.compensateOutput = true;
  9376. o.recordNotes = true;
  9377. o.recordAudio = false;
  9378. o.recordAutomation = false;
  9379. o.waitForInput = false;
  9380. o.quantise = 0;
  9381. o.placeSongClip = true;
  9382. o.recordingMarkers = false;
  9383. o.punchLoopRegion = false;
  9384. o.preRollBars = o.postRollBars = 0;
  9385. engine->setRecordOptions (o);
  9386. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  9387. 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");
  9388. // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
  9389. struct Event
  9390. {
  9391. std::int64_t heard;
  9392. juce::MidiMessage message;
  9393. };
  9394. struct Pass
  9395. {
  9396. std::vector<float> out;
  9397. std::vector<Event> events;
  9398. std::int64_t playingAt = -1; // the first sample of the block the song started in
  9399. int block = 0, blocks = 0;
  9400. std::function<void()> done;
  9401. };
  9402. constexpr int n = 512;
  9403. constexpr double rate = 48000.0;
  9404. // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
  9405. // ticks (the take is committed there); then stopped and its results left to the timer
  9406. auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  9407. *runPass = [this] (std::shared_ptr<Pass> pass) {
  9408. auto& cb = engine->deviceCallback();
  9409. std::vector<float> l (n), r (n);
  9410. float* outs[] = { l.data(), r.data() };
  9411. juce::AudioIODeviceCallbackContext context;
  9412. if (pass->block == 0)
  9413. {
  9414. engine->stop();
  9415. engine->seek ((double) (2 * bar));
  9416. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
  9417. engine->setRecording (true);
  9418. engine->startPlayback(); // the count-in starts
  9419. }
  9420. for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
  9421. {
  9422. // the events heard in this block: stamped the way the engine's clock maps time to heard samples
  9423. const auto blockStart = (std::int64_t) pass->block * n;
  9424. const auto clock = engine->liveClock();
  9425. const auto compMs = 1000.0 * (n + 256) / rate;
  9426. for (auto& e : pass->events)
  9427. if (e.heard >= blockStart && e.heard < blockStart + n)
  9428. {
  9429. auto m = e.message;
  9430. m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
  9431. engine->injectMidiInput (m);
  9432. }
  9433. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
  9434. pass->out.insert (pass->out.end(), l.begin(), l.end());
  9435. if (pass->playingAt < 0 && engine->getTransport().playing.load())
  9436. pass->playingAt = blockStart;
  9437. }
  9438. };
  9439. // (the recursion through the message loop; written out so each step lets the engine's timer run)
  9440. auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  9441. *drive = [this, runPass, drive, device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
  9442. if (engine == nullptr)
  9443. return;
  9444. (*runPass) (pass);
  9445. if (pass->block < pass->blocks)
  9446. {
  9447. juce::Timer::callAfterDelay (40, [pass, drive] { (*drive) (pass); });
  9448. return;
  9449. }
  9450. engine->stop();
  9451. juce::Timer::callAfterDelay (300, [this, pass] {
  9452. if (engine == nullptr)
  9453. return;
  9454. engine->setRecording (false);
  9455. juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
  9456. });
  9457. };
  9458. auto onsets = [] (const std::vector<float>& out) {
  9459. std::vector<std::int64_t> at;
  9460. std::int64_t last = -100000;
  9461. for (std::size_t i = 0; i < out.size(); ++i)
  9462. if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
  9463. {
  9464. at.push_back ((std::int64_t) i);
  9465. last = (std::int64_t) i;
  9466. }
  9467. else if (std::abs (out[i]) > 0.02f)
  9468. last = (std::int64_t) i;
  9469. return at;
  9470. };
  9471. // the graph is (re)built on the message thread: start once it has settled
  9472. juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
  9473. if (engine == nullptr)
  9474. return;
  9475. auto first = std::make_shared<Pass>();
  9476. first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
  9477. first->done = [this, first, step, finish, drive, onsets] {
  9478. const auto clicks = onsets (first->out);
  9479. juce::String list;
  9480. for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
  9481. list << clicks[i] << " ";
  9482. step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
  9483. // the bar-3 downbeat: the click at the block the song started in
  9484. std::int64_t down = -1;
  9485. for (auto c : clicks)
  9486. if (std::abs (c - first->playingAt) < n)
  9487. down = c;
  9488. if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
  9489. {
  9490. step ("result=FAILED no downbeat click found (or notes recorded without input)");
  9491. finish (1);
  9492. return;
  9493. }
  9494. const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
  9495. auto second = std::make_shared<Pass>();
  9496. second->blocks = first->blocks;
  9497. auto add = [&second] (std::int64_t at, int key, bool on) {
  9498. second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
  9499. };
  9500. for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
  9501. {
  9502. add (ms (-15.0), key, true);
  9503. add (ms (500.0), key, false);
  9504. }
  9505. add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
  9506. add (ms (-1250.0), 62, false);
  9507. add (ms (503.0), 77, true); // 3 ms after beat 2
  9508. add (ms (603.0), 77, false);
  9509. for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
  9510. {
  9511. add (ms (b * 2000.0), 70 + b, true);
  9512. add (ms (b * 2000.0 + 250.0), 70 + b, false);
  9513. }
  9514. second->done = [this, step, finish] {
  9515. const auto& s = engine->getSong();
  9516. const auto& p = s.patterns[0];
  9517. const lynx::Clip* clip = nullptr;
  9518. for (const auto& c : s.playlist)
  9519. if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
  9520. clip = &c;
  9521. const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
  9522. step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
  9523. auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
  9524. // where each one was heard (song ticks): 0.5 ms = ~1 tick
  9525. const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
  9526. { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
  9527. { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
  9528. { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
  9529. for (const auto& [key, tick] : want)
  9530. {
  9531. const lynx::Note* found = nullptr;
  9532. for (const auto& note : p.notes)
  9533. if (note.key == key)
  9534. found = &note;
  9535. const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
  9536. const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
  9537. ok = ok && good;
  9538. step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
  9539. + (good ? " ok" : " WRONG"));
  9540. }
  9541. const auto* chord = [&p] () -> const lynx::Note* {
  9542. for (const auto& note : p.notes)
  9543. if (note.key == 60)
  9544. return &note;
  9545. return nullptr;
  9546. }();
  9547. if (chord != nullptr)
  9548. step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
  9549. step (ok ? "result=OK" : "result=FAILED");
  9550. finish (ok ? 0 : 1);
  9551. };
  9552. (*drive) (second);
  9553. };
  9554. (*drive) (first);
  9555. });
  9556. }
  9557. // --cliplooptest (round 167q): see the command line above.
  9558. // --slicexedittest (round 190aj): see the command line above
  9559. void runSlicexEditTest (const juce::File& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  9560. {
  9561. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9562. juce::StringArray lines;
  9563. {
  9564. lynx::AudioEngine offline (false);
  9565. lynx::MainComponent ui (offline, false);
  9566. ui.setSize (1280, 720);
  9567. ui.openFile (project);
  9568. offline.dispatchPendingMessages();
  9569. int channel = -1;
  9570. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  9571. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  9572. channel = c;
  9573. if (channel < 0)
  9574. lines.add ("no Slicex channel in " + project.getFullPathName());
  9575. else
  9576. {
  9577. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  9578. juce::Component frame;
  9579. frame.setSize (panel->getWidth(), panel->getHeight());
  9580. frame.setOpaque (true);
  9581. frame.addAndMakeVisible (*panel);
  9582. panel->setTopLeftPosition (0, 0);
  9583. offline.dispatchPendingMessages();
  9584. juce::StringArray commands;
  9585. script.readLines (commands);
  9586. for (const auto& raw : commands)
  9587. {
  9588. const auto command = raw.trim();
  9589. if (command.isEmpty() || command.startsWith ("#"))
  9590. {
  9591. lines.add (command);
  9592. continue;
  9593. }
  9594. if (command.startsWith ("shot "))
  9595. {
  9596. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  9597. {
  9598. juce::Graphics g (image);
  9599. g.fillAll (lynx::theme::panel);
  9600. frame.paintEntireComponent (g, false);
  9601. }
  9602. const juce::File file (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png");
  9603. file.deleteFile();
  9604. juce::PNGImageFormat png;
  9605. if (auto out = file.createOutputStream())
  9606. png.writeImageToStream (image, *out);
  9607. lines.add (command + " -> " + file.getFileName());
  9608. continue;
  9609. }
  9610. const auto result = lynx::slicexEditorTest (*panel, command);
  9611. offline.dispatchPendingMessages();
  9612. lines.add (command + " -> " + result);
  9613. }
  9614. }
  9615. }
  9616. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  9617. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  9618. quit();
  9619. }
  9620. // --slicexkeytest (round 190ac): see the command line above
  9621. void runSlicexKeyTest (const juce::File& report)
  9622. {
  9623. engine = std::make_unique<lynx::AudioEngine>();
  9624. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  9625. struct StandIn final : juce::AudioIODevice
  9626. {
  9627. StandIn() : juce::AudioIODevice ("slicexkey", "test") {}
  9628. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  9629. juce::StringArray getInputChannelNames() override { return {}; }
  9630. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  9631. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  9632. int getDefaultBufferSize() override { return 512; }
  9633. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  9634. void close() override {}
  9635. bool isOpen() override { return true; }
  9636. void start (juce::AudioIODeviceCallback*) override {}
  9637. void stop() override {}
  9638. bool isPlaying() override { return true; }
  9639. juce::String getLastError() override { return {}; }
  9640. int getCurrentBufferSizeSamples() override { return 512; }
  9641. double getCurrentSampleRate() override { return 48000.0; }
  9642. int getCurrentBitDepth() override { return 32; }
  9643. juce::BigInteger getActiveOutputChannels() const override
  9644. {
  9645. juce::BigInteger b;
  9646. b.setRange (0, 2, true);
  9647. return b;
  9648. }
  9649. juce::BigInteger getActiveInputChannels() const override { return {}; }
  9650. int getOutputLatencyInSamples() override { return 0; }
  9651. int getInputLatencyInSamples() override { return 0; }
  9652. };
  9653. auto device = std::make_shared<StandIn>();
  9654. auto text = std::make_shared<juce::String>();
  9655. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  9656. // 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
  9657. // × region number), so the region a key played can be read from the output
  9658. constexpr int rate = 48000, regionFrames = rate / 4;
  9659. const auto wavFile = report.getSiblingFile ("slicexkey-deck.wav");
  9660. {
  9661. juce::MemoryOutputStream w;
  9662. auto chunk = [&w] (const char* id, const juce::MemoryBlock& body) {
  9663. w.write (id, 4);
  9664. w.writeInt ((int) body.getSize());
  9665. w.write (body.getData(), body.getSize());
  9666. };
  9667. juce::MemoryOutputStream fmt, data, cue;
  9668. fmt.writeShort (1);
  9669. fmt.writeShort (1);
  9670. fmt.writeInt (rate);
  9671. fmt.writeInt (rate * 2);
  9672. fmt.writeShort (2);
  9673. fmt.writeShort (16);
  9674. for (int i = 0; i < 4 * regionFrames; ++i)
  9675. data.writeShort ((short) std::lround (12000.0 * std::sin (juce::MathConstants<double>::twoPi * 200.0 * (double) (i / regionFrames + 1) * (double) i / rate)));
  9676. cue.writeInt (4);
  9677. for (int k = 0; k < 4; ++k)
  9678. {
  9679. cue.writeInt (k + 1);
  9680. cue.writeInt (k * regionFrames);
  9681. cue.write ("data", 4);
  9682. cue.writeInt (0);
  9683. cue.writeInt (0);
  9684. cue.writeInt (k * regionFrames);
  9685. }
  9686. juce::MemoryOutputStream riff;
  9687. riff.write ("WAVE", 4);
  9688. w.reset();
  9689. chunk ("fmt ", fmt.getMemoryBlock());
  9690. chunk ("data", data.getMemoryBlock());
  9691. chunk ("cue ", cue.getMemoryBlock());
  9692. riff.write (w.getData(), w.getDataSize());
  9693. juce::MemoryOutputStream file;
  9694. file.write ("RIFF", 4);
  9695. file.writeInt ((int) riff.getDataSize());
  9696. file.write (riff.getData(), riff.getDataSize());
  9697. wavFile.replaceWithData (file.getData(), file.getDataSize());
  9698. }
  9699. lynx::Song song;
  9700. song.bpm = 120.0;
  9701. song.mixer = lynx::Song::defaultMixer (2);
  9702. song.channels.resize (1);
  9703. auto& channel = song.channels[0];
  9704. channel.instrument = lynx::InstrumentKind::slicex;
  9705. channel.mixerTrack = 1;
  9706. channel.samplePath = wavFile.getFullPathName().toStdString();
  9707. {
  9708. auto state = lynx::slicex::fresh();
  9709. lynx::slicex::setDeckFile (state, 0, channel.samplePath, 4);
  9710. lynx::slicex::setDeckBeats (state, 0, 0.0, 2.0);
  9711. channel.pluginState = lynx::slicex::write (state);
  9712. }
  9713. song.patterns.emplace_back();
  9714. engine->setSong (song);
  9715. auto& callback = engine->deviceCallback();
  9716. callback.audioDeviceAboutToStart (device.get());
  9717. 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");
  9718. juce::Timer::callAfterDelay (2000, [this, device, step] {
  9719. if (engine == nullptr)
  9720. return;
  9721. auto& cb = engine->deviceCallback();
  9722. auto pump = [&cb] (int blocks) {
  9723. std::vector<float> l (512), r (512), out;
  9724. float* outs[] = { l.data(), r.data() };
  9725. juce::AudioIODeviceCallbackContext context;
  9726. for (int k = 0; k < blocks; ++k)
  9727. {
  9728. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  9729. out.insert (out.end(), l.begin(), l.end());
  9730. }
  9731. return out;
  9732. };
  9733. auto rms = [] (const std::vector<float>& x, int from, int count) {
  9734. double sum = 0.0;
  9735. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  9736. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  9737. return std::sqrt (sum / juce::jmax (1, count));
  9738. };
  9739. // the tone's frequency from its rising zero crossings over a stretch
  9740. auto hertz = [] (const std::vector<float>& x, int from, int count) {
  9741. int crossings = 0, first = -1, last = -1;
  9742. for (int i = from + 1; i < from + count && i < (int) x.size(); ++i)
  9743. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  9744. {
  9745. first = first < 0 ? i : first;
  9746. last = i;
  9747. ++crossings;
  9748. }
  9749. return crossings > 1 ? 48000.0 * (double) (crossings - 1) / (double) (last - first) : 0.0;
  9750. };
  9751. bool ok = true;
  9752. auto check = [&ok, step] (bool good, const juce::String& what) {
  9753. ok = ok && good;
  9754. step ((good ? "ok " : "FAIL ") + what);
  9755. };
  9756. const auto idle = pump (20);
  9757. engine->getMeters().takePeak (1, 0);
  9758. check (rms (idle, 0, (int) idle.size()) < 1.0e-6, "idle: rms " + juce::String (rms (idle, 0, (int) idle.size()), 9));
  9759. // 4 regions map to keys 60…63 (FL's automatic map); the editor's click: velocity 100 / 128
  9760. engine->sendLiveNote (0, 60, 0.78125f, true);
  9761. const auto first = pump (16); // 8192 frames = 171 ms, inside region 1 (250 ms)
  9762. const auto meter = engine->getMeters().takePeak (1, 0);
  9763. 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");
  9764. check (std::abs (hertz (first, 1024, 6000) - 200.0) < 4.0, "key 60 plays region 1 (200 Hz)");
  9765. check (meter > 0.01f, "mixer track 1 meter peak " + juce::String (meter, 6));
  9766. engine->sendLiveNote (0, 60, 0.0f, false);
  9767. const auto tail = pump (60);
  9768. 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));
  9769. engine->sendLiveNote (0, 62, 0.78125f, true);
  9770. const auto third = pump (16);
  9771. check (rms (third, 1024, 6000) > 0.01 && std::abs (hertz (third, 1024, 6000) - 600.0) < 8.0,
  9772. "key 62 plays region 3 (600 Hz): rms " + juce::String (rms (third, 1024, 6000), 6) + ", " + juce::String (hertz (third, 1024, 6000), 1) + " Hz");
  9773. engine->sendLiveNote (0, 62, 0.0f, false);
  9774. engine->sendLiveNote (0, 72, 0.78125f, true); // a key without a region
  9775. const auto none = pump (60);
  9776. 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));
  9777. engine->sendLiveNote (0, 72, 0.0f, false);
  9778. step (ok ? "result=OK" : "result=FAILED");
  9779. setApplicationReturnValue (ok ? 0 : 1);
  9780. quit();
  9781. });
  9782. }
  9783. void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
  9784. {
  9785. engine = std::make_unique<lynx::AudioEngine>();
  9786. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  9787. struct StandIn final : juce::AudioIODevice
  9788. {
  9789. StandIn() : juce::AudioIODevice ("cliploop", "test") {}
  9790. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  9791. juce::StringArray getInputChannelNames() override { return {}; }
  9792. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  9793. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  9794. int getDefaultBufferSize() override { return 512; }
  9795. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  9796. void close() override {}
  9797. bool isOpen() override { return true; }
  9798. void start (juce::AudioIODeviceCallback*) override {}
  9799. void stop() override {}
  9800. bool isPlaying() override { return true; }
  9801. juce::String getLastError() override { return {}; }
  9802. int getCurrentBufferSizeSamples() override { return 512; }
  9803. double getCurrentSampleRate() override { return 48000.0; }
  9804. int getCurrentBitDepth() override { return 32; }
  9805. juce::BigInteger getActiveOutputChannels() const override
  9806. {
  9807. juce::BigInteger b;
  9808. b.setRange (0, 2, true);
  9809. return b;
  9810. }
  9811. juce::BigInteger getActiveInputChannels() const override { return {}; }
  9812. int getOutputLatencyInSamples() override { return 0; }
  9813. int getInputLatencyInSamples() override { return 0; }
  9814. };
  9815. auto device = std::make_shared<StandIn>();
  9816. auto text = std::make_shared<juce::String>();
  9817. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  9818. constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
  9819. const auto ppq = (double) lynx::ppq;
  9820. lynx::Song song;
  9821. song.bpm = 120.0;
  9822. song.mixer = lynx::Song::defaultMixer (2);
  9823. song.channels.resize (1); // the synth of a new channel: deterministic
  9824. song.channels[0].mixerTrack = 1;
  9825. auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
  9826. for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
  9827. {
  9828. lynx::Note n;
  9829. n.start = b * lynx::ppq;
  9830. n.length = lynx::ppq / 4;
  9831. n.key = key;
  9832. pattern.notes.push_back (n);
  9833. }
  9834. lynx::Clip clip;
  9835. clip.pattern = 0;
  9836. clip.length = 16 * lynx::ppq; // stretched to 4 bars
  9837. song.playlist.push_back (clip);
  9838. song.mode = lynx::PlayMode::song;
  9839. {
  9840. // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
  9841. auto gui = song;
  9842. gui.playlist[0].length = 4 * lynx::ppq;
  9843. juce::String error;
  9844. lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
  9845. }
  9846. engine->setSong (song);
  9847. auto& callback = engine->deviceCallback();
  9848. callback.audioDeviceAboutToStart (device.get());
  9849. step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
  9850. // the graph is (re)built on the message thread: the scenarios run once it has settled
  9851. juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
  9852. if (engine == nullptr)
  9853. return;
  9854. auto& cb = engine->deviceCallback();
  9855. // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
  9856. auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
  9857. engine->stop();
  9858. engine->seek (from);
  9859. std::vector<float> l (512), r (512), out;
  9860. float* outs[] = { l.data(), r.data() };
  9861. juce::AudioIODeviceCallbackContext context;
  9862. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
  9863. engine->play();
  9864. for (int k = 0; (int) out.size() < samples; ++k)
  9865. {
  9866. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  9867. out.insert (out.end(), l.begin(), l.end());
  9868. if (between)
  9869. between (k);
  9870. }
  9871. engine->stop();
  9872. for (int k = 0; k < 400; ++k) // the tails of the scenario die out
  9873. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  9874. out.resize ((std::size_t) samples);
  9875. return out;
  9876. };
  9877. auto rms = [] (const std::vector<float>& x, int from, int count) {
  9878. double sum = 0.0;
  9879. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  9880. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  9881. return std::sqrt (sum / juce::jmax (1, count));
  9882. };
  9883. auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
  9884. double m = 0.0;
  9885. for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
  9886. m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
  9887. return m;
  9888. };
  9889. auto num = [] (double v) { return juce::String (v, 6); };
  9890. bool ok = true;
  9891. auto check = [&ok, step] (bool good, const juce::String& what) {
  9892. ok = ok && good;
  9893. step ((good ? "ok " : "FAIL ") + what);
  9894. };
  9895. lynx::setStretchedClipsLoop (true);
  9896. const auto a = play (0.0, 4 * bar);
  9897. const auto bar1 = rms (a, 0, bar);
  9898. check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
  9899. for (int k = 1; k < 4; ++k)
  9900. {
  9901. const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
  9902. check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  9903. "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
  9904. }
  9905. {
  9906. const auto x = play (10 * ppq, bar + bar / 2);
  9907. const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
  9908. check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
  9909. "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));
  9910. }
  9911. {
  9912. // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
  9913. const auto jumpBlock = 7 * beat / 512 - 1;
  9914. const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
  9915. if (k == jumpBlock)
  9916. engine->seek (14 * ppq);
  9917. });
  9918. // (the best of 0-2 samples late: anything but 0 fails)
  9919. const auto at = (jumpBlock + 1) * 512;
  9920. int lag = 0;
  9921. auto d = 1.0e9;
  9922. for (int l = 0; l <= 2; ++l)
  9923. if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
  9924. d = dl, lag = l;
  9925. d = lag == 0 ? d : 1.0;
  9926. const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
  9927. check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
  9928. "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
  9929. + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
  9930. }
  9931. {
  9932. engine->editSong ([ppq] (lynx::Song& s) {
  9933. s.loopStart = (std::int64_t) (4 * ppq);
  9934. s.loopEnd = (std::int64_t) (12 * ppq);
  9935. }, false);
  9936. const auto x = play (0.0, 7 * bar);
  9937. double d = 0.0;
  9938. juce::String lags;
  9939. for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
  9940. {
  9941. auto best = 1.0e9;
  9942. int lag = 0;
  9943. for (int l = 0; l <= 2; ++l)
  9944. if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
  9945. best = dl, lag = l;
  9946. d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
  9947. lags << (k > 1 ? "," : "") << lag;
  9948. }
  9949. const auto r = rms (x, bar, 6 * bar);
  9950. check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  9951. "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)
  9952. + " (samples late, bars 2-7: " + lags + ")");
  9953. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  9954. }
  9955. {
  9956. // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
  9957. // wrap used to play one sample more)
  9958. engine->editSong ([ppq] (lynx::Song& s) {
  9959. s.loopStart = (std::int64_t) (4 * ppq);
  9960. s.loopEnd = (std::int64_t) (8 * ppq);
  9961. }, false);
  9962. const auto x = play (0.0, 101 * bar);
  9963. double d = 0.0;
  9964. int worst = 0;
  9965. for (int k = 1; k <= 100; ++k)
  9966. if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
  9967. d = dk, worst = k + 1;
  9968. check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
  9969. + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
  9970. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  9971. }
  9972. lynx::setStretchedClipsLoop (false);
  9973. {
  9974. const auto x = play (0.0, 4 * bar);
  9975. const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
  9976. 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));
  9977. }
  9978. lynx::setStretchedClipsLoop (true);
  9979. cb.audioDeviceStopped();
  9980. // the export: a WAV of the 4 bars, read back from the file
  9981. if (wavFile != juce::File())
  9982. {
  9983. for (const auto loops : { true, false })
  9984. {
  9985. lynx::setStretchedClipsLoop (loops);
  9986. const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
  9987. file.deleteFile();
  9988. {
  9989. juce::WavAudioFormat wav;
  9990. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
  9991. engine->stop();
  9992. engine->seek (0.0);
  9993. lynx::AudioEngine::RenderOptions o;
  9994. o.seconds = 8.0;
  9995. o.sampleRate = 48000.0;
  9996. o.output = writer.get();
  9997. engine->renderOffline (o);
  9998. }
  9999. juce::WavAudioFormat wav;
  10000. std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
  10001. std::vector<float> x;
  10002. if (reader != nullptr)
  10003. {
  10004. juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
  10005. reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
  10006. x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
  10007. }
  10008. const auto b1 = rms (x, 0, bar);
  10009. juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
  10010. bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
  10011. for (int k = 1; k < 4; ++k)
  10012. {
  10013. const auto rk = rms (x, k * bar, bar);
  10014. line << ", bar " << (k + 1) << " " << num (rk);
  10015. 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);
  10016. }
  10017. if (loops)
  10018. 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);
  10019. check (good, line);
  10020. }
  10021. lynx::setStretchedClipsLoop (true);
  10022. }
  10023. step (ok ? "result=OK" : "result=FAILED");
  10024. setApplicationReturnValue (ok ? 0 : 1);
  10025. quit();
  10026. });
  10027. }
  10028. // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
  10029. // process leaves what was done).
  10030. void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  10031. const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
  10032. {
  10033. engine = std::make_unique<lynx::AudioEngine>();
  10034. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  10035. savedDeviceState = engine->getDeviceManager().createStateXml();
  10036. auto text = std::make_shared<juce::String>();
  10037. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  10038. auto finish = [this, step] (int code) {
  10039. restoreSavedDeviceState();
  10040. setApplicationReturnValue (code);
  10041. quit();
  10042. };
  10043. auto& devices = engine->getDeviceManager();
  10044. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  10045. devices.setCurrentAudioDeviceType (deviceType, true);
  10046. {
  10047. auto setup = devices.getAudioDeviceSetup();
  10048. if (deviceName.isNotEmpty())
  10049. setup.outputDeviceName = deviceName;
  10050. if (bufferSize > 0)
  10051. setup.bufferSize = bufferSize;
  10052. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  10053. step ("device_error=" + error);
  10054. }
  10055. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  10056. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  10057. // takes go next to the report, not into the user's recordings folder
  10058. engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
  10059. auto* device = devices.getCurrentAudioDevice();
  10060. if (device == nullptr || engine->getInputChannelNames().empty())
  10061. {
  10062. step ("result=ERROR no device / no input");
  10063. finish (1);
  10064. return;
  10065. }
  10066. const auto rate = device->getCurrentSampleRate();
  10067. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
  10068. + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
  10069. // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
  10070. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  10071. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  10072. {
  10073. lynx::takes::WavTakeWriter w;
  10074. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  10075. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  10076. std::vector<float> block (4096);
  10077. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  10078. {
  10079. std::fill (block.begin(), block.end(), 0.0f);
  10080. for (int k = 0; k < (int) block.size(); ++k)
  10081. {
  10082. const auto f = at + k;
  10083. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  10084. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  10085. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  10086. if (rel >= 0 && rel < 5)
  10087. block[(std::size_t) k] = 0.5f * shape[rel];
  10088. }
  10089. const float* d[] { block.data() };
  10090. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  10091. }
  10092. w.close();
  10093. }
  10094. lynx::Song song = lynx::Song::makeDefault();
  10095. song.bpm = 120.0;
  10096. song.mode = lynx::PlayMode::song;
  10097. song.playlist.clear();
  10098. lynx::ChannelDef c;
  10099. c.name = "Clicks";
  10100. c.instrument = lynx::InstrumentKind::audioClip;
  10101. c.samplePath = clickFile.getFullPathName().toStdString();
  10102. c.mixerTrack = 0;
  10103. c.volume = 1.0f;
  10104. song.channels.push_back (c);
  10105. lynx::Clip clip;
  10106. clip.kind = lynx::ClipKind::audio;
  10107. clip.channel = (int) song.channels.size() - 1;
  10108. clip.track = 0;
  10109. clip.start = 0;
  10110. clip.length = (std::int64_t) beats * lynx::ppq;
  10111. song.playlist.push_back (clip);
  10112. if (mode == 1) // loop recording, bars 2-4
  10113. {
  10114. song.loopStart = 4 * lynx::ppq;
  10115. song.loopEnd = 16 * lynx::ppq;
  10116. }
  10117. else if (mode == 2) // punch in/out, bars 3-4
  10118. {
  10119. song.loopStart = 8 * lynx::ppq;
  10120. song.loopEnd = 16 * lynx::ppq;
  10121. }
  10122. if (song.mixer.size() > 1)
  10123. {
  10124. song.mixer[1].name = "Loop In";
  10125. song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
  10126. }
  10127. engine->setSong (std::move (song));
  10128. engine->setInsertInput (1, 0, false);
  10129. juce::ignoreUnused (pdcSamples);
  10130. // 1) the ping
  10131. if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
  10132. step ("ping_error=" + error);
  10133. juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
  10134. if (engine == nullptr)
  10135. return;
  10136. if (engine->isPinging())
  10137. engine->cancelLatencyPing();
  10138. const auto r = engine->finishLatencyPing();
  10139. step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
  10140. + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
  10141. const auto l = engine->currentLatency();
  10142. step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
  10143. // 2) record
  10144. engine->setInsertArmed (1, true);
  10145. auto o = engine->getRecordOptions();
  10146. o.recordAudio = true;
  10147. o.countInBars = 0;
  10148. o.waitForInput = false;
  10149. o.punchLoopRegion = mode == 2;
  10150. o.preRollBars = mode == 2 ? 1 : 0;
  10151. o.postRollBars = mode == 2 ? 1 : 0;
  10152. // (round 177c: LYNX_RECTEST_BLEND_OFF=1: Blend off; LYNX_RECTEST_LAST_PASS=1: "only the last pass plays")
  10153. o.mode = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_BLEND_OFF", {}) == "1" ? lynx::RecordMode::replace
  10154. : lynx::RecordMode::overdub;
  10155. o.lastLoopPassPlays = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_LAST_PASS", {}) == "1";
  10156. engine->setRecordOptions (o);
  10157. engine->stop();
  10158. engine->rewind();
  10159. engine->setRecording (true);
  10160. juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
  10161. if (engine == nullptr)
  10162. return;
  10163. engine->startPlayback(); // (as the Play button: pre-roll / punch)
  10164. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
  10165. if (engine == nullptr)
  10166. return;
  10167. if (mode == 2)
  10168. step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
  10169. engine->stop();
  10170. juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
  10171. if (engine == nullptr)
  10172. return;
  10173. engine->setRecording (false);
  10174. const auto& s = engine->getSong();
  10175. const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
  10176. int take = -1;
  10177. for (int ch = 0; ch < (int) s.channels.size(); ++ch)
  10178. if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
  10179. take = ch;
  10180. if (take < 0)
  10181. {
  10182. step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
  10183. finish (1);
  10184. return;
  10185. }
  10186. std::vector<std::vector<float>> audio;
  10187. double takeRate = 0.0;
  10188. const auto& path = s.channels[(std::size_t) take].samplePath;
  10189. lynx::takes::readWav (path, audio, &takeRate);
  10190. const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
  10191. step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
  10192. + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
  10193. // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
  10194. std::vector<juce::int64> peaks;
  10195. if (! audio.empty())
  10196. for (juce::int64 f = 1; f + 1 < frames; ++f)
  10197. {
  10198. const auto x = std::abs (audio[0][(std::size_t) f]);
  10199. if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
  10200. && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
  10201. peaks.push_back (f);
  10202. }
  10203. // every clip of the take: each click inside it against the nearest beat
  10204. int clips = 0, checked = 0, muted = 0;
  10205. double worst = 0.0, sum = 0.0;
  10206. for (const auto& c : s.playlist)
  10207. {
  10208. if (c.kind != lynx::ClipKind::audio || c.channel != take)
  10209. continue;
  10210. ++clips;
  10211. muted += c.muted ? 1 : 0;
  10212. const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
  10213. for (const auto f : peaks)
  10214. {
  10215. const auto intoClip = (double) f - skip;
  10216. if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
  10217. continue;
  10218. const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
  10219. const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
  10220. const auto error = (songTick - beat) / tps;
  10221. worst = std::max (worst, std::abs (error));
  10222. sum += error;
  10223. ++checked;
  10224. }
  10225. step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
  10226. + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
  10227. + (c.muted ? " (muted lane)" : ""));
  10228. }
  10229. step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
  10230. + " muted_lanes=" + juce::String (muted));
  10231. step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
  10232. auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
  10233. if (mode == 2) // one clip, exactly the punch range, its 8 beats
  10234. {
  10235. const auto& sp = engine->getSong();
  10236. bool exact = false;
  10237. for (const auto& c : sp.playlist)
  10238. if (c.kind == lynx::ClipKind::audio && c.channel == take)
  10239. exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
  10240. step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
  10241. ok = ok && clips == 1 && exact && checked == 8;
  10242. }
  10243. report.getSiblingFile (report.getFileNameWithoutExtension() + "-project.lynx").replaceWithText (lynx::ProjectFile::toJson (engine->getSong()));
  10244. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  10245. finish (ok ? 0 : 1);
  10246. });
  10247. });
  10248. });
  10249. });
  10250. }
  10251. // --hwinserttest (round 164d): see the command line above.
  10252. void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  10253. const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
  10254. {
  10255. engine = std::make_unique<lynx::AudioEngine>();
  10256. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  10257. savedDeviceState = engine->getDeviceManager().createStateXml();
  10258. auto text = std::make_shared<juce::String>();
  10259. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  10260. auto finish = [this] (int code) {
  10261. if (engine != nullptr)
  10262. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  10263. restoreSavedDeviceState();
  10264. setApplicationReturnValue (code);
  10265. quit();
  10266. };
  10267. auto& devices = engine->getDeviceManager();
  10268. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  10269. devices.setCurrentAudioDeviceType (deviceType, true);
  10270. {
  10271. auto setup = devices.getAudioDeviceSetup();
  10272. if (deviceName.isNotEmpty())
  10273. setup.outputDeviceName = deviceName;
  10274. if (bufferSize > 0)
  10275. setup.bufferSize = bufferSize;
  10276. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  10277. step ("device_error=" + error);
  10278. }
  10279. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  10280. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  10281. auto* device = devices.getCurrentAudioDevice();
  10282. if (device == nullptr || engine->getInputChannelNames().empty())
  10283. {
  10284. step ("result=ERROR no device / no input");
  10285. finish (1);
  10286. return;
  10287. }
  10288. const auto rate = device->getCurrentSampleRate();
  10289. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
  10290. // the click track: the ping's pulse on every beat at 120 bpm
  10291. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  10292. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  10293. {
  10294. lynx::takes::WavTakeWriter w;
  10295. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  10296. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  10297. std::vector<float> block (4096);
  10298. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  10299. {
  10300. std::fill (block.begin(), block.end(), 0.0f);
  10301. for (int k = 0; k < (int) block.size(); ++k)
  10302. {
  10303. const auto f = at + k;
  10304. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  10305. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  10306. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  10307. if (rel >= 0 && rel < 5)
  10308. block[(std::size_t) k] = 0.5f * shape[rel];
  10309. }
  10310. const float* d[] { block.data() };
  10311. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  10312. }
  10313. w.close();
  10314. }
  10315. lynx::Song song = lynx::Song::makeDefault();
  10316. song.bpm = 120.0;
  10317. song.mode = lynx::PlayMode::song;
  10318. song.playlist.clear();
  10319. song.channels.clear();
  10320. for (int k = 0; k < 2; ++k)
  10321. {
  10322. lynx::ChannelDef c;
  10323. c.name = k == 0 ? "Wet" : "Dry";
  10324. c.instrument = lynx::InstrumentKind::audioClip;
  10325. c.samplePath = clickFile.getFullPathName().toStdString();
  10326. c.mixerTrack = k + 1;
  10327. c.volume = 1.0f;
  10328. song.channels.push_back (c);
  10329. lynx::Clip clip;
  10330. clip.kind = lynx::ClipKind::audio;
  10331. clip.channel = k;
  10332. clip.track = k;
  10333. clip.start = 0;
  10334. clip.length = (std::int64_t) beats * lynx::ppq;
  10335. song.playlist.push_back (clip);
  10336. }
  10337. song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
  10338. for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
  10339. fx.enabled = false;
  10340. song.mixer[1].pan = -1.0f;
  10341. song.mixer[2].pan = 1.0f;
  10342. auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  10343. hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
  10344. hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
  10345. hw.params[lynx::hwinsert::inputStereo] = 1.0f;
  10346. song.mixer[1].effects.clear();
  10347. lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
  10348. if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
  10349. {
  10350. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  10351. lynx::PatchNode node;
  10352. node.effect = hw;
  10353. slot.patcher.nodes = { node };
  10354. lynx::PatchWire in, out;
  10355. in.from = lynx::patchFromHost;
  10356. in.to = 0;
  10357. out.from = 0;
  10358. out.to = lynx::patchToHost;
  10359. slot.patcher.wires = { in, out };
  10360. song.mixer[1].effects.push_back (slot);
  10361. ref.nodes = { 0 };
  10362. }
  10363. else
  10364. song.mixer[1].effects.push_back (hw);
  10365. engine->setSong (std::move (song));
  10366. step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
  10367. const auto meter = [this, ref] (int output) {
  10368. const auto fx = engine->runningHardwareInsert (ref);
  10369. return fx != nullptr ? fx->controlOutput (output) : 0.0f;
  10370. };
  10371. // 1) the insert's ping (as its Ping button: a momentary value flipped)
  10372. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  10373. if (engine == nullptr)
  10374. return;
  10375. engine->pingHardwareInserts ({ ref });
  10376. juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  10377. if (engine == nullptr)
  10378. return;
  10379. // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
  10380. // new round trip rebuilds the insert (its latency), so the result is read from the slot
  10381. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  10382. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  10383. const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
  10384. const auto state = meter (lynx::hwinsert::pingState);
  10385. const auto ok = samples > 0 && setup == engine->currentSetupKey();
  10386. step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
  10387. + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
  10388. if (! ok)
  10389. {
  10390. step ("result=FAILED ping");
  10391. finish (1);
  10392. return;
  10393. }
  10394. // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
  10395. step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
  10396. // 2) play, capturing the Master
  10397. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
  10398. if (engine == nullptr)
  10399. return;
  10400. step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
  10401. // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
  10402. // odd round trip (12345 samples: the project keeps it to the sample)
  10403. if (! inPatcher)
  10404. {
  10405. auto odd = engine->getSong();
  10406. odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
  10407. juce::String error;
  10408. auto same = true;
  10409. for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
  10410. {
  10411. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
  10412. const auto saved = lynx::ProjectFile::save (*song, file, error);
  10413. const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
  10414. same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  10415. && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
  10416. && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
  10417. && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
  10418. }
  10419. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
  10420. step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
  10421. if (! same)
  10422. {
  10423. step ("result=FAILED project");
  10424. finish (1);
  10425. return;
  10426. }
  10427. }
  10428. auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
  10429. engine->stop();
  10430. engine->rewind();
  10431. engine->getMeters().capture.setSource (0);
  10432. engine->play();
  10433. auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
  10434. auto pull = std::make_shared<std::function<void()>>();
  10435. *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
  10436. if (engine == nullptr)
  10437. return;
  10438. engine->getMeters().capture.pull (*left, *right);
  10439. if (*pulls == 10) // the insert's editor while it plays (next to the report)
  10440. for (const auto scale : { 1.0f, 1.5f })
  10441. {
  10442. auto editor = inPatcher ? lynx::makeNodeEffectEditor (
  10443. *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
  10444. [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
  10445. : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
  10446. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  10447. {
  10448. juce::Graphics g (image);
  10449. g.fillAll (lynx::theme::panel);
  10450. editor->paintEntireComponent (g, false);
  10451. }
  10452. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
  10453. file.deleteFile();
  10454. juce::PNGImageFormat png;
  10455. if (auto stream = file.createOutputStream())
  10456. png.writeImageToStream (image, *stream);
  10457. }
  10458. if (--*pulls > 0)
  10459. {
  10460. juce::Timer::callAfterDelay (200, *pull);
  10461. return;
  10462. }
  10463. engine->stop();
  10464. const auto dropped = engine->getMeters().capture.droppedFrames();
  10465. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  10466. // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
  10467. auto peaksOf = [rate] (const std::vector<float>& x) {
  10468. std::vector<juce::int64> peaks;
  10469. for (std::size_t f = 1; f + 1 < x.size(); ++f)
  10470. 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])
  10471. && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
  10472. peaks.push_back ((juce::int64) f);
  10473. return peaks;
  10474. };
  10475. const auto wet = peaksOf (*left), dry = peaksOf (*right);
  10476. int pairs = 0;
  10477. juce::int64 worst = 0;
  10478. double gainSum = 0.0, residual = 0.0, energy = 0.0;
  10479. for (const auto w : wet)
  10480. {
  10481. 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); });
  10482. if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
  10483. continue;
  10484. ++pairs;
  10485. worst = std::max (worst, std::abs (*best - w));
  10486. gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
  10487. }
  10488. const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
  10489. // dry clicks with no wet click beside them (a dropout of the cable / device), listed
  10490. juce::String unmatched;
  10491. for (const auto d : dry)
  10492. if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
  10493. unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
  10494. if (unmatched.isNotEmpty())
  10495. step ("dry_clicks_without_wet=" + unmatched);
  10496. // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
  10497. for (const auto w : wet)
  10498. for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
  10499. {
  10500. const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
  10501. residual += d * d;
  10502. energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
  10503. }
  10504. const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
  10505. step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
  10506. + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
  10507. step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
  10508. auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
  10509. const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
  10510. step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
  10511. const auto excused = xruns > 0 ? 2 * xruns : 0;
  10512. const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
  10513. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  10514. // (round 165c) then the re-ping notice after a buffer size change
  10515. auto then = [this, ref, step, finish] (int code) {
  10516. if (code != 0)
  10517. finish (code);
  10518. else
  10519. runRepingCheck (ref, step, finish);
  10520. };
  10521. if (! ok)
  10522. {
  10523. finish (1);
  10524. return;
  10525. }
  10526. if (bounceFile == juce::File())
  10527. then (0);
  10528. else
  10529. runBounceCheck (bounceFile, step, then);
  10530. };
  10531. juce::Timer::callAfterDelay (200, *pull);
  10532. });
  10533. });
  10534. });
  10535. }
  10536. // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
  10537. // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
  10538. // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
  10539. // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
  10540. // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
  10541. // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
  10542. void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  10543. {
  10544. auto& devices = engine->getDeviceManager();
  10545. auto setup = devices.getAudioDeviceSetup();
  10546. const auto before = setup.bufferSize;
  10547. setup.bufferSize = before == 512 ? 256 : 512;
  10548. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  10549. step ("reping_device_error=" + error);
  10550. engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
  10551. juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
  10552. if (engine == nullptr)
  10553. return;
  10554. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  10555. const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
  10556. const auto notice = engine->takeHardwareInsertNotice();
  10557. step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
  10558. + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
  10559. if (notice.size() != 1 || ! (notice[0] == ref))
  10560. {
  10561. step ("result_reping=FAILED (no notice)");
  10562. finish (1);
  10563. return;
  10564. }
  10565. engine->pingHardwareInserts (notice); // ("Ping now")
  10566. juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
  10567. if (engine == nullptr)
  10568. return;
  10569. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  10570. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  10571. const auto stale = (int) engine->staleHardwareInserts().size();
  10572. step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
  10573. const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
  10574. step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
  10575. finish (ok ? 0 : 1);
  10576. });
  10577. });
  10578. }
  10579. void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  10580. {
  10581. // the Export window as the user sees it with the real-time option ticked (next to the report)
  10582. lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
  10583. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  10584. if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
  10585. {
  10586. std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
  10587. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
  10588. return t;
  10589. for (auto* child : c.getChildren())
  10590. if (auto* t = find (*child))
  10591. return t;
  10592. return nullptr;
  10593. };
  10594. if (auto* toggle = find (*w))
  10595. {
  10596. step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
  10597. toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
  10598. auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
  10599. if (c != nullptr)
  10600. {
  10601. const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
  10602. file.deleteFile();
  10603. juce::FileOutputStream out (file);
  10604. juce::PNGImageFormat png;
  10605. if (out.openedOk())
  10606. png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  10607. }
  10608. delete w;
  10609. break;
  10610. }
  10611. }
  10612. lynx::exportopts::Options o;
  10613. o.format = lynx::exportopts::Format::wav;
  10614. o.wavBits = 32;
  10615. o.dither = lynx::exportopts::DitherMode::none;
  10616. o.tail = lynx::exportopts::TailMode::cut;
  10617. o.range = lynx::exportopts::Range::song;
  10618. o.trimPdc = true;
  10619. o.hqAllPlugins = false;
  10620. o.pluginWarmUp = false;
  10621. const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
  10622. auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
  10623. o.sampleRate = engine->getTransport().sampleRate.load();
  10624. auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
  10625. struct Shared
  10626. {
  10627. std::atomic<int> done { 0 };
  10628. bool okRealtime = false, okOffline = false;
  10629. juce::String errorRealtime, errorOffline;
  10630. double lastProgress = 0.0;
  10631. double started = juce::Time::getMillisecondCounterHiRes();
  10632. };
  10633. auto shared = std::make_shared<Shared>();
  10634. // (the jobs stay owned by the message thread's poll below: they are destroyed there)
  10635. juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
  10636. shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
  10637. shared->okOffline = off->run ({}, shared->errorOffline);
  10638. shared->done.store (1);
  10639. });
  10640. auto poll = std::make_shared<std::function<void()>>();
  10641. *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
  10642. if (shared->done.load() == 0)
  10643. {
  10644. juce::Timer::callAfterDelay (100, *poll);
  10645. return;
  10646. }
  10647. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
  10648. step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
  10649. + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
  10650. + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
  10651. juce::AudioFormatManager formats;
  10652. formats.registerBasicFormats();
  10653. std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
  10654. if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
  10655. {
  10656. step ("result=FAILED bounce");
  10657. finish (1);
  10658. return;
  10659. }
  10660. const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
  10661. juce::AudioBuffer<float> x (2, frames), y (2, frames);
  10662. a->read (&x, 0, frames, 0, true, true);
  10663. b->read (&y, 0, frames, 0, true, true);
  10664. double residual = 0.0, energy = 0.0, wetDry = 0.0;
  10665. for (int ch = 0; ch < 2; ++ch)
  10666. for (int i = 0; i < frames; ++i)
  10667. {
  10668. const double d = x.getSample (ch, i) - y.getSample (ch, i);
  10669. residual += d * d;
  10670. energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
  10671. }
  10672. for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
  10673. wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
  10674. const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
  10675. step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
  10676. + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
  10677. + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
  10678. const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
  10679. step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
  10680. finish (ok ? 0 : 1);
  10681. };
  10682. juce::Timer::callAfterDelay (100, *poll);
  10683. }
  10684. // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
  10685. // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
  10686. juce::String finishStressTake (const juce::File& target, double seconds)
  10687. {
  10688. juce::String text;
  10689. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  10690. text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
  10691. if (device != nullptr)
  10692. text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
  10693. engine->setRecording (false); // closes the take: a clip of the song
  10694. juce::File take;
  10695. for (const auto& c : engine->getSong().channels)
  10696. if (c.instrument == lynx::InstrumentKind::audioClip)
  10697. take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
  10698. if (! take.existsAsFile())
  10699. return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
  10700. target.deleteFile();
  10701. if (! take.moveFileTo (target))
  10702. take.copyFileTo (target);
  10703. juce::AudioFormatManager formats;
  10704. formats.registerBasicFormats();
  10705. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
  10706. {
  10707. juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
  10708. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
  10709. const auto peak = audio.getMagnitude (0, audio.getNumSamples());
  10710. const auto length = (double) reader->lengthInSamples / reader->sampleRate;
  10711. text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
  10712. << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
  10713. << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
  10714. }
  10715. else
  10716. text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
  10717. return text;
  10718. }
  10719. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  10720. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  10721. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  10722. {
  10723. lynx::AudioEngine offline (false);
  10724. const juce::File input (inputPath);
  10725. juce::String error, report;
  10726. bool ok = false;
  10727. if (input.hasFileExtension ("flp;als;flm;songtmpl"))
  10728. ok = offline.importFlpFile (input, error);
  10729. else if (auto song = lynx::ProjectFile::load (input, error))
  10730. {
  10731. offline.setSong (std::move (*song));
  10732. ok = true;
  10733. }
  10734. int samplers = 0, samplersLoaded = 0;
  10735. if (ok)
  10736. {
  10737. for (const auto& c : offline.getSong().channels)
  10738. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  10739. {
  10740. ++samplers;
  10741. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  10742. }
  10743. const juce::File output (outputPath);
  10744. output.deleteFile();
  10745. juce::WavAudioFormat wav;
  10746. std::unique_ptr<juce::AudioFormatWriter> writer (
  10747. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  10748. if (writer == nullptr)
  10749. {
  10750. ok = false;
  10751. error = lynx::utf8 ("could not create ") + outputPath;
  10752. }
  10753. else
  10754. {
  10755. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  10756. report << "peak=" << peak << "\n";
  10757. ok = peak > 0.001f;
  10758. }
  10759. }
  10760. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  10761. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  10762. juce::File (outputPath + ".txt").replaceWithText (report);
  10763. setApplicationReturnValue (ok ? 0 : 1);
  10764. quit();
  10765. }
  10766. // LYNX.exe --export-flp project.(lynx|flp|als) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
  10767. // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
  10768. // report goes to output.txt
  10769. void runAlsExport (const juce::String& inputPath, const juce::String& folderPath, bool live11, bool reference)
  10770. {
  10771. juce::String error;
  10772. juce::StringArray notes;
  10773. juce::File als;
  10774. {
  10775. lynx::AudioEngine loader (false);
  10776. const juce::File input (inputPath);
  10777. bool ok = false;
  10778. // --scan: the targeted plugin scan an open runs first (child processes), so the set's plugins load
  10779. if (juce::JUCEApplication::getCommandLineParameterArray().contains ("--scan") && input.hasFileExtension ("flp;als;flm;songtmpl"))
  10780. {
  10781. juce::MemoryBlock data;
  10782. if (input.loadFileAsData (data))
  10783. {
  10784. const std::vector<std::uint8_t> bytes (static_cast<const std::uint8_t*> (data.getData()),
  10785. static_cast<const std::uint8_t*> (data.getData()) + data.getSize());
  10786. try
  10787. {
  10788. const auto uses = input.hasFileExtension ("als") ? lynx::alsForeignPlugins (bytes)
  10789. : lynx::flpForeignPlugins (flp::parseProject ({ bytes.data(), bytes.size() }));
  10790. loader.getPluginHost().scanFiles (loader.getPluginHost().filesToScanFor (uses), {});
  10791. }
  10792. catch (const std::exception&)
  10793. {
  10794. }
  10795. }
  10796. }
  10797. if (input.hasFileExtension ("flp;als;flm;songtmpl"))
  10798. ok = loader.importFlpFile (input, error);
  10799. else if (auto song = lynx::ProjectFile::load (input, error))
  10800. {
  10801. loader.setSong (std::move (*song));
  10802. ok = true;
  10803. }
  10804. if (ok)
  10805. {
  10806. loader.capturePluginStates();
  10807. const juce::File folder (folderPath);
  10808. folder.createDirectory();
  10809. als = lynx::writeAlsProject (loader.getSong(), &loader.getPluginHost(), live11 ? lynx::AlsVersion::live11 : lynx::AlsVersion::live12, ! reference, folder,
  10810. input.getFileNameWithoutExtension(), notes, error);
  10811. }
  10812. }
  10813. juce::String report;
  10814. report << (als != juce::File() ? "ok " + als.getFullPathName() : "error=" + error) << "\n" << notes.joinIntoString ("\n") << "\n";
  10815. juce::File (folderPath).getChildFile ("export-als.txt").replaceWithText (report);
  10816. setApplicationReturnValue (als != juce::File() ? 0 : 1);
  10817. quit();
  10818. }
  10819. // --versionsshot <prefix> (round 190ap): everything the round adds, offscreen (no window on the desktop):
  10820. // -versions.png / -versions-unsaved.png the Versions panel (a project with versions, backups and labels; a new one)
  10821. // -menu-file.png / -menu-file-pluginsoff.png the File menu, and as it is while the plugins are off
  10822. // -pluginsoff-window.png / -pluginsoff-mixer.png a project opened without its third-party plugins (the tags)
  10823. // -pluginsoff-panel.png / -pluginsoff-panel-one.png the list, all off, then after "Switch on" for one
  10824. // -export-default.png / -export.png the Export window as it opens, and with the additions in use
  10825. bool runLinkShot (const juce::String& prefix)
  10826. {
  10827. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10828. juce::StringArray report;
  10829. bool allOk = true;
  10830. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  10831. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  10832. allOk = allOk && ok;
  10833. };
  10834. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  10835. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  10836. };
  10837. using lynx::AutomationTarget;
  10838. using lynx::AutomationTargetKind;
  10839. using lynx::MidiLink;
  10840. lynx::AudioEngine engine (false);
  10841. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 },
  10842. insert { AutomationTargetKind::mixerVolume, 1 };
  10843. // ---- the window as it opens on a control with no link (FL's defaults)
  10844. {
  10845. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  10846. shoot (*panel, "remote-default");
  10847. check ("default_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  10848. // Auto detect: the controller that sends next fills the fields
  10849. engine.injectControllerForTest (74, 2, 100, 5);
  10850. lynx::remoteControlPanelPoll (*panel);
  10851. check ("auto_detect", lynx::remoteControlPanelState (*panel).startsWith ("5|3|74|"), lynx::remoteControlPanelState (*panel));
  10852. // a formula preset, smoothing; Accept writes the link
  10853. lynx::remoteControlPanelSetController (*panel, -1, 1, 7);
  10854. lynx::remoteControlPanelSetFormula (*panel, "Tension(Input,10)");
  10855. lynx::remoteControlPanelSetSmoothing (*panel, true, 469);
  10856. shoot (*panel, "remote-formula-smoothing");
  10857. lynx::remoteControlPanelPress (*panel, 2);
  10858. const auto& links = engine.getSong().midiLinks;
  10859. check ("accept_writes_link", links.size() == 1 && links[0].cc == 7 && links[0].channel == 0 && links[0].port == -1
  10860. && links[0].formula == "Tension(Input,10)" && links[0].smooth && links[0].target == volume);
  10861. }
  10862. // ---- a broken formula: the message, the red text
  10863. {
  10864. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  10865. lynx::remoteControlPanelSetFormula (*panel, "Min(Input*2,");
  10866. shoot (*panel, "remote-formula-error");
  10867. check ("formula_error_shown", ! lynx::remoteControlPanelState (*panel).contains ("Compiled ok."), lynx::remoteControlPanelState (*panel));
  10868. }
  10869. // ---- the engine: formula, port, conflicts, omni
  10870. {
  10871. engine.editSong ([&] (lynx::Song& s) {
  10872. s.midiLinks.clear();
  10873. MidiLink inverted { 20, 0, volume };
  10874. inverted.formula = "1-Input";
  10875. MidiLink ported { 21, 0, pan };
  10876. ported.port = 3;
  10877. s.midiLinks = { inverted, ported };
  10878. });
  10879. engine.injectControllerForTest (20, 0, 127);
  10880. check ("formula_inverts", std::abs (engine.currentTargetValue (volume)) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  10881. engine.injectControllerForTest (20, 0, 0);
  10882. check ("formula_inverts_back", std::abs (engine.currentTargetValue (volume) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  10883. const auto panBefore = engine.currentTargetValue (pan);
  10884. engine.injectControllerForTest (21, 0, 127); // no port: not this link's device
  10885. check ("port_must_match", std::abs (engine.currentTargetValue (pan) - panBefore) < 0.001f);
  10886. engine.injectControllerForTest (21, 0, 127, 3);
  10887. check ("port_matches", std::abs (engine.currentTargetValue (pan) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (pan)));
  10888. // the window on a control whose controller another control uses: Remove conflicts in red; Accept removes it
  10889. auto panel = lynx::makeRemoteControlPanel (engine, { insert }, false);
  10890. lynx::remoteControlPanelSetController (*panel, -1, 1, 20);
  10891. shoot (*panel, "remote-conflict");
  10892. check ("conflict_counted", lynx::remoteControlPanelState (*panel).contains ("|1|"), lynx::remoteControlPanelState (*panel));
  10893. lynx::remoteControlPanelPress (*panel, 2);
  10894. const auto& links = engine.getSong().midiLinks;
  10895. check ("conflict_removed", links.size() == 2
  10896. && std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; })
  10897. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == insert && l.cc == 20; }));
  10898. engine.undo();
  10899. check ("accept_is_one_undo_step", engine.getSong().midiLinks.size() == 2 && engine.getSong().midiLinks[0].target == volume);
  10900. }
  10901. // ---- an existing link opened again: "Link 1" / "New link"
  10902. {
  10903. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  10904. shoot (*panel, "remote-existing-link");
  10905. check ("existing_link_loaded", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|20|1-Input|"), lynx::remoteControlPanelState (*panel));
  10906. // Reset, then Accept: a link without a controller is removed
  10907. lynx::remoteControlPanelPress (*panel, 0);
  10908. check ("reset_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  10909. lynx::remoteControlPanelPress (*panel, 2);
  10910. const auto& links = engine.getSong().midiLinks;
  10911. check ("reset_accept_unlinks", std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; }));
  10912. }
  10913. // ---- several controls ("Link to controllers..."): Accept and Skip step through them
  10914. {
  10915. auto panel = lynx::makeRemoteControlPanel (engine, { volume, pan, insert }, false, [] {});
  10916. shoot (*panel, "remote-multilink");
  10917. const auto parameter = [&panel] { return juce::StringArray::fromTokens (lynx::remoteControlPanelState (*panel), "|", "")[6]; };
  10918. const auto first = parameter();
  10919. check ("multilink_caption_and_skip", first.startsWith ("1/3") && first.contains (lynx::tr ("Channel volume"))
  10920. && lynx::remoteControlPanelState (*panel).contains ("S|omni"),
  10921. lynx::remoteControlPanelState (*panel));
  10922. lynx::remoteControlPanelSetController (*panel, -1, 1, 30);
  10923. lynx::remoteControlPanelPress (*panel, 2); // Accept: volume linked, on to pan
  10924. const auto second = parameter();
  10925. lynx::remoteControlPanelPress (*panel, 1); // Skip: pan untouched, on to the insert
  10926. const auto third = parameter();
  10927. const auto beforeLast = lynx::remoteControlPanelFinished (*panel);
  10928. lynx::remoteControlPanelPress (*panel, 1); // Skip on the last one: done
  10929. const auto closed = ! beforeLast && lynx::remoteControlPanelFinished (*panel);
  10930. const auto& links = engine.getSong().midiLinks;
  10931. check ("multilink_steps", first != second && second != third && closed
  10932. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume && l.cc == 30; }),
  10933. first + " > " + second + " > " + third);
  10934. }
  10935. // ---- Global link settings
  10936. {
  10937. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  10938. shoot (*panel, "global-default");
  10939. lynx::remoteControlPanelSetController (*panel, 2, 1, 11);
  10940. lynx::remoteControlPanelSetFormula (*panel, "Input*0.5");
  10941. lynx::remoteControlPanelPress (*panel, 2);
  10942. const auto global = engine.globalLinkOf (volume);
  10943. check ("global_link_written", global && global->cc == 11 && global->port == 2 && global->formula == "Input*0.5");
  10944. const auto text = engine.getMidiPrefs().toText();
  10945. const auto back = lynx::prefs::MidiPrefs::fromText (text);
  10946. check ("global_link_settings_round_trip", back.globalLinks == engine.getMidiPrefs().globalLinks && text.find ("linkset=2|0|469|Input*0.5") != std::string::npos);
  10947. auto again = lynx::makeRemoteControlPanel (engine, { volume }, true);
  10948. shoot (*again, "global-existing-link");
  10949. engine.setGlobalLink (volume, std::nullopt);
  10950. check ("global_link_removed", ! engine.globalLinkOf (volume));
  10951. }
  10952. // ---- the project file: links with settings come back; a project of an older version loads the same
  10953. {
  10954. lynx::Song song = engine.getSong();
  10955. MidiLink plain { 7, -1, volume };
  10956. MidiLink rich { 74, 2, pan };
  10957. rich.port = 4;
  10958. rich.formula = "Min(Input*1.1,0.5)+Max(Input*1.1,0.6)-0.6";
  10959. rich.smooth = true;
  10960. rich.smoothing = -300;
  10961. rich.omni = true;
  10962. song.midiLinks = { plain, rich };
  10963. juce::String error;
  10964. const auto json = lynx::ProjectFile::toJson (song);
  10965. const auto back = lynx::ProjectFile::fromJson (json, error);
  10966. check ("project_round_trip", back && back->midiLinks == song.midiLinks, error);
  10967. // without settings the file holds only the list older versions wrote
  10968. song.midiLinks = { plain };
  10969. const auto plainJson = lynx::ProjectFile::toJson (song);
  10970. check ("plain_links_write_the_old_form", ! plainJson.contains ("midiLinkSettings") && plainJson.contains ("midiLinks"));
  10971. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  10972. check ("old_project_loads_the_same", plainBack && plainBack->midiLinks.size() == 1 && plainBack->midiLinks[0] == plain
  10973. && ! plainBack->midiLinks[0].hasSettings());
  10974. // what an older version does with a new file: it reads "midiLinks" alone, so the links stay (plain)
  10975. auto parsed = juce::JSON::parse (json);
  10976. if (auto* o = parsed.getDynamicObject())
  10977. o->removeProperty ("midiLinkSettings");
  10978. const auto stripped = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  10979. check ("older_version_keeps_the_links", stripped && stripped->midiLinks.size() == 2 && stripped->midiLinks[1].cc == 74
  10980. && ! stripped->midiLinks[1].hasSettings());
  10981. }
  10982. // ---- round 190cs: FL's live answers (live check 190cq) and the note / button link modes
  10983. {
  10984. const auto state = [] (juce::Component& p) { return lynx::remoteControlPanelState (p); };
  10985. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  10986. // the layout FL shows: no assignment list without a link, no Skip outside Multilink, no internal
  10987. // controller group without a controller in the project; the parameter caption in FL's words
  10988. auto fresh = lynx::makeRemoteControlPanel (engine, { volume }, false);
  10989. shoot (*fresh, "cs-remote-default");
  10990. check ("cs_layout_without_link", state (*fresh).contains ("|" + lynx::tr ("Channel volume") + "|") && state (*fresh).contains ("|shown=POC|"), state (*fresh));
  10991. // Omni: enabled on a mixer track's volume (FL: "Insert 1 - Volume"), greyed on the tempo
  10992. auto onInsert = lynx::makeRemoteControlPanel (engine, { insert }, false);
  10993. auto onTempo = lynx::makeRemoteControlPanel (engine, { AutomationTarget { AutomationTargetKind::tempo, 0 } }, false);
  10994. shoot (*onInsert, "cs-remote-omni-insert");
  10995. check ("cs_omni_mixer_track", state (*onInsert).contains ("|omni=on|") && state (*onTempo).contains ("|omni=off|"),
  10996. state (*onInsert) + " / " + state (*onTempo));
  10997. // the formula compiles on Enter only; FL's messages and colours
  10998. lynx::remoteControlPanelSetFormula (*fresh, "1-Input^2", false);
  10999. check ("cs_no_compile_while_typing", state (*fresh).contains ("|" + lynx::tr ("(default 1:1 mapping)") + "|"), state (*fresh));
  11000. lynx::remoteControlPanelSetFormula (*fresh, "-Input^2");
  11001. shoot (*fresh, "cs-remote-compiled");
  11002. check ("cs_compiled_on_enter", state (*fresh).contains ("|" + lynx::tr ("Compiled ok.") + "|"), state (*fresh));
  11003. const std::pair<const char*, const char*> errors[] { { "Input*", "Syntax error: function or operand" },
  11004. { "foo(Input)", "Invalid identifier: foo" },
  11005. { "Sin(Input", "Unequal brackets" },
  11006. { "Input 2", "input two space limited" } };
  11007. for (const auto& [text, expected] : errors)
  11008. {
  11009. lynx::remoteControlPanelSetFormula (*fresh, text);
  11010. check ("cs_fl_error_text", state (*fresh).contains (expected), state (*fresh));
  11011. }
  11012. lynx::remoteControlPanelSetFormula (*fresh, "foo(Input)");
  11013. shoot (*fresh, "cs-remote-error");
  11014. // Accept with that formula: the link is made, the formula is not kept (FL reopens it as "Input")
  11015. lynx::remoteControlPanelSetController (*fresh, -1, 1, 7);
  11016. lynx::remoteControlPanelPress (*fresh, 2);
  11017. check ("cs_bad_formula_accept_is_input", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == 7
  11018. && engine.getSong().midiLinks[0].formula.empty());
  11019. auto reopened = lynx::makeRemoteControlPanel (engine, { volume }, false);
  11020. shoot (*reopened, "cs-remote-reopened");
  11021. check ("cs_reopened_shows_input_and_link_list", state (*reopened).startsWith ("-1|1|7|Input|" + lynx::tr ("(default 1:1 mapping)") + "|")
  11022. && state (*reopened).contains ("|shown=PAOC|"),
  11023. state (*reopened));
  11024. // the internal controller group appears with a controller in the project, with "Record automation"
  11025. engine.editSong ([] (lynx::Song& s) {
  11026. lynx::EffectSlot peak;
  11027. peak.kind = lynx::EffectKind::peakController;
  11028. s.mixer[0].effects.push_back (peak);
  11029. });
  11030. auto withController = lynx::makeRemoteControlPanel (engine, { volume }, false);
  11031. lynx::remoteControlPanelSetInternal (*withController, 1, true);
  11032. shoot (*withController, "cs-remote-internal");
  11033. check ("cs_internal_group_shown", state (*withController).contains ("|shown=PAIOC|") && state (*withController).startsWith ("-1|1|-1|"),
  11034. state (*withController));
  11035. lynx::remoteControlPanelPress (*withController, 2);
  11036. const auto& autos = engine.getSong().automations;
  11037. check ("cs_record_automation_kept", std::any_of (autos.begin(), autos.end(), [&] (const lynx::Automation& a) {
  11038. return a.isLive() && a.target == volume && a.recordLive;
  11039. }));
  11040. engine.editSong ([] (lynx::Song& s) {
  11041. s.mixer[0].effects.pop_back();
  11042. s.automations.clear();
  11043. s.midiLinks.clear();
  11044. });
  11045. // the global window: no parameter list, Omni, Remove conflicts or Skip; Mode is there
  11046. auto globalPanel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  11047. shoot (*globalPanel, "cs-global-default");
  11048. check ("cs_global_layout", state (*globalPanel).contains ("|shown=|"), state (*globalPanel));
  11049. // a key link in each Mode: note 60 = FL's controller number 256 + 60
  11050. const auto key = lynx::linkNoteBase + 60;
  11051. auto modePanel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  11052. lynx::remoteControlPanelSetController (*modePanel, -1, 1, key);
  11053. lynx::remoteControlPanelSetMode (*modePanel, 2);
  11054. shoot (*modePanel, "cs-remote-note-latch");
  11055. lynx::remoteControlPanelPress (*modePanel, 2);
  11056. check ("cs_note_link_written", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == key
  11057. && engine.getSong().midiLinks[0].mode == 2);
  11058. const auto play = [&engine, key, volume] (int velocity) {
  11059. engine.injectControllerForTest (key, 0, velocity);
  11060. return engine.currentTargetValue (volume);
  11061. };
  11062. const auto setMode = [&engine] (int mode) {
  11063. engine.editSong ([mode] (lynx::Song& s) { s.midiLinks[0].mode = mode; });
  11064. engine.editSong ([] (lynx::Song& s) { s.setTargetValue ({ AutomationTargetKind::channelVolume, 0 }, 0.25f); });
  11065. };
  11066. setMode (2); // Latch: press switches, release does nothing
  11067. const auto l1 = play (100), l1off = play (0), l2 = play (90), l2off = play (0);
  11068. check ("cs_mode_latch", std::abs (l1 - 1.0f) < 1e-4f && std::abs (l1off - 1.0f) < 1e-4f && l2 < 1e-4f && l2off < 1e-4f,
  11069. juce::String (l1) + " " + juce::String (l1off) + " " + juce::String (l2) + " " + juce::String (l2off));
  11070. setMode (1); // Hold: the velocity while held, back to 0 on release
  11071. const auto h1 = play (100), h1off = play (0);
  11072. check ("cs_mode_hold", std::abs (h1 - 100.0f / 127.0f) < 1e-4f && h1off < 1e-4f, juce::String (h1) + " " + juce::String (h1off));
  11073. setMode (0); // Default: as Hold for a key
  11074. const auto d1 = play (64), d1off = play (0);
  11075. check ("cs_mode_default", std::abs (d1 - 64.0f / 127.0f) < 1e-4f && d1off < 1e-4f, juce::String (d1) + " " + juce::String (d1off));
  11076. setMode (3); // Inc: each press adds 1/128
  11077. const auto i1 = play (100), i1off = play (0), i2 = play (20);
  11078. check ("cs_mode_inc", std::abs (i1 - (0.25f + 1.0f / 128.0f)) < 1e-4f && std::abs (i1off - i1) < 1e-6f
  11079. && std::abs (i2 - (0.25f + 2.0f / 128.0f)) < 1e-4f,
  11080. juce::String (i1) + " " + juce::String (i2));
  11081. setMode (4); // Stay: the velocity, kept after the release
  11082. const auto s1 = play (100), s1off = play (0);
  11083. check ("cs_mode_stay", std::abs (s1 - 100.0f / 127.0f) < 1e-4f && std::abs (s1off - s1) < 1e-6f, juce::String (s1) + " " + juce::String (s1off));
  11084. // the project file keeps the key link and its mode; an older reader skips it
  11085. lynx::Song song = engine.getSong();
  11086. song.midiLinks[0].mode = 2;
  11087. MidiLink cc7 { 7, 0, pan };
  11088. cc7.mode = 4;
  11089. song.midiLinks.insert (song.midiLinks.begin(), cc7);
  11090. juce::String error;
  11091. const auto json = lynx::ProjectFile::toJson (song);
  11092. const auto back = lynx::ProjectFile::fromJson (json, error);
  11093. check ("cs_note_link_round_trip", back && back->midiLinks == song.midiLinks && json.contains ("midiNoteLinks"), error);
  11094. auto parsed = juce::JSON::parse (json);
  11095. if (auto* o = parsed.getDynamicObject())
  11096. {
  11097. o->removeProperty ("midiNoteLinks");
  11098. o->removeProperty ("midiLinkSettings");
  11099. }
  11100. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  11101. check ("cs_older_reader_keeps_cc_links_only", older && older->midiLinks.size() == 1 && older->midiLinks[0].cc == 7);
  11102. // "Record automation" of an internal-controller link, saved only when on
  11103. lynx::Automation live;
  11104. live.target = volume;
  11105. live.source.track = 0;
  11106. live.recordLive = true;
  11107. song.automations = { live };
  11108. const auto withLive = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  11109. live.recordLive = false;
  11110. song.automations = { live };
  11111. check ("cs_record_automation_round_trip", withLive && withLive->automations.size() == 1 && withLive->automations[0].recordLive
  11112. && ! lynx::ProjectFile::toJson (song).contains ("recordLive"));
  11113. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  11114. }
  11115. // ---- menus: the control menu, the formula presets, the controller list, the Multilink items
  11116. {
  11117. juce::PopupMenu control;
  11118. lynx::addAutomationItem (control, engine, volume, true);
  11119. engine.setMultilink (true);
  11120. engine.noteTweaked (volume);
  11121. engine.noteTweaked (pan);
  11122. juce::PopupMenu multilink;
  11123. lynx::addMultilinkControlsItems (multilink, engine);
  11124. check ("multilink_queue", engine.multilinkTargets().size() == 2);
  11125. engine.setMultilink (false);
  11126. saveMenus (juce::StringArray { "Control menu", "Formula presets", "Multilink" },
  11127. std::vector<juce::PopupMenu> { control, lynx::remoteControlFormulaMenu ([] (const juce::String&) {}), multilink },
  11128. prefix + "-menus.png");
  11129. saveMenus (juce::StringArray { "Ctrl menu" }, std::vector<juce::PopupMenu> { lynx::remoteControlControllerMenu ([] (int) {}) },
  11130. prefix + "-ctrl-menu.png");
  11131. // the Mode list as its box pops it up (round 190cs)
  11132. juce::PopupMenu modes;
  11133. for (const char* m : { "Default", "Hold", "Latch", "Inc", "Stay" })
  11134. modes.addItem (lynx::tr (m), true, juce::String (m) == "Default", [] {});
  11135. saveMenus (juce::StringArray { "Mode" }, std::vector<juce::PopupMenu> { modes }, prefix + "-mode-menu.png");
  11136. }
  11137. // ---- Settings > MIDI: the input's Port box, the link list with a link's settings
  11138. {
  11139. engine.editSong ([&] (lynx::Song& s) {
  11140. MidiLink l { 74, 2, pan };
  11141. l.port = 4;
  11142. l.formula = "1-Input";
  11143. l.smooth = true;
  11144. s.midiLinks = { MidiLink { 7, 0, volume }, l };
  11145. });
  11146. auto page = lynx::makeMidiPage (engine, {}, false);
  11147. page->setSize (760, 900);
  11148. shoot (*page, "settings-midi");
  11149. }
  11150. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  11151. return allOk;
  11152. }
  11153. // A stand-in hosted plugin for the shot route: three parameters, its state = their values
  11154. struct FlCtlShotPlugin final : juce::AudioPluginInstance
  11155. {
  11156. FlCtlShotPlugin()
  11157. {
  11158. for (const char* n : { "Cutoff", "Resonance", "Drive" })
  11159. addHostedParameter (std::make_unique<juce::AudioParameterFloat> (juce::ParameterID (n, 1), n, 0.0f, 1.0f, 0.5f));
  11160. }
  11161. const juce::String getName() const override { return "Shot plugin"; }
  11162. void prepareToPlay (double, int) override {}
  11163. void releaseResources() override {}
  11164. void processBlock (juce::AudioBuffer<float>&, juce::MidiBuffer&) override {}
  11165. double getTailLengthSeconds() const override { return 0.0; }
  11166. bool acceptsMidi() const override { return false; }
  11167. bool producesMidi() const override { return false; }
  11168. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  11169. bool hasEditor() const override { return false; }
  11170. int getNumPrograms() override { return 1; }
  11171. int getCurrentProgram() override { return 0; }
  11172. void setCurrentProgram (int) override {}
  11173. const juce::String getProgramName (int) override { return {}; }
  11174. void changeProgramName (int, const juce::String&) override {}
  11175. void getStateInformation (juce::MemoryBlock& b) override
  11176. {
  11177. for (auto* p : getParameters())
  11178. {
  11179. const float v = static_cast<juce::AudioParameterFloat*> (p)->get();
  11180. b.append (&v, sizeof (float));
  11181. }
  11182. }
  11183. void setStateInformation (const void* data, int size) override
  11184. {
  11185. const auto& list = getParameters();
  11186. for (int i = 0; i < list.size() && (i + 1) * (int) sizeof (float) <= size; ++i)
  11187. *static_cast<juce::AudioParameterFloat*> (list[i]) = static_cast<const float*> (data)[i];
  11188. }
  11189. void fillInPluginDescription (juce::PluginDescription& d) const override
  11190. {
  11191. d.name = getName();
  11192. d.pluginFormatName = "Shot";
  11193. d.fileOrIdentifier = "shot";
  11194. }
  11195. };
  11196. static juce::File writeShotSample (const juce::File& file, double hz)
  11197. {
  11198. juce::AudioBuffer<float> buffer (1, 22050);
  11199. for (int i = 0; i < buffer.getNumSamples(); ++i)
  11200. buffer.setSample (0, i, (float) (std::sin (juce::MathConstants<double>::twoPi * hz * i / 44100.0) * std::exp (-i / 6000.0)));
  11201. file.deleteFile();
  11202. juce::WavAudioFormat wav;
  11203. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  11204. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  11205. return file;
  11206. }
  11207. static bool clickMenuItem (const juce::PopupMenu& menu, const juce::String& text)
  11208. {
  11209. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  11210. if (it.getItem().text == text && it.getItem().isEnabled && it.getItem().action != nullptr)
  11211. {
  11212. it.getItem().action();
  11213. return true;
  11214. }
  11215. return false;
  11216. }
  11217. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen — the page as FL's shot (dock188a) shows it,
  11218. // the legacy effects, a small window, a zoomed waveform — and its laws turned as a user would; prefix-checks.txt
  11219. bool runSamplerPageShot (const juce::String& prefix)
  11220. {
  11221. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11222. juce::StringArray report;
  11223. bool allOk = true;
  11224. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  11225. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  11226. allOk = allOk && ok;
  11227. };
  11228. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  11229. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  11230. };
  11231. lynx::AudioEngine engine (false);
  11232. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("sampler-samples");
  11233. folder.createDirectory();
  11234. // an 808-like kick, 1 s (FL's shot: "Basic 808 Kick.wav")
  11235. const auto kick = folder.getChildFile ("Basic 808 Kick.wav");
  11236. {
  11237. juce::AudioBuffer<float> buffer (1, 44100);
  11238. double phase = 0.0;
  11239. for (int i = 0; i < buffer.getNumSamples(); ++i)
  11240. {
  11241. const auto t = i / 44100.0;
  11242. phase += juce::MathConstants<double>::twoPi * (48.0 + 90.0 * std::exp (-t * 30.0)) / 44100.0;
  11243. buffer.setSample (0, i, (float) (0.9 * std::sin (phase) * std::exp (-t * 3.2)));
  11244. }
  11245. kick.deleteFile();
  11246. juce::WavAudioFormat wav;
  11247. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (kick.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  11248. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  11249. }
  11250. engine.editSong ([&] (lynx::Song& s) {
  11251. if (s.channels.empty())
  11252. s.channels.resize (1);
  11253. lynx::audioclips::loadSampleInto (s.channels[0], kick.getFullPathName().toStdString(), "808 Kick");
  11254. // FL's shot: Resample and Load regions on, Use loop points on, declicking "Out only (no bleeding)"
  11255. s.channels[0].sampler.resampleOnLoad = true;
  11256. });
  11257. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  11258. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  11259. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  11260. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  11261. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  11262. shoot (*frame, "sampler-page");
  11263. report.add ("page size " + juce::String (frame->getWidth()) + "x" + juce::String (frame->getHeight()));
  11264. // ---- the laws, turned on the page
  11265. auto& f = *frame;
  11266. lynx::samplerPageTurn (f, "pingPong", 1.0);
  11267. check ("ping_pong", sampler().precompute.pingPong);
  11268. lynx::samplerPageTurn (f, "pingPong", 0.0);
  11269. lynx::samplerPageTurn (f, "loopStart", 5000.0);
  11270. check ("loop_start", sampler().loopStart == 5000 && sampler().loopEnd == 5001, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  11271. lynx::samplerPageTurn (f, "loopEnd", 15000.0);
  11272. check ("loop_end", sampler().loopStart == 5000 && sampler().loopEnd == 15000);
  11273. lynx::samplerPageTurn (f, "loopStart", 20000.0, true); // Shift: the loop moves
  11274. check ("loop_shift_moves", sampler().loopStart == 20000 && sampler().loopEnd == 30000, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  11275. check ("keep_on_disk_greyed_with_loop", lynx::samplerPageQuery (f, "keepOnDisk") == "0");
  11276. lynx::samplerPageTurn (f, "useLoops", 0.0);
  11277. check ("keep_on_disk_back", lynx::samplerPageQuery (f, "keepOnDisk") == "1" && ! sampler().useLoopPoints);
  11278. check ("not_cut_yet", ! lynx::channelCutsItself (engine.getSong().channels[0]));
  11279. lynx::samplerPageTurn (f, "useLoops", 1.0);
  11280. check ("use_loops_cuts_itself", sampler().useLoopPoints && lynx::channelCutsItself (engine.getSong().channels[0]));
  11281. engine.editSong ([] (lynx::Song& s) {
  11282. lynx::setChannelCutsItself (s.channels[0], 0, false);
  11283. s.channels[0].sampler.useLoopPoints = false;
  11284. });
  11285. lynx::samplerPageTurn (f, "crossfade", 300.0); // (Use loop points off: the crossfade switches it on)
  11286. check ("crossfade_switches_loops_on", sampler().precompute.crossfade == 300 && sampler().useLoopPoints);
  11287. lynx::samplerPageTurn (f, "crossfade", 0.0);
  11288. lynx::samplerPageTurn (f, "pitch", 300.0); // (Resample: FL switches to Auto)
  11289. check ("pitch_resample_to_auto", sampler().keepPitch && sampler().flStretchMode == 5 && sampler().flStretchPitch == 300
  11290. && lynx::samplerPageQuery (f, "mode") == lynx::tr ("General"),
  11291. lynx::samplerPageQuery (f, "mode") + " " + juce::String (sampler().pitch));
  11292. lynx::samplerPageTurn (f, "pitch", 0.0);
  11293. lynx::samplerPageTurn (f, "mode", 1.0); // Resample
  11294. check ("mode_resample", ! sampler().keepPitch && std::abs (sampler().pitch) < 1.0e-4f);
  11295. lynx::samplerPageTurn (f, "time", 4.0);
  11296. lynx::samplerPageTurn (f, "mul", 10000.0);
  11297. check ("time_mul", std::abs (sampler().stretchBeats - 8.0f) < 1.0e-3f && sampler().stretchMul == 10000, juce::String (sampler().stretchBeats));
  11298. lynx::samplerPageTurn (f, "mul", 0.0);
  11299. lynx::samplerPageTurn (f, "time", 0.0);
  11300. lynx::samplerPageTurn (f, "length", 0.5);
  11301. lynx::samplerPageTurn (f, "smpStart", 0.5);
  11302. check ("smp_start_keeps_length", std::abs (sampler().regionStart - 0.5f) < 1.0e-3f && std::abs (sampler().regionEnd - 0.75f) < 1.0e-3f,
  11303. juce::String (sampler().regionStart) + "-" + juce::String (sampler().regionEnd));
  11304. lynx::samplerPageTurn (f, "smpStart", 0.0);
  11305. lynx::samplerPageTurn (f, "length", 1.0);
  11306. lynx::samplerPageTurn (f, "declick", 4.0);
  11307. check ("declick_mode", sampler().declickMode == 4);
  11308. lynx::samplerPageTurn (f, "declick", 0.0);
  11309. // ---- the .lynx keeps what the page set
  11310. {
  11311. lynx::samplerPageTurn (f, "mul", -5000.0);
  11312. lynx::samplerPageTurn (f, "keepOnDisk", 1.0);
  11313. juce::String error;
  11314. const auto json = lynx::ProjectFile::toJson (engine.getSong(), false);
  11315. const auto back = lynx::ProjectFile::fromJson (json, error);
  11316. check ("lynx_round_trip", back.has_value() && back->channels[0].sampler == engine.getSong().channels[0].sampler, error);
  11317. lynx::samplerPageTurn (f, "mul", 0.0);
  11318. lynx::samplerPageTurn (f, "keepOnDisk", 0.0);
  11319. }
  11320. // ---- shots: FL's state again (loop points from the file: none), the legacy panel, a zoom, a small window
  11321. engine.editSong ([] (lynx::Song& s) {
  11322. auto& ch = s.channels[0];
  11323. ch.sampler.loopStart = ch.sampler.loopEnd = -1;
  11324. ch.sampler.useLoopPoints = true;
  11325. ch.sampler.precompute = {};
  11326. });
  11327. lynx::samplerPageTurn (f, "show", 0.0); // (no control: the page shows the channel again)
  11328. frame->createComponentSnapshot (frame->getLocalBounds());
  11329. shoot (*frame, "sampler-page-fl-state");
  11330. lynx::samplerPageTurn (f, "legacy", 1.0);
  11331. check ("legacy_panel", lynx::samplerPageQuery (f, "legacy") == "1");
  11332. shoot (*frame, "sampler-page-legacy");
  11333. lynx::samplerPageTurn (f, "legacy", 0.0);
  11334. lynx::samplerPageTurn (f, "zoom", 0.25);
  11335. check ("zoom_scroll", lynx::samplerPageQuery (f, "scroll") == "0.250", lynx::samplerPageQuery (f, "scroll"));
  11336. shoot (*frame, "sampler-page-zoom");
  11337. lynx::samplerPageTurn (f, "zoom", 1.0);
  11338. frame->setSize (520, 470);
  11339. frame->createComponentSnapshot (frame->getLocalBounds());
  11340. shoot (*frame, "sampler-page-small");
  11341. report.add (juce::String ("result=") + (allOk ? "OK" : "FAIL"));
  11342. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  11343. return allOk;
  11344. }
  11345. bool runFlCtlShot (const juce::String& prefix)
  11346. {
  11347. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11348. juce::StringArray report;
  11349. bool allOk = true;
  11350. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  11351. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  11352. allOk = allOk && ok;
  11353. };
  11354. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  11355. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  11356. };
  11357. using lynx::AutomationTarget;
  11358. using lynx::AutomationTargetKind;
  11359. lynx::AudioEngine engine (false);
  11360. engine.editSong ([] (lynx::Song& s) {
  11361. if (s.channels.size() < 3)
  11362. s.channels.resize (3);
  11363. if (s.patterns.empty())
  11364. s.patterns.resize (1);
  11365. s.currentPattern = 0;
  11366. });
  11367. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 };
  11368. // ---- FL's multilink menu: on with two queued controls, off with the last tweaked parameters
  11369. {
  11370. engine.setMultilink (true);
  11371. engine.noteTweaked (volume);
  11372. engine.noteTweaked (pan);
  11373. auto on = lynx::multilinkButtonMenu (engine);
  11374. juce::PopupMenu::MenuItemIterator first (on);
  11375. first.next();
  11376. check ("ml_caption_on", first.getItem().isSectionHeader && first.getItem().text == lynx::tr ("{0} parameters selected", { "2" }), first.getItem().text);
  11377. // Init pattern: the values at the pattern's start; ends multilink
  11378. const auto v0 = engine.currentTargetValue (volume);
  11379. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initPattern, engine.multilinkTargets(), 0);
  11380. const auto& lanes = engine.getSong().patterns[0].events;
  11381. check ("ml_init_pattern", lanes.size() == 2 && ! lanes[0].events.empty() && lanes[0].events[0].tick == 0
  11382. && std::abs (lanes[0].events[0].value - v0) < 1.0e-6f && ! engine.isMultilinkOn());
  11383. // Randomize keeps multilink on; Humanize moves at most an eighth
  11384. engine.setMultilink (true);
  11385. engine.noteTweaked (volume);
  11386. engine.noteTweaked (pan);
  11387. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::randomize, engine.multilinkTargets(), 1234);
  11388. check ("ml_randomize_keeps_queue", engine.isMultilinkOn() && engine.multilinkTargets().size() == 2);
  11389. const auto before = engine.currentTargetValue (volume);
  11390. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::humanize, engine.multilinkTargets(), 99);
  11391. check ("ml_humanize_small", std::abs (engine.currentTargetValue (volume) - before) <= 0.1251f && engine.isMultilinkOn(),
  11392. juce::String (before) + " -> " + juce::String (engine.currentTargetValue (volume)));
  11393. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initSong, engine.multilinkTargets(), 0);
  11394. check ("ml_init_song", engine.getSong().findInitialValue (volume) >= 0 && ! engine.isMultilinkOn());
  11395. // off: the last two tweaked parameters, no Cancel
  11396. auto off = lynx::multilinkButtonMenu (engine);
  11397. bool hasCancel = false;
  11398. for (juce::PopupMenu::MenuItemIterator it (off); it.next();)
  11399. hasCancel = hasCancel || it.getItem().text == lynx::tr ("Cancel");
  11400. juce::PopupMenu::MenuItemIterator offFirst (off);
  11401. offFirst.next();
  11402. check ("ml_off_caption", offFirst.getItem().text == lynx::tr ("Last 2 tweaked parameters") && ! hasCancel, offFirst.getItem().text);
  11403. // LYNX's own one-step items stay, after FL's items below a line (greyed while multilink is off)
  11404. juce::String last;
  11405. bool lineBefore = false, prevLine = false;
  11406. for (juce::PopupMenu::MenuItemIterator it (on); it.next();)
  11407. {
  11408. if (it.getItem().text == lynx::tr ("Link to controller"))
  11409. lineBefore = prevLine;
  11410. prevLine = it.getItem().isSeparator;
  11411. last = it.getItem().text;
  11412. }
  11413. check ("ml_lynx_items_after_fl", lineBefore && last == lynx::tr ("Override global links"), last);
  11414. saveMenus (juce::StringArray { "Multilink on (2 queued)", "Multilink off" }, std::vector<juce::PopupMenu> { on, off },
  11415. prefix + "-multilink-menu.png");
  11416. }
  11417. // ---- the plugin menu's spare state and Parameters > Link all parameters...
  11418. {
  11419. FlCtlShotPlugin plugin;
  11420. juce::PopupMenu menu;
  11421. lynx::addPluginWrapperItems (menu, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  11422. saveMenus (juce::StringArray { "Plugin menu: spare state and parameters" }, std::vector<juce::PopupMenu> { menu }, prefix + "-plugin-menu.png");
  11423. const auto targets = lynx::allPluginParameterTargets (plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  11424. check ("link_all_parameters", targets.size() == 3 && targets[2].param == 2 && targets[2].index == 1);
  11425. auto* cutoff = static_cast<juce::AudioParameterFloat*> (plugin.getParameters()[0]);
  11426. *cutoff = 0.2f;
  11427. check ("spare_store", clickMenuItem (menu, lynx::tr ("Store in spare state")));
  11428. *cutoff = 0.9f;
  11429. juce::PopupMenu again;
  11430. lynx::addPluginWrapperItems (again, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  11431. check ("spare_flip", clickMenuItem (again, lynx::tr ("Flip with spare state")) && std::abs (cutoff->get() - 0.2f) < 1.0e-6f, juce::String (cutoff->get()));
  11432. check ("spare_flip_back", clickMenuItem (again, lynx::tr ("Flip with spare state")) && std::abs (cutoff->get() - 0.9f) < 1.0e-6f, juce::String (cutoff->get()));
  11433. lynx::sparestate::shared().forget (&plugin);
  11434. }
  11435. // ---- the sampler's File row: Load (history menu, wheel), Locate, Remove
  11436. {
  11437. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flctl-samples");
  11438. folder.createDirectory();
  11439. const auto a = writeShotSample (folder.getChildFile ("Kick 1.wav"), 60.0), b = writeShotSample (folder.getChildFile ("Snare 2.wav"), 200.0),
  11440. c = writeShotSample (folder.getChildFile ("Hat 3.wav"), 900.0);
  11441. lynx::samplehistory::list().clear();
  11442. engine.editSong ([&] (lynx::Song& s) {
  11443. for (const auto& f : { c, b, a }) // (each load goes into the history, newest first)
  11444. lynx::audioclips::loadSampleInto (s.channels[1], f.getFullPathName().toStdString(), f.getFileNameWithoutExtension().toStdString());
  11445. });
  11446. check ("history_order", lynx::samplehistory::list().size() == 3 && lynx::samplehistory::list().front() == a.getFullPathName().toStdString());
  11447. juce::File located;
  11448. lynx::locateInBrowserHandler() = [&located] (const juce::File& f) { located = f; };
  11449. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  11450. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 820);
  11451. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  11452. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  11453. shoot (*frame, "sampler-file-row");
  11454. const auto history = lynx::samplerHistoryMenu (*frame);
  11455. check ("history_menu", history.has_value() && history->getNumItems() == 4); // (caption + three samples)
  11456. if (history)
  11457. saveMenus (juce::StringArray { "Load: Sample history" }, std::vector<juce::PopupMenu> { *history }, prefix + "-sample-history.png");
  11458. lynx::samplerFileRowPress (*frame, 0); // wheel down: the next (older) sample
  11459. check ("wheel_down", engine.getSong().channels[1].samplePath == b.getFullPathName().toStdString(), juce::String (engine.getSong().channels[1].samplePath));
  11460. lynx::samplerFileRowPress (*frame, 1); // wheel up: back
  11461. check ("wheel_up", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  11462. lynx::samplerFileRowPress (*frame, 2);
  11463. check ("locate", located == a, located.getFullPathName());
  11464. lynx::samplerFileRowPress (*frame, 3);
  11465. check ("remove", engine.getSong().channels[1].samplePath.empty());
  11466. engine.undo();
  11467. check ("remove_undo", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  11468. lynx::locateInBrowserHandler() = nullptr;
  11469. }
  11470. // ---- a sampler running FL's voice: FL's Envelope / instrument page with the tensions, the predelay and presets
  11471. {
  11472. engine.editSong ([] (lynx::Song& s) {
  11473. auto& ch = s.channels[2];
  11474. ch.instrument = lynx::InstrumentKind::sampler;
  11475. ch.name = "FL sampler";
  11476. const auto snap = lynx::flvp::defaultSnapshot();
  11477. ch.sampler.flChannel.assign (90, 0);
  11478. std::memcpy (ch.sampler.flChannel.data(), snap.data(), 85 * 4);
  11479. std::memcpy (&ch.sampler.flChannel[85], snap.data() + 0x15c, 4);
  11480. std::memcpy (&ch.sampler.flChannel[86], snap.data() + 0x160, 4);
  11481. std::memcpy (&ch.sampler.flChannel[87], snap.data() + 0x168, 4);
  11482. ch.sampler.flChannel[88] = 96;
  11483. ch.sampler.flChannel[89] = 0;
  11484. auto& vol = ch.sampler.flChannel; // the volume envelope on, bent
  11485. vol[17 + 1] = -1;
  11486. vol[17 + 2] = 4000; // predelay
  11487. vol[17 + 14] = -70; // attack tension
  11488. vol[17 + 15] = 60; // decay tension
  11489. vol[17 + 16] = -40; // release tension
  11490. });
  11491. auto frame = lynx::makeChannelFrame (engine, 2, 1);
  11492. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 560);
  11493. shoot (*frame, "sampler-fl-envelope");
  11494. check ("fl_page_shown", lynx::flVoicePresetsMenu (*frame).has_value());
  11495. lynx::flVoicePresetFolder().deleteRecursively();
  11496. check ("preset_save", lynx::flVoiceSavePreset (*frame, "Bent volume")
  11497. && lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV").getSize() == 68);
  11498. if (const auto menu = lynx::flVoicePresetsMenu (*frame))
  11499. saveMenus (juce::StringArray { "Channel envelope presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-envelope-presets.png");
  11500. // the preset into the pitch target: its record becomes the saved one
  11501. lynx::showFlVoiceTarget (*frame, lynx::flvoice::pitch);
  11502. const auto loaded = lynx::flVoiceLoadPreset (*frame, lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV"));
  11503. const auto& fl = engine.getSong().channels[2].sampler.flChannel;
  11504. check ("preset_load", loaded && fl.size() == 90 && fl[68 + 2] == 4000 && fl[68 + 14] == -70 && fl[68 + 16] == -40 && fl[88] == 96);
  11505. engine.undo();
  11506. check ("preset_load_undo", engine.getSong().channels[2].sampler.flChannel[68 + 14] != -70);
  11507. }
  11508. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  11509. return allOk;
  11510. }
  11511. // --flplshot (round 190dx): see the dispatch above
  11512. bool runFlPlShot (const juce::String& prefix)
  11513. {
  11514. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11515. juce::StringArray report;
  11516. bool allOk = true;
  11517. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  11518. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  11519. allOk = allOk && ok;
  11520. };
  11521. const auto plain = [] (juce::String t) {
  11522. // (without the shortcut column and the mnemonic: the mark, or the " (K)" a translation without the letter gets)
  11523. t = t.upToFirstOccurrenceOf ("\t", false, false);
  11524. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  11525. t = t.substring (0, at);
  11526. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  11527. };
  11528. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  11529. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  11530. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  11531. return it.getItem().subMenu.get();
  11532. return nullptr;
  11533. };
  11534. const auto texts = [&plain] (const juce::PopupMenu& menu, int count) {
  11535. juce::StringArray out;
  11536. for (juce::PopupMenu::MenuItemIterator it (menu); it.next() && out.size() < count;)
  11537. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  11538. return out;
  11539. };
  11540. const auto modelTexts = [] (const std::vector<lynx::fltrackmenus::Entry>& model) {
  11541. juce::StringArray out;
  11542. for (const auto& e : model)
  11543. if (e.kind != lynx::fltrackmenus::Entry::Kind::list)
  11544. out.add (e.kind == lynx::fltrackmenus::Entry::Kind::separator ? juce::String ("-")
  11545. : e.kind == lynx::fltrackmenus::Entry::Kind::caption ? "[" + lynx::tr (e.text) + "]"
  11546. : lynx::tr (e.text));
  11547. return out;
  11548. };
  11549. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  11550. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  11551. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  11552. {
  11553. it.getItem().action();
  11554. return true;
  11555. }
  11556. return false;
  11557. };
  11558. lynx::AudioEngine engine (false);
  11559. lynx::MainComponent ui (engine, false);
  11560. ui.setSize (1600, 900);
  11561. int vox = -1;
  11562. {
  11563. auto song = lynx::Song::makeDefault();
  11564. song.channels.push_back ({});
  11565. song.channels.back().name = "Vox";
  11566. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  11567. song.channels.back().volume = 0.6f;
  11568. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  11569. vox = (int) song.channels.size() - 1;
  11570. lynx::Clip c;
  11571. c.kind = lynx::ClipKind::audio;
  11572. c.channel = vox;
  11573. c.track = 3;
  11574. c.start = 4 * lynx::ppq;
  11575. c.length = 2 * lynx::ppq;
  11576. song.playlist.push_back (c);
  11577. engine.setSong (std::move (song));
  11578. }
  11579. engine.dispatchPendingMessages();
  11580. auto& playlist = ui.getPlaylistForSnapshot();
  11581. // ---- 1. the audio clip menu: Preview first, Automate › Panning / Volume
  11582. {
  11583. const auto menu = playlist.getClipMenuForSnapshot (0);
  11584. juce::PopupMenu::MenuItemIterator it (menu);
  11585. it.next(); // (the "Audio clip" title band)
  11586. it.next();
  11587. check ("clip_menu_preview_first", plain (it.getItem().text) == lynx::tr ("Preview"), it.getItem().text);
  11588. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  11589. check ("clip_menu_automate", automate != nullptr && texts (*automate, 9) == modelTexts (lynx::fltrackmenus::automate()),
  11590. automate != nullptr ? texts (*automate, 9).joinIntoString ("|") : juce::String ("missing"));
  11591. saveMenus (juce::StringArray { "Audio clip menu", "Automate" }, std::vector<juce::PopupMenu> { menu, automate != nullptr ? *automate : juce::PopupMenu() },
  11592. prefix + "-clip-menu.png");
  11593. const auto before = engine.getSong().automations.size();
  11594. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  11595. const auto& song = engine.getSong();
  11596. // (round 190dz: the Levels adjustment's volume multiplier, neutral = 0.5 of its 0…200 % travel)
  11597. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  11598. && song.automations.back().target.param == lynx::leveladjust::volume
  11599. && song.automations.back().target.index == vox && song.automations.back().points.size() == 2
  11600. && song.automations.back().points[1].tick == 2 * lynx::ppq && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  11601. const auto* clip = ok ? &song.playlist.back() : nullptr;
  11602. check ("automate_volume_clip", ok && clip->kind == lynx::ClipKind::automation && clip->track == 3 && clip->start == 4 * lynx::ppq
  11603. && clip->length == 2 * lynx::ppq,
  11604. ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  11605. engine.undo();
  11606. check ("automate_undo", engine.getSong().automations.size() == before);
  11607. // Preview: the clip's own audio (FL plays it through its channel); LYNX renders it for the preview output
  11608. const auto rendered = engine.renderClipAudio (0);
  11609. check ("preview_renders_the_clip", ! rendered.left.empty(), juce::String ((int) rendered.left.size()) + " frames");
  11610. }
  11611. // ---- 2. the Playlist's "+": its menu, a right click's audio track, the corner
  11612. {
  11613. const auto menu = playlist.getAddTrackMenuForSnapshot();
  11614. check ("add_menu_head", texts (menu, 5) == modelTexts (lynx::fltrackmenus::addTrack()), texts (menu, 5).joinIntoString ("|"));
  11615. saveMenus (juce::StringArray { "Playlist +" }, std::vector<juce::PopupMenu> { menu }, prefix + "-add-track-menu.png");
  11616. ui.selectTabForSnapshot (2);
  11617. engine.dispatchPendingMessages();
  11618. auto* button = playlist.getAddTrackButtonForSnapshot();
  11619. check ("add_button_in_corner", button != nullptr && button->isVisible() && button->getX() == 7 && button->getWidth() == 21 && button->getHeight() == 18
  11620. && button->getBottom() <= lynx::PlaylistComponent::headerHeight);
  11621. savePng (playlist.createComponentSnapshot (juce::Rectangle<int> (0, 0, juce::jmin (560, playlist.getWidth()), juce::jmin (260, playlist.getHeight()))),
  11622. prefix + "-playlist-corner.png");
  11623. const auto track = playlist.addAudioTrackNow();
  11624. const auto& song = engine.getSong();
  11625. check ("add_audio_track", track == 0 && song.playlistTracks.size() > 0 && song.playlistTracks[0].mode == lynx::PlaylistTrackMode::audio
  11626. && song.playlistTracks[0].mixerTrack > 0,
  11627. juce::String (track));
  11628. engine.undo();
  11629. }
  11630. // ---- 3. Track mode › Instrument track ›
  11631. {
  11632. const auto menu = playlist.getTrackMenuForSnapshot (5);
  11633. const auto* modes = findSub (menu, lynx::tr ("Track mode"));
  11634. const auto* instrument = modes != nullptr ? findSub (*modes, lynx::tr ("Instrument track")) : nullptr;
  11635. check ("instrument_track_head", instrument != nullptr && texts (*instrument, 4) == modelTexts (lynx::fltrackmenus::instrumentTrack()),
  11636. instrument != nullptr ? texts (*instrument, 4).joinIntoString ("|") : juce::String ("missing"));
  11637. const auto* existing = instrument != nullptr ? findSub (*instrument, lynx::tr ("Use existing channel")) : nullptr;
  11638. check ("use_existing_lists_generators", existing != nullptr && existing->getNumItems() == 5, existing != nullptr ? juce::String (existing->getNumItems()) : juce::String());
  11639. std::vector<juce::PopupMenu> menus { modes != nullptr ? *modes : juce::PopupMenu(), instrument != nullptr ? *instrument : juce::PopupMenu(),
  11640. existing != nullptr ? *existing : juce::PopupMenu() };
  11641. saveMenus (juce::StringArray { "Track mode", "Instrument track", "Use existing channel" }, menus, prefix + "-instrument-track-menu.png");
  11642. lynx::ChannelDef synth;
  11643. synth.name = "Lead";
  11644. synth.instrument = lynx::InstrumentKind::synth;
  11645. const auto channels = engine.getSong().channels.size();
  11646. int made = -1;
  11647. engine.editSong ([&] (lynx::Song& s) { made = lynx::trackmodes::addInstrumentTrack (s, synth, 5); });
  11648. check ("instrument_track_new_channel", made == (int) channels && engine.getSong().playlistTracks.size() > 5
  11649. && engine.getSong().playlistTracks[5].channel == made);
  11650. engine.undo();
  11651. }
  11652. // ---- 4. the Channel rack menu: Assign to new instrument track / Unassign
  11653. {
  11654. auto& rack = ui.getRackForSnapshot();
  11655. const auto menu = rack.getChannelMenuForSnapshot (1);
  11656. saveMenus (juce::StringArray { "Channel menu" }, std::vector<juce::PopupMenu> { menu }, prefix + "-channel-menu.png");
  11657. check ("assign_runs", click (menu, lynx::tr ("Assign to new instrument track")));
  11658. const auto tracks = lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1);
  11659. check ("assign_first_free_track", tracks == std::vector<int> { 0 }, juce::String (tracks.empty() ? -1 : tracks.front()));
  11660. const auto again = rack.getChannelMenuForSnapshot (1);
  11661. check ("unassign_offered", click (again, lynx::tr ("Unassign from instrument track")) && lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1).empty());
  11662. bool greyed = false;
  11663. const auto voxMenu = rack.getChannelMenuForSnapshot (vox);
  11664. for (juce::PopupMenu::MenuItemIterator it (voxMenu); it.next();)
  11665. if (plain (it.getItem().text) == plain (lynx::tr ("Assign to new instrument track")))
  11666. greyed = ! it.getItem().isEnabled;
  11667. check ("assign_greyed_for_audio_clip_channel", greyed);
  11668. }
  11669. // ---- 5. Tools › One-click audio recording
  11670. std::fprintf (stderr, "flplshot: tools\n");
  11671. {
  11672. const auto names = ui.getMenuNamesForSnapshot();
  11673. const auto tools = ui.getMenuForSnapshot (names.indexOf (lynx::tr ("Tools")));
  11674. const auto* oneClick = findSub (tools, lynx::tr ("One-click audio recording"));
  11675. check ("one_click_submenu", oneClick != nullptr && texts (*oneClick, 3) == modelTexts (lynx::fltrackmenus::oneClickRecording()),
  11676. oneClick != nullptr ? texts (*oneClick, 3).joinIntoString ("|") : juce::String ("missing"));
  11677. saveMenus (juce::StringArray { "Tools", "One-click audio recording" }, std::vector<juce::PopupMenu> { tools, oneClick != nullptr ? *oneClick : juce::PopupMenu() },
  11678. prefix + "-tools-one-click.png");
  11679. const auto plan = lynx::oneclick::plan (engine.getSong(), {}, 2, lynx::oneclick::Into::playlist);
  11680. check ("one_click_plan", plan.insert == 2 && plan.armInsert && plan.askInput && plan.songMode);
  11681. }
  11682. // ---- 6. Mixer › Disk recording › Latency compensation
  11683. {
  11684. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  11685. const auto menu = strips.buildMenu (1);
  11686. const auto* disk = findSub (menu, lynx::tr ("Disk recording"));
  11687. int after = -1, at = -1, i = 0;
  11688. bool ticked = false;
  11689. if (disk != nullptr)
  11690. for (juce::PopupMenu::MenuItemIterator it (*disk); it.next(); ++i)
  11691. {
  11692. if (plain (it.getItem().text) == plain (lynx::tr ("Auto-create audio clip (the rendered files go on the Playlist)")))
  11693. after = i;
  11694. if (plain (it.getItem().text) == plain (lynx::tr ("Latency compensation")))
  11695. {
  11696. at = i;
  11697. ticked = it.getItem().isTicked;
  11698. }
  11699. }
  11700. check ("latency_comp_item", disk != nullptr && after >= 0 && at == after + 1 && ticked && engine.getRecordOptions().latencyCompensation,
  11701. juce::String (after) + " " + juce::String (at));
  11702. saveMenus (juce::StringArray { "Disk recording" }, std::vector<juce::PopupMenu> { disk != nullptr ? *disk : juce::PopupMenu() },
  11703. prefix + "-disk-recording.png");
  11704. check ("latency_comp_toggles", disk != nullptr && click (*disk, lynx::tr ("Latency compensation")) && ! engine.getRecordOptions().latencyCompensation);
  11705. }
  11706. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  11707. return allOk;
  11708. }
  11709. // --flclipshot (round 190dz): see the dispatch above
  11710. // a menu as JUCE lays it out with explicit column breaks (PopupMenu::addColumnBreak): the columns side by side on
  11711. // one menu background; custom items (the title band) are painted by their own component
  11712. static juce::Image columnMenuImage (const juce::PopupMenu& menu)
  11713. {
  11714. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  11715. const auto border = lf.getPopupMenuBorderSize();
  11716. struct Row
  11717. {
  11718. const juce::PopupMenu::Item* item;
  11719. int height;
  11720. };
  11721. std::vector<std::vector<Row>> columns (1);
  11722. std::vector<int> widths (1, 160);
  11723. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  11724. {
  11725. const auto& item = it.getItem();
  11726. int w = 0, h = 0;
  11727. if (item.customComponent != nullptr)
  11728. item.customComponent->getIdealSize (w, h);
  11729. else
  11730. {
  11731. lf.getIdealPopupMenuItemSize (item.text.upToFirstOccurrenceOf ("\t", false, false), item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  11732. if (item.isSectionHeader)
  11733. h += h / 2; // as JUCE does
  11734. if (item.text.containsChar ('\t'))
  11735. w += 90;
  11736. }
  11737. columns.back().push_back ({ &item, h });
  11738. widths.back() = juce::jmax (widths.back(), w + 10);
  11739. if (item.shouldBreakAfter)
  11740. {
  11741. columns.emplace_back();
  11742. widths.push_back (160);
  11743. }
  11744. }
  11745. int width = 0, height = 0;
  11746. for (std::size_t c = 0; c < columns.size(); ++c)
  11747. {
  11748. width += widths[c];
  11749. int h = 2 * border;
  11750. for (const auto& row : columns[c])
  11751. h += row.height;
  11752. height = juce::jmax (height, h);
  11753. }
  11754. auto image = lynx::shot::canvas (width, height);
  11755. juce::Graphics g (image);
  11756. lynx::shot::logical (g);
  11757. lf.drawPopupMenuBackground (g, width, height);
  11758. int x = 0;
  11759. for (std::size_t c = 0; c < columns.size(); ++c)
  11760. {
  11761. int y = border;
  11762. for (const auto& row : columns[c])
  11763. {
  11764. const auto& item = *row.item;
  11765. const juce::Rectangle<int> r (x, y, widths[c], row.height);
  11766. if (item.customComponent != nullptr)
  11767. {
  11768. juce::Graphics::ScopedSaveState state (g);
  11769. g.setOrigin (r.getPosition());
  11770. item.customComponent->setSize (r.getWidth(), r.getHeight());
  11771. item.customComponent->paintEntireComponent (g, false);
  11772. }
  11773. else if (item.isSectionHeader)
  11774. lf.drawPopupMenuSectionHeader (g, r, item.text);
  11775. else
  11776. {
  11777. juce::Graphics::ScopedSaveState state (g);
  11778. g.setOrigin (r.getPosition());
  11779. lf.drawPopupMenuItem (g, r.withPosition (0, 0), item.isSeparator, item.isEnabled, false, item.isTicked, item.subMenu != nullptr,
  11780. item.text.upToFirstOccurrenceOf ("\t", false, false), item.text.fromFirstOccurrenceOf ("\t", false, false),
  11781. item.image.get(), nullptr);
  11782. }
  11783. y += row.height;
  11784. }
  11785. x += widths[c];
  11786. if (c + 1 < columns.size()) // (JUCE's column separator)
  11787. {
  11788. g.setColour (lf.findColour (juce::PopupMenu::textColourId).withAlpha (0.15f));
  11789. g.fillRect (x - 1, border, 1, height - 2 * border);
  11790. }
  11791. }
  11792. return image;
  11793. }
  11794. // --flfixshot (round 190ey): see the dispatch above
  11795. bool runFlFixShot (const juce::String& prefix)
  11796. {
  11797. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11798. juce::StringArray report;
  11799. bool allOk = true;
  11800. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  11801. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  11802. allOk = allOk && ok;
  11803. };
  11804. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  11805. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  11806. };
  11807. const auto plain = [] (juce::String t) {
  11808. t = t.upToFirstOccurrenceOf ("\t", false, false);
  11809. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  11810. t = t.substring (0, at);
  11811. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  11812. };
  11813. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  11814. juce::StringArray out;
  11815. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  11816. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  11817. return out;
  11818. };
  11819. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  11820. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  11821. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  11822. return it.getItem().subMenu.get();
  11823. return nullptr;
  11824. };
  11825. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  11826. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  11827. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  11828. {
  11829. it.getItem().action();
  11830. return true;
  11831. }
  11832. return false;
  11833. };
  11834. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flfix-samples");
  11835. folder.createDirectory();
  11836. const auto writeWav = [] (const juce::File& file, double rate, int frames, double hz) {
  11837. juce::AudioBuffer<float> buffer (1, frames);
  11838. for (int i = 0; i < frames; ++i)
  11839. buffer.setSample (0, i, (float) (0.8 * std::sin (juce::MathConstants<double>::twoPi * hz * i / rate) * std::exp (-i / (rate * 0.12))));
  11840. file.deleteFile();
  11841. juce::WavAudioFormat wav;
  11842. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), rate, 1, 16, {}, 0)))
  11843. out->writeFromAudioSampleBuffer (buffer, 0, frames);
  11844. return file;
  11845. };
  11846. // ---- 1. the Sampler page (SMP-1 / 4 / 5 / 7, CTL-4)
  11847. {
  11848. lynx::AudioEngine engine (false);
  11849. const auto clap = writeWav (folder.getChildFile ("Basic 808 Clap.wav"), 44100.0, 11600, 180.0);
  11850. const auto loop48 = writeWav (folder.getChildFile ("Loop 48k.wav"), 48000.0, 48000, 220.0);
  11851. engine.editSong ([&] (lynx::Song& s) {
  11852. if (s.channels.empty())
  11853. s.channels.resize (1);
  11854. lynx::audioclips::loadSampleInto (s.channels[0], clap.getFullPathName().toStdString(), "808 Clap");
  11855. });
  11856. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  11857. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  11858. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  11859. frame->createComponentSnapshot (frame->getLocalBounds());
  11860. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  11861. auto& f = *frame;
  11862. lynx::samplerPageTurn (f, "show", 0.0);
  11863. const auto rate = engine.getTransport().sampleRate.load();
  11864. check ("resample_greyed_at_project_rate", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 44100.0) < 0.5 ? "0" : "1"), juce::String (rate));
  11865. check ("load_regions_greyed_without_regions", lynx::samplerPageQuery (f, "loadRegions") == "0");
  11866. check ("load_markers_greyed_without_markers", lynx::samplerPageQuery (f, "loadMarkers") == "0");
  11867. check ("bit_depth_16", lynx::samplerPageQuery (f, "corner") == "16", lynx::samplerPageQuery (f, "corner"));
  11868. check ("wave_hint_summary", lynx::samplerPageQuery (f, "waveHint").startsWith ("44100Hz, 16Bit int mono, 0:263"), lynx::samplerPageQuery (f, "waveHint"));
  11869. shoot (f, "sampler-44k");
  11870. // SMP-5: MUL's text
  11871. lynx::samplerPageTurn (f, "mul", 800.0);
  11872. check ("mul_text", lynx::samplerPageQuery (f, "mulText") == "105.70%", lynx::samplerPageQuery (f, "mulText"));
  11873. lynx::samplerPageTurn (f, "mul", 0.0);
  11874. // SMP-4: CROSSFADE on a loopless sample: Use loop points on, the loop = the whole sample, the box reads 32
  11875. engine.editSong ([] (lynx::Song& s) { s.channels[0].sampler.useLoopPoints = false; });
  11876. lynx::samplerPageTurn (f, "crossfade", 120.0);
  11877. check ("crossfade_loops_whole_sample", sampler().useLoopPoints && sampler().loopStart == 0 && sampler().loopEnd == 11599,
  11878. juce::String (sampler().loopStart) + ".." + juce::String (sampler().loopEnd));
  11879. check ("bit_depth_32_precomputed", lynx::samplerPageQuery (f, "corner") == "32", lynx::samplerPageQuery (f, "corner"));
  11880. frame->createComponentSnapshot (frame->getLocalBounds());
  11881. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  11882. shoot (f, "sampler-crossfade-red-loop");
  11883. lynx::samplerPageTurn (f, "crossfade", 0.0);
  11884. // SMP-3: a loop set with END alone, drawn red (FL: 0..276)
  11885. engine.editSong ([] (lynx::Song& s) {
  11886. s.channels[0].sampler.loopStart = 0;
  11887. s.channels[0].sampler.loopEnd = 2400;
  11888. });
  11889. lynx::samplerPageTurn (f, "show", 0.0);
  11890. shoot (f, "sampler-end-loop-red");
  11891. // SMP-7: the waveform menu
  11892. const auto waveMenu = lynx::samplerWaveMenu (f);
  11893. const juce::StringArray expected { lynx::tr ("Reload"), lynx::tr ("Save as..."), lynx::tr ("Locate file"), lynx::tr ("Copy audio to clipboard"),
  11894. lynx::tr ("Paste audio from clipboard"), "-", lynx::tr ("Edit in audio editor"), "-",
  11895. lynx::tr ("Open in new sampler channel"), lynx::tr ("Open in new Fruity Granulizer channel"), "-",
  11896. lynx::tr ("Detect tempo") };
  11897. check ("wave_menu_items", waveMenu.has_value() && texts (*waveMenu) == expected, waveMenu.has_value() ? texts (*waveMenu).joinIntoString ("|") : juce::String ("none"));
  11898. if (waveMenu.has_value())
  11899. saveMenus (juce::StringArray { "Sampler waveform" }, std::vector<juce::PopupMenu> { *waveMenu }, prefix + "-wave-menu.png");
  11900. check ("copy_audio_to_clipboard", waveMenu.has_value() && click (*waveMenu, lynx::tr ("Copy audio to clipboard"))
  11901. && lynx::audioclipboard::editor().frames() == 11600);
  11902. // SMP-1: a 48 kHz sample in this project: Resample enabled
  11903. lynx::samplerPageTurn (f, "show", 0.0);
  11904. engine.editSong ([&] (lynx::Song& s) { s.channels[0].samplePath = loop48.getFullPathName().toStdString(); });
  11905. lynx::samplerPageTurn (f, "show", 0.0);
  11906. check ("resample_enabled_48k", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 48000.0) < 0.5 ? "0" : "1"), juce::String (rate));
  11907. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  11908. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  11909. shoot (f, "sampler-48k");
  11910. // CTL-4: Remove sample renames the channel "Sampler"
  11911. lynx::samplerFileRowPress (f, 3);
  11912. check ("remove_sample_renames", engine.getSong().channels[0].name == "Sampler" && engine.getSong().channels[0].samplePath.empty(),
  11913. juce::String::fromUTF8 (engine.getSong().channels[0].name.c_str()));
  11914. lynx::samplerPageTurn (f, "show", 0.0);
  11915. check ("no_sample_content_greyed", lynx::samplerPageQuery (f, "keepOnDisk") == "0" && lynx::samplerPageQuery (f, "resample") == "0");
  11916. shoot (f, "sampler-removed");
  11917. }
  11918. // ---- 2. the Multilink button's menu with multilink off (CTL-1)
  11919. lynx::AudioEngine engine (false);
  11920. lynx::MainComponent ui (engine, false);
  11921. ui.setSize (1600, 900);
  11922. {
  11923. using lynx::AutomationTarget;
  11924. using lynx::AutomationTargetKind;
  11925. engine.editSong ([] (lynx::Song& s) {
  11926. if (s.channels.empty())
  11927. s.channels.resize (1);
  11928. s.channels[0].name = "808 Kick";
  11929. });
  11930. engine.setMultilink (false);
  11931. engine.noteTweaked ({ AutomationTargetKind::channelVolume, 0 });
  11932. engine.noteTweaked ({ AutomationTargetKind::channelPan, 0 });
  11933. const auto menu = ui.getMultilinkMenuForSnapshot();
  11934. juce::PopupMenu::MenuItemIterator first (menu);
  11935. first.next();
  11936. const auto caption = first.getItem().text;
  11937. bool columnBreak = false, lynxLines = false;
  11938. juce::String rightCaption;
  11939. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  11940. {
  11941. if (columnBreak && rightCaption.isEmpty() && it.getItem().isSectionHeader)
  11942. rightCaption = it.getItem().text;
  11943. columnBreak = columnBreak || it.getItem().shouldBreakAfter;
  11944. lynxLines = lynxLines || it.getItem().text == lynx::tr ("Link to controller");
  11945. }
  11946. check ("ml_off_left_column_named", first.getItem().isSectionHeader && caption == lynx::describeAutomationTarget (engine, { AutomationTargetKind::channelPan, 0 }), caption);
  11947. check ("ml_off_two_columns", columnBreak && rightCaption == lynx::tr ("Last 2 tweaked parameters"), rightCaption);
  11948. check ("ml_off_no_lynx_greyed_lines", ! lynxLines);
  11949. savePng (columnMenuImage (menu), prefix + "-multilink-off-menu.png");
  11950. }
  11951. // ---- 3. the Playlist (PL-1 / 2 / 3 / 6 / 7 / 8)
  11952. auto& playlist = ui.getPlaylistForSnapshot();
  11953. {
  11954. auto song = lynx::Song::makeDefault();
  11955. lynx::ChannelDef bass;
  11956. bass.name = "Amount Too - Bass";
  11957. bass.instrument = lynx::InstrumentKind::audioClip;
  11958. bass.samplePath = writeWav (folder.getChildFile ("bass.wav"), 44100.0, 88200, 82.0).getFullPathName().toStdString();
  11959. bass.misc.levels.volume = 1.468f;
  11960. song.channels.push_back (bass);
  11961. lynx::Clip c;
  11962. c.kind = lynx::ClipKind::audio;
  11963. c.channel = (int) song.channels.size() - 1;
  11964. c.track = 3;
  11965. c.start = 4 * lynx::ppq;
  11966. c.length = 2 * lynx::ppq;
  11967. song.playlist.push_back (c);
  11968. engine.setSong (std::move (song));
  11969. }
  11970. engine.dispatchPendingMessages();
  11971. const auto clipIndex = (int) engine.getSong().playlist.size() - 1;
  11972. {
  11973. const auto menu = playlist.getClipMenuForSnapshot (clipIndex);
  11974. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  11975. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  11976. const auto& song = engine.getSong();
  11977. const auto made = (int) song.automations.size() - 1;
  11978. check ("automate_makes_current_clip", made >= 0 && playlist.brush.kind == lynx::ClipKind::automation && playlist.brush.index == made,
  11979. juce::String (playlist.brush.index));
  11980. // (PL-2: Levels VOL 147 %, FL's clip plays unity)
  11981. check ("automate_volume_unity", made >= 0 && song.automations.back().points[0].value == 0.5f
  11982. && lynx::lasttweak::valueText (song, song.automations.back().target, song.automations.back().points[0].value) == "100% 0.0dB 1.00");
  11983. const auto again = playlist.getClipMenuForSnapshot (clipIndex);
  11984. const auto* automate2 = findSub (again, lynx::tr ("Automate"));
  11985. check ("automate_second_is_2", automate2 != nullptr && click (*automate2, lynx::tr ("Volume"))
  11986. && juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()).endsWith (" #2"),
  11987. juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()));
  11988. // PL-7: Fade in / out curve
  11989. const auto* fadeIn = findSub (menu, lynx::tr ("Fade in curve"));
  11990. const auto* fadeOut = findSub (menu, lynx::tr ("Fade out curve"));
  11991. const juce::StringArray curve { lynx::tr ("Reset"), lynx::tr ("Normalize"), lynx::tr ("Normalize selection as a group"), lynx::tr ("Create crossfade"),
  11992. lynx::tr ("Manual"), "[" + lynx::tr ("Declicker") + "]", lynx::tr ("Automatic"), lynx::tr ("Disabled"), lynx::tr ("Enabled"),
  11993. "[" + lynx::tr ("Curve shape") + "]", lynx::tr ("Smooth curve"), lynx::tr ("Single curve") };
  11994. check ("fade_curve_submenus", fadeIn != nullptr && fadeOut != nullptr && texts (*fadeIn) == curve && texts (*fadeOut) == curve,
  11995. fadeIn != nullptr ? texts (*fadeIn).joinIntoString ("|") : juce::String ("missing"));
  11996. if (fadeOut != nullptr)
  11997. saveMenus (juce::StringArray { "Audio clip menu", "Fade out curve" }, std::vector<juce::PopupMenu> { menu, *fadeOut }, prefix + "-fade-curve-menu.png");
  11998. // PL-8: Detect tempo is one item now
  11999. bool detectItem = false;
  12000. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  12001. if (plain (it.getItem().text) == plain (lynx::tr ("Detect tempo")))
  12002. detectItem = it.getItem().subMenu == nullptr && it.getItem().action != nullptr;
  12003. check ("detect_tempo_item", detectItem);
  12004. // PL-3: Preview through the channel; transport start ends it
  12005. check ("preview_through_channel", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  12006. engine.play();
  12007. check ("preview_stops_on_transport", ! engine.isClipPreviewing());
  12008. engine.stop();
  12009. check ("preview_again_then_stop", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  12010. engine.stop();
  12011. check ("preview_stops_on_stop", ! engine.isClipPreviewing());
  12012. }
  12013. // PL-8: the dialog
  12014. {
  12015. lynx::ui::TempoDetectionRequest r;
  12016. r.name = "Amount Too - Bass";
  12017. // (a drum-like loop at 117.5 BPM, 100 beats as in FL's dialog: clicks on every beat)
  12018. {
  12019. auto beats = std::make_shared<lynx::SampleData>();
  12020. beats->sampleRate = 44100.0;
  12021. const auto period = 44100.0 * 60.0 / 117.5;
  12022. beats->left.assign ((std::size_t) std::llround (period * 100.0), 0.0f);
  12023. for (int b = 0; b < 100; ++b)
  12024. for (int i = 0; i < 2000; ++i)
  12025. if (const auto at = (std::size_t) std::llround (b * period) + (std::size_t) i; at < beats->left.size())
  12026. beats->left[at] = (float) (0.9 * std::sin (i * 0.09) * std::exp (-i / 400.0));
  12027. r.sample = beats;
  12028. }
  12029. r.projectBpm = 100.0;
  12030. double applied = -1.0;
  12031. r.apply = [&applied] (double beats) { applied = beats; };
  12032. auto panel = lynx::ui::makeTempoDetectionPanel (r);
  12033. panel->setSize (panel->getWidth(), panel->getHeight());
  12034. shoot (*panel, "tempo-detection");
  12035. report.add ("tempo dialog title: " + lynx::ui::tempoDetectionTitle (r.name));
  12036. const auto project = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 3);
  12037. const auto seconds = (double) r.sample->frames() / r.sample->sampleRate; // (100 beats at 117.5 BPM)
  12038. check ("tempo_project_button", std::abs (applied - seconds * 100.0 / 60.0) < 1.0e-6, project + " -> " + juce::String (applied));
  12039. const auto none = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 2);
  12040. check ("tempo_no_tempo_button", applied == 0.0, none);
  12041. }
  12042. // ---- 4. issue #152's question (ISS152-1): FL's message with "Remember my choice"
  12043. {
  12044. auto box = lynx::makeFlMessageDialog ({ lynx::tr ("External input"),
  12045. lynx::tr ("You've selected an external input. Do you want to switch to |External input only| to avoid recording internal audio on this track?"),
  12046. { lynx::tr ("Yes"), lynx::tr ("No") }, true });
  12047. shoot (*box, "external-input-question");
  12048. bool listed = false;
  12049. for (const auto& m : lynx::messages::all())
  12050. listed = listed || juce::String (m.id) == "RecAutoSwitchExternalInput";
  12051. check ("external_input_in_manage_messages", listed);
  12052. }
  12053. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  12054. return allOk;
  12055. }
  12056. bool runFlClipShot (const juce::String& prefix)
  12057. {
  12058. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12059. juce::StringArray report;
  12060. bool allOk = true;
  12061. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  12062. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  12063. allOk = allOk && ok;
  12064. };
  12065. const auto plain = [] (juce::String t) {
  12066. t = t.upToFirstOccurrenceOf ("\t", false, false);
  12067. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  12068. t = t.substring (0, at);
  12069. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  12070. };
  12071. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  12072. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  12073. if (plain (it.getItem().text) == plain (text))
  12074. return &it.getItem();
  12075. return nullptr;
  12076. };
  12077. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  12078. const auto* item = find (menu, text);
  12079. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  12080. return false;
  12081. item->action();
  12082. return true;
  12083. };
  12084. lynx::AudioEngine engine (false);
  12085. lynx::MainComponent ui (engine, false);
  12086. ui.setSize (1600, 900);
  12087. int vox = -1;
  12088. {
  12089. auto song = lynx::Song::makeDefault();
  12090. song.channels.push_back ({});
  12091. song.channels.back().name = "Vox";
  12092. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  12093. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  12094. vox = (int) song.channels.size() - 1;
  12095. lynx::Clip c;
  12096. c.kind = lynx::ClipKind::audio;
  12097. c.channel = vox;
  12098. c.track = 3;
  12099. c.start = 4 * lynx::ppq;
  12100. c.length = 2 * lynx::ppq;
  12101. c.fadeIn = lynx::ppq / 4;
  12102. song.playlist.push_back (c);
  12103. engine.setSong (std::move (song));
  12104. }
  12105. engine.dispatchPendingMessages();
  12106. auto& playlist = ui.getPlaylistForSnapshot();
  12107. // ---- 1. the audio clip menu: FL's order, sections and columns, then LYNX's own items
  12108. {
  12109. const auto menu = playlist.getClipMenuForSnapshot (0);
  12110. juce::StringArray got, want;
  12111. int breakAfter = -1;
  12112. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  12113. {
  12114. const auto& item = it.getItem();
  12115. got.add (item.customComponent != nullptr ? "[" + lynx::tr ("Audio clip") + "]"
  12116. : item.isSeparator ? juce::String ("-")
  12117. : item.isSectionHeader ? "[" + plain (item.text) + "]"
  12118. : plain (item.text));
  12119. if (item.shouldBreakAfter)
  12120. breakAfter = got.size() - 1;
  12121. }
  12122. for (const auto& e : lynx::flclipmenu::shown (true, false))
  12123. if (e.kind != lynx::flclipmenu::Entry::Kind::columnBreak)
  12124. want.add (e.kind == lynx::flclipmenu::Entry::Kind::separator ? juce::String ("-")
  12125. : e.kind == lynx::flclipmenu::Entry::Kind::header ? "[" + lynx::tr (e.text.c_str()) + "]"
  12126. : lynx::tr (e.text.c_str()));
  12127. want.add ("-");
  12128. for (const auto& x : lynx::flclipmenu::lynxExtras())
  12129. want.add (lynx::tr (x.c_str()));
  12130. check ("clip_menu_fl_order", got == want, got.joinIntoString ("|"));
  12131. check ("clip_menu_two_columns", breakAfter >= 0 && got[breakAfter] == lynx::tr ("Chop") && got[breakAfter + 1] == "[" + lynx::tr ("Sample") + "]",
  12132. juce::String (breakAfter));
  12133. const auto* crossfade = find (menu, lynx::tr ("Crossfade with"));
  12134. check ("crossfade_with_greyed", crossfade != nullptr && ! crossfade->isEnabled);
  12135. const auto* region = find (menu, lynx::tr ("Select region"));
  12136. const auto* full = region != nullptr && region->subMenu != nullptr ? find (*region->subMenu, lynx::tr ("Full")) : nullptr;
  12137. check ("select_region_full_ticked", full != nullptr && full->isTicked);
  12138. const auto* chop = find (menu, lynx::tr ("Chop"));
  12139. check ("chop_time_based", chop != nullptr && chop->subMenu != nullptr && find (*chop->subMenu, lynx::tr ("Chop in 32nd beats")) != nullptr
  12140. && find (*chop->subMenu, lynx::tr ("Chop to grid")) != nullptr);
  12141. savePng (columnMenuImage (menu), prefix + "-clip-menu.png");
  12142. std::fprintf (stderr, "flclipshot: menu saved\n");
  12143. // Muted is a check; Reset fades clears the fades; Select all similar clips selects
  12144. check ("muted_toggles", click (menu, lynx::tr ("Muted")) && engine.getSong().playlist[0].muted);
  12145. const auto again = playlist.getClipMenuForSnapshot (0);
  12146. const auto* muted = find (again, lynx::tr ("Muted"));
  12147. check ("muted_ticked", muted != nullptr && muted->isTicked);
  12148. check ("reset_fades", click (again, lynx::tr ("Reset fades")) && engine.getSong().playlist[0].fadeIn == 0);
  12149. engine.undo();
  12150. engine.undo();
  12151. engine.dispatchPendingMessages();
  12152. std::fprintf (stderr, "flclipshot: automate\n");
  12153. // Automate › Volume / Panning: the clip channel's Levels adjustment (FL's channel parameters 0x11 / 0x10)
  12154. const auto fresh = playlist.getClipMenuForSnapshot (0);
  12155. const auto* automate = find (fresh, lynx::tr ("Automate"));
  12156. const auto before = engine.getSong().automations.size();
  12157. check ("automate_volume_runs", automate != nullptr && automate->subMenu != nullptr && click (*automate->subMenu, lynx::tr ("Volume")));
  12158. const auto& song = engine.getSong();
  12159. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  12160. && song.automations.back().target.param == lynx::leveladjust::volume && song.automations.back().target.index == vox
  12161. && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  12162. check ("automate_volume_is_level_adjust", ok, ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  12163. engine.undo();
  12164. engine.dispatchPendingMessages();
  12165. }
  12166. std::fprintf (stderr, "flclipshot: overlap\n");
  12167. // ---- 2. a second channel's clip overlapping: Crossfade with leaves (FL would enable it; LYNX lacks it)
  12168. {
  12169. engine.editSong ([vox] (lynx::Song& s) {
  12170. auto copy = s.playlist[0]; // (another audio clip channel's clip, at the same time)
  12171. s.channels.push_back (s.channels[(std::size_t) vox]);
  12172. s.channels.back().name = "Vox 2";
  12173. copy.channel = (int) s.channels.size() - 1;
  12174. copy.track = 4;
  12175. s.playlist.push_back (copy);
  12176. });
  12177. engine.dispatchPendingMessages();
  12178. const auto overlapped = playlist.getClipMenuForSnapshot (0);
  12179. check ("crossfade_with_left_out_when_fl_enables", find (overlapped, lynx::tr ("Crossfade with")) == nullptr);
  12180. engine.undo();
  12181. engine.dispatchPendingMessages();
  12182. }
  12183. std::fprintf (stderr, "flclipshot: misc\n");
  12184. // ---- 3. the channel's Misc tab: Levels adjustment = the offsets (pan 0, volume 100 %, Mod X / Y 0 %)
  12185. {
  12186. engine.editSong ([vox] (lynx::Song& s) {
  12187. s.channels[(std::size_t) vox].misc.levels.volume = 0.5f;
  12188. s.channels[(std::size_t) vox].misc.levels.pan = -0.25f;
  12189. });
  12190. engine.dispatchPendingMessages();
  12191. auto frame = lynx::makeChannelFrame (engine, vox, -1);
  12192. frame->setSize (juce::jmax (frame->getWidth(), 800), juce::jmax (frame->getHeight(), 420));
  12193. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-misc-levels.png");
  12194. auto synthFrame = lynx::makeChannelFrame (engine, 0, -1);
  12195. synthFrame->setSize (juce::jmax (synthFrame->getWidth(), 800), juce::jmax (synthFrame->getHeight(), 420));
  12196. savePng (synthFrame->createComponentSnapshot (synthFrame->getLocalBounds()), prefix + "-misc-levels-ch1.png");
  12197. std::fprintf (stderr, "flclipshot: round trip\n");
  12198. // the .lynx round trip of the adjustment and of an automation of it; an old project writes nothing new
  12199. juce::String error;
  12200. auto song = engine.getSong();
  12201. lynx::Automation a;
  12202. a.target = { lynx::AutomationTargetKind::channelAdjust, vox, 0, lynx::leveladjust::volume };
  12203. a.points = { { 0, 0.25f, 0.0f } };
  12204. song.automations.push_back (a);
  12205. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  12206. check ("lynx_round_trip", back && back->channels[(std::size_t) vox].misc.levels == song.channels[(std::size_t) vox].misc.levels
  12207. && back->automations.back().target == a.target,
  12208. error);
  12209. auto old = lynx::Song::makeDefault();
  12210. const auto json = lynx::ProjectFile::toJson (old, false);
  12211. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  12212. check ("old_project_unchanged", ! json.contains ("\"levels\"") && reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json
  12213. && std::all_of (reloaded->channels.begin(), reloaded->channels.end(),
  12214. [] (const lynx::ChannelDef& c) { return c.misc.levels.neutral(); }));
  12215. }
  12216. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  12217. return allOk;
  12218. }
  12219. // --bandlabshot <prefix> (round 190ch): the Lyrics / Notes panel (Pattern and Simple layouts, and on its own), the
  12220. // Reference match window measured on a real render and a real file, "Start from", and Clean voice, off-screen; and
  12221. // <prefix>-report.txt with what each route did (ok / FAIL lines)
  12222. void runBandlabShot (const juce::String& prefix)
  12223. {
  12224. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12225. lynx::AudioEngine offline (false);
  12226. lynx::MainComponent ui (offline, false);
  12227. ui.setSize (1600, 900);
  12228. // (each step is named on stderr as it starts: a run that stops says where)
  12229. const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlabshot: %s\n", what.toRawUTF8()); };
  12230. const auto shoot = [&prefix, &note] (juce::Component& c, const char* name) {
  12231. note (name);
  12232. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  12233. };
  12234. juce::String report;
  12235. const auto check = [&report, &note] (const juce::String& what, bool ok) {
  12236. note ((ok ? "ok " : "FAIL ") + what);
  12237. report << (ok ? "ok " : "FAIL ") << what << "\n";
  12238. };
  12239. const auto bar = (double) lynx::ppq * 4.0;
  12240. // ---- 1. Lyrics / Notes: the project's Comments
  12241. {
  12242. auto song = lynx::makeShowcaseSong (0);
  12243. song.info.title = "Night Drive";
  12244. song.info.comments = "[Intro]\n\n[5] [Verse 1]\n[5] Headlights on the empty road\n[7] Radio is playing low\n[9] Every sign says slow\n"
  12245. "I keep driving through the night\n\n[Chorus]\nNight drive, night drive\nNothing but the white line\n\n"
  12246. "Notes: double the chorus vocal, try the second verse an octave down.";
  12247. lynx::Marker chorus;
  12248. chorus.tick = (std::int64_t) (12.0 * bar);
  12249. chorus.name = "Chorus";
  12250. song.addMarker (chorus);
  12251. offline.setSong (std::move (song));
  12252. }
  12253. note ("song set");
  12254. offline.dispatchPendingMessages();
  12255. ui.selectTabForSnapshot (2);
  12256. note ("show lyrics");
  12257. ui.showLyrics (false);
  12258. note ("lyrics shown");
  12259. if (auto* panel = ui.getLyricsPanelForSnapshot())
  12260. {
  12261. panel->showForSnapshot ({}, 6.5 * bar); // the playhead inside bar 7: that line is the one playing
  12262. shoot (ui, "lyrics-pattern");
  12263. shoot (*panel, "lyrics-panel");
  12264. const auto markersBefore = offline.getSong().markers().size();
  12265. panel->setCaretLineForSnapshot (6); // "I keep driving through the night"
  12266. panel->markAtPlayheadForSnapshot (10.0 * bar + 2.0 * lynx::ppq);
  12267. offline.dispatchPendingMessages();
  12268. ui.commitSongNotes();
  12269. const auto& s = offline.getSong();
  12270. check ("Marker at playhead stamps the line [11.3] and adds one marker",
  12271. juce::String::fromUTF8 (s.info.comments.c_str()).contains ("[11.3] I keep driving") && s.markers().size() == markersBefore + 1);
  12272. // (no audio device here: the seek is the request the audio thread takes at its next block)
  12273. const auto& seek = offline.getTransport().seekRequest;
  12274. check ("clicking the stamped line moves the playhead to bar 7", panel->jumpToLineForSnapshot (4) && std::abs (seek.load() - 6.0 * bar) < 1.0);
  12275. check ("clicking [Chorus] (no position) goes to the marker of that name, bar 13",
  12276. panel->jumpToLineForSnapshot (8) && std::abs (seek.load() - 12.0 * bar) < 1.0);
  12277. check ("a line without a position does not jump", ! panel->jumpToLineForSnapshot (9));
  12278. panel->showForSnapshot ("night", 10.5 * bar);
  12279. shoot (*panel, "lyrics-search");
  12280. // the text travels in the project file, and old readers see it as the Comments they always had
  12281. juce::String error;
  12282. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  12283. const auto back = lynx::ProjectFile::fromJson (json, error);
  12284. check ("lyrics round-trip through .lynx (the Comments field)", back.has_value() && back->info.comments == offline.getSong().info.comments);
  12285. const auto text = lynx::lyrics::exportText (offline.getSong(), lynx::lyrics::Stamps::times);
  12286. juce::File (prefix + "-lyrics-export.txt").replaceWithText (juce::String::fromUTF8 (text.c_str()));
  12287. check ("export as text with times", text.find ("[0:") != std::string::npos);
  12288. panel->showForSnapshot ({}, 6.5 * bar);
  12289. }
  12290. else
  12291. check ("the docked Lyrics panel exists", false);
  12292. {
  12293. const auto names = ui.getMenuNamesForSnapshot();
  12294. const auto view = names.indexOf (lynx::tr ("View"));
  12295. saveMenus (juce::StringArray { lynx::tr ("View") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (juce::jmax (0, view)) }, prefix + "-menu-view.png");
  12296. }
  12297. ui.showDesktopForSnapshot (false);
  12298. check ("the panel stays docked beside the Playlist in the default desktop", ui.isLyricsShowing());
  12299. shoot (ui, "lyrics-desktop");
  12300. // ---- the Simple layout: the Lyrics button in its title tools, the chooser's "Start from" link
  12301. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  12302. offline.dispatchPendingMessages();
  12303. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  12304. auto* simple = ui.getSimpleWorkflowForSnapshot();
  12305. check ("the Simple workflow exists", simple != nullptr);
  12306. if (simple != nullptr)
  12307. {
  12308. simple->hideChooser();
  12309. if (! ui.isLyricsShowing())
  12310. ui.showLyrics (false);
  12311. shoot (ui, "lyrics-simple");
  12312. ui.hideLyrics();
  12313. check ("closing the panel keeps the text", juce::String::fromUTF8 (offline.getSong().info.comments.c_str()).contains ("Night drive, night drive"));
  12314. // ---- 4. Clean voice: on a voice track, from the track's menu
  12315. lynx::simpletracks::Result voice;
  12316. offline.editSongStructural ([&voice] (lynx::Song& s) {
  12317. lynx::simpletracks::Request q;
  12318. q.kind = lynx::simpletracks::Kind::voice;
  12319. q.name = "Lead vocal";
  12320. voice = lynx::simpletracks::addTrack (s, q);
  12321. });
  12322. offline.dispatchPendingMessages();
  12323. check ("a voice track was added", voice.insert > 0);
  12324. if (voice.insert > 0)
  12325. {
  12326. auto menu = ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (voice.track);
  12327. juce::StringArray names { "Track" };
  12328. std::vector<juce::PopupMenu> menus { menu };
  12329. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  12330. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Clean voice"))
  12331. {
  12332. names.add (lynx::tr ("Clean voice"));
  12333. menus.push_back (*it.getItem().subMenu);
  12334. }
  12335. check ("the Simple track menu has Clean voice", menus.size() == 2);
  12336. saveMenus (names, menus, prefix + "-cleanvoice-menu.png");
  12337. const auto before = offline.getSong().mixer[(std::size_t) voice.insert].effects.size();
  12338. check ("Clean voice applies", lynx::ui::applyCleanVoice (offline, voice.insert, false));
  12339. offline.dispatchPendingMessages();
  12340. const auto& fx = offline.getSong().mixer[(std::size_t) voice.insert].effects;
  12341. check ("four slots in front of the track's effects", fx.size() == before + 4 && lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4
  12342. && fx[0].kind == lynx::EffectKind::facetEq);
  12343. check ("with noise reduction: five, none doubled", lynx::ui::applyCleanVoice (offline, voice.insert, true)
  12344. && offline.getSong().mixer[(std::size_t) voice.insert].effects.size() == before + 5);
  12345. offline.dispatchPendingMessages();
  12346. juce::String error;
  12347. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  12348. check ("the chain round-trips through .lynx and is still found", back.has_value() && lynx::cleanvoice::slotsOf (*back, voice.insert).size() == 5
  12349. && back->mixer[(std::size_t) voice.insert].effects == offline.getSong().mixer[(std::size_t) voice.insert].effects);
  12350. saveMenus (juce::StringArray { lynx::tr ("Clean voice") }, std::vector<juce::PopupMenu> { lynx::ui::cleanVoiceMenu (offline, voice.insert) },
  12351. prefix + "-cleanvoice-menu-on.png");
  12352. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  12353. offline.dispatchPendingMessages();
  12354. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  12355. ui.selectMixerTrackForSnapshot (voice.insert);
  12356. shoot (ui, "cleanvoice-mixer");
  12357. offline.undo(); // the second chain
  12358. offline.dispatchPendingMessages();
  12359. check ("undo brings the first chain back", lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4);
  12360. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  12361. offline.dispatchPendingMessages();
  12362. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  12363. simple = ui.getSimpleWorkflowForSnapshot();
  12364. }
  12365. }
  12366. // ---- 2. Reference match: the song's Master render against a file (pink noise with more top, at about -14 LUFS)
  12367. {
  12368. const auto file = juce::File (prefix + "-reference.wav");
  12369. file.deleteFile();
  12370. const auto rate = 44100.0;
  12371. const auto frames = (int) (20.0 * rate);
  12372. juce::AudioBuffer<float> audio (2, frames);
  12373. juce::Random random (190);
  12374. for (int ch = 0; ch < 2; ++ch)
  12375. {
  12376. double b0 = 0, b1 = 0, b2 = 0, hp = 0;
  12377. for (int i = 0; i < frames; ++i)
  12378. {
  12379. const auto w = (double) random.nextFloat() * 2.0 - 1.0;
  12380. b0 = 0.99765 * b0 + w * 0.0990460;
  12381. b1 = 0.96300 * b1 + w * 0.2965164;
  12382. b2 = 0.57000 * b2 + w * 1.0526913;
  12383. const auto pink = (b0 + b1 + b2 + w * 0.1848) * 0.071; // (about -14 LUFS: a streaming master)
  12384. hp += 0.25 * (pink - hp); // a little more top than pink noise has
  12385. audio.setSample (ch, i, (float) (pink + 0.35 * (pink - hp)));
  12386. }
  12387. }
  12388. if (auto out = file.createOutputStream())
  12389. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 24, {}, 0)))
  12390. {
  12391. out.release();
  12392. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  12393. }
  12394. note ("measure reference");
  12395. const auto reference = lynx::ReferenceMatchPanel::measureFile (offline, file);
  12396. note ("measure song");
  12397. const auto song = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), false);
  12398. check ("the reference file was measured", reference.valid);
  12399. check ("the song's Master render was measured", song.valid);
  12400. lynx::ReferenceMatchPanel panel (offline, {});
  12401. panel.setSize (lynx::ReferenceMatchPanel::defaultWidth, lynx::ReferenceMatchPanel::defaultHeight);
  12402. panel.showForSnapshot ("Reference.wav", song, reference, nullptr);
  12403. shoot (panel, "refmatch-measured");
  12404. const auto masterBefore = offline.getSong().mixer[0].effects.size();
  12405. check ("Match adds its two slots at the end of the Master", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  12406. offline.dispatchPendingMessages();
  12407. const auto first = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  12408. panel.showForSnapshot ("Reference.wav", song, reference, &first);
  12409. panel.refresh();
  12410. shoot (panel, "refmatch-matched");
  12411. report << " first Match: " << juce::String (first.lufs, 2) << " LUFS, " << juce::String (first.truePeakDb, 2) << " dBTP, EQ output "
  12412. << juce::String (lynx::facet::outputDb (offline.getSong().mixer[0].effects[masterBefore].params[(std::size_t) lynx::facet::outputParam]), 2) << " dB\n";
  12413. // a result more than 0.5 LU from the reference (a limiter that has to hold peaks back): Match again takes
  12414. // what is missing, as the window's note says
  12415. auto after = first;
  12416. const auto secondPass = std::abs (first.lufs - reference.lufs) > 0.5;
  12417. if (secondPass)
  12418. {
  12419. check ("Match again replaces the two slots (level corrected)", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  12420. offline.dispatchPendingMessages();
  12421. after = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  12422. panel.showForSnapshot ("Reference.wav", song, reference, &after);
  12423. panel.refresh();
  12424. shoot (panel, "refmatch-matched-again");
  12425. }
  12426. report << " " << (secondPass ? "a second Match was needed for the level" : "one Match was enough for the level") << "\n";
  12427. const auto& s = panel.suggestionForSnapshot();
  12428. report << " song " << juce::String (song.lufs, 2) << " LUFS, " << juce::String (song.truePeakDb, 2) << " dBTP, width " << juce::String (song.widthPercent(), 1)
  12429. << " % | reference " << juce::String (reference.lufs, 2) << " LUFS, " << juce::String (reference.truePeakDb, 2) << " dBTP, width "
  12430. << juce::String (reference.widthPercent(), 1) << " % | after " << juce::String (after.lufs, 2) << " LUFS, " << juce::String (after.truePeakDb, 2)
  12431. << " dBTP\n next suggestion: gain " << juce::String (s.gainDb, 2) << " dB, EQ fit error " << juce::String (s.fitErrorDb, 2) << " dB\n";
  12432. double before = 0.0, now = 0.0;
  12433. int counted = 0;
  12434. {
  12435. // tone only (each curve around its own mean), over the bands both hold
  12436. double ms = 0, mr = 0, ma = 0;
  12437. const auto used = juce::jmin (song.usedBands, reference.usedBands);
  12438. for (int k = 0; k < used; ++k)
  12439. ms += song.spectrumDb[(std::size_t) k], mr += reference.spectrumDb[(std::size_t) k], ma += after.spectrumDb[(std::size_t) k];
  12440. for (int k = 2; k < used; ++k, ++counted)
  12441. {
  12442. before += std::abs ((song.spectrumDb[(std::size_t) k] - ms / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  12443. now += std::abs ((after.spectrumDb[(std::size_t) k] - ma / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  12444. }
  12445. }
  12446. report << " mean tone difference to the reference: " << juce::String (before / juce::jmax (1, counted), 2) << " dB before, "
  12447. << juce::String (now / juce::jmax (1, counted), 2) << " dB after one Match (each band moves 6 dB at most)\n";
  12448. check ("after Match the tone is closer to the reference", after.valid && now < before);
  12449. check ("after Match the loudness is within 1 LU of the reference", std::abs (after.lufs - reference.lufs) < 1.0);
  12450. check ("the limiter holds the peaks: under 0 dBTP, within 0.6 dB of its -1 dB ceiling", after.truePeakDb < 0.0 && after.truePeakDb <= -1.0 + 0.6);
  12451. juce::String error;
  12452. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  12453. check ("the match round-trips through .lynx as two ordinary Master slots", back.has_value() && lynx::refmatch::present (*back)
  12454. && back->mixer[0].effects == offline.getSong().mixer[0].effects);
  12455. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  12456. offline.dispatchPendingMessages();
  12457. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  12458. ui.selectMixerTrackForSnapshot (0);
  12459. shoot (ui, "refmatch-mixer");
  12460. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  12461. offline.dispatchPendingMessages();
  12462. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  12463. simple = ui.getSimpleWorkflowForSnapshot();
  12464. if (simple != nullptr)
  12465. {
  12466. simple->hideChooser();
  12467. simple->showFinish();
  12468. shoot (ui, "finish-dock"); // "Match a reference track..." under the saving buttons
  12469. simple->hideFinish();
  12470. }
  12471. file.deleteFile();
  12472. }
  12473. // ---- 3. Start from: the chooser's link, the list, and opening an entry
  12474. if (simple != nullptr)
  12475. {
  12476. simple->showChooser();
  12477. shoot (ui, "chooser");
  12478. simple->hideChooser();
  12479. auto* panel = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot());
  12480. check ("the Start from list opens", panel != nullptr && simple->isStartFromShowing());
  12481. if (panel != nullptr)
  12482. {
  12483. shoot (ui, "startfrom");
  12484. auto list = lynx::startfrom::entries();
  12485. check ("it lists the demo song and the templates shipped", list.size() >= 3 && list[0].kind == lynx::startfrom::Entry::Kind::demo
  12486. && (int) list.size() == panel->entryCountForSnapshot());
  12487. for (auto& e : list)
  12488. report << " " << e.name << " | " << juce::String (e.bpm, 0) << " BPM, " << e.channels << " channels, " << e.bars << " bars"
  12489. << (e.playable ? ", preview" : "") << "\n";
  12490. if (const auto demo = lynx::startfrom::songOf (list[0]))
  12491. {
  12492. const auto wav = juce::File (prefix + "-preview.wav");
  12493. const auto ok = lynx::startfrom::renderPreview (*demo, wav);
  12494. check ("the demo's preview renders (" + juce::String (wav.getSize() / 1024) + " kB)", ok && wav.getSize() > 100000);
  12495. wav.deleteFile();
  12496. }
  12497. panel->selectForSnapshot (juce::jmin (2, panel->entryCountForSnapshot() - 1));
  12498. shoot (ui, "startfrom-selected");
  12499. offline.markSaved(); // (a project with changes asks first: Save / Don't save / Cancel)
  12500. const auto opened = panel->openForSnapshot (0);
  12501. offline.dispatchPendingMessages();
  12502. check ("opening the demo starts a new project from it and closes the list",
  12503. opened && ! simple->isStartFromShowing() && offline.getSong().info.comments.empty() && ! offline.getSong().channels.empty());
  12504. shoot (ui, "startfrom-opened");
  12505. }
  12506. }
  12507. juce::File (prefix + "-report.txt").replaceWithText (report);
  12508. }
  12509. void runVersionsShot (const juce::String& prefix)
  12510. {
  12511. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12512. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  12513. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  12514. };
  12515. // ---- the Versions panel, on files in a temporary folder
  12516. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  12517. .getChildFile ("lynx-versionsshot-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  12518. const juce::ScopeGuard cleanUp { [&root] { root.deleteRecursively(); } };
  12519. const auto project = root.getChildFile ("Night Drive"), backup = root.getChildFile ("Backup");
  12520. project.createDirectory();
  12521. backup.createDirectory();
  12522. const auto now = juce::Time::getCurrentTime();
  12523. const auto put = [&now] (const juce::File& folder, const juce::String& name, const char* kind, int kilobytes, double hoursAgo) {
  12524. const auto time = now - juce::RelativeTime::hours (hoursAgo);
  12525. const auto file = folder.getChildFile (kind == nullptr ? name + ".lynx" : name + " (" + kind + " on " + time.formatted ("%Y-%m-%d at %Hh%M") + ").lynx");
  12526. juce::MemoryBlock data ((size_t) kilobytes * 1024, true);
  12527. file.replaceWithData (data.getData(), data.getSize());
  12528. file.setLastModificationTime (time);
  12529. };
  12530. put (project, "Night Drive", nullptr, 412, 26.0 * 24.0);
  12531. put (project, "Night Drive_2", nullptr, 688, 9.0 * 24.0);
  12532. put (project, "Night Drive_3", nullptr, 731, 2.0 * 24.0);
  12533. put (project, "Night Drive_4", nullptr, 905, 1.6);
  12534. put (backup, "Night Drive_4", "autosaved", 907, 0.07);
  12535. put (backup, "Night Drive_4", "autosaved", 906, 0.4);
  12536. put (backup, "Night Drive_4", "overwritten", 890, 1.6);
  12537. put (backup, "Night Drive_4", "autosaved", 884, 3.2);
  12538. put (backup, "Night Drive_3", "overwritten", 720, 2.0 * 24.0);
  12539. put (backup, "Night Drive_2", "autosaved", 690, 8.0 * 24.0);
  12540. const lynx::VersionsContext context { project.getChildFile ("Night Drive_4.lynx"), "Night Drive_4", backup, ".lynx" };
  12541. {
  12542. const auto entries = lynx::versionEntries (context);
  12543. const auto label = [&] (const juce::String& startsWith, const char* text) {
  12544. for (const auto& e : entries)
  12545. if (juce::String::fromUTF8 (e.name.c_str()).startsWith (startsWith))
  12546. {
  12547. lynx::setVersionLabel (context, e, text);
  12548. return;
  12549. }
  12550. };
  12551. label ("Night Drive_2", "first full arrangement");
  12552. label ("Night Drive_3", "sent to the singer");
  12553. label ("Night Drive_4 (autosaved", "new bass line");
  12554. }
  12555. {
  12556. lynx::VersionsActions actions;
  12557. actions.context = [context] { return context; };
  12558. auto panel = lynx::makeVersionsPanel (actions);
  12559. shoot (*panel, "versions");
  12560. lynx::VersionsActions fresh;
  12561. fresh.context = [backup] { return lynx::VersionsContext { juce::File(), "Untitled", backup, ".lynx" }; };
  12562. auto empty = lynx::makeVersionsPanel (fresh);
  12563. shoot (*empty, "versions-unsaved");
  12564. }
  12565. // ---- the window
  12566. lynx::AudioEngine offline (false);
  12567. lynx::MainComponent ui (offline, false);
  12568. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  12569. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  12570. const auto saveFileMenu = [&] (const char* name) {
  12571. const auto index = juce::jmax (0, ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("File")));
  12572. saveMenus (juce::StringArray { lynx::tr ("File") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-" + name + ".png");
  12573. };
  12574. saveFileMenu ("menu-file");
  12575. // ---- a project opened without its third-party plugins (the plugins are not installed: nothing foreign runs)
  12576. {
  12577. const auto ref = [] (const char* id, const char* name) {
  12578. lynx::PluginRef r;
  12579. r.id = id;
  12580. r.name = name;
  12581. r.state = "c2V0dGluZ3M=";
  12582. return r;
  12583. };
  12584. auto song = lynx::Song::makeDefault();
  12585. while (song.channels.size() < 4)
  12586. song.channels.push_back (song.channels.front());
  12587. while (song.mixer.size() < 5)
  12588. song.mixer.push_back (song.mixer.back());
  12589. const char* names[] = { "Lead", "Pad" };
  12590. for (int c = 0; c < 2; ++c)
  12591. {
  12592. auto& channel = song.channels[(std::size_t) (c + 2)];
  12593. channel.instrument = lynx::InstrumentKind::plugin;
  12594. channel.plugin = ref ("VST3-ShotSynth-11111111-aaaaaaaa", "Shot Synth");
  12595. channel.name = names[c];
  12596. channel.mixerTrack = c + 1;
  12597. }
  12598. lynx::EffectSlot fx;
  12599. fx.kind = lynx::EffectKind::plugin;
  12600. fx.plugin = ref ("VST3-ShotVerb-22222222-bbbbbbbb", "Shot Verb");
  12601. song.mixer[1].effects.push_back (fx);
  12602. fx.plugin = ref ("VST3-ShotComp-33333333-cccccccc", "Shot Comp");
  12603. song.mixer[2].effects.push_back (fx);
  12604. song.mixer[0].effects.push_back (fx);
  12605. offline.setSongWithPluginsOff (std::move (song));
  12606. ui.showDesktopForSnapshot (false);
  12607. shoot (ui, "pluginsoff-window");
  12608. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  12609. shoot (ui, "pluginsoff-mixer"); // (the rack's and the mixer's "off" tags together)
  12610. saveFileMenu ("menu-file-pluginsoff");
  12611. auto panel = lynx::makePluginsOffPanel (offline);
  12612. shoot (*panel, "pluginsoff-panel");
  12613. offline.switchPluginOn ("VST3-ShotVerb-22222222-bbbbbbbb"); // (not installed: "Did not load")
  12614. auto after = lynx::makePluginsOffPanel (offline);
  12615. shoot (*after, "pluginsoff-panel-one");
  12616. }
  12617. // ---- the Export window: as it opens, and with a preset chosen, sections on and a last export to repeat
  12618. {
  12619. auto song = lynx::Song::makeDefault();
  12620. const auto bar = song.barTicks();
  12621. song.mode = lynx::PlayMode::song;
  12622. song.playlist.clear();
  12623. lynx::Clip clip;
  12624. clip.length = 32 * bar;
  12625. song.playlist.push_back (clip);
  12626. const char* sections[] = { "Intro", "Verse", "Chorus", "Outro" };
  12627. for (int i = 0; i < 4; ++i)
  12628. {
  12629. lynx::Marker m;
  12630. m.tick = i * 8 * bar;
  12631. m.name = sections[i];
  12632. song.addMarker (m);
  12633. }
  12634. offline.setSong (std::move (song)); // (also ends the plugins-off mode)
  12635. auto plain = lynx::makeExportPanel (offline, 0);
  12636. shoot (*plain, "export-default");
  12637. auto additions = lynx::makeExportPanelWithAdditions (offline);
  12638. shoot (*additions, "export");
  12639. }
  12640. }
  12641. void runGamepadShot (const juce::String& prefix)
  12642. {
  12643. juce::String report;
  12644. int failures = 0;
  12645. {
  12646. lynx::AudioEngine engine (false);
  12647. auto hints = lynx::makeGamepadHints();
  12648. savePng (lynx::shot::snapshot (*hints), prefix + "-hints.png");
  12649. auto prefs = engine.getMidiPrefs();
  12650. prefs.gamepad = true;
  12651. engine.setMidiPrefs (prefs, false);
  12652. auto page = lynx::makeMidiPage (engine, {}, false);
  12653. page->setSize (760, 1400);
  12654. savePng (lynx::shot::snapshot (*page), prefix + "-settings.png");
  12655. // the poller with fake states: what the handler gets
  12656. using namespace lynx::gamepad;
  12657. std::vector<std::string> got;
  12658. lynx::GamepadInput input ([&got] (const Changes& c, const State&, double dt) {
  12659. for (int i = 0; i < c.pressedCount; ++i)
  12660. got.push_back (std::string ("press ") + buttonName (c.pressed[(std::size_t) i]));
  12661. for (int i = 0; i < c.releasedCount; ++i)
  12662. got.push_back (std::string ("release ") + buttonName (c.released[(std::size_t) i]));
  12663. for (int i = 0; i < c.controllerCount; ++i)
  12664. got.push_back ("cc " + std::to_string (c.controller[(std::size_t) i]) + "=" + std::to_string (c.value[(std::size_t) i]));
  12665. if (c.connectedChanged)
  12666. got.push_back ("connected changed");
  12667. got.push_back ("dt " + std::to_string ((int) std::lround (dt * 1000)));
  12668. });
  12669. State pad;
  12670. pad.connected = true;
  12671. input.inject (pad, 1.0 / 60.0);
  12672. pad.buttons = mask (Button::a);
  12673. pad.rightTrigger = 255;
  12674. input.inject (pad, 1.0 / 60.0);
  12675. pad.buttons = 0;
  12676. input.inject (pad, 1.0 / 60.0);
  12677. const std::vector<std::string> expected { "connected changed", "dt 17", "press A", "cc 102=127", "cc 21=127", "dt 17",
  12678. "release A", "cc 102=0", "dt 17" };
  12679. for (const auto& line : got)
  12680. report << line << "\n";
  12681. if (got != expected)
  12682. {
  12683. ++failures;
  12684. report << "FAILED: the poller's changes differ from the expected ones\n";
  12685. }
  12686. report << "xinput " << (input.available() ? "loaded" : "not available") << "\n";
  12687. }
  12688. report << (failures == 0 ? "gamepad OK" : "gamepad FAILED") << "\n";
  12689. juce::File (prefix + "-gamepad.txt").replaceWithText (report);
  12690. setApplicationReturnValue (failures == 0 ? 0 : 1);
  12691. quit();
  12692. }
  12693. void runBundleExport (const juce::String& inputPath, const juce::String& folderPath, bool zip, bool mixdown, const juce::String& shotPrefix)
  12694. {
  12695. juce::String error;
  12696. bool ok = false;
  12697. lynx::otherapps::Result result;
  12698. {
  12699. lynx::AudioEngine loader (false);
  12700. const juce::File input (inputPath);
  12701. if (input.hasFileExtension ("flp;als"))
  12702. ok = loader.importFlpFile (input, error);
  12703. else if (auto song = lynx::ProjectFile::load (input, error))
  12704. {
  12705. loader.setSong (std::move (*song));
  12706. ok = true;
  12707. }
  12708. if (ok)
  12709. {
  12710. loader.capturePluginStates();
  12711. lynx::otherapps::Context context;
  12712. context.host = &loader.getPluginHost();
  12713. context.flOptions = lynx::flstudio::optionsFor (context.host, lynx::flpexport::LynxOnly::renderAudio, loader.getSong());
  12714. context.render = [] (const lynx::Song& s, const lynx::exportopts::Options& o, const juce::File& file,
  12715. const std::function<bool (double)>& progress, juce::String& err) {
  12716. lynx::ExportJob job (s, o, file);
  12717. return job.run (progress, err);
  12718. };
  12719. context.onMessageThread = [] (std::function<void()> f) { f(); };
  12720. lynx::exportbundle::Options options;
  12721. options.zip = zip;
  12722. options.mixdown = mixdown;
  12723. const auto name = input.getFileNameWithoutExtension();
  12724. const auto shot = [&shotPrefix] (juce::Component& c, const juce::String& suffix) {
  12725. if (shotPrefix.isNotEmpty())
  12726. savePng (lynx::shot::snapshot (c), shotPrefix + suffix);
  12727. };
  12728. if (auto panel = lynx::makeOtherAppsExportPanel (loader, name))
  12729. shot (*panel, "-panel.png");
  12730. ok = lynx::otherapps::write (loader.getSong(), name, options, juce::File (folderPath), context, result);
  12731. if (auto report = lynx::makeOtherAppsReportPanel (result.folder, result.written, result.failed))
  12732. shot (*report, "-report.png");
  12733. }
  12734. }
  12735. juce::String report;
  12736. report << (ok ? "ok " + result.folder.getFullPathName() : "error=" + error) << "\n";
  12737. for (const auto& w : result.written)
  12738. report << "written " << w << "\n";
  12739. for (const auto& f : result.failed)
  12740. report << "failed " << f << "\n";
  12741. juce::File (folderPath).getChildFile ("export-bundle.txt").replaceWithText (report);
  12742. setApplicationReturnValue (ok && result.failed.isEmpty() ? 0 : 1);
  12743. quit();
  12744. }
  12745. void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
  12746. {
  12747. juce::String error;
  12748. bool ok = false;
  12749. lynx::flstudio::Written written;
  12750. {
  12751. lynx::AudioEngine loader (false);
  12752. const juce::File input (inputPath);
  12753. // a Live set opens through the same import as an .flp (as File › Open does, and --export-als accepts an .flp)
  12754. if (input.hasFileExtension ("flp;als"))
  12755. ok = loader.importFlpFile (input, error);
  12756. else if (auto song = lynx::ProjectFile::load (input, error))
  12757. {
  12758. loader.setSong (std::move (*song));
  12759. ok = true;
  12760. }
  12761. if (ok)
  12762. {
  12763. const juce::File output (outputPath);
  12764. const auto zip = output.hasFileExtension ("zip");
  12765. const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
  12766. loader.capturePluginStates();
  12767. auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
  12768. // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
  12769. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
  12770. options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
  12771. const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
  12772. : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
  12773. ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
  12774. [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
  12775. const std::function<bool (double)>& progress, juce::String& err) {
  12776. lynx::ExportJob job (s, settings, wav);
  12777. return job.run (progress, err);
  12778. },
  12779. {}, written, error);
  12780. if (zip)
  12781. renderDir.deleteRecursively();
  12782. }
  12783. }
  12784. juce::String report;
  12785. report << (ok ? "ok" : "error=" + error) << "\n"
  12786. << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
  12787. << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
  12788. << " samples=" << written.samples << "\n\n"
  12789. << lynx::flstudio::reportText (written) << "\n";
  12790. juce::File (outputPath + ".txt").replaceWithText (report);
  12791. setApplicationReturnValue (ok ? 0 : 1);
  12792. quit();
  12793. }
  12794. // LYNX.exe --export project.(flp|als|lynx) output.(wav|flac|ogg|mp3) [--pattern] [--insert N] [--rate N]
  12795. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail.
  12796. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  12797. {
  12798. juce::String error, report;
  12799. bool ok = false;
  12800. const auto started = juce::Time::getMillisecondCounterHiRes();
  12801. lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
  12802. {
  12803. lynx::AudioEngine loader (false);
  12804. const juce::File input (inputPath);
  12805. // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
  12806. if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
  12807. {
  12808. juce::MemoryBlock data;
  12809. if (input.loadFileAsData (data))
  12810. try
  12811. {
  12812. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  12813. auto& host = loader.getPluginHost();
  12814. const auto listed = std::chrono::steady_clock::now();
  12815. const auto files = host.filesToScanFor (uses);
  12816. lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
  12817. report << "scanned=" << files.joinIntoString (";") << "\n";
  12818. const auto scanned = std::chrono::steady_clock::now();
  12819. host.scanFiles (files, {});
  12820. lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
  12821. }
  12822. catch (const flp::Error&)
  12823. {
  12824. }
  12825. }
  12826. if (input.hasFileExtension ("flp;als")) // a Live set opens through the same import (round 182b)
  12827. ok = loader.importFlpFile (input, error);
  12828. else if (auto song = lynx::ProjectFile::load (input, error))
  12829. {
  12830. loader.setSong (std::move (*song));
  12831. ok = true;
  12832. }
  12833. if (ok)
  12834. {
  12835. const juce::File output (outputPath);
  12836. lynx::ExportSettings settings;
  12837. settings.wholeSong = ! patternOnly;
  12838. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  12839. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  12840. : lynx::ExportSettings::Format::wav24;
  12841. // --insert N: only that insert's output (what "Render to audio" records)
  12842. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  12843. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  12844. loader.editSong ([] (lynx::Song& s) {
  12845. for (auto& t : s.mixer)
  12846. t.effects.clear();
  12847. }, false);
  12848. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  12849. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  12850. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  12851. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  12852. // .mp3: the Export window's MP3 (320 kbps); everything else as before
  12853. auto options = settings.toOptions();
  12854. // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
  12855. if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
  12856. options.saveTempo = true;
  12857. // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
  12858. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
  12859. options.pluginWarmUp = false;
  12860. // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
  12861. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
  12862. if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
  12863. options.sampleRate = rate;
  12864. if (output.hasFileExtension ("mp3"))
  12865. {
  12866. options.format = lynx::exportopts::Format::mp3;
  12867. options.mp3Kbps = 320;
  12868. }
  12869. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
  12870. job.setExtraData (true);
  12871. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  12872. lynx::loadtrace::end();
  12873. int lastPercent = -1;
  12874. ok = job.run ([&lastPercent] (double p) {
  12875. lastPercent = (int) (p * 100.0);
  12876. return true;
  12877. }, error);
  12878. auto joined = [] (const std::map<std::string, int>& items) {
  12879. juce::StringArray names;
  12880. for (const auto& [name, count] : items)
  12881. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  12882. return names.joinIntoString (", ");
  12883. };
  12884. const auto& importReport = loader.getImportReport();
  12885. report << "converted=" << joined (importReport.converted) << "\n"
  12886. << "approximated=" << joined (importReport.approximated) << "\n"
  12887. << "unsupported=" << joined (importReport.unsupported) << "\n"
  12888. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  12889. << "partial_effects=" << joined (importReport.partialEffects) << "\n"
  12890. << "missing_samples=" << importReport.missingSamples << "\n";
  12891. // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
  12892. for (const auto& line : loader.getMatchedPlugins())
  12893. report << "plugin_found=" << line << "\n";
  12894. for (const auto& m : loader.getMissingPluginDetails())
  12895. report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
  12896. << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
  12897. {
  12898. const auto& song = loader.getSong();
  12899. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  12900. {
  12901. const auto& track = song.mixer[t];
  12902. if (track.effects.empty() && track.sends.empty())
  12903. continue;
  12904. report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
  12905. << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
  12906. for (const auto& s : track.sends)
  12907. report << " send>" << s.target << "@" << juce::String (s.level, 3);
  12908. report << " |";
  12909. for (const auto& fx : track.effects)
  12910. report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
  12911. : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
  12912. << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
  12913. << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
  12914. report << "\n";
  12915. }
  12916. }
  12917. report << juce::String (lynx::loadtrace::reportLines());
  12918. lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
  12919. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  12920. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  12921. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  12922. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  12923. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  12924. << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
  12925. << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
  12926. << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
  12927. << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
  12928. << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
  12929. << "song_seconds=" << job.getMusicSeconds() << "\n"
  12930. << "peak=" << job.getPeak() << "\n"
  12931. << "final_progress=" << lastPercent << "\n"
  12932. << "bytes=" << output.getSize() << "\n";
  12933. ok = ok && job.getPeak() > 0.001f;
  12934. }
  12935. }
  12936. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  12937. juce::File (outputPath + ".txt").replaceWithText (report);
  12938. setApplicationReturnValue (ok ? 0 : 1);
  12939. quit();
  12940. }
  12941. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  12942. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  12943. // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
  12944. struct EditorCpuRun final : juce::Timer
  12945. {
  12946. struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
  12947. std::vector<Case> cases;
  12948. std::size_t at = 0;
  12949. int phase = 0;
  12950. double t0 = 0.0, c0 = 0.0;
  12951. juce::String report;
  12952. juce::File out;
  12953. std::unique_ptr<lynx::AudioEngine> engine;
  12954. std::unique_ptr<juce::DocumentWindow> window;
  12955. std::function<void()> done;
  12956. void start()
  12957. {
  12958. engine = std::make_unique<lynx::AudioEngine> (false);
  12959. report << "editor\tmode\tcpu % of one core\n";
  12960. open();
  12961. startTimer (250);
  12962. }
  12963. void open()
  12964. {
  12965. window.reset();
  12966. if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
  12967. const auto& c = cases[at];
  12968. lynx::Song song;
  12969. song.mixer.resize (2);
  12970. song.mixer[0].name = "Master";
  12971. song.mixer[1].name = "Insert 1";
  12972. song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
  12973. engine->setSong (std::move (song));
  12974. engine->dispatchPendingMessages();
  12975. lynx::setNativeEditorDemo (c.demo);
  12976. auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
  12977. : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
  12978. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
  12979. window->setUsingNativeTitleBar (true);
  12980. window->setContentOwned (editor.release(), true);
  12981. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  12982. window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
  12983. window->setVisible (true);
  12984. phase = 0;
  12985. t0 = juce::Time::getMillisecondCounterHiRes();
  12986. }
  12987. void timerCallback() override
  12988. {
  12989. const auto now = juce::Time::getMillisecondCounterHiRes();
  12990. if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
  12991. if (phase == 1 && now - t0 > 8000.0)
  12992. {
  12993. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  12994. const auto& c = cases[at];
  12995. report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
  12996. ++at;
  12997. open();
  12998. }
  12999. }
  13000. };
  13001. std::unique_ptr<EditorCpuRun> editorCpu;
  13002. void runEditorCpu (const juce::String& path)
  13003. {
  13004. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13005. editorCpu = std::make_unique<EditorCpuRun>();
  13006. editorCpu->out = juce::File (path);
  13007. using K = lynx::EffectKind;
  13008. for (const auto demo : { false, true })
  13009. for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
  13010. { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
  13011. { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
  13012. { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
  13013. editorCpu->cases.push_back (c);
  13014. editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
  13015. editorCpu->start();
  13016. }
  13017. struct ParityShow
  13018. {
  13019. std::unique_ptr<lynx::AudioEngine> engine;
  13020. std::unique_ptr<juce::Component> editor;
  13021. std::unique_ptr<juce::DocumentWindow> window;
  13022. ~ParityShow() { window.reset(); editor.reset(); engine.reset(); }
  13023. };
  13024. std::shared_ptr<ParityShow> parityShow;
  13025. bool parityShotFailed = false; // --parityshot: the effect name matched no built-in effect
  13026. void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
  13027. {
  13028. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13029. int kindIndex = -1;
  13030. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  13031. if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
  13032. kindIndex = k;
  13033. if (kindIndex < 0)
  13034. {
  13035. // round tp172b7: say so and fail (a silent exit 0 hid a split effect name in a launch script)
  13036. std::fprintf (stderr, "unknown effect: %s\n", effectName.toRawUTF8());
  13037. std::fflush (stderr);
  13038. parityShotFailed = true;
  13039. return;
  13040. }
  13041. const auto kind = (lynx::EffectKind) kindIndex;
  13042. auto fx = lynx::makeEffectSlot (kind);
  13043. if (paramsFile.isNotEmpty())
  13044. for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
  13045. {
  13046. const auto t = juce::StringArray::fromTokens (line, " \t", "");
  13047. const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
  13048. if (index >= 0 && index < lynx::maxEffectParams)
  13049. fx.params[(std::size_t) index] = t[1].getFloatValue();
  13050. }
  13051. auto offlineOwner = std::make_unique<lynx::AudioEngine> (false); // (kept alive by LYNX_PARITYSHOT_SHOW's window)
  13052. auto& offline = *offlineOwner;
  13053. auto song = lynx::Song::makeDefault();
  13054. song.mixer.resize (2);
  13055. song.mixer[0].name = "Master";
  13056. song.mixer[1].name = "Insert 1";
  13057. song.mixer[1].effects.assign (1, fx);
  13058. for (auto& c : song.channels)
  13059. c.mixerTrack = 1;
  13060. offline.setSong (std::move (song));
  13061. offline.dispatchPendingMessages();
  13062. const bool facet = kind == lynx::EffectKind::facetEq;
  13063. // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
  13064. // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
  13065. const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
  13066. // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
  13067. const bool pro = lynx::ProEditorWindows::handles (kind)
  13068. && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
  13069. auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  13070. : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  13071. if (editor == nullptr)
  13072. return;
  13073. if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
  13074. {
  13075. lynx::AudioEngine::RenderOptions o;
  13076. o.seconds = 3.0;
  13077. o.sampleRate = 48000.0;
  13078. o.pluginWarmUp = false;
  13079. int sinceTick = 0;
  13080. o.capture = [&] (const float*, const float*, int n) {
  13081. sinceTick += n;
  13082. if (sinceTick < 1600) return;
  13083. sinceTick = 0;
  13084. if (facet) lynx::tickFacetEqEditor (*editor);
  13085. else lynx::tickNativeEffectEditor (*editor);
  13086. };
  13087. offline.renderOffline (o);
  13088. }
  13089. // round tp172b5: LYNX_PARITYSHOT_CLICKS drives the editor before the picture (the originals' pictures have their
  13090. // panels open), tokens in order: "x,y" a click, then the pointer leaves; "h:x,y" the pointer rests there (a hover);
  13091. // "d:x,y,x2,y2" a drag from there to there, the button still down in the picture
  13092. for (const auto& token : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_CLICKS", {}), " ", ""))
  13093. {
  13094. const auto hover = token.startsWith ("h:"), drag = token.startsWith ("d:");
  13095. const auto xy = juce::StringArray::fromTokens (hover || drag ? token.substring (2) : token, ",", "");
  13096. if (xy.size() < (drag ? 4 : 2))
  13097. continue;
  13098. const juce::Point<int> at (xy[0].getIntValue(), xy[1].getIntValue());
  13099. editor->setVisible (true); // (getComponentAt finds nothing in a hidden component; it never goes on screen)
  13100. auto* target = editor->getComponentAt (at);
  13101. if (target == nullptr)
  13102. continue;
  13103. const auto local = target->getLocalPoint (editor.get(), at).toFloat();
  13104. const auto now = juce::Time::getCurrentTime();
  13105. auto source = juce::Desktop::getInstance().getMainMouseSource();
  13106. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  13107. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods, bool dragged) {
  13108. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, local, now, 1, dragged);
  13109. };
  13110. target->mouseMove (event (local, {}, false));
  13111. if (hover)
  13112. continue;
  13113. target->mouseDown (event (local, left, false));
  13114. if (drag)
  13115. {
  13116. const auto end = target->getLocalPoint (editor.get(), juce::Point<int> (xy[2].getIntValue(), xy[3].getIntValue())).toFloat();
  13117. target->mouseDrag (event (end, left, true));
  13118. continue;
  13119. }
  13120. target->mouseUp (event (local, {}, false));
  13121. target->mouseExit (event ({ -1000.0f, -1000.0f }, {}, false));
  13122. }
  13123. // round tp172b6: LYNX_PARITYSHOT_SHOW=1 puts the same editor in a real window and keeps it open (for a guarded GUI check
  13124. // of its pop-up menus, which the offscreen picture cannot hold); closing the window quits
  13125. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_SHOW", {}) == "1")
  13126. {
  13127. struct ShowWindow final : juce::DocumentWindow
  13128. {
  13129. ShowWindow() : juce::DocumentWindow ("LYNX parity check", juce::Colours::black, juce::DocumentWindow::closeButton) {}
  13130. void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }
  13131. };
  13132. parityShow = std::make_shared<ParityShow>();
  13133. parityShow->engine = std::move (offlineOwner);
  13134. parityShow->editor = std::move (editor);
  13135. auto window = std::make_unique<ShowWindow>();
  13136. window->setUsingNativeTitleBar (true);
  13137. window->setContentNonOwned (parityShow->editor.get(), true);
  13138. window->setTopLeftPosition (80, 80);
  13139. window->setVisible (true);
  13140. parityShow->window = std::move (window);
  13141. return;
  13142. }
  13143. // round 190ar: LYNX_PARITYSHOT_SCALE=2 draws the same editor at twice the pixel density (as on a 200 % display);
  13144. // round 190bi: the shared shot scale (--shot-scale, LYNX_SHOT_SCALE, LYNX_PARITYSHOT_SCALE as before)
  13145. const auto shotScale = lynx::shot::scale();
  13146. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) editor->getWidth() * shotScale), juce::roundToInt ((float) editor->getHeight() * shotScale), true);
  13147. {
  13148. juce::Graphics g (image);
  13149. g.fillAll (lynx::theme::panel);
  13150. g.addTransform (juce::AffineTransform::scale (shotScale));
  13151. editor->paintEntireComponent (g, false);
  13152. }
  13153. const auto file = lynx::shot::file (juce::File (path));
  13154. file.deleteFile();
  13155. juce::PNGImageFormat png;
  13156. if (auto stream = file.createOutputStream())
  13157. png.writeImageToStream (image, *stream);
  13158. }
  13159. // an Audio Effect Rack shaped like Live's reference (REA_rodada183c §8): two chains with chain-select zones and fades,
  13160. // four named macros (one on a chain's volume, one on two parameters), two variations, every view open
  13161. static lynx::EffectSlot shotRack()
  13162. {
  13163. auto slot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  13164. auto& doc = slot.patcher;
  13165. doc.rack[0].chains[0].name = "Vocoder";
  13166. lynx::PatchNode vocoder, eq, verb;
  13167. vocoder.effect = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  13168. eq.effect = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  13169. verb.effect = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
  13170. const auto nVoc = lynx::rack::addDevice (doc, 0, vocoder);
  13171. const auto nEq = lynx::rack::addDevice (doc, 0, eq);
  13172. lynx::rack::addChain (doc, "dry bypass");
  13173. lynx::rack::addDevice (doc, 1, verb);
  13174. doc.rack[0].chains[0].select = { 0, 79, 0, 63 };
  13175. doc.rack[0].chains[1].select = { 32, 127, 48, 127 };
  13176. lynx::rack::setChainVolume (doc, 0, 0.33f);
  13177. lynx::rack::setChainVolume (doc, 1, 0.5f);
  13178. const char* names[] { "Sibilance", "Intensity", "Formant Shift", "Bright Level" };
  13179. for (int m = 0; m < 4; ++m)
  13180. doc.rack[0].macros[(std::size_t) m].name = names[m];
  13181. lynx::RackMapping vol;
  13182. vol.target = lynx::RackMapping::Target::chainVolume, vol.chain = 0, vol.min = 0.0f, vol.max = lynx::rack::unityVolume;
  13183. lynx::rack::map (doc, 0, vol);
  13184. lynx::RackMapping a, b, c, d;
  13185. a.node = nVoc, a.param = 0;
  13186. b.node = nVoc, b.param = 1, b.min = 0.2f, b.max = 0.8f;
  13187. c.node = nEq, c.param = 0, c.min = 0.3f, c.max = 0.9f;
  13188. d.node = nEq, d.param = 1;
  13189. lynx::rack::map (doc, 1, a);
  13190. lynx::rack::map (doc, 2, b);
  13191. lynx::rack::map (doc, 3, c);
  13192. lynx::rack::map (doc, 3, d);
  13193. lynx::rack::setMacro (doc, 0, 60.0f);
  13194. lynx::rack::setMacro (doc, 1, 40.0f);
  13195. lynx::rack::setMacro (doc, 2, 70.0f);
  13196. lynx::rack::setMacro (doc, 3, 86.0f);
  13197. lynx::rack::storeVariation (doc);
  13198. lynx::rack::renameVariation (doc, 0, "Verse");
  13199. lynx::rack::setMacro (doc, 3, 120.0f);
  13200. lynx::rack::storeVariation (doc);
  13201. lynx::rack::renameVariation (doc, 1, "Drop");
  13202. lynx::rack::launchVariation (doc, 0);
  13203. auto& r = doc.rack[0];
  13204. r.showMacros = r.showChains = r.showDevices = r.showVariations = true;
  13205. r.zoneEditor = 2;
  13206. r.selectedChain = 0;
  13207. lynx::rack::setSelector (doc, 56.0f);
  13208. lynx::rack::compile (doc);
  13209. return slot;
  13210. }
  13211. bool runRackShots (const juce::File& out, const juce::String& liveSet = {})
  13212. {
  13213. out.createDirectory();
  13214. lynx::AudioEngine offline (false);
  13215. auto save = [&] (juce::Component& c, const juce::String& name) {
  13216. auto image = lynx::shot::paint (c, lynx::theme::panel);
  13217. const auto f = lynx::shot::file (out.getChildFile (name));
  13218. f.deleteFile();
  13219. juce::PNGImageFormat png;
  13220. if (auto stream = f.createOutputStream())
  13221. return png.writeImageToStream (image, *stream);
  13222. return false;
  13223. };
  13224. auto song = lynx::Song::makeDefault();
  13225. song.mixer.resize (3);
  13226. song.mixer[1].name = "Vocal Main";
  13227. auto slot = shotRack();
  13228. song.mixer[1].effects = { slot };
  13229. // an Instrument Rack: three chains split over the keyboard
  13230. lynx::ChannelDef inst;
  13231. inst.name = "Keys Rack";
  13232. inst.instrument = lynx::InstrumentKind::patcher;
  13233. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  13234. for (int k = 0; k < 3; ++k)
  13235. {
  13236. if (k > 0)
  13237. lynx::rack::addChain (inst.patcher);
  13238. lynx::PatchNode synth;
  13239. synth.generator = true;
  13240. synth.channel.instrument = lynx::InstrumentKind::synth;
  13241. synth.channel.name = "Synth";
  13242. lynx::rack::addDevice (inst.patcher, k, synth);
  13243. }
  13244. inst.patcher.rack[0].chains[0].key = { 0, 52, 0, 47 };
  13245. inst.patcher.rack[0].chains[1].key = { 48, 76, 53, 71 };
  13246. inst.patcher.rack[0].chains[2].key = { 72, 127, 77, 127 };
  13247. inst.patcher.rack[0].chains[0].name = "Low";
  13248. inst.patcher.rack[0].chains[1].name = "Mid";
  13249. inst.patcher.rack[0].chains[2].name = "High";
  13250. inst.patcher.rack[0].showChains = inst.patcher.rack[0].showDevices = true;
  13251. inst.patcher.rack[0].zoneEditor = 0;
  13252. lynx::rack::compile (inst.patcher);
  13253. song.channels.push_back (inst);
  13254. const auto channel = (int) song.channels.size() - 1;
  13255. offline.setSong (std::move (song));
  13256. offline.dispatchPendingMessages();
  13257. bool ok = true;
  13258. // [set.als]: a Live set's racks as LYNX imports them, the one with the most chains drawn with its title bar (the
  13259. // like-for-like pair with Live's own picture of that set)
  13260. if (liveSet.isNotEmpty())
  13261. {
  13262. juce::MemoryBlock bytes;
  13263. juce::File (liveSet).loadFileAsData (bytes);
  13264. const std::vector<std::uint8_t> data ((const std::uint8_t*) bytes.getData(), (const std::uint8_t*) bytes.getData() + bytes.getSize());
  13265. lynx::AlsImportOptions o;
  13266. o.common.projectFolder = juce::File (liveSet).getParentDirectory().getFullPathName().toStdString();
  13267. std::string error;
  13268. if (auto imported = lynx::importAls (data, o, &error))
  13269. {
  13270. int bestTrack = -1, bestSlot = -1;
  13271. std::size_t most = 0;
  13272. for (int t = 0; t < (int) imported->mixer.size(); ++t)
  13273. for (int s = 0; s < (int) imported->mixer[(std::size_t) t].effects.size(); ++s)
  13274. 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)
  13275. most = fx.patcher.rack[0].chains.size(), bestTrack = t, bestSlot = s;
  13276. if (bestTrack >= 0)
  13277. {
  13278. offline.setSong (std::move (*imported));
  13279. offline.dispatchPendingMessages();
  13280. auto view = lynx::RackWindows::makeSlotView (offline, bestTrack, bestSlot, true);
  13281. view->setSize (view->preferredWidth (228), 228);
  13282. ok = save (*view, "rack-live-import.png") && ok;
  13283. view->setMapMode (true);
  13284. view->setSize (view->preferredWidth (228), 228);
  13285. ok = save (*view, "rack-live-import-map.png") && ok;
  13286. return ok;
  13287. }
  13288. }
  13289. return false;
  13290. }
  13291. {
  13292. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, false);
  13293. view->setSize (view->preferredWidth (206), 206);
  13294. ok = save (*view, "rack-deviceview.png") && ok;
  13295. }
  13296. {
  13297. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, true);
  13298. view->setMapMode (true);
  13299. view->setSize (view->preferredWidth (228), 228);
  13300. ok = save (*view, "rack-mapmode.png") && ok;
  13301. }
  13302. {
  13303. auto view = lynx::RackWindows::makeChannelView (offline, channel, true);
  13304. view->setSize (view->preferredWidth (228), 228);
  13305. ok = save (*view, "rack-instrument.png") && ok;
  13306. }
  13307. return ok;
  13308. }
  13309. void runEq166fShots (const juce::String& folder)
  13310. {
  13311. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13312. const juce::File out (folder);
  13313. out.createDirectory();
  13314. lynx::AudioEngine offline (false);
  13315. auto save = [&] (juce::Component& editor, const juce::String& name) {
  13316. auto image = lynx::shot::paint (editor, lynx::theme::panel);
  13317. const auto f = lynx::shot::file (out.getChildFile (name));
  13318. f.deleteFile();
  13319. juce::PNGImageFormat png;
  13320. if (auto stream = f.createOutputStream())
  13321. png.writeImageToStream (image, *stream);
  13322. };
  13323. // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
  13324. auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
  13325. auto song = lynx::Song::makeDefault();
  13326. song.mixer.resize (3);
  13327. song.mixer[0].name = "Master";
  13328. song.mixer[1].name = "Vocal";
  13329. song.mixer[2].name = "Reference mix";
  13330. song.mixer[1].effects.assign (1, fx);
  13331. for (std::size_t c = 0; c < song.channels.size(); ++c)
  13332. song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
  13333. return song;
  13334. };
  13335. auto feed = [&] (juce::Component& editor, bool facet, int frames) {
  13336. // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
  13337. lynx::AudioEngine::RenderOptions o;
  13338. o.seconds = frames / 30.0;
  13339. o.sampleRate = 48000.0;
  13340. o.pluginWarmUp = false;
  13341. int sinceTick = 0;
  13342. o.capture = [&] (const float*, const float*, int n) {
  13343. sinceTick += n;
  13344. if (sinceTick < 1600) return;
  13345. sinceTick = 0;
  13346. if (facet) lynx::tickFacetEqEditor (editor);
  13347. else lynx::tickNativeEffectEditor (editor);
  13348. };
  13349. offline.renderOffline (o);
  13350. if (facet) lynx::tickFacetEqEditor (editor);
  13351. else lynx::tickNativeEffectEditor (editor);
  13352. };
  13353. // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
  13354. auto& display = lynx::peqview::displaySettings();
  13355. const auto kept = display;
  13356. display.spectrum = display.heatmap = true;
  13357. display.position = 0;
  13358. 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" },
  13359. { 0.0, "peq2-heatmap-top.png" } })
  13360. {
  13361. auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  13362. eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
  13363. eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
  13364. display.position = juce::String (name).contains ("top") ? 1 : 0;
  13365. offline.setSong (songWith (eq, false));
  13366. offline.dispatchPendingMessages();
  13367. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
  13368. feed (*editor, false, 120);
  13369. save (*editor, name);
  13370. }
  13371. display = kept;
  13372. // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
  13373. {
  13374. using namespace lynx::facet;
  13375. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  13376. eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
  13377. eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
  13378. eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
  13379. eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
  13380. eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
  13381. eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
  13382. eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
  13383. eq.sidechain = 2;
  13384. for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
  13385. {
  13386. eq.params[(std::size_t) listenParam] = listenValue (l);
  13387. offline.setSong (songWith (eq, true));
  13388. offline.dispatchPendingMessages();
  13389. auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
  13390. feed (*editor, true, 90);
  13391. save (*editor, name);
  13392. }
  13393. }
  13394. }
  13395. void runDesign168rShots (const juce::String& folder)
  13396. {
  13397. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13398. const juce::File out (folder);
  13399. out.createDirectory();
  13400. lynx::AudioEngine offline (false);
  13401. using K = lynx::EffectKind;
  13402. for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
  13403. K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
  13404. K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
  13405. K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
  13406. {
  13407. const auto& bank = lynx::presets::factory (kind);
  13408. // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
  13409. std::optional<lynx::EffectSlot> flPreset;
  13410. if (kind == K::lovePhilter || kind == K::distructor)
  13411. {
  13412. const auto roots = lynx::findFlStudioRoots();
  13413. const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  13414. .getChildFile ("Patches/Plugin presets/Effects")
  13415. .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
  13416. juce::MemoryBlock bytes;
  13417. if (file.loadFileAsData (bytes))
  13418. flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
  13419. (const std::uint8_t*) bytes.getData() + bytes.getSize()));
  13420. }
  13421. for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
  13422. {
  13423. auto fx = lynx::makeEffectSlot (kind);
  13424. if (pass == 1 && flPreset)
  13425. fx = *flPreset;
  13426. else if (pass == 1)
  13427. {
  13428. fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
  13429. fx.presetName = bank.front().name;
  13430. }
  13431. lynx::Song song;
  13432. song.mixer.resize (2);
  13433. song.mixer[0].name = "Master";
  13434. song.mixer[1].name = "Insert 1";
  13435. song.mixer[1].effects.push_back (fx);
  13436. offline.setSong (std::move (song));
  13437. offline.dispatchPendingMessages();
  13438. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  13439. for (const auto scale : { 1.0f, 2.0f })
  13440. for (int page = 0; page < pages; ++page)
  13441. {
  13442. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
  13443. if (editor == nullptr)
  13444. continue;
  13445. juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
  13446. {
  13447. juce::Graphics g (image);
  13448. g.fillAll (lynx::theme::panel);
  13449. editor->paintEntireComponent (g, false);
  13450. }
  13451. // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
  13452. const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
  13453. + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
  13454. + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
  13455. + (scale > 1.5f ? "-200" : "-100") + ".png");
  13456. file.deleteFile();
  13457. juce::PNGImageFormat png;
  13458. if (auto stream = file.createOutputStream())
  13459. png.writeImageToStream (image, *stream);
  13460. }
  13461. }
  13462. }
  13463. }
  13464. bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
  13465. {
  13466. folder.createDirectory();
  13467. auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
  13468. juce::StringArray wanted;
  13469. wanted.addTokens (which, ",", "");
  13470. auto ok = true;
  13471. struct Shot
  13472. {
  13473. juce::String name;
  13474. std::optional<lynx::ChannelDef> channel;
  13475. };
  13476. std::vector<Shot> shots;
  13477. for (const auto& e : lynx::natives::instrumentEngines())
  13478. {
  13479. const auto name = key (e.name);
  13480. const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
  13481. if (! banked && ! wanted.contains (name))
  13482. continue;
  13483. auto channel = source == "fl" || source == "flm" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
  13484. : lynx::banks::defaultChannel (e.kind, e.name);
  13485. // (round 190u) source "flm": the channel as the .flm import makes it (Transistor Bass: FL Studio Mobile's build)
  13486. if (source == "flm" && channel && e.kind == lynx::InstrumentKind::transistorbass)
  13487. {
  13488. 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
  13489. channel->modelParams = { 1.0f };
  13490. channel->samplePath.clear();
  13491. }
  13492. if (! channel)
  13493. {
  13494. std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
  13495. ok = false;
  13496. continue;
  13497. }
  13498. shots.push_back ({ name, std::move (channel) });
  13499. }
  13500. // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
  13501. if (wanted.contains ("autogun"))
  13502. {
  13503. if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
  13504. shots.push_back ({ "autogun", std::move (channel) });
  13505. else
  13506. {
  13507. std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
  13508. ok = false;
  13509. }
  13510. }
  13511. for (auto& shot : shots)
  13512. {
  13513. const auto& name = shot.name;
  13514. auto& channel = shot.channel;
  13515. lynx::AudioEngine offline (false);
  13516. lynx::Song song;
  13517. song.mixer = lynx::Song::defaultMixer (2);
  13518. song.channels.push_back (*channel);
  13519. song.patterns.emplace_back();
  13520. {
  13521. juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
  13522. lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
  13523. }
  13524. offline.setSong (std::move (song));
  13525. offline.dispatchPendingMessages();
  13526. auto frame = lynx::makeChannelFrame (offline, 0, 0);
  13527. if (frame == nullptr || frame->getWidth() <= 0)
  13528. {
  13529. ok = false;
  13530. continue;
  13531. }
  13532. for (const auto scale : { 1.0f, 1.5f, 2.0f })
  13533. {
  13534. const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  13535. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
  13536. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
  13537. }
  13538. // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
  13539. for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
  13540. {
  13541. lynx::showChannelLayoutPage (*frame, page);
  13542. const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
  13543. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
  13544. std::printf ("%s\n", file.getFullPathName().toRawUTF8());
  13545. }
  13546. }
  13547. return ok;
  13548. }
  13549. // --- round 170j: the pilot editors with their own art -------------------------------------------------
  13550. struct ArtPilot
  13551. {
  13552. std::string file; // the art's name as a file name: "toxic-biohazard"
  13553. bool instrument;
  13554. lynx::InstrumentKind instrumentKind;
  13555. lynx::EffectKind effectKind;
  13556. lynx::skin::Style before; // the automatic style it had before the Themed style
  13557. };
  13558. static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
  13559. {
  13560. static juce::StringArray only;
  13561. return only;
  13562. }
  13563. // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
  13564. // registries, so a new theme is shot without touching this list
  13565. static const std::vector<ArtPilot>& artPilots()
  13566. {
  13567. using I = lynx::InstrumentKind;
  13568. using E = lynx::EffectKind;
  13569. static const std::vector<ArtPilot> list = [] {
  13570. std::vector<ArtPilot> all;
  13571. auto slug = [] (lynx::skin::Art a) {
  13572. return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
  13573. };
  13574. for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
  13575. if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
  13576. all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
  13577. for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
  13578. if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
  13579. all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
  13580. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  13581. if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
  13582. all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
  13583. std::vector<ArtPilot> kept;
  13584. for (auto& p : all)
  13585. if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
  13586. if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
  13587. kept.push_back (p);
  13588. return kept;
  13589. }();
  13590. return list;
  13591. }
  13592. // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
  13593. static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
  13594. {
  13595. lynx::Song song;
  13596. song.mixer = lynx::Song::defaultMixer (2);
  13597. if (p.instrument)
  13598. {
  13599. for (const auto& e : lynx::natives::instrumentEngines())
  13600. if (e.kind == p.instrumentKind)
  13601. {
  13602. auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
  13603. if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
  13604. if (! channel) return nullptr;
  13605. song.channels.push_back (*channel);
  13606. break;
  13607. }
  13608. if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
  13609. {
  13610. const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
  13611. auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
  13612. if (! channel)
  13613. {
  13614. channel = lynx::ChannelDef {};
  13615. channel->instrument = p.instrumentKind;
  13616. channel->name = name;
  13617. }
  13618. song.channels.push_back (*channel);
  13619. }
  13620. song.patterns.emplace_back();
  13621. }
  13622. else
  13623. {
  13624. song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
  13625. }
  13626. engine.setSong (std::move (song));
  13627. engine.dispatchPendingMessages();
  13628. if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
  13629. if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
  13630. if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
  13631. return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
  13632. }
  13633. // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
  13634. static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
  13635. {
  13636. lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
  13637. lynx::skin::setArtMotion (mode != "still");
  13638. }
  13639. bool runArtShots (const juce::File& folder, bool before)
  13640. {
  13641. folder.createDirectory();
  13642. auto ok = true;
  13643. juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
  13644. for (const auto& p : artPilots())
  13645. {
  13646. artPilotStyle (p, before ? "before" : "after");
  13647. lynx::AudioEngine offline (false);
  13648. auto editor = makeArtPilot (offline, p);
  13649. if (editor == nullptr || editor->getWidth() <= 0)
  13650. {
  13651. std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
  13652. ok = false;
  13653. continue;
  13654. }
  13655. if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
  13656. // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
  13657. auto fit = [&] (const juce::String& at) {
  13658. const auto f = lynx::skin::lastTitleFit();
  13659. if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
  13660. titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
  13661. << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
  13662. };
  13663. for (const auto scale : { 1.0f, 2.0f })
  13664. {
  13665. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  13666. lynx::skin::resetTitleFit();
  13667. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
  13668. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
  13669. if (scale == 1.0f) fit ("100");
  13670. }
  13671. // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
  13672. if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
  13673. {
  13674. editor->setSize (smallest.x, smallest.y);
  13675. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
  13676. lynx::skin::resetTitleFit();
  13677. savePng (lynx::shot::snapshot (*editor), file.getFullPathName());
  13678. fit ("min");
  13679. }
  13680. }
  13681. folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
  13682. lynx::skin::setForcedStyle (-1);
  13683. return ok;
  13684. }
  13685. struct ArtGuiRun final : juce::Timer
  13686. {
  13687. juce::File folder;
  13688. juce::String mode, report;
  13689. std::size_t at = 0;
  13690. int phase = 0;
  13691. double t0 = 0.0, c0 = 0.0;
  13692. std::unique_ptr<lynx::AudioEngine> engine;
  13693. std::unique_ptr<juce::DocumentWindow> window;
  13694. std::function<void()> done;
  13695. void start()
  13696. {
  13697. engine = std::make_unique<lynx::AudioEngine> (false);
  13698. report << "editor\tmode\tcpu % of one core\tart layer animating\n";
  13699. open();
  13700. startTimer (100);
  13701. }
  13702. void open()
  13703. {
  13704. window.reset();
  13705. const auto& pilots = artPilots();
  13706. if (at >= pilots.size())
  13707. {
  13708. folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
  13709. stopTimer();
  13710. lynx::skin::setForcedStyle (-1);
  13711. lynx::skin::setArtMotion (true);
  13712. if (done) done();
  13713. return;
  13714. }
  13715. const auto& p = pilots[at];
  13716. artPilotStyle (p, mode);
  13717. auto editor = makeArtPilot (*engine, p);
  13718. if (editor == nullptr) { ++at; open(); return; }
  13719. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
  13720. window->setUsingNativeTitleBar (true);
  13721. window->setContentOwned (editor.release(), true);
  13722. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  13723. window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
  13724. window->setAlwaysOnTop (true);
  13725. window->setVisible (true);
  13726. phase = 0;
  13727. t0 = juce::Time::getMillisecondCounterHiRes();
  13728. }
  13729. bool animating() const
  13730. {
  13731. if (window == nullptr || window->getContentComponent() == nullptr) return false;
  13732. std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
  13733. if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
  13734. for (auto* child : c.getChildren())
  13735. if (find (*child)) return true;
  13736. return false;
  13737. };
  13738. return find (*window->getContentComponent());
  13739. }
  13740. void timerCallback() override
  13741. {
  13742. const auto now = juce::Time::getMillisecondCounterHiRes();
  13743. const auto& p = artPilots()[at];
  13744. const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
  13745. const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
  13746. if (phase == 0 && now - t0 > 1500.0)
  13747. {
  13748. // the window's content on screen, in physical pixels, for the outside screenshot to crop
  13749. auto* c = window->getContentComponent();
  13750. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  13751. const auto b = c->getScreenBounds();
  13752. shotDone.deleteFile();
  13753. ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
  13754. + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
  13755. phase = 1;
  13756. t0 = now;
  13757. return;
  13758. }
  13759. if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
  13760. {
  13761. ready.deleteFile();
  13762. shotDone.deleteFile();
  13763. phase = 2;
  13764. t0 = now;
  13765. c0 = lynx::processCpuSeconds();
  13766. return;
  13767. }
  13768. if (phase == 2 && now - t0 > 6000.0)
  13769. {
  13770. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  13771. report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
  13772. ++at;
  13773. open();
  13774. }
  13775. }
  13776. };
  13777. std::unique_ptr<ArtGuiRun> artGui;
  13778. void runArtGui (const juce::File& folder, const juce::String& mode)
  13779. {
  13780. folder.createDirectory();
  13781. artGui = std::make_unique<ArtGuiRun>();
  13782. artGui->folder = folder;
  13783. artGui->mode = mode;
  13784. artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
  13785. artGui->start();
  13786. }
  13787. void runPluginEditorSnapshots (const juce::String& folder)
  13788. {
  13789. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13790. {
  13791. const juce::File out (folder);
  13792. out.createDirectory();
  13793. lynx::AudioEngine offline (false);
  13794. const auto roots = lynx::findFlStudioRoots();
  13795. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  13796. auto kinds = lynx::plugui::flLayoutKinds();
  13797. kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
  13798. for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
  13799. kinds.push_back (own);
  13800. kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
  13801. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
  13802. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
  13803. kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
  13804. const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
  13805. auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
  13806. auto ridgePasses = 0;
  13807. // round 173d3: the parity pictures of one editor — LYNX_PLUGUI_ONLY=<effect name>, LYNX_PLUGUI_PRESET=<.fst>,
  13808. // LYNX_PLUGUI_PAGES=<page,page,…> (the page numbers as the editor encodes them)
  13809. const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_ONLY", {});
  13810. const auto onlyPreset = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PRESET", {});
  13811. const auto onlyPages = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PAGES", {}), ",", "");
  13812. for (const auto kind : kinds)
  13813. {
  13814. if (only.isNotEmpty() && only != lynx::effectInfo (kind).name)
  13815. continue;
  13816. auto fx = lynx::makeEffectSlot (kind);
  13817. juce::String name (lynx::effectInfo (kind).name);
  13818. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  13819. {
  13820. const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
  13821. auto file = dir.getChildFile ("Default.fst");
  13822. if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
  13823. for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
  13824. file = f;
  13825. if (only.isNotEmpty() && onlyPreset.isNotEmpty())
  13826. file = juce::File (onlyPreset);
  13827. if (! file.existsAsFile())
  13828. {
  13829. auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
  13830. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
  13831. file = files.isEmpty() ? juce::File() : files[0];
  13832. }
  13833. juce::MemoryBlock data;
  13834. if (file.existsAsFile() && file.loadFileAsData (data))
  13835. {
  13836. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  13837. 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)
  13838. fx = *loaded;
  13839. }
  13840. name = juce::String::fromUTF8 (plugin.c_str());
  13841. break;
  13842. }
  13843. if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
  13844. {
  13845. juce::MemoryBlock data;
  13846. juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
  13847. lynx::maximusfx::Blob blob;
  13848. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  13849. blob.mix = 600;
  13850. const auto* b = static_cast<const std::uint8_t*> (data.getData());
  13851. blob.state.assign (b, b + data.getSize());
  13852. fx = lynx::makeEffectSlot (kind);
  13853. fx.state = lynx::maximusfx::pack (blob);
  13854. name = "Soundgoodizer";
  13855. }
  13856. if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
  13857. {
  13858. for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
  13859. { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
  13860. { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
  13861. { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
  13862. { "Process order", 0.4783f }, { "De-esser", 1.0f } })
  13863. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  13864. name = "Ridge Strip (Vocal strip)";
  13865. }
  13866. else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
  13867. {
  13868. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
  13869. { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
  13870. { "Filter split", 1.0f }, { "Expander", 1.0f } })
  13871. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  13872. name = "Ridge Strip (E console)";
  13873. }
  13874. else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
  13875. for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
  13876. { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
  13877. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  13878. if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
  13879. {
  13880. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
  13881. { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
  13882. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  13883. name = "Compressor (RComp role)";
  13884. }
  13885. if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
  13886. fx.params[0] = 0.33f;
  13887. if (kind == lynx::EffectKind::ember)
  13888. {
  13889. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
  13890. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
  13891. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
  13892. }
  13893. if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
  13894. for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
  13895. { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
  13896. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  13897. lynx::Song song;
  13898. song.mixer.resize (2);
  13899. song.mixer[0].name = "Master";
  13900. song.mixer[1].name = "Insert 1";
  13901. song.mixer[1].effects.push_back (fx);
  13902. offline.setSong (std::move (song));
  13903. offline.dispatchPendingMessages();
  13904. if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
  13905. {
  13906. auto editor = lynx::makeProEditor (offline, 1, 0, true);
  13907. auto image = lynx::shot::paint (*editor);
  13908. const auto file = lynx::shot::file (out.getChildFile (name + ".png"));
  13909. file.deleteFile();
  13910. juce::PNGImageFormat png;
  13911. if (auto stream = file.createOutputStream())
  13912. png.writeImageToStream (image, *stream);
  13913. continue;
  13914. }
  13915. const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  13916. std::vector<int> pageList;
  13917. for (int page = 0; page < pages; ++page)
  13918. pageList.push_back (page);
  13919. if (only.isNotEmpty() && ! onlyPages.isEmpty())
  13920. {
  13921. pageList.clear();
  13922. for (const auto& p : onlyPages)
  13923. pageList.push_back (p.getIntValue());
  13924. }
  13925. for (const auto page : pageList)
  13926. {
  13927. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  13928. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  13929. const auto file = lynx::shot::file (out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png"));
  13930. file.deleteFile();
  13931. juce::PNGImageFormat png;
  13932. if (auto stream = file.createOutputStream())
  13933. png.writeImageToStream (image, *stream);
  13934. }
  13935. }
  13936. // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
  13937. {
  13938. namespace ef = lynx::echosuite::echoform;
  13939. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  13940. fx.params[ef::rhythm] = 1.0f;
  13941. fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
  13942. fx.params[ef::rhythmDecay] = 0.25f;
  13943. fx.params[ef::rhythmTap1 + 2] = 0.45f;
  13944. fx.params[ef::feedback] = 0.25f;
  13945. fx.params[ef::era] = 0.5f;
  13946. for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
  13947. fx.params[(std::size_t) param] = value;
  13948. fx.params[ef::rhythmShape] = 0.5f; // swell
  13949. lynx::Song song;
  13950. song.mixer.resize (2);
  13951. song.mixer[0].name = "Master";
  13952. song.mixer[1].name = "Insert 1";
  13953. song.mixer[1].effects.push_back (fx);
  13954. offline.setSong (std::move (song));
  13955. offline.dispatchPendingMessages();
  13956. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  13957. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  13958. const auto file = lynx::shot::file (out.getChildFile ("Echoform-rhythm.png"));
  13959. file.deleteFile();
  13960. juce::PNGImageFormat png;
  13961. if (auto stream = file.createOutputStream())
  13962. png.writeImageToStream (image, *stream);
  13963. }
  13964. // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
  13965. {
  13966. namespace ef = lynx::echosuite::echoform;
  13967. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  13968. fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
  13969. fx.params[ef::style] = ef::styleValue (ef::Style::dual);
  13970. lynx::Song song;
  13971. song.mixer.resize (2);
  13972. song.mixer[0].name = "Master";
  13973. song.mixer[1].name = "Insert 1";
  13974. song.mixer[1].effects.push_back (fx);
  13975. offline.setSong (std::move (song));
  13976. offline.dispatchPendingMessages();
  13977. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  13978. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  13979. const auto file = lynx::shot::file (out.getChildFile ("Echoform-voicing.png"));
  13980. file.deleteFile();
  13981. juce::PNGImageFormat png;
  13982. if (auto stream = file.createOutputStream())
  13983. png.writeImageToStream (image, *stream);
  13984. }
  13985. // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
  13986. {
  13987. auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  13988. fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
  13989. fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
  13990. lynx::Song song;
  13991. song.mixer.resize (2);
  13992. song.mixer[0].name = "Master";
  13993. song.mixer[1].name = "Insert 1";
  13994. song.mixer[1].effects.push_back (fx);
  13995. offline.setSong (std::move (song));
  13996. offline.dispatchPendingMessages();
  13997. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  13998. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  13999. const auto file = lynx::shot::file (out.getChildFile ("Auto-pan-tweak.png"));
  14000. file.deleteFile();
  14001. juce::PNGImageFormat png;
  14002. if (auto stream = file.createOutputStream())
  14003. png.writeImageToStream (image, *stream);
  14004. }
  14005. // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
  14006. {
  14007. namespace em = lynx::mixsuite::ember;
  14008. auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
  14009. fx.params[em::voicing] = 1.0f;
  14010. fx.params[em::classicDrive] = 0.35f;
  14011. lynx::Song song;
  14012. song.mixer.resize (2);
  14013. song.mixer[0].name = "Master";
  14014. song.mixer[1].name = "Insert 1";
  14015. song.mixer[1].effects.push_back (fx);
  14016. offline.setSong (std::move (song));
  14017. offline.dispatchPendingMessages();
  14018. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  14019. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  14020. const auto file = lynx::shot::file (out.getChildFile ("Ember Saturator-classic.png"));
  14021. file.deleteFile();
  14022. juce::PNGImageFormat png;
  14023. if (auto stream = file.createOutputStream())
  14024. png.writeImageToStream (image, *stream);
  14025. }
  14026. // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
  14027. {
  14028. auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
  14029. fx.params[14] = 1.0f; // the measured plate voicing
  14030. fx.params[15] = 1.0f; // View = Plate
  14031. lynx::Song song;
  14032. song.mixer.resize (2);
  14033. song.mixer[0].name = "Master";
  14034. song.mixer[1].name = "Insert 1";
  14035. song.mixer[1].effects.push_back (fx);
  14036. offline.setSong (std::move (song));
  14037. offline.dispatchPendingMessages();
  14038. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  14039. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  14040. const auto file = lynx::shot::file (out.getChildFile ("Foil Plate-plate.png"));
  14041. file.deleteFile();
  14042. juce::PNGImageFormat png;
  14043. if (auto stream = file.createOutputStream())
  14044. png.writeImageToStream (image, *stream);
  14045. }
  14046. // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
  14047. // and LYNX Tune (demo pitch phrase)
  14048. {
  14049. lynx::setNativeEditorDemo (true);
  14050. using namespace lynx::facet;
  14051. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  14052. const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
  14053. { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
  14054. { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
  14055. };
  14056. for (int b = 0; b < 5; ++b)
  14057. {
  14058. eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
  14059. eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
  14060. eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
  14061. eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
  14062. eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
  14063. eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
  14064. }
  14065. eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
  14066. const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
  14067. lynx::Song song;
  14068. song.mixer.resize (2);
  14069. song.mixer[0].name = "Master";
  14070. song.mixer[1].name = "Vocal";
  14071. song.mixer[1].effects.push_back (fx);
  14072. offline.setSong (std::move (song));
  14073. offline.dispatchPendingMessages();
  14074. auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
  14075. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  14076. const auto f = lynx::shot::file (out.getChildFile (file));
  14077. f.deleteFile();
  14078. juce::PNGImageFormat png;
  14079. if (auto stream = f.createOutputStream())
  14080. png.writeImageToStream (image, *stream);
  14081. };
  14082. own (eq, "Facet EQ.png", true);
  14083. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
  14084. {
  14085. // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
  14086. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  14087. tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
  14088. tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
  14089. tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
  14090. // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
  14091. tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
  14092. tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
  14093. tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
  14094. tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
  14095. tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
  14096. tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
  14097. own (tune, "LYNX Tune-p2.png", false, 1);
  14098. }
  14099. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
  14100. lynx::setNativeEditorDemo (false);
  14101. }
  14102. // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
  14103. const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
  14104. 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" } })
  14105. {
  14106. juce::MemoryBlock data;
  14107. if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
  14108. {
  14109. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  14110. files.sort();
  14111. for (const auto& f : files)
  14112. {
  14113. juce::MemoryBlock block;
  14114. if (! f.loadFileAsData (block))
  14115. continue;
  14116. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  14117. try
  14118. {
  14119. const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
  14120. if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
  14121. {
  14122. preset = nullptr;
  14123. data = block;
  14124. break;
  14125. }
  14126. }
  14127. catch (const std::exception&)
  14128. {
  14129. }
  14130. }
  14131. }
  14132. auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
  14133. : generators.getChildFile (folder).getChildFile (preset);
  14134. if (! file.existsAsFile())
  14135. {
  14136. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  14137. files.sort();
  14138. file = files.isEmpty() ? juce::File() : files[0];
  14139. }
  14140. if (data.isEmpty() && ! file.loadFileAsData (data))
  14141. continue;
  14142. try
  14143. {
  14144. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  14145. auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
  14146. if (project.channels.empty())
  14147. continue;
  14148. project.channels.front().type = flp::ChannelType::native;
  14149. lynx::FlpImportOptions options;
  14150. options.roots = roots;
  14151. options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
  14152. options.readFile = [] (const std::string& path) {
  14153. juce::MemoryBlock block;
  14154. lynx::platform::localFile (path).loadFileAsData (block);
  14155. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  14156. return std::vector<std::uint8_t> (b, b + block.getSize());
  14157. };
  14158. options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  14159. const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
  14160. f.getParentDirectory().createDirectory();
  14161. f.replaceWithData (wav.data(), wav.size());
  14162. return f.getFullPathName().toStdString();
  14163. };
  14164. auto song = lynx::importFlp (project, options);
  14165. // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
  14166. if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
  14167. {
  14168. song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
  14169. song.channels.front().modelParams.assign (3, 32768.0f);
  14170. }
  14171. if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
  14172. {
  14173. song.channels.front().instrument = lynx::InstrumentKind::flkeys;
  14174. song.channels.front().pluginState = project.channels.front().pluginState;
  14175. }
  14176. offline.setSong (std::move (song));
  14177. offline.dispatchPendingMessages();
  14178. if (offline.getSong().channels.empty())
  14179. continue;
  14180. auto panel = lynx::makeChannelSettingsPanel (offline, 0);
  14181. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  14182. const auto out2 = lynx::shot::file (out.getChildFile (juce::String (folder) + ".png"));
  14183. out2.deleteFile();
  14184. juce::PNGImageFormat png;
  14185. if (auto stream = out2.createOutputStream())
  14186. png.writeImageToStream (image, *stream);
  14187. }
  14188. catch (const std::exception&)
  14189. {
  14190. }
  14191. }
  14192. }
  14193. quit();
  14194. }
  14195. void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
  14196. {
  14197. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14198. // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
  14199. struct VideoShot final : juce::Timer
  14200. {
  14201. lynx::AudioEngine offline { false };
  14202. std::unique_ptr<juce::Component> editor;
  14203. juce::String prefix, report;
  14204. int step = 0;
  14205. std::function<void()> done;
  14206. void moveTo (double seconds)
  14207. {
  14208. offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
  14209. }
  14210. void timerCallback() override
  14211. {
  14212. static constexpr double times[] = { 0.0, 1.5, 3.25 };
  14213. constexpr int typeInStep = (int) std::size (times) + 1;
  14214. if (step > 0 && step < typeInStep && editor != nullptr)
  14215. savePng (lynx::shot::snapshot (*editor), prefix + "-" + juce::String (step - 1) + ".png");
  14216. if (editor != nullptr && step == (int) std::size (times))
  14217. {
  14218. // round 174d: FL's in-place type-in of the current time (a right click on it)
  14219. lynx::videoview::openTypeIn (*editor, 2);
  14220. ++step;
  14221. return;
  14222. }
  14223. if (editor != nullptr && step == typeInStep)
  14224. savePng (lynx::shot::snapshot (*editor), prefix + "-typein.png");
  14225. if (editor == nullptr || step >= typeInStep)
  14226. {
  14227. stopTimer();
  14228. juce::File (prefix + "-report.txt").replaceWithText (report);
  14229. if (done)
  14230. done();
  14231. return;
  14232. }
  14233. moveTo (times[step++]);
  14234. }
  14235. };
  14236. static std::unique_ptr<VideoShot> shot;
  14237. shot = std::make_unique<VideoShot>();
  14238. shot->prefix = prefix;
  14239. auto& offline = shot->offline;
  14240. lynx::videoview::install (offline);
  14241. lynx::Song song;
  14242. song.mixer = lynx::Song::defaultMixer (2);
  14243. lynx::ChannelDef c;
  14244. c.name = "Fruity Video Player";
  14245. c.instrument = lynx::InstrumentKind::videoplayer;
  14246. lynx::video::Settings vs;
  14247. vs.path = juce::File (videoPath).getFullPathName().toStdString();
  14248. vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
  14249. c.pluginState = lynx::video::write (vs);
  14250. song.channels.push_back (c);
  14251. song.patterns.emplace_back();
  14252. {
  14253. // round 174d (A3): the same Video Player in a song whose tempo drops from 120 to 60 BPM at bar 5, for FL
  14254. // (LYNX.exe --export-flp <prefix>-tempo.lynx <prefix>-tempo.flp), to compare FL's video clock with LYNX's
  14255. auto fl = song;
  14256. fl.bpm = 120.0;
  14257. fl.mode = lynx::PlayMode::song;
  14258. auto settings = vs;
  14259. settings.delay = 0;
  14260. settings.timeDisplay = lynx::video::Settings {}.timeDisplay;
  14261. fl.channels[0].pluginState = lynx::video::write (settings);
  14262. fl.patterns[0].name = "Pattern 1";
  14263. lynx::Automation tempo;
  14264. tempo.name = "Tempo";
  14265. tempo.target = { lynx::AutomationTargetKind::tempo, 0, 0, 0 };
  14266. const auto bar = (std::int64_t) lynx::ppq * 4;
  14267. tempo.points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { bar * 4 - 1, lynx::valueFromTempo (120.0), 0.0f },
  14268. { bar * 4, lynx::valueFromTempo (60.0), 0.0f }, { bar * 8, lynx::valueFromTempo (60.0), 0.0f } };
  14269. fl.automations.push_back (tempo);
  14270. lynx::Clip at;
  14271. at.kind = lynx::ClipKind::automation;
  14272. at.automation = 0;
  14273. at.track = 1;
  14274. at.start = 0;
  14275. at.length = bar * 8;
  14276. fl.playlist.push_back (at);
  14277. lynx::Clip pc;
  14278. pc.pattern = 0;
  14279. pc.track = 0;
  14280. pc.start = 0;
  14281. pc.length = bar * 8;
  14282. fl.playlist.push_back (pc);
  14283. juce::String error;
  14284. lynx::ProjectFile::save (fl, juce::File (prefix + "-tempo.lynx"), error);
  14285. }
  14286. offline.setSong (std::move (song));
  14287. offline.dispatchPendingMessages();
  14288. auto& report = shot->report;
  14289. report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
  14290. report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
  14291. shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
  14292. if (shot->editor != nullptr)
  14293. shot->editor->setVisible (true);
  14294. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  14295. shot->startTimer (1500);
  14296. }
  14297. void runVideoTrackShot (const juce::String& prefix, const juce::String& videoPath, const juce::String& secondPath)
  14298. {
  14299. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14300. struct TrackShot final : juce::Timer
  14301. {
  14302. lynx::AudioEngine offline { false };
  14303. std::unique_ptr<lynx::PlaylistComponent> playlist;
  14304. std::unique_ptr<lynx::media::FrameDecoder> decoder;
  14305. juce::String prefix, report, path;
  14306. double fps = 25.0;
  14307. int step = 0, waits = 0, adrStep = 0;
  14308. std::unique_ptr<juce::Component> adrPanel;
  14309. std::function<void()> done;
  14310. // song times (s): before, inside the first clip (on and between frame edges), across the second clip
  14311. std::vector<double> times { 0.0, 1.0, 2.0 + 1.0 / 25.0, 2.5, 4.0, 7.3 };
  14312. void timerCallback() override
  14313. {
  14314. if (step > 0 && adrStep == 0)
  14315. {
  14316. // the frame the decoder shows for the wanted file time (the clip starts at song 1.0 s, offset 0)
  14317. const auto want = times[(std::size_t) step - 1] - 1.0;
  14318. double ft = -1.0;
  14319. const auto img = decoder->frame (ft);
  14320. const auto expected = std::floor (want * fps + 1e-6) / fps;
  14321. if (want >= 0.0 && ft < expected - 1e-3 && ++waits < 20)
  14322. return; // (still decoding)
  14323. waits = 0;
  14324. report << "song " << juce::String (times[(std::size_t) step - 1], 3) << " s: wanted file time " << juce::String (want, 4)
  14325. << ", frame shown at " << juce::String (ft, 4) << " (expected " << juce::String (expected, 4) << ")"
  14326. << (want < 0.0 ? " [before the clip]" : std::abs (ft - expected) < 1e-3 ? " OK" : " MISMATCH") << "\n";
  14327. savePng (lynx::shot::snapshot (*playlist), prefix + "-playlist-" + juce::String (step - 1) + ".png");
  14328. if (img.isValid())
  14329. savePng (img, prefix + "-frame-" + juce::String (step - 1) + ".png");
  14330. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  14331. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  14332. savePng (lynx::shot::snapshot (*c), prefix + "-window-" + juce::String (step - 1) + ".png");
  14333. }
  14334. if (step >= (int) times.size() && adrStep == 0)
  14335. {
  14336. // the ADR window: two cues, takes on the first; the play position inside the streamer before the in
  14337. // point (4.0 s), so the video window shows the streamer and the line
  14338. adrStep = 1;
  14339. offline.editSong ([] (lynx::Song& s) {
  14340. lynx::AdrCue a, b;
  14341. a.id = "SC1-01";
  14342. a.in = 4.0;
  14343. a.out = 6.4;
  14344. a.character = "Dr. Silva";
  14345. a.line = "We have to leave before the storm reaches the coast.";
  14346. a.notes = "softer, out of breath";
  14347. a.status = lynx::AdrCue::Status::recorded;
  14348. for (int n = 1; n <= 3; ++n)
  14349. {
  14350. lynx::AdrTake t;
  14351. t.number = n;
  14352. t.name = lynx::adr::takeName (a, n);
  14353. t.rating = n == 2 ? 4 : n;
  14354. t.circled = n == 2;
  14355. a.takes.push_back (t);
  14356. }
  14357. a.selected = 2;
  14358. lynx::adr::setCompRange (a, 4.0, 5.1, 2);
  14359. lynx::adr::setCompRange (a, 5.1, 6.4, 3);
  14360. b.id = "SC1-02";
  14361. b.in = 8.0;
  14362. b.out = 9.5;
  14363. b.character = "Marta";
  14364. b.line = "Then we go now.";
  14365. s.adr.cues = { a, b };
  14366. s.adr.current = 0;
  14367. });
  14368. adrPanel = lynx::adrwindow::makePanel (offline);
  14369. adrPanel->setSize (1200, 640);
  14370. adrPanel->setVisible (true);
  14371. offline.getTransport().positionTicks.store (3.0 * offline.getSong().bpm / 60.0 * lynx::ppq);
  14372. decoder->request (2.0, false);
  14373. return;
  14374. }
  14375. if (adrStep == 1)
  14376. {
  14377. adrStep = 2;
  14378. savePng (lynx::shot::snapshot (*adrPanel), prefix + "-adr.png");
  14379. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  14380. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  14381. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window.png");
  14382. offline.getTransport().positionTicks.store (4.5 * offline.getSong().bpm / 60.0 * lynx::ppq);
  14383. decoder->request (3.5, false);
  14384. return;
  14385. }
  14386. if (adrStep == 2)
  14387. {
  14388. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  14389. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  14390. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window-line.png");
  14391. adrPanel.reset();
  14392. // export with video: a 3 s mix under the picture, re-encoded (the clip starts at 1 s) and copied (from 1 s)
  14393. {
  14394. const juce::File wav (prefix + "-mix.wav");
  14395. wav.deleteFile();
  14396. juce::WavAudioFormat format;
  14397. if (std::unique_ptr<juce::OutputStream> os (wav.createOutputStream().release()); os != nullptr)
  14398. if (std::unique_ptr<juce::AudioFormatWriter> w (format.createWriterFor (os.get(), 48000.0, 2, 16, {}, 0)); w != nullptr)
  14399. {
  14400. os.release();
  14401. juce::AudioBuffer<float> b (2, 48000 * 3);
  14402. for (int k = 0; k < b.getNumSamples(); ++k)
  14403. 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));
  14404. w->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  14405. }
  14406. for (const auto origin : { 0.0, 1.0 })
  14407. {
  14408. const juce::File out (prefix + "-mux-" + juce::String ((int) origin) + ".mp4");
  14409. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  14410. const auto error = lynx::videotracks::muxWithVideo (offline.getSong(), origin, wav, out);
  14411. report << "export with video from " << origin << " s: " << (error.isEmpty() ? "OK " + juce::String (out.getSize()) + " bytes" : "FAILED " + error)
  14412. << " (" << juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0, 2) << " s)\n";
  14413. }
  14414. }
  14415. stopTimer();
  14416. report << "frames decoded " << decoder->frameCount() << ", dropped " << decoder->droppedCount() << "\n";
  14417. juce::File (prefix + "-report.txt").replaceWithText (report);
  14418. if (done)
  14419. done();
  14420. return;
  14421. }
  14422. const auto t = times[(std::size_t) step++];
  14423. offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
  14424. decoder->request (std::max (0.0, t - 1.0), false);
  14425. }
  14426. };
  14427. static std::unique_ptr<TrackShot> shot;
  14428. shot = std::make_unique<TrackShot>();
  14429. shot->prefix = prefix;
  14430. auto& offline = shot->offline;
  14431. lynx::Song song;
  14432. song.mixer = lynx::Song::defaultMixer (2);
  14433. song.patterns.emplace_back();
  14434. song.mode = lynx::PlayMode::song;
  14435. song.bpm = 120.0;
  14436. offline.setSong (std::move (song));
  14437. offline.dispatchPendingMessages();
  14438. const juce::File video (videoPath);
  14439. const auto pr = lynx::media::probe (video.getFullPathName());
  14440. auto& report = shot->report;
  14441. report << "decoder: " << (pr.backend.isEmpty() ? juce::String ("none") : pr.backend) << " (system: " << lynx::media::nativeBackendName()
  14442. << ", ffmpeg: " << lynx::findFfmpeg().getFullPathName() << ")\n";
  14443. report << "video: " << pr.info.width << "x" << pr.info.height << " " << juce::String (pr.info.fps, 3) << " fps " << juce::String (pr.info.duration, 3)
  14444. << " s, sound " << (pr.info.hasAudio ? "yes" : "no") << "\n";
  14445. shot->fps = pr.info.fps > 1.0 ? pr.info.fps : 25.0;
  14446. shot->times[2] = 2.0 + 1.0 / shot->fps; // (exactly on a frame edge)
  14447. lynx::videotracks::importVideo (offline, video, 1.0, -1);
  14448. if (secondPath.isNotEmpty())
  14449. lynx::videotracks::importVideo (offline, juce::File (secondPath), 3.0, 1);
  14450. offline.editSong ([] (lynx::Song& s) {
  14451. s.video.startTimecode = 3600.0;
  14452. s.video.burnIn = true;
  14453. if (s.videoTracks.size() < 2)
  14454. s.videoTracks.push_back ({});
  14455. s.videoTracks[0].name = "Picture";
  14456. s.videoTracks[1].name = "Reference";
  14457. });
  14458. report << "project rate: " << lynx::vtime::rateName (offline.getSong().video.rate) << ", clip 1: "
  14459. << juce::String (offline.getSong().videoTracks[0].clips.empty() ? -1.0 : offline.getSong().videoTracks[0].clips[0].length, 3) << " s\n";
  14460. // the project round trip
  14461. {
  14462. const juce::File file (prefix + "-project.lynx");
  14463. juce::String error;
  14464. lynx::ProjectFile::save (offline.getSong(), file, error);
  14465. const auto back = lynx::ProjectFile::load (file, error);
  14466. report << "project file round trip: " << (back && back->videoTracks == offline.getSong().videoTracks && back->video == offline.getSong().video ? "OK" : "MISMATCH " + error) << "\n";
  14467. }
  14468. shot->playlist = std::make_unique<lynx::PlaylistComponent> (offline);
  14469. shot->playlist->setSize (1400, 640);
  14470. shot->playlist->setVisible (true);
  14471. shot->decoder = std::make_unique<lynx::media::FrameDecoder>();
  14472. shot->decoder->setSource (video.getFullPathName(), pr.info);
  14473. shot->decoder->setSize (pr.info.width, pr.info.height);
  14474. shot->decoder->startThread (juce::Thread::Priority::low);
  14475. lynx::videotracks::showWindow (offline, 0);
  14476. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  14477. shot->startTimer (700);
  14478. }
  14479. void runDanceShot (const juce::String& prefix)
  14480. {
  14481. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14482. // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
  14483. {
  14484. constexpr int cell = 120, cols = 8;
  14485. auto sheet = lynx::shot::canvas (130 + cols * cell, lynx::dance::moveCount * cell + 10);
  14486. {
  14487. // (the picture is complete when its Graphics is gone: round 190ba, the file was blank on Windows)
  14488. juce::Graphics g (sheet);
  14489. lynx::shot::logical (g);
  14490. g.fillAll (lynx::theme::colour::bg0);
  14491. for (int m = 0; m < lynx::dance::moveCount; ++m)
  14492. {
  14493. g.setColour (lynx::theme::colour::textSecondary);
  14494. g.setFont (14.0f);
  14495. g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
  14496. for (int k = 0; k < cols; ++k)
  14497. {
  14498. const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
  14499. lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
  14500. }
  14501. }
  14502. }
  14503. savePng (sheet, prefix + "-moves.png");
  14504. }
  14505. lynx::AudioEngine offline (false);
  14506. lynx::Song song;
  14507. song.mixer = lynx::Song::defaultMixer (2);
  14508. for (int d = 0; d < 2; ++d)
  14509. {
  14510. lynx::ChannelDef c;
  14511. c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
  14512. c.instrument = lynx::InstrumentKind::fruitydance;
  14513. lynx::dance::Settings s;
  14514. s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
  14515. s.x = d == 0 ? 520 : 760;
  14516. s.y = 560;
  14517. s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
  14518. s.mirrored = d == 1;
  14519. c.pluginState = lynx::dance::toState (s);
  14520. song.channels.push_back (c);
  14521. }
  14522. // Issue #121 (round 190ba): a sprite sheet in FL's Fruity Dance format (8 frames across, a row per move, a names
  14523. // file beside it), made here from LYNX's own poses, loaded back as a user's sheet would be
  14524. juce::String sheetReport;
  14525. {
  14526. constexpr int fw = 120, fh = 150;
  14527. const std::vector<std::pair<const char*, int>> rows { { "Idle", lynx::dance::waiting }, { "Step", lynx::dance::stepping },
  14528. { "Jump", lynx::dance::jumping }, { "Wave", lynx::dance::waving },
  14529. { "Windmill", lynx::dance::windmill }, { "Held", lynx::dance::held } };
  14530. juce::Image sheet (juce::Image::ARGB, fw * lynx::dance::sheetColumns, fh * (int) rows.size(), true);
  14531. {
  14532. juce::Graphics g (sheet);
  14533. for (int r = 0; r < (int) rows.size(); ++r)
  14534. for (int k = 0; k < lynx::dance::sheetColumns; ++k)
  14535. {
  14536. juce::Graphics::ScopedSaveState save (g);
  14537. g.reduceClipRegion (k * fw, r * fh, fw, fh);
  14538. lynx::dancer::draw (g, { (k + 0.5f) * fw, (float) (r + 1) * fh - 8.0f }, 96.0f,
  14539. lynx::dance::pose (rows[(std::size_t) r].second, k / (double) lynx::dance::sheetColumns, 1), false, juce::Colour (0xff35c46a));
  14540. }
  14541. }
  14542. const juce::File picture (prefix + "-sheet.png");
  14543. savePng (sheet, picture.getFullPathName());
  14544. juce::String names;
  14545. for (const auto& [name, move] : rows)
  14546. names << (names.isEmpty() ? "" : "\r\n") << name;
  14547. picture.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  14548. // a picture that is not a whole number of frames: FL's "Bitmap size is incorrect."
  14549. const juce::File wrong (prefix + "-sheet-wrong.png");
  14550. savePng (sheet.getClippedImage ({ 0, 0, sheet.getWidth() - 3, sheet.getHeight() }), wrong.getFullPathName());
  14551. wrong.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  14552. auto error = lynx::dancer::SheetError::none;
  14553. const auto loaded = lynx::dancer::sheetFor (picture.getFullPathName().toStdString(), &error);
  14554. auto wrongError = lynx::dancer::SheetError::none;
  14555. const auto refused = lynx::dancer::sheetFor (wrong.getFullPathName().toStdString(), &wrongError);
  14556. auto missingError = lynx::dancer::SheetError::none;
  14557. const auto missing = lynx::dancer::sheetFor (juce::File (prefix + "-sheet-none.png").getFullPathName().toStdString(), &missingError);
  14558. sheetReport << "sheet_loaded=" << (loaded != nullptr ? 1 : 0) << "\n"
  14559. << "sheet_wrong_size_refused=" << (refused == nullptr && wrongError == lynx::dancer::SheetError::size ? 1 : 0) << "\n"
  14560. << "sheet_missing_refused=" << (missing == nullptr && missingError == lynx::dancer::SheetError::missing ? 1 : 0) << "\n";
  14561. bool ok = loaded != nullptr && refused == nullptr && missing == nullptr;
  14562. if (loaded != nullptr)
  14563. {
  14564. sheetReport << "sheet_rows=" << loaded->layout.rows << "\nsheet_frame=" << loaded->layout.frameWidth << "x" << loaded->layout.frameHeight
  14565. << "\nsheet_moves=" << loaded->moves() << "\nsheet_names=";
  14566. for (const auto& n : loaded->names)
  14567. sheetReport << juce::String::fromUTF8 (n.c_str()) << ";";
  14568. sheetReport << "\n";
  14569. ok = ok && loaded->layout.rows == (int) rows.size() && loaded->layout.frameWidth == fw && loaded->layout.frameHeight == fh;
  14570. // the animation as the stage draws it: a row of moments of the move "Wave" (blending on), then mirrored,
  14571. // then the row shown while the dancer is held
  14572. auto strip = lynx::shot::canvas (fw * 12, fh * 3 + 20);
  14573. int solid = 0;
  14574. {
  14575. juce::Graphics g (strip);
  14576. lynx::shot::logical (g);
  14577. g.fillAll (lynx::theme::colour::bg0);
  14578. for (int line = 0; line < 3; ++line)
  14579. {
  14580. lynx::dance::SheetAnimator animator (3);
  14581. for (int k = 0; k < 12; ++k)
  14582. {
  14583. const auto frame = animator.advance (k / 12.0 + 0.001, loaded->layout.rows, 4, line == 1, true, 0.5f, line == 2);
  14584. const juce::Point<float> feet ((k + 0.5f) * fw, (float) (line + 1) * fh + 5.0f);
  14585. lynx::dancer::drawSheet (g, *loaded, feet, 1.0f, frame);
  14586. solid += lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (0.0f, -70.0f)) ? 1 : 0;
  14587. ok = ok && ! lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (-(float) fw * 0.5f + 1.0f, -(float) fh + 1.0f));
  14588. }
  14589. }
  14590. }
  14591. // mirrored = the same frame flipped left-right, on whatever renderer this build draws with
  14592. {
  14593. lynx::dance::SheetFrame plain;
  14594. plain.row = 3;
  14595. plain.column = 2;
  14596. auto turned = plain;
  14597. turned.mirrored = true;
  14598. juce::Image a (juce::Image::ARGB, fw, fh, true), b (juce::Image::ARGB, fw, fh, true);
  14599. {
  14600. juce::Graphics ga (a);
  14601. lynx::dancer::drawSheet (ga, *loaded, { fw * 0.5f, (float) fh }, 1.0f, plain);
  14602. }
  14603. {
  14604. juce::Graphics gb (b);
  14605. lynx::dancer::drawSheet (gb, *loaded, { fw * 0.5f, (float) fh }, 1.0f, turned);
  14606. }
  14607. int same = 0, flippedSame = 0, solidPixels = 0;
  14608. for (int y = 0; y < fh; ++y)
  14609. for (int x = 0; x < fw; ++x)
  14610. {
  14611. const auto pa = a.getPixelAt (x, y);
  14612. if (pa.getAlpha() < 200)
  14613. continue;
  14614. ++solidPixels;
  14615. auto alike = [pa] (juce::Colour c) {
  14616. return std::abs ((int) c.getRed() - (int) pa.getRed()) + std::abs ((int) c.getGreen() - (int) pa.getGreen())
  14617. + std::abs ((int) c.getBlue() - (int) pa.getBlue()) + std::abs ((int) c.getAlpha() - (int) pa.getAlpha()) < 12;
  14618. };
  14619. same += alike (b.getPixelAt (x, y)) ? 1 : 0;
  14620. flippedSame += alike (b.getPixelAt (fw - 1 - x, y)) ? 1 : 0;
  14621. }
  14622. const auto flips = solidPixels > 500 && flippedSame >= solidPixels * 98 / 100 && same < solidPixels * 95 / 100;
  14623. sheetReport << "sheet_mirror_flips=" << (flips ? 1 : 0) << " (" << flippedSame << " of " << solidPixels << " solid pixels match flipped, " << same
  14624. << " unflipped)\n";
  14625. ok = ok && flips;
  14626. }
  14627. sheetReport << "sheet_body_solid=" << solid << "/36\n";
  14628. ok = ok && solid >= 18;
  14629. savePng (strip, prefix + "-sheet-frames.png");
  14630. }
  14631. sheetReport << "sheet_result=" << (ok ? "OK" : "ERROR") << "\n";
  14632. lynx::ChannelDef c;
  14633. c.name = "Fruity Dance #3";
  14634. c.instrument = lynx::InstrumentKind::fruitydance;
  14635. lynx::dance::Settings s;
  14636. s.move = 2; // (the sheet's second row: "Step")
  14637. s.x = 1000;
  14638. s.y = 560;
  14639. s.sheet = picture.getFullPathName().toStdString();
  14640. c.pluginState = lynx::dance::toState (s);
  14641. song.channels.push_back (c);
  14642. }
  14643. song.patterns.emplace_back();
  14644. {
  14645. const juce::File demo (prefix + "-demo.lynx");
  14646. juce::String error;
  14647. lynx::ProjectFile::save (song, demo, error);
  14648. }
  14649. offline.setSong (std::move (song));
  14650. offline.dispatchPendingMessages();
  14651. if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
  14652. savePng (lynx::shot::snapshot (*editor), prefix + "-editor.png");
  14653. if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
  14654. savePng (lynx::shot::snapshot (*frame), prefix + "-frame.png");
  14655. if (auto editor = lynx::makeChannelSettingsPanel (offline, 2))
  14656. savePng (lynx::shot::snapshot (*editor), prefix + "-sheet-editor.png");
  14657. {
  14658. // the stage with the three dancers (the third from the sheet)
  14659. lynx::DanceStage stage (offline);
  14660. stage.setSize (1280, 640);
  14661. stage.update();
  14662. sheetReport << "stage_dancers=" << stage.dancerCount() << "\n";
  14663. auto picture = lynx::shot::canvas (1280, 640);
  14664. {
  14665. juce::Graphics g (picture);
  14666. lynx::shot::logical (g);
  14667. g.fillAll (lynx::theme::colour::bg0);
  14668. stage.paintEntireComponent (g, true);
  14669. }
  14670. savePng (picture, prefix + "-sheet-stage.png");
  14671. }
  14672. juce::File (prefix + "-sheetreport.txt").replaceWithText (sheetReport);
  14673. }
  14674. void runControllerShot (const juce::String& prefix)
  14675. {
  14676. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14677. lynx::AudioEngine offline (false);
  14678. lynx::Song song;
  14679. song.mixer = lynx::Song::defaultMixer (2);
  14680. song.mixer[1].name = "Insert 1";
  14681. auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
  14682. lynx::formula::State formula;
  14683. formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
  14684. fx.state = lynx::formula::writeState (formula);
  14685. fx.params[0] = 0.5f;
  14686. fx.params[1] = 0.25f;
  14687. fx.params[2] = 0.5f;
  14688. song.mixer[1].effects.push_back (fx);
  14689. // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
  14690. {
  14691. auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
  14692. xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
  14693. xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
  14694. xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
  14695. song.mixer[1].effects.push_back (xyFx);
  14696. auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
  14697. xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
  14698. song.mixer[1].effects.push_back (xyzFx);
  14699. // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
  14700. xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
  14701. xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
  14702. xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
  14703. xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
  14704. song.mixer[1].effects.push_back (xyzFx);
  14705. auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
  14706. lynx::SurfaceControl c;
  14707. for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
  14708. { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
  14709. { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
  14710. { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
  14711. { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
  14712. { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
  14713. { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
  14714. {
  14715. c.kind = kind;
  14716. c.name = name;
  14717. c.value = v;
  14718. c.valueY = 0.6f;
  14719. c.x = x;
  14720. c.y = y;
  14721. lynx::surface::add (panel, c);
  14722. }
  14723. song.mixer[1].effects.push_back (panel);
  14724. }
  14725. lynx::ChannelDef env;
  14726. env.name = "Envelope Controller";
  14727. env.instrument = lynx::InstrumentKind::controller;
  14728. auto ecData = lynx::defaultEnvelopeController();
  14729. ecData[0].lfoOn = true;
  14730. ecData[0].lfoTempo = true;
  14731. ecData[0].lfoSpeed = 40898;
  14732. ecData[0].maps[lynx::mapKeyboard].count = 2;
  14733. ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  14734. ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  14735. ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
  14736. env.controllerState = lynx::writeEnvelopeController (ecData);
  14737. song.channels.push_back (env);
  14738. lynx::ChannelDef out;
  14739. out.name = "MIDI Out";
  14740. out.instrument = lynx::InstrumentKind::midiOut;
  14741. lynx::midictl::MidiOutSettings settings;
  14742. settings.port = 1;
  14743. lynx::midictl::writeMidiOut (out.pluginState, settings);
  14744. song.channels.push_back (out);
  14745. // a Layer (round 164) over three synths split across the keyboard, crossfading
  14746. for (const auto* name : { "Bass", "Pad", "Lead" })
  14747. {
  14748. lynx::ChannelDef c;
  14749. c.name = name;
  14750. c.instrument = lynx::InstrumentKind::synth;
  14751. song.channels.push_back (c);
  14752. }
  14753. {
  14754. lynx::ChannelDef layer;
  14755. layer.name = "Layer";
  14756. layer.instrument = lynx::InstrumentKind::layer;
  14757. song.channels.push_back (layer);
  14758. const auto self = (int) song.channels.size() - 1;
  14759. lynx::layer::setChildren (song, self, { 2, 3, 4 });
  14760. song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
  14761. song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
  14762. song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
  14763. song.channels[(std::size_t) self].layer.crossfade = true;
  14764. song.channels[(std::size_t) self].layer.fade = 0.35f;
  14765. }
  14766. {
  14767. lynx::ChannelDef dash; // channel 6
  14768. dash.name = "Dashboard";
  14769. dash.instrument = lynx::InstrumentKind::dashboard;
  14770. dash.patcher.surface = lynx::surface::starterControls();
  14771. song.channels.push_back (dash);
  14772. }
  14773. {
  14774. lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
  14775. volt.name = "Voltage Controller";
  14776. volt.instrument = lynx::InstrumentKind::voltage;
  14777. lynx::voltage::Settings v;
  14778. v.enabled = true;
  14779. v.params[9] = 49152;
  14780. v.unipolar[2] = true;
  14781. v.tracks = { 3, 0, 0 };
  14782. v.source[6] = lynx::voltage::Source::clock;
  14783. volt.pluginState = lynx::voltage::write (v);
  14784. song.channels.push_back (volt);
  14785. }
  14786. song.patterns.emplace_back();
  14787. offline.setSong (std::move (song));
  14788. offline.dispatchPendingMessages();
  14789. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  14790. if (c == nullptr)
  14791. return;
  14792. savePng (lynx::shot::snapshot (*c), prefix + name);
  14793. };
  14794. shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
  14795. shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
  14796. shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
  14797. shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
  14798. {
  14799. const auto slotOf = [] (int k) -> lynx::SlotLocator {
  14800. return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
  14801. };
  14802. const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
  14803. shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
  14804. shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
  14805. shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
  14806. shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
  14807. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
  14808. shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
  14809. }
  14810. // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
  14811. if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
  14812. for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
  14813. {
  14814. juce::MemoryBlock bytes;
  14815. if (! file.loadFileAsData (bytes))
  14816. continue;
  14817. const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
  14818. const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
  14819. if (! dash || dash->controls.empty())
  14820. continue;
  14821. offline.editSong ([&] (lynx::Song& s) {
  14822. s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
  14823. s.channels[6].patcher.surface = dash->controls;
  14824. s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
  14825. });
  14826. offline.dispatchPendingMessages();
  14827. const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
  14828. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
  14829. // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
  14830. if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
  14831. {
  14832. std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
  14833. for (auto* child : c.getChildren())
  14834. {
  14835. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
  14836. b->setToggleState (true, juce::sendNotificationSync);
  14837. pressEdit (*child);
  14838. }
  14839. };
  14840. pressEdit (*panel);
  14841. shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
  14842. }
  14843. }
  14844. // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
  14845. if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
  14846. for (int part = 0; part < 7; ++part)
  14847. {
  14848. for (auto* child : ec->getChildren())
  14849. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  14850. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  14851. savePng (lynx::shot::snapshot (*ec), prefix + "-ec-part" + juce::String (part) + ".png");
  14852. }
  14853. lynx::FormulaControllerWindows::open (offline, 1, 0);
  14854. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  14855. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  14856. if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
  14857. savePng (lynx::shot::snapshot (*w->getContentComponent()), prefix + "-formula-controller.png");
  14858. lynx::FormulaControllerWindows::closeAll();
  14859. }
  14860. bool runEdisonSlotTest (const juce::String& folderPath, const juce::String& flp)
  14861. {
  14862. namespace ae = lynx::audioedit;
  14863. namespace ef = lynx::edisonfx;
  14864. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14865. const juce::File folder (folderPath);
  14866. folder.createDirectory();
  14867. juce::String report;
  14868. bool all = true;
  14869. auto check = [&] (const juce::String& name, bool ok, const juce::String& note = {}) {
  14870. report << name << "=" << (ok ? "ok" : "FAIL") << (note.isNotEmpty() ? " (" + note + ")" : juce::String()) << "\n";
  14871. all = all && ok;
  14872. };
  14873. auto shot = [&folder] (juce::Component& c, const juce::String& name) {
  14874. savePng (lynx::shot::paint (c, lynx::theme::panel), folder.getChildFile (name).getFullPathName());
  14875. };
  14876. auto findSlot = [] (const lynx::Song& song, int& track, int& slot) {
  14877. for (track = 0; track < (int) song.mixer.size(); ++track)
  14878. for (slot = 0; slot < (int) song.mixer[(std::size_t) track].effects.size(); ++slot)
  14879. if (song.mixer[(std::size_t) track].effects[(std::size_t) slot].kind == lynx::EffectKind::edison)
  14880. return true;
  14881. return false;
  14882. };
  14883. {
  14884. lynx::AudioEngine engine (false);
  14885. engine.setRecordingTarget (folder.getChildFile ("Audio").getChildFile ("Recorded"), "Test");
  14886. // a project without the plugin is written as before: nothing of it in the file, and it reads back the same
  14887. const auto before = lynx::ProjectFile::toJson (engine.getSong(), false);
  14888. juce::String error;
  14889. const auto same = lynx::ProjectFile::fromJson (before, error);
  14890. check ("old_project_text_has_no_trace", ! before.containsIgnoreCase ("edison"));
  14891. check ("old_project_round_trip_stable", same.has_value() && lynx::ProjectFile::toJson (*same, false) == before);
  14892. const auto at = lynx::addEdisonSlot (engine, 1);
  14893. engine.dispatchPendingMessages();
  14894. check ("slot_added_to_first_empty_slot", at == 0 && engine.getSong().mixer[1].effects.size() == 1
  14895. && engine.getSong().mixer[1].effects[0].kind == lynx::EffectKind::edison);
  14896. if (at < 0)
  14897. {
  14898. folder.getChildFile ("report.txt").replaceWithText (report);
  14899. return false;
  14900. }
  14901. const auto second = lynx::addEdisonSlot (engine, 1); // several instances on a track
  14902. engine.dispatchPendingMessages();
  14903. check ("second_instance_on_the_same_track", second == 1);
  14904. engine.editSong ([at] (lynx::Song& s) {
  14905. s.mixer[1].effects[(std::size_t) at].params[ef::recordMode] = ef::modeValue (ef::Mode::now);
  14906. });
  14907. engine.dispatchPendingMessages();
  14908. const auto slotOf = [&engine, at] { return engine.getSong().mixer[1].effects[(std::size_t) at]; };
  14909. const auto fx = engine.getEffect (1, at);
  14910. const auto p = std::dynamic_pointer_cast<ef::Processor> (fx);
  14911. const auto session = ef::findSession (slotOf().instance.id);
  14912. check ("engine_built_the_effect_with_its_session", p != nullptr && session != nullptr);
  14913. const auto other = ef::findSession (engine.getSong().mixer[1].effects[1].instance.id);
  14914. check ("instances_have_their_own_audio", other != nullptr && other != session);
  14915. if (p == nullptr || session == nullptr)
  14916. {
  14917. folder.getChildFile ("report.txt").replaceWithText (report);
  14918. return false;
  14919. }
  14920. // idle: the audio passes through bit for bit
  14921. const auto rate = p->sampleRate();
  14922. std::vector<float> l (512), r (512);
  14923. auto fill = [&] (int block) {
  14924. for (int k = 0; k < 512; ++k)
  14925. {
  14926. const auto t = (double) (block * 512 + k) / rate;
  14927. l[(std::size_t) k] = 0.6f * (float) std::sin (2.0 * 3.141592653589793 * 220.0 * t);
  14928. r[(std::size_t) k] = 0.4f * (float) std::sin (2.0 * 3.141592653589793 * 330.0 * t);
  14929. }
  14930. };
  14931. fill (0);
  14932. auto inL = l, inR = r;
  14933. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  14934. check ("idle_pass_through_bit_exact", l == inL && r == inR);
  14935. // a take through the slot (Now), then the flush that makes it a file of the project
  14936. std::vector<float> wantL, wantR;
  14937. check ("record_starts", session->start (p, true));
  14938. for (int block = 0; block < 60; ++block)
  14939. {
  14940. fill (block);
  14941. wantL.insert (wantL.end(), l.begin(), l.end());
  14942. wantR.insert (wantR.end(), r.begin(), r.end());
  14943. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  14944. }
  14945. session->stop();
  14946. check ("take_is_the_input", session->document().audio.numChannels() == 2 && session->document().audio.channels[0] == wantL
  14947. && session->document().audio.channels[1] == wantR);
  14948. ae::Document withMarkers = session->document();
  14949. ae::addMarker (withMarkers, 4000, "Verse");
  14950. ae::addMarker (withMarkers, 12000);
  14951. ae::setLoop (withMarkers, { 2000, 20000 });
  14952. session->setDocument (withMarkers);
  14953. engine.flushEdisonAudio();
  14954. engine.dispatchPendingMessages();
  14955. const juce::File file (juce::String::fromUTF8 (slotOf().samplePath.c_str()));
  14956. check ("audio_written_to_the_project_folder", file.existsAsFile() && file.isAChildOf (folder.getChildFile ("Audio").getChildFile ("Recorded")),
  14957. file.getFullPathName());
  14958. check ("file_listed_with_the_session_recordings", std::find (engine.getSessionRecordings().begin(), engine.getSessionRecordings().end(), file)
  14959. != engine.getSessionRecordings().end());
  14960. check ("effect_kept_running_through_the_flush", engine.getEffect (1, at) == fx);
  14961. check ("nothing_unsaved_after_the_flush", ! session->dirty());
  14962. engine.flushEdisonAudio(); // (a second flush writes nothing new)
  14963. check ("second_flush_keeps_the_file", juce::File (juce::String::fromUTF8 (slotOf().samplePath.c_str())) == file);
  14964. // the project file: saved, loaded, the same slot with the same audio
  14965. engine.editSong ([at] (lynx::Song& s) {
  14966. auto& params = s.mixer[1].effects[(std::size_t) at].params;
  14967. params[ef::recordMode] = ef::modeValue (ef::Mode::onPlay);
  14968. params[ef::append] = 0.0f;
  14969. params[ef::muteInput] = 1.0f;
  14970. params[ef::slave] = 1.0f;
  14971. params[ef::maxTime] = 5.0f / 6.0f;
  14972. });
  14973. engine.capturePluginStates();
  14974. const auto project = folder.getChildFile ("edison-slot.lynx");
  14975. check ("project_saved", lynx::ProjectFile::save (engine.getSong(), project, error), error);
  14976. auto loaded = lynx::ProjectFile::load (project, error);
  14977. check ("project_loaded", loaded.has_value(), error);
  14978. if (loaded)
  14979. {
  14980. const auto& a = slotOf();
  14981. const auto& b = loaded->mixer[1].effects[(std::size_t) at];
  14982. check ("slot_kind_kept", b.kind == lynx::EffectKind::edison && loaded->mixer[1].effects.size() == 2);
  14983. check ("slot_settings_kept", ef::modeOf (b.params) == ef::Mode::onPlay && b.params[ef::append] < 0.5f && b.params[ef::muteInput] >= 0.5f
  14984. && b.params[ef::slave] >= 0.5f && ef::maxTimeIndexOf (b.params) == 5
  14985. && std::abs (b.params[ef::noiseThreshold] - a.params[ef::noiseThreshold]) < 1.0e-6f);
  14986. check ("slot_audio_path_kept", b.samplePath == a.samplePath);
  14987. check ("project_text_round_trip_stable", lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (engine.getSong(), false));
  14988. lynx::AudioEngine second (false);
  14989. second.setSong (std::move (*loaded));
  14990. second.dispatchPendingMessages();
  14991. const auto reopened = ef::findSession (second.getSong().mixer[1].effects[(std::size_t) at].instance.id);
  14992. check ("reopened_project_has_the_audio", reopened != nullptr && reopened != session
  14993. && reopened->document().audio.channels == withMarkers.audio.channels
  14994. && reopened->document().audio.sampleRate == withMarkers.audio.sampleRate);
  14995. check ("reopened_project_has_markers_and_loop", reopened != nullptr && reopened->document().markers.size() == 2
  14996. && reopened->document().markers[0].name == "Verse"
  14997. && reopened->document().loopStart == 2000 && reopened->document().loopEnd == 20000);
  14998. check ("reopened_empty_instance_is_empty", ef::findSession (second.getSong().mixer[1].effects[1].instance.id) != nullptr
  14999. && ef::findSession (second.getSong().mixer[1].effects[1].instance.id)->document().audio.empty());
  15000. if (auto editor = lynx::makeEdisonSlotEditor (second, 1, at))
  15001. {
  15002. editor->setSize (1120, 600);
  15003. second.dispatchPendingMessages();
  15004. shot (*editor, "slot-editor-reopened.png");
  15005. }
  15006. }
  15007. // the plugin's window: the audio editor on the slot (empty instance, then the one with the take)
  15008. if (auto editor = lynx::makeEdisonSlotEditor (engine, 1, 1))
  15009. {
  15010. editor->setSize (1120, 600);
  15011. engine.dispatchPendingMessages();
  15012. shot (*editor, "slot-editor-empty.png");
  15013. }
  15014. auto editor = lynx::makeEdisonSlotEditor (engine, 1, at);
  15015. check ("slot_window_is_the_audio_editor", editor != nullptr);
  15016. if (editor != nullptr)
  15017. {
  15018. editor->setSize (1120, 600);
  15019. engine.dispatchPendingMessages();
  15020. shot (*editor, "slot-editor.png");
  15021. juce::File (folder.getChildFile ("slot-menu.txt")).replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  15022. }
  15023. check ("no_editor_for_other_slots", lynx::makeEdisonSlotEditor (engine, 0, 0) == nullptr);
  15024. editor.reset();
  15025. // deleting the slot leaves the song without it (the file stays for the unused-recordings prompt)
  15026. engine.editSong ([at] (lynx::Song& s) { s.mixer[1].effects.erase (s.mixer[1].effects.begin() + at); });
  15027. engine.dispatchPendingMessages();
  15028. check ("deleted_slot_is_gone", engine.getSong().mixer[1].effects.size() == 1 && file.existsAsFile());
  15029. }
  15030. if (flp.isNotEmpty())
  15031. {
  15032. lynx::AudioEngine engine (false);
  15033. juce::String error;
  15034. const auto imported = engine.importFlpFile (juce::File (flp), error);
  15035. engine.dispatchPendingMessages();
  15036. check ("flp_imported", imported, error);
  15037. int count = 0, withAudio = 0;
  15038. const auto& song = engine.getSong();
  15039. for (int t = 0; t < (int) song.mixer.size(); ++t)
  15040. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  15041. {
  15042. const auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) s];
  15043. if (fx.kind != lynx::EffectKind::edison)
  15044. continue;
  15045. ++count;
  15046. const auto session = ef::findSession (fx.instance.id);
  15047. const auto frames = session != nullptr ? session->document().audio.frames() : -1;
  15048. withAudio += frames > 0 ? 1 : 0;
  15049. report << "flp_slot track " << t << " slot " << s << ": mode " << ef::modeName (ef::modeOf (fx.params))
  15050. << ", append " << (fx.params[ef::append] >= 0.5f ? "on" : "off") << ", mute input " << (fx.params[ef::muteInput] >= 0.5f ? "on" : "off")
  15051. << ", slave " << (fx.params[ef::slave] >= 0.5f ? "on" : "off") << ", loop " << (fx.params[ef::loopPlay] >= 0.5f ? "on" : "off")
  15052. << ", max time index " << ef::maxTimeIndexOf (fx.params) << ", threshold " << juce::String (fx.params[ef::noiseThreshold], 4)
  15053. << ", state " << (int) fx.state.size() << " bytes, audio " << (juce::int64) frames << " frames"
  15054. << (session != nullptr && frames > 0 ? " at " + juce::String (session->document().audio.sampleRate, 0) + " Hz, "
  15055. + juce::String (session->document().audio.numChannels()) + " ch, "
  15056. + juce::String ((int) session->document().markers.size()) + " markers"
  15057. : juce::String())
  15058. << "\n";
  15059. if (count == 1 || (frames > 0 && withAudio == 1))
  15060. if (auto editor = lynx::makeEdisonSlotEditor (engine, t, s))
  15061. {
  15062. editor->setSize (1120, 600);
  15063. engine.dispatchPendingMessages();
  15064. shot (*editor, frames > 0 ? "slot-editor-flp-audio.png" : "slot-editor-flp.png");
  15065. }
  15066. }
  15067. check ("flp_edison_slots_kept_as_the_plugin", count > 0, juce::String (count) + " slots, " + juce::String (withAudio) + " with audio");
  15068. // saved as .lynx and read again: still the plugin, FL's state (the audio) with it
  15069. int t = 0, s = 0;
  15070. if (findSlot (song, t, s))
  15071. {
  15072. const auto project = folder.getChildFile ("edison-flp.lynx");
  15073. const auto saved = lynx::ProjectFile::save (song, project, error);
  15074. std::optional<lynx::Song> loaded;
  15075. if (saved)
  15076. loaded = lynx::ProjectFile::load (project, error);
  15077. check ("flp_slot_survives_the_project_file", loaded.has_value() && t < (int) loaded->mixer.size()
  15078. && s < (int) loaded->mixer[(std::size_t) t].effects.size()
  15079. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::edison
  15080. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].state == song.mixer[(std::size_t) t].effects[(std::size_t) s].state
  15081. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].params == song.mixer[(std::size_t) t].effects[(std::size_t) s].params,
  15082. error);
  15083. }
  15084. }
  15085. // round 190ct (live FL check 190cq): the open-and-record preset, the fresh defaults and the question before
  15086. // "Remove all Edison instances", in the app
  15087. {
  15088. lynx::AudioEngine engine (false);
  15089. lynx::MainComponent ui (engine, false);
  15090. ui.setSize (1600, 900);
  15091. engine.dispatchPendingMessages();
  15092. const auto toolsMenu = [&ui] {
  15093. const auto names = ui.getMenuNamesForSnapshot();
  15094. for (int m = 0; m < names.size(); ++m)
  15095. if (names[m] == lynx::tr ("Tools"))
  15096. return ui.getMenuForSnapshot (m);
  15097. return juce::PopupMenu();
  15098. };
  15099. const auto removeItem = [&toolsMenu] (bool& found, bool& enabled) {
  15100. found = enabled = false;
  15101. const auto menu = toolsMenu(); // (the iterator keeps a reference)
  15102. for (juce::PopupMenu::MenuItemIterator it (menu, true); it.next();)
  15103. if (it.getItem().text == lynx::tr ("Remove all Edison instances"))
  15104. {
  15105. found = true;
  15106. enabled = it.getItem().isEnabled;
  15107. if (enabled && it.getItem().action)
  15108. it.getItem().action(); // asks: nothing may go before the answer
  15109. return;
  15110. }
  15111. };
  15112. const auto count = [&engine] {
  15113. int n = 0;
  15114. for (const auto& track : engine.getSong().mixer)
  15115. for (const auto& fx : track.effects)
  15116. n += fx.kind == lynx::EffectKind::edison ? 1 : 0;
  15117. return n;
  15118. };
  15119. bool found = false, enabled = false;
  15120. removeItem (found, enabled);
  15121. check ("remove_all_edison_enabled_with_none", found && enabled && count() == 0);
  15122. const auto plain = lynx::addEdisonSlot (engine, 1);
  15123. const auto armed = lynx::addEdisonSlot (engine, 2, true);
  15124. engine.dispatchPendingMessages();
  15125. if (plain >= 0 && armed >= 0)
  15126. {
  15127. const auto& a = engine.getSong().mixer[1].effects[(std::size_t) plain].params;
  15128. const auto& b = engine.getSong().mixer[2].effects[(std::size_t) armed].params;
  15129. check ("open_audio_editor_fresh_defaults", ef::modeOf (a) == ef::Mode::onInput && ef::maxTimeIndexOf (a) == 5 && a[ef::append] >= 0.5f
  15130. && a[ef::slave] < 0.5f);
  15131. check ("open_audio_editor_and_record_preset", ef::modeOf (b) == ef::Mode::onPlay && ef::maxTimeIndexOf (b) == 3 && b[ef::append] < 0.5f
  15132. && b[ef::slave] >= 0.5f);
  15133. }
  15134. else
  15135. check ("open_audio_editor_slots_added", false);
  15136. removeItem (found, enabled);
  15137. engine.dispatchPendingMessages();
  15138. check ("remove_all_edison_asks_first", found && enabled && count() == 2);
  15139. const auto question = lynx::removeAllEdisonInstancesQuestion();
  15140. check ("remove_all_edison_question_is_fls", question.getTitle() == lynx::tr ("Remove Edison instances")
  15141. && question.getMessage() == lynx::tr ("Are you sure you want to remove all Edison instances from the project ?")
  15142. && question.getNumButtons() == 2 && question.getButtonText (0) == lynx::tr ("Yes")
  15143. && question.getButtonText (1) == lynx::tr ("No"));
  15144. // LYNX keeps an undo for the removal (rollup 190cv), so the question may not promise "(No undo)" in any
  15145. // language, and the Yes action must come back with one undo
  15146. {
  15147. bool noUndoLine = false;
  15148. for (const auto& line : juce::StringArray::fromLines (question.getMessage()))
  15149. noUndoLine = noUndoLine || line.trim().startsWithChar ('(');
  15150. check ("remove_all_edison_question_has_no_no_undo_line", ! noUndoLine && ! question.getMessage().contains ("No undo"));
  15151. const int before = count();
  15152. lynx::removeAllEdisonInstances (engine);
  15153. engine.dispatchPendingMessages();
  15154. const int removed = count();
  15155. engine.undo();
  15156. engine.dispatchPendingMessages();
  15157. check ("remove_all_edison_yes_removes_and_undo_restores", before == 2 && removed == 0 && count() == 2);
  15158. }
  15159. {
  15160. juce::AlertWindow box (question.getTitle(), question.getMessage(), question.getIconType());
  15161. box.addButton (question.getButtonText (0), 1);
  15162. box.addButton (question.getButtonText (1), 0);
  15163. box.setSize (box.getWidth(), box.getHeight());
  15164. savePng (lynx::shot::paint (box, lynx::theme::panel), folder.getChildFile ("remove-all-edison-question.png").getFullPathName());
  15165. }
  15166. {
  15167. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::edison);
  15168. lynx::edisonfx::setOpenAndRecord (slot.params);
  15169. engine.editSong ([&slot] (lynx::Song& s) { s.mixer[3].effects.push_back (slot); });
  15170. engine.dispatchPendingMessages();
  15171. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 3, 0))
  15172. {
  15173. editor->setSize (1120, 600);
  15174. engine.dispatchPendingMessages();
  15175. shot (*editor, "slot-editor-open-and-record.png");
  15176. }
  15177. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 1, plain))
  15178. {
  15179. editor->setSize (1120, 600);
  15180. engine.dispatchPendingMessages();
  15181. shot (*editor, "slot-editor-fresh-defaults.png");
  15182. }
  15183. }
  15184. }
  15185. report << (all ? "ALL OK\n" : "FAILURES\n");
  15186. folder.getChildFile ("report.txt").replaceWithText (report);
  15187. return all;
  15188. }
  15189. void runEdisonShot (const juce::String& prefix, const juce::String& file)
  15190. {
  15191. namespace ae = lynx::audioedit;
  15192. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15193. lynx::AudioEngine offline (false);
  15194. ae::Document d;
  15195. if (file.isNotEmpty())
  15196. {
  15197. juce::MemoryBlock bytes;
  15198. if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
  15199. {
  15200. std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
  15201. return;
  15202. }
  15203. }
  15204. else
  15205. {
  15206. // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
  15207. d.title = "Drum loop";
  15208. d.audio.sampleRate = 44100.0;
  15209. const auto frames = (std::size_t) (44100 * 2);
  15210. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  15211. std::uint32_t seed = 7;
  15212. for (std::size_t i = 0; i < frames; ++i)
  15213. {
  15214. seed = seed * 1664525u + 1013904223u;
  15215. const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
  15216. const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
  15217. d.audio.channels[0][i] = hiss + hum;
  15218. d.audio.channels[1][i] = hiss * 0.9f + hum;
  15219. }
  15220. for (int hit = 0; hit < 8; ++hit)
  15221. {
  15222. const auto at = (std::size_t) hit * frames / 8;
  15223. const auto kick = hit % 2 == 0;
  15224. double phase = 0.0;
  15225. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  15226. {
  15227. seed = seed * 1664525u + 1013904223u;
  15228. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  15229. const auto t = (double) i / 44100.0;
  15230. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  15231. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  15232. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  15233. d.audio.channels[0][at + i] += v;
  15234. d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
  15235. }
  15236. }
  15237. for (int hit = 1; hit < 8; ++hit)
  15238. ae::addMarker (d, (std::int64_t) (hit * frames / 8));
  15239. ae::setLoop (d, { 0, (std::int64_t) frames });
  15240. }
  15241. // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
  15242. 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 } };
  15243. auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
  15244. auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
  15245. auto image = lynx::shot::paint (c, lynx::theme::panel);
  15246. savePng (image, prefix + name);
  15247. };
  15248. editor->setSize (1120, 600);
  15249. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
  15250. shot (*editor, "-editor-volume-envelope.png");
  15251. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
  15252. juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  15253. // round 190ee: the first marker's menu (Trigger note) and FL's four snap modes on a probe frame
  15254. if (! d.markers.empty())
  15255. juce::File (prefix + "-marker-menu.txt").replaceWithText (lynx::audioEditorMarkerMenuForSnapshot (*editor, 0).joinIntoString ("\n") + "\n");
  15256. {
  15257. juce::StringArray snaps;
  15258. const auto probe = (std::int64_t) (d.audio.frames() * 3 / 8) + 777;
  15259. for (int mode = 0; mode < 4; ++mode)
  15260. snaps.add (lynx::setAudioEditorSnapForSnapshot (*editor, mode, probe));
  15261. juce::File (prefix + "-snap.txt").replaceWithText (snaps.joinIntoString ("\n") + "\n");
  15262. shot (*editor, "-editor-snap-on.png");
  15263. }
  15264. for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
  15265. {
  15266. const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
  15267. if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
  15268. {
  15269. offline.dispatchPendingMessages();
  15270. const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
  15271. shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
  15272. if (envelopeTool)
  15273. shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
  15274. panel.reset(); // (puts the envelope back)
  15275. }
  15276. }
  15277. }
  15278. static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
  15279. {
  15280. if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
  15281. return b;
  15282. for (auto* child : root.getChildren())
  15283. if (auto* b = findButton (*child, text))
  15284. return b;
  15285. return nullptr;
  15286. }
  15287. // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
  15288. void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
  15289. {
  15290. const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
  15291. for (const auto& [tab, file] : tabs)
  15292. if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
  15293. {
  15294. b->onClick();
  15295. savePng (lynx::shot::snapshot (panel), name + "-tab-" + file + ".png");
  15296. }
  15297. engine.editSong ([&] (lynx::Song& s) {
  15298. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  15299. auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
  15300. settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
  15301. " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
  15302. st.fl = lynx::vfx::writeScript (settings);
  15303. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  15304. });
  15305. engine.dispatchPendingMessages();
  15306. if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
  15307. {
  15308. engine.dispatchPendingMessages();
  15309. if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
  15310. b->onClick();
  15311. savePng (lynx::shot::snapshot (*broken), name + "-error.png");
  15312. }
  15313. }
  15314. void runVfxShot (const juce::String& prefix)
  15315. {
  15316. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15317. lynx::AudioEngine offline (false);
  15318. lynx::MainComponent ui (offline, false);
  15319. ui.setSize (1280, 720);
  15320. auto song = lynx::Song::makeDefault();
  15321. song.channels.clear();
  15322. for (const auto kind : lynx::vfx::allKinds)
  15323. {
  15324. lynx::ChannelDef c;
  15325. lynx::vfx::makeChannel (c, kind);
  15326. if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
  15327. for (const auto& p : lynx::vfx::builtInPresets (kind))
  15328. if (p.name == "Major triad")
  15329. {
  15330. auto st = *lynx::vfx::readState (c.pluginState);
  15331. st.fl = p.fl;
  15332. c.pluginState = lynx::vfx::writeState (st);
  15333. }
  15334. song.channels.push_back (c);
  15335. }
  15336. // a Patcher: its notes through a Color Mapper to three synths
  15337. lynx::ChannelDef patcher;
  15338. patcher.name = "Patcher";
  15339. patcher.instrument = lynx::InstrumentKind::patcher;
  15340. lynx::PatchNode mapper;
  15341. mapper.generator = true;
  15342. lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
  15343. mapper.x = 260.0f;
  15344. patcher.patcher.nodes.push_back (mapper);
  15345. lynx::PatchWire notes;
  15346. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  15347. patcher.patcher.wires.push_back (notes);
  15348. for (int k = 0; k < 3; ++k)
  15349. {
  15350. lynx::PatchNode synth;
  15351. synth.generator = true;
  15352. synth.channel.instrument = lynx::InstrumentKind::synth;
  15353. synth.channel.name = "Synth " + std::to_string (k + 1);
  15354. synth.x = 520.0f, synth.y = (float) k * 90.0f;
  15355. patcher.patcher.nodes.push_back (synth);
  15356. lynx::PatchWire in, out;
  15357. in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
  15358. out.from = 1 + k, out.to = lynx::patchToHost;
  15359. patcher.patcher.wires.push_back (in);
  15360. patcher.patcher.wires.push_back (out);
  15361. }
  15362. patcher.patcher.outputX = 760.0f;
  15363. song.channels.push_back (patcher);
  15364. offline.setSong (std::move (song));
  15365. offline.dispatchPendingMessages();
  15366. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  15367. if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
  15368. {
  15369. offline.dispatchPendingMessages();
  15370. savePng (lynx::shot::snapshot (*panel),
  15371. prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
  15372. }
  15373. // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
  15374. // a Script with FL's "Snap To Scale"
  15375. if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
  15376. {
  15377. const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
  15378. const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
  15379. { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
  15380. { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
  15381. };
  15382. for (const auto& [kind, path] : extra)
  15383. {
  15384. juce::MemoryBlock bytes;
  15385. if (! data.getChildFile (path).loadFileAsData (bytes))
  15386. continue;
  15387. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  15388. const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
  15389. int index = -1;
  15390. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  15391. if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
  15392. index = c;
  15393. if (! fl || index < 0)
  15394. continue;
  15395. offline.editSong ([&] (lynx::Song& s) {
  15396. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  15397. st.fl = *fl;
  15398. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  15399. });
  15400. offline.dispatchPendingMessages();
  15401. if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
  15402. {
  15403. offline.dispatchPendingMessages();
  15404. const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
  15405. savePng (lynx::shot::snapshot (*panel), name + "-fl.png");
  15406. if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
  15407. shootScriptTabs (*panel, offline, index, name);
  15408. }
  15409. }
  15410. }
  15411. lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
  15412. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  15413. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  15414. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  15415. {
  15416. auto* content = w->getContentComponent();
  15417. savePng (lynx::shot::snapshot (*content), prefix + "-patcher.png");
  15418. delete w;
  15419. break;
  15420. }
  15421. lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
  15422. savePng (image, prefix + "-patcher-menu-" + name + ".png");
  15423. });
  15424. // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
  15425. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
  15426. {
  15427. const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
  15428. offline.getPluginHost().setPluginName (key, "1_EQ");
  15429. offline.editSong ([] (lynx::Song& s) {
  15430. if (s.mixer.size() > 1)
  15431. {
  15432. lynx::EffectSlot slot;
  15433. slot.kind = lynx::EffectKind::parametricEq;
  15434. s.mixer[1].effects.push_back (slot);
  15435. }
  15436. });
  15437. offline.dispatchPendingMessages();
  15438. {
  15439. lynx::QuickAddTargets targets;
  15440. targets.addInstrument = [] (lynx::ChannelDef) {};
  15441. targets.addEffect = [] (lynx::EffectSlot) {};
  15442. auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
  15443. savePng (lynx::shot::snapshot (*palette), prefix + "-quickadd-renamed.png");
  15444. }
  15445. ui.selectTabForSnapshot (3);
  15446. ui.getMixerForSnapshot().selectTrack (1);
  15447. offline.dispatchPendingMessages();
  15448. savePng (lynx::shot::snapshot (ui), prefix + "-mixer-renamed.png");
  15449. offline.getPluginHost().setPluginName (key, "");
  15450. }
  15451. }
  15452. void runAudioXShot (const juce::String& prefix)
  15453. {
  15454. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15455. lynx::AudioEngine offline (false);
  15456. {
  15457. lynx::MainComponent ui (offline, false);
  15458. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  15459. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  15460. offline.dispatchPendingMessages();
  15461. // 1. sends: insert 1 feeds insert 3 pre-fader and insert 4 post-fader (FL's way)
  15462. offline.editSong ([] (lynx::Song& s) {
  15463. if (s.mixer.size() < 5)
  15464. return;
  15465. s.mixer[1].name = "Vocal";
  15466. s.mixer[3].name = "Reverb";
  15467. s.mixer[4].name = "Delay";
  15468. s.setRoute (1, 3, true);
  15469. s.setRoute (1, 4, true);
  15470. s.setRouteLevel (1, 3, 0.6f);
  15471. s.setRouteLevel (1, 4, 0.4f);
  15472. s.setSendPre (1, 3, true);
  15473. });
  15474. offline.dispatchPendingMessages();
  15475. ui.selectTabForSnapshot (3);
  15476. ui.getMixerForSnapshot().selectTrack (1);
  15477. offline.dispatchPendingMessages();
  15478. saveSnapshot (ui, prefix + "-send-pre.png");
  15479. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  15480. saveMenus (juce::StringArray { "Send to Reverb (pre-fader)", "Send to Delay (post-fader)" },
  15481. std::vector<juce::PopupMenu> { strips.buildSendMenu (3), strips.buildSendMenu (4) }, prefix + "-send-menu.png");
  15482. // 2. low latency while recording: the monitored track's look-ahead limiter is bypassed, the EQ stays
  15483. offline.editSong ([] (lynx::Song& s) {
  15484. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::parametricEq));
  15485. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  15486. s.mixer[1].inputChannel = 0;
  15487. s.mixer[1].monitor = lynx::InputMonitor::on;
  15488. });
  15489. offline.dispatchPendingMessages();
  15490. saveSnapshot (ui, prefix + "-lowlat-off.png");
  15491. auto options = offline.getRecordOptions();
  15492. options.lowLatencyRecording = true;
  15493. offline.setRecordOptions (options);
  15494. offline.dispatchPendingMessages();
  15495. ui.getMixerForSnapshot().selectTrack (1);
  15496. offline.dispatchPendingMessages();
  15497. saveSnapshot (ui, prefix + "-lowlat-on.png");
  15498. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getFullRecordMenuForSnapshot() }, prefix + "-lowlat-menu.png");
  15499. juce::String report;
  15500. report << "latency_with_option=" << offline.getLatencySamples() << " bypassed_slots=" << offline.lowLatencyBypassedCount() << "\n";
  15501. options.lowLatencyRecording = false;
  15502. offline.setRecordOptions (options);
  15503. offline.dispatchPendingMessages();
  15504. report << "latency_without_option=" << offline.getLatencySamples() << "\n";
  15505. // 3. the Browser's "Preview in time": a 120 BPM loop previewed in a 140 BPM project
  15506. const auto dir = juce::File (prefix).getParentDirectory().getChildFile ("audiox-preview");
  15507. dir.createDirectory();
  15508. const auto wav = dir.getChildFile ("Drum loop 120 bpm.wav");
  15509. {
  15510. const int frames = 44100 * 4;
  15511. juce::AudioBuffer<float> audio (1, frames);
  15512. for (int i = 0; i < frames; ++i)
  15513. {
  15514. const auto t = (double) (i % 22050) / 44100.0;
  15515. 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)));
  15516. }
  15517. wav.deleteFile();
  15518. juce::WavAudioFormat format;
  15519. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  15520. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  15521. {
  15522. out.release();
  15523. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  15524. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  15525. }
  15526. }
  15527. offline.getTransport().bpm.store (140.0);
  15528. offline.setPreviewInTime (true);
  15529. ui.showDesktopForSnapshot (false);
  15530. offline.previewFile (wav);
  15531. offline.finishPreviewJobs();
  15532. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  15533. offline.dispatchPendingMessages();
  15534. saveSnapshot (ui, prefix + "-preview-in-time.png");
  15535. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { ui.getBrowserForSnapshot().buildViewMenu() }, prefix + "-preview-menu.png");
  15536. const auto& timing = offline.getPreviewTiming();
  15537. report << "preview file_bpm=" << timing.fileBpm << " project_bpm=" << timing.projectBpm << " ratio=" << timing.ratio
  15538. << " prepare_ms=" << juce::String (offline.getLastPreviewPrepareMs(), 1) << "\n";
  15539. offline.previewFile ({});
  15540. offline.setPreviewInTime (false);
  15541. juce::File (prefix + "-report.txt").replaceWithText (report);
  15542. }
  15543. }
  15544. void runComp177Shot (const juce::String& prefix, const juce::String& projectPath)
  15545. {
  15546. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15547. lynx::AudioEngine offline (false);
  15548. {
  15549. lynx::MainComponent ui (offline, false);
  15550. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  15551. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  15552. ui.openFile (juce::File (projectPath));
  15553. offline.dispatchPendingMessages();
  15554. ui.selectTabForSnapshot (2);
  15555. offline.dispatchPendingMessages();
  15556. auto& playlist = ui.getPlaylistForSnapshot();
  15557. std::int64_t last = 0;
  15558. for (const auto& c : offline.getSong().playlist)
  15559. last = std::max (last, c.end());
  15560. const auto bars = juce::jmax (1, (int) (last / (4 * lynx::ppq)) + 1);
  15561. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  15562. // (the first paint asks for the clips' waveforms, a worker thread loads them)
  15563. saveSnapshot (ui, prefix + "-opened.png");
  15564. juce::Thread::sleep (3000);
  15565. offline.dispatchPendingMessages();
  15566. saveSnapshot (ui, prefix + "-opened.png");
  15567. // a muted clip selected
  15568. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  15569. if (offline.getSong().playlist[(std::size_t) c].muted)
  15570. {
  15571. playlist.selectClipsForSnapshot ({ c });
  15572. offline.dispatchPendingMessages();
  15573. saveSnapshot (ui, prefix + "-selected.png");
  15574. playlist.selectClipsForSnapshot ({});
  15575. break;
  15576. }
  15577. juce::String report;
  15578. const auto listTracks = [&offline, &report] (const juce::String& title) {
  15579. const auto& s = offline.getSong();
  15580. report << title << "\n";
  15581. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  15582. {
  15583. int clips = 0, muted = 0;
  15584. for (const auto& c : s.playlist)
  15585. if (c.track == t)
  15586. ++clips, muted += c.muted ? 1 : 0;
  15587. const auto& pt = s.playlistTracks[(std::size_t) t];
  15588. if (clips > 0 || pt.grouped || ! pt.name.empty())
  15589. report << "track " << (t + 1) << " '" << juce::String::fromUTF8 (pt.name.c_str()) << "' grouped=" << (pt.grouped ? 1 : 0) << " collapsed=" << (pt.collapsed ? 1 : 0)
  15590. << " comp=" << (pt.compTrack ? 1 : 0) << " clips=" << clips << " muted=" << muted << "\n";
  15591. }
  15592. };
  15593. listTracks ("opened");
  15594. // the first group's header (a member's menu holds "Comp these takes" too)
  15595. int firstGroup = -1;
  15596. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && firstGroup < 0; ++t)
  15597. if (lynx::comp::canComp (offline.getSong(), t))
  15598. firstGroup = t;
  15599. report << "first group with takes: track " << (firstGroup + 1) << "\n";
  15600. if (firstGroup >= 0)
  15601. {
  15602. saveMenus (juce::StringArray { "Playlist track" }, std::vector<juce::PopupMenu> { playlist.getTrackMenuForSnapshot (firstGroup) }, prefix + "-trackmenu.png");
  15603. int comp = -1;
  15604. offline.editSong ([firstGroup, &comp] (lynx::Song& s) { comp = lynx::comp::compTakes (s, firstGroup); });
  15605. offline.dispatchPendingMessages();
  15606. saveSnapshot (ui, prefix + "-comped.png");
  15607. listTracks ("after Comp these takes");
  15608. const auto g = lynx::comp::groupOf (offline.getSong(), comp);
  15609. std::int64_t from = -1, to = 0;
  15610. for (const auto& c : offline.getSong().playlist)
  15611. if (c.track == g.first)
  15612. from = from < 0 ? c.start : std::min (from, c.start), to = std::max (to, c.end());
  15613. if (g.valid() && to > from)
  15614. {
  15615. offline.editSong ([&g, from, to] (lynx::Song& s) { lynx::comp::swipe (s, g.first, from + (to - from) / 4, from + (to - from) / 2); });
  15616. offline.dispatchPendingMessages();
  15617. saveSnapshot (ui, prefix + "-swiped.png");
  15618. listTracks ("after a swipe of the middle of the first lane");
  15619. // a lane auditioned; the crossfade close up; the comp flattened
  15620. offline.editSong ([&g] (lynx::Song& s) { lynx::comp::setAudition (s, g.first); }, false);
  15621. offline.dispatchPendingMessages();
  15622. saveSnapshot (ui, prefix + "-audition.png");
  15623. offline.editSong ([] (lynx::Song& s) { lynx::comp::setAudition (s, -1); }, false);
  15624. const auto switchAt = from + (to - from) / 4;
  15625. playlist.setViewForSnapshot (4.0 * 4.0 * lynx::ppq, 0, 0);
  15626. playlist.setScrollTickForSnapshot ((double) (switchAt - 100));
  15627. juce::Thread::sleep (1500);
  15628. offline.dispatchPendingMessages();
  15629. saveSnapshot (ui, prefix + "-crossfade.png");
  15630. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  15631. offline.editSong ([comp] (lynx::Song& s) { lynx::comp::flatten (s, comp); });
  15632. offline.dispatchPendingMessages();
  15633. saveSnapshot (ui, prefix + "-flattened.png");
  15634. listTracks ("after Flatten comp");
  15635. }
  15636. }
  15637. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getRecordMenuForSnapshot() }, prefix + "-recordmenu.png");
  15638. juce::File (prefix + "-tracks.txt").replaceWithText (report);
  15639. }
  15640. }
  15641. // Round 190bx: the Settings pages alone (the full --snapshot takes minutes). prefix-settings-<page>.png at the
  15642. // window's size, -small.png at 390 x 390 (rows must scroll, never be cut off or squeezed) and -whole.png tall
  15643. // enough to show every row of the page.
  15644. void runSettingsShot (const juce::String& prefix)
  15645. {
  15646. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15647. {
  15648. lynx::AudioEngine offline (false);
  15649. offline.editSong ([] (lynx::Song& s) {
  15650. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  15651. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  15652. }, false);
  15653. auto shoot = [&] (lynx::SettingsPage page, const juce::String& name, int width, int height) {
  15654. auto panel = lynx::makeSettingsPanel (offline, page);
  15655. if (width > 0)
  15656. panel->setSize (width, height);
  15657. juce::Component frame;
  15658. frame.setSize (panel->getWidth(), panel->getHeight());
  15659. frame.addAndMakeVisible (*panel);
  15660. panel->setTopLeftPosition (0, 0);
  15661. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  15662. {
  15663. juce::Graphics g (image);
  15664. g.fillAll (lynx::theme::panel);
  15665. frame.paintEntireComponent (g, false);
  15666. }
  15667. savePng (image, prefix + "-settings-" + name + ".png");
  15668. };
  15669. const std::pair<lynx::SettingsPage, const char*> pages[] = { { lynx::SettingsPage::audio, "audio" }, { lynx::SettingsPage::midi, "midi" },
  15670. { lynx::SettingsPage::general, "general" }, { lynx::SettingsPage::theme, "theme" },
  15671. { lynx::SettingsPage::files, "files" }, { lynx::SettingsPage::extras, "extras" },
  15672. { lynx::SettingsPage::project, "project" }, { lynx::SettingsPage::info, "info" } };
  15673. for (const auto& [page, name] : pages)
  15674. {
  15675. shoot (page, name, 0, 0);
  15676. shoot (page, juce::String (name) + "-small", 390, 390);
  15677. }
  15678. shoot (lynx::SettingsPage::audio, "audio-whole", 680, 1500);
  15679. shoot (lynx::SettingsPage::general, "general-whole", 680, 2300);
  15680. }
  15681. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  15682. }
  15683. // round 190bw: FL's 13 curve modes of an automation clip's points (see --curveshot)
  15684. bool runTrackModeShot (const juce::String& prefix)
  15685. {
  15686. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15687. lynx::AudioEngine offline (false);
  15688. bool all = true;
  15689. juce::String report;
  15690. {
  15691. lynx::MainComponent ui (offline, false);
  15692. ui.setSize (1600, 900);
  15693. offline.dispatchPendingMessages();
  15694. auto& playlist = ui.getPlaylistForSnapshot();
  15695. // the track's menu, Track mode and Audio track side by side; the Audio track entries as FL writes them
  15696. // ("-" in front = greyed, "v" = ticked)
  15697. const auto shoot = [&] (int track, const juce::String& name, const juce::StringArray& fl) {
  15698. const auto menu = playlist.getTrackMenuForSnapshot (track);
  15699. juce::StringArray names { "Track " + juce::String (track + 1) };
  15700. std::vector<juce::PopupMenu> menus { menu };
  15701. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  15702. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Track mode"), 'T'))
  15703. {
  15704. names.add (lynx::tr ("Track mode"));
  15705. menus.push_back (*it.getItem().subMenu);
  15706. }
  15707. if (menus.size() == 2)
  15708. for (juce::PopupMenu::MenuItemIterator it (menus[1]); it.next();)
  15709. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Audio track"), 'A'))
  15710. {
  15711. names.add (lynx::tr ("Audio track"));
  15712. menus.push_back (*it.getItem().subMenu);
  15713. }
  15714. juce::StringArray lynxList;
  15715. if (menus.size() == 3)
  15716. for (juce::PopupMenu::MenuItemIterator it (menus[2]); it.next();)
  15717. lynxList.add (it.getItem().isSeparator ? juce::String ("|")
  15718. : (it.getItem().isTicked ? "v " : "") + juce::String (it.getItem().isEnabled ? "" : "- ") + it.getItem().text);
  15719. saveMenus (names, menus, prefix + "-" + name + ".png");
  15720. const auto same = menus.size() == 3 && lynxList == fl;
  15721. all = all && same;
  15722. report << name << ": " << (same ? "SAME AS FL" : "DIFFERENT") << "\n LYNX: " << lynxList.joinIntoString (" / ")
  15723. << "\n FL: " << fl.joinIntoString (" / ") << "\n";
  15724. };
  15725. const auto flList = [] (int inserts, std::map<int, juce::String> named, std::set<int> greyed) {
  15726. juce::StringArray l { "New mixer track(s)", "|" };
  15727. for (int i = 1; i <= inserts; ++i)
  15728. l.add ((greyed.count (i) ? "- " : "") + juce::String (i) + ". " + (named.count (i) ? named[i] : "Insert " + juce::String (i)));
  15729. return l;
  15730. };
  15731. // q1-01: a fresh project, Track 1 unassigned
  15732. shoot (0, "fresh", flList (16, {}, {}));
  15733. // q1-02: Track 1 linked to insert 6, insert 7 renamed "Vox chain"; Track 2's menu
  15734. offline.editSong ([] (lynx::Song& s) {
  15735. lynx::trackmodes::assignAudioTracks (s, { 0 }, 6);
  15736. s.mixer[7].name = "Vox chain";
  15737. });
  15738. offline.dispatchPendingMessages();
  15739. shoot (1, "linked-renamed", flList (16, { { 7, "Vox chain" } }, { 6 }));
  15740. // q1-07: the rest of FL's session (live 190cu Q2): Track 3 → 7; Track 4 → New mixer track (17), insert 9
  15741. // renamed "Vox chain", Track 4 → 9; Track 5 "Lead" → 11, insert 12 "Vox chain", Track 5 → 12; Track 6 "Lead"
  15742. // (unassigned), insert 13 "Vox chain", Track 6 → 13. Track 7's menu
  15743. offline.editSong ([] (lynx::Song& s) {
  15744. namespace tm = lynx::trackmodes;
  15745. if (s.playlistTracks.size() < 8)
  15746. s.playlistTracks.resize (8);
  15747. tm::assignAudioTracks (s, { 2 }, 7);
  15748. tm::assignAudioTracks (s, { 3 }, tm::newMixerTrack);
  15749. s.mixer[9].name = "Vox chain";
  15750. tm::assignAudioTracks (s, { 3 }, 9);
  15751. s.playlistTracks[4].name = "Lead";
  15752. tm::assignAudioTracks (s, { 4 }, 11);
  15753. s.mixer[12].name = "Vox chain";
  15754. tm::assignAudioTracks (s, { 4 }, 12);
  15755. s.playlistTracks[5].name = "Lead";
  15756. s.mixer[13].name = "Vox chain";
  15757. tm::assignAudioTracks (s, { 5 }, 13);
  15758. });
  15759. offline.dispatchPendingMessages();
  15760. shoot (6, "full-state", flList (17, { { 7, "Vox chain" }, { 9, "Insert 17" }, { 12, "Lead" }, { 13, "Vox chain" } }, { 6, 7, 9, 12, 13 }));
  15761. }
  15762. report << (all ? "ALL SAME AS FL\n" : "FAILURES\n");
  15763. juce::File (prefix + "-report.txt").replaceWithText (report);
  15764. return all;
  15765. }
  15766. void runCurveShot (const juce::String& prefix)
  15767. {
  15768. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15769. lynx::AudioEngine offline (false);
  15770. {
  15771. lynx::MainComponent ui (offline, false);
  15772. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  15773. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  15774. offline.dispatchPendingMessages();
  15775. // FL's menu order, one bar per mode, the levels going up and down; a tension where the mode needs one to show
  15776. static const int order[] = { lynx::flcurve::smooth, lynx::flcurve::hold, lynx::flcurve::singleCurve, lynx::flcurve::singleCurve2,
  15777. lynx::flcurve::singleCurve3, lynx::flcurve::doubleCurve, lynx::flcurve::doubleCurve2, lynx::flcurve::doubleCurve3,
  15778. lynx::flcurve::halfSine, lynx::flcurve::stairs, lynx::flcurve::smoothStairs, lynx::flcurve::pulse, lynx::flcurve::wave };
  15779. const auto bar = (std::int64_t) lynx::ppq * 4;
  15780. offline.editSong ([bar] (lynx::Song& song) {
  15781. song.mode = lynx::PlayMode::song;
  15782. lynx::Automation a;
  15783. a.name = "Curve modes";
  15784. a.target = { lynx::AutomationTargetKind::mixerVolume, 1 };
  15785. a.points.push_back ({ 0, 0.15f, 0.0f });
  15786. int k = 0;
  15787. for (const auto mode : order)
  15788. {
  15789. const auto stepped = mode == lynx::flcurve::stairs || mode == lynx::flcurve::smoothStairs || mode == lynx::flcurve::pulse || mode == lynx::flcurve::wave;
  15790. a.points.back().mode = (std::uint8_t) mode;
  15791. a.points.back().tension = mode == lynx::flcurve::smooth || mode == lynx::flcurve::hold ? 0.0f : stepped ? -0.72f : (k % 2 == 0 ? 0.55f : -0.55f);
  15792. ++k;
  15793. a.points.push_back ({ bar * k, k % 2 == 1 ? 0.85f : 0.15f, 0.0f });
  15794. }
  15795. song.automations.insert (song.automations.begin(), a);
  15796. for (auto& c : song.playlist)
  15797. if (c.kind == lynx::ClipKind::automation)
  15798. ++c.automation;
  15799. lynx::Clip clip;
  15800. clip.kind = lynx::ClipKind::automation;
  15801. clip.automation = 0;
  15802. clip.track = 3;
  15803. clip.length = bar * 13;
  15804. song.playlist.push_back (clip);
  15805. if (song.playlistTracks.size() < 4)
  15806. song.playlistTracks.resize (4);
  15807. song.playlistTracks[3].height = 150;
  15808. }, false);
  15809. offline.dispatchPendingMessages();
  15810. ui.selectTabForSnapshot (2);
  15811. offline.dispatchPendingMessages();
  15812. auto& playlist = ui.getPlaylistForSnapshot();
  15813. saveSnapshot (ui, prefix + "-playlist.png");
  15814. const auto clipIndex = (int) offline.getSong().playlist.size() - 1;
  15815. // the point menu of the point that ends the "Stairs" segment (point 10), and of the first point
  15816. saveMenus (juce::StringArray { "Automation point (ends a Stairs segment)", "First point" },
  15817. std::vector<juce::PopupMenu> { playlist.getAutomationPointMenuForSnapshot (clipIndex, 10), playlist.getAutomationPointMenuForSnapshot (clipIndex, 0) },
  15818. prefix + "-point-menu.png");
  15819. auto editor = lynx::makeAutomationEditor (offline, 0);
  15820. editor->setSize (1500, 420);
  15821. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
  15822. editor.reset();
  15823. // the project itself, for --export-flp and a look at the same clip in FL
  15824. {
  15825. juce::String saveError;
  15826. lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-modes.lynx"), saveError);
  15827. }
  15828. // part 2: the Piano roll tools that gained FL's options (they preview on the pattern and put the notes back)
  15829. ui.selectTabForSnapshot (1);
  15830. offline.dispatchPendingMessages();
  15831. auto& roll = ui.getPianoRollForSnapshot();
  15832. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::flip, "-tool-flip.png" },
  15833. { lynx::NoteTool::limit, "-tool-limit.png" },
  15834. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  15835. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  15836. { lynx::NoteTool::lfo, "-tool-lfo.png" } };
  15837. // round 190ct: checks of the FL-live fixes, one line each in <prefix>-checks.txt (OK / FAIL)
  15838. juce::StringArray checks;
  15839. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  15840. {
  15841. juce::String header;
  15842. const auto pointMenu = playlist.getAutomationPointMenuForSnapshot (clipIndex, 10); // (the iterator keeps a reference)
  15843. for (juce::PopupMenu::MenuItemIterator it (pointMenu); it.next();)
  15844. {
  15845. header = it.getItem().text;
  15846. break;
  15847. }
  15848. check (header == "Point 11/14", "point menu header \"" + header + "\" (FL: \"Point n/N\")");
  15849. }
  15850. for (const auto& [tool, name] : tools)
  15851. {
  15852. auto panel = lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot());
  15853. offline.dispatchPendingMessages();
  15854. savePng (panel->createComponentSnapshot (panel->getLocalBounds()), prefix + name);
  15855. if (tool == lynx::NoteTool::flip)
  15856. {
  15857. std::vector<juce::ToggleButton*> toggles;
  15858. for (auto* child : panel->getChildren())
  15859. if (auto* t = dynamic_cast<juce::ToggleButton*> (child))
  15860. toggles.push_back (t);
  15861. check (toggles.size() == 3 && toggles[0]->getToggleState() && toggles[1]->getToggleState() && ! toggles[2]->getToggleState(),
  15862. "flip opens with Flip horizontally on, Preserve start times on, Flip vertically off");
  15863. if (toggles.size() == 3)
  15864. {
  15865. toggles[2]->setToggleState (true, juce::sendNotificationSync);
  15866. check (! toggles[0]->getToggleState() && toggles[2]->getToggleState(), "flip: vertically turns horizontally off (radios)");
  15867. toggles[0]->setToggleState (true, juce::sendNotificationSync);
  15868. check (toggles[0]->getToggleState() && ! toggles[2]->getToggleState(), "flip: horizontally turns vertically off (radios)");
  15869. }
  15870. }
  15871. if (tool == lynx::NoteTool::limit)
  15872. {
  15873. auto* list = lynx::noteToolLongestChoiceForSnapshot (*panel);
  15874. juce::ComboBox* key = nullptr;
  15875. for (auto* child : panel->getChildren())
  15876. if (auto* box = dynamic_cast<juce::ComboBox*> (child); box != nullptr && box->getNumItems() == 12)
  15877. key = box;
  15878. check (list != nullptr && list->getNumItems() == 89, "limit list has (none) + 66 chords + 22 scales: "
  15879. + juce::String (list != nullptr ? list->getNumItems() : 0));
  15880. check (list != nullptr && key != nullptr && list->getY() == key->getY() && list->getX() > key->getRight(),
  15881. "limit: Key and the chord / scale list share one row");
  15882. if (list != nullptr)
  15883. saveMenus (juce::StringArray { "Limit: Key / scale list" }, std::vector<juce::PopupMenu> { *list->getRootMenu() },
  15884. prefix + "-tool-limit-list.png");
  15885. }
  15886. if (tool == lynx::NoteTool::lfo)
  15887. saveMenus (juce::StringArray { "LFO tool: right-click on a Period slider" },
  15888. std::vector<juce::PopupMenu> { lynx::noteToolPresetMenuForSnapshot (*panel) }, prefix + "-tool-lfo-steps.png");
  15889. }
  15890. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  15891. }
  15892. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  15893. }
  15894. void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
  15895. {
  15896. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15897. lynx::AudioEngine offline (false);
  15898. {
  15899. lynx::MainComponent ui (offline, false);
  15900. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  15901. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  15902. if (projectPath.isNotEmpty())
  15903. ui.openFile (juce::File (projectPath));
  15904. offline.dispatchPendingMessages();
  15905. ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
  15906. offline.dispatchPendingMessages();
  15907. // the scale the pattern's notes fit best (major / minor, any root)
  15908. const auto& song = offline.getSong();
  15909. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  15910. int bestRoot = 0, bestScale = 1, bestHits = -1;
  15911. for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
  15912. {
  15913. const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
  15914. if (name != "Major" && name != "Minor")
  15915. continue;
  15916. for (int root = 0; root < 12; ++root)
  15917. {
  15918. int hits = 0;
  15919. for (const auto& n : notes)
  15920. hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
  15921. if (hits > bestHits)
  15922. bestHits = hits, bestRoot = root, bestScale = sc;
  15923. }
  15924. }
  15925. auto& roll = ui.getPianoRollForSnapshot();
  15926. roll.setScaleForSnapshot (bestRoot, bestScale);
  15927. roll.scrollToNotes();
  15928. offline.dispatchPendingMessages();
  15929. saveSnapshot (ui, prefix + "-pr-scale.png");
  15930. roll.setFoldToScale (true);
  15931. offline.dispatchPendingMessages();
  15932. saveSnapshot (ui, prefix + "-pr-folded.png");
  15933. roll.setFoldToScale (false);
  15934. // ghost channels: only the first other channel with notes stays a ghost
  15935. const auto selected = offline.getSelectedChannel();
  15936. int keep = -1;
  15937. for (const auto& n : notes)
  15938. if (n.channel != selected && keep < 0)
  15939. keep = n.channel;
  15940. offline.editSong ([keep] (lynx::Song& s) {
  15941. for (int c = 0; c < (int) s.channels.size(); ++c)
  15942. s.channels[(std::size_t) c].ghostHidden = c != keep;
  15943. }, false);
  15944. offline.dispatchPendingMessages();
  15945. saveSnapshot (ui, prefix + "-pr-ghost-one.png");
  15946. saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
  15947. offline.editSong ([] (lynx::Song& s) {
  15948. for (auto& c : s.channels)
  15949. c.ghostHidden = false;
  15950. }, false);
  15951. // the Mixer at 500 inserts
  15952. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  15953. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
  15954. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  15955. offline.dispatchPendingMessages();
  15956. ui.selectTabForSnapshot (3);
  15957. offline.dispatchPendingMessages();
  15958. auto& mixer = ui.getMixerForSnapshot();
  15959. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  15960. saveSnapshot (ui, prefix + "-mixer500-start.png");
  15961. const auto t3 = juce::Time::getMillisecondCounterHiRes();
  15962. mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
  15963. offline.dispatchPendingMessages();
  15964. saveSnapshot (ui, prefix + "-mixer500-end.png");
  15965. juce::File (prefix + "-mixer500.txt")
  15966. .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
  15967. + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
  15968. }
  15969. }
  15970. // Round 190ay, Freeze, end to end with the real engine, files and export (LYNX.exe --freezetest prefix [project]).
  15971. // The project (.lynx / .flp / .als; without one, a small demo song) is rendered live, every channel that can be
  15972. // frozen is frozen, and the same render is made again: the two mixes must null. Written to prefix-report.txt: the
  15973. // null residual, the process memory and the render time before / frozen / unfrozen, what a save holds, whether
  15974. // Unfreeze gives the channels back as they were, the out-of-date and missing-audio states. Shots: the Channel Rack
  15975. // (live, frozen, out of date), the channel menus, the Piano roll of a frozen channel. The frozen audio goes to
  15976. // prefix-data (never next to the project). True = every check passed.
  15977. bool runFreezeTest (const juce::String& prefix, const juce::String& projectPath, const juce::String& mode = {})
  15978. {
  15979. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15980. lynx::AudioEngine offline (false);
  15981. lynx::MainComponent ui (offline, false);
  15982. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  15983. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  15984. const auto write = [&prefix, &ui] (const char* name) {
  15985. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  15986. file.deleteFile();
  15987. juce::FileOutputStream out (file);
  15988. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  15989. };
  15990. juce::String report;
  15991. int failures = 0;
  15992. const auto check = [&] (bool ok, const juce::String& what) {
  15993. report << (ok ? "ok " : "FAIL ") << what << "\n";
  15994. failures += ok ? 0 : 1;
  15995. };
  15996. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  15997. if (projectPath.isNotEmpty())
  15998. {
  15999. ui.openFile (juce::File (projectPath));
  16000. offline.dispatchPendingMessages();
  16001. }
  16002. else
  16003. offline.editSong ([] (lynx::Song& s) {
  16004. s.channels.clear();
  16005. s.patterns.clear();
  16006. s.playlist.clear();
  16007. s.bpm = 120.0;
  16008. const char* names[] = { "Lead", "Bass", "Pad", "Kick" };
  16009. for (int c = 0; c < 4; ++c)
  16010. {
  16011. lynx::ChannelDef d;
  16012. d.name = names[c];
  16013. d.instrument = c == 3 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  16014. d.synth.release = 0.3f + 0.3f * (float) c;
  16015. d.synth.cutoff = 1500.0f + 900.0f * (float) c;
  16016. d.mixerTrack = c + 1;
  16017. s.channels.push_back (d);
  16018. }
  16019. for (int p = 0; p < 2; ++p)
  16020. {
  16021. auto& pattern = s.patterns.emplace_back();
  16022. pattern.name = p == 0 ? "Verse" : "Break";
  16023. pattern.lengthTicks = 4 * lynx::ppq * 4;
  16024. for (int c = 0; c < 4; ++c)
  16025. for (int step = 0; step < (p == 0 ? 8 : 2); ++step)
  16026. {
  16027. lynx::Note n;
  16028. n.channel = c;
  16029. n.start = (std::int64_t) step * lynx::ppq * (p == 0 ? 2 : 1) + (c == 2 ? lynx::ppq / 2 : 0);
  16030. n.length = c == 3 ? lynx::ppq / 4 : lynx::ppq;
  16031. n.key = c == 3 ? 36 : 48 + c * 7 + (step * 5) % 12;
  16032. pattern.notes.push_back (n);
  16033. }
  16034. pattern.sortNotes();
  16035. }
  16036. const int order[] = { 0, 0, 1, 0 };
  16037. for (int i = 0; i < 4; ++i)
  16038. {
  16039. lynx::Clip clip;
  16040. clip.pattern = order[i];
  16041. clip.start = (std::int64_t) i * 16 * lynx::ppq;
  16042. clip.length = 16 * lynx::ppq;
  16043. s.playlist.push_back (clip);
  16044. }
  16045. s.mode = lynx::PlayMode::song;
  16046. });
  16047. offline.dispatchPendingMessages();
  16048. // the case Freeze exists for, a heavy hosted plugin: LYNX_FREEZETEST_PLUGIN = a plugin file whose first
  16049. // instrument plays the demo song's Lead (tools/testplugin/lynx_test_heavy_vst3.cpp: memory, CPU, latency, a
  16050. // state, and with LYNX_TEST_HEAVY_LOG the instances alive)
  16051. int hostedChannel = -1;
  16052. const auto hostedLog = juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_HEAVY_LOG", {});
  16053. const auto hostedAlive = [&hostedLog] {
  16054. int alive = 0;
  16055. juce::StringArray lines;
  16056. juce::File (hostedLog).readLines (lines);
  16057. for (const auto& l : lines)
  16058. alive += l.startsWith ("create") ? 1 : l.startsWith ("destroy") ? -1 : 0;
  16059. return alive;
  16060. };
  16061. if (const auto pluginPath = juce::SystemStats::getEnvironmentVariable ("LYNX_FREEZETEST_PLUGIN", {}); pluginPath.isNotEmpty() && projectPath.isEmpty())
  16062. {
  16063. auto& host = offline.getPluginHost();
  16064. const auto added = host.addPluginFile (juce::File (pluginPath));
  16065. report << "hosted plugin file: " << pluginPath << " (" << added << " plugins)\n";
  16066. for (const auto& type : host.getKnownPlugins().getTypes())
  16067. if (type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  16068. {
  16069. offline.editSong ([&type] (lynx::Song& s) {
  16070. auto& c = s.channels[0];
  16071. c.instrument = lynx::InstrumentKind::plugin;
  16072. c.plugin.id = type.createIdentifierString().toStdString();
  16073. c.plugin.name = type.name.toStdString();
  16074. });
  16075. hostedChannel = 0;
  16076. break;
  16077. }
  16078. offline.dispatchPendingMessages();
  16079. auto* instance = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (0).get());
  16080. check (hostedChannel == 0 && instance != nullptr, "the hosted plugin is loaded on channel 1");
  16081. report << "hosted plugin: " << juce::String::fromUTF8 (offline.getSong().channels[0].plugin.name.c_str())
  16082. << ", engine latency " << offline.getLatencySamples() << " frames, instances alive " << hostedAlive() << "\n";
  16083. }
  16084. const auto hostedLine = [&] (const char* stage) {
  16085. if (hostedChannel < 0)
  16086. return;
  16087. offline.freeRetiredRacks();
  16088. report << "hosted, " << stage << ": instance on the channel "
  16089. << (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr ? "yes" : "no")
  16090. << ", plugin instances alive in the process " << (hostedLog.isNotEmpty() ? juce::String (hostedAlive()) : juce::String ("(no log)")) << "\n";
  16091. };
  16092. const juce::File data (prefix + "-data");
  16093. data.deleteRecursively();
  16094. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "freezetest");
  16095. report << "project=" << (projectPath.isNotEmpty() ? projectPath : juce::String ("(demo song)")) << "\n"
  16096. << "frozen_audio_folder=" << offline.getFreezeFolder().getFullPathName() << "\n";
  16097. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  16098. struct Mix
  16099. {
  16100. juce::AudioBuffer<float> audio;
  16101. double renderSeconds = 0.0, audioSeconds = 0.0;
  16102. std::int64_t workingSet = 0, privateBytes = 0;
  16103. };
  16104. // the song as it stands, rendered by an export (its own engine: frozen channels play their audio there too)
  16105. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr, std::vector<int>* renderedLive = nullptr, int range = 0) {
  16106. Mix m;
  16107. offline.dispatchPendingMessages();
  16108. offline.freeRetiredRacks(); // (what the message loop does in the app: this mode runs without one)
  16109. m.workingSet = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  16110. m.privateBytes = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  16111. const juce::File file (prefix + "-" + name + ".wav");
  16112. lynx::ExportSettings settings;
  16113. settings.format = lynx::ExportSettings::Format::wav32Float;
  16114. settings.sampleRate = offline.getTransport().sampleRate.load();
  16115. settings.tailSeconds = 2.0;
  16116. juce::String error;
  16117. {
  16118. auto options = settings.toOptions();
  16119. options.hqAllPlugins = false; // the quality heard while playing: what a frozen channel's audio is made at
  16120. options.disableMaxPolyphony = false; // (and each channel's Max polyphony, as while playing)
  16121. if (range == 1)
  16122. options.range = lynx::exportopts::Range::selection;
  16123. if (range == 2)
  16124. {
  16125. options.range = lynx::exportopts::Range::pattern;
  16126. options.loops = 2;
  16127. }
  16128. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  16129. if (renderedLive != nullptr)
  16130. *renderedLive = job.channelsRenderedLive();
  16131. const auto started = juce::Time::getMillisecondCounterHiRes();
  16132. const auto ok = job.run ([] (double) { return true; }, error);
  16133. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  16134. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  16135. }
  16136. juce::WavAudioFormat wav;
  16137. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  16138. {
  16139. m.audio.setSize (2, (int) reader->lengthInSamples);
  16140. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  16141. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  16142. }
  16143. file.deleteFile();
  16144. return m;
  16145. };
  16146. // the worst sample difference, in dB below the first mix's peak
  16147. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  16148. float worst = 0.0f;
  16149. peak = 0.0f;
  16150. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  16151. for (int ch = 0; ch < 2; ++ch)
  16152. for (int i = 0; i < n; ++i)
  16153. {
  16154. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  16155. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  16156. }
  16157. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  16158. };
  16159. const auto line = [&] (const char* name, const Mix& m) {
  16160. report << name << ": working set " << megabytes (m.workingSet) << " MB, private " << megabytes (m.privateBytes) << " MB, render "
  16161. << juce::String (m.renderSeconds, 2) << " s for " << juce::String (m.audioSeconds, 2) << " s of audio ("
  16162. << juce::String (m.audioSeconds > 0.0 ? 100.0 * m.renderSeconds / m.audioSeconds : 0.0, 1) << " % of real time)\n";
  16163. };
  16164. if (mode == "measure")
  16165. {
  16166. // a process that only loaded this project and renders it: its memory with the project loaded, and after
  16167. int frozenCount = 0, hosted = 0;
  16168. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  16169. {
  16170. frozenCount += offline.getSong().channels[(std::size_t) c].freeze.on();
  16171. hosted += dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) != nullptr;
  16172. }
  16173. report << "channels " << (int) offline.getSong().channels.size() << ", frozen " << frozenCount << ", hosted plugin instances " << hosted << "\n";
  16174. const auto m = renderMix ("measure");
  16175. line ("loaded ", m);
  16176. report << "after the render: working set " << megabytes (lynx::toolbar::PerformanceMeter::processMemoryBytes()) << " MB, private "
  16177. << megabytes (lynx::toolbar::PerformanceMeter::processPrivateBytes()) << " MB\n";
  16178. flush();
  16179. return failures == 0;
  16180. }
  16181. // --- live ---
  16182. offline.capturePluginStates();
  16183. offline.editSong ([] (lynx::Song&) {}, false); // (whatever any edit settles — ids of new objects... — settled first)
  16184. const auto before = offline.getSong();
  16185. // (the project's working-time counter runs on while the test does: not part of what is compared)
  16186. const auto savedJson = [] (lynx::Song song) {
  16187. song.info.workSeconds = 0.0;
  16188. return lynx::ProjectFile::toJson (song, false);
  16189. };
  16190. const auto jsonBefore = savedJson (before);
  16191. std::vector<int> targets;
  16192. for (int c = 0; c < (int) before.channels.size(); ++c)
  16193. {
  16194. const auto* why = lynx::freeze::whyNot (before, c);
  16195. const auto plays = std::any_of (before.patterns.begin(), before.patterns.end(), [c] (const lynx::Pattern& p) {
  16196. return std::any_of (p.notes.begin(), p.notes.end(), [c] (const lynx::Note& n) { return n.channel == c; });
  16197. });
  16198. report << "channel " << (c + 1) << " '" << juce::String::fromUTF8 (before.channels[(std::size_t) c].name.c_str()) << "': "
  16199. << (why != nullptr ? juce::String ("not frozen (") + why + ")" : plays ? juce::String ("freeze") : juce::String ("no notes, left alone")) << "\n";
  16200. if (why == nullptr && plays)
  16201. {
  16202. targets.push_back (c);
  16203. // what could make a stem differ from the live channel, for the record
  16204. const auto& def = before.channels[(std::size_t) c];
  16205. int volPan = 0, params = 0, live = 0, lanes = 0, routes = 0;
  16206. for (const auto& a : before.automations)
  16207. if (a.target.index == c)
  16208. {
  16209. volPan += a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan;
  16210. params += a.target.kind == lynx::AutomationTargetKind::channelParam;
  16211. live += a.isLive() && (a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan
  16212. || a.target.kind == lynx::AutomationTargetKind::channelParam);
  16213. }
  16214. for (const auto& p : before.patterns)
  16215. for (const auto& lane : p.events)
  16216. lanes += lane.target.index == c && (lane.target.kind == lynx::AutomationTargetKind::channelVolume
  16217. || lane.target.kind == lynx::AutomationTargetKind::channelPan
  16218. || lane.target.kind == lynx::AutomationTargetKind::channelParam);
  16219. for (const auto& m : before.modulators)
  16220. for (const auto& r : m.routes)
  16221. routes += r.target.index == c && (r.target.kind == lynx::AutomationTargetKind::channelVolume
  16222. || r.target.kind == lynx::AutomationTargetKind::channelPan
  16223. || r.target.kind == lynx::AutomationTargetKind::channelParam);
  16224. report << " instrument kind " << (int) def.instrument << ", insert " << def.mixerTrack << ", automation: volume/pan " << volPan
  16225. << ", parameters " << params << ", live links " << live << ", event lanes " << lanes << ", modulator routes " << routes << "\n";
  16226. }
  16227. }
  16228. check (! targets.empty(), "the project has channels to freeze (" + juce::String ((int) targets.size()) + ")");
  16229. if (targets.empty())
  16230. {
  16231. flush();
  16232. return false;
  16233. }
  16234. const auto first = targets.front();
  16235. offline.setSelectedChannel (first);
  16236. ui.selectTabForSnapshot (0);
  16237. write ("rack-live");
  16238. saveMenus (juce::StringArray { "Channel (live)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-live.png");
  16239. const auto live = renderMix ("live");
  16240. line ("live ", live);
  16241. hostedLine ("live");
  16242. const auto hostedState = hostedChannel >= 0 ? before.channels[(std::size_t) hostedChannel].plugin.state : std::string();
  16243. if (hostedChannel >= 0)
  16244. check (! hostedState.empty(), "the hosted plugin's state is in the project (" + juce::String ((int) hostedState.size()) + " characters)");
  16245. flush();
  16246. // --- frozen ---
  16247. const auto freezeStarted = juce::Time::getMillisecondCounterHiRes();
  16248. for (const auto c : targets)
  16249. {
  16250. const auto error = lynx::freezeChannelNow (offline, c);
  16251. check (error.isEmpty(), "freeze channel " + juce::String (c + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  16252. }
  16253. const auto freezeSeconds = (juce::Time::getMillisecondCounterHiRes() - freezeStarted) / 1000.0;
  16254. offline.dispatchPendingMessages();
  16255. std::int64_t stemBytes = 0;
  16256. int stemFiles = 0;
  16257. bool pluginsGone = true, allFrozen = true;
  16258. for (const auto c : targets)
  16259. {
  16260. const auto& ch = offline.getSong().channels[(std::size_t) c];
  16261. allFrozen = allFrozen && ch.freeze.on() && ! offline.frozenAudioMissing (c) && ! offline.freezeOutOfDate (c);
  16262. for (const auto& stem : ch.freeze.stems)
  16263. {
  16264. stemBytes += juce::File (juce::String::fromUTF8 (stem.path.c_str())).getSize();
  16265. ++stemFiles;
  16266. }
  16267. pluginsGone = pluginsGone && dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) == nullptr;
  16268. auto thawed = ch;
  16269. thawed.freeze = {};
  16270. check (thawed == before.channels[(std::size_t) c], "channel " + juce::String (c + 1) + " keeps its instrument and settings as they were while frozen");
  16271. }
  16272. check (allFrozen, "every target is frozen, its audio on disk and up to date");
  16273. check (pluginsGone, "no hosted plugin instance is left on a frozen channel");
  16274. report << "freeze: " << juce::String (freezeSeconds, 2) << " s for " << (int) targets.size() << " channels, " << stemFiles << " files, "
  16275. << megabytes (stemBytes) << " MB on disk\n";
  16276. if (mode == "keep")
  16277. {
  16278. juce::String error;
  16279. check (lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-frozen.lynx"), error), "the frozen project is saved" + (error.isEmpty() ? juce::String() : ": " + error));
  16280. flush();
  16281. return failures == 0;
  16282. }
  16283. const auto frozen = renderMix ("frozen");
  16284. line ("frozen ", frozen);
  16285. hostedLine ("frozen");
  16286. if (hostedChannel >= 0 && hostedLog.isNotEmpty())
  16287. check (hostedAlive() == 0, "while frozen no instance of the hosted plugin is alive in the process");
  16288. float peak = 0.0f;
  16289. const auto nullFrozen = residual (live, frozen, peak);
  16290. report << "null frozen vs live: " << juce::String (nullFrozen, 1) << " dB (peak " << juce::String (peak, 4) << ", "
  16291. << live.audio.getNumSamples() << " / " << frozen.audio.getNumSamples() << " samples)\n";
  16292. check (peak > 0.001f && nullFrozen < -90.0 && live.audio.getNumSamples() == frozen.audio.getNumSamples(), "the frozen mix nulls against the live mix (below -90 dB)");
  16293. ui.selectTabForSnapshot (0);
  16294. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  16295. write ("rack-frozen");
  16296. saveMenus (juce::StringArray { "Channel (frozen)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-frozen.png");
  16297. report << "hint frozen: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  16298. offline.setSelectedChannel (first);
  16299. ui.selectTabForSnapshot (1);
  16300. offline.setSelectedChannel (first);
  16301. offline.dispatchPendingMessages();
  16302. ui.setHintForSnapshot ({ lynx::tr ("{0} is frozen: Unfreeze to edit ([RMB] on the channel, Unfreeze)",
  16303. { juce::String::fromUTF8 (offline.getSong().channels[(std::size_t) first].name.c_str()) }), {} });
  16304. write ("pianoroll-frozen");
  16305. // --- exports that do not play the song's timeline once: a selection, one pattern twice ---
  16306. // (the frozen audio is the whole song from its start: those renders play the instruments, never a wrong part of it)
  16307. if (projectPath.isEmpty())
  16308. {
  16309. auto part = offline.getSong();
  16310. part.loopStart = 16 * lynx::ppq;
  16311. part.loopEnd = 40 * lynx::ppq;
  16312. const auto partLive = lynx::freeze::thawed (part);
  16313. for (int range = 1; range <= 2; ++range)
  16314. {
  16315. std::vector<int> renderedLive;
  16316. const auto a = renderMix (range == 1 ? "selection-live" : "pattern-live", &partLive, nullptr, range);
  16317. const auto b = renderMix (range == 1 ? "selection-frozen" : "pattern-frozen", &part, &renderedLive, range);
  16318. float partPeak = 0.0f;
  16319. const auto null = residual (a, b, partPeak);
  16320. report << (range == 1 ? "export of a selection (bars 5-10)" : "export of the current pattern, twice") << ", frozen vs live: " << juce::String (null, 1)
  16321. << " dB (peak " << juce::String (partPeak, 4) << ", " << juce::String (b.audioSeconds, 2) << " s), channels rendered live: " << (int) renderedLive.size() << "\n";
  16322. check (partPeak > 0.001f && null < -90.0 && a.audio.getNumSamples() == b.audio.getNumSamples(),
  16323. range == 1 ? "an export of a selection of a frozen project is the selection" : "an export of one pattern of a frozen project is that pattern");
  16324. }
  16325. }
  16326. // --- what a save holds ---
  16327. {
  16328. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  16329. juce::String error;
  16330. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  16331. check (json.contains ("\"freeze\""), "the saved project holds the frozen state");
  16332. check (loaded.has_value() && loaded->channels.size() == offline.getSong().channels.size()
  16333. && loaded->channels[(std::size_t) first].freeze == offline.getSong().channels[(std::size_t) first].freeze,
  16334. "a frozen project loads frozen, with the same audio files");
  16335. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore,
  16336. "without the frozen state the saved project is byte for byte what it was before the freeze");
  16337. check (! jsonBefore.contains ("\"freeze\""), "a project with nothing frozen has no freeze field");
  16338. }
  16339. // --- out of date: the tempo, a note of the frozen channel; not another channel's notes ---
  16340. {
  16341. offline.editSong ([] (lynx::Song& s) { s.bpm += 4.0; });
  16342. check (offline.freezeOutOfDate (first), "a tempo change marks the freeze out of date");
  16343. ui.selectTabForSnapshot (0);
  16344. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  16345. write ("rack-out-of-date");
  16346. report << "hint out of date: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  16347. offline.editSong ([] (lynx::Song& s) { s.bpm -= 4.0; });
  16348. check (! offline.freezeOutOfDate (first), "the tempo back: up to date again");
  16349. int pattern = -1;
  16350. for (int p = 0; p < (int) before.patterns.size() && pattern < 0; ++p)
  16351. for (const auto& n : before.patterns[(std::size_t) p].notes)
  16352. if (n.channel == first)
  16353. {
  16354. pattern = p;
  16355. break;
  16356. }
  16357. if (pattern >= 0)
  16358. {
  16359. offline.editSong ([pattern, first] (lynx::Song& s) {
  16360. lynx::Note n;
  16361. n.channel = first;
  16362. n.start = 0;
  16363. n.key = 71;
  16364. s.patterns[(std::size_t) pattern].notes.push_back (n);
  16365. s.patterns[(std::size_t) pattern].sortNotes();
  16366. });
  16367. check (offline.freezeOutOfDate (first), "a note edit on the frozen channel marks it out of date");
  16368. bool othersFresh = true;
  16369. for (const auto c : targets)
  16370. othersFresh = othersFresh && (c == first || ! offline.freezeOutOfDate (c));
  16371. check (othersFresh, "the other frozen channels stay up to date");
  16372. // an export of the project in that state: the out-of-date channel renders live (never the old audio),
  16373. // the others keep their frozen audio — the same mix as the edited project with nothing frozen
  16374. {
  16375. std::vector<int> renderedLive;
  16376. const auto stale = renderMix ("stale", nullptr, &renderedLive);
  16377. const auto edited = lynx::freeze::thawed (offline.getSong());
  16378. const auto reference = renderMix ("stale-reference", &edited);
  16379. float stalePeak = 0.0f;
  16380. const auto nullStale = residual (reference, stale, stalePeak);
  16381. const auto nullOld = residual (frozen, stale, stalePeak);
  16382. report << "export with channel " << (first + 1) << " out of date: " << juce::String (nullStale, 1) << " dB vs the edited project live, "
  16383. << juce::String (nullOld, 1) << " dB vs the old frozen mix; channels rendered live: " << (int) renderedLive.size() << "\n";
  16384. check (renderedLive == std::vector<int> { first }, "an export renders the out-of-date frozen channel live, and only that one");
  16385. check (nullStale < -90.0 && nullOld > -60.0, "an export of an out-of-date freeze holds the edited notes, not the old audio");
  16386. }
  16387. offline.editSong ([&before] (lynx::Song& s) { s.patterns = before.patterns; });
  16388. check (! offline.freezeOutOfDate (first), "the notes back: up to date again");
  16389. }
  16390. }
  16391. // --- the audio gone: the instrument plays, never silence ---
  16392. {
  16393. const auto stems = offline.getSong().channels[(std::size_t) first].freeze.stems;
  16394. std::vector<std::pair<juce::File, juce::File>> moved;
  16395. for (const auto& stem : stems)
  16396. {
  16397. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  16398. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  16399. if (file.moveFileTo (away))
  16400. moved.emplace_back (file, away);
  16401. }
  16402. offline.editSong ([] (lynx::Song&) {}, false);
  16403. check (offline.frozenAudioMissing (first), "frozen audio that is not on disk is noticed");
  16404. report << "hint audio missing: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  16405. const auto fallback = renderMix ("missing");
  16406. const auto nullMissing = residual (live, fallback, peak);
  16407. report << "null with the first channel's audio missing vs live: " << juce::String (nullMissing, 1) << " dB\n";
  16408. check (nullMissing < -90.0, "with its audio missing the channel plays its instrument");
  16409. for (const auto& [file, away] : moved)
  16410. away.moveFileTo (file);
  16411. offline.editSong ([] (lynx::Song&) {}, false);
  16412. check (! offline.frozenAudioMissing (first), "the audio back: frozen again");
  16413. // the frozen mix did not null and the first channel is not (alone) why: which one is, each thawed in turn
  16414. if (nullFrozen >= -90.0 && nullMissing >= -90.0)
  16415. for (const auto c : targets)
  16416. {
  16417. if (c == first)
  16418. continue;
  16419. std::vector<std::pair<juce::File, juce::File>> aside;
  16420. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  16421. {
  16422. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  16423. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  16424. if (file.moveFileTo (away))
  16425. aside.emplace_back (file, away);
  16426. }
  16427. offline.editSong ([] (lynx::Song&) {}, false);
  16428. const auto one = renderMix ("thawed");
  16429. report << "null with channel " << (c + 1) << " thawed vs live: " << juce::String (residual (live, one, peak), 1) << " dB\n";
  16430. for (const auto& [file, away] : aside)
  16431. away.moveFileTo (file);
  16432. offline.editSong ([] (lynx::Song&) {}, false);
  16433. }
  16434. }
  16435. // --- unfrozen ---
  16436. std::vector<juce::File> stemPaths;
  16437. for (const auto c : targets)
  16438. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  16439. stemPaths.emplace_back (juce::String::fromUTF8 (stem.path.c_str()));
  16440. for (const auto c : targets)
  16441. lynx::unfreezeChannel (offline, c);
  16442. offline.dispatchPendingMessages();
  16443. check (offline.getSong().channels == before.channels, "Unfreeze gives every channel back exactly as it was (instrument, plugin state, settings)");
  16444. {
  16445. const auto jsonAfter = savedJson (offline.getSong());
  16446. check (jsonAfter == jsonBefore, "the unfrozen project saves byte for byte as before the freeze");
  16447. if (jsonAfter != jsonBefore)
  16448. {
  16449. juce::File (prefix + "-before.json").replaceWithText (jsonBefore);
  16450. juce::File (prefix + "-after.json").replaceWithText (jsonAfter);
  16451. }
  16452. }
  16453. int left = 0;
  16454. for (const auto& f : stemPaths)
  16455. left += f.existsAsFile() ? 1 : 0;
  16456. check (left == 0, "Unfreeze deletes the frozen audio (" + juce::String (left) + " of " + juce::String ((int) stemPaths.size()) + " files left)");
  16457. if (hostedChannel >= 0)
  16458. {
  16459. // the new instance (it starts with another tuning than the first one had) took the saved state
  16460. offline.capturePluginStates();
  16461. check (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr, "Unfreeze loads the hosted plugin again");
  16462. check (offline.getSong().channels[(std::size_t) hostedChannel].plugin.state == hostedState,
  16463. "the hosted plugin's state, read back from the new instance, is the state it had before the freeze");
  16464. }
  16465. const auto unfrozen = renderMix ("unfrozen");
  16466. line ("unfrozen ", unfrozen);
  16467. hostedLine ("unfrozen");
  16468. const auto nullUnfrozen = residual (live, unfrozen, peak);
  16469. report << "null unfrozen vs live: " << juce::String (nullUnfrozen, 1) << " dB\n";
  16470. check (nullUnfrozen < -90.0, "the unfrozen mix nulls against the live mix");
  16471. ui.selectTabForSnapshot (0);
  16472. flush();
  16473. data.deleteRecursively();
  16474. return failures == 0;
  16475. }
  16476. // Round 190ff, the Clip-launch workflow's track commands end to end with the real engine, files and export
  16477. // (LYNX --trackfreezetest prefix). A demo song of three tracks (Lead through a delay and a reverb whose mix is
  16478. // automated, Bass through a delay, Drums on a bare insert; each insert's fader, pan and EQ set) is rendered live; then
  16479. // Freeze Track on every track (the instrument with its volume and pan through its insert's effects), the same render
  16480. // again (must null), the effects and instruments unloaded, the render time (the CPU while frozen), what a save holds;
  16481. // Flatten (Bounce Track in Place on a frozen track) with its undo; Bounce Track in Place of a live track; Bounce to New
  16482. // Track of a track's clips against that track's device output; Consolidate of pattern clips; Unfreeze. Written to
  16483. // prefix-report.txt; shots of the grid, the column menus, the Detail View's frozen devices and the Playlist's clip
  16484. // menu. True = every check passed.
  16485. bool runTrackFreezeTest (const juce::String& prefix)
  16486. {
  16487. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16488. lynx::AudioEngine offline (false);
  16489. lynx::MainComponent ui (offline, false);
  16490. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  16491. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  16492. const auto write = [&prefix, &ui] (const char* name) {
  16493. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  16494. file.deleteFile();
  16495. juce::FileOutputStream out (file);
  16496. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  16497. };
  16498. juce::String report;
  16499. int failures = 0;
  16500. const auto check = [&] (bool ok, const juce::String& what) {
  16501. report << (ok ? "ok " : "FAIL ") << what << "\n";
  16502. failures += ok ? 0 : 1;
  16503. };
  16504. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  16505. const juce::File data (prefix + "-data");
  16506. data.deleteRecursively();
  16507. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "trackfreezetest");
  16508. ui.setVisible (true);
  16509. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  16510. ui.setClipLaunchWorkflow (true);
  16511. offline.editSong ([] (lynx::Song& s) {
  16512. s.channels.clear();
  16513. s.patterns.clear();
  16514. s.playlist.clear();
  16515. s.automations.clear();
  16516. s.bpm = 120.0;
  16517. s.mode = lynx::PlayMode::song;
  16518. const char* names[] = { "Lead", "Bass", "Drums" };
  16519. for (int c = 0; c < 3; ++c)
  16520. {
  16521. lynx::ChannelDef d;
  16522. d.name = names[c];
  16523. d.instrument = c == 2 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  16524. d.synth.release = c == 0 ? 0.6f : 0.2f;
  16525. d.synth.cutoff = c == 0 ? 2400.0f : 900.0f;
  16526. d.volume = c == 0 ? 0.65f : 0.78f;
  16527. d.pan = c == 0 ? 0.25f : 0.0f;
  16528. d.mixerTrack = c + 1;
  16529. s.channels.push_back (d);
  16530. }
  16531. if (s.mixer.size() < 5)
  16532. s.mixer.resize (5);
  16533. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay), lynx::makeEffectSlot (lynx::EffectKind::reverb) };
  16534. s.mixer[2].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay) };
  16535. s.mixer[3].effects.clear();
  16536. for (int t = 1; t <= 3; ++t)
  16537. {
  16538. s.mixer[(std::size_t) t].name = names[t - 1];
  16539. s.mixer[(std::size_t) t].volume = 0.7f;
  16540. s.mixer[(std::size_t) t].pan = t == 1 ? -0.3f : 0.1f;
  16541. s.mixer[(std::size_t) t].eq.gainDb[1] = 3.0f;
  16542. }
  16543. for (int p = 0; p < 3; ++p)
  16544. {
  16545. auto& pattern = s.patterns.emplace_back();
  16546. pattern.name = names[p];
  16547. pattern.lengthTicks = 4 * lynx::ppq * 2;
  16548. for (int step = 0; step < 8; ++step)
  16549. {
  16550. lynx::Note n;
  16551. n.channel = p;
  16552. n.start = (std::int64_t) step * lynx::ppq;
  16553. n.length = p == 2 ? lynx::ppq / 4 : lynx::ppq / 2;
  16554. n.key = p == 2 ? 36 : (p == 0 ? 60 : 36) + (step * 5) % 12;
  16555. pattern.notes.push_back (n);
  16556. }
  16557. }
  16558. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  16559. for (int t = 0; t < 3; ++t)
  16560. {
  16561. s.playlistTracks[(std::size_t) t].name = names[t];
  16562. for (int k = 0; k < 3; ++k)
  16563. {
  16564. if (t == 0 && k == 1)
  16565. continue; // (a gap in the Lead: its tail rings into it)
  16566. lynx::Clip clip;
  16567. clip.pattern = t;
  16568. clip.track = t;
  16569. clip.start = (std::int64_t) k * 8 * lynx::ppq;
  16570. clip.length = 8 * lynx::ppq;
  16571. s.playlist.push_back (clip);
  16572. }
  16573. }
  16574. // the Lead's reverb mix rises over the song (automation the freeze takes into its audio)
  16575. lynx::Automation a;
  16576. a.name = "Lead reverb mix";
  16577. a.target = { lynx::AutomationTargetKind::effectMix, 1, 1, 0 };
  16578. a.points = { { 0, 0.2f }, { 24 * lynx::ppq, 0.9f } };
  16579. s.automations.push_back (a);
  16580. lynx::Clip lane;
  16581. lane.kind = lynx::ClipKind::automation;
  16582. lane.automation = 0;
  16583. lane.track = 3;
  16584. lane.length = 24 * lynx::ppq;
  16585. s.playlist.push_back (lane);
  16586. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& x, const lynx::Clip& y) { return x.start < y.start; });
  16587. });
  16588. offline.dispatchPendingMessages();
  16589. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  16590. struct Mix
  16591. {
  16592. juce::AudioBuffer<float> audio;
  16593. double renderSeconds = 0.0, audioSeconds = 0.0;
  16594. };
  16595. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr) {
  16596. Mix m;
  16597. offline.dispatchPendingMessages();
  16598. offline.freeRetiredRacks();
  16599. const juce::File file (prefix + "-" + name + ".wav");
  16600. lynx::ExportSettings settings;
  16601. settings.format = lynx::ExportSettings::Format::wav32Float;
  16602. settings.sampleRate = offline.getTransport().sampleRate.load();
  16603. settings.tailSeconds = 2.0;
  16604. juce::String error;
  16605. auto options = settings.toOptions();
  16606. options.hqAllPlugins = false;
  16607. options.disableMaxPolyphony = false;
  16608. {
  16609. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  16610. const auto started = juce::Time::getMillisecondCounterHiRes();
  16611. const auto ok = job.run ([] (double) { return true; }, error);
  16612. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  16613. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  16614. }
  16615. juce::WavAudioFormat wav;
  16616. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  16617. {
  16618. m.audio.setSize (2, (int) reader->lengthInSamples);
  16619. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  16620. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  16621. }
  16622. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TRACKFREEZE_KEEP", {}).isEmpty()) // (kept: to look at a residual)
  16623. file.deleteFile();
  16624. return m;
  16625. };
  16626. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  16627. float worst = 0.0f;
  16628. peak = 0.0f;
  16629. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  16630. for (int ch = 0; ch < 2; ++ch)
  16631. for (int i = 0; i < n; ++i)
  16632. {
  16633. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  16634. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  16635. }
  16636. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  16637. };
  16638. const auto nullLine = [&] (const char* what, const Mix& a, const Mix& b, double limit) {
  16639. float peak = 0.0f;
  16640. const auto r = residual (a, b, peak);
  16641. report << what << ": " << juce::String (r, 1) << " dB (peak " << juce::String (peak, 4) << ", " << a.audio.getNumSamples() << " / "
  16642. << b.audio.getNumSamples() << " samples)\n";
  16643. check (peak > 0.001f && r < limit && a.audio.getNumSamples() == b.audio.getNumSamples(), juce::String (what) + " below " + juce::String (limit, 0) + " dB");
  16644. return r;
  16645. };
  16646. const auto savedJson = [] (lynx::Song song) {
  16647. song.info.workSeconds = 0.0;
  16648. return lynx::ProjectFile::toJson (song, false);
  16649. };
  16650. // --- live ---
  16651. offline.capturePluginStates();
  16652. offline.editSong ([] (lynx::Song&) {}, false);
  16653. const auto before = offline.getSong();
  16654. const auto jsonBefore = savedJson (before);
  16655. auto* grid = ui.getClipGridForSnapshot();
  16656. check (grid != nullptr, "the Clip-launch workflow's grid is there");
  16657. if (grid == nullptr)
  16658. {
  16659. flush();
  16660. return false;
  16661. }
  16662. ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
  16663. write ("live");
  16664. saveMenus (juce::StringArray { "Track title (live)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-live.png");
  16665. int leadClip = -1;
  16666. for (int i = 0; i < (int) before.playlist.size() && leadClip < 0; ++i)
  16667. if (before.playlist[(std::size_t) i].track == 0 && before.playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  16668. leadClip = i;
  16669. ui.getPlaylistForSnapshot().selectForSnapshot ({ leadClip });
  16670. saveMenus (juce::StringArray { "Playlist clip (Clip-launch workflow)" }, std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().getClipMenuForSnapshot (leadClip) },
  16671. prefix + "-menu-clip.png");
  16672. const auto live = renderMix ("live");
  16673. report << "live: render " << juce::String (live.renderSeconds, 2) << " s for " << juce::String (live.audioSeconds, 2) << " s of audio\n";
  16674. // --- Freeze Track on every track ---
  16675. std::vector<int> channels;
  16676. for (int t = 0; t < 3; ++t)
  16677. {
  16678. const auto c = lynx::detailchain::forTrack (before, t).channel;
  16679. check (c == t, "track " + juce::String (t + 1) + " shows channel " + juce::String (t + 1));
  16680. const auto* why = lynx::freeze::whyNotTrack (before, c);
  16681. check (why == nullptr, "track " + juce::String (t + 1) + " can be frozen" + (why != nullptr ? juce::String (": ") + why : juce::String()));
  16682. const auto error = lynx::freezeTrackNow (offline, c);
  16683. check (error.isEmpty(), "Freeze Track " + juce::String (t + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  16684. channels.push_back (c);
  16685. }
  16686. offline.dispatchPendingMessages();
  16687. offline.freeRetiredRacks();
  16688. int loadedEffects = 0;
  16689. for (int t = 1; t <= 3; ++t)
  16690. for (int slot = 0; slot < (int) offline.getSong().mixer[(std::size_t) t].effects.size(); ++slot)
  16691. loadedEffects += offline.getEffect (t, slot) != nullptr ? 1 : 0;
  16692. check (loadedEffects == 0, "no effect of a frozen track is loaded (" + juce::String (loadedEffects) + " left)");
  16693. bool fresh = true;
  16694. for (const auto c : channels)
  16695. {
  16696. const auto& f = offline.getSong().channels[(std::size_t) c].freeze;
  16697. fresh = fresh && f.on() && f.insert == c + 1 && lynx::freeze::trackFreezeHolds (offline.getSong(), c) && ! offline.freezeOutOfDate (c)
  16698. && ! offline.frozenAudioMissing (c);
  16699. }
  16700. check (fresh, "every track is frozen with its insert, its audio on disk and up to date");
  16701. check (offline.getSong().mixer == before.mixer, "the project keeps every effect as it was (Unfreeze brings them back)");
  16702. const auto frozenSong = offline.getSong();
  16703. const auto frozen = renderMix ("frozen");
  16704. report << "frozen: render " << juce::String (frozen.renderSeconds, 2) << " s (" << juce::String (100.0 * frozen.renderSeconds / juce::jmax (0.001, live.renderSeconds), 0)
  16705. << " % of the live render's time)\n";
  16706. nullLine ("frozen vs live", live, frozen, -90.0);
  16707. write ("frozen");
  16708. saveMenus (juce::StringArray { "Track title (frozen)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-frozen.png");
  16709. if (auto* detail = ui.getDetailViewForSnapshot())
  16710. {
  16711. detail->showSelection (0, 0);
  16712. detail->setPage (lynx::DetailView::Page::devices);
  16713. write ("detail-frozen");
  16714. }
  16715. // the insert's fader is live: moved, the frozen and the live song change alike
  16716. {
  16717. auto liveLouder = before, frozenLouder = frozenSong;
  16718. liveLouder.mixer[1].volume = frozenLouder.mixer[1].volume = 0.8f;
  16719. nullLine ("frozen vs live, the Lead's fader moved afterwards", renderMix ("live-louder", &liveLouder), renderMix ("frozen-louder", &frozenLouder), -90.0);
  16720. }
  16721. // --- what a save holds ---
  16722. {
  16723. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  16724. juce::String error;
  16725. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  16726. check (json.contains ("\"trackFreeze\"") && ! json.contains ("\"freeze\""), "a track freeze is saved under its own key (older versions play it live)");
  16727. check (loaded.has_value() && loaded->channels.size() == frozenSong.channels.size() && loaded->channels[0].freeze == frozenSong.channels[0].freeze,
  16728. "a track-frozen project loads frozen, with its insert and audio files");
  16729. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore, "without the frozen state the project saves as before the freeze");
  16730. }
  16731. // --- an edit of a frozen device's insert routing: the freeze stops holding, the track plays live ---
  16732. {
  16733. offline.editSong ([] (lynx::Song& s) { s.channels[1].mixerTrack = 1; }); // (the Bass into the Lead's insert)
  16734. check (! lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && offline.freezeOutOfDate (0), "another channel routed into a frozen insert: out of date, plays live");
  16735. offline.undo();
  16736. offline.dispatchPendingMessages();
  16737. check (lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && ! offline.freezeOutOfDate (0), "undo: frozen again");
  16738. }
  16739. // --- Flatten: Bounce Track in Place on the frozen Lead, and its undo ---
  16740. {
  16741. const auto error = lynx::flattenChannelNow (offline, 0);
  16742. check (error.isEmpty(), "Bounce Track in Place of the frozen Lead (Flatten)" + (error.isEmpty() ? juce::String() : ": " + error));
  16743. const auto& song = offline.getSong();
  16744. check (song.channels[0].instrument == lynx::InstrumentKind::audioClip && song.mixer[1].effects.empty() && song.mixer[1].volume == before.mixer[1].volume
  16745. && song.channels[0].name == "Lead (Bounce)",
  16746. "the Lead is audio now (\"Lead (Bounce)\"), its insert's effects removed, its fader kept");
  16747. int audioClips = 0;
  16748. for (const auto& c : song.playlist)
  16749. audioClips += c.kind == lynx::ClipKind::audio && c.channel == 0;
  16750. report << "flattened Lead: " << audioClips << " audio clips\n";
  16751. write ("flattened");
  16752. // over the song (the flattened clips end where the arrangement ends, as a frozen track plays; an export's
  16753. // ring-out after the song's end is not in them)
  16754. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  16755. auto flatMix = renderMix ("flattened");
  16756. auto reference = live;
  16757. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  16758. flatMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  16759. nullLine ("flattened (Lead) + frozen (others) vs live, over the song", reference, flatMix, -90.0);
  16760. offline.undo();
  16761. offline.dispatchPendingMessages();
  16762. check (savedJson (offline.getSong()) == savedJson (frozenSong), "undo of the Flatten: the frozen project exactly as before");
  16763. }
  16764. // --- Unfreeze every track ---
  16765. for (const auto c : channels)
  16766. lynx::unfreezeChannel (offline, c);
  16767. offline.dispatchPendingMessages();
  16768. check (savedJson (offline.getSong()) == jsonBefore, "Unfreeze: the project saves byte for byte as before the freeze");
  16769. nullLine ("unfrozen vs live", live, renderMix ("unfrozen"), -90.0);
  16770. // --- Bounce Track in Place of a live track (render and flatten in one step, one undo) ---
  16771. {
  16772. const auto error = lynx::freezeTrackNow (offline, 1, true);
  16773. check (error.isEmpty(), "Bounce Track in Place of the live Bass" + (error.isEmpty() ? juce::String() : ": " + error));
  16774. check (offline.getSong().channels[1].instrument == lynx::InstrumentKind::audioClip && ! offline.getSong().channels[1].freeze.on(),
  16775. "the Bass is audio, not frozen");
  16776. auto bouncedMix = renderMix ("bounced");
  16777. auto reference = live;
  16778. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  16779. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  16780. bouncedMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  16781. nullLine ("Bass bounced in place vs live, over the song", reference, bouncedMix, -90.0);
  16782. offline.undo();
  16783. offline.dispatchPendingMessages();
  16784. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce Track in Place: the project as before");
  16785. }
  16786. // --- Bounce to New Track: the Lead's clips onto a new track (the clips muted, the new track with the Lead's mixer) ---
  16787. {
  16788. std::vector<int> leadClips;
  16789. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  16790. if (offline.getSong().playlist[(std::size_t) i].track == 0 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  16791. leadClips.push_back (i);
  16792. const auto channelsBefore = offline.getSong().channels.size();
  16793. const auto error = lynx::bounceToNewTrack (offline, leadClips, true);
  16794. check (error.isEmpty(), "Bounce to New Track of the Lead's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  16795. const auto& song = offline.getSong();
  16796. check (song.channels.size() == channelsBefore + 1 && song.channels.back().instrument == lynx::InstrumentKind::audioClip
  16797. && song.channels.back().mixerTrack > 3 && song.mixer[(std::size_t) song.channels.back().mixerTrack].volume == before.mixer[1].volume,
  16798. "a new audio channel holds the bounce, on an insert with the Lead's mixer");
  16799. // the song's span (the bounce stops at the last clip's end, the live render rings on after it)
  16800. auto bounced = renderMix ("bounced-new-track");
  16801. auto reference = live;
  16802. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  16803. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  16804. bounced.audio.setSize (2, reference.audio.getNumSamples(), true);
  16805. nullLine ("Bounce to New Track (Lead's clips muted) vs live, over the song", reference, bounced, -90.0);
  16806. write ("bounced-new-track");
  16807. offline.undo();
  16808. offline.dispatchPendingMessages();
  16809. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce to New Track: the project as before");
  16810. }
  16811. // --- Consolidate: the Bass's three pattern clips become one ---
  16812. {
  16813. std::vector<int> bassClips;
  16814. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  16815. if (offline.getSong().playlist[(std::size_t) i].track == 1 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  16816. bassClips.push_back (i);
  16817. const auto error = lynx::consolidateClips (offline, bassClips, true);
  16818. check (error.isEmpty(), "Consolidate of the Bass's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  16819. int left = 0;
  16820. for (const auto& c : offline.getSong().playlist)
  16821. left += c.track == 1 && c.kind == lynx::ClipKind::pattern;
  16822. check (left == 1, "one clip on the Bass track (" + juce::String (left) + ")");
  16823. nullLine ("consolidated vs live", live, renderMix ("consolidated"), -90.0);
  16824. offline.undo();
  16825. offline.dispatchPendingMessages();
  16826. check (savedJson (offline.getSong()) == jsonBefore, "undo of Consolidate: the project as before");
  16827. }
  16828. report << "frozen audio folder: " << offline.getFreezeFolder().getFullPathName() << "\n";
  16829. flush();
  16830. data.deleteRecursively();
  16831. (void) megabytes;
  16832. return failures == 0;
  16833. }
  16834. void runGridShot (const juce::String& prefix, const juce::String& projectPath = {})
  16835. {
  16836. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16837. lynx::AudioEngine offline (false);
  16838. lynx::MainComponent ui (offline, false);
  16839. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  16840. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  16841. const auto write = [&prefix, &ui] (const char* name) {
  16842. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  16843. file.deleteFile();
  16844. juce::FileOutputStream out (file);
  16845. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  16846. };
  16847. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  16848. if (projectPath.isNotEmpty())
  16849. {
  16850. ui.openFile (juce::File (projectPath));
  16851. offline.dispatchPendingMessages();
  16852. ui.setClipLaunchWorkflow (true);
  16853. offline.dispatchPendingMessages();
  16854. write ("file-both");
  16855. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  16856. write ("file-grid");
  16857. const auto& song = offline.getSong();
  16858. juce::String info;
  16859. info << "grid " << (song.clipGrid ? "yes" : "no") << ", clips " << (song.clipGrid ? (int) song.clipGrid->clips.size() : 0)
  16860. << ", scenes " << (song.clipGrid ? (int) song.clipGrid->scenes.size() : 0) << ", playlist clips " << (int) song.playlist.size() << "\n";
  16861. juce::File (prefix + "-file.txt").replaceWithText (info);
  16862. ui.setClipLaunchWorkflow (false);
  16863. return;
  16864. }
  16865. write ("pattern"); // Pattern workflow: nothing of the grid exists yet
  16866. const auto madeBefore = lynx::launcher::Runtime::instances.load();
  16867. offline.editSong ([] (lynx::Song& s) {
  16868. while (s.patterns.size() < 6)
  16869. s.patterns.emplace_back();
  16870. for (int p = 0; p < 6; ++p)
  16871. {
  16872. auto& pattern = s.patterns[(std::size_t) p];
  16873. const char* names[] { "Drums A", "Drums B", "Bass", "Chords", "Lead", "Pad" };
  16874. pattern.name = names[p];
  16875. pattern.lengthTicks = 4 * lynx::ppq;
  16876. }
  16877. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  16878. const char* tracks[] { "Drums", "Bass", "Chords", "Lead", "Vocals", "FX" };
  16879. for (int t = 0; t < 6; ++t)
  16880. s.playlistTracks[(std::size_t) t].name = tracks[t];
  16881. 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 } };
  16882. for (const auto& c : placed)
  16883. {
  16884. lynx::Clip clip;
  16885. clip.pattern = c[2];
  16886. clip.length = 4 * lynx::ppq;
  16887. lynx::launcher::setClip (s, c[0], c[1], clip);
  16888. }
  16889. auto& grid = lynx::launcher::ensureGrid (s);
  16890. const char* scenes[] { "Intro", "Verse", "Drop", "Break" };
  16891. grid.scenes.resize (6);
  16892. for (int r = 0; r < 4; ++r)
  16893. grid.scenes[(std::size_t) r].name = scenes[r];
  16894. }, false);
  16895. offline.dispatchPendingMessages();
  16896. write ("pattern-edited"); // the same song as -pattern-after: the workflow must leave no trace
  16897. ui.setClipLaunchWorkflow (true);
  16898. offline.dispatchPendingMessages();
  16899. if (auto* runtime = offline.launcherStateForSnapshot())
  16900. {
  16901. runtime->tracks[0].playing.store (2);
  16902. runtime->tracks[0].progress.store (0.4f);
  16903. runtime->tracks[0].taken.store (true);
  16904. runtime->tracks[1].playing.store (2);
  16905. runtime->tracks[1].progress.store (0.4f);
  16906. runtime->tracks[1].taken.store (true);
  16907. runtime->tracks[2].pending.store (2);
  16908. runtime->tracks[3].taken.store (true);
  16909. }
  16910. write ("both");
  16911. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  16912. write ("grid");
  16913. // round 190bv: recording into slots and the Groove Pool. Two tracks armed (round record buttons in their empty
  16914. // slots, their arm buttons lit), one of them recording and one waiting for its start; then a clip through a
  16915. // groove with the pool shown, and the slot menus
  16916. if (auto* gridView = ui.getClipGridForSnapshot())
  16917. {
  16918. offline.setGridTrackArmed (4, true);
  16919. offline.setGridTrackArmed (5, true, false);
  16920. offline.dispatchPendingMessages();
  16921. write ("rec-armed");
  16922. if (auto* runtime = offline.launcherStateForSnapshot())
  16923. {
  16924. runtime->tracks[4].recording.store (1);
  16925. runtime->tracks[4].recordFrom.store (0.0); // (round 190cy: one beat recorded, the counter reads 0.1.0)
  16926. runtime->clockNow.store ((double) lynx::ppq);
  16927. runtime->tracks[5].recordPending.store (1);
  16928. }
  16929. write ("rec-recording");
  16930. if (auto* runtime = offline.launcherStateForSnapshot())
  16931. {
  16932. runtime->tracks[4].recording.store (-1);
  16933. runtime->tracks[5].recordPending.store (-1);
  16934. }
  16935. offline.editSong ([] (lynx::Song& s) {
  16936. const auto& bank = lynx::groove::factoryBank();
  16937. std::uint32_t first = 0;
  16938. for (const auto index : { std::size_t (9), std::size_t (20), std::size_t (27) })
  16939. if (index < bank.size())
  16940. {
  16941. const auto id = lynx::groove::add (s.grooves, bank[index].groove);
  16942. first = first == 0 ? id : first;
  16943. }
  16944. lynx::groove::setClipGroove (s, 0, 0, first);
  16945. }, false);
  16946. offline.dispatchPendingMessages();
  16947. lynx::setClipGridGroovePoolShown (*gridView, true);
  16948. write ("groove-pool");
  16949. saveMenus ({ "Clip slot", "Groove", "Empty slot" },
  16950. { lynx::clipGridSlotMenu (*gridView, 0, 0), [&] {
  16951. juce::PopupMenu found;
  16952. const auto menu = lynx::clipGridSlotMenu (*gridView, 0, 0);
  16953. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  16954. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Groove"))
  16955. found = *it.getItem().subMenu;
  16956. return found;
  16957. }(), lynx::clipGridSlotMenu (*gridView, 4, 1) },
  16958. prefix + "-rec-menus.png");
  16959. lynx::setClipGridGroovePoolShown (*gridView, false);
  16960. // round 190cy: a second record button pressed while recording: the first take ("Vocals 1") plays on, the
  16961. // clicked slot records "Vocals 2" with its counter at 2.0.2 (as Live 12.4.16, live check 190cw shot 03b)
  16962. {
  16963. const auto name = offline.slotRecordingName (4);
  16964. offline.editSong ([&name] (lynx::Song& s) { lynx::session::placeRecordedPattern (s, 4, 0, {}, 8 * lynx::ppq, name); }, false);
  16965. offline.dispatchPendingMessages();
  16966. if (auto* runtime = offline.launcherStateForSnapshot())
  16967. {
  16968. runtime->tracks[4].playing.store (0);
  16969. runtime->tracks[4].progress.store (0.3f);
  16970. runtime->tracks[4].recording.store (1);
  16971. runtime->tracks[4].recordFrom.store (0.0);
  16972. runtime->clockNow.store (8.0 * lynx::ppq + 2.0 * lynx::ppq / 4.0);
  16973. }
  16974. write ("rec-second");
  16975. if (auto* runtime = offline.launcherStateForSnapshot())
  16976. {
  16977. runtime->tracks[4].playing.store (-1);
  16978. runtime->tracks[4].recording.store (-1);
  16979. }
  16980. offline.editSong ([] (lynx::Song& s) {
  16981. if (lynx::session::cut (s, 4, 0) && ! s.patterns.empty())
  16982. s.patterns.pop_back();
  16983. }, false);
  16984. offline.dispatchPendingMessages();
  16985. }
  16986. offline.setGridTrackArmed (4, false);
  16987. offline.setGridTrackArmed (5, false);
  16988. offline.dispatchPendingMessages();
  16989. }
  16990. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  16991. write ("song");
  16992. ui.setClipLaunchWorkflow (false);
  16993. write ("pattern-after");
  16994. juce::File (prefix + "-counts.txt").replaceWithText ("runtimes before " + juce::String (madeBefore) + ", after " + juce::String (lynx::launcher::Runtime::instances.load()) + "\n");
  16995. }
  16996. // Round 190bu: the Simple workflow's track dock (ui/SimpleDock.h), off-screen
  16997. void runSimpleFxShot (const juce::String& prefix)
  16998. {
  16999. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17000. lynx::AudioEngine offline (false);
  17001. lynx::MainComponent ui (offline, false);
  17002. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  17003. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  17004. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  17005. const auto file = juce::File (prefix + "-" + name + ".png");
  17006. file.deleteFile();
  17007. juce::FileOutputStream out (file);
  17008. juce::PNGImageFormat().writeImageToStream (image, out);
  17009. };
  17010. juce::String report;
  17011. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  17012. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  17013. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  17014. ui.selectTabForSnapshot (2);
  17015. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17016. offline.dispatchPendingMessages();
  17017. auto* simple = ui.getSimpleWorkflowForSnapshot();
  17018. if (simple == nullptr)
  17019. {
  17020. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  17021. return;
  17022. }
  17023. simple->hideChooser();
  17024. // three tracks: a voice, keys with a few chords, a drum kit
  17025. int keysInsert = -1;
  17026. offline.editSong ([&keysInsert] (lynx::Song& s) {
  17027. namespace st = lynx::simpletracks;
  17028. st::Request q;
  17029. q.kind = st::Kind::voice;
  17030. q.name = "Lead vocal";
  17031. st::addTrack (s, q);
  17032. q = {};
  17033. q.kind = st::Kind::instrument;
  17034. q.name = "Keys";
  17035. lynx::ChannelDef keys;
  17036. keys.instrument = lynx::InstrumentKind::synth;
  17037. q.channel = keys;
  17038. lynx::Pattern chords;
  17039. for (int i = 0; i < 4; ++i)
  17040. for (int k : { 60, 64, 67 })
  17041. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  17042. q.pattern = chords;
  17043. keysInsert = st::addTrack (s, q).insert;
  17044. q = {};
  17045. q.kind = st::Kind::drums;
  17046. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  17047. {
  17048. lynx::ChannelDef c;
  17049. c.instrument = kind;
  17050. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  17051. q.kit.push_back (c);
  17052. }
  17053. lynx::Pattern beat;
  17054. for (int step = 0; step < 16; step += 2)
  17055. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
  17056. q.pattern = beat;
  17057. st::addTrack (s, q);
  17058. });
  17059. offline.dispatchPendingMessages();
  17060. simple->hideChooser();
  17061. auto& playlist = ui.getPlaylistForSnapshot();
  17062. // the tracks' places in the Playlist
  17063. int voiceTrack = -1, keysTrack = -1, drumsTrack = -1;
  17064. {
  17065. const auto& song = offline.getSong();
  17066. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  17067. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  17068. {
  17069. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  17070. voiceTrack = t;
  17071. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  17072. keysTrack = t;
  17073. else if (*kind == lynx::simpletracks::Kind::drums && drumsTrack < 0)
  17074. drumsTrack = t;
  17075. }
  17076. }
  17077. check ("three Simple tracks (voice, keys, drums)", voiceTrack >= 0 && keysTrack >= 0 && drumsTrack >= 0);
  17078. playlist.selectTrack (keysTrack);
  17079. offline.dispatchPendingMessages();
  17080. auto* dock = simple->dockForSnapshot();
  17081. if (dock == nullptr)
  17082. {
  17083. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  17084. return;
  17085. }
  17086. // the whole window and the dock alone, at 1x and 2x
  17087. const auto shots = [&] (const juce::String& name) {
  17088. offline.dispatchPendingMessages();
  17089. for (float scale : { 1.0f, 2.0f })
  17090. {
  17091. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  17092. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  17093. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  17094. }
  17095. };
  17096. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  17097. juce::StringArray names { title };
  17098. std::vector<juce::PopupMenu> menus { menu };
  17099. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17100. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  17101. {
  17102. names.add (subTitle);
  17103. menus.push_back (*it.getItem().subMenu);
  17104. }
  17105. saveMenus (names, menus, prefix + "-" + name + ".png");
  17106. };
  17107. // --- the Instrument tab ---------------------------------------------------------------------------------------
  17108. check ("the dock shows the selected track", dock->shownTrack() == keysTrack && dock->isVisible() && dock->getParentComponent() != nullptr);
  17109. check ("an instrument track opens on its sound", dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::instrument);
  17110. const auto channel = dock->channelForCheck();
  17111. line ("sound at first: " + dock->soundNameForCheck() + ", rows in its category: " + juce::String (dock->soundRowsForCheck()));
  17112. shots ("instrument");
  17113. // a click on a row of another category: the track plays that sound, its own settings stay
  17114. const auto before = offline.getSong().channels[(std::size_t) channel];
  17115. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::pad);
  17116. offline.dispatchPendingMessages();
  17117. const auto padRows = dock->soundRowsForCheck();
  17118. dock->clickSoundForCheck (juce::jmin (2, padRows - 1));
  17119. offline.dispatchPendingMessages();
  17120. {
  17121. const auto& now = offline.getSong().channels[(std::size_t) channel];
  17122. const auto found = lynx::soundlib::find (lynx::soundlib::builtIn(), now);
  17123. check ("a click on a sound puts it on the track's channel (" + dock->soundNameForCheck() + ")",
  17124. padRows > 0 && found >= 0 && lynx::soundlib::builtIn()[(std::size_t) found].category == lynx::soundlib::Category::pad
  17125. && ! lynx::soundlib::sameSound (before, now));
  17126. check ("the channel keeps its name, level and insert", now.name == before.name && now.volume == before.volume && now.mixerTrack == before.mixerTrack);
  17127. double seconds = 0.0;
  17128. const auto heard = offline.auditionSound (now, { 60, 64, 67 }, &seconds);
  17129. check ("the sound's audition renders (" + juce::String (seconds, 2) + " s)", heard && seconds > 1.0);
  17130. }
  17131. shots ("instrument-pad");
  17132. const auto picked = dock->soundNameForCheck();
  17133. dock->stepSoundForCheck (1);
  17134. offline.dispatchPendingMessages();
  17135. const auto stepped = dock->soundNameForCheck();
  17136. dock->stepSoundForCheck (-1);
  17137. offline.dispatchPendingMessages();
  17138. check ("the arrows step through the category (" + picked + " -> " + stepped + " -> back)", stepped != picked && dock->soundNameForCheck() == picked);
  17139. check ("one undo step per sound", offline.canUndo());
  17140. // the user's SoundFont files (an index made here: no file is read)
  17141. {
  17142. std::vector<lynx::sf::IndexedFont> fonts (2);
  17143. fonts[0].path = "/home/me/SoundFonts/Concert Band.sf2";
  17144. fonts[0].name = "Concert Band";
  17145. int program = 0;
  17146. for (const char* name : { "Grand Piano", "Bright Piano", "Electric Piano", "Harpsichord", "Clavinet", "Celesta", "Music Box", "Vibraphone" })
  17147. fonts[0].presets.push_back ({ name, 0, program++ });
  17148. for (const auto& [name, p] : std::initializer_list<std::pair<const char*, int>> { { "Finger Bass", 33 }, { "Picked Bass", 34 }, { "Nylon Guitar", 24 }, { "Strings", 48 }, { "Choir Aahs", 52 }, { "Trumpet", 56 } })
  17149. fonts[0].presets.push_back ({ name, 0, p });
  17150. fonts[0].presets.push_back ({ "Standard Kit", 128, 0 });
  17151. fonts[1].path = "/home/me/SoundFonts/Old Upright.sf2";
  17152. fonts[1].name = "Old Upright";
  17153. fonts[1].presets.push_back ({ "Old Upright", 0, 0 });
  17154. fonts[1].presets.push_back ({ "Old Upright Soft", 0, 1 });
  17155. dock->setFontsForSnapshot (fonts);
  17156. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::keys);
  17157. offline.dispatchPendingMessages();
  17158. check ("My SoundFonts lists the presets of the user's files by category (Keys: " + juce::String (dock->soundRowsForCheck()) + " of 17)", dock->soundRowsForCheck() == 7);
  17159. dock->clickSoundForCheck (0);
  17160. offline.dispatchPendingMessages();
  17161. const auto& now = offline.getSong().channels[(std::size_t) channel];
  17162. check ("a SoundFont preset becomes the track's sound (" + dock->soundNameForCheck() + ")",
  17163. now.instrument == lynx::InstrumentKind::soundfont && juce::String (now.samplePath).endsWith (".sf2"));
  17164. shots ("instrument-soundfonts");
  17165. }
  17166. // --- the Effects tab ------------------------------------------------------------------------------------------
  17167. playlist.selectTrack (voiceTrack);
  17168. offline.dispatchPendingMessages();
  17169. const auto insert = dock->insertForCheck();
  17170. check ("an audio track has no Instrument tab and opens on its effects",
  17171. dock->shownTrack() == voiceTrack && ! dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::effects && insert > 0);
  17172. check ("no effects yet: no cards", dock->cardCountForCheck() == 0);
  17173. shots ("effects-empty");
  17174. menuShot (dock->addMenuForSnapshot(), lynx::tr ("Add an effect"), {}, "menu-add");
  17175. // + adds one-knob effects at the end of the chain
  17176. dock->addOneKnobForCheck (lynx::goals::brighter);
  17177. dock->addOneKnobForCheck (lynx::goals::room);
  17178. dock->addOneKnobForCheck (lynx::goals::level);
  17179. offline.dispatchPendingMessages();
  17180. const auto slotsText = [&offline] (int t) {
  17181. juce::String text;
  17182. const auto rows = lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) t].effects); // (the Mixer's slot of each)
  17183. std::size_t at = 0;
  17184. for (const auto& fx : offline.getSong().mixer[(std::size_t) t].effects)
  17185. text << "[slot " << rows[at++] + 1 << " " << lynx::effectInfo (fx.kind).name
  17186. << (lynx::goals::active (fx) ? " = " + juce::String (lynx::goals::name (fx.goal)) + " " + juce::String (juce::roundToInt (fx.goalAmount * 100.0f)) + "%" : juce::String())
  17187. << (fx.enabled ? "" : " off") << "] ";
  17188. return text.trimEnd();
  17189. };
  17190. line ("after + x3: " + slotsText (insert));
  17191. check ("three cards, three one-knob effects", dock->cardCountForCheck() == 3 && dock->oneKnobCardsForCheck() == 3);
  17192. // the knob writes the effect's own parameters
  17193. const auto roomBefore = offline.getSong().mixer[(std::size_t) insert].effects[1];
  17194. dock->turnKnobForCheck (1, 0.8f);
  17195. offline.dispatchPendingMessages();
  17196. {
  17197. const auto& room = offline.getSong().mixer[(std::size_t) insert].effects[1];
  17198. check ("the knob at 80 % writes the mapped parameters", std::abs (room.goalAmount - 0.8f) < 1.0e-6f && lynx::goals::active (room) && ! (room.params == roomBefore.params));
  17199. }
  17200. // ‹ › reorder, × removes
  17201. dock->moveCardForCheck (2, -1);
  17202. offline.dispatchPendingMessages();
  17203. line ("Level moved left: " + slotsText (insert));
  17204. {
  17205. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  17206. check ("the card moved one place earlier", fx.size() == 3 && fx[1].goal == lynx::goals::level && fx[2].goal == lynx::goals::room);
  17207. }
  17208. dock->removeCardForCheck (0);
  17209. offline.dispatchPendingMessages();
  17210. line ("Brighter removed: " + slotsText (insert));
  17211. check ("the card is gone", dock->cardCountForCheck() == 2 && offline.getSong().mixer[(std::size_t) insert].effects.size() == 2);
  17212. // a hand edit in the full editor: the slot is an ordinary effect again (its card shows Mix)
  17213. offline.editSong ([insert] (lynx::Song& s) {
  17214. auto& slot = s.mixer[(std::size_t) insert].effects[0];
  17215. const auto moved = (std::size_t) lynx::goals::mapping (slot.goal, slot.goalAmount).back().param;
  17216. slot.params[moved] = slot.params[moved] > 0.5f ? 0.2f : 0.9f;
  17217. });
  17218. offline.dispatchPendingMessages();
  17219. check ("a parameter moved by hand makes the card an ordinary effect", dock->cardCountForCheck() == 2 && dock->oneKnobCardsForCheck() == 1);
  17220. dock->turnKnobForCheck (0, 0.5f); // (its knob is the slot's Mix now)
  17221. offline.dispatchPendingMessages();
  17222. check ("an ordinary card's knob is the slot's Mix", std::abs (offline.getSong().mixer[(std::size_t) insert].effects[0].mix - 0.5f) < 1.0e-6f);
  17223. // a preset replaces the chain; Blend is the chain's dry/wet
  17224. if (const auto* preset = lynx::chains::find ("Clear Voice"))
  17225. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  17226. offline.dispatchPendingMessages();
  17227. line ("preset Clear Voice: " + slotsText (insert));
  17228. check ("the preset's chain is on the insert", offline.getSong().mixer[(std::size_t) insert].chainPreset == "Clear Voice" && lynx::chains::unchanged (offline.getSong(), insert)
  17229. && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size());
  17230. shots ("effects-preset");
  17231. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("Voice"), "menu-preset");
  17232. dock->setBlendForCheck (0.7f);
  17233. dock->addOneKnobForCheck (lynx::goals::echo);
  17234. offline.dispatchPendingMessages();
  17235. check ("Blend 70 % is the insert's chain blend; the preset shows as edited",
  17236. std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.7f) < 1.0e-6f && ! lynx::chains::unchanged (offline.getSong(), insert));
  17237. shots ("effects-edited");
  17238. // a user preset: saved to a file, loaded on another track (its slots and Blend; that track's level stays)
  17239. const auto mine = offline.getSong().mixer[(std::size_t) insert];
  17240. const auto saved = lynx::SimpleDock::saveUserPreset (offline, insert, "My voice");
  17241. const auto file = lynx::SimpleDock::userPresetFolder().getChildFile ("My voice.lynxtrack");
  17242. check ("the preset is saved as " + file.getFileName(), saved && file.existsAsFile() && offline.getSong().mixer[(std::size_t) insert].chainPreset == "My voice");
  17243. offline.editSong ([keysInsert] (lynx::Song& s) { s.mixer[(std::size_t) keysInsert].volume = 0.42f; });
  17244. const auto loaded = keysInsert > 0 && lynx::SimpleDock::loadUserPreset (offline, keysInsert, file);
  17245. offline.dispatchPendingMessages();
  17246. {
  17247. const auto& other = offline.getSong().mixer[(std::size_t) keysInsert];
  17248. auto same = loaded && other.effects.size() == mine.effects.size() && std::abs (other.chainBlend - mine.chainBlend) < 1.0e-6f && other.chainPreset == "My voice";
  17249. for (std::size_t i = 0; same && i < mine.effects.size(); ++i)
  17250. same = other.effects[i].kind == mine.effects[i].kind && other.effects[i].goal == mine.effects[i].goal
  17251. && lynx::mixerops::effectRows (other.effects)[i] == lynx::mixerops::effectRows (mine.effects)[i] && std::abs (other.effects[i].goalAmount - mine.effects[i].goalAmount) < 1.0e-6f && lynx::goals::active (other.effects[i]) == lynx::goals::active (mine.effects[i]);
  17252. check ("loaded on the Keys track: the same slots and Blend", same);
  17253. check ("the Keys track keeps its level", std::abs (other.volume - 0.42f) < 1.0e-6f);
  17254. line ("Keys after load: " + slotsText (keysInsert));
  17255. }
  17256. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("My presets"), "menu-preset-mine");
  17257. file.deleteFile();
  17258. // the drums: effects only (a kit has no single sound to pick)
  17259. playlist.selectTrack (drumsTrack);
  17260. offline.dispatchPendingMessages();
  17261. check ("the Drums track shows its insert's effects, no Instrument tab", dock->shownTrack() == drumsTrack && ! dock->hasInstrumentTabForCheck() && dock->insertForCheck() > 0);
  17262. if (const auto* preset = lynx::chains::find ("Smash Room"))
  17263. offline.editSongStructural ([t = dock->insertForCheck(), preset] (lynx::Song& s) { lynx::chains::apply (s, t, *preset); });
  17264. shots ("effects-drums");
  17265. // the project file keeps all of it
  17266. {
  17267. juce::String error;
  17268. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  17269. const auto back = lynx::ProjectFile::fromJson (json, error);
  17270. auto same = back && back->mixer.size() == offline.getSong().mixer.size();
  17271. for (std::size_t t = 0; same && t < back->mixer.size(); ++t)
  17272. {
  17273. const auto& a = offline.getSong().mixer[t];
  17274. const auto& b = back->mixer[t];
  17275. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  17276. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  17277. same = a.effects[i].kind == b.effects[i].kind && a.effects[i].goal == b.effects[i].goal && a.effects[i].row == b.effects[i].row
  17278. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f;
  17279. }
  17280. check ("saved and loaded as a project: the same chains, knobs, Blend and preset names", same);
  17281. }
  17282. // --- the same plugins in the same slots in FL's layout --------------------------------------------------------
  17283. const auto simpleSong = offline.getSong();
  17284. const auto inSimple = slotsText (insert);
  17285. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  17286. offline.dispatchPendingMessages();
  17287. check ("Pattern workflow: the dock is gone", dock->getParentComponent() == nullptr);
  17288. ui.selectTabForSnapshot (3);
  17289. ui.getMixerForSnapshot().selectTrack (insert);
  17290. offline.dispatchPendingMessages();
  17291. for (float scale : { 1.0f, 2.0f })
  17292. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), juce::String ("pattern-mixer") + (scale > 1.0f ? "@2x" : ""));
  17293. line ("Simple layout: " + inSimple);
  17294. line ("Pattern layout: " + slotsText (insert));
  17295. check ("the same effects in the same Mixer slots in the Pattern workflow", offline.getSong().mixer == simpleSong.mixer && offline.getSong().channels == simpleSong.channels);
  17296. // an effect added in the Mixer's way shows as a card when the Simple workflow comes back
  17297. offline.editSongStructural ([insert] (lynx::Song& s) { lynx::mixerops::insertEffectAtRow (s, insert, lynx::makeEffectSlot (lynx::EffectKind::chorus), 7); });
  17298. ui.selectTabForSnapshot (2);
  17299. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17300. offline.dispatchPendingMessages();
  17301. simple->hideChooser();
  17302. playlist.selectTrack (voiceTrack);
  17303. offline.dispatchPendingMessages();
  17304. check ("back in Simple: the dock shows the insert as it is now, the Mixer's new effect too",
  17305. dock->getParentComponent() != nullptr && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size()
  17306. && lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) insert].effects).back() == 7);
  17307. line ("Simple again: " + slotsText (insert));
  17308. shots ("effects-back");
  17309. // hidden with its key, shown again by "+FX"
  17310. simple->toggleDock();
  17311. offline.dispatchPendingMessages();
  17312. check ("Ctrl+Alt+L hides the dock", ! simple->isDockShowing() && ! lynx::SimpleDock::shownSetting);
  17313. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "dock-hidden");
  17314. simple->showEffectsOfInsert (keysInsert);
  17315. offline.dispatchPendingMessages();
  17316. check ("+FX on a track header shows the dock on that track's effects",
  17317. simple->isDockShowing() && dock->shownTrack() == keysTrack && dock->getTab() == lynx::SimpleDock::Tab::effects && dock->insertForCheck() == keysInsert);
  17318. simple->cycleDockTab();
  17319. check ("Shift+Tab goes to the Instrument tab", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  17320. line ("Simple workflow objects: " + juce::String (madeBefore) + " before, " + juce::String (lynx::SimpleWorkflow::instances.load()) + " after");
  17321. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  17322. juce::File (prefix + "-report.txt").replaceWithText (report);
  17323. }
  17324. // --simpleclosetest (round 190fc, 0.1.27 RC blocker B1): every close in the Simple layout crashed (the Simple workflow
  17325. // was destroyed after the Workspace and its destructor called into it). Off-screen, no window: the main window in the
  17326. // Simple layout with everything of it open — Welcome, the first-song tour's card, Start from, a demo song, each dock
  17327. // tab (the Editor tab docks the Piano roll), Finish, Lyrics, the chooser — then destroyed as the app's shutdown does.
  17328. // A second main window goes Simple -> Pattern -> Simple and closes too. Checks: no Simple workflow outlives its main
  17329. // window's destructor body, none is left at all. (Under ASan on Linux the old order is a heap-use-after-free.)
  17330. bool runSimpleCloseTest (const juce::String& reportPath)
  17331. {
  17332. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17333. juce::String report;
  17334. bool ok = true;
  17335. const auto line = [&report, &reportPath] (const juce::String& text) {
  17336. report << text << "\n";
  17337. juce::File (reportPath).replaceWithText (report); // (written as it goes: a crash still leaves the last step)
  17338. };
  17339. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  17340. line ((good ? "ok " : "FAIL ") + what);
  17341. ok = ok && good;
  17342. };
  17343. const auto aliveBefore = lynx::SimpleWorkflow::alive.load();
  17344. {
  17345. lynx::AudioEngine offline (false);
  17346. {
  17347. lynx::MainComponent ui (offline, false);
  17348. ui.setSize (1600, 900);
  17349. ui.setVisible (true); // (no window: the docked editor and the tour only need their parents visible)
  17350. const auto settle = [&] {
  17351. for (int k = 0; k < 3; ++k)
  17352. offline.dispatchPendingMessages();
  17353. };
  17354. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17355. settle();
  17356. auto* simple = ui.getSimpleWorkflowForSnapshot();
  17357. check ("the Simple workflow is up", simple != nullptr);
  17358. if (simple != nullptr)
  17359. {
  17360. const auto empty = lynx::builtInTemplateIndex ("Empty");
  17361. offline.setSong (empty >= 0 ? lynx::makeNewProject (empty) : lynx::makeNewProject());
  17362. settle();
  17363. simple->showWelcome();
  17364. settle();
  17365. auto* tour = simple->tourForSnapshot();
  17366. check ("Welcome screen shown", tour != nullptr && tour->isWelcomeShowing());
  17367. simple->startOrContinueTour();
  17368. settle();
  17369. simple->doTourStep (lynx::tour::beat);
  17370. settle();
  17371. check ("the tour runs with its card up", simple->tourRunning() && tour != nullptr && tour->cardForSnapshot() != nullptr);
  17372. // a demo song from Start from (the panel stays up over the Playlist)
  17373. if (auto* start = simple->startFromForSnapshot(); start != nullptr && lynx::demos::count > 1)
  17374. {
  17375. offline.setSong (lynx::demos::make (1));
  17376. settle();
  17377. check ("a demo song opened, Start from up", simple->isStartFromShowing() && ! offline.getSong().playlist.empty());
  17378. }
  17379. // the dock on a track, every tab (the Editor tab docks the Piano roll)
  17380. if (auto* dock = simple->dockForSnapshot())
  17381. {
  17382. simple->trackSelected ([] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  17383. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  17384. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  17385. return t;
  17386. return 0;
  17387. } (offline.getSong()));
  17388. for (auto tab : { lynx::SimpleDock::Tab::instrument, lynx::SimpleDock::Tab::keyboard, lynx::SimpleDock::Tab::editor,
  17389. lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::editor })
  17390. {
  17391. dock->setTab (tab);
  17392. settle();
  17393. }
  17394. check ("the dock shows", simple->isDockShowing());
  17395. line ("dock tab at the close: " + juce::String ((int) dock->getTab()) + " (2 = Editor, the docked Piano roll)");
  17396. }
  17397. ui.toggleLyrics(); // (Lyrics, then Finish: they share the dock on the right)
  17398. settle();
  17399. simple->showFinish();
  17400. settle();
  17401. check ("Finish open", simple->isFinishShowing());
  17402. simple->showChooser();
  17403. settle();
  17404. line ("Simple workflow objects alive before the close: " + juce::String (lynx::SimpleWorkflow::alive.load() - aliveBefore));
  17405. }
  17406. } // (the main window goes as at shutdown)
  17407. check ("no Simple workflow outlived its main window's destructor body (it reaches the Workspace)",
  17408. lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore);
  17409. check ("none left after the close", lynx::SimpleWorkflow::alive.load() == aliveBefore);
  17410. // Simple, then Pattern, then Simple again, and closed
  17411. {
  17412. lynx::MainComponent ui (offline, false);
  17413. ui.setSize (1600, 900);
  17414. ui.setVisible (true);
  17415. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17416. offline.dispatchPendingMessages();
  17417. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  17418. offline.dispatchPendingMessages();
  17419. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17420. offline.dispatchPendingMessages();
  17421. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  17422. simple->showWelcome();
  17423. offline.dispatchPendingMessages();
  17424. }
  17425. check ("Simple -> Pattern -> Simple, closed: none outlived the destructor body", lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore
  17426. && lynx::SimpleWorkflow::alive.load() == aliveBefore);
  17427. }
  17428. line (ok ? "result=OK" : "result=FAILED");
  17429. return ok;
  17430. }
  17431. void runTour190dvShot (const juce::String& prefix)
  17432. {
  17433. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17434. lynx::AudioEngine offline (false);
  17435. lynx::MainComponent ui (offline, false);
  17436. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  17437. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  17438. ui.setVisible (true); // (no window: the docked editor and the ring's targets only need their parents visible)
  17439. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  17440. const auto file = juce::File (prefix + "-" + name + ".png");
  17441. file.deleteFile();
  17442. juce::FileOutputStream out (file);
  17443. juce::PNGImageFormat().writeImageToStream (image, out);
  17444. };
  17445. juce::String report;
  17446. // (written as it goes: a run that stops halfway still leaves its checks)
  17447. const auto line = [&report, &prefix] (const juce::String& text) {
  17448. report << text << "\n";
  17449. juce::File (prefix + "-report.txt").replaceWithText (report);
  17450. };
  17451. const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
  17452. ui.selectTabForSnapshot (2);
  17453. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17454. offline.dispatchPendingMessages();
  17455. auto* simple = ui.getSimpleWorkflowForSnapshot();
  17456. auto* tour = simple != nullptr ? simple->tourForSnapshot() : nullptr;
  17457. if (tour == nullptr)
  17458. {
  17459. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow / tour\n");
  17460. return;
  17461. }
  17462. check ("no Welcome screen by itself in a --snapshot route (not a real first start)", ! tour->isWelcomeShowing());
  17463. const auto settle = [&] {
  17464. for (int k = 0; k < 3; ++k)
  17465. offline.dispatchPendingMessages();
  17466. };
  17467. const auto window = [&] (const juce::String& name, bool twoX = false) {
  17468. settle();
  17469. tour->ringForSnapshot(); // (the ring follows the layout: resolved now, as its timer would)
  17470. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
  17471. if (twoX)
  17472. if (auto* card = tour->cardForSnapshot(); card != nullptr && card->getParentComponent() != nullptr)
  17473. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), name + "-card@2x");
  17474. };
  17475. const auto stepIs = [&] (int step, const juce::String& target) {
  17476. settle();
  17477. const auto ring = tour->ringForSnapshot();
  17478. const auto id = tour->targetIdForSnapshot();
  17479. line ("step " + juce::String (tour->step() + 1) + " (" + lynx::tour::stepId (tour->step()) + "): ring on " + (id.isEmpty() ? juce::String ("-") : id) + " "
  17480. + ring.toString());
  17481. check (juce::String ("the card shows step ") + lynx::tour::stepId (step), tour->isRunning() && tour->step() == step);
  17482. if (target.isNotEmpty())
  17483. check ("the ring is on " + target, id == target && ! ring.isEmpty());
  17484. };
  17485. // --- the Welcome screen (on a new, empty project: the built-in "Empty" template, as File › New can give) -------------
  17486. const auto emptyProject = [] {
  17487. const auto index = lynx::builtInTemplateIndex ("Empty");
  17488. return index >= 0 ? lynx::makeNewProject (index) : lynx::makeNewProject();
  17489. };
  17490. offline.setSong (emptyProject());
  17491. settle();
  17492. check ("the new project is empty for the Simple workflow (it opens on the chooser)", lynx::simpletracks::isEmptySong (offline.getSong()));
  17493. simple->showWelcome();
  17494. settle();
  17495. check ("Help › Welcome screen shows it", tour->isWelcomeShowing());
  17496. window ("welcome");
  17497. if (auto* w = tour->welcomeForSnapshot())
  17498. writeImage (w->createComponentSnapshot (w->getLocalBounds(), true, 2.0f), "welcome@2x");
  17499. tour->clickForSnapshot ("welcome.tour");
  17500. settle();
  17501. check ("Make my first song: the Welcome screen closes, the tour starts, the chooser comes up for the beat",
  17502. ! tour->isWelcomeShowing() && tour->isRunning() && simple->isChooserShowing());
  17503. // --- step 1: the beat ---------------------------------------------------------------------------------------------
  17504. stepIs (lynx::tour::beat, "simple.tile.drums");
  17505. window ("step1-beat", true);
  17506. simple->showStarterPageForSnapshot();
  17507. stepIs (lynx::tour::beat, "simple.starters");
  17508. window ("step1-beat-starters");
  17509. tour->clickForSnapshot ("do");
  17510. settle();
  17511. check ("Do it for me added a starter beat", lynx::tour::hasBeat (offline.getSong()));
  17512. // --- step 2: the key ----------------------------------------------------------------------------------------------
  17513. stepIs (lynx::tour::key, "toolbar.key");
  17514. window ("step2-key", true);
  17515. tour->clickForSnapshot ("do");
  17516. settle();
  17517. check ("Do it for me set A minor", lynx::projectkey::get (offline.getSong()).has_value());
  17518. // --- step 3: an instrument (Add track opens the chooser: the ring moves to its tile) ------------------------------
  17519. stepIs (lynx::tour::instrument, "simple.addTrack");
  17520. window ("step3-instrument", true);
  17521. simple->showChooser();
  17522. stepIs (lynx::tour::instrument, "simple.tile.instrument");
  17523. window ("step3-instrument-chooser");
  17524. tour->clickForSnapshot ("do");
  17525. settle();
  17526. check ("Do it for me added an Instrument track (the chooser closed)", lynx::tour::firstInstrumentTrack (offline.getSong()) >= 0 && ! simple->isChooserShowing());
  17527. // --- step 4: chords -----------------------------------------------------------------------------------------------
  17528. stepIs (lynx::tour::chords, "keyboard.chordPad");
  17529. window ("step4-chords", true);
  17530. tour->clickForSnapshot ("do");
  17531. settle();
  17532. check ("Do it for me wrote four chords (12 notes) on the instrument's pattern", [&] {
  17533. const auto& song = offline.getSong();
  17534. const auto p = lynx::simpletracks::patternOf (song, lynx::tour::firstInstrumentTrack (song));
  17535. return p >= 0 && song.patterns[(std::size_t) p].notes.size() == 12;
  17536. }());
  17537. // --- step 5: a voice or a loop (no "Do it for me": a loop is dropped as a user would) ------------------------------
  17538. stepIs (lynx::tour::loop, "simple.addTrack");
  17539. window ("step5-loop", true);
  17540. {
  17541. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190dv-loops");
  17542. dir.deleteRecursively();
  17543. dir.createDirectory();
  17544. const auto wav = dir.getChildFile ("Warm Keys 120 Am.wav");
  17545. const int frames = 192000;
  17546. juce::AudioBuffer<float> audio (1, frames);
  17547. for (int i = 0; i < frames; ++i)
  17548. {
  17549. const auto t = (double) i / 48000.0;
  17550. double v = 0.0;
  17551. for (const auto key : { 57, 60, 64 })
  17552. v += std::sin (2.0 * juce::MathConstants<double>::pi * 440.0 * std::pow (2.0, (key - 69) / 12.0) * t);
  17553. audio.setSample (0, i, (float) (0.1 * v * (1.0 - std::exp (-std::fmod (t, 0.5) * 60.0))));
  17554. }
  17555. {
  17556. juce::WavAudioFormat format;
  17557. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  17558. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  17559. {
  17560. out.release();
  17561. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  17562. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  17563. }
  17564. }
  17565. simple->dropFiles ({ wav.getFullPathName() }, 0);
  17566. settle();
  17567. check ("a dropped loop (A minor in its name) follows the key", [&] {
  17568. for (const auto& c : offline.getSong().playlist)
  17569. if (c.kind == lynx::ClipKind::audio)
  17570. return c.followKey;
  17571. return false;
  17572. }());
  17573. }
  17574. // --- step 6: a one-knob effect --------------------------------------------------------------------------------------
  17575. stepIs (lynx::tour::effect, "simple.dock.addEffect");
  17576. window ("step6-effect", true);
  17577. tour->clickForSnapshot ("do");
  17578. settle();
  17579. check ("Do it for me put Room on the instrument track", lynx::tour::hasOneKnob (offline.getSong()));
  17580. // --- step 7: Finish -----------------------------------------------------------------------------------------------
  17581. stepIs (lynx::tour::finish, "simple.finish");
  17582. window ("step7-finish", true);
  17583. tour->clickForSnapshot ("do");
  17584. settle();
  17585. check ("Do it for me opened Finish and chose Balanced", simple->isFinishShowing() && lynx::looks::present (offline.getSong()));
  17586. // --- the end card, Back / Next, close -------------------------------------------------------------------------------
  17587. settle();
  17588. check ("the end card", tour->isRunning() && tour->step() == lynx::tour::stepCount);
  17589. window ("end", true);
  17590. tour->clickForSnapshot ("back");
  17591. settle();
  17592. check ("Back: the Finish step again, shown done (the tour waits for Next)", tour->step() == lynx::tour::finish
  17593. && tour->machineForCheck().shownDone (offline.getSong()));
  17594. window ("back-done", true);
  17595. tour->clickForSnapshot ("next");
  17596. settle();
  17597. check ("Next: the end card again", tour->step() == lynx::tour::stepCount);
  17598. check ("all seven steps done by the song", tour->machineForCheck().state().completed == 0x7fu);
  17599. tour->clickForSnapshot ("close");
  17600. settle();
  17601. check ("closing the end card ends the tour (not continued from Help)", ! tour->isRunning() && ! tour->canContinue()
  17602. && tour->machineForCheck().state().done);
  17603. line ("-- paused tour");
  17604. // --- a paused tour, the Help menu and the chooser's button ---------------------------------------------------------
  17605. offline.setSong (emptyProject());
  17606. settle();
  17607. tour->machineForCheck() = lynx::tour::Machine {};
  17608. simple->startOrContinueTour();
  17609. settle();
  17610. line ("-- do beat");
  17611. simple->doTourStep (lynx::tour::beat);
  17612. settle();
  17613. check ("a new tour on an empty project: the beat done moves it to the key", tour->step() == lynx::tour::key);
  17614. tour->clickForSnapshot ("close");
  17615. settle();
  17616. check ("closing the card pauses the tour (Help continues it)", ! tour->isRunning() && tour->canContinue());
  17617. line ("-- help menu");
  17618. {
  17619. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  17620. bool continueItem = false, welcomeItem = false;
  17621. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  17622. {
  17623. continueItem = continueItem || it.getItem().text.startsWith (lynx::tr ("Continue the first-song tour (step {0} of {1})", { "2", "7" }));
  17624. welcomeItem = welcomeItem || it.getItem().text == lynx::tr ("Welcome screen...");
  17625. }
  17626. check ("Help: Continue the first-song tour (step 2 of 7) and Welcome screen...", continueItem && welcomeItem);
  17627. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help.png");
  17628. }
  17629. simple->startOrContinueTour();
  17630. settle();
  17631. check ("Help › Continue: back on the key step", tour->isRunning() && tour->step() == lynx::tour::key);
  17632. tour->clickForSnapshot ("skip");
  17633. settle();
  17634. check ("Skip tour ends it", ! tour->isRunning() && ! tour->canContinue());
  17635. offline.setSong (emptyProject());
  17636. settle();
  17637. simple->showChooser();
  17638. window ("chooser");
  17639. line ("-- start from");
  17640. // --- Start from: the three demo songs; a demo opened in Simple -------------------------------------------------------
  17641. if (auto* start = simple->startFromForSnapshot())
  17642. {
  17643. settle();
  17644. writeImage (start->createComponentSnapshot (start->getLocalBounds(), true, 1.0f), "startfrom");
  17645. const auto list = lynx::startfrom::entries();
  17646. int demos = 0;
  17647. for (const auto& e : list)
  17648. demos += e.kind == lynx::startfrom::Entry::Kind::demo && e.playable ? 1 : 0;
  17649. check ("Start from lists three playable demo songs first", demos == 3 && list.size() >= 3 && list[1].demo == 1 && list[2].demo == 2);
  17650. for (int d = 1; d < 3 && d < (int) list.size(); ++d)
  17651. line ("demo " + list[(std::size_t) d].name + ": " + juce::String (list[(std::size_t) d].bpm) + " BPM, " + juce::String (list[(std::size_t) d].bars) + " bars");
  17652. simple->hideStartFrom();
  17653. }
  17654. line ("-- demos");
  17655. for (int d = 1; d < lynx::demos::count; ++d)
  17656. {
  17657. offline.setSong (lynx::demos::make (d));
  17658. settle();
  17659. simple->hideChooser();
  17660. window (juce::String ("demo-") + (d == 1 ? "hiphop" : "pop"));
  17661. // the committed file is the generated song
  17662. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile ("resources/demos").getChildFile (lynx::demos::fileName (d));
  17663. juce::String error;
  17664. const auto loaded = lynx::ProjectFile::load (file, error);
  17665. check ("resources/demos/" + juce::String (lynx::demos::fileName (d)) + " loads and is the generated song",
  17666. loaded.has_value() && lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (lynx::demos::make (d), false));
  17667. }
  17668. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  17669. juce::File (prefix + "-report.txt").replaceWithText (report);
  17670. }
  17671. // --patterns190ea (round 190ea): FL keeps at least one pattern; the engine now does too (AudioEngine::publishSong,
  17672. // Song::keepOnePattern). Before, a Song without a pattern crashed the docked Piano roll's listener.
  17673. bool runPatterns190ea (const juce::String& reportPath)
  17674. {
  17675. namespace st = lynx::simpletracks;
  17676. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17677. lynx::AudioEngine offline (false);
  17678. lynx::MainComponent ui (offline, false);
  17679. ui.setSize (1600, 900);
  17680. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  17681. juce::String report;
  17682. bool ok = true;
  17683. const auto check = [&report, &ok] (const juce::String& what, bool good) {
  17684. report << (good ? "OK " : "ERROR ") << what << "\n";
  17685. ok = ok && good;
  17686. };
  17687. const auto save = [&report, &reportPath] { juce::File (reportPath).replaceWithText (report); };
  17688. const auto settle = [&] { offline.dispatchPendingMessages(); ui.getPianoRollForSnapshot().repaint(); };
  17689. const auto onePattern = [&offline] {
  17690. const auto& s = offline.getSong();
  17691. return s.patterns.size() >= 1 && s.currentPattern >= 0 && s.currentPattern < (int) s.patterns.size();
  17692. };
  17693. // the hand-built songs the engine can be given: none of them has a pattern
  17694. const auto bare = [] {
  17695. lynx::Song s;
  17696. s.mixer = lynx::Song::defaultMixer();
  17697. return s;
  17698. };
  17699. // every way to reach "no pattern" in the current layout
  17700. const auto paths = [&] (const juce::String& where) {
  17701. offline.setSong (bare());
  17702. settle();
  17703. check (where + ": a song without a pattern opens with one empty \"Pattern 1\"",
  17704. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].name == "Pattern 1"
  17705. && offline.getSong().patterns[0].notes.empty());
  17706. offline.editSong ([] (lynx::Song& s) { s.patterns.clear(); });
  17707. settle();
  17708. check (where + ": an edit that clears every pattern leaves one", onePattern());
  17709. offline.editSong ([] (lynx::Song& s) {
  17710. s.patterns.resize (2);
  17711. s.patterns[1].notes.push_back ({});
  17712. s.currentPattern = 1;
  17713. });
  17714. settle();
  17715. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  17716. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  17717. settle();
  17718. check (where + ": deleting the last pattern leaves an empty \"Pattern 1\" (FL's invariant)",
  17719. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].notes.empty());
  17720. for (int k = 0; k < 6; ++k)
  17721. {
  17722. offline.undo();
  17723. settle();
  17724. }
  17725. check (where + ": undo back over those steps keeps a pattern", onePattern());
  17726. for (int k = 0; k < 6; ++k)
  17727. {
  17728. offline.redo();
  17729. settle();
  17730. }
  17731. check (where + ": redo keeps a pattern", onePattern());
  17732. offline.applyRemote (bare());
  17733. settle();
  17734. check (where + ": a live session's remote song without a pattern gets one", onePattern());
  17735. offline.editSong ([] (lynx::Song& s) { s.currentPattern = 99; });
  17736. settle();
  17737. check (where + ": a current pattern out of range is put back in range", onePattern() && offline.getSong().currentPattern == 0);
  17738. };
  17739. // the Simple layout with the Piano roll docked in the Editor tab (round 190dv's crash)
  17740. ui.selectTabForSnapshot (2);
  17741. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17742. settle();
  17743. auto* simple = ui.getSimpleWorkflowForSnapshot();
  17744. check ("the Simple workflow is up", simple != nullptr);
  17745. if (simple == nullptr)
  17746. {
  17747. save();
  17748. return false;
  17749. }
  17750. simple->hideChooser();
  17751. st::Request q;
  17752. q.kind = st::Kind::instrument;
  17753. q.name = "Keys";
  17754. lynx::ChannelDef synth;
  17755. synth.instrument = lynx::InstrumentKind::synth;
  17756. q.channel = synth;
  17757. q.emptyBars = 4;
  17758. st::Result r;
  17759. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  17760. settle();
  17761. ui.getPlaylistForSnapshot().selectTrack (r.track);
  17762. simple->trackSelected (r.track);
  17763. settle();
  17764. auto* dock = simple->dockForSnapshot();
  17765. check ("the instrument track's dock has the Editor tab", dock != nullptr && dock->hasPlayTabsForCheck());
  17766. if (dock != nullptr)
  17767. dock->setTab (lynx::SimpleDock::Tab::editor);
  17768. settle();
  17769. check ("the Piano roll is docked in the Editor tab", dock != nullptr && dock->isEditorDocked() && dock->isParentOf (&ui.getPianoRollForSnapshot()));
  17770. paths ("Simple, Editor tab");
  17771. // the Pattern layout with the Piano roll panel, then the Clip-launch layout
  17772. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  17773. settle();
  17774. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::pianoRoll });
  17775. settle();
  17776. paths ("Pattern layout, Piano roll");
  17777. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  17778. settle();
  17779. paths ("Clip-launch layout");
  17780. report << (ok ? "RESULT OK\n" : "RESULT FAILED\n");
  17781. save();
  17782. return ok;
  17783. }
  17784. void runSimple190dsShot (const juce::String& prefix)
  17785. {
  17786. namespace st = lynx::simpletracks;
  17787. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17788. lynx::AudioEngine offline (false);
  17789. lynx::MainComponent ui (offline, false);
  17790. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  17791. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  17792. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  17793. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  17794. const auto file = juce::File (prefix + "-" + name + ".png");
  17795. file.deleteFile();
  17796. juce::FileOutputStream out (file);
  17797. juce::PNGImageFormat().writeImageToStream (image, out);
  17798. };
  17799. juce::String report;
  17800. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  17801. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  17802. ui.selectTabForSnapshot (2);
  17803. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  17804. offline.dispatchPendingMessages();
  17805. auto* simple = ui.getSimpleWorkflowForSnapshot();
  17806. if (simple == nullptr)
  17807. {
  17808. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  17809. return;
  17810. }
  17811. simple->hideChooser();
  17812. auto& playlist = ui.getPlaylistForSnapshot();
  17813. // --- three loops: two with their key in the name, one only in its sound ---------------------------------------
  17814. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190ds-loops");
  17815. dir.deleteRecursively();
  17816. dir.createDirectory();
  17817. // a chord loop (two bars at 120 BPM, 48 kHz): each chord's notes with six harmonics, a soft attack per beat
  17818. const auto writeLoop = [&dir] (const juce::String& name, std::vector<std::vector<int>> chords) {
  17819. const int frames = 192000;
  17820. juce::AudioBuffer<float> audio (1, frames);
  17821. audio.clear();
  17822. for (int i = 0; i < frames; ++i)
  17823. {
  17824. const auto& chord = chords[(std::size_t) (i / (frames / (int) chords.size()))];
  17825. const auto t = (double) i / 48000.0;
  17826. const auto beat = std::fmod (t, 0.5);
  17827. double v = 0.0;
  17828. for (const auto key : chord)
  17829. {
  17830. const auto f = 440.0 * std::pow (2.0, (key - 69) / 12.0);
  17831. for (int h = 1; h <= 6; ++h)
  17832. v += std::sin (2.0 * juce::MathConstants<double>::pi * f * h * t) / (h * h);
  17833. }
  17834. audio.setSample (0, i, (float) (0.08 * v * (1.0 - std::exp (-beat * 60.0)) * (0.6 + 0.4 * std::exp (-beat * 3.0))));
  17835. }
  17836. const auto wav = dir.getChildFile (name);
  17837. juce::WavAudioFormat format;
  17838. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  17839. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  17840. {
  17841. out.release();
  17842. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  17843. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  17844. }
  17845. return wav.getFullPathName();
  17846. };
  17847. const auto gMinor = writeLoop ("Night Pad 120 Gm.wav", { { 55, 58, 62 }, { 51, 55, 58 }, { 53, 57, 60 }, { 55, 58, 62 } });
  17848. const auto dMinor = writeLoop ("Pluck_120_D_minor.wav", { { 50, 53, 57 }, { 46, 50, 53 }, { 48, 52, 55 }, { 50, 53, 57 } });
  17849. const auto eMinor = writeLoop ("Warm Keys Loop 120 bpm.wav", { { 52, 55, 59, 64 }, { 48, 52, 55, 60 }, { 50, 54, 57, 62 }, { 52, 55, 59, 64 } });
  17850. lynx::SimpleWorkflow::answerForSnapshot = 1; // "Set the project key to G minor?" — yes
  17851. simple->dropFiles ({ gMinor, dMinor, eMinor }, 0);
  17852. lynx::SimpleWorkflow::answerForSnapshot = -1;
  17853. offline.dispatchPendingMessages();
  17854. simple->hideChooser();
  17855. line ("question: " + simple->lastKeyQuestionForCheck());
  17856. check ("the first keyed loop offered its key (G minor)", simple->lastKeyQuestionForCheck().contains ("G minor"));
  17857. {
  17858. const auto& song = offline.getSong();
  17859. const auto key = lynx::projectkey::get (song);
  17860. check ("the project key is G minor", key && key->root == 7 && lynx::projectkey::isMinor (*key));
  17861. std::vector<int> clips;
  17862. for (int i = 0; i < (int) song.playlist.size(); ++i)
  17863. if (song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  17864. clips.push_back (i);
  17865. check ("three loop clips", clips.size() == 3);
  17866. const int expect[] { 0, 5, 3 }; // G minor, D minor (F -> Bb: +5), E minor detected (G -> Bb: +3)
  17867. const int roots[] { 7, 2, 4 };
  17868. const int sources[] { 1, 1, 2 };
  17869. for (std::size_t k = 0; k < clips.size() && k < 3; ++k)
  17870. {
  17871. const auto& c = song.playlist[(std::size_t) clips[k]];
  17872. const auto& sampler = song.channels[(std::size_t) c.channel].sampler;
  17873. line ("loop " + juce::String ((int) k + 1) + ": key " + juce::String (sampler.loopKeyRoot) + (sampler.loopKeyMinor ? "m" : "") + " source "
  17874. + juce::String ((int) sampler.loopKeySource) + " follow " + juce::String (c.followKey ? 1 : 0) + " shift " + juce::String ((int) c.keyShift)
  17875. + " pitch " + juce::String (c.pitch));
  17876. check ("loop " + juce::String ((int) k + 1) + " key, source and move", sampler.loopKeyRoot == roots[k] && sampler.loopKeyMinor
  17877. && sampler.loopKeySource == sources[k] && c.followKey
  17878. && c.keyShift == expect[k] && std::abs (c.pitch - (float) expect[k]) < 1.0e-4f);
  17879. }
  17880. }
  17881. // the key changes: every following loop moves with it (one undo step)
  17882. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, lynx::projectkey::Key { 9, lynx::projectkey::commonFirst()[1] }); });
  17883. offline.dispatchPendingMessages();
  17884. {
  17885. const auto& song = offline.getSong();
  17886. std::vector<int> shifts;
  17887. for (const auto& c : song.playlist)
  17888. if (c.kind == lynx::ClipKind::audio)
  17889. shifts.push_back (c.keyShift);
  17890. line ("after A minor: " + juce::String (shifts.size() > 2 ? shifts[0] : 99) + " " + juce::String (shifts.size() > 2 ? shifts[1] : 99) + " "
  17891. + juce::String (shifts.size() > 2 ? shifts[2] : 99));
  17892. check ("A minor: the loops move by +2, -5, +5", shifts == std::vector<int> { 2, -5, 5 });
  17893. }
  17894. // the loop tracks in the dock: the switch and what it does
  17895. int loopTrack = -1;
  17896. for (const auto& c : offline.getSong().playlist)
  17897. if (c.kind == lynx::ClipKind::audio && loopTrack < 0)
  17898. loopTrack = c.track;
  17899. playlist.selectTrack (loopTrack);
  17900. offline.dispatchPendingMessages();
  17901. auto* dock = simple->dockForSnapshot();
  17902. if (dock == nullptr)
  17903. {
  17904. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  17905. return;
  17906. }
  17907. simple->trackSelected (loopTrack);
  17908. offline.dispatchPendingMessages();
  17909. const auto shots = [&] (const juce::String& name) {
  17910. offline.dispatchPendingMessages();
  17911. for (float scale : { 1.0f, 2.0f })
  17912. {
  17913. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  17914. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  17915. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  17916. }
  17917. };
  17918. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  17919. juce::StringArray names { title };
  17920. std::vector<juce::PopupMenu> menus { menu };
  17921. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17922. if (it.getItem().subMenu != nullptr && it.getItem().text.startsWith (subTitle))
  17923. {
  17924. names.add (subTitle);
  17925. menus.push_back (*it.getItem().subMenu);
  17926. }
  17927. saveMenus (names, menus, prefix + "-" + name + ".png");
  17928. };
  17929. check ("the dock shows the follow switch for the loop track", dock->followShownForCheck());
  17930. shots ("follow-on");
  17931. {
  17932. int clip = -1;
  17933. for (int i = 0; i < (int) offline.getSong().playlist.size() && clip < 0; ++i)
  17934. if (offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  17935. clip = i;
  17936. const auto menu = playlist.getClipMenuForSnapshot (clip);
  17937. bool follow = false, keyItem = false;
  17938. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17939. {
  17940. follow = follow || (it.getItem().text.startsWith (lynx::tr ("Follow the project key")) && it.getItem().isTicked);
  17941. keyItem = keyItem || it.getItem().text.startsWith (lynx::tr ("Loop key"));
  17942. }
  17943. check ("the clip menu has Follow the project key (ticked) and Loop key", follow && keyItem);
  17944. menuShot (menu, lynx::tr ("Audio clip"), lynx::tr ("Loop key"), "menu-clip-key");
  17945. }
  17946. dock->clickFollowForCheck(); // off: back to its own key
  17947. offline.dispatchPendingMessages();
  17948. {
  17949. float pitch = 99.0f;
  17950. bool following = true;
  17951. for (const auto& c : offline.getSong().playlist)
  17952. if (c.kind == lynx::ClipKind::audio && c.track == loopTrack)
  17953. pitch = c.pitch, following = c.followKey;
  17954. check ("switched off: the loop plays in its own key (pitch 0)", ! following && std::abs (pitch) < 1.0e-6f);
  17955. }
  17956. shots ("follow-off");
  17957. dock->clickFollowForCheck();
  17958. offline.dispatchPendingMessages();
  17959. // --- an instrument track from the tile: a pattern to write into, the Editor tab ------------------------------
  17960. {
  17961. st::Request q;
  17962. q.kind = st::Kind::instrument;
  17963. q.name = "Keys";
  17964. lynx::ChannelDef synth;
  17965. synth.instrument = lynx::InstrumentKind::synth;
  17966. q.channel = synth;
  17967. q.emptyBars = 4;
  17968. st::Result r;
  17969. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  17970. offline.dispatchPendingMessages();
  17971. check ("the new Instrument track has an empty 4-bar pattern on it", r.ok() && r.pattern >= 0
  17972. && st::patternOf (offline.getSong(), r.track) == r.pattern
  17973. && offline.getSong().patterns[(std::size_t) r.pattern].notes.empty());
  17974. // a few notes, as the first clicks would write them (A minor: A C E, then G B D)
  17975. offline.editSong ([r] (lynx::Song& s) {
  17976. auto& p = s.patterns[(std::size_t) r.pattern];
  17977. const int keys[] { 57, 60, 64, 67, 71, 74, 69, 72 };
  17978. for (int i = 0; i < 8; ++i)
  17979. {
  17980. lynx::Note n;
  17981. n.channel = r.channels.front();
  17982. n.key = keys[i];
  17983. n.start = (std::int64_t) (i / 3) * lynx::ppq * 2 + (i % 3 == 0 ? 0 : 0);
  17984. n.length = lynx::ppq * 2;
  17985. n.velocity = 0.8f;
  17986. p.notes.push_back (n);
  17987. }
  17988. p.sortNotes();
  17989. });
  17990. offline.dispatchPendingMessages();
  17991. playlist.selectTrack (r.track);
  17992. simple->trackSelected (r.track);
  17993. offline.dispatchPendingMessages();
  17994. check ("the instrument track has the Keyboard and Editor tabs", dock->hasPlayTabsForCheck());
  17995. dock->setTab (lynx::SimpleDock::Tab::editor);
  17996. offline.dispatchPendingMessages();
  17997. check ("the Piano roll is docked in the Editor tab", dock->isEditorDocked());
  17998. check ("on the track's pattern", offline.getSong().currentPattern == r.pattern);
  17999. ui.getPianoRollForSnapshot().scrollToNotes(); // (done asynchronously when it docks)
  18000. shots ("editor");
  18001. dock->clickFoldForCheck (true); // "Only notes in key"
  18002. check ("Only notes in key folds the rows to A minor", ui.getPianoRollForSnapshot().isFoldedToScale());
  18003. ui.getPianoRollForSnapshot().scrollToNotes();
  18004. shots ("editor-in-key");
  18005. dock->clickFoldForCheck (false);
  18006. // --- the keyboard's modes ------------------------------------------------------------------------------
  18007. auto& keyboard = lynx::scalekeys::current();
  18008. const auto saved = keyboard;
  18009. keyboard = {};
  18010. keyboard.lockToKey = true;
  18011. dock->setTab (lynx::SimpleDock::Tab::keyboard);
  18012. if (auto* panel = dock->keyboardPanelForSnapshot())
  18013. {
  18014. lynx::refreshKeyboardPanel (*panel);
  18015. shots ("keys-locked");
  18016. keyboard.lockToKey = false;
  18017. keyboard.mode = lynx::scalekeys::Mode::scaleKeys;
  18018. lynx::refreshKeyboardPanel (*panel);
  18019. shots ("scale-keys");
  18020. keyboard.mode = lynx::scalekeys::Mode::chordPad;
  18021. keyboard.complexity = lynx::scalekeys::Complexity::seventh;
  18022. keyboard.strumMs = 40;
  18023. lynx::refreshKeyboardPanel (*panel);
  18024. shots ("chord-pad");
  18025. }
  18026. check ("the Keyboard tab shows the keyboard panel", dock->keyboardPanelForSnapshot() != nullptr);
  18027. // the same panel as the Touch keyboard window, each mode with a key / pad held
  18028. for (const auto& [mode, name, pressed] : { std::tuple { lynx::scalekeys::Mode::scaleKeys, juce::String ("window-scale-keys"), 4 },
  18029. std::tuple { lynx::scalekeys::Mode::chordPad, juce::String ("window-chord-pad"), 3 } })
  18030. {
  18031. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, mode, pressed, [ch = r.channels.front()] { return ch; });
  18032. panel->setSize (1100, 260);
  18033. for (float scale : { 1.0f, 2.0f })
  18034. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  18035. if (mode == lynx::scalekeys::Mode::chordPad)
  18036. menuShot (lynx::chordPadMenuForSnapshot (*panel, 3), lynx::tr ("Edit chord"), lynx::tr ("Chord type"), "menu-chord-edit");
  18037. }
  18038. // the Chord pad on an FL Studio Mobile chord set (the default set's shape: C Dm Em F G Am B° C)
  18039. {
  18040. const auto set = lynx::scalekeys::parseFlmChordSet (R"({"chords":[{"baseNote":0,"extensions":[],"octave":3,"quality":0},{"baseNote":2,"extensions":[],"octave":3,"quality":1},{"baseNote":4,"extensions":[],"octave":3,"quality":1},{"baseNote":5,"extensions":[],"octave":3,"quality":0},{"baseNote":7,"extensions":[],"octave":3,"quality":0},{"baseNote":9,"extensions":[],"octave":3,"quality":1},{"baseNote":11,"extensions":[],"octave":3,"quality":3},{"baseNote":0,"extensions":[],"octave":4,"quality":0}],"rootNote":0})");
  18041. check ("an FLM chord set reads as 8 chords (B diminished)", set.size() == 8 && set[6].quality == 3);
  18042. offline.editSong ([set] (lynx::Song& s) { s.keyboardChords = set; });
  18043. keyboard.projectChords = true;
  18044. keyboard.complexity = lynx::scalekeys::Complexity::triad;
  18045. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, lynx::scalekeys::Mode::chordPad, 5, [ch = r.channels.front()] { return ch; });
  18046. panel->setSize (1100, 260);
  18047. for (float scale : { 1.0f, 2.0f })
  18048. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), juce::String ("window-chord-set") + (scale > 1.0f ? "@2x" : ""));
  18049. }
  18050. // the typing keys in each mode (A minor; Z = the root)
  18051. {
  18052. const auto& song = offline.getSong();
  18053. lynx::scalekeys::Settings s;
  18054. s.mode = lynx::scalekeys::Mode::scaleKeys;
  18055. juce::String z;
  18056. for (const int typed : { 60, 62, 64, 65, 67, 69, 71, 72, 61 })
  18057. {
  18058. const auto n = lynx::scalekeys::typedNotes (song, s, typed, 60);
  18059. z << (n.empty() ? juce::String ("-") : juce::String (n.front())) << " ";
  18060. }
  18061. line ("Scale keys, typing C D E F G A B C C#: " + z);
  18062. check ("Scale keys: the white typing keys play A minor from A", z.trim() == "69 71 72 74 76 77 79 81 -");
  18063. s.mode = lynx::scalekeys::Mode::chordPad;
  18064. s.projectChords = false;
  18065. const auto pad = lynx::scalekeys::typedNotes (song, s, 60, 60);
  18066. check ("Chord pad: Z plays A minor (A C E)", pad == std::vector<int> { 69, 72, 76 });
  18067. }
  18068. keyboard = saved;
  18069. }
  18070. // --- the project round trip --------------------------------------------------------------------------------
  18071. {
  18072. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  18073. juce::String error;
  18074. const auto back = lynx::ProjectFile::fromJson (json, error);
  18075. bool same = back.has_value() && back->keyboardChords == offline.getSong().keyboardChords && back->playlist.size() == offline.getSong().playlist.size();
  18076. for (std::size_t i = 0; same && i < back->playlist.size(); ++i)
  18077. same = back->playlist[i].followKey == offline.getSong().playlist[i].followKey && back->playlist[i].keyShift == offline.getSong().playlist[i].keyShift
  18078. && back->playlist[i].pitch == offline.getSong().playlist[i].pitch;
  18079. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  18080. same = back->channels[c].sampler.loopKeyRoot == offline.getSong().channels[c].sampler.loopKeyRoot
  18081. && back->channels[c].sampler.loopKeySource == offline.getSong().channels[c].sampler.loopKeySource;
  18082. check ("follow, key moves, loop keys and the chord set survive .lynx", same);
  18083. }
  18084. dir.deleteRecursively();
  18085. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  18086. juce::File (prefix + "-report.txt").replaceWithText (report);
  18087. }
  18088. void runSimple190dgShot (const juce::String& prefix)
  18089. {
  18090. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18091. lynx::AudioEngine offline (false);
  18092. lynx::MainComponent ui (offline, false);
  18093. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  18094. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  18095. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  18096. const auto file = juce::File (prefix + "-" + name + ".png");
  18097. file.deleteFile();
  18098. juce::FileOutputStream out (file);
  18099. juce::PNGImageFormat().writeImageToStream (image, out);
  18100. };
  18101. juce::String report;
  18102. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  18103. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  18104. ui.selectTabForSnapshot (2);
  18105. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  18106. offline.dispatchPendingMessages();
  18107. auto* simple = ui.getSimpleWorkflowForSnapshot();
  18108. if (simple == nullptr)
  18109. {
  18110. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  18111. return;
  18112. }
  18113. simple->hideChooser();
  18114. offline.editSong ([] (lynx::Song& s) {
  18115. namespace st = lynx::simpletracks;
  18116. st::Request q;
  18117. q.kind = st::Kind::voice;
  18118. q.name = "Lead vocal";
  18119. st::addTrack (s, q);
  18120. q = {};
  18121. q.kind = st::Kind::instrument;
  18122. q.name = "Keys";
  18123. lynx::ChannelDef keys;
  18124. keys.instrument = lynx::InstrumentKind::synth;
  18125. q.channel = keys;
  18126. st::addTrack (s, q);
  18127. });
  18128. offline.dispatchPendingMessages();
  18129. simple->hideChooser();
  18130. auto& playlist = ui.getPlaylistForSnapshot();
  18131. int voiceTrack = -1, keysTrack = -1;
  18132. {
  18133. const auto& song = offline.getSong();
  18134. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  18135. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  18136. {
  18137. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  18138. voiceTrack = t;
  18139. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  18140. keysTrack = t;
  18141. }
  18142. }
  18143. check ("two Simple tracks (voice, keys)", voiceTrack >= 0 && keysTrack >= 0);
  18144. playlist.selectTrack (voiceTrack);
  18145. offline.dispatchPendingMessages();
  18146. auto* dock = simple->dockForSnapshot();
  18147. if (dock == nullptr)
  18148. {
  18149. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  18150. return;
  18151. }
  18152. const auto shots = [&] (const juce::String& name) {
  18153. offline.dispatchPendingMessages();
  18154. for (float scale : { 1.0f, 2.0f })
  18155. {
  18156. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  18157. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  18158. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  18159. }
  18160. };
  18161. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  18162. juce::StringArray names { title };
  18163. std::vector<juce::PopupMenu> menus { menu };
  18164. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  18165. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  18166. {
  18167. names.add (subTitle);
  18168. menus.push_back (*it.getItem().subMenu);
  18169. }
  18170. saveMenus (names, menus, prefix + "-" + name + ".png");
  18171. };
  18172. const auto insert = dock->insertForCheck();
  18173. // --- every one-knob effect as a card, each at a knob position of its own -------------------------------------
  18174. const float at[] { 0.0f, 0.55f, 0.40f, 0.70f, 0.30f, 0.60f, 0.45f, 0.35f, 0.80f };
  18175. for (int id = 1; id <= lynx::goals::count; ++id)
  18176. dock->addOneKnobForCheck (id);
  18177. offline.dispatchPendingMessages();
  18178. for (int id = 1; id <= lynx::goals::count; ++id)
  18179. dock->turnKnobForCheck (id - 1, at[id]);
  18180. offline.dispatchPendingMessages();
  18181. check ("eight one-knob cards on the insert", dock->cardCountForCheck() == 8 && dock->oneKnobCardsForCheck() == 8);
  18182. {
  18183. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  18184. bool turned = fx.size() == 8;
  18185. for (std::size_t i = 0; turned && i < fx.size(); ++i)
  18186. turned = lynx::goals::active (fx[i]) && std::abs (fx[i].goalAmount - at[i + 1]) < 1.0e-6f;
  18187. check ("each knob wrote its effect's parameters", turned);
  18188. }
  18189. shots ("effects-all");
  18190. offline.dispatchPendingMessages();
  18191. for (int card = 0; card < dock->cardCountForCheck(); ++card)
  18192. {
  18193. const auto area = dock->cardBoundsForSnapshot (card);
  18194. const auto name = juce::String (lynx::goals::name (card + 1)).toLowerCase();
  18195. check ("card " + juce::String (card + 1) + " (" + name + ") is on screen", ! area.isEmpty() && dock->getLocalBounds().contains (area));
  18196. for (float scale : { 1.0f, 2.0f })
  18197. writeImage (dock->createComponentSnapshot (area.expanded (4), true, scale), "card-" + name + (scale > 1.0f ? "@2x" : ""));
  18198. }
  18199. // --- a chain preset with Blend --------------------------------------------------------------------------------
  18200. if (const auto* preset = lynx::chains::find ("Canyon"))
  18201. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  18202. offline.dispatchPendingMessages();
  18203. dock->setBlendForCheck (0.6f);
  18204. offline.dispatchPendingMessages();
  18205. check ("preset Canyon with Blend 60 % (shown as edited)", offline.getSong().mixer[(std::size_t) insert].chainPreset == "Canyon"
  18206. && std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.6f) < 1.0e-6f
  18207. && ! lynx::chains::unchanged (offline.getSong(), insert));
  18208. shots ("effects-preset-blend");
  18209. // favourites: the track's preset starred; the menu lists it first
  18210. const auto favFile = lynx::SimpleDock::favouritesFile();
  18211. const auto hadFavourites = favFile.existsAsFile();
  18212. const auto oldFavourites = favFile.loadFileAsString();
  18213. lynx::SimpleDock::setFavouritePreset ("Canyon", true);
  18214. lynx::SimpleDock::setFavouritePreset ("Clear Voice", true);
  18215. lynx::SimpleDock::setFavouritePreset ("Canyon", true); // (twice: once in the list)
  18216. check ("two favourites kept, in order", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Canyon", "Clear Voice" });
  18217. {
  18218. bool first = false, toggle = false;
  18219. const auto menu = dock->presetMenuForSnapshot();
  18220. juce::PopupMenu::MenuItemIterator it (menu);
  18221. if (it.next())
  18222. first = it.getItem().subMenu != nullptr && it.getItem().text.contains (lynx::tr ("Favourites"));
  18223. for (juce::PopupMenu::MenuItemIterator all (menu); all.next();)
  18224. toggle = toggle || all.getItem().text == lynx::tr ("Remove \"{0}\" from favourites", { "Canyon" });
  18225. check ("the Preset menu starts with the favourites and offers to unstar the track's preset", first && toggle);
  18226. menuShot (menu, lynx::tr ("Preset"), juce::String::fromUTF8 ("\xe2\x98\x85 ") + lynx::tr ("Favourites"), "menu-preset-favourites");
  18227. }
  18228. lynx::SimpleDock::setFavouritePreset ("Canyon", false);
  18229. check ("unstarred", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Clear Voice" });
  18230. if (hadFavourites)
  18231. favFile.replaceWithText (oldFavourites);
  18232. else
  18233. favFile.deleteFile();
  18234. // --- the sound picker: a search, and the installed plugins -----------------------------------------------------
  18235. playlist.selectTrack (keysTrack);
  18236. offline.dispatchPendingMessages();
  18237. check ("the Keys track opens on its sound", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  18238. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::bass);
  18239. dock->setSearchForSnapshot ("sub");
  18240. offline.dispatchPendingMessages();
  18241. line ("search \"sub\" in Bass: " + juce::String (dock->soundRowsForCheck()) + " rows");
  18242. check ("a search narrows the category", dock->soundRowsForCheck() > 0 && dock->soundRowsForCheck() < (int) lynx::soundlib::filter (lynx::soundlib::builtIn(), lynx::soundlib::Category::bass).size());
  18243. shots ("picker-search");
  18244. dock->setSearchForSnapshot ({});
  18245. // a made-up list of installed plugins (nothing is scanned or loaded)
  18246. dock->setPluginsForSnapshot ({ { "VST3-demo-1", "Analog Mono", "Example Audio", "VST3", "Instrument|Synth" },
  18247. { "VST3-demo-2", "Grand Upright", "Example Audio", "VST3", "Instrument|Piano" },
  18248. { "VST3-demo-3", "Beat Kit 808", "Sample Lab", "VST3", "Instrument|Drum" },
  18249. { "CLAP-demo-4", "Orchestra Strings", "Sample Lab", "CLAP", "Instrument|Sampler" },
  18250. { "VST3-demo-5", "Wave Table One", "Example Audio", "VST3", "Instrument|Synth" },
  18251. { "VST-demo-6", "Sub Bass Machine", "Low End", "VST", "Synth" },
  18252. { "VST3-demo-7", "Sample Player", "Sample Lab", "VST3", "Instrument|Sampler" } });
  18253. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::synths);
  18254. offline.dispatchPendingMessages();
  18255. check ("My plugins: the generic synths and samplers in their own category (" + juce::String (dock->soundRowsForCheck()) + " of 7)", dock->soundRowsForCheck() == 3);
  18256. shots ("picker-plugins");
  18257. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  18258. juce::File (prefix + "-report.txt").replaceWithText (report);
  18259. }
  18260. void runSimpleShot (const juce::String& prefix)
  18261. {
  18262. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18263. lynx::AudioEngine offline (false);
  18264. lynx::MainComponent ui (offline, false);
  18265. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  18266. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  18267. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  18268. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  18269. file.deleteFile();
  18270. juce::FileOutputStream out (file);
  18271. juce::PNGImageFormat().writeImageToStream (image, out);
  18272. };
  18273. const auto write = [&ui, &writeImage] (const char* name) { writeImage (lynx::shot::snapshot (ui), name); };
  18274. // View › Layout style, with its submenu, as it is with `style` chosen
  18275. const auto viewMenu = [&ui] {
  18276. const auto names = ui.getMenuNamesForSnapshot();
  18277. const auto view = names.indexOf (lynx::tr ("View"));
  18278. return ui.getMenuForSnapshot (juce::jmax (0, view));
  18279. };
  18280. const auto saveStyleMenus = [&] (const juce::String& suffix) {
  18281. const auto view = viewMenu();
  18282. juce::StringArray names { lynx::tr ("View") };
  18283. std::vector<juce::PopupMenu> menus { view };
  18284. for (juce::PopupMenu::MenuItemIterator it (view); it.next();)
  18285. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Layout style"))
  18286. {
  18287. names.add (lynx::tr ("Layout style"));
  18288. menus.push_back (*it.getItem().subMenu);
  18289. }
  18290. saveMenus (names, menus, prefix + "-menu-" + suffix + ".png");
  18291. };
  18292. // Settings › General with `style` selected, and its style list
  18293. const auto saveSettings = [&] (lynx::layoutstyle::Style style, const char* name) {
  18294. lynx::SettingsHooks hooks;
  18295. hooks.getGeneral = [style] {
  18296. lynx::GeneralOptions o;
  18297. o.language = lynx::i18n::current();
  18298. o.layoutStyle = (int) style;
  18299. return o;
  18300. };
  18301. auto page = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general, false, hooks);
  18302. const auto image = lynx::shot::paint (*page, lynx::theme::panel, -1, juce::jmin (page->getHeight(), 420));
  18303. writeImage (image, name);
  18304. std::function<juce::ComboBox* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ComboBox* {
  18305. if (c.getComponentID() == "layoutStyle")
  18306. return dynamic_cast<juce::ComboBox*> (&c);
  18307. for (auto* child : c.getChildren())
  18308. if (auto* box = find (*child))
  18309. return box;
  18310. return nullptr;
  18311. };
  18312. if (auto* box = find (*page); box != nullptr && box->getRootMenu() != nullptr)
  18313. saveMenus (juce::StringArray { lynx::tr ("Layout style") }, std::vector<juce::PopupMenu> { *box->getRootMenu() },
  18314. prefix + "-" + name + "-list.png");
  18315. };
  18316. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  18317. ui.selectTabForSnapshot (2); // the Playlist panel, maximized (as --gridshot)
  18318. write ("pattern");
  18319. saveStyleMenus ("pattern");
  18320. saveSettings (lynx::layoutstyle::Style::pattern, "settings-pattern");
  18321. const auto madePattern = lynx::SimpleWorkflow::instances.load();
  18322. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  18323. saveStyleMenus ("cliplaunch");
  18324. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  18325. offline.dispatchPendingMessages();
  18326. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  18327. simple->showChooser(); // (an empty project opens on it by itself; the offline project may hold the default song)
  18328. write ("simple"); // the New track chooser (slice S3)
  18329. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  18330. {
  18331. simple->showStarterPageForSnapshot();
  18332. write ("simple-starter");
  18333. simple->hideChooser();
  18334. write ("simple-closed");
  18335. // round 190p: a loop keeps time. Two files with the same 4.8 s of audio dropped on the empty Simple timeline:
  18336. // "Guitar loop 100.wav" (2 bars at 100 BPM) lasts 2 bars at the project's tempo, "Guitar take.wav" plays at
  18337. // its own speed. Both are undone again, so the shots after this one are as they were.
  18338. {
  18339. const auto folder = juce::File (prefix + "-loops");
  18340. folder.createDirectory();
  18341. juce::StringArray files;
  18342. for (const auto* name : { "Guitar loop 100.wav", "Guitar take.wav" })
  18343. {
  18344. const auto file = folder.getChildFile (name);
  18345. file.deleteFile();
  18346. const auto rate = 44100.0;
  18347. const auto frames = (int) (4.8 * rate);
  18348. juce::AudioBuffer<float> audio (1, frames);
  18349. for (int i = 0; i < frames; ++i)
  18350. {
  18351. const auto t = (double) i / rate, inBeat = std::fmod (t, 0.6); // a plucked note on every beat at 100 BPM
  18352. audio.setSample (0, i, (float) (0.7 * std::exp (-inBeat * 7.0) * std::sin (juce::MathConstants<double>::twoPi * 196.0 * t)));
  18353. }
  18354. if (auto out = file.createOutputStream())
  18355. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0)))
  18356. {
  18357. out.release();
  18358. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  18359. }
  18360. files.add (file.getFullPathName());
  18361. }
  18362. simple->dropFiles (files, 0);
  18363. offline.dispatchPendingMessages();
  18364. // the clips' waveforms are analysed in the background and drawn once ready (a live window repaints by
  18365. // itself; one off-screen paint came too early and showed empty clips)
  18366. for (const auto& path : files)
  18367. lynx::ui::WaveformCache::getInstance()->find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  18368. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  18369. offline.dispatchPendingMessages();
  18370. write ("simple-loop");
  18371. const auto& song = offline.getSong();
  18372. juce::String report;
  18373. for (const auto& clip : song.playlist)
  18374. if (clip.kind == lynx::ClipKind::audio)
  18375. report << song.channels[(std::size_t) clip.channel].name << ": " << juce::String ((double) clip.length / lynx::ppq, 3) << " beats, stretch "
  18376. << juce::String (song.channels[(std::size_t) clip.channel].sampler.stretchBeats, 2) << "\n";
  18377. juce::File (prefix + "-loop.txt").replaceWithText ("tempo " + juce::String (song.bpm, 1) + "\n" + report);
  18378. for (int i = 0; i < files.size() && offline.canUndo(); ++i) // (one undo step per dropped file)
  18379. offline.undo();
  18380. offline.dispatchPendingMessages();
  18381. simple->hideChooser();
  18382. }
  18383. // round 190t, slice A: one click on a starter beat adds it, placed for four bars (undone again)
  18384. {
  18385. const auto clipsBefore = offline.getSong().playlist.size();
  18386. const auto tempoBefore = offline.getSong().bpm;
  18387. simple->clickStarterForSnapshot (1);
  18388. offline.dispatchPendingMessages();
  18389. write ("simple-starter-added");
  18390. const auto& song = offline.getSong();
  18391. juce::String report ("tempo " + juce::String (tempoBefore, 1) + " -> " + juce::String (song.bpm, 1) + "\n");
  18392. for (auto i = clipsBefore; i < song.playlist.size(); ++i)
  18393. report << "clip at beat " << juce::String ((double) song.playlist[i].start / lynx::ppq, 2) << ", " << juce::String ((double) song.playlist[i].length / lynx::ppq, 2)
  18394. << " beats, pattern " << song.playlist[i].pattern << ", track " << song.playlist[i].track << "\n";
  18395. juce::File (prefix + "-starter.txt").replaceWithText (report);
  18396. if (song.playlist.size() > clipsBefore && offline.canUndo())
  18397. offline.undo();
  18398. offline.dispatchPendingMessages();
  18399. simple->hideChooser();
  18400. }
  18401. // slice S4: the Simple headers with a few tracks (voice, instrument, drums, an audio file), some levels moved
  18402. offline.editSong ([] (lynx::Song& s) {
  18403. namespace st = lynx::simpletracks;
  18404. st::Request q;
  18405. q.kind = st::Kind::voice;
  18406. q.name = "Lead vocal";
  18407. st::addTrack (s, q);
  18408. q = {};
  18409. q.kind = st::Kind::instrument;
  18410. q.name = "Keys";
  18411. lynx::ChannelDef keys;
  18412. keys.instrument = lynx::InstrumentKind::synth;
  18413. q.channel = keys;
  18414. lynx::Pattern chords;
  18415. for (int i = 0; i < 4; ++i)
  18416. for (int k : { 60, 64, 67 })
  18417. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  18418. q.pattern = chords;
  18419. const auto r = st::addTrack (s, q);
  18420. q = {};
  18421. q.kind = st::Kind::drums;
  18422. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  18423. {
  18424. lynx::ChannelDef c;
  18425. c.instrument = kind;
  18426. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  18427. q.kit.push_back (c);
  18428. }
  18429. lynx::Pattern beat;
  18430. const auto hit = [&beat] (int step, int row) { beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, row, 60 }); };
  18431. for (int step = 0; step < 16; step += 2)
  18432. hit (step, 2); // hats on the 8ths, kick on 1 and 3, snare on 2 and 4
  18433. for (int step : { 0, 8 })
  18434. hit (step, 0);
  18435. for (int step : { 4, 12 })
  18436. hit (step, 1);
  18437. q.pattern = beat;
  18438. q.bpm = 96.0;
  18439. st::addTrack (s, q);
  18440. if (r.insert > 0)
  18441. {
  18442. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  18443. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  18444. s.mixer[(std::size_t) r.insert].solo = true;
  18445. }
  18446. });
  18447. offline.dispatchPendingMessages();
  18448. ui.getPlaylistForSnapshot().selectTrack (1);
  18449. write ("simple-tracks");
  18450. // round 190t, slice E: the backup status beside the title tools, in each of its states
  18451. {
  18452. const auto now = juce::Time::currentTimeMillis();
  18453. juce::String states;
  18454. int n = 0;
  18455. for (const auto& text : { lynx::MainComponent::simpleSaveStatusText (true, false, 0, now), lynx::MainComponent::simpleSaveStatusText (true, false, now - 5000, now),
  18456. lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now), lynx::MainComponent::simpleSaveStatusText (false, true, 0, now),
  18457. lynx::MainComponent::simpleSaveStatusText (false, false, 0, now) })
  18458. {
  18459. simple->setStatusForSnapshot (text);
  18460. offline.dispatchPendingMessages();
  18461. states << n << ": " << text << "\n";
  18462. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withTop (juce::jmin (ui.getHeight() - 1, 70)).withHeight (juce::jmin (ui.getHeight(), 44))),
  18463. ("status-" + juce::String (n++)).toRawUTF8());
  18464. }
  18465. juce::File (prefix + "-status.txt").replaceWithText (states);
  18466. simple->setStatusForSnapshot (lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now));
  18467. offline.dispatchPendingMessages();
  18468. write ("simple-status");
  18469. }
  18470. // slice S8: the Finish dock, empty, then with a look on the Master (Balanced, Normal, a little Tone)
  18471. simple->showFinish();
  18472. offline.dispatchPendingMessages();
  18473. write ("simple-finish-empty");
  18474. offline.editSongStructural ([] (lynx::Song& s) { lynx::looks::apply (s, lynx::MasterLookSettings { lynx::looks::balanced, 0.5f, { 1.5f, 0.0f, 1.0f }, -3.0f }); });
  18475. offline.dispatchPendingMessages();
  18476. simple->showFinish();
  18477. write ("simple-finish");
  18478. simple->hideFinish();
  18479. }
  18480. saveStyleMenus ("simple");
  18481. saveSettings (lynx::layoutstyle::Style::simple, "settings-simple");
  18482. // round 184a S11: the Key panel (no key, then an A minor riff and its guesses) and its menu
  18483. const auto toolbarShot = [&] (const char* name) {
  18484. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 80))), name);
  18485. };
  18486. toolbarShot ("key-none");
  18487. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-empty.png");
  18488. offline.editSong ([] (lynx::Song& s) {
  18489. if (s.channels.empty())
  18490. s.channels.resize (1);
  18491. if (s.patterns.empty())
  18492. s.patterns.emplace_back();
  18493. int t = 0;
  18494. for (int k : { 57, 60, 64, 67, 69, 67, 64, 60, 57, 59, 60, 62, 64, 62, 60, 59, 57, 57, 64, 45 })
  18495. {
  18496. lynx::Note n;
  18497. n.channel = 0;
  18498. n.key = k;
  18499. n.start = t * lynx::ppq / 2;
  18500. n.length = k == 57 || k == 45 ? lynx::ppq : lynx::ppq / 2;
  18501. s.patterns[0].notes.push_back (n);
  18502. ++t;
  18503. }
  18504. });
  18505. offline.dispatchPendingMessages();
  18506. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-guess.png");
  18507. const auto guesses = lynx::keyguess::guess (offline.getSong(), 3);
  18508. if (! guesses.empty())
  18509. offline.editSong ([k = guesses[0].key] (lynx::Song& s) { lynx::projectkey::set (s, k); });
  18510. offline.dispatchPendingMessages();
  18511. toolbarShot ("key-set");
  18512. write ("simple-key");
  18513. juce::String keyCounts;
  18514. for (const auto& g : guesses)
  18515. keyCounts << "guess " << lynx::projectkey::name (g.key) << " " << g.notesInScale << "/" << g.notes << " score " << g.score << "\n";
  18516. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, std::nullopt); });
  18517. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  18518. offline.dispatchPendingMessages();
  18519. toolbarShot ("key-pattern-toolbar");
  18520. write ("pattern-after");
  18521. // round 184a S17: the setup wizard with its Workflow choice — a first start (Pattern selected), then reopened in Simple
  18522. for (int style : { 0, 2 })
  18523. {
  18524. auto wizard = lynx::makeSetupWizardContent (offline, {}, {}, style, {});
  18525. auto image = lynx::shot::paint (*wizard);
  18526. writeImage (image, style == 0 ? "wizard-pattern" : "wizard-simple");
  18527. }
  18528. juce::File (prefix + "-counts.txt").replaceWithText ("simple workflows before " + juce::String (madeBefore) + ", in pattern workflow "
  18529. + juce::String (madePattern) + ", after " + juce::String (lynx::SimpleWorkflow::instances.load())
  18530. + "\nstyle after " + lynx::layoutstyle::id (ui.getLayoutStyle()) + "\n" + keyCounts);
  18531. }
  18532. void runLiveShot190ce (const juce::String& prefix)
  18533. {
  18534. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18535. lynx::AudioEngine offline (false);
  18536. lynx::MainComponent ui (offline, false);
  18537. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  18538. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  18539. const auto write = [&prefix, &ui, &offline] (const char* name) {
  18540. offline.dispatchPendingMessages();
  18541. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  18542. file.deleteFile();
  18543. juce::FileOutputStream out (file);
  18544. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  18545. };
  18546. juce::String checks;
  18547. const auto check = [&checks] (const char* what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  18548. // a small library of its own (empty files: only names are shown)
  18549. const auto lib = juce::File (prefix + "-library");
  18550. lib.deleteRecursively();
  18551. for (const auto* path : { "Drums/Kicks/Kick Hard.wav", "Drums/Kicks/Kick Soft.wav", "Drums/Snare Tight.wav", "Drums/Hat Closed.wav",
  18552. "Loops/Break 120.wav", "Loops/Shaker 98.wav", "Textures/Vinyl Noise.wav", "Textures/Rain.wav" })
  18553. lib.getChildFile (path).create();
  18554. auto& browser = ui.getBrowserForSnapshot();
  18555. auto& store = lynx::BrowserComponent::collectionStore();
  18556. store = {};
  18557. const auto item = [&lib] (const char* path) { return lib.getChildFile (path).getFullPathName().toStdString(); };
  18558. ui.setVisible (true);
  18559. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  18560. ui.setClipLaunchWorkflow (true);
  18561. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  18562. offline.editSong ([] (lynx::Song& s) {
  18563. if (s.channels.size() < 2)
  18564. s.channels.resize (2);
  18565. s.channels[0].name = "Bass synth";
  18566. s.channels[0].mixerTrack = 2;
  18567. s.channels[1].mixerTrack = 3;
  18568. if (s.mixer.size() < 4)
  18569. s.mixer.resize (4);
  18570. s.mixer[2].name = "Bass";
  18571. s.mixer[2].effects.clear();
  18572. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  18573. {
  18574. lynx::EffectSlot fx;
  18575. fx.kind = kind;
  18576. const auto& info = lynx::effectInfo (kind);
  18577. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  18578. fx.params[k] = info.params[k].defaultValue;
  18579. s.mixer[2].effects.push_back (fx);
  18580. }
  18581. s.mixer[2].effects[1].enabled = false; // the compressor: off, at half mix
  18582. s.mixer[2].effects[1].mix = 0.5f;
  18583. while (s.patterns.size() < 2)
  18584. s.patterns.emplace_back();
  18585. s.patterns[0].name = "Bass line";
  18586. lynx::Note note;
  18587. note.channel = 0;
  18588. note.key = 36;
  18589. s.patterns[0].notes = { note };
  18590. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  18591. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  18592. s.playlistTracks[1].name = "Bass";
  18593. lynx::Clip clip;
  18594. clip.pattern = 0;
  18595. clip.length = 4 * lynx::ppq;
  18596. lynx::launcher::setClip (s, 1, 0, clip);
  18597. }, false);
  18598. offline.dispatchPendingMessages();
  18599. auto* detail = ui.getDetailViewForSnapshot();
  18600. if (detail == nullptr)
  18601. {
  18602. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  18603. return;
  18604. }
  18605. detail->showSelection (1, 0);
  18606. detail->setPage (lynx::DetailView::Page::devices);
  18607. detail->selectCardForCheck (2); // the compressor (card 0 is the instrument)
  18608. write ("01-devices"); // the cards' title buttons: hot-swap, save, fold
  18609. saveMenus (juce::StringArray { "Device (effect card)" }, std::vector<juce::PopupMenu> { detail->cardMenuForSnapshot (2) }, prefix + "-02-device-menu.png");
  18610. // hot-swap on for the compressor: the Browser's bar, the Plugin database's effects, the card's button lit
  18611. const auto compressor = lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1);
  18612. browser.beginHotSwap (compressor);
  18613. write ("03-hotswap-effect");
  18614. check ("hot-swap links the compressor", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  18615. // a swap through the Browser itself (the row of LYNX's Reverb, then Enter): the slot keeps its place, its off
  18616. // state and its Mix; the link moves to the new device
  18617. {
  18618. browser.showPluginDatabase ("LYNX SHARE", 0); // (the folder of LYNX's own effects, opened as a click would)
  18619. browser.selectRowForSnapshot (lynx::tr (lynx::effectInfo (lynx::EffectKind::reverb).name));
  18620. write ("03a-hotswap-row"); // the candidate's row selected
  18621. check ("swap: Enter on the Reverb row is taken by hot-swap", browser.hotSwapLoadSelected());
  18622. offline.dispatchPendingMessages();
  18623. const auto& slot = offline.getSong().mixer[2].effects[1];
  18624. // (round 190cy: the device comes in with its own on / off state, on, as in Live 12.4.16; the Mix stays)
  18625. check ("swap: reverb in the compressor's place, on (its own state), at 50 % mix", slot.kind == lynx::EffectKind::reverb && slot.enabled && slot.mix == 0.5f);
  18626. check ("swap: three effects as before", offline.getSong().mixer[2].effects.size() == 3);
  18627. check ("swap: the Browser is linked to the new device", browser.isHotSwapping() && browser.hotSwapTarget() == lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1)
  18628. && ! (browser.hotSwapTarget() == compressor));
  18629. write ("03b-hotswap-swapped");
  18630. offline.undo();
  18631. offline.dispatchPendingMessages();
  18632. const auto& back = offline.getSong().mixer[2].effects[1];
  18633. check ("undo: the compressor is back with its instance", back.kind == lynx::EffectKind::compressor && back.instance.id == compressor.instance);
  18634. check ("undo: the Browser is still linked to it", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  18635. }
  18636. // round 190cy (Live 12.4.16 live check 190cw shot 02a): hot-swap starts on the device's current preset. The
  18637. // compressor got its settings from a saved preset of LYNX's ("Glue bus", in this run's own settings folder)
  18638. {
  18639. browser.endHotSwap();
  18640. const auto folder = lynx::pluginheader::userFolder (lynx::EffectKind::compressor);
  18641. folder.createDirectory();
  18642. const auto& fx = offline.getSong().mixer[2].effects[1];
  18643. for (const auto* name : { "Glue bus", "Gentle", "Parallel smash" })
  18644. folder.getChildFile (juce::String (name) + ".lynxpreset").replaceWithText (lynx::presets::toText (lynx::EffectKind::compressor, name, fx.params));
  18645. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects[1].presetName = "Glue bus"; }, false);
  18646. offline.dispatchPendingMessages();
  18647. browser.beginHotSwap (compressor);
  18648. write ("03c-hotswap-current-preset");
  18649. check ("hot-swap starts on the current preset", browser.getSelectedFile() == folder.getChildFile ("Glue bus.lynxpreset"));
  18650. // a preset of the same effect swapped in comes in on (the compressor was off)
  18651. browser.selectRowForSnapshot ("Gentle.lynxpreset");
  18652. check ("swap: the preset row is taken by hot-swap", browser.hotSwapLoadSelected());
  18653. offline.dispatchPendingMessages();
  18654. const auto& now = offline.getSong().mixer[2].effects[1];
  18655. check ("swap: the preset's settings, the device on", now.kind == lynx::EffectKind::compressor && now.presetName == "Gentle" && now.enabled);
  18656. write ("03d-hotswap-preset-swapped");
  18657. offline.undo();
  18658. offline.dispatchPendingMessages();
  18659. check ("undo: the compressor off again", ! offline.getSong().mixer[2].effects[1].enabled);
  18660. browser.endHotSwap();
  18661. check ("hot-swap ended: the preset list goes", ! browser.isHotSwapping());
  18662. browser.beginHotSwap (compressor);
  18663. }
  18664. // linked to the instrument instead
  18665. const auto bass = lynx::hotswap::targetOfChannel (offline.getSong(), 0);
  18666. browser.beginHotSwap (bass);
  18667. detail->selectCardForCheck (0);
  18668. write ("04-hotswap-instrument");
  18669. check ("re-link to the instrument", browser.hotSwapTarget() == bass);
  18670. browser.endHotSwap();
  18671. check ("hot-swap ended", ! browser.isHotSwapping());
  18672. write ("05-hotswap-ended"); // the Browser as it was before
  18673. // the device is deleted while linked: the mode ends by itself
  18674. browser.beginHotSwap (lynx::hotswap::targetOfEffect (offline.getSong(), 2, 2));
  18675. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.pop_back(); });
  18676. offline.dispatchPendingMessages();
  18677. check ("deleting the linked device ends hot-swap", ! browser.isHotSwapping());
  18678. offline.undo();
  18679. offline.dispatchPendingMessages();
  18680. // Duplicate (Ctrl+D) of the EQ
  18681. check ("duplicate", detail->duplicateCardForCheck (1));
  18682. offline.dispatchPendingMessages();
  18683. check ("duplicate: four effects, EQ twice", offline.getSong().mixer[2].effects.size() == 4 && offline.getSong().mixer[2].effects[1].kind == lynx::EffectKind::eq
  18684. && offline.getSong().mixer[2].effects[0].instance.id != offline.getSong().mixer[2].effects[1].instance.id);
  18685. write ("06-duplicated");
  18686. // --- collections ---
  18687. browser.showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  18688. ui.waitForBrowserForSnapshot();
  18689. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 0, true);
  18690. browser.setInCollection (item ("Drums/Snare Tight.wav"), 0, true);
  18691. browser.setInCollection (item ("Loops"), 0, true);
  18692. browser.setTab (lynx::BrowserComponent::starredTab);
  18693. write ("07-starred-only"); // only Starred shown: the tab as it always was
  18694. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 4, true); // also Blue
  18695. browser.setInCollection (item ("Loops/Break 120.wav"), 4, true);
  18696. browser.setInCollection (item ("Textures/Vinyl Noise.wav"), 3, true);
  18697. browser.setInCollection (item ("Textures/Rain.wav"), 3, true);
  18698. browser.setInCollection (item ("Drums/Hat Closed.wav"), 1, true);
  18699. store.rename (3, "Textures");
  18700. browser.setCollectionShown (1, true);
  18701. browser.setCollectionShown (3, true);
  18702. browser.setCollectionShown (4, true);
  18703. write ("08-collections"); // a heading per collection shown
  18704. check ("collections: four shown", store.shown().size() == 4);
  18705. check ("collections: an item in two", store.mask (item ("Drums/Kicks/Kick Hard.wav")) == 0b10001);
  18706. // round 190cy: the Clip-launch workflow's row menu lists the collections flat, as Live's item menu (shot 05);
  18707. // the Pattern workflow keeps the "Collections" sub-menu
  18708. browser.setLiveItemMenus (false);
  18709. saveMenus (juce::StringArray { "Collections (Pattern workflow: a row's sub-menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  18710. prefix + "-09-collections-menu.png");
  18711. browser.setLiveItemMenus (true);
  18712. saveMenus (juce::StringArray { "Collections (Clip-launch workflow: a row's menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  18713. prefix + "-09b-collections-flat.png");
  18714. // the key of a hidden collection (6, Purple) labels the row and the collection appears
  18715. check ("hidden collection: not shown before", ! store.isShown (5));
  18716. browser.setInCollection (item ("Textures/Rain.wav"), 5, true);
  18717. check ("hidden collection: its key shows it", store.isShown (5) && store.has (item ("Textures/Rain.wav"), 5));
  18718. write ("08b-hidden-collection-shown");
  18719. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { browser.buildViewMenu() }, prefix + "-10-browser-options.png");
  18720. browser.setTab (lynx::BrowserComponent::allTab);
  18721. write ("11-all-tab-chips"); // the colour chips on the rows of the ALL tab
  18722. browser.setSearchForSnapshot ("textures");
  18723. ui.waitForBrowserForSnapshot();
  18724. write ("12-search-collection-name"); // found by the collection's name
  18725. browser.setSearchForSnapshot ({});
  18726. // the file round trip
  18727. {
  18728. const auto text = store.toText();
  18729. check ("collections: text round trip", lynx::collections::Store::fromText (text) == store);
  18730. }
  18731. store = {};
  18732. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  18733. lib.deleteRecursively();
  18734. }
  18735. void runMapShot190ef (const juce::String& prefix)
  18736. {
  18737. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18738. lynx::AudioEngine offline (false);
  18739. lynx::MainComponent ui (offline, false);
  18740. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  18741. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  18742. const auto write = [&prefix] (juce::Component& c, const char* name) {
  18743. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  18744. file.deleteFile();
  18745. juce::FileOutputStream out (file);
  18746. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  18747. };
  18748. juce::String checks;
  18749. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  18750. using namespace lynx::remotemap;
  18751. ui.setVisible (true);
  18752. // the Pattern layout first: Ctrl+M stays FL's metronome there and no map mode starts
  18753. {
  18754. const auto before = offline.getTransport().metronome.load();
  18755. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  18756. check ("Pattern layout: Ctrl+M is the metronome, no map mode", ui.getMapMode() == Mode::off && offline.getTransport().metronome.load() != before);
  18757. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  18758. ui.setMapMode (Mode::midi);
  18759. check ("Pattern layout: setMapMode stays off", ui.getMapMode() == Mode::off);
  18760. }
  18761. ui.setClipLaunchWorkflow (true);
  18762. offline.editSong ([] (lynx::Song& s) {
  18763. if (s.mixer.size() < 6)
  18764. s.mixer.resize (6);
  18765. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  18766. for (int i = 1; i < 6; ++i)
  18767. s.mixer[(std::size_t) i].name = inserts[i];
  18768. const int channels = (int) s.channels.size();
  18769. s.channels.resize ((std::size_t) channels + 3);
  18770. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  18771. for (int k = 0; k < 3; ++k)
  18772. {
  18773. auto& ch = s.channels[(std::size_t) (channels + k)];
  18774. ch.name = names[k];
  18775. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  18776. ch.mixerTrack = k + 1;
  18777. }
  18778. s.mixer[2].effects.clear();
  18779. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  18780. {
  18781. lynx::EffectSlot fx;
  18782. fx.kind = kind;
  18783. const auto& info = lynx::effectInfo (kind);
  18784. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  18785. fx.params[k] = info.params[k].defaultValue;
  18786. s.mixer[2].effects.push_back (fx);
  18787. }
  18788. while (s.patterns.size() < 3)
  18789. s.patterns.emplace_back();
  18790. const char* patterns[] { "Beat", "Bassline", "Chords" };
  18791. for (int p = 0; p < 3; ++p)
  18792. {
  18793. auto& pattern = s.patterns[(std::size_t) p];
  18794. pattern.name = patterns[p];
  18795. lynx::Note n;
  18796. n.channel = channels + p;
  18797. n.key = 48 + p * 5;
  18798. pattern.notes = { n };
  18799. pattern.lengthTicks = 4 * lynx::ppq;
  18800. }
  18801. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  18802. const char* tracks[] { "Drums", "Bass", "Keys", "Vox" };
  18803. for (int t = 0; t < 4; ++t)
  18804. s.playlistTracks[(std::size_t) t].name = tracks[t];
  18805. for (int t = 0; t < 3; ++t)
  18806. for (int r = 0; r < 3; ++r)
  18807. {
  18808. lynx::Clip clip;
  18809. clip.pattern = t;
  18810. clip.length = 4 * lynx::ppq;
  18811. lynx::launcher::setClip (s, t, r, clip);
  18812. }
  18813. auto& grid = lynx::launcher::ensureGrid (s);
  18814. const char* scenes[] { "Intro", "Verse", "Drop" };
  18815. grid.scenes.resize (4);
  18816. for (int r = 0; r < 3; ++r)
  18817. grid.scenes[(std::size_t) r].name = scenes[r];
  18818. // some mappings, as the lesson's pictures show them (pads on slots and scenes, knobs on volume and pan)
  18819. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  18820. assignMidi (s, Target::slot (1, 0), { 0, lynx::linkNoteBase + 37, -1 });
  18821. assignMidi (s, Target::sceneLaunch (1), { 0, lynx::linkNoteBase + 44, -1 });
  18822. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }), { 0, 17, -1 });
  18823. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }), { 0, 16, -1 });
  18824. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  18825. setRange (s, rows (s, Mode::midi)[0], 0.0f, 0.85f);
  18826. assignKey (s, Target::slot (0, 1), 'A');
  18827. assignKey (s, Target::slot (1, 1), 'S');
  18828. assignKey (s, Target::sceneLaunch (2), '3');
  18829. assignKey (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 }), 'V');
  18830. }, false);
  18831. offline.dispatchPendingMessages();
  18832. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser }); // (no floating Channel Rack over the grid)
  18833. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  18834. offline.dispatchPendingMessages();
  18835. ui.resized();
  18836. if (auto* detail = ui.getDetailViewForSnapshot())
  18837. {
  18838. detail->showSelection (1, 0);
  18839. detail->setPage (lynx::DetailView::Page::devices);
  18840. }
  18841. ui.resized();
  18842. offline.dispatchPendingMessages();
  18843. write (ui, "00-clip-launch-before");
  18844. // Ctrl+M in the Clip-launch layout: MIDI Map Mode (the metronome stays as it was)
  18845. const auto metronome = offline.getTransport().metronome.load();
  18846. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  18847. check ("Clip-launch layout: Ctrl+M starts MIDI Map Mode", ui.getMapMode() == Mode::midi && offline.getTransport().metronome.load() == metronome);
  18848. auto* overlay = ui.mapOverlayForSnapshot();
  18849. auto* list = ui.mappingBrowserForSnapshot();
  18850. if (overlay == nullptr || list == nullptr)
  18851. {
  18852. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no overlay\n");
  18853. return;
  18854. }
  18855. overlay->refresh();
  18856. const auto& spots = overlay->spots();
  18857. const auto count = [&] (lynx::RemoteAction a) { return (int) std::count_if (spots.begin(), spots.end(), [a] (const lynx::mapmode::Spot& p) { return p.target.action == a; }); };
  18858. const auto params = [&] (lynx::AutomationTargetKind k) {
  18859. return (int) std::count_if (spots.begin(), spots.end(), [k] (const lynx::mapmode::Spot& p) { return p.target.action == lynx::RemoteAction::parameter && p.target.param.kind == k; });
  18860. };
  18861. check ("overlay: clip slots (" + juce::String (count (lynx::RemoteAction::clipSlot)) + ")", count (lynx::RemoteAction::clipSlot) >= 12);
  18862. check ("overlay: scene launch buttons (" + juce::String (count (lynx::RemoteAction::sceneLaunch)) + ")", count (lynx::RemoteAction::sceneLaunch) >= 4);
  18863. check ("overlay: track stop buttons", count (lynx::RemoteAction::trackStop) >= 4);
  18864. check ("overlay: Stop all clips, Session Record", count (lynx::RemoteAction::stopAllClips) == 1 && count (lynx::RemoteAction::sessionRecord) == 1);
  18865. check ("overlay: transport play / stop / record / metronome", count (lynx::RemoteAction::play) == 1 && count (lynx::RemoteAction::stop) == 1
  18866. && count (lynx::RemoteAction::record) == 1 && count (lynx::RemoteAction::metronome) == 1);
  18867. check ("overlay: tempo", params (lynx::AutomationTargetKind::tempo) == 1);
  18868. check ("overlay: mixer volume / pan (" + juce::String (params (lynx::AutomationTargetKind::mixerVolume)) + " / " + juce::String (params (lynx::AutomationTargetKind::mixerPan)) + ")",
  18869. params (lynx::AutomationTargetKind::mixerVolume) >= 3 && params (lynx::AutomationTargetKind::mixerPan) >= 3);
  18870. check ("overlay: device knobs (" + juce::String (params (lynx::AutomationTargetKind::effectParam)) + ")", params (lynx::AutomationTargetKind::effectParam) >= 2);
  18871. // a click on Keys' first slot selects it; a MIDI control assigns it (as the engine's catch would)
  18872. for (const auto& spot : spots)
  18873. if (spot.target == Target::slot (2, 0))
  18874. {
  18875. auto source = juce::Desktop::getInstance().getMainMouseSource();
  18876. const auto now = juce::Time::getCurrentTime();
  18877. const auto at = spot.area.getCentre().toFloat();
  18878. overlay->mouseDown (juce::MouseEvent (source, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
  18879. overlay, overlay, now, at, now, 1, false));
  18880. break;
  18881. }
  18882. if (spots.empty())
  18883. {
  18884. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no spots\n");
  18885. return;
  18886. }
  18887. check ("a click selects the slot", overlay->selection() == std::optional<Target> (Target::slot (2, 0)));
  18888. check ("the overlay takes clicks only on elements", overlay->hitTest (spots.front().area.getCentreX(), spots.front().area.getCentreY()) && ! overlay->hitTest (2, ui.getHeight() - 2));
  18889. check ("a pad assigns it", overlay->assignMidi ({ 0, lynx::linkNoteBase + 38, -1 }) && midiOf (offline.getSong(), Target::slot (2, 0)).number == lynx::linkNoteBase + 38);
  18890. check ("the same pad again on track 0 is refused", ! (overlay->select (Target::slot (0, 2)), overlay->assignMidi ({ 0, lynx::linkNoteBase + 36, -1 })));
  18891. overlay->select (Target::slot (2, 0));
  18892. list->setMode (Mode::midi);
  18893. list->selectRow (0);
  18894. ui.resized();
  18895. overlay->refresh();
  18896. write (ui, "01-midi-map-mode");
  18897. check ("Mapping Browser rows (MIDI): " + juce::String ((int) list->rowsShown().size()), list->rowsShown().size() == 7);
  18898. write (*list, "02-mapping-browser-midi");
  18899. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { list->rowMenu (0) }, prefix + "-03-row-menu.png");
  18900. // Ctrl+K: Key Map Mode; a key assigns the selected element
  18901. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  18902. check ("Ctrl+K switches to Key Map Mode", ui.getMapMode() == Mode::key && offline.getMapMode() == Mode::key);
  18903. overlay->select (Target::sceneLaunch (0));
  18904. ui.keyPressed (juce::KeyPress ('1', {}, '1'));
  18905. check ("a key assigns the selected scene", keyOf (offline.getSong(), Target::sceneLaunch (0)).key == '1');
  18906. overlay->select (Target::sceneLaunch (1));
  18907. ui.keyPressed (juce::KeyPress ('A', {}, 'a'));
  18908. check ("a key already on a slot is refused for a scene", ! keyOf (offline.getSong(), Target::sceneLaunch (1)).found);
  18909. overlay->refresh();
  18910. write (ui, "04-key-map-mode");
  18911. write (*list, "05-mapping-browser-key");
  18912. {
  18913. // round 190em: Min / Max in the parameter's unit, Path "<track> | Mixer", Name "Track Volume" / "Slot n"
  18914. const lynx::remotemap::Target volume = Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 });
  18915. const auto [path, name] = lynx::mapmode::describe (offline, volume);
  18916. check ("browser: volume row Path / Name = " + path + " / " + name, path == "Bass | Mixer" && name == "Track Volume");
  18917. check ("browser: volume Min / Max = " + lynx::mapmode::rangeText (offline, volume, 0.0f) + " / " + lynx::mapmode::rangeText (offline, volume, 1.0f),
  18918. lynx::mapmode::rangeText (offline, volume, 0.0f) == juce::String::fromUTF8 ("\xe2\x88\x92\xe2\x88\x9e dB")
  18919. && lynx::mapmode::rangeText (offline, volume, 1.0f).endsWith (" dB"));
  18920. const lynx::remotemap::Target pan = Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 });
  18921. check ("browser: pan Min / Max = " + lynx::mapmode::rangeText (offline, pan, 0.25f) + " / " + lynx::mapmode::rangeText (offline, pan, 0.5f),
  18922. lynx::mapmode::rangeText (offline, pan, 0.25f) == "50L" && lynx::mapmode::rangeText (offline, pan, 0.5f) == "C"
  18923. && lynx::mapmode::rangeText (offline, pan, 1.0f) == "100R");
  18924. const auto typed = lynx::mapmode::rangeValueOf (offline, volume, "0 dB");
  18925. check ("browser: typing 0 dB", typed.has_value() && std::abs (lynx::mapmode::rangeText (offline, volume, *typed).getDoubleValue()) < 0.15);
  18926. check ("browser: typing 50L", lynx::mapmode::rangeValueOf (offline, pan, "50L") == std::optional<float> (0.25f));
  18927. check ("browser: Key column = " + lynx::mapmode::listKeyText ('V') + ", " + lynx::mapmode::listKeyText ('3'),
  18928. lynx::mapmode::listKeyText ('V') == "Key v" && lynx::mapmode::listKeyText ('3') == "Key 3");
  18929. check ("browser: slot row Name = " + lynx::mapmode::describe (offline, Target::slot (0, 2)).second,
  18930. lynx::mapmode::describe (offline, Target::slot (0, 2)) == std::pair<juce::String, juce::String> ("Drums", "Slot 3"));
  18931. }
  18932. // off again: the key mapping on a parameter toggles it between Min and Max
  18933. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  18934. check ("Ctrl+K again ends it", ui.getMapMode() == Mode::off && ! overlay->isVisible() && ! list->isVisible());
  18935. const lynx::AutomationTarget keysVolume { lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 };
  18936. // (round 190em, Live 12.4.16: the first press goes to Min, then Max, then Min)
  18937. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  18938. check ("the mapped key V moves Bass's volume to Min first", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  18939. ui.keyStateChanged (false); // (V is not down any more: its release)
  18940. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  18941. check ("again: to Max", std::abs (offline.currentTargetValue (keysVolume) - 1.0f) < 0.01f);
  18942. ui.keyStateChanged (false);
  18943. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  18944. check ("again: to Min", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  18945. ui.keyStateChanged (false);
  18946. // the title bar switches
  18947. ui.setMapMode (Mode::midi);
  18948. write (ui, "06-switches-midi-on");
  18949. ui.setMapMode (Mode::off);
  18950. ui.setClipLaunchWorkflow (false);
  18951. check ("leaving the Clip-launch layout ends the map mode", ui.getMapMode() == Mode::off);
  18952. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  18953. }
  18954. void runSceneShot190ef (const juce::String& prefix)
  18955. {
  18956. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18957. lynx::AudioEngine offline (false);
  18958. lynx::MainComponent ui (offline, false);
  18959. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  18960. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  18961. const auto write = [&prefix] (juce::Component& c, const char* name) {
  18962. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  18963. file.deleteFile();
  18964. juce::FileOutputStream out (file);
  18965. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  18966. };
  18967. juce::String checks;
  18968. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  18969. ui.setVisible (true);
  18970. lynx::DetailView::shownSetting = false;
  18971. ui.setClipLaunchWorkflow (true);
  18972. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  18973. offline.editSong ([] (lynx::Song& s) {
  18974. const int channels = (int) s.channels.size();
  18975. s.channels.resize ((std::size_t) channels + 3);
  18976. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  18977. for (int k = 0; k < 3; ++k)
  18978. {
  18979. auto& ch = s.channels[(std::size_t) (channels + k)];
  18980. ch.name = names[k];
  18981. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  18982. }
  18983. while (s.patterns.size() < 3)
  18984. s.patterns.emplace_back();
  18985. const char* patterns[] { "Beat", "Bassline", "Chords" };
  18986. for (int p = 0; p < 3; ++p)
  18987. {
  18988. auto& pattern = s.patterns[(std::size_t) p];
  18989. pattern.name = patterns[p];
  18990. lynx::Note n;
  18991. n.channel = channels + p;
  18992. n.key = 48 + p * 5;
  18993. pattern.notes = { n };
  18994. pattern.lengthTicks = 4 * lynx::ppq;
  18995. }
  18996. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  18997. const char* tracks[] { "Drums", "Bass", "Keys" };
  18998. const std::uint32_t colours[] { 0xFFE0533Bu, 0xFF3B8BE0u, 0xFF46C27Au };
  18999. for (int t = 0; t < 3; ++t)
  19000. {
  19001. s.playlistTracks[(std::size_t) t].name = tracks[t];
  19002. s.playlistTracks[(std::size_t) t].colour = colours[t];
  19003. }
  19004. for (int t = 0; t < 3; ++t)
  19005. for (int r = 0; r < 3; ++r)
  19006. if (! (t == 2 && r == 0))
  19007. {
  19008. lynx::Clip clip;
  19009. clip.pattern = t;
  19010. clip.length = 4 * lynx::ppq;
  19011. lynx::launcher::setClip (s, t, r, clip);
  19012. }
  19013. auto& grid = lynx::launcher::ensureGrid (s);
  19014. grid.scenes.resize (4);
  19015. const char* scenes[] { "Intro", "Verse", "Drop" };
  19016. for (int r = 0; r < 3; ++r)
  19017. grid.scenes[(std::size_t) r].name = scenes[r];
  19018. lynx::session::setSceneTempo (s, 1, 128.0);
  19019. lynx::session::setSceneSignature (s, 1, 3, 4); // (as the live check's "Verse": 3 / 4)
  19020. lynx::session::setSceneSignature (s, 2, 6, 8); // (round 190em: a denominator of its own)
  19021. grid.scenes[2].colour = 0xFF8E5BD6u;
  19022. }, false);
  19023. offline.dispatchPendingMessages();
  19024. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  19025. offline.dispatchPendingMessages();
  19026. ui.resized();
  19027. auto* gridView = ui.getClipGridForSnapshot();
  19028. if (gridView == nullptr)
  19029. {
  19030. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  19031. return;
  19032. }
  19033. lynx::clipGridSceneTempoShown() = true;
  19034. lynx::refreshClipGrid (*gridView);
  19035. lynx::selectClipGridScene (*gridView, 1);
  19036. write (*gridView, "01-scene-fields");
  19037. {
  19038. // round 190em: a plain scene's launch triangle in Live's dark grey (#1E1E1E), scene 4 (row 3)
  19039. const auto image = lynx::shot::snapshot (*gridView);
  19040. int dark = 0;
  19041. for (int y = 0; y < image.getHeight(); ++y)
  19042. for (int x = image.getWidth() - 240; x < image.getWidth() - 180; ++x)
  19043. if (const auto p = image.getPixelAt (x, y); y > 3 * 24 + 26 && y < 4 * 24 + 26 && std::abs (p.getRed() - 0x1e) <= 2
  19044. && std::abs (p.getGreen() - 0x1e) <= 2 && std::abs (p.getBlue() - 0x1e) <= 2)
  19045. ++dark;
  19046. check ("plain scene triangle in Live's #1E1E1E (" + juce::String (dark) + " px)", dark >= 20);
  19047. }
  19048. saveMenus (juce::StringArray { "Scene menu (Verse)" }, std::vector<juce::PopupMenu> { lynx::clipGridSceneMenu (*gridView, 1) }, prefix + "-02-scene-menu.png");
  19049. saveMenus (juce::StringArray { "Scene tempo field", "Scene time signature field" },
  19050. std::vector<juce::PopupMenu> { lynx::clipGridSceneFieldMenu (*gridView, 1, 1), lynx::clipGridSceneFieldMenu (*gridView, 2, 2) },
  19051. prefix + "-03-field-menus.png");
  19052. saveMenus (juce::StringArray { "Column title (Bass)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*gridView, 1) }, prefix + "-04-title-menu.png");
  19053. const auto clipsIn = [&offline] (int row) {
  19054. int n = 0;
  19055. if (const auto& g = offline.getSong().clipGrid)
  19056. for (int t = 0; t < 8; ++t)
  19057. n += lynx::launcher::clipAt (*g, t, row) != nullptr ? 1 : 0;
  19058. return n;
  19059. };
  19060. const auto before = clipsIn (1);
  19061. const auto dup = lynx::duplicateClipGridScene (*gridView, 1);
  19062. offline.dispatchPendingMessages();
  19063. const auto& scenesNow = offline.getSong().clipGrid->scenes;
  19064. check ("duplicate: Verse's copy is row 2, with its clips and tempo", dup == 2 && clipsIn (2) == before && scenesNow.size() > 2
  19065. && scenesNow[2].name == "Verse" && scenesNow[2].tempo == 128.0);
  19066. write (*gridView, "05-scene-duplicated");
  19067. const auto cap = lynx::captureClipGridScene (*gridView, 3, { 0, 2, 1 }); // Drums row 0, Bass row 2, Keys row 1
  19068. offline.dispatchPendingMessages();
  19069. check ("capture: a new row 4 with the three playing clips", cap == 4 && clipsIn (4) == 3);
  19070. {
  19071. const auto& sc = offline.getSong().clipGrid->scenes;
  19072. check ("capture while playing: the new scene is plain (no name, fields off)", sc.size() > 4 && sc[4] == lynx::ClipGridScene {});
  19073. }
  19074. write (*gridView, "06-scene-captured");
  19075. // round 190em: nothing plays: an empty scene like the selected one (name, tempo, signature), selected
  19076. const auto empty = lynx::captureClipGridScene (*gridView, 1, { -1, -1 });
  19077. offline.dispatchPendingMessages();
  19078. {
  19079. const auto& sc = offline.getSong().clipGrid->scenes;
  19080. check ("capture with nothing playing: an empty row 2 named Verse, 128 BPM, 3 / 4", empty == 2 && clipsIn (2) == 0 && sc[2].name == "Verse"
  19081. && sc[2].tempo == 128.0 && sc[2].beatsPerBar == 3 && sc[2].beatUnit == 4);
  19082. }
  19083. write (*gridView, "06b-scene-captured-stopped");
  19084. // round 190em: Capture and Insert while clips play: playback moves to the new row (the runtime view shows what
  19085. // the player reports once the published song holds the moved slots)
  19086. {
  19087. const auto rowsBefore = offline.getSong().clipGrid->scenes.size();
  19088. lynx::selectClipGridScene (*gridView, 0);
  19089. const auto at = lynx::captureClipGridScene (*gridView, 0, { 0, 0, -1 });
  19090. offline.dispatchPendingMessages();
  19091. const auto& g = *offline.getSong().clipGrid;
  19092. check ("capture while playing: row 1 holds the moved playing slots", at == 1 && g.scenes.size() == rowsBefore + 1
  19093. && clipsIn (1) == 2 && clipsIn (0) == 2 && g.scenes[1] == lynx::ClipGridScene {});
  19094. if (auto* runtime = offline.launcherStateForSnapshot())
  19095. for (int t = 0; t < 2; ++t)
  19096. runtime->tracks[(std::size_t) t].playing.store (1);
  19097. lynx::refreshClipGrid (*gridView);
  19098. write (*gridView, "09-capture-playing-moves");
  19099. if (auto* runtime = offline.launcherStateForSnapshot())
  19100. for (int t = 0; t < 2; ++t)
  19101. runtime->tracks[(std::size_t) t].playing.store (-1);
  19102. }
  19103. // round 190em: the fields as "n / d", a selected field, Del = Return to Default
  19104. lynx::clipGridSceneTempoShown() = true;
  19105. lynx::refreshClipGrid (*gridView);
  19106. {
  19107. const auto& sc = offline.getSong().clipGrid->scenes;
  19108. int verse = -1;
  19109. for (int r = 0; r < (int) sc.size() && verse < 0; ++r)
  19110. if (sc[(std::size_t) r].name == "Verse" && sc[(std::size_t) r].tempo > 0.0)
  19111. verse = r;
  19112. lynx::selectClipGridSceneField (*gridView, verse, 1);
  19113. write (*gridView, "10-field-selected");
  19114. gridView->keyPressed (juce::KeyPress (juce::KeyPress::deleteKey));
  19115. offline.dispatchPendingMessages();
  19116. const auto& after = offline.getSong().clipGrid->scenes;
  19117. check ("Del on a selected tempo field returns it to default (scene kept)", verse >= 0 && after.size() == sc.size()
  19118. && after[(std::size_t) verse].tempo == 0.0 && after[(std::size_t) verse].beatsPerBar == 3);
  19119. write (*gridView, "11-field-returned-to-default");
  19120. }
  19121. // round 190em: Capture MIDI to the armed track (Bass), the selected scene's slot, the tempo from the phrase
  19122. {
  19123. offline.stop();
  19124. offline.setGridTrackArmed (1, true, true);
  19125. lynx::selectClipGridScene (*gridView, 0);
  19126. int empty = 0;
  19127. while (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, empty) != nullptr)
  19128. ++empty;
  19129. const auto now = juce::Time::getMillisecondCounterHiRes();
  19130. const auto beat = 60000.0 / 148.0;
  19131. for (int i = 0; i < 8; ++i)
  19132. {
  19133. const auto at = now - 9.0 * beat + i * beat;
  19134. offline.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  19135. offline.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  19136. }
  19137. int placed = -1;
  19138. bool into = true;
  19139. const auto r = offline.captureMidiToSlot (1, empty, placed, into);
  19140. offline.dispatchPendingMessages();
  19141. check ("Capture MIDI: 8 notes into Bass row " + juce::String (placed) + ", tempo " + juce::String (offline.getSong().bpm, 2),
  19142. r.notes == 8 && placed == empty && ! into && std::abs (offline.getSong().bpm - 148.0) < 0.5 && offline.getTransport().playing.load());
  19143. const auto& capturedGrid = *offline.getSong().clipGrid;
  19144. const auto* capturedClip = lynx::launcher::clipAt (capturedGrid, 1, placed);
  19145. const auto* slot = capturedClip != nullptr ? &capturedGrid.slots[(std::size_t) capturedClip->gridSlot] : nullptr;
  19146. check ("Capture MIDI: the clip has no name of its own (blank label, as Live)", slot != nullptr && slot->name.empty() && slot->blankName);
  19147. if (auto* runtime = offline.launcherStateForSnapshot())
  19148. runtime->tracks[1].playing.store (placed);
  19149. lynx::refreshClipGrid (*gridView);
  19150. write (*gridView, "12-capture-midi");
  19151. if (auto* runtime = offline.launcherStateForSnapshot())
  19152. runtime->tracks[1].playing.store (-1);
  19153. offline.stop();
  19154. }
  19155. write (ui, "07-window");
  19156. lynx::clipGridSceneTempoShown() = false;
  19157. lynx::refreshClipGrid (*gridView);
  19158. write (*gridView, "08-fields-off");
  19159. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  19160. }
  19161. void runDrawShot190ef (const juce::String& prefix)
  19162. {
  19163. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19164. lynx::AudioEngine offline (false);
  19165. lynx::MainComponent ui (offline, false);
  19166. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  19167. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  19168. const auto write = [&prefix] (juce::Component& c, const char* name) {
  19169. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  19170. file.deleteFile();
  19171. juce::FileOutputStream out (file);
  19172. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  19173. };
  19174. juce::String checks;
  19175. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  19176. ui.setVisible (true);
  19177. ui.setClipLaunchWorkflow (true);
  19178. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  19179. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  19180. lynx::autolanes::setShown (true);
  19181. offline.editSong ([] (lynx::Song& s) {
  19182. if (s.mixer.size() < 4)
  19183. s.mixer.resize (4);
  19184. s.mixer[1].name = "Bass";
  19185. s.mixer[2].name = "Pad";
  19186. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  19187. s.playlistTracks[0].name = "Bass";
  19188. s.playlistTracks[0].mode = lynx::PlaylistTrackMode::audio;
  19189. s.playlistTracks[0].mixerTrack = 1;
  19190. s.playlistTracks[1].name = "Pad";
  19191. s.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  19192. s.playlistTracks[1].mixerTrack = 2;
  19193. }, false);
  19194. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0);
  19195. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerPan, 2, 0, 0 }, 1);
  19196. offline.editSong ([] (lynx::Song& s) {
  19197. for (int t = 0; t < 2; ++t)
  19198. if (! s.playlistTracks[(std::size_t) t].lanes.empty())
  19199. s.playlistTracks[(std::size_t) t].lanes[0].height = 110;
  19200. }, false);
  19201. offline.dispatchPendingMessages();
  19202. auto& playlist = ui.getPlaylistForSnapshot();
  19203. playlist.setViewForSnapshot (180.0, 0, 0);
  19204. ui.resized();
  19205. offline.dispatchPendingMessages();
  19206. const auto& song = offline.getSong();
  19207. const auto laneA = song.playlistTracks[0].lanes.empty() ? -1 : song.playlistTracks[0].lanes[0].automation;
  19208. const auto laneB = song.playlistTracks[1].lanes.empty() ? -1 : song.playlistTracks[1].lanes[0].automation;
  19209. check ("two lanes made", laneA >= 0 && laneB >= 0);
  19210. if (laneA < 0 || laneB < 0)
  19211. {
  19212. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  19213. return;
  19214. }
  19215. write (ui, "00-lanes-before");
  19216. const auto before = song.automations[(std::size_t) laneA].points;
  19217. // a drag through the Playlist's own handlers (the events a real mouse sends)
  19218. auto source = juce::Desktop::getInstance().getMainMouseSource();
  19219. const auto now = juce::Time::getCurrentTime();
  19220. const auto stroke = [&] (int track, const std::vector<juce::Point<float>>& path, juce::ModifierKeys extra) {
  19221. const juce::ModifierKeys mods (juce::ModifierKeys::leftButtonModifier | extra.getRawFlags());
  19222. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  19223. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, path.front(), now, 1, dragged);
  19224. };
  19225. juce::ignoreUnused (track);
  19226. // (the engine joins the edits of one press into one undo step while a button is down)
  19227. const auto held = juce::ModifierKeys::currentModifiers;
  19228. juce::ModifierKeys::currentModifiers = mods;
  19229. playlist.mouseDown (event (path.front(), mods, false));
  19230. for (std::size_t i = 1; i < path.size(); ++i)
  19231. playlist.mouseDrag (event (path[i], mods, true));
  19232. juce::ModifierKeys::currentModifiers = held;
  19233. playlist.mouseUp (event (path.back(), extra, true));
  19234. };
  19235. const auto bodyA = playlist.laneBodyForSnapshot (0, 0), bodyB = playlist.laneBodyForSnapshot (1, 0);
  19236. const auto bar = (double) (4 * lynx::ppq);
  19237. const auto x = [&] (double bars) { return (float) playlist.xOfTickForSnapshot (bars * bar); };
  19238. const auto y = [] (juce::Rectangle<float> body, float v) { return body.getBottom() - v * body.getHeight(); };
  19239. lynx::drawmode::set (true);
  19240. // steps: a rise over bar 1 and a fall over bar 2, at the Playlist's grid (Line, at this zoom)
  19241. std::vector<juce::Point<float>> steps;
  19242. for (int k = 0; k <= 16; ++k)
  19243. steps.push_back ({ x (1.0 + k / 16.0) + 2.0f, y (bodyA, 0.15f + 0.05f * (float) k) });
  19244. for (int k = 0; k <= 16; ++k)
  19245. steps.push_back ({ x (2.0 + k / 16.0) + 2.0f, y (bodyA, 0.95f - 0.05f * (float) k) });
  19246. stroke (0, steps, {});
  19247. const auto& afterSteps = offline.getSong().automations[(std::size_t) laneA].points;
  19248. check ("Draw Mode drag made steps (" + juce::String ((int) afterSteps.size()) + " points)", afterSteps.size() > before.size() + 4);
  19249. bool unchangedOutside = true;
  19250. for (double t = 0.0; t < 6.0 * bar; t += 37.0)
  19251. if ((t < bar - 1.0 || t > 3.1 * bar) && std::abs (lynx::automationCurveAt (before, t) - lynx::automationCurveAt (afterSteps, t)) > 1.0e-4f)
  19252. unchangedOutside = false;
  19253. check ("the curve outside the drawn bars is unchanged", unchangedOutside);
  19254. {
  19255. // flat inside each drawn cell: the values in a cell's first and last tick are the same
  19256. int flatCells = 0, cells = 0;
  19257. for (double t = bar; t < 3.0 * bar; t += lynx::ppq / 4.0)
  19258. {
  19259. ++cells;
  19260. if (std::abs (lynx::automationCurveAt (afterSteps, t + 1.0) - lynx::automationCurveAt (afterSteps, t + lynx::ppq / 4.0 - 1.0)) < 1.0e-5f)
  19261. ++flatCells;
  19262. }
  19263. check ("each sixteenth inside bars 2-3 is flat (" + juce::String (flatCells) + " / " + juce::String (cells) + ")", flatCells == cells);
  19264. }
  19265. // freehand: Alt (no grid) on the pad's pan lane, a wave over bars 1-4
  19266. const auto panBefore = offline.getSong().automations[(std::size_t) laneB].points;
  19267. // (off-screen every press has the same mouse-down time, which the undo history uses to join one press's edits:
  19268. // an edit with no button down in between separates the two strokes, as a real second press does)
  19269. offline.editSong ([] (lynx::Song&) {});
  19270. std::vector<juce::Point<float>> wave;
  19271. for (int k = 0; k <= 60; ++k)
  19272. wave.push_back ({ x (1.0 + 3.0 * k / 60.0), y (bodyB, 0.5f + 0.4f * std::sin ((float) k * 0.3f)) });
  19273. stroke (1, wave, juce::ModifierKeys (juce::ModifierKeys::altModifier));
  19274. const auto& pan = offline.getSong().automations[(std::size_t) laneB].points;
  19275. check ("Alt drag drew freehand (" + juce::String ((int) pan.size()) + " points)", pan.size() > 30);
  19276. playlist.repaint();
  19277. write (ui, "01-draw-mode-steps-and-freehand");
  19278. if (auto* parent = playlist.getParentComponent())
  19279. write (*parent, "01b-playlist");
  19280. // one stroke is one undo step
  19281. offline.undo();
  19282. check ("one undo takes the whole freehand stroke back", offline.getSong().automations[(std::size_t) laneB].points == panBefore);
  19283. // Draw Mode off: the same press adds one point, as before
  19284. lynx::drawmode::set (false);
  19285. const auto countOff = offline.getSong().automations[(std::size_t) laneA].points.size();
  19286. stroke (0, { { x (4.5), y (bodyA, 0.8f) } }, {});
  19287. check ("Draw Mode off: a press adds one point", offline.getSong().automations[(std::size_t) laneA].points.size() == countOff + 1);
  19288. // the Options menu (Clip-launch layout) with the switch
  19289. lynx::drawmode::set (true);
  19290. {
  19291. const auto names = ui.getMenuNamesForSnapshot();
  19292. const auto index = names.indexOf (TRANS ("Options"));
  19293. if (index >= 0)
  19294. saveMenus (juce::StringArray { "Options" }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-02-options-menu.png");
  19295. check ("Options menu found", index >= 0);
  19296. }
  19297. lynx::drawmode::set (false);
  19298. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  19299. }
  19300. void runLiveShot190dr (const juce::String& prefix)
  19301. {
  19302. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19303. lynx::AudioEngine offline (false);
  19304. lynx::MainComponent ui (offline, false);
  19305. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  19306. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  19307. const auto write = [&prefix] (juce::Component& c, const char* name) {
  19308. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  19309. file.deleteFile();
  19310. juce::FileOutputStream out (file);
  19311. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  19312. };
  19313. juce::String checks;
  19314. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  19315. // a two-bar loop of clicks for the audio clip
  19316. const auto wav = juce::File (prefix + "-loop.wav");
  19317. wav.deleteFile();
  19318. {
  19319. const double rate = 48000.0;
  19320. juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
  19321. buffer.clear();
  19322. for (int hit = 0; hit < 16; ++hit)
  19323. for (int k = 0; k < 3000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
  19324. for (int ch = 0; ch < 2; ++ch)
  19325. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  19326. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  19327. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  19328. {
  19329. out.release();
  19330. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  19331. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  19332. }
  19333. }
  19334. ui.setVisible (true);
  19335. lynx::DetailView::shownSetting = true;
  19336. lynx::DetailView::devicesPage = false;
  19337. ui.setClipLaunchWorkflow (true);
  19338. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  19339. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  19340. offline.dispatchPendingMessages();
  19341. int audioChannel = -1;
  19342. offline.editSong ([&audioChannel] (lynx::Song& s) {
  19343. lynx::Clip audio;
  19344. if (! s.playlist.empty())
  19345. {
  19346. audio = s.playlist.front();
  19347. audioChannel = audio.channel;
  19348. s.playlist.clear();
  19349. }
  19350. const int channels = (int) s.channels.size();
  19351. s.channels.resize ((std::size_t) channels + 3);
  19352. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  19353. for (int k = 0; k < 3; ++k)
  19354. {
  19355. auto& ch = s.channels[(std::size_t) (channels + k)];
  19356. ch.name = names[k];
  19357. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  19358. ch.mixerTrack = k + 1;
  19359. }
  19360. if (audioChannel >= 0)
  19361. s.channels[(std::size_t) audioChannel].mixerTrack = 5;
  19362. if (s.mixer.size() < 8)
  19363. s.mixer.resize (8);
  19364. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
  19365. for (int i = 1; i < 8; ++i)
  19366. s.mixer[(std::size_t) i].name = inserts[i];
  19367. s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
  19368. s.mixer[2].pan = 0.3f;
  19369. s.mixer[2].effects.clear();
  19370. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  19371. {
  19372. lynx::EffectSlot fx;
  19373. fx.kind = kind;
  19374. const auto& info = lynx::effectInfo (kind);
  19375. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  19376. fx.params[k] = info.params[k].defaultValue;
  19377. s.mixer[2].effects.push_back (fx);
  19378. }
  19379. s.mixer[3].muted = true; // the Keys' activator off
  19380. s.mixer[4].inputChannel = 0;
  19381. s.mixer[4].inputStereo = true;
  19382. s.mixer[4].monitor = lynx::InputMonitor::automatic;
  19383. s.mixer[4].effects.clear();
  19384. {
  19385. lynx::EffectSlot fx;
  19386. fx.kind = lynx::EffectKind::reverb;
  19387. s.mixer[4].effects.push_back (fx);
  19388. }
  19389. s.mixer[5].solo = true;
  19390. for (auto [from, to, level] : std::initializer_list<std::tuple<int, int, float>> { { 1, 6, 0.35f }, { 2, 6, 0.6f }, { 3, 6, 0.8f }, { 2, 7, 0.25f }, { 4, 7, 0.5f } })
  19391. {
  19392. lynx::MixerSend send;
  19393. send.target = to;
  19394. send.level = lynx::faderGain (level);
  19395. s.mixer[(std::size_t) from].sends.push_back (send);
  19396. }
  19397. while (s.patterns.size() < 3)
  19398. s.patterns.emplace_back();
  19399. const char* patterns[] { "Beat", "Bassline", "Chords" };
  19400. for (int p = 0; p < 3; ++p)
  19401. {
  19402. auto& pattern = s.patterns[(std::size_t) p];
  19403. pattern.name = patterns[p];
  19404. lynx::Note n;
  19405. n.channel = channels + p;
  19406. n.key = 48 + p * 5;
  19407. pattern.notes = { n };
  19408. pattern.lengthTicks = 4 * lynx::ppq;
  19409. }
  19410. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  19411. const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
  19412. for (int t = 0; t < 6; ++t)
  19413. s.playlistTracks[(std::size_t) t].name = tracks[t];
  19414. s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
  19415. s.playlistTracks[3].mixerTrack = 4;
  19416. for (int t = 0; t < 3; ++t)
  19417. for (int r = 0; r < 3; ++r)
  19418. if (! (t == 2 && r == 0))
  19419. {
  19420. lynx::Clip clip;
  19421. clip.pattern = t;
  19422. clip.length = 4 * lynx::ppq;
  19423. lynx::launcher::setClip (s, t, r, clip);
  19424. }
  19425. if (audioChannel >= 0)
  19426. {
  19427. lynx::clipsample::setWarp (s, audioChannel, true, 4.0); // (Warp on, as a dropped loop in Live)
  19428. audio.track = 4;
  19429. audio.start = 0;
  19430. lynx::launcher::setClip (s, 4, 0, audio);
  19431. lynx::launcher::setClip (s, 4, 1, audio);
  19432. }
  19433. auto& grid = lynx::launcher::ensureGrid (s);
  19434. const char* scenes[] { "Intro", "Verse", "Drop" };
  19435. grid.scenes.resize (5);
  19436. for (int r = 0; r < 3; ++r)
  19437. grid.scenes[(std::size_t) r].name = scenes[r];
  19438. }, false);
  19439. offline.dispatchPendingMessages();
  19440. offline.setGridTrackArmed (3, true);
  19441. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  19442. offline.dispatchPendingMessages();
  19443. ui.resized();
  19444. auto* gridView = ui.getClipGridForSnapshot();
  19445. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  19446. auto* detail = ui.getDetailViewForSnapshot();
  19447. if (gridView == nullptr || mixer == nullptr || detail == nullptr)
  19448. {
  19449. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid, mixer or detail view\n");
  19450. return;
  19451. }
  19452. // the meters: a level per insert, as a playing song leaves them (offscreen nothing plays), two ticks
  19453. const auto levels = [&] {
  19454. for (int k = 0; k < 2; ++k)
  19455. {
  19456. const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
  19457. for (int i = 0; i < 8; ++i)
  19458. offline.getMeters().accumulate (i, peaks[i], peaks[i] * 0.85f);
  19459. mixer->tick();
  19460. }
  19461. };
  19462. if (auto* runtime = offline.launcherStateForSnapshot())
  19463. {
  19464. runtime->tracks[0].playing.store (1);
  19465. runtime->tracks[0].progress.store (0.3f);
  19466. runtime->tracks[1].playing.store (1);
  19467. runtime->tracks[1].progress.store (0.3f);
  19468. runtime->tracks[4].playing.store (0);
  19469. runtime->tracks[4].progress.store (0.5f);
  19470. runtime->running.store (true);
  19471. }
  19472. levels();
  19473. gridView->resized();
  19474. write (ui, "01-session-mixer");
  19475. write (*gridView, "01b-grid-alone");
  19476. using Part = lynx::SessionMixerComponent::Part;
  19477. check ("mixer: Sends rows are the two buses (Reverb 6, Delay 7)", mixer->sendTargets() == std::vector<int> { 6, 7 });
  19478. check ("mixer: the arm buttons moved into the Volume section", mixer->armsShown());
  19479. check ("mixer: Drums strip has activator, solo, arm, pan, volume", ! mixer->partBounds (0, Part::activator).isEmpty() && ! mixer->partBounds (0, Part::solo).isEmpty()
  19480. && ! mixer->partBounds (0, Part::arm).isEmpty() && ! mixer->partBounds (0, Part::pan).isEmpty()
  19481. && ! mixer->partBounds (0, Part::volume).isEmpty());
  19482. check ("mixer: Vox strip (audio track) has Audio From, its channel, Monitor and Audio To", ! mixer->partBounds (3, Part::inType).isEmpty()
  19483. && ! mixer->partBounds (3, Part::inChannel).isEmpty()
  19484. && ! mixer->partBounds (3, Part::monAuto).isEmpty()
  19485. && ! mixer->partBounds (3, Part::output).isEmpty());
  19486. check ("mixer: Bass strip (instrument) shows MIDI From, no Monitor", mixer->partBounds (1, Part::monIn).isEmpty() && ! mixer->partBounds (1, Part::output).isEmpty());
  19487. check ("mixer: FX strip (no clips) has no activator but an arm", mixer->partBounds (5, Part::activator).isEmpty() && ! mixer->partBounds (5, Part::arm).isEmpty());
  19488. check ("mixer: Main strip has volume and pan, no activator", ! mixer->partBounds (-2, Part::volume).isEmpty() && mixer->partBounds (-2, Part::activator).isEmpty());
  19489. {
  19490. const auto hit = mixer->hitAt (mixer->partBounds (2, Part::solo).getCentre());
  19491. check ("mixer: a click on the Keys' S is its solo", hit.column == 2 && hit.part == Part::solo);
  19492. const auto send = mixer->hitAt (mixer->partBounds (1, Part::send, 1).getCentre());
  19493. check ("mixer: the Bass' second knob is its send to Delay", send.column == 1 && send.part == Part::send && send.row == 1);
  19494. }
  19495. {
  19496. juce::PopupMenu menu;
  19497. mixer->addViewItems (menu);
  19498. saveMenus (juce::StringArray { "Mixer (footer button)" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-mixer-view-menu.png");
  19499. }
  19500. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.trackOptions = true; }, false);
  19501. offline.dispatchPendingMessages();
  19502. gridView->resized();
  19503. levels();
  19504. write (*gridView, "03-mixer-track-options");
  19505. offline.editSong ([] (lynx::Song& s) {
  19506. auto& v = lynx::launcher::ensureGrid (s).mixerView;
  19507. v.trackOptions = v.io = v.sends = false;
  19508. }, false);
  19509. offline.dispatchPendingMessages();
  19510. gridView->resized();
  19511. levels();
  19512. write (*gridView, "04-mixer-volume-only");
  19513. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.shown = false; }, false);
  19514. offline.dispatchPendingMessages();
  19515. gridView->resized();
  19516. write (*gridView, "05-mixer-hidden");
  19517. check ("mixer hidden: the arm buttons are back in the status row", ! mixer->armsShown() && mixer->getHeight() == 0);
  19518. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView = {}; }, false);
  19519. offline.dispatchPendingMessages();
  19520. gridView->resized();
  19521. // the Clip page of the Loop clip (track 4, scene 0) while it plays: Warp on, the Set buttons lit, the title
  19522. detail->showSelection (4, 0);
  19523. detail->setPage (lynx::DetailView::Page::clip);
  19524. offline.editSong ([] (lynx::Song&) {}, false); // (a change message: the Clip panel reads the playing state)
  19525. offline.dispatchPendingMessages();
  19526. write (ui, "06-clip-audio-warp-on");
  19527. if (audioChannel >= 0)
  19528. {
  19529. const auto beforeLength = lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length;
  19530. offline.editSong ([audioChannel] (lynx::Song& s) { lynx::clipsample::setWarp (s, audioChannel, false, 4.0); });
  19531. offline.dispatchPendingMessages();
  19532. write (ui, "07-clip-audio-warp-off");
  19533. check ("warp off: the channel plays at its own speed", ! lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  19534. offline.undo();
  19535. offline.dispatchPendingMessages();
  19536. check ("warp: undo gives the clip back as it was", lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length == beforeLength
  19537. && lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  19538. // Set (start) at the play position, half way: one undo step
  19539. const auto clipBefore = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  19540. offline.editSong ([] (lynx::Song& s) {
  19541. for (auto& c : s.clipGrid->clips)
  19542. if (c.track == 4 && c.gridSlot >= 0 && s.clipGrid->slots[(std::size_t) c.gridSlot].scene == 0)
  19543. lynx::clipsample::setStartAt (c, lynx::clipsample::playPosition (c, 0.5f));
  19544. });
  19545. const auto& after = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  19546. check ("set start: the clip starts half way and ends where it did", after.offset == clipBefore.offset + clipBefore.length / 2
  19547. && after.offset + after.length == clipBefore.offset + clipBefore.length);
  19548. offline.undo();
  19549. offline.dispatchPendingMessages();
  19550. }
  19551. // a MIDI clip's Clip page too (the Set buttons are there for every clip), playing through a groove of the pool
  19552. offline.editSong ([] (lynx::Song& s) {
  19553. const auto& bank = lynx::groove::factoryBank();
  19554. if (bank.size() > 9)
  19555. lynx::groove::setClipGroove (s, 0, 1, lynx::groove::add (s.grooves, bank[9].groove));
  19556. }, false);
  19557. detail->showSelection (0, 1);
  19558. offline.editSong ([] (lynx::Song&) {}, false);
  19559. offline.dispatchPendingMessages();
  19560. write (ui, "08-clip-midi-set-buttons");
  19561. // the Device View of Bass (insert 2): its compressor dragged onto Keys (insert 3), then Ctrl-dragged onto Vox
  19562. detail->showSelection (1, 0);
  19563. detail->setPage (lynx::DetailView::Page::devices);
  19564. offline.dispatchPendingMessages();
  19565. write (ui, "09-devices-bass-before");
  19566. lynx::setClipGridDeviceDropForSnapshot (*gridView, 2);
  19567. write (ui, "10-device-dragged-over-keys");
  19568. lynx::setClipGridDeviceDropForSnapshot (*gridView, -1);
  19569. int fromId = 0;
  19570. {
  19571. const auto& s = offline.getSong();
  19572. fromId = (int) (s.mixer[2].effects[1].instance.id & 0x7fffffff);
  19573. }
  19574. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  19575. offline.dispatchPendingMessages();
  19576. check ("drag to Keys: the compressor moved (same device)", offline.getSong().mixer[2].effects.size() == 2 && offline.getSong().mixer[3].effects.size() == 1
  19577. && (int) (offline.getSong().mixer[3].effects[0].instance.id & 0x7fffffff) == fromId);
  19578. detail->showSelection (2, 1);
  19579. offline.dispatchPendingMessages();
  19580. write (ui, "11-devices-keys-after-move");
  19581. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 0, 4, true); });
  19582. offline.dispatchPendingMessages();
  19583. check ("Ctrl-drag to Vox: a copy of the EQ after its reverb, Bass keeps its own", offline.getSong().mixer[4].effects.size() == 2
  19584. && offline.getSong().mixer[4].effects[1].kind == lynx::EffectKind::eq
  19585. && offline.getSong().mixer[2].effects[0].kind == lynx::EffectKind::eq);
  19586. offline.undo();
  19587. offline.undo();
  19588. offline.dispatchPendingMessages();
  19589. check ("undo twice: Bass has its three devices again, Keys none", offline.getSong().mixer[2].effects.size() == 3 && offline.getSong().mixer[3].effects.empty()
  19590. && offline.getSong().mixer[4].effects.size() == 1);
  19591. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  19592. wav.deleteFile();
  19593. }
  19594. void runWarpShot (const juce::String& prefix)
  19595. {
  19596. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19597. lynx::AudioEngine offline (false);
  19598. lynx::MainComponent ui (offline, false);
  19599. ui.setSize (1600, 900);
  19600. const auto write = [&prefix] (juce::Component& c, const char* name) {
  19601. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  19602. file.deleteFile();
  19603. juce::FileOutputStream out (file);
  19604. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  19605. };
  19606. // a two-bar loop of clicks, a little off the grid (what Quantize is for)
  19607. const auto wav = juce::File (prefix + "-loop.wav");
  19608. wav.deleteFile();
  19609. {
  19610. const double rate = 44100.0;
  19611. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  19612. buffer.clear();
  19613. for (int hit = 0; hit < 8; ++hit)
  19614. {
  19615. const auto at = (int) ((hit * 0.5 + (hit % 3) * 0.035) * rate);
  19616. for (int k = 0; k < 4000 && at + k < buffer.getNumSamples(); ++k)
  19617. buffer.setSample (0, at + k, (float) (std::sin (k * (hit % 2 ? 0.25 : 0.06)) * std::exp (-k / 700.0) * 0.8));
  19618. }
  19619. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  19620. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  19621. {
  19622. out.release();
  19623. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  19624. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  19625. }
  19626. }
  19627. ui.setVisible (true);
  19628. lynx::DetailView::shownSetting = true;
  19629. ui.selectTabForSnapshot (2);
  19630. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  19631. lynx::autolanes::setShown (true);
  19632. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  19633. offline.dispatchPendingMessages();
  19634. int channel = -1;
  19635. offline.editSong ([&channel] (lynx::Song& s) {
  19636. if (s.playlist.empty())
  19637. return;
  19638. auto audio = s.playlist.front();
  19639. channel = audio.channel;
  19640. audio.track = 1;
  19641. s.playlist.front() = audio;
  19642. for (int k = 1; k < 3; ++k)
  19643. {
  19644. auto more = audio;
  19645. more.start = audio.start + k * 8 * lynx::ppq;
  19646. s.playlist.push_back (more);
  19647. }
  19648. while (s.patterns.size() < 1)
  19649. s.patterns.emplace_back();
  19650. for (int t = 2; t < 5; ++t)
  19651. for (int k = 0; k < 4; ++k)
  19652. {
  19653. lynx::Clip c;
  19654. c.pattern = 0;
  19655. c.track = t;
  19656. c.start = k * 4 * lynx::ppq;
  19657. c.length = 4 * lynx::ppq;
  19658. s.playlist.push_back (c);
  19659. }
  19660. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  19661. s.playlistTracks[1].name = "Loop";
  19662. s.playlistTracks[2].name = "Drums";
  19663. s.playlistTracks[3].name = "Kick";
  19664. s.playlistTracks[4].name = "Hats";
  19665. s.playlistTracks[4].folded = true;
  19666. lynx::noteedit::groupWithAbove (s, 3);
  19667. lynx::noteedit::groupWithAbove (s, 4);
  19668. lynx::arrange::makeGroupBus (s, 3);
  19669. lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::tempo, 0, 0, 0 }, "Tempo", lynx::valueFromTempo (s.bpm));
  19670. if (! s.automations.empty())
  19671. s.automations.back().points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { 8 * lynx::ppq, lynx::valueFromTempo (120.0), 0.0f },
  19672. { 12 * lynx::ppq, lynx::valueFromTempo (180.0), 0.0f }, { 16 * lynx::ppq, lynx::valueFromTempo (140.0), 0.0f } };
  19673. s.addMarker ({ 4 * lynx::ppq, "Verse", 0, 0 });
  19674. s.addMarker ({ 8 * lynx::ppq, {}, 3, 4 });
  19675. s.addMarker ({ 14 * lynx::ppq, {}, 4, 4 });
  19676. s.loopStart = 4 * lynx::ppq;
  19677. s.loopEnd = 12 * lynx::ppq;
  19678. s.loopOff = true;
  19679. s.tempoViewLow = 60.0; // the tempo lane's range
  19680. s.tempoViewHigh = 200.0;
  19681. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& a, const lynx::Clip& b) { return a.start < b.start; });
  19682. // the same audio in the clip grid, for the Clip page
  19683. lynx::Clip slot = audio;
  19684. slot.start = 0;
  19685. slot.pitch = -2.25f;
  19686. slot.gain = 0.7f;
  19687. lynx::launcher::setClip (s, 1, 0, slot);
  19688. // a few warp markers, as Quantize leaves them
  19689. if (channel >= 0 && channel < (int) s.channels.size())
  19690. {
  19691. auto& sampler = s.channels[(std::size_t) channel].sampler;
  19692. lynx::warpedit::ensureMarkers (sampler, 4.0, s.bpm);
  19693. std::vector<double> attacks;
  19694. for (int hit = 1; hit < 8; ++hit)
  19695. attacks.push_back (hit * 0.5 + (hit % 3) * 0.035);
  19696. lynx::warptools::quantize (sampler, attacks, 0.0, 4.0, 0.5, 1.0);
  19697. lynx::warpedit::syncLength (sampler, 4.0);
  19698. }
  19699. }, false);
  19700. offline.dispatchPendingMessages();
  19701. ui.resized();
  19702. write (ui, "arrangement-loop-off");
  19703. offline.editSong ([] (lynx::Song& s) { s.loopOff = false; }, false);
  19704. offline.dispatchPendingMessages();
  19705. write (ui, "arrangement-loop-on");
  19706. juce::String facts;
  19707. {
  19708. const auto& s = offline.getSong();
  19709. facts << "channel " << channel << ", warp markers " << (channel >= 0 ? (int) s.channels[(std::size_t) channel].sampler.warp.size() : -1)
  19710. << ", group bus insert " << lynx::arrange::groupBus (s, 3) << ", folded track 4: " << (lynx::arrange::isFolded (s, 4) ? 1 : 0) << "\n";
  19711. }
  19712. if (auto* detail = ui.getDetailViewForSnapshot())
  19713. {
  19714. detail->showSelection (1, 0);
  19715. detail->setPage (lynx::DetailView::Page::clip);
  19716. offline.dispatchPendingMessages();
  19717. write (ui, "clip-audio");
  19718. }
  19719. if (channel >= 0)
  19720. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  19721. {
  19722. editor->setSize (1120, 600);
  19723. write (*editor, "audio-editor-warp");
  19724. // round 190cy (Live 12.4.16 live check 190cw shot 09): a plain drag of marker 3 holds it two sixteenths
  19725. // later (its audio goes there); Shift + drag slides the audio under it. Round 190db: the Clip-launch
  19726. // workflow draws the warped clip in beats, so the held drag shows the audio stretched around the marker
  19727. // (plain) or slid under it, its attack later (Shift, to the right as in Live's shot)
  19728. const auto& w = offline.getSong().channels[(std::size_t) channel].sampler.warp;
  19729. if (w.size() > 4)
  19730. {
  19731. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].beats + 0.5, false);
  19732. write (*editor, "audio-editor-drag-stretch");
  19733. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].seconds - 0.12, true);
  19734. write (*editor, "audio-editor-drag-slide");
  19735. }
  19736. // the same clip in file time (the Pattern workflow's view, or "Show the audio in beats" off)
  19737. if (auto inFileTime = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  19738. {
  19739. inFileTime->setSize (1120, 600);
  19740. lynx::setAudioEditorBeatTimeForSnapshot (*inFileTime, 0);
  19741. write (*inFileTime, "audio-editor-file-time");
  19742. if (w.size() > 4)
  19743. {
  19744. lynx::holdAudioEditorWarpDragForSnapshot (*inFileTime, 3, w[3].beats + 0.5, false);
  19745. write (*inFileTime, "audio-editor-file-time-drag");
  19746. }
  19747. }
  19748. }
  19749. // round 190cy (Live 12.4.16 live check 190cw shot 02): ÷2 from the editor of the first Playlist clip halves that
  19750. // clip's length with the markers' beats; ÷2 on the grid clip's Clip page halves the grid clip
  19751. {
  19752. const auto lengthOf = [&offline] (int index) { return index < (int) offline.getSong().playlist.size() ? offline.getSong().playlist[(std::size_t) index].length : -1; };
  19753. const auto gridLength = [&offline] {
  19754. const auto& s = offline.getSong();
  19755. const auto* c = s.clipGrid ? lynx::launcher::clipAt (*s.clipGrid, 1, 0) : nullptr;
  19756. return c != nullptr ? c->length : (std::int64_t) -1;
  19757. };
  19758. const auto first = [&offline] {
  19759. const auto& s = offline.getSong();
  19760. for (int i = 0; i < (int) s.playlist.size(); ++i)
  19761. if (s.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  19762. return i;
  19763. return -1;
  19764. }();
  19765. facts << "halve: playlist clip " << first << " length " << lengthOf (first);
  19766. if (first >= 0)
  19767. if (auto editor = lynx::makeAudioEditorPanel (offline, offline.getSong().playlist[(std::size_t) first].channel, first, true))
  19768. {
  19769. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  19770. offline.dispatchPendingMessages();
  19771. }
  19772. facts << " -> " << lengthOf (first) << "; grid clip length " << gridLength();
  19773. if (channel >= 0)
  19774. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, -1, true))
  19775. {
  19776. lynx::setAudioEditorGridClip (*editor, 1, 0);
  19777. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  19778. offline.dispatchPendingMessages();
  19779. }
  19780. facts << " -> " << gridLength() << "\n";
  19781. ui.resized();
  19782. write (ui, "arrangement-halved");
  19783. // Duplicate Time over beats 4-8 holding the locator "Verse" (beat 4): a second "Verse" at beat 8
  19784. offline.editSong ([] (lynx::Song& s) { lynx::arrange::duplicateTime (s, 4 * lynx::ppq, 8 * lynx::ppq); });
  19785. offline.dispatchPendingMessages();
  19786. int verses = 0;
  19787. for (const auto& m : offline.getSong().markers())
  19788. verses += m.name == "Verse" ? 1 : 0;
  19789. facts << "duplicate time: locators named Verse " << verses << "\n";
  19790. write (ui, "arrangement-duplicated-time");
  19791. }
  19792. juce::File (prefix + "-facts.txt").replaceWithText (facts);
  19793. lynx::autolanes::setShown (false);
  19794. }
  19795. void runDetailShot (const juce::String& prefix)
  19796. {
  19797. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19798. lynx::AudioEngine offline (false);
  19799. lynx::MainComponent ui (offline, false);
  19800. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  19801. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  19802. const auto write = [&prefix, &ui] (const char* name) {
  19803. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  19804. file.deleteFile();
  19805. juce::FileOutputStream out (file);
  19806. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  19807. };
  19808. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  19809. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  19810. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  19811. offline.editSong ([] (lynx::Song& s) {
  19812. if (s.channels.size() < 2)
  19813. s.channels.resize (2);
  19814. s.channels[0].name = "Bass synth";
  19815. s.channels[0].mixerTrack = 2;
  19816. s.channels[1].mixerTrack = 3;
  19817. if (s.mixer.size() < 4)
  19818. s.mixer.resize (4);
  19819. s.mixer[2].name = "Bass";
  19820. s.mixer[2].effects.clear();
  19821. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::reverb, lynx::EffectKind::delay })
  19822. {
  19823. lynx::EffectSlot fx;
  19824. fx.kind = kind;
  19825. const auto& info = lynx::effectInfo (kind);
  19826. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  19827. fx.params[k] = info.params[k].defaultValue;
  19828. fx.enabled = kind != lynx::EffectKind::compressor; // one switched off
  19829. s.mixer[2].effects.push_back (fx);
  19830. }
  19831. while (s.patterns.size() < 2)
  19832. s.patterns.emplace_back();
  19833. s.patterns[0].name = "Bass line";
  19834. s.patterns[0].notes.clear();
  19835. for (int n = 0; n < 4; ++n)
  19836. {
  19837. lynx::Note note;
  19838. note.channel = 0;
  19839. note.start = n * lynx::ppq;
  19840. note.key = 36 + (n % 2) * 7;
  19841. s.patterns[0].notes.push_back (note);
  19842. }
  19843. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  19844. lynx::PatternEvents lane; // a volume swell for the Envelopes tab (slice 3)
  19845. lane.target = lynx::AutomationTarget { lynx::AutomationTargetKind::channelVolume, 0 };
  19846. for (int e = 0; e < 16; ++e)
  19847. lane.events.push_back ({ e * lynx::ppq / 4, 0.3f + 0.6f * (float) e / 15.0f });
  19848. s.patterns[0].events = { lane };
  19849. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  19850. s.playlistTracks[1].name = "Bass";
  19851. }, false);
  19852. offline.dispatchPendingMessages();
  19853. write ("pattern"); // Pattern workflow: no detail view exists
  19854. ui.setClipLaunchWorkflow (true);
  19855. offline.editSong ([] (lynx::Song& s) {
  19856. lynx::Clip clip;
  19857. clip.pattern = 0;
  19858. clip.length = 4 * lynx::ppq;
  19859. lynx::launcher::setClip (s, 1, 0, clip);
  19860. }, false);
  19861. offline.dispatchPendingMessages();
  19862. juce::String counts;
  19863. if (auto* detail = ui.getDetailViewForSnapshot())
  19864. {
  19865. detail->showSelection (1, 0);
  19866. detail->setPage (lynx::DetailView::Page::devices);
  19867. write ("devices");
  19868. counts << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << ", channel " << detail->chainChannelForCheck() << "\n";
  19869. detail->toggleFoldForCheck (3); // the reverb (card 0 is the instrument)
  19870. write ("folded");
  19871. counts << "folded card 3: " << (detail->isFoldedForCheck (3) ? 1 : 0) << "\n";
  19872. detail->showSelection (2, 0); // an empty track
  19873. write ("empty-track");
  19874. detail->showSelection (1, 0);
  19875. detail->setPage (lynx::DetailView::Page::clip);
  19876. offline.dispatchPendingMessages();
  19877. ui.getPianoRollForSnapshot().scrollToNotes(); // (the app does it on the message loop, which this shot doesn't run)
  19878. write ("clip"); // slice 2: the Piano roll docked here
  19879. {
  19880. // round 190s: the Transform panel with each MIDI tool, then Arpeggiate applied (and undone again)
  19881. auto& tools = detail->midiToolsForSnapshot();
  19882. for (int t = 0; t < lynx::MidiToolsPanel::toolCount; ++t)
  19883. {
  19884. tools.setTool (t);
  19885. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase()).toRawUTF8());
  19886. }
  19887. // round 190aa: the pages again with the settings of the Live shots they are compared with
  19888. tools.setAuto (false);
  19889. tools.setLiveShotSettingsForSnapshot();
  19890. for (int t : { (int) lynx::MidiToolsPanel::chop, (int) lynx::MidiToolsPanel::quantize, (int) lynx::MidiToolsPanel::timeWarp })
  19891. {
  19892. tools.setTool (t);
  19893. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase() + "-set").toRawUTF8());
  19894. }
  19895. tools.setAuto (true);
  19896. tools.setTool (lynx::MidiToolsPanel::arpeggiate);
  19897. tools.transformNow();
  19898. offline.dispatchPendingMessages();
  19899. write ("clip-mt-applied");
  19900. counts << "midi tools: arpeggiate made " << (int) offline.getSong().patterns[0].notes.size() << " notes of 4\n";
  19901. offline.undo();
  19902. offline.dispatchPendingMessages();
  19903. counts << "midi tools: undo gives " << (int) offline.getSong().patterns[0].notes.size() << " notes\n";
  19904. }
  19905. counts << "piano roll docked: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  19906. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() == detail ? 1 : 0) << "\n";
  19907. detail->setClipTab (true); // slice 3: the pattern's events in the Envelopes tab
  19908. offline.dispatchPendingMessages();
  19909. write ("envelopes");
  19910. detail->setClipTab (false);
  19911. detail->setPage (lynx::DetailView::Page::devices);
  19912. // round 183c-card: an Audio Effect Rack in the chain draws as its own card (the rack's view, Rand / Map in its
  19913. // title bar), as Live's Device View shows a rack
  19914. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.insert (s.mixer[2].effects.begin() + 1, shotRack()); }, false);
  19915. offline.dispatchPendingMessages();
  19916. detail->showSelection (2, 0);
  19917. detail->showSelection (1, 0);
  19918. write ("devices-rack");
  19919. counts << "rack card: cards " << detail->cardCountForCheck() << "\n";
  19920. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.erase (s.mixer[2].effects.begin() + 1); }, false);
  19921. offline.dispatchPendingMessages();
  19922. counts << "piano roll back in its panel: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  19923. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() != detail ? 1 : 0) << "\n";
  19924. }
  19925. else
  19926. counts << "no detail view\n";
  19927. ui.setClipLaunchWorkflow (false);
  19928. offline.dispatchPendingMessages();
  19929. write ("pattern-after");
  19930. juce::File (prefix + "-counts.txt").replaceWithText (counts);
  19931. }
  19932. void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
  19933. {
  19934. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19935. lynx::AudioEngine offline (false);
  19936. {
  19937. lynx::MainComponent ui (offline, false);
  19938. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  19939. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  19940. if (projectPath.isNotEmpty())
  19941. ui.openFile (juce::File (projectPath));
  19942. offline.dispatchPendingMessages();
  19943. // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
  19944. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
  19945. offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
  19946. offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
  19947. offline.dispatchPendingMessages();
  19948. // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
  19949. // and on every other one the next clip waiting for its sync point
  19950. const auto& song = offline.getSong();
  19951. auto& live = offline.performanceStateForSnapshot();
  19952. const auto zone = lynx::perf::zoneClips (song);
  19953. int lastTrack = -1, launched = 0;
  19954. for (const auto index : zone)
  19955. {
  19956. const auto& c = song.playlist[(std::size_t) index];
  19957. if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
  19958. continue;
  19959. lastTrack = c.track;
  19960. std::int64_t clips[64];
  19961. const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
  19962. auto& view = live.tracks[(std::size_t) c.track];
  19963. view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
  19964. view.progress.store (0.2f + 0.15f * (float) (launched % 5));
  19965. if (launched % 2 == 1 && n > 1)
  19966. view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
  19967. ++launched;
  19968. }
  19969. live.anyPlaying.store (launched > 0);
  19970. ui.selectTabForSnapshot (2);
  19971. offline.dispatchPendingMessages();
  19972. auto& playlist = ui.getPlaylistForSnapshot();
  19973. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-song.png");
  19974. playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
  19975. offline.dispatchPendingMessages();
  19976. saveSnapshot (ui, prefix + "-playlist.png");
  19977. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-only.png");
  19978. // patcherize: the first insert with effects (all of them) and the first channel that can be
  19979. auto patched = offline.getSong();
  19980. for (int t = 0; t < (int) patched.mixer.size(); ++t)
  19981. if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
  19982. {
  19983. lynx::patcherize::patcherizeSlots (patched, t, 0, true);
  19984. break;
  19985. }
  19986. for (int c = 0; c < (int) patched.channels.size(); ++c)
  19987. if (lynx::patcherize::patcherizeChannel (patched, c))
  19988. break;
  19989. juce::String error;
  19990. lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
  19991. }
  19992. }
  19993. void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
  19994. {
  19995. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19996. lynx::AudioEngine offline (false);
  19997. {
  19998. lynx::MainComponent ui (offline, false);
  19999. ui.setSize (1280, 720);
  20000. if (projectPath.isNotEmpty())
  20001. ui.openFile (juce::File (projectPath));
  20002. else
  20003. {
  20004. auto song = lynx::Song::makeDefault();
  20005. song.mixer.resize (4);
  20006. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  20007. slot.patcher.wires.clear();
  20008. for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
  20009. { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
  20010. {
  20011. lynx::PatchNode n;
  20012. n.effect = lynx::makeEffectSlot (kind);
  20013. n.x = x;
  20014. n.y = y;
  20015. slot.patcher.nodes.push_back (n);
  20016. }
  20017. { // round 165c: a Hardware Insert node (its editor opens from the node)
  20018. lynx::PatchNode n;
  20019. n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  20020. n.x = 420.0f, n.y = 260.0f;
  20021. slot.patcher.nodes.push_back (n);
  20022. }
  20023. auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
  20024. lynx::PatchWire w;
  20025. w.kind = kind;
  20026. w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
  20027. slot.patcher.wires.push_back (w);
  20028. };
  20029. wire (lynx::patchFromHost, 0, 0, 0);
  20030. wire (0, 1, 1, 0);
  20031. wire (0, 3, 2, 0, 0.5f);
  20032. wire (1, 0, lynx::patchToHost, 0);
  20033. wire (2, 0, lynx::patchToHost, 0);
  20034. wire (lynx::patchFromHost, 1, 3, 0);
  20035. wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  20036. wire (0, 2, lynx::patchToHost, 1, 0.7f);
  20037. // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
  20038. // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
  20039. {
  20040. lynx::SurfaceControl knob;
  20041. knob.name = "Knob 1";
  20042. knob.value = 0.6f;
  20043. slot.patcher.surface = { knob };
  20044. slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
  20045. lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
  20046. lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
  20047. lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
  20048. wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
  20049. wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  20050. }
  20051. slot.patcher.outputTracks = { 3 };
  20052. slot.patcher.inputX = -20.0f;
  20053. slot.patcher.outputX = 660.0f;
  20054. song.mixer[1].effects = { slot };
  20055. lynx::ChannelDef ch;
  20056. ch.name = "Patcher";
  20057. ch.instrument = lynx::InstrumentKind::patcher;
  20058. lynx::PatchNode synth, chorus;
  20059. synth.generator = true;
  20060. synth.channel.instrument = lynx::InstrumentKind::synth;
  20061. synth.channel.name = "Synth";
  20062. synth.x = 220.0f;
  20063. chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
  20064. chorus.x = 420.0f;
  20065. // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
  20066. // on the notes moving the chorus
  20067. lynx::PatchNode midiOut, envelope;
  20068. midiOut.generator = envelope.generator = true;
  20069. midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
  20070. midiOut.channel.name = "MIDI Out";
  20071. lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
  20072. midiOut.x = 220.0f, midiOut.y = 160.0f;
  20073. envelope.channel.instrument = lynx::InstrumentKind::controller;
  20074. envelope.channel.name = "Envelope Controller";
  20075. envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  20076. envelope.x = 220.0f, envelope.y = 260.0f;
  20077. lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
  20078. osc.generator = true;
  20079. osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  20080. osc.channel.instrument = lynx::InstrumentKind::threeosc;
  20081. osc.channel.name = "3x Osc";
  20082. osc.x = 420.0f, osc.y = 260.0f;
  20083. // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
  20084. lynx::PatchNode keys, soundfont, granulizer, dashboard;
  20085. keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
  20086. keys.channel.instrument = lynx::InstrumentKind::controller;
  20087. keys.channel.name = "Keyboard Controller";
  20088. {
  20089. lynx::KeyboardControllerData ramp;
  20090. for (std::size_t k = 0; k < ramp.keys.size(); ++k)
  20091. ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
  20092. lynx::writeKeyboardController (ramp, keys.channel.controllerState);
  20093. }
  20094. soundfont.channel = lynx::sf::makeChannel();
  20095. granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  20096. granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
  20097. granulizer.channel.name = "Fruity Granulizer";
  20098. dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
  20099. dashboard.channel.name = "Dashboard";
  20100. dashboard.channel.patcher.surface = lynx::surface::starterControls();
  20101. keys.x = 20.0f, keys.y = 440.0f;
  20102. soundfont.x = 220.0f, soundfont.y = 440.0f;
  20103. granulizer.x = 420.0f, granulizer.y = 440.0f;
  20104. dashboard.x = 20.0f, dashboard.y = 540.0f;
  20105. // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
  20106. lynx::PatchNode layerNode;
  20107. layerNode.generator = true;
  20108. layerNode.channel.instrument = lynx::InstrumentKind::layer;
  20109. layerNode.channel.name = "Layer";
  20110. layerNode.channel.layer.crossfade = true;
  20111. layerNode.channel.layer.fade = 0.35f;
  20112. layerNode.x = 220.0f, layerNode.y = 540.0f;
  20113. ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
  20114. lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
  20115. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  20116. a.from = 0, a.to = 1;
  20117. b.from = 1;
  20118. portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
  20119. portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
  20120. envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
  20121. envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
  20122. lynx::PatchWire oscNotes, oscOut;
  20123. oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
  20124. oscOut.from = 4;
  20125. lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
  20126. layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
  20127. layerNotes.to = 9;
  20128. layerToFont.from = 9, layerToFont.to = 6;
  20129. layerToGrains.from = 9, layerToGrains.to = 7;
  20130. fontOut.from = 6;
  20131. grainsOut.from = 7;
  20132. ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
  20133. ch.patcher.fromMidiPorts = { 1, 5 };
  20134. ch.patcher.toMidiPorts = { 3 };
  20135. ch.patcher.outputX = 640.0f;
  20136. song.channels.push_back (ch);
  20137. // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
  20138. if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
  20139. {
  20140. if (! song.patterns.empty())
  20141. for (int k = 0; k < 4; ++k)
  20142. 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 });
  20143. juce::String error;
  20144. lynx::ProjectFile::save (song, juce::File (save), error);
  20145. // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
  20146. juce::String report;
  20147. if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
  20148. {
  20149. const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  20150. && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
  20151. const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
  20152. report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
  20153. if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
  20154. {
  20155. const auto& a = song.mixer[1].effects[0].patcher;
  20156. report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
  20157. << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
  20158. for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
  20159. if (! (a.nodes[n] == d.nodes[n]))
  20160. report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
  20161. << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
  20162. << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
  20163. }
  20164. for (int n = 0; n < (int) d.nodes.size(); ++n)
  20165. report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
  20166. << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
  20167. for (const auto& w : d.wires)
  20168. if (w.kind == lynx::PatchWire::Kind::control)
  20169. report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
  20170. for (const auto& p : d.published)
  20171. report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
  20172. }
  20173. else
  20174. report << "patcher round trip: load failed: " << error << "\n";
  20175. juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
  20176. }
  20177. offline.setSong (std::move (song));
  20178. }
  20179. offline.dispatchPendingMessages();
  20180. const auto& song = offline.getSong();
  20181. auto shootOpen = [&] (const juce::String& name) {
  20182. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  20183. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  20184. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  20185. {
  20186. auto* c = w->getContentComponent();
  20187. savePng (lynx::shot::snapshot (*c), prefix + name);
  20188. delete w;
  20189. return;
  20190. }
  20191. };
  20192. int shots = 0;
  20193. for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
  20194. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  20195. if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
  20196. {
  20197. lynx::PatcherWindows::openSlot (offline, t, s);
  20198. shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
  20199. // each built-in node's editor, as a double-click opens it (round 165c)
  20200. lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
  20201. savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
  20202. });
  20203. ++shots;
  20204. if (shots == 1) // its menus (round 162)
  20205. lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
  20206. savePng (image, prefix + "-menu-" + name + ".png");
  20207. });
  20208. }
  20209. for (int c = 0; c < (int) song.channels.size(); ++c)
  20210. if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
  20211. {
  20212. lynx::PatcherWindows::openChannel (offline, c);
  20213. shootOpen ("-channel" + juce::String (c) + ".png");
  20214. // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
  20215. lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
  20216. savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
  20217. });
  20218. lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
  20219. savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
  20220. });
  20221. }
  20222. }
  20223. }
  20224. // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
  20225. struct TypeAheadTest final : private juce::Timer
  20226. {
  20227. juce::File out;
  20228. juce::StringArray log;
  20229. int step = 0, picked = 0;
  20230. bool ok = true, menuShown = false;
  20231. std::unique_ptr<juce::DocumentWindow> owner;
  20232. juce::PopupMenu pending;
  20233. static juce::String highlighted()
  20234. {
  20235. if (auto* window = juce::Component::getCurrentlyModalComponent())
  20236. for (auto* child : window->getChildren())
  20237. if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
  20238. return h->getTitle();
  20239. return "(none)";
  20240. }
  20241. static void press (const juce::KeyPress& key)
  20242. {
  20243. if (auto* window = juce::Component::getCurrentlyModalComponent())
  20244. if (auto* peer = window->getPeer())
  20245. peer->handleKeyPress (key);
  20246. }
  20247. void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
  20248. {
  20249. const auto good = got == wanted;
  20250. ok = ok && good;
  20251. log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
  20252. }
  20253. void start()
  20254. {
  20255. juce::PopupMenu menu, sub;
  20256. auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
  20257. m.addItem (text, enabled, false, [this, id] { picked = id; });
  20258. };
  20259. menu.addSectionHeader ("LYNX SHARE");
  20260. item (menu, 1, "Echoform");
  20261. item (menu, 2, "EQ");
  20262. item (menu, 3, "Halo");
  20263. menu.addSectionHeader ("Misc");
  20264. item (menu, 4, "Effector");
  20265. item (menu, 5, "Exciter (unavailable)", false);
  20266. item (sub, 10, "Delay");
  20267. item (sub, 11, "Edison");
  20268. item (sub, 12, "Eventide");
  20269. menu.addSubMenu ("Tree", sub);
  20270. // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
  20271. // menu of a background process at once)
  20272. owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
  20273. owner->setBounds (200, 200, 300, 200);
  20274. owner->setVisible (true);
  20275. lynx::forceForegroundForTest (*owner);
  20276. pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
  20277. startTimer (300);
  20278. }
  20279. void timerCallback() override
  20280. {
  20281. const auto e = juce::KeyPress ('e', {}, 'e');
  20282. if (step == 0 && owner != nullptr && ! menuShown)
  20283. {
  20284. menuShown = true;
  20285. lynx::forceForegroundForTest (*owner);
  20286. lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
  20287. return;
  20288. }
  20289. switch (step++)
  20290. {
  20291. case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
  20292. case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
  20293. case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
  20294. case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
  20295. case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
  20296. case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
  20297. case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
  20298. case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
  20299. case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
  20300. case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
  20301. case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
  20302. case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
  20303. case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
  20304. case 13: break;
  20305. default:
  20306. expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
  20307. expect ("Enter picked", juce::String (picked), "12");
  20308. stopTimer();
  20309. owner.reset();
  20310. log.add (ok ? "result=OK" : "result=FAIL");
  20311. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  20312. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  20313. juce::JUCEApplication::quit();
  20314. return;
  20315. }
  20316. }
  20317. };
  20318. std::unique_ptr<TypeAheadTest> typeAheadTest;
  20319. struct ChooserTest final : private juce::Timer
  20320. {
  20321. juce::File out, file;
  20322. juce::StringArray log;
  20323. std::unique_ptr<juce::FileChooser> chooser;
  20324. double started = 0;
  20325. bool shot = false, done = false;
  20326. void start()
  20327. {
  20328. log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
  20329. log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  20330. chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
  20331. started = juce::Time::getMillisecondCounterHiRes();
  20332. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  20333. [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
  20334. startTimer (200);
  20335. }
  20336. static juce::FileChooserDialogBox* builtInDialog()
  20337. {
  20338. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
  20339. if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
  20340. return box;
  20341. return nullptr;
  20342. }
  20343. static juce::FileBrowserComponent* findBrowser (juce::Component& c)
  20344. {
  20345. if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
  20346. return b;
  20347. for (auto* child : c.getChildren())
  20348. if (auto* b = findBrowser (*child))
  20349. return b;
  20350. return nullptr;
  20351. }
  20352. void timerCallback() override
  20353. {
  20354. if (done)
  20355. return;
  20356. if (auto* box = builtInDialog(); box != nullptr && ! shot)
  20357. {
  20358. shot = true;
  20359. log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
  20360. const auto image = lynx::shot::snapshot (*box);
  20361. juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
  20362. if (png.openedOk())
  20363. {
  20364. png.setPosition (0), png.truncate();
  20365. juce::PNGImageFormat().writeImageToStream (image, png);
  20366. }
  20367. if (auto* browser = findBrowser (*box))
  20368. {
  20369. browser->setRoot (file.getParentDirectory());
  20370. browser->setFileName (file.getFileName());
  20371. log.add ("typed " + file.getFileName());
  20372. box->exitModalState (1);
  20373. }
  20374. else
  20375. log.add ("no file browser in the dialog");
  20376. }
  20377. if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
  20378. finish ({}, "timeout");
  20379. }
  20380. void finish (const juce::File& result, const juce::String& why = {})
  20381. {
  20382. if (done)
  20383. return;
  20384. done = true;
  20385. stopTimer();
  20386. log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
  20387. + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
  20388. log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  20389. const auto ok = result == file && result.existsAsFile();
  20390. log.add (ok ? "result=OK" : "result=FAIL");
  20391. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  20392. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  20393. juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
  20394. }
  20395. };
  20396. std::unique_ptr<ChooserTest> chooserTest;
  20397. void runChooserTest (const juce::File& out, const juce::File& file)
  20398. {
  20399. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20400. chooserTest = std::make_unique<ChooserTest>();
  20401. chooserTest->out = out;
  20402. chooserTest->file = file;
  20403. chooserTest->start();
  20404. }
  20405. void runTypeAheadTest (const juce::File& out)
  20406. {
  20407. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20408. typeAheadTest = std::make_unique<TypeAheadTest>();
  20409. typeAheadTest->out = out;
  20410. typeAheadTest->start();
  20411. }
  20412. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  20413. {
  20414. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20415. // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
  20416. if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
  20417. if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
  20418. lynx::themeui::apply (*spec, false);
  20419. {
  20420. lynx::AudioEngine offline (false);
  20421. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  20422. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  20423. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  20424. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  20425. if (projectPath.isNotEmpty())
  20426. ui.openFile (juce::File (projectPath));
  20427. offline.dispatchPendingMessages(); // change notifications are asynchronous
  20428. ui.waitForBrowserForSnapshot();
  20429. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  20430. // (and a sample hint in the status strip, as when hovering a knob)
  20431. ui.showDesktopForSnapshot (false);
  20432. ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
  20433. offline.dispatchPendingMessages();
  20434. saveSnapshot (ui, prefix + "-desktop.png");
  20435. // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
  20436. {
  20437. const auto size = ui.getBounds();
  20438. ui.showSetupWizard();
  20439. offline.dispatchPendingMessages();
  20440. saveSnapshot (ui, prefix + "-desktop-setup.png");
  20441. ui.setSize (1024, 600);
  20442. offline.dispatchPendingMessages();
  20443. saveSnapshot (ui, prefix + "-desktop-setup-small.png");
  20444. ui.closeSetupWizardForSnapshot();
  20445. ui.setBounds (size);
  20446. offline.dispatchPendingMessages();
  20447. }
  20448. // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
  20449. // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
  20450. {
  20451. const auto size = ui.getBounds();
  20452. for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
  20453. {
  20454. ui.setSize (w, h);
  20455. offline.dispatchPendingMessages();
  20456. saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
  20457. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
  20458. if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
  20459. {
  20460. ui.scrollRackForSnapshot (100000);
  20461. offline.dispatchPendingMessages();
  20462. saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
  20463. ui.scrollRackForSnapshot (0);
  20464. }
  20465. }
  20466. // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
  20467. ui.setSize (1600, 900);
  20468. for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
  20469. {
  20470. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  20471. layout.iconSize = iconSize;
  20472. ui.setToolbarLayoutForSnapshot (layout);
  20473. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
  20474. }
  20475. {
  20476. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  20477. layout.move (lynx::toolbarlayout::Group::windows, -3);
  20478. layout.setShown (lynx::toolbarlayout::Group::record, false);
  20479. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  20480. ui.setToolbarLayoutForSnapshot (layout);
  20481. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
  20482. }
  20483. {
  20484. // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
  20485. ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
  20486. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  20487. lynx::AutomationTarget t;
  20488. t.kind = lynx::AutomationTargetKind::mixerVolume;
  20489. t.index = 0;
  20490. offline.noteTweaked (t);
  20491. ui.refreshTweakReadoutForSnapshot();
  20492. offline.dispatchPendingMessages();
  20493. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
  20494. ui.setSize (1600, 900);
  20495. }
  20496. {
  20497. // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
  20498. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  20499. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  20500. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  20501. ui.setToolbarLayoutForSnapshot (layout);
  20502. ui.setToolbarEditingForSnapshot (true);
  20503. offline.dispatchPendingMessages();
  20504. saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
  20505. ui.setToolbarEditingForSnapshot (false);
  20506. // Ctrl+F11: only the menu and the hint bar
  20507. layout = lynx::toolbarlayout::Layout::makeDefault();
  20508. layout.visible = false;
  20509. ui.setToolbarLayoutForSnapshot (layout);
  20510. saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
  20511. }
  20512. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  20513. // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
  20514. offline.dispatchPendingMessages();
  20515. saveQuickTips (ui, prefix);
  20516. ui.setBounds (size);
  20517. offline.dispatchPendingMessages();
  20518. }
  20519. // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
  20520. // glyphs, and a text too long for one line (two lines)
  20521. {
  20522. const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
  20523. const lynx::ui::Hint hints[] = {
  20524. { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
  20525. { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
  20526. { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  20527. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
  20528. };
  20529. for (int i = 0; i < 3; ++i)
  20530. {
  20531. ui.setHintForSnapshot (hints[i], i == 0);
  20532. saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
  20533. }
  20534. }
  20535. ui.showDesktopForSnapshot (true);
  20536. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  20537. saveSnapshot (ui, prefix + "-desktop-all.png");
  20538. ui.selectTabForSnapshot (0);
  20539. saveSnapshot (ui, prefix + "-rack.png");
  20540. {
  20541. // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
  20542. int found = -1;
  20543. const auto before = offline.getSong().currentPattern;
  20544. {
  20545. const auto& song = offline.getSong();
  20546. for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
  20547. for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
  20548. if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
  20549. found = p;
  20550. }
  20551. if (found >= 0)
  20552. {
  20553. offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
  20554. offline.dispatchPendingMessages();
  20555. saveSnapshot (ui, prefix + "-rack-preview.png");
  20556. offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
  20557. offline.dispatchPendingMessages();
  20558. }
  20559. }
  20560. ui.selectTabForSnapshot (1);
  20561. saveSnapshot (ui, prefix + "-pianoroll.png");
  20562. {
  20563. // View › Keyboard style › Piano keys (round 190j, discussion #136), also with tall keys
  20564. auto& roll = ui.getPianoRollForSnapshot();
  20565. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  20566. roll.repaint();
  20567. saveSnapshot (ui, prefix + "-pianoroll-pianokeys.png");
  20568. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::flat;
  20569. roll.repaint();
  20570. // round 190j (discussion #10): the toolbar in a narrow window: the chord stamp as an icon button, and
  20571. // the menu button still there
  20572. for (int narrower : { 150, 270, 330 })
  20573. {
  20574. roll.squeezeToolbarForSnapshot (narrower);
  20575. saveSnapshot (ui, prefix + "-pianoroll-narrow" + juce::String (narrower) + ".png");
  20576. roll.squeezeToolbarForSnapshot (-narrower);
  20577. }
  20578. }
  20579. if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
  20580. saveArea (ui, strip, prefix + "-pianoroll-tools.png");
  20581. // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
  20582. ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
  20583. saveSnapshot (ui, prefix + "-pianoroll-hover.png");
  20584. {
  20585. // a pattern with note Chance or a Velocity Range (round 187c): the Piano roll with those lanes
  20586. const auto& song = offline.getSong();
  20587. const auto& notes = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)].notes;
  20588. if (std::any_of (notes.begin(), notes.end(), [] (const lynx::Note& n) { return n.hasChance(); }))
  20589. {
  20590. auto& roll = ui.getPianoRollForSnapshot();
  20591. ui.setHintForSnapshot ({});
  20592. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneChance, "chance" },
  20593. { lynx::PianoRollComponent::laneVelocityRange, "velrange" },
  20594. { lynx::PianoRollComponent::laneVelocity, "velocity" } })
  20595. {
  20596. roll.setLaneForSnapshot (lane);
  20597. offline.dispatchPendingMessages();
  20598. saveSnapshot (ui, prefix + "-pianoroll-" + name + ".png");
  20599. }
  20600. }
  20601. }
  20602. ui.selectTabForSnapshot (2);
  20603. saveSnapshot (ui, prefix + "-playlist.png");
  20604. if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
  20605. saveArea (ui, strip, prefix + "-playlist-tools.png");
  20606. ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
  20607. saveSnapshot (ui, prefix + "-playlist-hover.png");
  20608. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  20609. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  20610. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  20611. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  20612. offline.dispatchPendingMessages();
  20613. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  20614. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  20615. // round 177b: automation lanes on (two lanes under track 2: a volume ramp and a pan wobble)
  20616. {
  20617. const auto before = offline.getSong();
  20618. offline.editSong ([] (lynx::Song& s) {
  20619. s.loopStart = s.loopEnd = 0; // (no time selection in this one)
  20620. const auto bar = s.barTicks();
  20621. const auto vol = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Insert 1 - Volume", 0.3f);
  20622. s.automations[(std::size_t) vol].points = { { 0, 0.3f, 0.0f }, { bar * 2, 0.8f, 0.4f }, { bar * 4, 0.6f, 0.0f } };
  20623. const auto pan = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, "Insert 1 - Pan", 0.5f);
  20624. 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 } };
  20625. }, false);
  20626. lynx::autolanes::setShown (true);
  20627. ui.getPlaylistForSnapshot().resized();
  20628. offline.dispatchPendingMessages();
  20629. saveSnapshot (ui, prefix + "-playlist-lanes.png");
  20630. lynx::autolanes::setShown (false);
  20631. offline.editSong ([before] (lynx::Song& s) { s = before; }, false);
  20632. offline.dispatchPendingMessages();
  20633. }
  20634. // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
  20635. {
  20636. int header = -1;
  20637. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
  20638. if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
  20639. header = t;
  20640. if (header >= 0)
  20641. {
  20642. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
  20643. offline.dispatchPendingMessages();
  20644. saveSnapshot (ui, prefix + "-playlist-group-folded.png");
  20645. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
  20646. }
  20647. ui.getPickerForSnapshot().setView (1);
  20648. offline.dispatchPendingMessages();
  20649. saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
  20650. ui.getPickerForSnapshot().setView (0);
  20651. }
  20652. // round 104: the Channel Rack filtered to its first filter group
  20653. if (! offline.getSong().channelGroups.empty())
  20654. {
  20655. ui.selectTabForSnapshot (0);
  20656. ui.getRackForSnapshot().setFilterGroup (0);
  20657. offline.dispatchPendingMessages();
  20658. saveSnapshot (ui, prefix + "-rack-filter.png");
  20659. ui.getRackForSnapshot().setFilterGroup (-1);
  20660. }
  20661. ui.selectTabForSnapshot (3);
  20662. // LYNX_SNAPSHOT_ARRANGE=1 (round 186c): Mixer menu › "Arrange inserts like the Playlist" first
  20663. if (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_ARRANGE", {}) == "1")
  20664. {
  20665. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::arrangeLikePlaylist (s); });
  20666. offline.dispatchPendingMessages();
  20667. }
  20668. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  20669. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  20670. {
  20671. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  20672. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  20673. offline.dispatchPendingMessages();
  20674. }
  20675. saveSnapshot (ui, prefix + "-mixer.png");
  20676. // round 190am: LYNX's two mixer extras, before and after (the demo project leaves most inserts unused). The
  20677. // loudness panel shows a real measurement of 12 s of a test tone (a 1 kHz sine at -14 dBFS after a quieter
  20678. // stretch, pushed through the Master's tap as the audio thread does)
  20679. {
  20680. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  20681. saveSnapshot (ui, prefix + "-mixer190am-before.png");
  20682. strips.setShowUsedOnly (true);
  20683. offline.dispatchPendingMessages();
  20684. saveSnapshot (ui, prefix + "-mixer190am-usedonly.png");
  20685. strips.setShowUsedOnly (false);
  20686. strips.setShowLoudness (true);
  20687. {
  20688. const double sr = 48000.0;
  20689. std::vector<float> tone (480);
  20690. auto& tap = offline.getMeters().loudness;
  20691. for (int block = 0; block < 1200; ++block)
  20692. {
  20693. const auto gain = std::pow (10.0, (block < 400 ? -20.0 : -14.0) / 20.0);
  20694. for (int i = 0; i < 480; ++i)
  20695. tone[(std::size_t) i] = (float) (gain * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * (block * 480 + i) / sr));
  20696. tap.push (tone.data(), tone.data(), 480, sr);
  20697. }
  20698. }
  20699. strips.refreshLoudnessForSnapshot();
  20700. offline.dispatchPendingMessages();
  20701. saveSnapshot (ui, prefix + "-mixer190am-loudness.png");
  20702. for (const auto l : { lynx::mixerlayout::Layout::compact, lynx::mixerlayout::Layout::extraLarge })
  20703. {
  20704. const auto was = lynx::MixerStrips::layout;
  20705. strips.setLayout (l);
  20706. offline.dispatchPendingMessages();
  20707. saveSnapshot (ui, prefix + "-mixer190am-loudness-" + juce::String ((int) l) + ".png");
  20708. strips.setLayout (was);
  20709. }
  20710. strips.setShowUsedOnly (true);
  20711. offline.dispatchPendingMessages();
  20712. saveSnapshot (ui, prefix + "-mixer190am-both.png");
  20713. strips.setShowUsedOnly (false);
  20714. strips.setShowLoudness (false);
  20715. offline.dispatchPendingMessages();
  20716. }
  20717. // round 168h (issue #52): FL's 8 Mixer layouts
  20718. {
  20719. const auto before = lynx::MixerStrips::layout;
  20720. for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
  20721. {
  20722. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
  20723. offline.dispatchPendingMessages();
  20724. saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
  20725. }
  20726. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
  20727. offline.dispatchPendingMessages();
  20728. }
  20729. // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
  20730. {
  20731. const auto size = ui.getBounds();
  20732. for (auto h : { 450, 560, 680, 820 })
  20733. {
  20734. ui.setSize (size.getWidth(), h);
  20735. offline.dispatchPendingMessages();
  20736. saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
  20737. }
  20738. ui.setBounds (size);
  20739. offline.dispatchPendingMessages();
  20740. }
  20741. // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
  20742. // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
  20743. {
  20744. const auto before = offline.getSong();
  20745. offline.editSong ([] (lynx::Song& s) {
  20746. if (s.mixer.size() < 5)
  20747. return;
  20748. s.mixer[1].effects.clear();
  20749. lynx::EffectSlot fx;
  20750. fx.kind = lynx::EffectKind::compressor;
  20751. s.mixer[1].effects.push_back (fx);
  20752. lynx::mixerops::moveEffectBy (s, 1, 0, 1);
  20753. lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
  20754. });
  20755. ui.selectMixerTrackForSnapshot (1);
  20756. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
  20757. offline.dispatchPendingMessages();
  20758. saveSnapshot (ui, prefix + "-mixer170b.png");
  20759. juce::PopupMenu effects, generators;
  20760. lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
  20761. lynx::quickpick::addFolderViewItems (effects, offline);
  20762. lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  20763. lynx::quickpick::addFolderViewItems (generators, offline);
  20764. saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
  20765. // round 190bf (fl190be Q3): the Channel Rack's "+" menu in FL's three views, with two root entries (plugins
  20766. // at the top of the database, in no folder) and the Categories / Simple / Tree switch at the end
  20767. {
  20768. auto& host = offline.getPluginHost();
  20769. const auto keep = host.databaseFolders();
  20770. auto folders = keep;
  20771. int added = 0;
  20772. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  20773. if (e.folder == 3 && e.available && added < 2) // (installed plugins: FL's root entries are such)
  20774. {
  20775. folders.top.insert (e.key);
  20776. ++added;
  20777. }
  20778. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  20779. if (e.folder != 3 && added < 2)
  20780. {
  20781. folders.top.insert (e.key);
  20782. ++added;
  20783. }
  20784. static const char* const views[] { "categories", "simple", "tree" };
  20785. for (int v = 0; v < 3; ++v)
  20786. {
  20787. folders.view = v;
  20788. host.setDatabaseFolders (folders);
  20789. juce::PopupMenu plus;
  20790. lynx::quickpick::addGeneratorMenu (plus, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  20791. lynx::quickpick::addFolderViewItems (plus, offline);
  20792. saveMenus (juce::StringArray { juce::String ("Channel Rack +: ") + views[v] }, { plus }, prefix + "-menus190bf-" + views[v] + ".png");
  20793. }
  20794. host.setDatabaseFolders (keep);
  20795. }
  20796. offline.setSong (before);
  20797. offline.dispatchPendingMessages();
  20798. }
  20799. // standalone windows, with the theme background
  20800. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  20801. juce::Component frame;
  20802. frame.setSize (c->getWidth(), c->getHeight());
  20803. frame.setOpaque (true);
  20804. // an AlertWindow is built on the desktop: shown there first, it would take the foreground from whoever has it
  20805. // (TopLevelWindow::visibilityChanged calls toFront (true)). Off the desktop, its control that showing it would
  20806. // have focused (what grabKeyboardFocus picks) is marked, so the picture keeps that control's focus ring
  20807. if (c->isOnDesktop())
  20808. {
  20809. c->removeFromDesktop();
  20810. auto* focus = c.get();
  20811. for (int depth = 0; focus != nullptr && depth < 32; ++depth)
  20812. {
  20813. if (focus->getWantsKeyboardFocus() && (focus->isEnabled() || focus == c.get()))
  20814. {
  20815. focus->getProperties().set ("lynxSnapshotFocus", true);
  20816. break;
  20817. }
  20818. auto traverser = focus->createKeyboardFocusTraverser();
  20819. focus = traverser != nullptr ? traverser->getDefaultComponent (focus) : nullptr;
  20820. }
  20821. }
  20822. frame.addAndMakeVisible (*c);
  20823. c->setTopLeftPosition (0, 0);
  20824. checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
  20825. auto image = lynx::shot::paint (frame, lynx::theme::panel);
  20826. const auto file = lynx::shot::file (juce::File (prefix + name));
  20827. file.deleteFile();
  20828. juce::PNGImageFormat png;
  20829. if (auto out = file.createOutputStream())
  20830. png.writeImageToStream (image, *out);
  20831. };
  20832. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  20833. saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
  20834. saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
  20835. {
  20836. // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
  20837. // Export window for "Render selected tracks to wave file(s)"
  20838. const auto before = offline.getSong();
  20839. offline.editSong ([] (lynx::Song& s) {
  20840. if (s.mixer.size() > 3)
  20841. {
  20842. s.mixer[1].latencyMs = 5.0f;
  20843. s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  20844. s.mixer[2].latencyMs = -1.5f;
  20845. }
  20846. });
  20847. offline.dispatchPendingMessages();
  20848. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  20849. strips.setSelection ({ 1, 2, 3 }, 1);
  20850. const auto menu = strips.buildMenu (1);
  20851. juce::StringArray names { "Mixer track" };
  20852. std::vector<juce::PopupMenu> menus { menu };
  20853. const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
  20854. const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
  20855. lynx::tr ("Plugin delay compensation") };
  20856. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  20857. {
  20858. const auto& item = it.getItem();
  20859. if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
  20860. {
  20861. names.add (item.text.upToFirstOccurrenceOf (":", false, false));
  20862. menus.push_back (*item.subMenu);
  20863. }
  20864. }
  20865. saveMenus (names, menus, prefix + "-menus165-mixer.png");
  20866. saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
  20867. offline.setSong (before);
  20868. offline.dispatchPendingMessages();
  20869. }
  20870. saveSplashFrames (prefix);
  20871. saveIconSheet (prefix + "-icons.png", 1.0f);
  20872. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  20873. saveWindow (lynx::MainComponent::makeHelpContent(), "-help.png");
  20874. saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
  20875. saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
  20876. // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
  20877. offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
  20878. offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
  20879. saveMenus (ui, prefix + "-menus.png");
  20880. {
  20881. // the windows' own menus (title bars) and the toolbar's recording menu
  20882. juce::StringArray names;
  20883. std::vector<juce::PopupMenu> menus;
  20884. for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
  20885. { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
  20886. { lynx::workspace::Panel::browser, "Browser" } })
  20887. {
  20888. names.add (name);
  20889. menus.push_back (ui.getPanelMenuForSnapshot (panel));
  20890. }
  20891. names.add ("Recording");
  20892. menus.push_back (ui.getRecordMenuForSnapshot());
  20893. names.add ("Toolbar");
  20894. menus.push_back (ui.getToolbarMenuForSnapshot());
  20895. saveMenus (names, menus, prefix + "-panel-menus.png");
  20896. }
  20897. // round 189e: the Playlist menu's Edit and Select submenus (FL's items and order) and the header drop question
  20898. saveMenus (juce::StringArray { "Playlist: Edit", "Playlist: Select" },
  20899. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().editMenu(), ui.getPlaylistForSnapshot().selectMenu() },
  20900. prefix + "-playlist-edit189e.png");
  20901. saveWindow (lynx::PlaylistComponent::makeHeaderDropDialog(), "-header-drop189e.png");
  20902. {
  20903. // round 189i: FL's fade handle menu (right-click on an audio clip's fade handle), on the song's first audio
  20904. // clip, or on one added for the shot
  20905. const auto before = offline.getSong();
  20906. auto clipIndex = -1;
  20907. for (std::size_t i = 0; i < before.playlist.size() && clipIndex < 0; ++i)
  20908. if (before.playlist[i].kind == lynx::ClipKind::audio)
  20909. clipIndex = (int) i;
  20910. if (clipIndex < 0)
  20911. {
  20912. auto song = before;
  20913. lynx::ChannelDef channel;
  20914. channel.instrument = lynx::InstrumentKind::audioClip;
  20915. channel.name = "Audio clip";
  20916. song.channels.push_back (channel);
  20917. lynx::Clip clip;
  20918. clip.kind = lynx::ClipKind::audio;
  20919. clip.channel = (int) song.channels.size() - 1;
  20920. clip.length = lynx::ppq * 4;
  20921. song.playlist.push_back (clip);
  20922. clipIndex = (int) song.playlist.size() - 1;
  20923. offline.setSong (song);
  20924. offline.dispatchPendingMessages();
  20925. }
  20926. saveMenus (juce::StringArray { "Fade handle" },
  20927. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().fadeHandleMenu (clipIndex, 1) },
  20928. prefix + "-fade-handle189i.png");
  20929. if (offline.getSong().playlist.size() != before.playlist.size())
  20930. {
  20931. offline.setSong (before);
  20932. offline.dispatchPendingMessages();
  20933. }
  20934. }
  20935. {
  20936. // round 189n: FL's gain handle menu with two overlapping clips selected (Normalize selection individually / as a
  20937. // group) and the later clip's fade in menu (Create crossfade enabled); FL shots in /mnt/e/lynx-work/flgap189n
  20938. const auto before = offline.getSong();
  20939. auto song = before;
  20940. lynx::ChannelDef channel;
  20941. channel.instrument = lynx::InstrumentKind::audioClip;
  20942. channel.name = "Audio clip";
  20943. song.channels.push_back (channel);
  20944. int lane = 0;
  20945. for (const auto& c : song.playlist)
  20946. lane = std::max (lane, c.track + 1);
  20947. for (int k = 0; k < 2; ++k)
  20948. {
  20949. lynx::Clip clip;
  20950. clip.kind = lynx::ClipKind::audio;
  20951. clip.channel = (int) song.channels.size() - 1;
  20952. clip.track = lane;
  20953. clip.start = k * lynx::ppq * 3;
  20954. clip.length = lynx::ppq * 4;
  20955. song.playlist.push_back (clip);
  20956. }
  20957. const auto second = (int) song.playlist.size() - 1;
  20958. song.autoCrossfades = true; // FL's capture: Thief has Automatic crossfades on
  20959. offline.setSong (song);
  20960. offline.dispatchPendingMessages();
  20961. auto& playlist = ui.getPlaylistForSnapshot();
  20962. playlist.selectForSnapshot ({ second - 1, second });
  20963. auto gain = playlist.gainMenu (second);
  20964. auto fadeIn = playlist.fadeHandleMenu (second, 0); // (both selected, as in FL's capture)
  20965. playlist.selectForSnapshot ({});
  20966. saveMenus (juce::StringArray { "Gain handle, 2 selected", "Fade in, overlapping" },
  20967. std::vector<juce::PopupMenu> { gain, fadeIn }, prefix + "-fade-gain189n.png");
  20968. // round 189o: the audio clip menu with both overlapping clips selected (FL's Fades › Crossfade selected
  20969. // shown) and with none selected (hidden)
  20970. playlist.selectForSnapshot ({ second - 1, second });
  20971. auto clipSelected = playlist.getClipMenuForSnapshot (second);
  20972. playlist.selectForSnapshot ({});
  20973. auto clipAlone = playlist.getClipMenuForSnapshot (second);
  20974. saveMenus (juce::StringArray { "Audio clip, 2 selected", "Audio clip, none selected" },
  20975. std::vector<juce::PopupMenu> { clipSelected, clipAlone }, prefix + "-xfadesel189o.png");
  20976. offline.setSong (before);
  20977. offline.dispatchPendingMessages();
  20978. }
  20979. {
  20980. // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
  20981. std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
  20982. ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
  20983. ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
  20984. saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
  20985. // round 190as: the Piano roll's scripts (FL's Tools › Scripts column) and a script's form
  20986. saveMenus (juce::StringArray { "Piano roll scripts" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getScriptsMenuForSnapshot() },
  20987. prefix + "-prscripts-menu.png");
  20988. {
  20989. lynx::prscript::Score score;
  20990. const auto out = lynx::prscript::run (lynx::prscript::builtins().front().source, score, {});
  20991. if (out.status == lynx::prscript::Outcome::Status::needsForm)
  20992. {
  20993. lynx::ScriptPanel::Options options;
  20994. options.acceptText = lynx::tr ("Accept");
  20995. saveWindow (std::make_unique<lynx::ScriptPanel> (out.form, [] (const lynx::scriptform::Form&) {}, [] (const lynx::scriptform::Form&) {},
  20996. nullptr, options),
  20997. "-prscript-form.png");
  20998. }
  20999. }
  21000. // round 190j (discussion #10): the Piano roll menu's Chord stamp list
  21001. saveMenus (juce::StringArray { "Chord stamp" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getStampMenuForSnapshot() },
  21002. prefix + "-stamp-menu.png");
  21003. // round 167l: the channel menu ("Lock active/mute state")
  21004. if (! offline.getSong().channels.empty())
  21005. saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
  21006. // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
  21007. {
  21008. juce::PopupMenu folder;
  21009. folder.addSectionHeader ("Documents");
  21010. folder.addItem (1, "Expand all");
  21011. folder.addItem (2, "Collapse all");
  21012. folder.addSeparator();
  21013. folder.addItem (3, "Refresh");
  21014. folder.addSectionHeader ("System");
  21015. folder.addItem (4, "Open");
  21016. folder.addItem (5, "Copy the file path");
  21017. folder.addSectionHeader ("Tags");
  21018. folder.addItem (6, "Starred", true, true);
  21019. folder.addSeparator();
  21020. folder.addItem (7, "Add folder...");
  21021. const auto wasCompact = lynx::theme::menus::compact();
  21022. lynx::theme::menus::setCompact (true);
  21023. saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
  21024. lynx::theme::menus::setCompact (false);
  21025. saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
  21026. lynx::theme::menus::setCompact (wasCompact);
  21027. }
  21028. // and the clip menus of the first pattern, audio and automation clips of the project
  21029. juce::StringArray clipNames;
  21030. std::vector<juce::PopupMenu> clipMenus;
  21031. for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
  21032. { lynx::ClipKind::automation, "Automation clip" } })
  21033. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  21034. if (offline.getSong().playlist[(std::size_t) c].kind == kind)
  21035. {
  21036. clipNames.add (name);
  21037. clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
  21038. break;
  21039. }
  21040. if (! clipMenus.empty())
  21041. saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
  21042. }
  21043. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  21044. alert->setOpaque (true);
  21045. saveWindow (std::move (alert), name);
  21046. };
  21047. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  21048. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  21049. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  21050. saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
  21051. // round 190ah: Online Sessions — a guest's "go back in?" at start-up, the host's question at a guest's file limit
  21052. saveAlert (lynx::liveui::makeRejoinDialog ("Ana", juce::Time (2026, 10, 10, 21, 40).toString (true, true, false, true)), "-live-rejoin.png");
  21053. saveAlert (lynx::liveui::makeMediaLimitDialog ("Pedro", (juce::int64) 1010 << 20, (juce::int64) 1 << 30), "-live-media-limit.png");
  21054. saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
  21055. saveAlert (lynx::makeGradientColourDialog (juce::Colour (0xffe5383b), juce::Colour (0xff3a7bd5), 8), "-gradient.png"); // round 177a
  21056. saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
  21057. // round 186c: FL's mixer "Delete" questions and its Settings › General › Manage messages menu
  21058. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Delete tracks"), lynx::tr ("This will |delete| {0} selected mixer track(s). Are you sure?", { "1" }),
  21059. { lynx::tr ("Yes"), lynx::tr ("No") }, true }),
  21060. "-delete-tracks.png");
  21061. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Playlist tracks"),
  21062. lynx::tr ("One or more mixer tracks that will be deleted are connected to instrument/audio tracks.") + "\n"
  21063. + lynx::tr ("Do you want to unlink the tracks and channels or delete them?"),
  21064. { lynx::tr ("Delete tracks and channels"), lynx::tr ("Unlink tracks and channels"), lynx::tr ("Cancel") }, false }),
  21065. "-delete-tracks-linked.png");
  21066. saveMenus (juce::StringArray { "Manage messages" }, std::vector<juce::PopupMenu> { lynx::messages::manageMenu() }, prefix + "-manage-messages.png");
  21067. saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
  21068. saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
  21069. saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
  21070. // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
  21071. {
  21072. struct Bars final : juce::Component
  21073. {
  21074. Bars()
  21075. {
  21076. constexpr int h = lynx::updater::UpdateBar::height;
  21077. setSize (1100, 4 * (h + 6));
  21078. for (int state = 0; state < 4; ++state)
  21079. {
  21080. bars[state].setBounds (0, state * (h + 6), getWidth(), h);
  21081. bars[state].showForSnapshot (state);
  21082. addAndMakeVisible (bars[state]);
  21083. }
  21084. }
  21085. lynx::updater::UpdateBar bars[4];
  21086. };
  21087. saveWindow (std::make_unique<Bars>(), "-update-bar.png");
  21088. saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
  21089. }
  21090. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
  21091. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
  21092. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
  21093. {
  21094. // the Settings pages, with credits like a project imported from FL would carry
  21095. offline.editSong ([] (lynx::Song& s) {
  21096. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  21097. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  21098. }, false);
  21099. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
  21100. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
  21101. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
  21102. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
  21103. {
  21104. // round 189o: the whole General page (the Editing and Plugins sections hold FL's "Monophonic painting in
  21105. // piano roll" and "Limit the number of open plugin editors")
  21106. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  21107. tall->setSize (tall->getWidth(), 3200);
  21108. saveWindow (std::move (tall), "-settings-general-tall189o.png");
  21109. }
  21110. {
  21111. // the whole General page (round 186a: the Startup section is below the first screen)
  21112. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  21113. tall->setSize (tall->getWidth(), 1500);
  21114. saveWindow (std::move (tall), "-settings-general-tall.png");
  21115. }
  21116. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
  21117. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::extras), "-settings-extras.png"); // round 190am
  21118. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
  21119. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
  21120. {
  21121. // round 190bj (QA): the MIDI page in a small window keeps each row's switch and device name
  21122. auto small = lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi);
  21123. small->setSize (390, 390);
  21124. saveWindow (std::move (small), "-settings-midi-small.png");
  21125. }
  21126. {
  21127. // round 190bj (QA): the Apex Limiter's window content at its default size, as sized before (JUCE's ratio
  21128. // on the whole window: the status row cut off) and now
  21129. lynx::AudioEngine apexEngine (false);
  21130. lynx::Song song;
  21131. song.mixer.resize (2);
  21132. song.mixer[0].name = "Master";
  21133. song.mixer[1].name = "Insert 1";
  21134. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::apexLimiter));
  21135. apexEngine.setSong (std::move (song));
  21136. apexEngine.dispatchPendingMessages();
  21137. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, true), prefix + "-apex-window-before190bj.png");
  21138. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, false), prefix + "-apex-window.png");
  21139. }
  21140. saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
  21141. saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
  21142. }
  21143. {
  21144. // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
  21145. saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
  21146. const auto& clips = offline.getSong().playlist;
  21147. for (int i = 0; i < (int) clips.size(); ++i)
  21148. if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
  21149. {
  21150. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
  21151. break;
  21152. }
  21153. for (int i = 0; i < (int) clips.size(); ++i)
  21154. if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
  21155. {
  21156. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
  21157. break;
  21158. }
  21159. if (offline.getSong().arrangements.size() < 2)
  21160. offline.editSong ([] (lynx::Song& s) {
  21161. const auto current = s.currentArrangement;
  21162. s.addArrangement ("Radio edit", true);
  21163. s.addArrangement ("Intro loop");
  21164. s.selectArrangement (current);
  21165. }, false);
  21166. saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
  21167. saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
  21168. saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
  21169. }
  21170. {
  21171. // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
  21172. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
  21173. {
  21174. juce::AudioBuffer<float> line (1, 44100 * 2);
  21175. const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
  21176. double ph = 0.0;
  21177. for (int i = 0; i < line.getNumSamples(); ++i)
  21178. {
  21179. const auto f0 = hz[std::min (4, i / 17640)];
  21180. 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;
  21181. float v = 0.0f;
  21182. for (int h = 1; f0 > 0.0 && h < 8; ++h)
  21183. v += (float) (0.3 / h * std::sin (h * ph));
  21184. line.setSample (0, i, v);
  21185. }
  21186. wav.deleteFile();
  21187. juce::WavAudioFormat format;
  21188. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  21189. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
  21190. {
  21191. out.release();
  21192. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  21193. writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
  21194. }
  21195. }
  21196. if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
  21197. {
  21198. auto notes = lynx::newtonefx::analyseNotes (*sample);
  21199. if (notes.pitches.size() > 1)
  21200. notes.pitches[1].shift = 2.0;
  21201. lynx::newtonefx::WarpMap warp;
  21202. warp.frames = (std::int64_t) sample->frames();
  21203. warp.markers = { { 22050, 33075 } };
  21204. int at = 0;
  21205. offline.editSong ([&] (lynx::Song& song) {
  21206. if (song.mixer.size() < 2)
  21207. song.mixer.resize (2);
  21208. auto& fx = song.mixer[1].effects;
  21209. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  21210. tone.samplePath = wav.getFullPathName().toStdString();
  21211. tone.state = lynx::newtonefx::writeNative (notes);
  21212. auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
  21213. time.samplePath = tone.samplePath;
  21214. time.state = lynx::newtonefx::writeWarp (warp);
  21215. at = (int) fx.size();
  21216. fx.push_back (tone);
  21217. fx.push_back (time);
  21218. }, false);
  21219. saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
  21220. saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
  21221. offline.editSong ([at] (lynx::Song& song) {
  21222. auto& fx = song.mixer[1].effects;
  21223. fx.erase (fx.begin() + at, fx.begin() + at + 2);
  21224. }, false);
  21225. }
  21226. }
  21227. if (! offline.getSong().automations.empty())
  21228. {
  21229. auto editor = lynx::makeAutomationEditor (offline, 0);
  21230. editor->setSize (760, 300);
  21231. saveWindow (std::move (editor), "-automation.png");
  21232. // round 177b: the same clip in FL's LFO mode: FL's defaults, then one shaped state (the UI gate pairs)
  21233. const auto before = offline.getSong().automations[0].lfo;
  21234. const auto lfoShot = [&offline, &saveWindow] (std::function<void (lynx::AutomationLfo&)> set, const char* suffix) {
  21235. offline.editSong ([&set] (lynx::Song& song) {
  21236. auto& lfo = song.automations[0].lfo;
  21237. lfo = lynx::AutomationLfo {};
  21238. lfo.on = true;
  21239. set (lfo);
  21240. }, false);
  21241. auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
  21242. lfoEditor->setSize (760, 346);
  21243. saveWindow (std::move (lfoEditor), suffix);
  21244. };
  21245. lfoShot ([] (lynx::AutomationLfo&) {}, "-automation-lfo.png");
  21246. lfoShot ([] (lynx::AutomationLfo& lfo) {
  21247. // the state set through FL's own UI for the UI gate (TNS 50 %, SKEW 25 %, PW 25 %, two points), as FL saved it
  21248. lfo.tension = 64;
  21249. lfo.skew = 32;
  21250. lfo.pulseWidth = 28;
  21251. lfo.amp = { { 0, 0.6716f, 0.0f }, { (std::int64_t) (lynx::ppq * 1.4128), 0.9204f, 0.0f } };
  21252. }, "-automation-lfo-shape.png");
  21253. offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
  21254. }
  21255. // round 177b: LYNX's modulators window, with one routed modulator
  21256. {
  21257. offline.editSong ([] (lynx::Song& song) {
  21258. lynx::Modulator m;
  21259. m.name = "LFO 1";
  21260. m.shape = lynx::ModShape::triangle;
  21261. m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  21262. song.modulators.push_back (m);
  21263. lynx::Modulator r;
  21264. r.name = "LFO 2";
  21265. r.shape = lynx::ModShape::smoothRandom;
  21266. r.sync = false;
  21267. r.hz = 0.5;
  21268. song.modulators.push_back (r);
  21269. }, false);
  21270. auto mods = lynx::makeModulatorsPanel (offline);
  21271. mods->setSize (720, 360);
  21272. saveWindow (std::move (mods), "-modulators.png");
  21273. offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
  21274. }
  21275. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  21276. // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
  21277. saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
  21278. saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
  21279. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  21280. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  21281. {
  21282. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  21283. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  21284. break;
  21285. }
  21286. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  21287. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  21288. {
  21289. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  21290. break;
  21291. }
  21292. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  21293. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  21294. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  21295. {
  21296. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  21297. break;
  21298. }
  21299. // round 180c: Fruity Slicer's editor
  21300. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  21301. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fruityslicer)
  21302. {
  21303. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fruityslicer.png");
  21304. // rounds 190f / 190m: its Envelope / instrument page, one picture per target
  21305. saveWindow (lynx::makeChannelFrame (offline, c, 1), "-fruityslicer-envelope.png");
  21306. for (const auto& [target, name] : std::vector<std::pair<int, const char*>> { { 0, "panning" }, { 2, "modx" }, { 3, "mody" }, { 4, "pitch" } })
  21307. {
  21308. auto frame = lynx::makeChannelFrame (offline, c, 1);
  21309. lynx::showFlVoiceTarget (*frame, target);
  21310. saveWindow (std::move (frame), juce::String ("-fruityslicer-envelope-") + name + ".png");
  21311. }
  21312. break;
  21313. }
  21314. // round 190r: Slicex's editor
  21315. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  21316. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  21317. {
  21318. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-slicex.png");
  21319. break;
  21320. }
  21321. // round 190q: FPC's editor
  21322. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  21323. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fpc)
  21324. {
  21325. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fpc.png");
  21326. break;
  21327. }
  21328. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  21329. {
  21330. int bestTrack = -1, bestSlot = -1;
  21331. double bestShape = -1.0;
  21332. const auto& mixer = offline.getSong().mixer;
  21333. for (int t = 0; t < (int) mixer.size(); ++t)
  21334. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  21335. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  21336. {
  21337. double shape = 0.0;
  21338. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  21339. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  21340. if (shape > bestShape)
  21341. {
  21342. bestShape = shape;
  21343. bestTrack = t;
  21344. bestSlot = s;
  21345. }
  21346. }
  21347. if (bestTrack >= 0)
  21348. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  21349. }
  21350. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  21351. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  21352. saveWindow (std::move (inspector), "-noteinspector.png");
  21353. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  21354. saveWindow (std::move (inspector), "-noteinspector-one.png");
  21355. // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
  21356. {
  21357. auto& roll = ui.getPianoRollForSnapshot();
  21358. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
  21359. { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
  21360. { lynx::NoteTool::flip, "-tool-flip.png" },
  21361. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  21362. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  21363. { lynx::NoteTool::limit, "-tool-limit.png" },
  21364. { lynx::NoteTool::quantize, "-tool-quantize.png" },
  21365. { lynx::NoteTool::chop, "-tool-chop.png" },
  21366. { lynx::NoteTool::flam, "-tool-flam.png" },
  21367. { lynx::NoteTool::lfo, "-tool-lfo.png" },
  21368. { lynx::NoteTool::claw, "-tool-claw.png" },
  21369. { lynx::NoteTool::articulate, "-tool-articulate.png" },
  21370. { lynx::NoteTool::riffMachine, "-tool-riff.png" },
  21371. { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
  21372. for (const auto& [tool, name] : tools)
  21373. saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
  21374. }
  21375. // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
  21376. {
  21377. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
  21378. const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
  21379. offline.editSong ([&] (lynx::Song& s) {
  21380. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
  21381. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
  21382. lynx::prtools::LfoOptions lfo;
  21383. lfo.startSpeed = 7 * 4096; // one beat
  21384. lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
  21385. }, false);
  21386. saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
  21387. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  21388. // issue #86: the same editor on the Tempo target, with the project's own Tempo events (a sample ramp if none)
  21389. const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
  21390. offline.editSong ([&] (lynx::Song& s) {
  21391. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], tempo);
  21392. if (lane.events.empty())
  21393. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.05f, 0.11f, lynx::ticksPerStep);
  21394. }, false);
  21395. saveWindow (lynx::makeEventEditor (offline, tempo), "-eventeditor-tempo.png");
  21396. {
  21397. auto compact = lynx::makeEventEditor (offline, tempo); // the toolbar in a small window
  21398. compact->setSize (640, 300);
  21399. saveWindow (std::move (compact), "-eventeditor-tempo-small.png");
  21400. auto narrowest = lynx::makeEventEditor (offline, tempo); // the tool window's lower limit
  21401. narrowest->setSize (400, 300);
  21402. saveWindow (std::move (narrowest), "-eventeditor-tempo-narrowest.png");
  21403. }
  21404. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  21405. }
  21406. // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
  21407. // and its menu items (-audioeditor-menu.txt)
  21408. {
  21409. namespace ae = lynx::audioedit;
  21410. ae::Document d;
  21411. d.title = "Drum loop";
  21412. d.audio.sampleRate = 44100.0;
  21413. const auto frames = (std::size_t) (44100 * 2);
  21414. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  21415. std::uint32_t seed = 7;
  21416. for (int hit = 0; hit < 8; ++hit)
  21417. {
  21418. const auto at = (std::size_t) hit * frames / 8;
  21419. const auto kick = hit % 2 == 0;
  21420. double phase = 0.0;
  21421. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  21422. {
  21423. seed = seed * 1664525u + 1013904223u;
  21424. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  21425. const auto t = (double) i / 44100.0;
  21426. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  21427. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  21428. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  21429. d.audio.channels[0][at + i] += v;
  21430. d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
  21431. }
  21432. }
  21433. ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
  21434. ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
  21435. ae::setLoop (d, { 0, (std::int64_t) frames });
  21436. auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
  21437. juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
  21438. saveWindow (std::move (wave), "-audioeditor.png");
  21439. saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
  21440. }
  21441. // warp markers (round 175a, M3): the audio editor of the first audio clip whose channel has warp markers,
  21442. // opened as the Playlist opens it, with its warp lane
  21443. {
  21444. const auto& song = offline.getSong();
  21445. for (int i = 0; i < (int) song.playlist.size(); ++i)
  21446. {
  21447. const auto& c = song.playlist[(std::size_t) i];
  21448. if (c.kind == lynx::ClipKind::audio && juce::isPositiveAndBelow (c.channel, (int) song.channels.size())
  21449. && song.channels[(std::size_t) c.channel].sampler.warp.size() >= 3)
  21450. {
  21451. if (auto panel = lynx::makeAudioEditorPanel (offline, c.channel, i, true))
  21452. saveWindow (std::move (panel), "-audioeditor-warp.png");
  21453. break;
  21454. }
  21455. }
  21456. }
  21457. // the tempo tapper after five steady taps (round 132)
  21458. saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
  21459. // the Channel Rack's piano-roll view (round 132)
  21460. ui.selectTabForSnapshot (0);
  21461. ui.getRackForSnapshot().setPianoRollView (true);
  21462. offline.dispatchPendingMessages();
  21463. saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
  21464. ui.getRackForSnapshot().setPianoRollView (false);
  21465. // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
  21466. ui.selectTabForSnapshot (0);
  21467. ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
  21468. offline.dispatchPendingMessages();
  21469. saveSnapshot (ui, prefix + "-rack-graph.png");
  21470. ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
  21471. saveSnapshot (ui, prefix + "-rack-graph-pan.png");
  21472. ui.getRackForSnapshot().toggleGraphLanes();
  21473. saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
  21474. // the Mixer with three inserts selected and one armed for recording
  21475. ui.selectTabForSnapshot (3);
  21476. if (offline.getSong().mixer.size() > 4)
  21477. {
  21478. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
  21479. offline.setInsertArmed (3, true);
  21480. offline.dispatchPendingMessages();
  21481. saveSnapshot (ui, prefix + "-mixer-multi.png");
  21482. // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
  21483. offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
  21484. ui.getMixerForSnapshot().selectTrack (3);
  21485. offline.dispatchPendingMessages();
  21486. saveSnapshot (ui, prefix + "-mixer-input.png");
  21487. offline.undo();
  21488. offline.setInsertArmed (3, false);
  21489. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
  21490. }
  21491. // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
  21492. if (offline.getSong().mixer.size() > 6)
  21493. {
  21494. int source = -1;
  21495. for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
  21496. if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
  21497. source = t;
  21498. const auto temporary = source < 0;
  21499. if (temporary) // the demo has no sends: add two for the picture
  21500. {
  21501. source = 1;
  21502. 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); });
  21503. }
  21504. ui.getMixerForSnapshot().selectTrack (source);
  21505. offline.dispatchPendingMessages();
  21506. saveSnapshot (ui, prefix + "-mixer-sends.png");
  21507. if (temporary)
  21508. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
  21509. ui.getMixerForSnapshot().selectTrack (0);
  21510. }
  21511. // the Playlist with ripple editing on
  21512. ui.selectTabForSnapshot (2);
  21513. ui.getPlaylistForSnapshot().setRipple (true);
  21514. saveSnapshot (ui, prefix + "-playlist-ripple.png");
  21515. ui.getPlaylistForSnapshot().setRipple (false);
  21516. // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
  21517. {
  21518. const auto saved = offline.getSong();
  21519. offline.editSong ([] (lynx::Song& s) {
  21520. s.patternBlocksOn = true;
  21521. while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
  21522. lynx::clonePattern (s, (int) s.patterns.size() - 1);
  21523. const auto rows = juce::jmin (6, (int) s.patterns.size());
  21524. for (int r = 0; r < rows; ++r)
  21525. lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
  21526. (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
  21527. }, false);
  21528. offline.dispatchPendingMessages();
  21529. saveSnapshot (ui, prefix + "-playlist-blocks.png");
  21530. // issue #127 (PR #132 and our follow-up): the Playlist's pencil, brush and eraser on the blocks, driven
  21531. // with real mouse events on the view. One picture per tool, and the gestures' results in
  21532. // <prefix>-playlist-blocks-tools.txt ("OK", or the checks that failed).
  21533. if (auto* blocks = ui.getPlaylistForSnapshot().getBlocksViewForSnapshot())
  21534. {
  21535. juce::StringArray failed;
  21536. const auto expect = [&failed] (bool ok, const char* what) { if (! ok) failed.add (what); };
  21537. const auto bar = offline.getSong().barTicks();
  21538. offline.editSong ([bar] (lynx::Song& s) {
  21539. s.blocks.clear();
  21540. for (std::size_t r = 0; r < 4 && r < s.patterns.size(); ++r)
  21541. s.patterns[r].lengthTicks = r == 1 ? 2 * bar : bar; // row 2 holds a 2-bar pattern
  21542. }, false);
  21543. offline.dispatchPendingMessages();
  21544. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  21545. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  21546. juce::Point<float> pressedAt;
  21547. const auto event = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  21548. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  21549. const auto now = juce::Time::getCurrentTime();
  21550. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, 1, false);
  21551. };
  21552. const auto press = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  21553. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  21554. blocks->mouseDown (event (row, tick, mods));
  21555. };
  21556. const auto dragTo = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (event (row, tick, mods)); };
  21557. const auto release = [&] (int row, std::int64_t tick) { blocks->mouseUp (event (row, tick, {})); };
  21558. // the starts of row `row`'s blocks, as "0,2,5" (bars from 0)
  21559. const auto rowBars = [&] (int row) {
  21560. juce::StringArray bars;
  21561. for (const auto& b : offline.getSong().blocks)
  21562. if (b.pattern == row)
  21563. bars.add (juce::String (b.start / bar) + (b.start % bar != 0 ? "+" : ""));
  21564. return bars.joinIntoString (",");
  21565. };
  21566. auto& tools = ui.getPlaylistForSnapshot();
  21567. // Pencil: a press on empty space places one block that follows the mouse along its row
  21568. tools.setToolForSnapshot (lynx::EditTool::pencil);
  21569. press (0, 2 * bar + 40, left);
  21570. expect (rowBars (0) == "2", "pencil: a press places one block");
  21571. dragTo (2, 5 * bar + 40, left); // (over another row: the block stays in its own)
  21572. release (2, 5 * bar + 40);
  21573. expect (rowBars (0) == "5" && rowBars (2).isEmpty(), "pencil: the placed block follows the drag in its row");
  21574. // a 2-bar block grabbed by its second bar keeps that bar under the mouse (it used to jump a bar)
  21575. press (1, 1 * bar + 40, left);
  21576. release (1, 1 * bar + 40);
  21577. expect (rowBars (1) == "1", "pencil: a click places the 2-bar block");
  21578. press (1, 2 * bar + 40, left);
  21579. dragTo (1, 2 * bar + bar / 2, left);
  21580. expect (rowBars (1) == "1", "move: a small move on the grabbed bar leaves the block in place");
  21581. dragTo (1, 4 * bar + 40, left);
  21582. release (1, 4 * bar + 40);
  21583. expect (rowBars (1) == "3", "move: the grabbed bar stays under the mouse");
  21584. offline.dispatchPendingMessages();
  21585. saveSnapshot (ui, prefix + "-playlist-blocks-pencil.png");
  21586. // Brush: a drag over empty space paints a run; a press on a block moves it
  21587. tools.setToolForSnapshot (lynx::EditTool::brush);
  21588. press (2, 0, left);
  21589. dragTo (2, 3 * bar + 40, left);
  21590. release (2, 3 * bar + 40);
  21591. expect (rowBars (2) == "0,1,2,3", "brush: a drag paints a run");
  21592. press (2, 3 * bar + 40, left);
  21593. dragTo (2, 6 * bar + 40, left);
  21594. release (2, 6 * bar + 40);
  21595. expect (rowBars (2) == "0,1,2,6", "brush: a press on a block moves it");
  21596. offline.dispatchPendingMessages();
  21597. saveSnapshot (ui, prefix + "-playlist-blocks-brush.png");
  21598. // Eraser, and the right button with any tool: only the blocks under the mouse, row by row
  21599. offline.editSong ([bar] (lynx::Song& s) {
  21600. for (int r = 0; r < 4 && r < (int) s.patterns.size(); ++r)
  21601. lynx::patternblocks::place (s, r, 8 * bar);
  21602. }, false);
  21603. offline.dispatchPendingMessages();
  21604. expect (rowBars (0) == "5,8" && rowBars (3) == "8", "eraser: the column is set up");
  21605. saveSnapshot (ui, prefix + "-playlist-blocks-eraser-before.png");
  21606. tools.setToolForSnapshot (lynx::EditTool::eraser);
  21607. press (0, 8 * bar + 40, left);
  21608. expect (rowBars (0) == "5" && rowBars (1) == "3,8" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8",
  21609. "eraser: a click takes only the block under the mouse");
  21610. dragTo (1, 8 * bar + 60, left); // down one row: that row's block goes too, the rows below stay
  21611. release (1, 8 * bar + 60);
  21612. expect (rowBars (1) == "3" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8", "eraser: the drag erases the rows it crosses, no others");
  21613. tools.setToolForSnapshot (lynx::EditTool::pencil);
  21614. press (3, 8 * bar + 40, right);
  21615. release (3, 8 * bar + 40);
  21616. expect (rowBars (3).isEmpty() && rowBars (2) == "0,1,2,6,8", "right click: erases only the block under the mouse");
  21617. offline.dispatchPendingMessages();
  21618. saveSnapshot (ui, prefix + "-playlist-blocks-eraser.png");
  21619. juce::File (prefix + "-playlist-blocks-tools.txt").replaceWithText (failed.isEmpty() ? juce::String ("OK\n") : "ERROR\n" + failed.joinIntoString ("\n") + "\n");
  21620. }
  21621. offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
  21622. offline.dispatchPendingMessages();
  21623. }
  21624. // quick-add palette, and the Browser searching
  21625. saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
  21626. ui.showDesktopForSnapshot (false);
  21627. ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
  21628. offline.dispatchPendingMessages();
  21629. saveSnapshot (ui, prefix + "-browser-search.png");
  21630. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  21631. ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
  21632. offline.dispatchPendingMessages();
  21633. saveSnapshot (ui, prefix + "-browser-tree.png");
  21634. // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
  21635. ui.getBrowserForSnapshot().showProjectForSnapshot();
  21636. offline.dispatchPendingMessages();
  21637. saveSnapshot (ui, prefix + "-browser-project.png");
  21638. ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
  21639. offline.dispatchPendingMessages();
  21640. saveSnapshot (ui, prefix + "-browser-plugins.png");
  21641. // round 190bf (fl190be Q1): the Plugin database's right-click menus, a folder's and an entry's (FL's System group)
  21642. saveMenus (juce::StringArray { "Plugin database: folder", "Plugin database: entry" }, ui.getBrowserForSnapshot().pluginDatabaseMenusForSnapshot(),
  21643. prefix + "-browser190bf-menus.png");
  21644. ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
  21645. saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
  21646. {
  21647. // round 164: the content filter leaves out the folders with nothing to list (a small library)
  21648. const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
  21649. lib.deleteRecursively();
  21650. for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
  21651. "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
  21652. lib.getChildFile (path).create();
  21653. ui.showDesktopForSnapshot (false);
  21654. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  21655. offline.dispatchPendingMessages();
  21656. saveSnapshot (ui, prefix + "-browser164-all.png");
  21657. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
  21658. offline.dispatchPendingMessages();
  21659. saveSnapshot (ui, prefix + "-browser164-samples.png");
  21660. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
  21661. offline.dispatchPendingMessages();
  21662. saveSnapshot (ui, prefix + "-browser164-projects.png");
  21663. lib.deleteRecursively();
  21664. ui.getBrowserForSnapshot().resetViewForSnapshot();
  21665. }
  21666. {
  21667. // round 190as: "Find similar samples" on a small library of kicks, hats and pads (LYNX_SNAPSHOT_SIMILAR =
  21668. // "<folder>|<file>" lists a real folder instead)
  21669. auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-similar");
  21670. auto query = lib.getChildFile ("Drums/Kicks/Kick 2.wav");
  21671. const auto real = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIMILAR", {});
  21672. const auto made = real.isEmpty();
  21673. if (made)
  21674. {
  21675. lib.deleteRecursively();
  21676. juce::Random random (190);
  21677. const auto write = [&] (const juce::String& path, char kind, int v) {
  21678. const auto rate = 44100.0;
  21679. const auto frames = (int) (rate * (kind == 'k' ? 0.35 : kind == 'h' ? 0.09 : 2.5));
  21680. juce::AudioBuffer<float> audio (1, frames);
  21681. double phase = 0.0;
  21682. float last = 0.0f;
  21683. for (int i = 0; i < frames; ++i)
  21684. {
  21685. const auto t = i / rate;
  21686. float x = 0.0f;
  21687. if (kind == 'k')
  21688. {
  21689. phase += juce::MathConstants<double>::twoPi * ((46.0 + 3.0 * v) + 150.0 * std::exp (-t * 35.0)) / rate;
  21690. x = (float) (std::sin (phase) * std::exp (-t * (8.0 + v)));
  21691. }
  21692. else if (kind == 'h')
  21693. {
  21694. const auto n = random.nextFloat() * 2.0f - 1.0f;
  21695. x = (n - last) * 0.5f * (float) std::exp (-t * (50.0 + 12.0 * v));
  21696. last = n;
  21697. }
  21698. else
  21699. {
  21700. const auto base = 220.0 * std::pow (2.0, v / 12.0);
  21701. x = (float) (0.25 * std::min (1.0, t / 0.4) * std::min (1.0, (2.5 - t) / 0.5)
  21702. * (std::sin (juce::MathConstants<double>::twoPi * base * t) + std::sin (juce::MathConstants<double>::twoPi * base * 1.5 * t)));
  21703. }
  21704. audio.setSample (0, i, 0.8f * x);
  21705. }
  21706. const auto file = lib.getChildFile (path);
  21707. file.getParentDirectory().createDirectory();
  21708. juce::WavAudioFormat wav;
  21709. if (auto out = file.createOutputStream())
  21710. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (out.release(), rate, 1, 16, {}, 0)))
  21711. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  21712. };
  21713. for (int v = 1; v <= 5; ++v)
  21714. {
  21715. write ("Drums/Kicks/Kick " + juce::String (v) + ".wav", 'k', v);
  21716. write ("Drums/Hats/Hat " + juce::String (v) + ".wav", 'h', v);
  21717. write ("Keys/Pad " + juce::String (v) + ".wav", 'p', v);
  21718. }
  21719. }
  21720. else
  21721. {
  21722. lib = juce::File (real.upToFirstOccurrenceOf ("|", false, false));
  21723. query = juce::File (real.fromFirstOccurrenceOf ("|", false, false));
  21724. }
  21725. ui.showDesktopForSnapshot (false);
  21726. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  21727. ui.getBrowserForSnapshot().findSimilarForSnapshot (query, lib);
  21728. offline.dispatchPendingMessages();
  21729. saveSnapshot (ui, prefix + "-browser-similar.png");
  21730. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  21731. if (made)
  21732. lib.deleteRecursively();
  21733. ui.getBrowserForSnapshot().resetViewForSnapshot();
  21734. }
  21735. // the undo history after a few edits
  21736. offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
  21737. offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
  21738. offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
  21739. offline.undo();
  21740. saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
  21741. // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
  21742. // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
  21743. {
  21744. const juce::File wav (prefix + "-wavedemo.wav");
  21745. writeWaveDemo (wav, offline.getSong().bpm);
  21746. const auto path = wav.getFullPathName();
  21747. const auto pathUtf8 = path.toStdString();
  21748. int samplerChannel = -1, firstTrack = 0;
  21749. offline.editSong ([&] (lynx::Song& s) {
  21750. for (const auto& clip : s.playlist)
  21751. firstTrack = std::max (firstTrack, clip.track + 1);
  21752. lynx::ChannelDef audio;
  21753. audio.name = "Beat (audio)";
  21754. audio.instrument = lynx::InstrumentKind::audioClip;
  21755. audio.samplePath = pathUtf8;
  21756. s.channels.push_back (audio);
  21757. const auto audioChannel = (int) s.channels.size() - 1;
  21758. lynx::ChannelDef sampler = audio;
  21759. sampler.name = "Beat (sampler)";
  21760. sampler.instrument = lynx::InstrumentKind::sampler;
  21761. sampler.sampler.regionStart = 0.06f;
  21762. sampler.sampler.regionEnd = 0.94f;
  21763. s.channels.push_back (sampler);
  21764. samplerChannel = (int) s.channels.size() - 1;
  21765. const auto bar = s.barTicks();
  21766. const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
  21767. lynx::Clip clip;
  21768. clip.kind = lynx::ClipKind::audio;
  21769. clip.channel = audioChannel;
  21770. clip.track = firstTrack;
  21771. clip.length = whole;
  21772. s.playlist.push_back (clip);
  21773. clip.track = firstTrack + 1; // a slice of it, later in the song
  21774. clip.start = bar;
  21775. clip.offset = bar;
  21776. clip.length = 2 * bar;
  21777. s.playlist.push_back (clip);
  21778. // taller rows for the audio (tracks can be resized: P18)
  21779. if ((int) s.playlistTracks.size() < firstTrack + 2)
  21780. s.playlistTracks.resize ((std::size_t) firstTrack + 2);
  21781. s.playlistTracks[(std::size_t) firstTrack].height = 80;
  21782. s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
  21783. });
  21784. offline.dispatchPendingMessages();
  21785. auto& cache = *lynx::ui::WaveformCache::getInstance();
  21786. cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  21787. cache.waitUntilIdle (30000);
  21788. ui.selectTabForSnapshot (2);
  21789. auto& playlist = ui.getPlaylistForSnapshot();
  21790. playlist.setTimeSelectionForSnapshot (0, 0);
  21791. {
  21792. // the Playlist alone (the floating Channel Rack would cover the clips)
  21793. auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
  21794. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  21795. saveSnapshot (ui, prefix + "-playlist-audio.png");
  21796. playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
  21797. saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
  21798. lynx::ui::WaveformCache::stereo = true;
  21799. saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
  21800. lynx::ui::WaveformCache::stereo = false;
  21801. lynx::ui::WaveformCache::spectral = true;
  21802. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  21803. saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
  21804. lynx::ui::WaveformCache::spectral = false;
  21805. playlist.setViewForSnapshot (40.0, 0, 0);
  21806. saveSnapshot (ui, prefix + "-playlist-audio-far.png");
  21807. // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
  21808. // a fade, a reversed copy), at three zoom levels
  21809. if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
  21810. ! files.isEmpty())
  21811. {
  21812. const auto realTrack = firstTrack + 2;
  21813. std::vector<juce::String> paths;
  21814. for (const auto& f : files)
  21815. if (juce::File (f.trim()).existsAsFile())
  21816. paths.push_back (f.trim());
  21817. offline.editSong ([&] (lynx::Song& s) {
  21818. const auto bar = s.barTicks();
  21819. const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
  21820. for (std::size_t i = 0; i < paths.size(); ++i)
  21821. {
  21822. lynx::ChannelDef audio;
  21823. audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
  21824. audio.instrument = lynx::InstrumentKind::audioClip;
  21825. audio.samplePath = paths[i].toStdString();
  21826. audio.colour = colours[i % 6];
  21827. audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
  21828. audio.sampler.keepPitch = true;
  21829. s.channels.push_back (audio);
  21830. lynx::Clip clip;
  21831. clip.kind = lynx::ClipKind::audio;
  21832. clip.channel = (int) s.channels.size() - 1;
  21833. clip.track = realTrack + (int) i;
  21834. clip.length = 4 * bar;
  21835. clip.fadeIn = i == 1 ? bar / 2 : 0;
  21836. s.playlist.push_back (clip);
  21837. clip.start = 4 * bar;
  21838. clip.fadeIn = 0;
  21839. clip.fadeOut = i == 0 ? bar : 0;
  21840. s.playlist.push_back (clip);
  21841. }
  21842. if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
  21843. s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
  21844. if (! paths.empty())
  21845. s.playlistTracks[(std::size_t) realTrack].height = 90;
  21846. });
  21847. offline.dispatchPendingMessages();
  21848. for (const auto& path2 : paths)
  21849. cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
  21850. cache.waitUntilIdle (60000);
  21851. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  21852. saveSnapshot (ui, prefix + "-playlist-real.png");
  21853. playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
  21854. saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
  21855. playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
  21856. saveSnapshot (ui, prefix + "-playlist-real-close.png");
  21857. playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
  21858. saveSnapshot (ui, prefix + "-playlist-real-far.png");
  21859. // the clip menu of the first real clip
  21860. if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
  21861. saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
  21862. if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
  21863. saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
  21864. // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
  21865. {
  21866. juce::StringArray log;
  21867. auto clipOf = [&offline] (const std::string& channelName, int nth) {
  21868. const auto& sg = offline.getSong();
  21869. for (int i = 0; i < (int) sg.playlist.size(); ++i)
  21870. {
  21871. const auto& c = sg.playlist[(std::size_t) i];
  21872. if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
  21873. return i;
  21874. }
  21875. return -1;
  21876. };
  21877. std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
  21878. for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
  21879. {
  21880. auto& item = it.getItem();
  21881. if (item.subMenu != nullptr && run (*item.subMenu, text))
  21882. return true;
  21883. // (without the menu mnemonic's mark: FL's underlined letters, round 190dz)
  21884. if (item.text.removeCharacters (juce::String::charToString (1)).startsWith (text) && item.isEnabled && item.action)
  21885. {
  21886. item.action();
  21887. return true;
  21888. }
  21889. }
  21890. return false;
  21891. };
  21892. auto act = [&] (const std::string& name, int nth, const juce::String& text) {
  21893. const auto clip = clipOf (name, nth);
  21894. const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
  21895. offline.dispatchPendingMessages();
  21896. return ok;
  21897. };
  21898. auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
  21899. for (const auto& c : offline.getSong().channels)
  21900. if (c.name == name)
  21901. return &c;
  21902. return nullptr;
  21903. };
  21904. auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
  21905. const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
  21906. if (names.size() >= 4)
  21907. {
  21908. const auto channelsBefore = offline.getSong().channels.size();
  21909. check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
  21910. offline.undo();
  21911. offline.dispatchPendingMessages();
  21912. check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
  21913. act (names[2], 0, lynx::tr ("Reverse"));
  21914. check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
  21915. && channelOf (names[3] + " #2") != nullptr);
  21916. check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
  21917. && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
  21918. const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
  21919. check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
  21920. && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
  21921. const auto clipsBefore = offline.getSong().playlist.size();
  21922. check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
  21923. check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
  21924. check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
  21925. && offline.getSong().playlist.size() == clipsBefore + 2);
  21926. check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
  21927. check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
  21928. }
  21929. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  21930. saveSnapshot (ui, prefix + "-playlist-real-actions.png");
  21931. juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
  21932. }
  21933. }
  21934. }
  21935. saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
  21936. ui.showDesktopForSnapshot (false);
  21937. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  21938. saveSnapshot (ui, prefix + "-browser-preview.png");
  21939. }
  21940. }
  21941. // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
  21942. // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
  21943. juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
  21944. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  21945. quit();
  21946. }
  21947. // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
  21948. // hats and the noise riser = high), to show the spectral waveform colours
  21949. static void writeWaveDemo (const juce::File& file, double bpm)
  21950. {
  21951. constexpr double rate = 44100.0;
  21952. const auto frames = (int) (8.0 * rate);
  21953. juce::AudioBuffer<float> buffer (2, frames);
  21954. buffer.clear();
  21955. auto* l = buffer.getWritePointer (0);
  21956. auto* r = buffer.getWritePointer (1);
  21957. const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
  21958. std::uint32_t noise = 0x9e3779b9u;
  21959. auto white = [&noise] {
  21960. noise ^= noise << 13;
  21961. noise ^= noise >> 17;
  21962. noise ^= noise << 5;
  21963. return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
  21964. };
  21965. float previous = 0.0f;
  21966. for (int i = 0; i < frames; ++i)
  21967. {
  21968. const auto t = i / rate;
  21969. const auto inBeat = std::fmod (t, beat);
  21970. const auto bar = (int) (t / (beat * 4.0));
  21971. float left = 0.0f, right = 0.0f;
  21972. // kick on every beat: a falling sine
  21973. {
  21974. const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
  21975. const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
  21976. left += k;
  21977. right += k;
  21978. }
  21979. // hats on the off-beats: high-passed noise bursts, a little to the right
  21980. {
  21981. const auto h = std::fmod (t + beat * 0.5, beat);
  21982. const auto n = white();
  21983. const auto hp = (n - previous) * 0.5f;
  21984. previous = n;
  21985. const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
  21986. left += hat * 0.6f;
  21987. right += hat;
  21988. }
  21989. // a chord in the second and third bars (mid band)
  21990. if (bar == 1 || bar == 2)
  21991. {
  21992. const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
  21993. float chord = 0.0f;
  21994. for (const auto hz : { 523.25, 659.25, 783.99 })
  21995. chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
  21996. left += chord * 0.09f * std::max (0.0f, env);
  21997. right += chord * 0.09f * std::max (0.0f, env);
  21998. }
  21999. // a white-noise riser over the last two seconds (high band)
  22000. if (t > 6.0)
  22001. {
  22002. const auto rise = (float) ((t - 6.0) / 2.0);
  22003. left += white() * 0.4f * rise * rise;
  22004. right += white() * 0.4f * rise * rise;
  22005. }
  22006. l[i] = left;
  22007. r[i] = right;
  22008. }
  22009. buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
  22010. file.deleteFile();
  22011. juce::WavAudioFormat wav;
  22012. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
  22013. writer->writeFromAudioSampleBuffer (buffer, 0, frames);
  22014. }
  22015. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  22016. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  22017. {
  22018. const auto names = ui.getMenuNamesForSnapshot();
  22019. std::vector<juce::PopupMenu> source;
  22020. for (int m = 0; m < names.size(); ++m)
  22021. source.push_back (ui.getMenuForSnapshot (m));
  22022. saveMenus (names, source, path);
  22023. }
  22024. // menus side by side, each under its name
  22025. static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
  22026. {
  22027. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  22028. struct Laid
  22029. {
  22030. juce::PopupMenu menu;
  22031. int width = 0, height = 0;
  22032. };
  22033. std::vector<Laid> menus;
  22034. const auto border = lf.getPopupMenuBorderSize();
  22035. for (int m = 0; m < names.size(); ++m)
  22036. {
  22037. Laid laid { source[(std::size_t) m] };
  22038. int width = 160, height = 2 * border;
  22039. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  22040. {
  22041. const auto& item = it.getItem();
  22042. int w = 0, h = 0;
  22043. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  22044. if (item.isSectionHeader) h += h / 2; // as JUCE does
  22045. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  22046. w += 90;
  22047. width = juce::jmax (width, w + 10);
  22048. height += h;
  22049. }
  22050. laid.width = width;
  22051. laid.height = height;
  22052. menus.push_back (std::move (laid));
  22053. }
  22054. int totalWidth = 16, totalHeight = 0;
  22055. for (const auto& l : menus)
  22056. {
  22057. totalWidth += l.width + 16;
  22058. totalHeight = juce::jmax (totalHeight, l.height + 32);
  22059. }
  22060. auto image = lynx::shot::canvas (totalWidth, totalHeight);
  22061. {
  22062. juce::Graphics g (image);
  22063. lynx::shot::logical (g);
  22064. g.fillAll (lynx::theme::colour::bg1);
  22065. int x = 16;
  22066. for (int m = 0; m < (int) menus.size(); ++m)
  22067. {
  22068. const auto& l = menus[(std::size_t) m];
  22069. g.setColour (lynx::theme::colour::textSecondary);
  22070. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  22071. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  22072. {
  22073. juce::Graphics::ScopedSaveState state (g);
  22074. g.reduceClipRegion (x, 24, l.width, l.height);
  22075. g.setOrigin (x, 24);
  22076. lf.drawPopupMenuBackground (g, l.width, l.height);
  22077. int y = border;
  22078. bool first = true;
  22079. for (juce::PopupMenu::MenuItemIterator it (l.menu); it.next();)
  22080. {
  22081. const auto& item = it.getItem();
  22082. int w = 0, h = 0;
  22083. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  22084. if (item.isSectionHeader) h += h / 2; // as JUCE does
  22085. const juce::Rectangle<int> r (0, y, l.width, h);
  22086. auto text = item.text, shortcut = item.shortcutKeyDescription;
  22087. if (text.containsChar ('\t'))
  22088. {
  22089. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  22090. text = text.upToFirstOccurrenceOf ("\t", false, false);
  22091. }
  22092. if (item.isSectionHeader)
  22093. lf.drawPopupMenuSectionHeader (g, r, text);
  22094. else
  22095. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  22096. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  22097. first = false;
  22098. y += h;
  22099. }
  22100. }
  22101. x += l.width + 16;
  22102. }
  22103. }
  22104. const auto file = lynx::shot::file (juce::File (path));
  22105. file.deleteFile();
  22106. juce::PNGImageFormat png;
  22107. if (auto out = file.createOutputStream())
  22108. png.writeImageToStream (image, *out);
  22109. }
  22110. static void writePng (const juce::Image& image, const juce::String& path)
  22111. {
  22112. const auto file = lynx::shot::file (juce::File (path));
  22113. file.deleteFile();
  22114. juce::PNGImageFormat png;
  22115. if (auto out = file.createOutputStream())
  22116. png.writeImageToStream (image, *out);
  22117. }
  22118. // the splash screen: one settled frame, and a strip of frames through its animation
  22119. static void saveSplashFrames (const juce::String& prefix)
  22120. {
  22121. lynx::SplashScreen splash;
  22122. splash.setStatus (lynx::tr ("Loading the workspace..."));
  22123. splash.setTimeForSnapshot (1.6);
  22124. writePng (lynx::shot::snapshot (splash), prefix + "-splash.png");
  22125. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  22126. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  22127. auto strip = lynx::shot::canvas (4 * (w + 8) + 8, 2 * (h + 8) + 8);
  22128. {
  22129. juce::Graphics g (strip);
  22130. lynx::shot::logical (g);
  22131. g.fillAll (lynx::theme::colour::bg1);
  22132. for (int i = 0; i < 8; ++i)
  22133. {
  22134. splash.setTimeForSnapshot (times[i]);
  22135. const auto frame = lynx::shot::snapshot (splash);
  22136. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  22137. }
  22138. }
  22139. writePng (strip, prefix + "-splash-frames.png");
  22140. }
  22141. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  22142. // colours: at rest, hovered and switched on
  22143. static void saveIconSheet (const juce::String& path, float scale)
  22144. {
  22145. scale *= lynx::shot::scale();
  22146. const int sizes[] = { 16, 20, 24 };
  22147. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  22148. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  22149. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  22150. {
  22151. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  22152. g.addTransform (juce::AffineTransform::scale (scale));
  22153. g.fillAll (lynx::theme::colour::bg3);
  22154. g.setFont (lynx::theme::font (lynx::theme::type::small));
  22155. for (int i = 1; i < lynx::iconCount; ++i)
  22156. {
  22157. const auto y = 8 + (i - 1) * cell;
  22158. g.setColour (lynx::theme::colour::textDisabled);
  22159. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  22160. for (int v = 0; v < 3; ++v)
  22161. for (int s = 0; s < 3; ++s)
  22162. {
  22163. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  22164. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  22165. g.setColour (bg);
  22166. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  22167. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  22168. : lynx::theme::colour::textSecondary.brighter (0.25f);
  22169. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  22170. }
  22171. }
  22172. }
  22173. writePng (image, path);
  22174. }
  22175. // a part of a component (e.g. the main toolbar)
  22176. static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
  22177. {
  22178. const auto file = lynx::shot::file (juce::File (path));
  22179. file.deleteFile();
  22180. juce::PNGImageFormat png;
  22181. if (auto out = file.createOutputStream())
  22182. png.writeImageToStream (lynx::shot::snapshot (c, area), *out);
  22183. }
  22184. static void savePng (const juce::Image& image, const juce::String& path)
  22185. {
  22186. const auto file = lynx::shot::file (juce::File (path));
  22187. file.deleteFile();
  22188. juce::PNGImageFormat png;
  22189. if (auto out = file.createOutputStream())
  22190. png.writeImageToStream (image, *out);
  22191. }
  22192. // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
  22193. // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
  22194. static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
  22195. {
  22196. const auto tips = ui.getQuickTipsForSnapshot();
  22197. const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
  22198. auto image = lynx::shot::snapshot (ui, top);
  22199. {
  22200. juce::Graphics g (image);
  22201. lynx::shot::logical (g);
  22202. const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
  22203. lynx::tr ("Window options"), lynx::tr ("Close") };
  22204. std::vector<juce::Rectangle<int>> used;
  22205. for (const auto& [area, tip] : tips)
  22206. {
  22207. const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
  22208. if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
  22209. continue;
  22210. const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
  22211. if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
  22212. continue;
  22213. used.push_back (bubble);
  22214. g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
  22215. g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
  22216. lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
  22217. }
  22218. }
  22219. savePng (image, prefix + "-toolbar-tips.png");
  22220. // the sheet: bubbles in rows
  22221. const int width = 900;
  22222. int x = 12, y = 12;
  22223. std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
  22224. for (const auto& [area, tip] : tips)
  22225. {
  22226. auto r = lynx::ui::quickTipSize (tip);
  22227. if (x + r.getWidth() > width - 12)
  22228. {
  22229. x = 12;
  22230. y += r.getHeight() + 10;
  22231. }
  22232. placed.emplace_back (r.withPosition (x, y), tip);
  22233. x += r.getWidth() + 10;
  22234. }
  22235. auto sheet = lynx::shot::canvas (width, y + 20 + 12);
  22236. {
  22237. juce::Graphics g (sheet);
  22238. lynx::shot::logical (g);
  22239. g.fillAll (lynx::theme::colour::bg3);
  22240. for (const auto& [r, tip] : placed)
  22241. lynx::ui::paintQuickTip (g, r.toFloat(), tip);
  22242. }
  22243. savePng (sheet, prefix + "-tips-sheet.png");
  22244. }
  22245. static juce::StringArray& textFitLog()
  22246. {
  22247. static juce::StringArray log;
  22248. return log;
  22249. }
  22250. // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
  22251. static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
  22252. {
  22253. if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
  22254. return false;
  22255. auto visible = [] (juce::GlyphArrangement& ga) {
  22256. int n = 0;
  22257. for (int i = 0; i < ga.getNumGlyphs(); ++i)
  22258. n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
  22259. return n;
  22260. };
  22261. juce::GlyphArrangement fitted, full;
  22262. fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
  22263. juce::jmax (1, maxLines), minScale);
  22264. full.addLineOfText (font, text, 0.0f, 0.0f);
  22265. return visible (fitted) < visible (full);
  22266. }
  22267. // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
  22268. static void checkTextFit (juce::Component& root, const juce::String& where)
  22269. {
  22270. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  22271. if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
  22272. return;
  22273. juce::String text;
  22274. bool cut = false;
  22275. if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
  22276. {
  22277. const auto font = label->getLookAndFeel().getLabelFont (*label);
  22278. const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
  22279. text = label->getText();
  22280. cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
  22281. label->getMinimumHorizontalScale());
  22282. }
  22283. else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
  22284. {
  22285. const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
  22286. text = toggle->getButtonText();
  22287. cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
  22288. c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
  22289. }
  22290. else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
  22291. button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
  22292. {
  22293. text = button->getButtonText();
  22294. cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
  22295. button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
  22296. }
  22297. if (cut)
  22298. {
  22299. juce::String path;
  22300. for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
  22301. if (p->getName().isNotEmpty())
  22302. path = p->getName() + (path.isEmpty() ? "" : "/") + path;
  22303. const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
  22304. + (path.isEmpty() ? juce::String() : " | " + path);
  22305. textFitLog().addIfNotAlreadyThere (line);
  22306. }
  22307. for (auto* child : c.getChildren())
  22308. visit (*child);
  22309. };
  22310. visit (root);
  22311. }
  22312. static void saveSnapshot (juce::Component& c, const juce::String& path)
  22313. {
  22314. checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
  22315. const auto file = lynx::shot::file (juce::File (path));
  22316. file.deleteFile();
  22317. juce::PNGImageFormat png;
  22318. if (auto out = file.createOutputStream())
  22319. png.writeImageToStream (lynx::shot::snapshot (c), *out);
  22320. }
  22321. class MainWindow final : public juce::DocumentWindow
  22322. {
  22323. public:
  22324. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  22325. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons)
  22326. {
  22327. setUsingNativeTitleBar (true);
  22328. setIcon (lynx::logoImage());
  22329. content = new lynx::MainComponent (engine);
  22330. setContentOwned (content, true);
  22331. setResizable (true, true);
  22332. setResizeLimits (800, 400, 10000, 10000);
  22333. // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
  22334. // display: the AppImage catalog test runs on an 800x600 screen)
  22335. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  22336. {
  22337. const auto area = display->userArea;
  22338. const auto fit = [] (int design, int available) {
  22339. return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
  22340. };
  22341. setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
  22342. }
  22343. centreWithSize (getWidth(), getHeight());
  22344. // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
  22345. // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
  22346. const auto saved = stateFile().loadFileAsString().trim();
  22347. // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
  22348. const auto firstStart = saved.isEmpty()
  22349. && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
  22350. maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
  22351. if (saved.isNotEmpty())
  22352. restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
  22353. }
  22354. // Shows the window (built hidden while the splash screen is up).
  22355. void reveal()
  22356. {
  22357. if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
  22358. watchFrames ({});
  22359. setVisible (true);
  22360. lynx::applyWindowChrome (*this);
  22361. lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
  22362. if (maximiseOnReveal)
  22363. setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
  22364. toFront (true);
  22365. content->grabKeyboardFocus();
  22366. // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
  22367. // place and above it, once the window manager has placed this one
  22368. juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  22369. if (safe != nullptr)
  22370. safe->content->restoreDetachedWindows();
  22371. });
  22372. }
  22373. // The window's place and maximized state for the next start (main-window.txt in the settings folder).
  22374. void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
  22375. static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
  22376. void openFile (const juce::File& file) { content->openFile (file); }
  22377. lynx::MainComponent& getContent() { return *content; }
  22378. void showSetupWizard() { content->showSetupWizard(); }
  22379. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  22380. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  22381. // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
  22382. // counting when --uiperf watches too.
  22383. void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
  22384. {
  22385. if (probe == nullptr)
  22386. {
  22387. probe = std::make_unique<lynx::ui::FrameProbe>();
  22388. Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
  22389. probe->setBounds (getLocalBounds());
  22390. }
  22391. probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
  22392. if (lynx::uitrace::enabled())
  22393. lynx::uitrace::frame (now);
  22394. if (callback)
  22395. callback (now, area);
  22396. };
  22397. }
  22398. void resized() override
  22399. {
  22400. DocumentWindow::resized();
  22401. if (probe != nullptr)
  22402. probe->setBounds (getLocalBounds());
  22403. }
  22404. // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
  22405. std::function<void (double)> onFrame;
  22406. void paint (juce::Graphics& g) override
  22407. {
  22408. if (onFrame)
  22409. frameStart = juce::Time::getMillisecondCounterHiRes();
  22410. DocumentWindow::paint (g);
  22411. }
  22412. void paintOverChildren (juce::Graphics& g) override
  22413. {
  22414. DocumentWindow::paintOverChildren (g);
  22415. if (onFrame && frameStart > 0.0)
  22416. onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
  22417. frameStart = 0.0;
  22418. }
  22419. private:
  22420. lynx::MainComponent* content = nullptr; // owned by the window
  22421. std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
  22422. double frameStart = 0.0;
  22423. bool maximiseOnReveal = false;
  22424. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  22425. };
  22426. lynx::theme::LookAndFeel lookAndFeel;
  22427. std::unique_ptr<lynx::AudioEngine> engine;
  22428. std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
  22429. // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
  22430. // without registering it, listed as the driver type "ASIO driver file". True when one was added.
  22431. bool addDriverFileDeviceType()
  22432. {
  22433. const auto args = juce::JUCEApplication::getCommandLineParameterArray();
  22434. const auto i = args.indexOf ("--asiodll");
  22435. if (i < 0 || i + 1 >= args.size() || engine == nullptr)
  22436. return false;
  22437. auto& devices = engine->getDeviceManager();
  22438. devices.getAvailableDeviceTypes(); // creates the standard types first
  22439. for (auto* t : devices.getAvailableDeviceTypes())
  22440. if (t->getTypeName() == lynx::dllAsioTypeName)
  22441. return true;
  22442. auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
  22443. if (type == nullptr)
  22444. return false;
  22445. devices.addAudioDeviceType (std::move (type));
  22446. return true;
  22447. }
  22448. void restoreSavedDeviceState()
  22449. {
  22450. if (engine != nullptr)
  22451. engine->restoreAudioDeviceState (savedDeviceState.get());
  22452. }
  22453. std::unique_ptr<MainWindow> mainWindow;
  22454. std::unique_ptr<juce::Timer> perf; // --uiperf
  22455. std::unique_ptr<lynx::SplashScreen> splash;
  22456. double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
  22457. lynx::StartupOptions startupOptions;
  22458. juce::File fileToOpen;
  22459. bool startupFileHandled = false;
  22460. bool startWithoutPlugins = false; // --no-plugins project.lynx (round 190ap)
  22461. juce::File openTimeReport; // --opentime
  22462. int openTimeIdleSeconds = 10;
  22463. };
  22464. START_JUCE_APPLICATION (LynxApplication)